a595f8775c37a0122b8973450b2570c2f1a2c65b
[pandora-kernel.git] / fs / btrfs / volumes.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18 #include <linux/sched.h>
19 #include <linux/bio.h>
20 #include <linux/slab.h>
21 #include <linux/buffer_head.h>
22 #include <linux/blkdev.h>
23 #include <linux/random.h>
24 #include <linux/iocontext.h>
25 #include <linux/capability.h>
26 #include <asm/div64.h>
27 #include "compat.h"
28 #include "ctree.h"
29 #include "extent_map.h"
30 #include "disk-io.h"
31 #include "transaction.h"
32 #include "print-tree.h"
33 #include "volumes.h"
34 #include "async-thread.h"
35
36 static int init_first_rw_device(struct btrfs_trans_handle *trans,
37                                 struct btrfs_root *root,
38                                 struct btrfs_device *device);
39 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
40
41 static DEFINE_MUTEX(uuid_mutex);
42 static LIST_HEAD(fs_uuids);
43
44 static void lock_chunks(struct btrfs_root *root)
45 {
46         mutex_lock(&root->fs_info->chunk_mutex);
47 }
48
49 static void unlock_chunks(struct btrfs_root *root)
50 {
51         mutex_unlock(&root->fs_info->chunk_mutex);
52 }
53
54 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
55 {
56         struct btrfs_device *device;
57         WARN_ON(fs_devices->opened);
58         while (!list_empty(&fs_devices->devices)) {
59                 device = list_entry(fs_devices->devices.next,
60                                     struct btrfs_device, dev_list);
61                 list_del(&device->dev_list);
62                 kfree(device->name);
63                 kfree(device);
64         }
65         kfree(fs_devices);
66 }
67
68 int btrfs_cleanup_fs_uuids(void)
69 {
70         struct btrfs_fs_devices *fs_devices;
71
72         while (!list_empty(&fs_uuids)) {
73                 fs_devices = list_entry(fs_uuids.next,
74                                         struct btrfs_fs_devices, list);
75                 list_del(&fs_devices->list);
76                 free_fs_devices(fs_devices);
77         }
78         return 0;
79 }
80
81 static noinline struct btrfs_device *__find_device(struct list_head *head,
82                                                    u64 devid, u8 *uuid)
83 {
84         struct btrfs_device *dev;
85
86         list_for_each_entry(dev, head, dev_list) {
87                 if (dev->devid == devid &&
88                     (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
89                         return dev;
90                 }
91         }
92         return NULL;
93 }
94
95 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
96 {
97         struct btrfs_fs_devices *fs_devices;
98
99         list_for_each_entry(fs_devices, &fs_uuids, list) {
100                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
101                         return fs_devices;
102         }
103         return NULL;
104 }
105
106 static void requeue_list(struct btrfs_pending_bios *pending_bios,
107                         struct bio *head, struct bio *tail)
108 {
109
110         struct bio *old_head;
111
112         old_head = pending_bios->head;
113         pending_bios->head = head;
114         if (pending_bios->tail)
115                 tail->bi_next = old_head;
116         else
117                 pending_bios->tail = tail;
118 }
119
120 /*
121  * we try to collect pending bios for a device so we don't get a large
122  * number of procs sending bios down to the same device.  This greatly
123  * improves the schedulers ability to collect and merge the bios.
124  *
125  * But, it also turns into a long list of bios to process and that is sure
126  * to eventually make the worker thread block.  The solution here is to
127  * make some progress and then put this work struct back at the end of
128  * the list if the block device is congested.  This way, multiple devices
129  * can make progress from a single worker thread.
130  */
131 static noinline int run_scheduled_bios(struct btrfs_device *device)
132 {
133         struct bio *pending;
134         struct backing_dev_info *bdi;
135         struct btrfs_fs_info *fs_info;
136         struct btrfs_pending_bios *pending_bios;
137         struct bio *tail;
138         struct bio *cur;
139         int again = 0;
140         unsigned long num_run;
141         unsigned long batch_run = 0;
142         unsigned long limit;
143         unsigned long last_waited = 0;
144         int force_reg = 0;
145         int sync_pending;
146         struct blk_plug plug;
147
148         /*
149          * this function runs all the bios we've collected for
150          * a particular device.  We don't want to wander off to
151          * another device without first sending all of these down.
152          * So, setup a plug here and finish it off before we return
153          */
154         blk_start_plug(&plug);
155
156         bdi = blk_get_backing_dev_info(device->bdev);
157         fs_info = device->dev_root->fs_info;
158         limit = btrfs_async_submit_limit(fs_info);
159         limit = limit * 2 / 3;
160
161 loop:
162         spin_lock(&device->io_lock);
163
164 loop_lock:
165         num_run = 0;
166
167         /* take all the bios off the list at once and process them
168          * later on (without the lock held).  But, remember the
169          * tail and other pointers so the bios can be properly reinserted
170          * into the list if we hit congestion
171          */
172         if (!force_reg && device->pending_sync_bios.head) {
173                 pending_bios = &device->pending_sync_bios;
174                 force_reg = 1;
175         } else {
176                 pending_bios = &device->pending_bios;
177                 force_reg = 0;
178         }
179
180         pending = pending_bios->head;
181         tail = pending_bios->tail;
182         WARN_ON(pending && !tail);
183
184         /*
185          * if pending was null this time around, no bios need processing
186          * at all and we can stop.  Otherwise it'll loop back up again
187          * and do an additional check so no bios are missed.
188          *
189          * device->running_pending is used to synchronize with the
190          * schedule_bio code.
191          */
192         if (device->pending_sync_bios.head == NULL &&
193             device->pending_bios.head == NULL) {
194                 again = 0;
195                 device->running_pending = 0;
196         } else {
197                 again = 1;
198                 device->running_pending = 1;
199         }
200
201         pending_bios->head = NULL;
202         pending_bios->tail = NULL;
203
204         spin_unlock(&device->io_lock);
205
206         while (pending) {
207
208                 rmb();
209                 /* we want to work on both lists, but do more bios on the
210                  * sync list than the regular list
211                  */
212                 if ((num_run > 32 &&
213                     pending_bios != &device->pending_sync_bios &&
214                     device->pending_sync_bios.head) ||
215                    (num_run > 64 && pending_bios == &device->pending_sync_bios &&
216                     device->pending_bios.head)) {
217                         spin_lock(&device->io_lock);
218                         requeue_list(pending_bios, pending, tail);
219                         goto loop_lock;
220                 }
221
222                 cur = pending;
223                 pending = pending->bi_next;
224                 cur->bi_next = NULL;
225                 atomic_dec(&fs_info->nr_async_bios);
226
227                 if (atomic_read(&fs_info->nr_async_bios) < limit &&
228                     waitqueue_active(&fs_info->async_submit_wait))
229                         wake_up(&fs_info->async_submit_wait);
230
231                 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
232
233                 /*
234                  * if we're doing the sync list, record that our
235                  * plug has some sync requests on it
236                  *
237                  * If we're doing the regular list and there are
238                  * sync requests sitting around, unplug before
239                  * we add more
240                  */
241                 if (pending_bios == &device->pending_sync_bios) {
242                         sync_pending = 1;
243                 } else if (sync_pending) {
244                         blk_finish_plug(&plug);
245                         blk_start_plug(&plug);
246                         sync_pending = 0;
247                 }
248
249                 submit_bio(cur->bi_rw, cur);
250                 num_run++;
251                 batch_run++;
252                 if (need_resched())
253                         cond_resched();
254
255                 /*
256                  * we made progress, there is more work to do and the bdi
257                  * is now congested.  Back off and let other work structs
258                  * run instead
259                  */
260                 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
261                     fs_info->fs_devices->open_devices > 1) {
262                         struct io_context *ioc;
263
264                         ioc = current->io_context;
265
266                         /*
267                          * the main goal here is that we don't want to
268                          * block if we're going to be able to submit
269                          * more requests without blocking.
270                          *
271                          * This code does two great things, it pokes into
272                          * the elevator code from a filesystem _and_
273                          * it makes assumptions about how batching works.
274                          */
275                         if (ioc && ioc->nr_batch_requests > 0 &&
276                             time_before(jiffies, ioc->last_waited + HZ/50UL) &&
277                             (last_waited == 0 ||
278                              ioc->last_waited == last_waited)) {
279                                 /*
280                                  * we want to go through our batch of
281                                  * requests and stop.  So, we copy out
282                                  * the ioc->last_waited time and test
283                                  * against it before looping
284                                  */
285                                 last_waited = ioc->last_waited;
286                                 if (need_resched())
287                                         cond_resched();
288                                 continue;
289                         }
290                         spin_lock(&device->io_lock);
291                         requeue_list(pending_bios, pending, tail);
292                         device->running_pending = 1;
293
294                         spin_unlock(&device->io_lock);
295                         btrfs_requeue_work(&device->work);
296                         goto done;
297                 }
298         }
299
300         cond_resched();
301         if (again)
302                 goto loop;
303
304         spin_lock(&device->io_lock);
305         if (device->pending_bios.head || device->pending_sync_bios.head)
306                 goto loop_lock;
307         spin_unlock(&device->io_lock);
308
309 done:
310         blk_finish_plug(&plug);
311         return 0;
312 }
313
314 static void pending_bios_fn(struct btrfs_work *work)
315 {
316         struct btrfs_device *device;
317
318         device = container_of(work, struct btrfs_device, work);
319         run_scheduled_bios(device);
320 }
321
322 static noinline int device_list_add(const char *path,
323                            struct btrfs_super_block *disk_super,
324                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
325 {
326         struct btrfs_device *device;
327         struct btrfs_fs_devices *fs_devices;
328         u64 found_transid = btrfs_super_generation(disk_super);
329         char *name;
330
331         fs_devices = find_fsid(disk_super->fsid);
332         if (!fs_devices) {
333                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
334                 if (!fs_devices)
335                         return -ENOMEM;
336                 INIT_LIST_HEAD(&fs_devices->devices);
337                 INIT_LIST_HEAD(&fs_devices->alloc_list);
338                 list_add(&fs_devices->list, &fs_uuids);
339                 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
340                 fs_devices->latest_devid = devid;
341                 fs_devices->latest_trans = found_transid;
342                 mutex_init(&fs_devices->device_list_mutex);
343                 device = NULL;
344         } else {
345                 device = __find_device(&fs_devices->devices, devid,
346                                        disk_super->dev_item.uuid);
347         }
348         if (!device) {
349                 if (fs_devices->opened)
350                         return -EBUSY;
351
352                 device = kzalloc(sizeof(*device), GFP_NOFS);
353                 if (!device) {
354                         /* we can safely leave the fs_devices entry around */
355                         return -ENOMEM;
356                 }
357                 device->devid = devid;
358                 device->work.func = pending_bios_fn;
359                 memcpy(device->uuid, disk_super->dev_item.uuid,
360                        BTRFS_UUID_SIZE);
361                 spin_lock_init(&device->io_lock);
362                 device->name = kstrdup(path, GFP_NOFS);
363                 if (!device->name) {
364                         kfree(device);
365                         return -ENOMEM;
366                 }
367                 INIT_LIST_HEAD(&device->dev_alloc_list);
368
369                 mutex_lock(&fs_devices->device_list_mutex);
370                 list_add_rcu(&device->dev_list, &fs_devices->devices);
371                 mutex_unlock(&fs_devices->device_list_mutex);
372
373                 device->fs_devices = fs_devices;
374                 fs_devices->num_devices++;
375         } else if (!device->name || strcmp(device->name, path)) {
376                 name = kstrdup(path, GFP_NOFS);
377                 if (!name)
378                         return -ENOMEM;
379                 kfree(device->name);
380                 device->name = name;
381                 if (device->missing) {
382                         fs_devices->missing_devices--;
383                         device->missing = 0;
384                 }
385         }
386
387         if (found_transid > fs_devices->latest_trans) {
388                 fs_devices->latest_devid = devid;
389                 fs_devices->latest_trans = found_transid;
390         }
391         *fs_devices_ret = fs_devices;
392         return 0;
393 }
394
395 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
396 {
397         struct btrfs_fs_devices *fs_devices;
398         struct btrfs_device *device;
399         struct btrfs_device *orig_dev;
400
401         fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
402         if (!fs_devices)
403                 return ERR_PTR(-ENOMEM);
404
405         INIT_LIST_HEAD(&fs_devices->devices);
406         INIT_LIST_HEAD(&fs_devices->alloc_list);
407         INIT_LIST_HEAD(&fs_devices->list);
408         mutex_init(&fs_devices->device_list_mutex);
409         fs_devices->latest_devid = orig->latest_devid;
410         fs_devices->latest_trans = orig->latest_trans;
411         memcpy(fs_devices->fsid, orig->fsid, sizeof(fs_devices->fsid));
412
413         /* We have held the volume lock, it is safe to get the devices. */
414         list_for_each_entry(orig_dev, &orig->devices, dev_list) {
415                 device = kzalloc(sizeof(*device), GFP_NOFS);
416                 if (!device)
417                         goto error;
418
419                 device->name = kstrdup(orig_dev->name, GFP_NOFS);
420                 if (!device->name) {
421                         kfree(device);
422                         goto error;
423                 }
424
425                 device->devid = orig_dev->devid;
426                 device->work.func = pending_bios_fn;
427                 memcpy(device->uuid, orig_dev->uuid, sizeof(device->uuid));
428                 spin_lock_init(&device->io_lock);
429                 INIT_LIST_HEAD(&device->dev_list);
430                 INIT_LIST_HEAD(&device->dev_alloc_list);
431
432                 list_add(&device->dev_list, &fs_devices->devices);
433                 device->fs_devices = fs_devices;
434                 fs_devices->num_devices++;
435         }
436         return fs_devices;
437 error:
438         free_fs_devices(fs_devices);
439         return ERR_PTR(-ENOMEM);
440 }
441
442 int btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
443 {
444         struct btrfs_device *device, *next;
445
446         mutex_lock(&uuid_mutex);
447 again:
448         /* This is the initialized path, it is safe to release the devices. */
449         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
450                 if (device->in_fs_metadata)
451                         continue;
452
453                 if (device->bdev) {
454                         blkdev_put(device->bdev, device->mode);
455                         device->bdev = NULL;
456                         fs_devices->open_devices--;
457                 }
458                 if (device->writeable) {
459                         list_del_init(&device->dev_alloc_list);
460                         device->writeable = 0;
461                         fs_devices->rw_devices--;
462                 }
463                 list_del_init(&device->dev_list);
464                 fs_devices->num_devices--;
465                 kfree(device->name);
466                 kfree(device);
467         }
468
469         if (fs_devices->seed) {
470                 fs_devices = fs_devices->seed;
471                 goto again;
472         }
473
474         mutex_unlock(&uuid_mutex);
475         return 0;
476 }
477
478 static void __free_device(struct work_struct *work)
479 {
480         struct btrfs_device *device;
481
482         device = container_of(work, struct btrfs_device, rcu_work);
483
484         if (device->bdev)
485                 blkdev_put(device->bdev, device->mode);
486
487         kfree(device->name);
488         kfree(device);
489 }
490
491 static void free_device(struct rcu_head *head)
492 {
493         struct btrfs_device *device;
494
495         device = container_of(head, struct btrfs_device, rcu);
496
497         INIT_WORK(&device->rcu_work, __free_device);
498         schedule_work(&device->rcu_work);
499 }
500
501 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
502 {
503         struct btrfs_device *device;
504
505         if (--fs_devices->opened > 0)
506                 return 0;
507
508         mutex_lock(&fs_devices->device_list_mutex);
509         list_for_each_entry(device, &fs_devices->devices, dev_list) {
510                 struct btrfs_device *new_device;
511
512                 if (device->bdev)
513                         fs_devices->open_devices--;
514
515                 if (device->writeable) {
516                         list_del_init(&device->dev_alloc_list);
517                         fs_devices->rw_devices--;
518                 }
519
520                 if (device->can_discard)
521                         fs_devices->num_can_discard--;
522
523                 new_device = kmalloc(sizeof(*new_device), GFP_NOFS);
524                 BUG_ON(!new_device);
525                 memcpy(new_device, device, sizeof(*new_device));
526                 new_device->name = kstrdup(device->name, GFP_NOFS);
527                 BUG_ON(device->name && !new_device->name);
528                 new_device->bdev = NULL;
529                 new_device->writeable = 0;
530                 new_device->in_fs_metadata = 0;
531                 new_device->can_discard = 0;
532                 list_replace_rcu(&device->dev_list, &new_device->dev_list);
533
534                 call_rcu(&device->rcu, free_device);
535         }
536         mutex_unlock(&fs_devices->device_list_mutex);
537
538         WARN_ON(fs_devices->open_devices);
539         WARN_ON(fs_devices->rw_devices);
540         fs_devices->opened = 0;
541         fs_devices->seeding = 0;
542
543         return 0;
544 }
545
546 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
547 {
548         struct btrfs_fs_devices *seed_devices = NULL;
549         int ret;
550
551         mutex_lock(&uuid_mutex);
552         ret = __btrfs_close_devices(fs_devices);
553         if (!fs_devices->opened) {
554                 seed_devices = fs_devices->seed;
555                 fs_devices->seed = NULL;
556         }
557         mutex_unlock(&uuid_mutex);
558
559         while (seed_devices) {
560                 fs_devices = seed_devices;
561                 seed_devices = fs_devices->seed;
562                 __btrfs_close_devices(fs_devices);
563                 free_fs_devices(fs_devices);
564         }
565         return ret;
566 }
567
568 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
569                                 fmode_t flags, void *holder)
570 {
571         struct request_queue *q;
572         struct block_device *bdev;
573         struct list_head *head = &fs_devices->devices;
574         struct btrfs_device *device;
575         struct block_device *latest_bdev = NULL;
576         struct buffer_head *bh;
577         struct btrfs_super_block *disk_super;
578         u64 latest_devid = 0;
579         u64 latest_transid = 0;
580         u64 devid;
581         int seeding = 1;
582         int ret = 0;
583
584         flags |= FMODE_EXCL;
585
586         list_for_each_entry(device, head, dev_list) {
587                 if (device->bdev)
588                         continue;
589                 if (!device->name)
590                         continue;
591
592                 bdev = blkdev_get_by_path(device->name, flags, holder);
593                 if (IS_ERR(bdev)) {
594                         printk(KERN_INFO "open %s failed\n", device->name);
595                         goto error;
596                 }
597                 set_blocksize(bdev, 4096);
598
599                 bh = btrfs_read_dev_super(bdev);
600                 if (!bh) {
601                         ret = -EINVAL;
602                         goto error_close;
603                 }
604
605                 disk_super = (struct btrfs_super_block *)bh->b_data;
606                 devid = btrfs_stack_device_id(&disk_super->dev_item);
607                 if (devid != device->devid)
608                         goto error_brelse;
609
610                 if (memcmp(device->uuid, disk_super->dev_item.uuid,
611                            BTRFS_UUID_SIZE))
612                         goto error_brelse;
613
614                 device->generation = btrfs_super_generation(disk_super);
615                 if (!latest_transid || device->generation > latest_transid) {
616                         latest_devid = devid;
617                         latest_transid = device->generation;
618                         latest_bdev = bdev;
619                 }
620
621                 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
622                         device->writeable = 0;
623                 } else {
624                         device->writeable = !bdev_read_only(bdev);
625                         seeding = 0;
626                 }
627
628                 q = bdev_get_queue(bdev);
629                 if (blk_queue_discard(q)) {
630                         device->can_discard = 1;
631                         fs_devices->num_can_discard++;
632                 }
633
634                 device->bdev = bdev;
635                 device->in_fs_metadata = 0;
636                 device->mode = flags;
637
638                 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
639                         fs_devices->rotating = 1;
640
641                 fs_devices->open_devices++;
642                 if (device->writeable) {
643                         fs_devices->rw_devices++;
644                         list_add(&device->dev_alloc_list,
645                                  &fs_devices->alloc_list);
646                 }
647                 brelse(bh);
648                 continue;
649
650 error_brelse:
651                 brelse(bh);
652 error_close:
653                 blkdev_put(bdev, flags);
654 error:
655                 continue;
656         }
657         if (fs_devices->open_devices == 0) {
658                 ret = -EIO;
659                 goto out;
660         }
661         fs_devices->seeding = seeding;
662         fs_devices->opened = 1;
663         fs_devices->latest_bdev = latest_bdev;
664         fs_devices->latest_devid = latest_devid;
665         fs_devices->latest_trans = latest_transid;
666         fs_devices->total_rw_bytes = 0;
667 out:
668         return ret;
669 }
670
671 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
672                        fmode_t flags, void *holder)
673 {
674         int ret;
675
676         mutex_lock(&uuid_mutex);
677         if (fs_devices->opened) {
678                 fs_devices->opened++;
679                 ret = 0;
680         } else {
681                 ret = __btrfs_open_devices(fs_devices, flags, holder);
682         }
683         mutex_unlock(&uuid_mutex);
684         return ret;
685 }
686
687 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
688                           struct btrfs_fs_devices **fs_devices_ret)
689 {
690         struct btrfs_super_block *disk_super;
691         struct block_device *bdev;
692         struct buffer_head *bh;
693         int ret;
694         u64 devid;
695         u64 transid;
696
697         mutex_lock(&uuid_mutex);
698
699         flags |= FMODE_EXCL;
700         bdev = blkdev_get_by_path(path, flags, holder);
701
702         if (IS_ERR(bdev)) {
703                 ret = PTR_ERR(bdev);
704                 goto error;
705         }
706
707         ret = set_blocksize(bdev, 4096);
708         if (ret)
709                 goto error_close;
710         bh = btrfs_read_dev_super(bdev);
711         if (!bh) {
712                 ret = -EINVAL;
713                 goto error_close;
714         }
715         disk_super = (struct btrfs_super_block *)bh->b_data;
716         devid = btrfs_stack_device_id(&disk_super->dev_item);
717         transid = btrfs_super_generation(disk_super);
718         if (disk_super->label[0])
719                 printk(KERN_INFO "device label %s ", disk_super->label);
720         else
721                 printk(KERN_INFO "device fsid %pU ", disk_super->fsid);
722         printk(KERN_CONT "devid %llu transid %llu %s\n",
723                (unsigned long long)devid, (unsigned long long)transid, path);
724         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
725
726         brelse(bh);
727 error_close:
728         blkdev_put(bdev, flags);
729 error:
730         mutex_unlock(&uuid_mutex);
731         return ret;
732 }
733
734 /* helper to account the used device space in the range */
735 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
736                                    u64 end, u64 *length)
737 {
738         struct btrfs_key key;
739         struct btrfs_root *root = device->dev_root;
740         struct btrfs_dev_extent *dev_extent;
741         struct btrfs_path *path;
742         u64 extent_end;
743         int ret;
744         int slot;
745         struct extent_buffer *l;
746
747         *length = 0;
748
749         if (start >= device->total_bytes)
750                 return 0;
751
752         path = btrfs_alloc_path();
753         if (!path)
754                 return -ENOMEM;
755         path->reada = 2;
756
757         key.objectid = device->devid;
758         key.offset = start;
759         key.type = BTRFS_DEV_EXTENT_KEY;
760
761         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
762         if (ret < 0)
763                 goto out;
764         if (ret > 0) {
765                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
766                 if (ret < 0)
767                         goto out;
768         }
769
770         while (1) {
771                 l = path->nodes[0];
772                 slot = path->slots[0];
773                 if (slot >= btrfs_header_nritems(l)) {
774                         ret = btrfs_next_leaf(root, path);
775                         if (ret == 0)
776                                 continue;
777                         if (ret < 0)
778                                 goto out;
779
780                         break;
781                 }
782                 btrfs_item_key_to_cpu(l, &key, slot);
783
784                 if (key.objectid < device->devid)
785                         goto next;
786
787                 if (key.objectid > device->devid)
788                         break;
789
790                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
791                         goto next;
792
793                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
794                 extent_end = key.offset + btrfs_dev_extent_length(l,
795                                                                   dev_extent);
796                 if (key.offset <= start && extent_end > end) {
797                         *length = end - start + 1;
798                         break;
799                 } else if (key.offset <= start && extent_end > start)
800                         *length += extent_end - start;
801                 else if (key.offset > start && extent_end <= end)
802                         *length += extent_end - key.offset;
803                 else if (key.offset > start && key.offset <= end) {
804                         *length += end - key.offset + 1;
805                         break;
806                 } else if (key.offset > end)
807                         break;
808
809 next:
810                 path->slots[0]++;
811         }
812         ret = 0;
813 out:
814         btrfs_free_path(path);
815         return ret;
816 }
817
818 /*
819  * find_free_dev_extent - find free space in the specified device
820  * @trans:      transaction handler
821  * @device:     the device which we search the free space in
822  * @num_bytes:  the size of the free space that we need
823  * @start:      store the start of the free space.
824  * @len:        the size of the free space. that we find, or the size of the max
825  *              free space if we don't find suitable free space
826  *
827  * this uses a pretty simple search, the expectation is that it is
828  * called very infrequently and that a given device has a small number
829  * of extents
830  *
831  * @start is used to store the start of the free space if we find. But if we
832  * don't find suitable free space, it will be used to store the start position
833  * of the max free space.
834  *
835  * @len is used to store the size of the free space that we find.
836  * But if we don't find suitable free space, it is used to store the size of
837  * the max free space.
838  */
839 int find_free_dev_extent(struct btrfs_trans_handle *trans,
840                          struct btrfs_device *device, u64 num_bytes,
841                          u64 *start, u64 *len)
842 {
843         struct btrfs_key key;
844         struct btrfs_root *root = device->dev_root;
845         struct btrfs_dev_extent *dev_extent;
846         struct btrfs_path *path;
847         u64 hole_size;
848         u64 max_hole_start;
849         u64 max_hole_size;
850         u64 extent_end;
851         u64 search_start;
852         u64 search_end = device->total_bytes;
853         int ret;
854         int slot;
855         struct extent_buffer *l;
856
857         /* FIXME use last free of some kind */
858
859         /* we don't want to overwrite the superblock on the drive,
860          * so we make sure to start at an offset of at least 1MB
861          */
862         search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
863
864         max_hole_start = search_start;
865         max_hole_size = 0;
866
867         if (search_start >= search_end) {
868                 ret = -ENOSPC;
869                 goto error;
870         }
871
872         path = btrfs_alloc_path();
873         if (!path) {
874                 ret = -ENOMEM;
875                 goto error;
876         }
877         path->reada = 2;
878
879         key.objectid = device->devid;
880         key.offset = search_start;
881         key.type = BTRFS_DEV_EXTENT_KEY;
882
883         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
884         if (ret < 0)
885                 goto out;
886         if (ret > 0) {
887                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
888                 if (ret < 0)
889                         goto out;
890         }
891
892         while (1) {
893                 l = path->nodes[0];
894                 slot = path->slots[0];
895                 if (slot >= btrfs_header_nritems(l)) {
896                         ret = btrfs_next_leaf(root, path);
897                         if (ret == 0)
898                                 continue;
899                         if (ret < 0)
900                                 goto out;
901
902                         break;
903                 }
904                 btrfs_item_key_to_cpu(l, &key, slot);
905
906                 if (key.objectid < device->devid)
907                         goto next;
908
909                 if (key.objectid > device->devid)
910                         break;
911
912                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
913                         goto next;
914
915                 if (key.offset > search_start) {
916                         hole_size = key.offset - search_start;
917
918                         if (hole_size > max_hole_size) {
919                                 max_hole_start = search_start;
920                                 max_hole_size = hole_size;
921                         }
922
923                         /*
924                          * If this free space is greater than which we need,
925                          * it must be the max free space that we have found
926                          * until now, so max_hole_start must point to the start
927                          * of this free space and the length of this free space
928                          * is stored in max_hole_size. Thus, we return
929                          * max_hole_start and max_hole_size and go back to the
930                          * caller.
931                          */
932                         if (hole_size >= num_bytes) {
933                                 ret = 0;
934                                 goto out;
935                         }
936                 }
937
938                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
939                 extent_end = key.offset + btrfs_dev_extent_length(l,
940                                                                   dev_extent);
941                 if (extent_end > search_start)
942                         search_start = extent_end;
943 next:
944                 path->slots[0]++;
945                 cond_resched();
946         }
947
948         hole_size = search_end- search_start;
949         if (hole_size > max_hole_size) {
950                 max_hole_start = search_start;
951                 max_hole_size = hole_size;
952         }
953
954         /* See above. */
955         if (hole_size < num_bytes)
956                 ret = -ENOSPC;
957         else
958                 ret = 0;
959
960 out:
961         btrfs_free_path(path);
962 error:
963         *start = max_hole_start;
964         if (len)
965                 *len = max_hole_size;
966         return ret;
967 }
968
969 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
970                           struct btrfs_device *device,
971                           u64 start)
972 {
973         int ret;
974         struct btrfs_path *path;
975         struct btrfs_root *root = device->dev_root;
976         struct btrfs_key key;
977         struct btrfs_key found_key;
978         struct extent_buffer *leaf = NULL;
979         struct btrfs_dev_extent *extent = NULL;
980
981         path = btrfs_alloc_path();
982         if (!path)
983                 return -ENOMEM;
984
985         key.objectid = device->devid;
986         key.offset = start;
987         key.type = BTRFS_DEV_EXTENT_KEY;
988
989         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
990         if (ret > 0) {
991                 ret = btrfs_previous_item(root, path, key.objectid,
992                                           BTRFS_DEV_EXTENT_KEY);
993                 if (ret)
994                         goto out;
995                 leaf = path->nodes[0];
996                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
997                 extent = btrfs_item_ptr(leaf, path->slots[0],
998                                         struct btrfs_dev_extent);
999                 BUG_ON(found_key.offset > start || found_key.offset +
1000                        btrfs_dev_extent_length(leaf, extent) < start);
1001         } else if (ret == 0) {
1002                 leaf = path->nodes[0];
1003                 extent = btrfs_item_ptr(leaf, path->slots[0],
1004                                         struct btrfs_dev_extent);
1005         }
1006         BUG_ON(ret);
1007
1008         if (device->bytes_used > 0)
1009                 device->bytes_used -= btrfs_dev_extent_length(leaf, extent);
1010         ret = btrfs_del_item(trans, root, path);
1011
1012 out:
1013         btrfs_free_path(path);
1014         return ret;
1015 }
1016
1017 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1018                            struct btrfs_device *device,
1019                            u64 chunk_tree, u64 chunk_objectid,
1020                            u64 chunk_offset, u64 start, u64 num_bytes)
1021 {
1022         int ret;
1023         struct btrfs_path *path;
1024         struct btrfs_root *root = device->dev_root;
1025         struct btrfs_dev_extent *extent;
1026         struct extent_buffer *leaf;
1027         struct btrfs_key key;
1028
1029         WARN_ON(!device->in_fs_metadata);
1030         path = btrfs_alloc_path();
1031         if (!path)
1032                 return -ENOMEM;
1033
1034         key.objectid = device->devid;
1035         key.offset = start;
1036         key.type = BTRFS_DEV_EXTENT_KEY;
1037         ret = btrfs_insert_empty_item(trans, root, path, &key,
1038                                       sizeof(*extent));
1039         BUG_ON(ret);
1040
1041         leaf = path->nodes[0];
1042         extent = btrfs_item_ptr(leaf, path->slots[0],
1043                                 struct btrfs_dev_extent);
1044         btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1045         btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1046         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1047
1048         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1049                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1050                     BTRFS_UUID_SIZE);
1051
1052         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1053         btrfs_mark_buffer_dirty(leaf);
1054         btrfs_free_path(path);
1055         return ret;
1056 }
1057
1058 static noinline int find_next_chunk(struct btrfs_root *root,
1059                                     u64 objectid, u64 *offset)
1060 {
1061         struct btrfs_path *path;
1062         int ret;
1063         struct btrfs_key key;
1064         struct btrfs_chunk *chunk;
1065         struct btrfs_key found_key;
1066
1067         path = btrfs_alloc_path();
1068         if (!path)
1069                 return -ENOMEM;
1070
1071         key.objectid = objectid;
1072         key.offset = (u64)-1;
1073         key.type = BTRFS_CHUNK_ITEM_KEY;
1074
1075         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1076         if (ret < 0)
1077                 goto error;
1078
1079         BUG_ON(ret == 0);
1080
1081         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
1082         if (ret) {
1083                 *offset = 0;
1084         } else {
1085                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1086                                       path->slots[0]);
1087                 if (found_key.objectid != objectid)
1088                         *offset = 0;
1089                 else {
1090                         chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
1091                                                struct btrfs_chunk);
1092                         *offset = found_key.offset +
1093                                 btrfs_chunk_length(path->nodes[0], chunk);
1094                 }
1095         }
1096         ret = 0;
1097 error:
1098         btrfs_free_path(path);
1099         return ret;
1100 }
1101
1102 static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
1103 {
1104         int ret;
1105         struct btrfs_key key;
1106         struct btrfs_key found_key;
1107         struct btrfs_path *path;
1108
1109         root = root->fs_info->chunk_root;
1110
1111         path = btrfs_alloc_path();
1112         if (!path)
1113                 return -ENOMEM;
1114
1115         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1116         key.type = BTRFS_DEV_ITEM_KEY;
1117         key.offset = (u64)-1;
1118
1119         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1120         if (ret < 0)
1121                 goto error;
1122
1123         BUG_ON(ret == 0);
1124
1125         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
1126                                   BTRFS_DEV_ITEM_KEY);
1127         if (ret) {
1128                 *objectid = 1;
1129         } else {
1130                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1131                                       path->slots[0]);
1132                 *objectid = found_key.offset + 1;
1133         }
1134         ret = 0;
1135 error:
1136         btrfs_free_path(path);
1137         return ret;
1138 }
1139
1140 /*
1141  * the device information is stored in the chunk root
1142  * the btrfs_device struct should be fully filled in
1143  */
1144 int btrfs_add_device(struct btrfs_trans_handle *trans,
1145                      struct btrfs_root *root,
1146                      struct btrfs_device *device)
1147 {
1148         int ret;
1149         struct btrfs_path *path;
1150         struct btrfs_dev_item *dev_item;
1151         struct extent_buffer *leaf;
1152         struct btrfs_key key;
1153         unsigned long ptr;
1154
1155         root = root->fs_info->chunk_root;
1156
1157         path = btrfs_alloc_path();
1158         if (!path)
1159                 return -ENOMEM;
1160
1161         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1162         key.type = BTRFS_DEV_ITEM_KEY;
1163         key.offset = device->devid;
1164
1165         ret = btrfs_insert_empty_item(trans, root, path, &key,
1166                                       sizeof(*dev_item));
1167         if (ret)
1168                 goto out;
1169
1170         leaf = path->nodes[0];
1171         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1172
1173         btrfs_set_device_id(leaf, dev_item, device->devid);
1174         btrfs_set_device_generation(leaf, dev_item, 0);
1175         btrfs_set_device_type(leaf, dev_item, device->type);
1176         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1177         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1178         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1179         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1180         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1181         btrfs_set_device_group(leaf, dev_item, 0);
1182         btrfs_set_device_seek_speed(leaf, dev_item, 0);
1183         btrfs_set_device_bandwidth(leaf, dev_item, 0);
1184         btrfs_set_device_start_offset(leaf, dev_item, 0);
1185
1186         ptr = (unsigned long)btrfs_device_uuid(dev_item);
1187         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1188         ptr = (unsigned long)btrfs_device_fsid(dev_item);
1189         write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1190         btrfs_mark_buffer_dirty(leaf);
1191
1192         ret = 0;
1193 out:
1194         btrfs_free_path(path);
1195         return ret;
1196 }
1197
1198 static int btrfs_rm_dev_item(struct btrfs_root *root,
1199                              struct btrfs_device *device)
1200 {
1201         int ret;
1202         struct btrfs_path *path;
1203         struct btrfs_key key;
1204         struct btrfs_trans_handle *trans;
1205
1206         root = root->fs_info->chunk_root;
1207
1208         path = btrfs_alloc_path();
1209         if (!path)
1210                 return -ENOMEM;
1211
1212         trans = btrfs_start_transaction(root, 0);
1213         if (IS_ERR(trans)) {
1214                 btrfs_free_path(path);
1215                 return PTR_ERR(trans);
1216         }
1217         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1218         key.type = BTRFS_DEV_ITEM_KEY;
1219         key.offset = device->devid;
1220         lock_chunks(root);
1221
1222         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1223         if (ret < 0)
1224                 goto out;
1225
1226         if (ret > 0) {
1227                 ret = -ENOENT;
1228                 goto out;
1229         }
1230
1231         ret = btrfs_del_item(trans, root, path);
1232         if (ret)
1233                 goto out;
1234 out:
1235         btrfs_free_path(path);
1236         unlock_chunks(root);
1237         btrfs_commit_transaction(trans, root);
1238         return ret;
1239 }
1240
1241 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1242 {
1243         struct btrfs_device *device;
1244         struct btrfs_device *next_device;
1245         struct block_device *bdev;
1246         struct buffer_head *bh = NULL;
1247         struct btrfs_super_block *disk_super;
1248         struct btrfs_fs_devices *cur_devices;
1249         u64 all_avail;
1250         u64 devid;
1251         u64 num_devices;
1252         u8 *dev_uuid;
1253         int ret = 0;
1254         bool clear_super = false;
1255
1256         mutex_lock(&uuid_mutex);
1257         mutex_lock(&root->fs_info->volume_mutex);
1258
1259         all_avail = root->fs_info->avail_data_alloc_bits |
1260                 root->fs_info->avail_system_alloc_bits |
1261                 root->fs_info->avail_metadata_alloc_bits;
1262
1263         if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
1264             root->fs_info->fs_devices->num_devices <= 4) {
1265                 printk(KERN_ERR "btrfs: unable to go below four devices "
1266                        "on raid10\n");
1267                 ret = -EINVAL;
1268                 goto out;
1269         }
1270
1271         if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
1272             root->fs_info->fs_devices->num_devices <= 2) {
1273                 printk(KERN_ERR "btrfs: unable to go below two "
1274                        "devices on raid1\n");
1275                 ret = -EINVAL;
1276                 goto out;
1277         }
1278
1279         if (strcmp(device_path, "missing") == 0) {
1280                 struct list_head *devices;
1281                 struct btrfs_device *tmp;
1282
1283                 device = NULL;
1284                 devices = &root->fs_info->fs_devices->devices;
1285                 /*
1286                  * It is safe to read the devices since the volume_mutex
1287                  * is held.
1288                  */
1289                 list_for_each_entry(tmp, devices, dev_list) {
1290                         if (tmp->in_fs_metadata && !tmp->bdev) {
1291                                 device = tmp;
1292                                 break;
1293                         }
1294                 }
1295                 bdev = NULL;
1296                 bh = NULL;
1297                 disk_super = NULL;
1298                 if (!device) {
1299                         printk(KERN_ERR "btrfs: no missing devices found to "
1300                                "remove\n");
1301                         goto out;
1302                 }
1303         } else {
1304                 bdev = blkdev_get_by_path(device_path, FMODE_READ | FMODE_EXCL,
1305                                           root->fs_info->bdev_holder);
1306                 if (IS_ERR(bdev)) {
1307                         ret = PTR_ERR(bdev);
1308                         goto out;
1309                 }
1310
1311                 set_blocksize(bdev, 4096);
1312                 bh = btrfs_read_dev_super(bdev);
1313                 if (!bh) {
1314                         ret = -EINVAL;
1315                         goto error_close;
1316                 }
1317                 disk_super = (struct btrfs_super_block *)bh->b_data;
1318                 devid = btrfs_stack_device_id(&disk_super->dev_item);
1319                 dev_uuid = disk_super->dev_item.uuid;
1320                 device = btrfs_find_device(root, devid, dev_uuid,
1321                                            disk_super->fsid);
1322                 if (!device) {
1323                         ret = -ENOENT;
1324                         goto error_brelse;
1325                 }
1326         }
1327
1328         if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1329                 printk(KERN_ERR "btrfs: unable to remove the only writeable "
1330                        "device\n");
1331                 ret = -EINVAL;
1332                 goto error_brelse;
1333         }
1334
1335         if (device->writeable) {
1336                 lock_chunks(root);
1337                 list_del_init(&device->dev_alloc_list);
1338                 unlock_chunks(root);
1339                 root->fs_info->fs_devices->rw_devices--;
1340                 clear_super = true;
1341         }
1342
1343         ret = btrfs_shrink_device(device, 0);
1344         if (ret)
1345                 goto error_undo;
1346
1347         ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1348         if (ret)
1349                 goto error_undo;
1350
1351         device->in_fs_metadata = 0;
1352         btrfs_scrub_cancel_dev(root, device);
1353
1354         /*
1355          * the device list mutex makes sure that we don't change
1356          * the device list while someone else is writing out all
1357          * the device supers.
1358          */
1359
1360         cur_devices = device->fs_devices;
1361         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1362         list_del_rcu(&device->dev_list);
1363
1364         device->fs_devices->num_devices--;
1365
1366         if (device->missing)
1367                 root->fs_info->fs_devices->missing_devices--;
1368
1369         next_device = list_entry(root->fs_info->fs_devices->devices.next,
1370                                  struct btrfs_device, dev_list);
1371         if (device->bdev == root->fs_info->sb->s_bdev)
1372                 root->fs_info->sb->s_bdev = next_device->bdev;
1373         if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1374                 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1375
1376         if (device->bdev)
1377                 device->fs_devices->open_devices--;
1378
1379         call_rcu(&device->rcu, free_device);
1380         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1381
1382         num_devices = btrfs_super_num_devices(&root->fs_info->super_copy) - 1;
1383         btrfs_set_super_num_devices(&root->fs_info->super_copy, num_devices);
1384
1385         if (cur_devices->open_devices == 0) {
1386                 struct btrfs_fs_devices *fs_devices;
1387                 fs_devices = root->fs_info->fs_devices;
1388                 while (fs_devices) {
1389                         if (fs_devices->seed == cur_devices)
1390                                 break;
1391                         fs_devices = fs_devices->seed;
1392                 }
1393                 fs_devices->seed = cur_devices->seed;
1394                 cur_devices->seed = NULL;
1395                 lock_chunks(root);
1396                 __btrfs_close_devices(cur_devices);
1397                 unlock_chunks(root);
1398                 free_fs_devices(cur_devices);
1399         }
1400
1401         /*
1402          * at this point, the device is zero sized.  We want to
1403          * remove it from the devices list and zero out the old super
1404          */
1405         if (clear_super) {
1406                 /* make sure this device isn't detected as part of
1407                  * the FS anymore
1408                  */
1409                 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1410                 set_buffer_dirty(bh);
1411                 sync_dirty_buffer(bh);
1412         }
1413
1414         ret = 0;
1415
1416 error_brelse:
1417         brelse(bh);
1418 error_close:
1419         if (bdev)
1420                 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1421 out:
1422         mutex_unlock(&root->fs_info->volume_mutex);
1423         mutex_unlock(&uuid_mutex);
1424         return ret;
1425 error_undo:
1426         if (device->writeable) {
1427                 lock_chunks(root);
1428                 list_add(&device->dev_alloc_list,
1429                          &root->fs_info->fs_devices->alloc_list);
1430                 unlock_chunks(root);
1431                 root->fs_info->fs_devices->rw_devices++;
1432         }
1433         goto error_brelse;
1434 }
1435
1436 /*
1437  * does all the dirty work required for changing file system's UUID.
1438  */
1439 static int btrfs_prepare_sprout(struct btrfs_trans_handle *trans,
1440                                 struct btrfs_root *root)
1441 {
1442         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1443         struct btrfs_fs_devices *old_devices;
1444         struct btrfs_fs_devices *seed_devices;
1445         struct btrfs_super_block *disk_super = &root->fs_info->super_copy;
1446         struct btrfs_device *device;
1447         u64 super_flags;
1448
1449         BUG_ON(!mutex_is_locked(&uuid_mutex));
1450         if (!fs_devices->seeding)
1451                 return -EINVAL;
1452
1453         seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1454         if (!seed_devices)
1455                 return -ENOMEM;
1456
1457         old_devices = clone_fs_devices(fs_devices);
1458         if (IS_ERR(old_devices)) {
1459                 kfree(seed_devices);
1460                 return PTR_ERR(old_devices);
1461         }
1462
1463         list_add(&old_devices->list, &fs_uuids);
1464
1465         memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1466         seed_devices->opened = 1;
1467         INIT_LIST_HEAD(&seed_devices->devices);
1468         INIT_LIST_HEAD(&seed_devices->alloc_list);
1469         mutex_init(&seed_devices->device_list_mutex);
1470
1471         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1472         list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1473                               synchronize_rcu);
1474         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1475
1476         list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1477         list_for_each_entry(device, &seed_devices->devices, dev_list) {
1478                 device->fs_devices = seed_devices;
1479         }
1480
1481         fs_devices->seeding = 0;
1482         fs_devices->num_devices = 0;
1483         fs_devices->open_devices = 0;
1484         fs_devices->seed = seed_devices;
1485
1486         generate_random_uuid(fs_devices->fsid);
1487         memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1488         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1489         super_flags = btrfs_super_flags(disk_super) &
1490                       ~BTRFS_SUPER_FLAG_SEEDING;
1491         btrfs_set_super_flags(disk_super, super_flags);
1492
1493         return 0;
1494 }
1495
1496 /*
1497  * strore the expected generation for seed devices in device items.
1498  */
1499 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1500                                struct btrfs_root *root)
1501 {
1502         struct btrfs_path *path;
1503         struct extent_buffer *leaf;
1504         struct btrfs_dev_item *dev_item;
1505         struct btrfs_device *device;
1506         struct btrfs_key key;
1507         u8 fs_uuid[BTRFS_UUID_SIZE];
1508         u8 dev_uuid[BTRFS_UUID_SIZE];
1509         u64 devid;
1510         int ret;
1511
1512         path = btrfs_alloc_path();
1513         if (!path)
1514                 return -ENOMEM;
1515
1516         root = root->fs_info->chunk_root;
1517         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1518         key.offset = 0;
1519         key.type = BTRFS_DEV_ITEM_KEY;
1520
1521         while (1) {
1522                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1523                 if (ret < 0)
1524                         goto error;
1525
1526                 leaf = path->nodes[0];
1527 next_slot:
1528                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1529                         ret = btrfs_next_leaf(root, path);
1530                         if (ret > 0)
1531                                 break;
1532                         if (ret < 0)
1533                                 goto error;
1534                         leaf = path->nodes[0];
1535                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1536                         btrfs_release_path(path);
1537                         continue;
1538                 }
1539
1540                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1541                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1542                     key.type != BTRFS_DEV_ITEM_KEY)
1543                         break;
1544
1545                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1546                                           struct btrfs_dev_item);
1547                 devid = btrfs_device_id(leaf, dev_item);
1548                 read_extent_buffer(leaf, dev_uuid,
1549                                    (unsigned long)btrfs_device_uuid(dev_item),
1550                                    BTRFS_UUID_SIZE);
1551                 read_extent_buffer(leaf, fs_uuid,
1552                                    (unsigned long)btrfs_device_fsid(dev_item),
1553                                    BTRFS_UUID_SIZE);
1554                 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1555                 BUG_ON(!device);
1556
1557                 if (device->fs_devices->seeding) {
1558                         btrfs_set_device_generation(leaf, dev_item,
1559                                                     device->generation);
1560                         btrfs_mark_buffer_dirty(leaf);
1561                 }
1562
1563                 path->slots[0]++;
1564                 goto next_slot;
1565         }
1566         ret = 0;
1567 error:
1568         btrfs_free_path(path);
1569         return ret;
1570 }
1571
1572 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1573 {
1574         struct request_queue *q;
1575         struct btrfs_trans_handle *trans;
1576         struct btrfs_device *device;
1577         struct block_device *bdev;
1578         struct list_head *devices;
1579         struct super_block *sb = root->fs_info->sb;
1580         u64 total_bytes;
1581         int seeding_dev = 0;
1582         int ret = 0;
1583
1584         if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1585                 return -EINVAL;
1586
1587         bdev = blkdev_get_by_path(device_path, FMODE_EXCL,
1588                                   root->fs_info->bdev_holder);
1589         if (IS_ERR(bdev))
1590                 return PTR_ERR(bdev);
1591
1592         if (root->fs_info->fs_devices->seeding) {
1593                 seeding_dev = 1;
1594                 down_write(&sb->s_umount);
1595                 mutex_lock(&uuid_mutex);
1596         }
1597
1598         filemap_write_and_wait(bdev->bd_inode->i_mapping);
1599         mutex_lock(&root->fs_info->volume_mutex);
1600
1601         devices = &root->fs_info->fs_devices->devices;
1602         /*
1603          * we have the volume lock, so we don't need the extra
1604          * device list mutex while reading the list here.
1605          */
1606         list_for_each_entry(device, devices, dev_list) {
1607                 if (device->bdev == bdev) {
1608                         ret = -EEXIST;
1609                         goto error;
1610                 }
1611         }
1612
1613         device = kzalloc(sizeof(*device), GFP_NOFS);
1614         if (!device) {
1615                 /* we can safely leave the fs_devices entry around */
1616                 ret = -ENOMEM;
1617                 goto error;
1618         }
1619
1620         device->name = kstrdup(device_path, GFP_NOFS);
1621         if (!device->name) {
1622                 kfree(device);
1623                 ret = -ENOMEM;
1624                 goto error;
1625         }
1626
1627         ret = find_next_devid(root, &device->devid);
1628         if (ret) {
1629                 kfree(device->name);
1630                 kfree(device);
1631                 goto error;
1632         }
1633
1634         trans = btrfs_start_transaction(root, 0);
1635         if (IS_ERR(trans)) {
1636                 kfree(device->name);
1637                 kfree(device);
1638                 ret = PTR_ERR(trans);
1639                 goto error;
1640         }
1641
1642         lock_chunks(root);
1643
1644         q = bdev_get_queue(bdev);
1645         if (blk_queue_discard(q))
1646                 device->can_discard = 1;
1647         device->writeable = 1;
1648         device->work.func = pending_bios_fn;
1649         generate_random_uuid(device->uuid);
1650         spin_lock_init(&device->io_lock);
1651         device->generation = trans->transid;
1652         device->io_width = root->sectorsize;
1653         device->io_align = root->sectorsize;
1654         device->sector_size = root->sectorsize;
1655         device->total_bytes = i_size_read(bdev->bd_inode);
1656         device->disk_total_bytes = device->total_bytes;
1657         device->dev_root = root->fs_info->dev_root;
1658         device->bdev = bdev;
1659         device->in_fs_metadata = 1;
1660         device->mode = FMODE_EXCL;
1661         set_blocksize(device->bdev, 4096);
1662
1663         if (seeding_dev) {
1664                 sb->s_flags &= ~MS_RDONLY;
1665                 ret = btrfs_prepare_sprout(trans, root);
1666                 BUG_ON(ret);
1667         }
1668
1669         device->fs_devices = root->fs_info->fs_devices;
1670
1671         /*
1672          * we don't want write_supers to jump in here with our device
1673          * half setup
1674          */
1675         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1676         list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
1677         list_add(&device->dev_alloc_list,
1678                  &root->fs_info->fs_devices->alloc_list);
1679         root->fs_info->fs_devices->num_devices++;
1680         root->fs_info->fs_devices->open_devices++;
1681         root->fs_info->fs_devices->rw_devices++;
1682         if (device->can_discard)
1683                 root->fs_info->fs_devices->num_can_discard++;
1684         root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
1685
1686         if (!blk_queue_nonrot(bdev_get_queue(bdev)))
1687                 root->fs_info->fs_devices->rotating = 1;
1688
1689         total_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
1690         btrfs_set_super_total_bytes(&root->fs_info->super_copy,
1691                                     total_bytes + device->total_bytes);
1692
1693         total_bytes = btrfs_super_num_devices(&root->fs_info->super_copy);
1694         btrfs_set_super_num_devices(&root->fs_info->super_copy,
1695                                     total_bytes + 1);
1696         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1697
1698         if (seeding_dev) {
1699                 ret = init_first_rw_device(trans, root, device);
1700                 BUG_ON(ret);
1701                 ret = btrfs_finish_sprout(trans, root);
1702                 BUG_ON(ret);
1703         } else {
1704                 ret = btrfs_add_device(trans, root, device);
1705         }
1706
1707         /*
1708          * we've got more storage, clear any full flags on the space
1709          * infos
1710          */
1711         btrfs_clear_space_info_full(root->fs_info);
1712
1713         unlock_chunks(root);
1714         btrfs_commit_transaction(trans, root);
1715
1716         if (seeding_dev) {
1717                 mutex_unlock(&uuid_mutex);
1718                 up_write(&sb->s_umount);
1719
1720                 ret = btrfs_relocate_sys_chunks(root);
1721                 BUG_ON(ret);
1722         }
1723 out:
1724         mutex_unlock(&root->fs_info->volume_mutex);
1725         return ret;
1726 error:
1727         blkdev_put(bdev, FMODE_EXCL);
1728         if (seeding_dev) {
1729                 mutex_unlock(&uuid_mutex);
1730                 up_write(&sb->s_umount);
1731         }
1732         goto out;
1733 }
1734
1735 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
1736                                         struct btrfs_device *device)
1737 {
1738         int ret;
1739         struct btrfs_path *path;
1740         struct btrfs_root *root;
1741         struct btrfs_dev_item *dev_item;
1742         struct extent_buffer *leaf;
1743         struct btrfs_key key;
1744
1745         root = device->dev_root->fs_info->chunk_root;
1746
1747         path = btrfs_alloc_path();
1748         if (!path)
1749                 return -ENOMEM;
1750
1751         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1752         key.type = BTRFS_DEV_ITEM_KEY;
1753         key.offset = device->devid;
1754
1755         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1756         if (ret < 0)
1757                 goto out;
1758
1759         if (ret > 0) {
1760                 ret = -ENOENT;
1761                 goto out;
1762         }
1763
1764         leaf = path->nodes[0];
1765         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1766
1767         btrfs_set_device_id(leaf, dev_item, device->devid);
1768         btrfs_set_device_type(leaf, dev_item, device->type);
1769         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1770         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1771         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1772         btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
1773         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1774         btrfs_mark_buffer_dirty(leaf);
1775
1776 out:
1777         btrfs_free_path(path);
1778         return ret;
1779 }
1780
1781 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
1782                       struct btrfs_device *device, u64 new_size)
1783 {
1784         struct btrfs_super_block *super_copy =
1785                 &device->dev_root->fs_info->super_copy;
1786         u64 old_total = btrfs_super_total_bytes(super_copy);
1787         u64 diff = new_size - device->total_bytes;
1788
1789         if (!device->writeable)
1790                 return -EACCES;
1791         if (new_size <= device->total_bytes)
1792                 return -EINVAL;
1793
1794         btrfs_set_super_total_bytes(super_copy, old_total + diff);
1795         device->fs_devices->total_rw_bytes += diff;
1796
1797         device->total_bytes = new_size;
1798         device->disk_total_bytes = new_size;
1799         btrfs_clear_space_info_full(device->dev_root->fs_info);
1800
1801         return btrfs_update_device(trans, device);
1802 }
1803
1804 int btrfs_grow_device(struct btrfs_trans_handle *trans,
1805                       struct btrfs_device *device, u64 new_size)
1806 {
1807         int ret;
1808         lock_chunks(device->dev_root);
1809         ret = __btrfs_grow_device(trans, device, new_size);
1810         unlock_chunks(device->dev_root);
1811         return ret;
1812 }
1813
1814 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1815                             struct btrfs_root *root,
1816                             u64 chunk_tree, u64 chunk_objectid,
1817                             u64 chunk_offset)
1818 {
1819         int ret;
1820         struct btrfs_path *path;
1821         struct btrfs_key key;
1822
1823         root = root->fs_info->chunk_root;
1824         path = btrfs_alloc_path();
1825         if (!path)
1826                 return -ENOMEM;
1827
1828         key.objectid = chunk_objectid;
1829         key.offset = chunk_offset;
1830         key.type = BTRFS_CHUNK_ITEM_KEY;
1831
1832         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1833         BUG_ON(ret);
1834
1835         ret = btrfs_del_item(trans, root, path);
1836
1837         btrfs_free_path(path);
1838         return ret;
1839 }
1840
1841 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
1842                         chunk_offset)
1843 {
1844         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1845         struct btrfs_disk_key *disk_key;
1846         struct btrfs_chunk *chunk;
1847         u8 *ptr;
1848         int ret = 0;
1849         u32 num_stripes;
1850         u32 array_size;
1851         u32 len = 0;
1852         u32 cur;
1853         struct btrfs_key key;
1854
1855         array_size = btrfs_super_sys_array_size(super_copy);
1856
1857         ptr = super_copy->sys_chunk_array;
1858         cur = 0;
1859
1860         while (cur < array_size) {
1861                 disk_key = (struct btrfs_disk_key *)ptr;
1862                 btrfs_disk_key_to_cpu(&key, disk_key);
1863
1864                 len = sizeof(*disk_key);
1865
1866                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1867                         chunk = (struct btrfs_chunk *)(ptr + len);
1868                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1869                         len += btrfs_chunk_item_size(num_stripes);
1870                 } else {
1871                         ret = -EIO;
1872                         break;
1873                 }
1874                 if (key.objectid == chunk_objectid &&
1875                     key.offset == chunk_offset) {
1876                         memmove(ptr, ptr + len, array_size - (cur + len));
1877                         array_size -= len;
1878                         btrfs_set_super_sys_array_size(super_copy, array_size);
1879                 } else {
1880                         ptr += len;
1881                         cur += len;
1882                 }
1883         }
1884         return ret;
1885 }
1886
1887 static int btrfs_relocate_chunk(struct btrfs_root *root,
1888                          u64 chunk_tree, u64 chunk_objectid,
1889                          u64 chunk_offset)
1890 {
1891         struct extent_map_tree *em_tree;
1892         struct btrfs_root *extent_root;
1893         struct btrfs_trans_handle *trans;
1894         struct extent_map *em;
1895         struct map_lookup *map;
1896         int ret;
1897         int i;
1898
1899         root = root->fs_info->chunk_root;
1900         extent_root = root->fs_info->extent_root;
1901         em_tree = &root->fs_info->mapping_tree.map_tree;
1902
1903         ret = btrfs_can_relocate(extent_root, chunk_offset);
1904         if (ret)
1905                 return -ENOSPC;
1906
1907         /* step one, relocate all the extents inside this chunk */
1908         ret = btrfs_relocate_block_group(extent_root, chunk_offset);
1909         if (ret)
1910                 return ret;
1911
1912         trans = btrfs_start_transaction(root, 0);
1913         BUG_ON(IS_ERR(trans));
1914
1915         lock_chunks(root);
1916
1917         /*
1918          * step two, delete the device extents and the
1919          * chunk tree entries
1920          */
1921         read_lock(&em_tree->lock);
1922         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1923         read_unlock(&em_tree->lock);
1924
1925         BUG_ON(em->start > chunk_offset ||
1926                em->start + em->len < chunk_offset);
1927         map = (struct map_lookup *)em->bdev;
1928
1929         for (i = 0; i < map->num_stripes; i++) {
1930                 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
1931                                             map->stripes[i].physical);
1932                 BUG_ON(ret);
1933
1934                 if (map->stripes[i].dev) {
1935                         ret = btrfs_update_device(trans, map->stripes[i].dev);
1936                         BUG_ON(ret);
1937                 }
1938         }
1939         ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
1940                                chunk_offset);
1941
1942         BUG_ON(ret);
1943
1944         trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
1945
1946         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
1947                 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
1948                 BUG_ON(ret);
1949         }
1950
1951         ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
1952         BUG_ON(ret);
1953
1954         write_lock(&em_tree->lock);
1955         remove_extent_mapping(em_tree, em);
1956         write_unlock(&em_tree->lock);
1957
1958         kfree(map);
1959         em->bdev = NULL;
1960
1961         /* once for the tree */
1962         free_extent_map(em);
1963         /* once for us */
1964         free_extent_map(em);
1965
1966         unlock_chunks(root);
1967         btrfs_end_transaction(trans, root);
1968         return 0;
1969 }
1970
1971 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
1972 {
1973         struct btrfs_root *chunk_root = root->fs_info->chunk_root;
1974         struct btrfs_path *path;
1975         struct extent_buffer *leaf;
1976         struct btrfs_chunk *chunk;
1977         struct btrfs_key key;
1978         struct btrfs_key found_key;
1979         u64 chunk_tree = chunk_root->root_key.objectid;
1980         u64 chunk_type;
1981         bool retried = false;
1982         int failed = 0;
1983         int ret;
1984
1985         path = btrfs_alloc_path();
1986         if (!path)
1987                 return -ENOMEM;
1988
1989 again:
1990         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1991         key.offset = (u64)-1;
1992         key.type = BTRFS_CHUNK_ITEM_KEY;
1993
1994         while (1) {
1995                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
1996                 if (ret < 0)
1997                         goto error;
1998                 BUG_ON(ret == 0);
1999
2000                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2001                                           key.type);
2002                 if (ret < 0)
2003                         goto error;
2004                 if (ret > 0)
2005                         break;
2006
2007                 leaf = path->nodes[0];
2008                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2009
2010                 chunk = btrfs_item_ptr(leaf, path->slots[0],
2011                                        struct btrfs_chunk);
2012                 chunk_type = btrfs_chunk_type(leaf, chunk);
2013                 btrfs_release_path(path);
2014
2015                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2016                         ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2017                                                    found_key.objectid,
2018                                                    found_key.offset);
2019                         if (ret == -ENOSPC)
2020                                 failed++;
2021                         else if (ret)
2022                                 BUG();
2023                 }
2024
2025                 if (found_key.offset == 0)
2026                         break;
2027                 key.offset = found_key.offset - 1;
2028         }
2029         ret = 0;
2030         if (failed && !retried) {
2031                 failed = 0;
2032                 retried = true;
2033                 goto again;
2034         } else if (failed && retried) {
2035                 WARN_ON(1);
2036                 ret = -ENOSPC;
2037         }
2038 error:
2039         btrfs_free_path(path);
2040         return ret;
2041 }
2042
2043 static u64 div_factor(u64 num, int factor)
2044 {
2045         if (factor == 10)
2046                 return num;
2047         num *= factor;
2048         do_div(num, 10);
2049         return num;
2050 }
2051
2052 int btrfs_balance(struct btrfs_root *dev_root)
2053 {
2054         int ret;
2055         struct list_head *devices = &dev_root->fs_info->fs_devices->devices;
2056         struct btrfs_device *device;
2057         u64 old_size;
2058         u64 size_to_free;
2059         struct btrfs_path *path;
2060         struct btrfs_key key;
2061         struct btrfs_root *chunk_root = dev_root->fs_info->chunk_root;
2062         struct btrfs_trans_handle *trans;
2063         struct btrfs_key found_key;
2064
2065         if (dev_root->fs_info->sb->s_flags & MS_RDONLY)
2066                 return -EROFS;
2067
2068         if (!capable(CAP_SYS_ADMIN))
2069                 return -EPERM;
2070
2071         mutex_lock(&dev_root->fs_info->volume_mutex);
2072         dev_root = dev_root->fs_info->dev_root;
2073
2074         /* step one make some room on all the devices */
2075         list_for_each_entry(device, devices, dev_list) {
2076                 old_size = device->total_bytes;
2077                 size_to_free = div_factor(old_size, 1);
2078                 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2079                 if (!device->writeable ||
2080                     device->total_bytes - device->bytes_used > size_to_free)
2081                         continue;
2082
2083                 ret = btrfs_shrink_device(device, old_size - size_to_free);
2084                 if (ret == -ENOSPC)
2085                         break;
2086                 BUG_ON(ret);
2087
2088                 trans = btrfs_start_transaction(dev_root, 0);
2089                 BUG_ON(IS_ERR(trans));
2090
2091                 ret = btrfs_grow_device(trans, device, old_size);
2092                 BUG_ON(ret);
2093
2094                 btrfs_end_transaction(trans, dev_root);
2095         }
2096
2097         /* step two, relocate all the chunks */
2098         path = btrfs_alloc_path();
2099         if (!path) {
2100                 ret = -ENOMEM;
2101                 goto error;
2102         }
2103         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2104         key.offset = (u64)-1;
2105         key.type = BTRFS_CHUNK_ITEM_KEY;
2106
2107         while (1) {
2108                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2109                 if (ret < 0)
2110                         goto error;
2111
2112                 /*
2113                  * this shouldn't happen, it means the last relocate
2114                  * failed
2115                  */
2116                 if (ret == 0)
2117                         break;
2118
2119                 ret = btrfs_previous_item(chunk_root, path, 0,
2120                                           BTRFS_CHUNK_ITEM_KEY);
2121                 if (ret)
2122                         break;
2123
2124                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2125                                       path->slots[0]);
2126                 if (found_key.objectid != key.objectid)
2127                         break;
2128
2129                 /* chunk zero is special */
2130                 if (found_key.offset == 0)
2131                         break;
2132
2133                 btrfs_release_path(path);
2134                 ret = btrfs_relocate_chunk(chunk_root,
2135                                            chunk_root->root_key.objectid,
2136                                            found_key.objectid,
2137                                            found_key.offset);
2138                 if (ret && ret != -ENOSPC)
2139                         goto error;
2140                 key.offset = found_key.offset - 1;
2141         }
2142         ret = 0;
2143 error:
2144         btrfs_free_path(path);
2145         mutex_unlock(&dev_root->fs_info->volume_mutex);
2146         return ret;
2147 }
2148
2149 /*
2150  * shrinking a device means finding all of the device extents past
2151  * the new size, and then following the back refs to the chunks.
2152  * The chunk relocation code actually frees the device extent
2153  */
2154 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
2155 {
2156         struct btrfs_trans_handle *trans;
2157         struct btrfs_root *root = device->dev_root;
2158         struct btrfs_dev_extent *dev_extent = NULL;
2159         struct btrfs_path *path;
2160         u64 length;
2161         u64 chunk_tree;
2162         u64 chunk_objectid;
2163         u64 chunk_offset;
2164         int ret;
2165         int slot;
2166         int failed = 0;
2167         bool retried = false;
2168         struct extent_buffer *l;
2169         struct btrfs_key key;
2170         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
2171         u64 old_total = btrfs_super_total_bytes(super_copy);
2172         u64 old_size = device->total_bytes;
2173         u64 diff = device->total_bytes - new_size;
2174
2175         if (new_size >= device->total_bytes)
2176                 return -EINVAL;
2177
2178         path = btrfs_alloc_path();
2179         if (!path)
2180                 return -ENOMEM;
2181
2182         path->reada = 2;
2183
2184         lock_chunks(root);
2185
2186         device->total_bytes = new_size;
2187         if (device->writeable)
2188                 device->fs_devices->total_rw_bytes -= diff;
2189         unlock_chunks(root);
2190
2191 again:
2192         key.objectid = device->devid;
2193         key.offset = (u64)-1;
2194         key.type = BTRFS_DEV_EXTENT_KEY;
2195
2196         while (1) {
2197                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2198                 if (ret < 0)
2199                         goto done;
2200
2201                 ret = btrfs_previous_item(root, path, 0, key.type);
2202                 if (ret < 0)
2203                         goto done;
2204                 if (ret) {
2205                         ret = 0;
2206                         btrfs_release_path(path);
2207                         break;
2208                 }
2209
2210                 l = path->nodes[0];
2211                 slot = path->slots[0];
2212                 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
2213
2214                 if (key.objectid != device->devid) {
2215                         btrfs_release_path(path);
2216                         break;
2217                 }
2218
2219                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
2220                 length = btrfs_dev_extent_length(l, dev_extent);
2221
2222                 if (key.offset + length <= new_size) {
2223                         btrfs_release_path(path);
2224                         break;
2225                 }
2226
2227                 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
2228                 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
2229                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
2230                 btrfs_release_path(path);
2231
2232                 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
2233                                            chunk_offset);
2234                 if (ret && ret != -ENOSPC)
2235                         goto done;
2236                 if (ret == -ENOSPC)
2237                         failed++;
2238                 key.offset -= 1;
2239         }
2240
2241         if (failed && !retried) {
2242                 failed = 0;
2243                 retried = true;
2244                 goto again;
2245         } else if (failed && retried) {
2246                 ret = -ENOSPC;
2247                 lock_chunks(root);
2248
2249                 device->total_bytes = old_size;
2250                 if (device->writeable)
2251                         device->fs_devices->total_rw_bytes += diff;
2252                 unlock_chunks(root);
2253                 goto done;
2254         }
2255
2256         /* Shrinking succeeded, else we would be at "done". */
2257         trans = btrfs_start_transaction(root, 0);
2258         if (IS_ERR(trans)) {
2259                 ret = PTR_ERR(trans);
2260                 goto done;
2261         }
2262
2263         lock_chunks(root);
2264
2265         device->disk_total_bytes = new_size;
2266         /* Now btrfs_update_device() will change the on-disk size. */
2267         ret = btrfs_update_device(trans, device);
2268         if (ret) {
2269                 unlock_chunks(root);
2270                 btrfs_end_transaction(trans, root);
2271                 goto done;
2272         }
2273         WARN_ON(diff > old_total);
2274         btrfs_set_super_total_bytes(super_copy, old_total - diff);
2275         unlock_chunks(root);
2276         btrfs_end_transaction(trans, root);
2277 done:
2278         btrfs_free_path(path);
2279         return ret;
2280 }
2281
2282 static int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
2283                            struct btrfs_root *root,
2284                            struct btrfs_key *key,
2285                            struct btrfs_chunk *chunk, int item_size)
2286 {
2287         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
2288         struct btrfs_disk_key disk_key;
2289         u32 array_size;
2290         u8 *ptr;
2291
2292         array_size = btrfs_super_sys_array_size(super_copy);
2293         if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
2294                 return -EFBIG;
2295
2296         ptr = super_copy->sys_chunk_array + array_size;
2297         btrfs_cpu_key_to_disk(&disk_key, key);
2298         memcpy(ptr, &disk_key, sizeof(disk_key));
2299         ptr += sizeof(disk_key);
2300         memcpy(ptr, chunk, item_size);
2301         item_size += sizeof(disk_key);
2302         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
2303         return 0;
2304 }
2305
2306 /*
2307  * sort the devices in descending order by max_avail, total_avail
2308  */
2309 static int btrfs_cmp_device_info(const void *a, const void *b)
2310 {
2311         const struct btrfs_device_info *di_a = a;
2312         const struct btrfs_device_info *di_b = b;
2313
2314         if (di_a->max_avail > di_b->max_avail)
2315                 return -1;
2316         if (di_a->max_avail < di_b->max_avail)
2317                 return 1;
2318         if (di_a->total_avail > di_b->total_avail)
2319                 return -1;
2320         if (di_a->total_avail < di_b->total_avail)
2321                 return 1;
2322         return 0;
2323 }
2324
2325 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
2326                                struct btrfs_root *extent_root,
2327                                struct map_lookup **map_ret,
2328                                u64 *num_bytes_out, u64 *stripe_size_out,
2329                                u64 start, u64 type)
2330 {
2331         struct btrfs_fs_info *info = extent_root->fs_info;
2332         struct btrfs_fs_devices *fs_devices = info->fs_devices;
2333         struct list_head *cur;
2334         struct map_lookup *map = NULL;
2335         struct extent_map_tree *em_tree;
2336         struct extent_map *em;
2337         struct btrfs_device_info *devices_info = NULL;
2338         u64 total_avail;
2339         int num_stripes;        /* total number of stripes to allocate */
2340         int sub_stripes;        /* sub_stripes info for map */
2341         int dev_stripes;        /* stripes per dev */
2342         int devs_max;           /* max devs to use */
2343         int devs_min;           /* min devs needed */
2344         int devs_increment;     /* ndevs has to be a multiple of this */
2345         int ncopies;            /* how many copies to data has */
2346         int ret;
2347         u64 max_stripe_size;
2348         u64 max_chunk_size;
2349         u64 stripe_size;
2350         u64 num_bytes;
2351         int ndevs;
2352         int i;
2353         int j;
2354
2355         if ((type & BTRFS_BLOCK_GROUP_RAID1) &&
2356             (type & BTRFS_BLOCK_GROUP_DUP)) {
2357                 WARN_ON(1);
2358                 type &= ~BTRFS_BLOCK_GROUP_DUP;
2359         }
2360
2361         if (list_empty(&fs_devices->alloc_list))
2362                 return -ENOSPC;
2363
2364         sub_stripes = 1;
2365         dev_stripes = 1;
2366         devs_increment = 1;
2367         ncopies = 1;
2368         devs_max = 0;   /* 0 == as many as possible */
2369         devs_min = 1;
2370
2371         /*
2372          * define the properties of each RAID type.
2373          * FIXME: move this to a global table and use it in all RAID
2374          * calculation code
2375          */
2376         if (type & (BTRFS_BLOCK_GROUP_DUP)) {
2377                 dev_stripes = 2;
2378                 ncopies = 2;
2379                 devs_max = 1;
2380         } else if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
2381                 devs_min = 2;
2382         } else if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
2383                 devs_increment = 2;
2384                 ncopies = 2;
2385                 devs_max = 2;
2386                 devs_min = 2;
2387         } else if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
2388                 sub_stripes = 2;
2389                 devs_increment = 2;
2390                 ncopies = 2;
2391                 devs_min = 4;
2392         } else {
2393                 devs_max = 1;
2394         }
2395
2396         if (type & BTRFS_BLOCK_GROUP_DATA) {
2397                 max_stripe_size = 1024 * 1024 * 1024;
2398                 max_chunk_size = 10 * max_stripe_size;
2399         } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
2400                 max_stripe_size = 256 * 1024 * 1024;
2401                 max_chunk_size = max_stripe_size;
2402         } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
2403                 max_stripe_size = 8 * 1024 * 1024;
2404                 max_chunk_size = 2 * max_stripe_size;
2405         } else {
2406                 printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
2407                        type);
2408                 BUG_ON(1);
2409         }
2410
2411         /* we don't want a chunk larger than 10% of writeable space */
2412         max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
2413                              max_chunk_size);
2414
2415         devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
2416                                GFP_NOFS);
2417         if (!devices_info)
2418                 return -ENOMEM;
2419
2420         cur = fs_devices->alloc_list.next;
2421
2422         /*
2423          * in the first pass through the devices list, we gather information
2424          * about the available holes on each device.
2425          */
2426         ndevs = 0;
2427         while (cur != &fs_devices->alloc_list) {
2428                 struct btrfs_device *device;
2429                 u64 max_avail;
2430                 u64 dev_offset;
2431
2432                 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
2433
2434                 cur = cur->next;
2435
2436                 if (!device->writeable) {
2437                         printk(KERN_ERR
2438                                "btrfs: read-only device in alloc_list\n");
2439                         WARN_ON(1);
2440                         continue;
2441                 }
2442
2443                 if (!device->in_fs_metadata)
2444                         continue;
2445
2446                 if (device->total_bytes > device->bytes_used)
2447                         total_avail = device->total_bytes - device->bytes_used;
2448                 else
2449                         total_avail = 0;
2450                 /* avail is off by max(alloc_start, 1MB), but that is the same
2451                  * for all devices, so it doesn't hurt the sorting later on
2452                  */
2453
2454                 ret = find_free_dev_extent(trans, device,
2455                                            max_stripe_size * dev_stripes,
2456                                            &dev_offset, &max_avail);
2457                 if (ret && ret != -ENOSPC)
2458                         goto error;
2459
2460                 if (ret == 0)
2461                         max_avail = max_stripe_size * dev_stripes;
2462
2463                 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
2464                         continue;
2465
2466                 devices_info[ndevs].dev_offset = dev_offset;
2467                 devices_info[ndevs].max_avail = max_avail;
2468                 devices_info[ndevs].total_avail = total_avail;
2469                 devices_info[ndevs].dev = device;
2470                 ++ndevs;
2471         }
2472
2473         /*
2474          * now sort the devices by hole size / available space
2475          */
2476         sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
2477              btrfs_cmp_device_info, NULL);
2478
2479         /* round down to number of usable stripes */
2480         ndevs -= ndevs % devs_increment;
2481
2482         if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
2483                 ret = -ENOSPC;
2484                 goto error;
2485         }
2486
2487         if (devs_max && ndevs > devs_max)
2488                 ndevs = devs_max;
2489         /*
2490          * the primary goal is to maximize the number of stripes, so use as many
2491          * devices as possible, even if the stripes are not maximum sized.
2492          */
2493         stripe_size = devices_info[ndevs-1].max_avail;
2494         num_stripes = ndevs * dev_stripes;
2495
2496         if (stripe_size * num_stripes > max_chunk_size * ncopies) {
2497                 stripe_size = max_chunk_size * ncopies;
2498                 do_div(stripe_size, num_stripes);
2499         }
2500
2501         do_div(stripe_size, dev_stripes);
2502         do_div(stripe_size, BTRFS_STRIPE_LEN);
2503         stripe_size *= BTRFS_STRIPE_LEN;
2504
2505         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
2506         if (!map) {
2507                 ret = -ENOMEM;
2508                 goto error;
2509         }
2510         map->num_stripes = num_stripes;
2511
2512         for (i = 0; i < ndevs; ++i) {
2513                 for (j = 0; j < dev_stripes; ++j) {
2514                         int s = i * dev_stripes + j;
2515                         map->stripes[s].dev = devices_info[i].dev;
2516                         map->stripes[s].physical = devices_info[i].dev_offset +
2517                                                    j * stripe_size;
2518                 }
2519         }
2520         map->sector_size = extent_root->sectorsize;
2521         map->stripe_len = BTRFS_STRIPE_LEN;
2522         map->io_align = BTRFS_STRIPE_LEN;
2523         map->io_width = BTRFS_STRIPE_LEN;
2524         map->type = type;
2525         map->sub_stripes = sub_stripes;
2526
2527         *map_ret = map;
2528         num_bytes = stripe_size * (num_stripes / ncopies);
2529
2530         *stripe_size_out = stripe_size;
2531         *num_bytes_out = num_bytes;
2532
2533         trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
2534
2535         em = alloc_extent_map();
2536         if (!em) {
2537                 ret = -ENOMEM;
2538                 goto error;
2539         }
2540         em->bdev = (struct block_device *)map;
2541         em->start = start;
2542         em->len = num_bytes;
2543         em->block_start = 0;
2544         em->block_len = em->len;
2545
2546         em_tree = &extent_root->fs_info->mapping_tree.map_tree;
2547         write_lock(&em_tree->lock);
2548         ret = add_extent_mapping(em_tree, em);
2549         write_unlock(&em_tree->lock);
2550         BUG_ON(ret);
2551         free_extent_map(em);
2552
2553         ret = btrfs_make_block_group(trans, extent_root, 0, type,
2554                                      BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2555                                      start, num_bytes);
2556         BUG_ON(ret);
2557
2558         for (i = 0; i < map->num_stripes; ++i) {
2559                 struct btrfs_device *device;
2560                 u64 dev_offset;
2561
2562                 device = map->stripes[i].dev;
2563                 dev_offset = map->stripes[i].physical;
2564
2565                 ret = btrfs_alloc_dev_extent(trans, device,
2566                                 info->chunk_root->root_key.objectid,
2567                                 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2568                                 start, dev_offset, stripe_size);
2569                 BUG_ON(ret);
2570         }
2571
2572         kfree(devices_info);
2573         return 0;
2574
2575 error:
2576         kfree(map);
2577         kfree(devices_info);
2578         return ret;
2579 }
2580
2581 static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
2582                                 struct btrfs_root *extent_root,
2583                                 struct map_lookup *map, u64 chunk_offset,
2584                                 u64 chunk_size, u64 stripe_size)
2585 {
2586         u64 dev_offset;
2587         struct btrfs_key key;
2588         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
2589         struct btrfs_device *device;
2590         struct btrfs_chunk *chunk;
2591         struct btrfs_stripe *stripe;
2592         size_t item_size = btrfs_chunk_item_size(map->num_stripes);
2593         int index = 0;
2594         int ret;
2595
2596         chunk = kzalloc(item_size, GFP_NOFS);
2597         if (!chunk)
2598                 return -ENOMEM;
2599
2600         index = 0;
2601         while (index < map->num_stripes) {
2602                 device = map->stripes[index].dev;
2603                 device->bytes_used += stripe_size;
2604                 ret = btrfs_update_device(trans, device);
2605                 BUG_ON(ret);
2606                 index++;
2607         }
2608
2609         index = 0;
2610         stripe = &chunk->stripe;
2611         while (index < map->num_stripes) {
2612                 device = map->stripes[index].dev;
2613                 dev_offset = map->stripes[index].physical;
2614
2615                 btrfs_set_stack_stripe_devid(stripe, device->devid);
2616                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
2617                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
2618                 stripe++;
2619                 index++;
2620         }
2621
2622         btrfs_set_stack_chunk_length(chunk, chunk_size);
2623         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
2624         btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
2625         btrfs_set_stack_chunk_type(chunk, map->type);
2626         btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
2627         btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
2628         btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
2629         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
2630         btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
2631
2632         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2633         key.type = BTRFS_CHUNK_ITEM_KEY;
2634         key.offset = chunk_offset;
2635
2636         ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
2637         BUG_ON(ret);
2638
2639         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2640                 ret = btrfs_add_system_chunk(trans, chunk_root, &key, chunk,
2641                                              item_size);
2642                 BUG_ON(ret);
2643         }
2644
2645         kfree(chunk);
2646         return 0;
2647 }
2648
2649 /*
2650  * Chunk allocation falls into two parts. The first part does works
2651  * that make the new allocated chunk useable, but not do any operation
2652  * that modifies the chunk tree. The second part does the works that
2653  * require modifying the chunk tree. This division is important for the
2654  * bootstrap process of adding storage to a seed btrfs.
2655  */
2656 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
2657                       struct btrfs_root *extent_root, u64 type)
2658 {
2659         u64 chunk_offset;
2660         u64 chunk_size;
2661         u64 stripe_size;
2662         struct map_lookup *map;
2663         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
2664         int ret;
2665
2666         ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
2667                               &chunk_offset);
2668         if (ret)
2669                 return ret;
2670
2671         ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
2672                                   &stripe_size, chunk_offset, type);
2673         if (ret)
2674                 return ret;
2675
2676         ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
2677                                    chunk_size, stripe_size);
2678         BUG_ON(ret);
2679         return 0;
2680 }
2681
2682 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
2683                                          struct btrfs_root *root,
2684                                          struct btrfs_device *device)
2685 {
2686         u64 chunk_offset;
2687         u64 sys_chunk_offset;
2688         u64 chunk_size;
2689         u64 sys_chunk_size;
2690         u64 stripe_size;
2691         u64 sys_stripe_size;
2692         u64 alloc_profile;
2693         struct map_lookup *map;
2694         struct map_lookup *sys_map;
2695         struct btrfs_fs_info *fs_info = root->fs_info;
2696         struct btrfs_root *extent_root = fs_info->extent_root;
2697         int ret;
2698
2699         ret = find_next_chunk(fs_info->chunk_root,
2700                               BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
2701         if (ret)
2702                 return ret;
2703
2704         alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
2705                         (fs_info->metadata_alloc_profile &
2706                          fs_info->avail_metadata_alloc_bits);
2707         alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
2708
2709         ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
2710                                   &stripe_size, chunk_offset, alloc_profile);
2711         BUG_ON(ret);
2712
2713         sys_chunk_offset = chunk_offset + chunk_size;
2714
2715         alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
2716                         (fs_info->system_alloc_profile &
2717                          fs_info->avail_system_alloc_bits);
2718         alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
2719
2720         ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
2721                                   &sys_chunk_size, &sys_stripe_size,
2722                                   sys_chunk_offset, alloc_profile);
2723         BUG_ON(ret);
2724
2725         ret = btrfs_add_device(trans, fs_info->chunk_root, device);
2726         BUG_ON(ret);
2727
2728         /*
2729          * Modifying chunk tree needs allocating new blocks from both
2730          * system block group and metadata block group. So we only can
2731          * do operations require modifying the chunk tree after both
2732          * block groups were created.
2733          */
2734         ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
2735                                    chunk_size, stripe_size);
2736         BUG_ON(ret);
2737
2738         ret = __finish_chunk_alloc(trans, extent_root, sys_map,
2739                                    sys_chunk_offset, sys_chunk_size,
2740                                    sys_stripe_size);
2741         BUG_ON(ret);
2742         return 0;
2743 }
2744
2745 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
2746 {
2747         struct extent_map *em;
2748         struct map_lookup *map;
2749         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
2750         int readonly = 0;
2751         int i;
2752
2753         read_lock(&map_tree->map_tree.lock);
2754         em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
2755         read_unlock(&map_tree->map_tree.lock);
2756         if (!em)
2757                 return 1;
2758
2759         if (btrfs_test_opt(root, DEGRADED)) {
2760                 free_extent_map(em);
2761                 return 0;
2762         }
2763
2764         map = (struct map_lookup *)em->bdev;
2765         for (i = 0; i < map->num_stripes; i++) {
2766                 if (!map->stripes[i].dev->writeable) {
2767                         readonly = 1;
2768                         break;
2769                 }
2770         }
2771         free_extent_map(em);
2772         return readonly;
2773 }
2774
2775 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
2776 {
2777         extent_map_tree_init(&tree->map_tree);
2778 }
2779
2780 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
2781 {
2782         struct extent_map *em;
2783
2784         while (1) {
2785                 write_lock(&tree->map_tree.lock);
2786                 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
2787                 if (em)
2788                         remove_extent_mapping(&tree->map_tree, em);
2789                 write_unlock(&tree->map_tree.lock);
2790                 if (!em)
2791                         break;
2792                 kfree(em->bdev);
2793                 /* once for us */
2794                 free_extent_map(em);
2795                 /* once for the tree */
2796                 free_extent_map(em);
2797         }
2798 }
2799
2800 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
2801 {
2802         struct extent_map *em;
2803         struct map_lookup *map;
2804         struct extent_map_tree *em_tree = &map_tree->map_tree;
2805         int ret;
2806
2807         read_lock(&em_tree->lock);
2808         em = lookup_extent_mapping(em_tree, logical, len);
2809         read_unlock(&em_tree->lock);
2810         BUG_ON(!em);
2811
2812         BUG_ON(em->start > logical || em->start + em->len < logical);
2813         map = (struct map_lookup *)em->bdev;
2814         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
2815                 ret = map->num_stripes;
2816         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
2817                 ret = map->sub_stripes;
2818         else
2819                 ret = 1;
2820         free_extent_map(em);
2821         return ret;
2822 }
2823
2824 static int find_live_mirror(struct map_lookup *map, int first, int num,
2825                             int optimal)
2826 {
2827         int i;
2828         if (map->stripes[optimal].dev->bdev)
2829                 return optimal;
2830         for (i = first; i < first + num; i++) {
2831                 if (map->stripes[i].dev->bdev)
2832                         return i;
2833         }
2834         /* we couldn't find one that doesn't fail.  Just return something
2835          * and the io error handling code will clean up eventually
2836          */
2837         return optimal;
2838 }
2839
2840 static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
2841                              u64 logical, u64 *length,
2842                              struct btrfs_multi_bio **multi_ret,
2843                              int mirror_num)
2844 {
2845         struct extent_map *em;
2846         struct map_lookup *map;
2847         struct extent_map_tree *em_tree = &map_tree->map_tree;
2848         u64 offset;
2849         u64 stripe_offset;
2850         u64 stripe_end_offset;
2851         u64 stripe_nr;
2852         u64 stripe_nr_orig;
2853         u64 stripe_nr_end;
2854         int stripes_allocated = 8;
2855         int stripes_required = 1;
2856         int stripe_index;
2857         int i;
2858         int num_stripes;
2859         int max_errors = 0;
2860         struct btrfs_multi_bio *multi = NULL;
2861
2862         if (multi_ret && !(rw & (REQ_WRITE | REQ_DISCARD)))
2863                 stripes_allocated = 1;
2864 again:
2865         if (multi_ret) {
2866                 multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
2867                                 GFP_NOFS);
2868                 if (!multi)
2869                         return -ENOMEM;
2870
2871                 atomic_set(&multi->error, 0);
2872         }
2873
2874         read_lock(&em_tree->lock);
2875         em = lookup_extent_mapping(em_tree, logical, *length);
2876         read_unlock(&em_tree->lock);
2877
2878         if (!em) {
2879                 printk(KERN_CRIT "unable to find logical %llu len %llu\n",
2880                        (unsigned long long)logical,
2881                        (unsigned long long)*length);
2882                 BUG();
2883         }
2884
2885         BUG_ON(em->start > logical || em->start + em->len < logical);
2886         map = (struct map_lookup *)em->bdev;
2887         offset = logical - em->start;
2888
2889         if (mirror_num > map->num_stripes)
2890                 mirror_num = 0;
2891
2892         /* if our multi bio struct is too small, back off and try again */
2893         if (rw & REQ_WRITE) {
2894                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
2895                                  BTRFS_BLOCK_GROUP_DUP)) {
2896                         stripes_required = map->num_stripes;
2897                         max_errors = 1;
2898                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
2899                         stripes_required = map->sub_stripes;
2900                         max_errors = 1;
2901                 }
2902         }
2903         if (rw & REQ_DISCARD) {
2904                 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2905                                  BTRFS_BLOCK_GROUP_RAID1 |
2906                                  BTRFS_BLOCK_GROUP_DUP |
2907                                  BTRFS_BLOCK_GROUP_RAID10)) {
2908                         stripes_required = map->num_stripes;
2909                 }
2910         }
2911         if (multi_ret && (rw & (REQ_WRITE | REQ_DISCARD)) &&
2912             stripes_allocated < stripes_required) {
2913                 stripes_allocated = map->num_stripes;
2914                 free_extent_map(em);
2915                 kfree(multi);
2916                 goto again;
2917         }
2918         stripe_nr = offset;
2919         /*
2920          * stripe_nr counts the total number of stripes we have to stride
2921          * to get to this block
2922          */
2923         do_div(stripe_nr, map->stripe_len);
2924
2925         stripe_offset = stripe_nr * map->stripe_len;
2926         BUG_ON(offset < stripe_offset);
2927
2928         /* stripe_offset is the offset of this block in its stripe*/
2929         stripe_offset = offset - stripe_offset;
2930
2931         if (rw & REQ_DISCARD)
2932                 *length = min_t(u64, em->len - offset, *length);
2933         else if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2934                               BTRFS_BLOCK_GROUP_RAID1 |
2935                               BTRFS_BLOCK_GROUP_RAID10 |
2936                               BTRFS_BLOCK_GROUP_DUP)) {
2937                 /* we limit the length of each bio to what fits in a stripe */
2938                 *length = min_t(u64, em->len - offset,
2939                                 map->stripe_len - stripe_offset);
2940         } else {
2941                 *length = em->len - offset;
2942         }
2943
2944         if (!multi_ret)
2945                 goto out;
2946
2947         num_stripes = 1;
2948         stripe_index = 0;
2949         stripe_nr_orig = stripe_nr;
2950         stripe_nr_end = (offset + *length + map->stripe_len - 1) &
2951                         (~(map->stripe_len - 1));
2952         do_div(stripe_nr_end, map->stripe_len);
2953         stripe_end_offset = stripe_nr_end * map->stripe_len -
2954                             (offset + *length);
2955         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
2956                 if (rw & REQ_DISCARD)
2957                         num_stripes = min_t(u64, map->num_stripes,
2958                                             stripe_nr_end - stripe_nr_orig);
2959                 stripe_index = do_div(stripe_nr, map->num_stripes);
2960         } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
2961                 if (rw & (REQ_WRITE | REQ_DISCARD))
2962                         num_stripes = map->num_stripes;
2963                 else if (mirror_num)
2964                         stripe_index = mirror_num - 1;
2965                 else {
2966                         stripe_index = find_live_mirror(map, 0,
2967                                             map->num_stripes,
2968                                             current->pid % map->num_stripes);
2969                 }
2970
2971         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
2972                 if (rw & (REQ_WRITE | REQ_DISCARD))
2973                         num_stripes = map->num_stripes;
2974                 else if (mirror_num)
2975                         stripe_index = mirror_num - 1;
2976
2977         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
2978                 int factor = map->num_stripes / map->sub_stripes;
2979
2980                 stripe_index = do_div(stripe_nr, factor);
2981                 stripe_index *= map->sub_stripes;
2982
2983                 if (rw & REQ_WRITE)
2984                         num_stripes = map->sub_stripes;
2985                 else if (rw & REQ_DISCARD)
2986                         num_stripes = min_t(u64, map->sub_stripes *
2987                                             (stripe_nr_end - stripe_nr_orig),
2988                                             map->num_stripes);
2989                 else if (mirror_num)
2990                         stripe_index += mirror_num - 1;
2991                 else {
2992                         stripe_index = find_live_mirror(map, stripe_index,
2993                                               map->sub_stripes, stripe_index +
2994                                               current->pid % map->sub_stripes);
2995                 }
2996         } else {
2997                 /*
2998                  * after this do_div call, stripe_nr is the number of stripes
2999                  * on this device we have to walk to find the data, and
3000                  * stripe_index is the number of our device in the stripe array
3001                  */
3002                 stripe_index = do_div(stripe_nr, map->num_stripes);
3003         }
3004         BUG_ON(stripe_index >= map->num_stripes);
3005
3006         if (rw & REQ_DISCARD) {
3007                 for (i = 0; i < num_stripes; i++) {
3008                         multi->stripes[i].physical =
3009                                 map->stripes[stripe_index].physical +
3010                                 stripe_offset + stripe_nr * map->stripe_len;
3011                         multi->stripes[i].dev = map->stripes[stripe_index].dev;
3012
3013                         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3014                                 u64 stripes;
3015                                 u32 last_stripe = 0;
3016                                 int j;
3017
3018                                 div_u64_rem(stripe_nr_end - 1,
3019                                             map->num_stripes,
3020                                             &last_stripe);
3021
3022                                 for (j = 0; j < map->num_stripes; j++) {
3023                                         u32 test;
3024
3025                                         div_u64_rem(stripe_nr_end - 1 - j,
3026                                                     map->num_stripes, &test);
3027                                         if (test == stripe_index)
3028                                                 break;
3029                                 }
3030                                 stripes = stripe_nr_end - 1 - j;
3031                                 do_div(stripes, map->num_stripes);
3032                                 multi->stripes[i].length = map->stripe_len *
3033                                         (stripes - stripe_nr + 1);
3034
3035                                 if (i == 0) {
3036                                         multi->stripes[i].length -=
3037                                                 stripe_offset;
3038                                         stripe_offset = 0;
3039                                 }
3040                                 if (stripe_index == last_stripe)
3041                                         multi->stripes[i].length -=
3042                                                 stripe_end_offset;
3043                         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3044                                 u64 stripes;
3045                                 int j;
3046                                 int factor = map->num_stripes /
3047                                              map->sub_stripes;
3048                                 u32 last_stripe = 0;
3049
3050                                 div_u64_rem(stripe_nr_end - 1,
3051                                             factor, &last_stripe);
3052                                 last_stripe *= map->sub_stripes;
3053
3054                                 for (j = 0; j < factor; j++) {
3055                                         u32 test;
3056
3057                                         div_u64_rem(stripe_nr_end - 1 - j,
3058                                                     factor, &test);
3059
3060                                         if (test ==
3061                                             stripe_index / map->sub_stripes)
3062                                                 break;
3063                                 }
3064                                 stripes = stripe_nr_end - 1 - j;
3065                                 do_div(stripes, factor);
3066                                 multi->stripes[i].length = map->stripe_len *
3067                                         (stripes - stripe_nr + 1);
3068
3069                                 if (i < map->sub_stripes) {
3070                                         multi->stripes[i].length -=
3071                                                 stripe_offset;
3072                                         if (i == map->sub_stripes - 1)
3073                                                 stripe_offset = 0;
3074                                 }
3075                                 if (stripe_index >= last_stripe &&
3076                                     stripe_index <= (last_stripe +
3077                                                      map->sub_stripes - 1)) {
3078                                         multi->stripes[i].length -=
3079                                                 stripe_end_offset;
3080                                 }
3081                         } else
3082                                 multi->stripes[i].length = *length;
3083
3084                         stripe_index++;
3085                         if (stripe_index == map->num_stripes) {
3086                                 /* This could only happen for RAID0/10 */
3087                                 stripe_index = 0;
3088                                 stripe_nr++;
3089                         }
3090                 }
3091         } else {
3092                 for (i = 0; i < num_stripes; i++) {
3093                         multi->stripes[i].physical =
3094                                 map->stripes[stripe_index].physical +
3095                                 stripe_offset +
3096                                 stripe_nr * map->stripe_len;
3097                         multi->stripes[i].dev =
3098                                 map->stripes[stripe_index].dev;
3099                         stripe_index++;
3100                 }
3101         }
3102         if (multi_ret) {
3103                 *multi_ret = multi;
3104                 multi->num_stripes = num_stripes;
3105                 multi->max_errors = max_errors;
3106         }
3107 out:
3108         free_extent_map(em);
3109         return 0;
3110 }
3111
3112 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3113                       u64 logical, u64 *length,
3114                       struct btrfs_multi_bio **multi_ret, int mirror_num)
3115 {
3116         return __btrfs_map_block(map_tree, rw, logical, length, multi_ret,
3117                                  mirror_num);
3118 }
3119
3120 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
3121                      u64 chunk_start, u64 physical, u64 devid,
3122                      u64 **logical, int *naddrs, int *stripe_len)
3123 {
3124         struct extent_map_tree *em_tree = &map_tree->map_tree;
3125         struct extent_map *em;
3126         struct map_lookup *map;
3127         u64 *buf;
3128         u64 bytenr;
3129         u64 length;
3130         u64 stripe_nr;
3131         int i, j, nr = 0;
3132
3133         read_lock(&em_tree->lock);
3134         em = lookup_extent_mapping(em_tree, chunk_start, 1);
3135         read_unlock(&em_tree->lock);
3136
3137         BUG_ON(!em || em->start != chunk_start);
3138         map = (struct map_lookup *)em->bdev;
3139
3140         length = em->len;
3141         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3142                 do_div(length, map->num_stripes / map->sub_stripes);
3143         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3144                 do_div(length, map->num_stripes);
3145
3146         buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
3147         BUG_ON(!buf);
3148
3149         for (i = 0; i < map->num_stripes; i++) {
3150                 if (devid && map->stripes[i].dev->devid != devid)
3151                         continue;
3152                 if (map->stripes[i].physical > physical ||
3153                     map->stripes[i].physical + length <= physical)
3154                         continue;
3155
3156                 stripe_nr = physical - map->stripes[i].physical;
3157                 do_div(stripe_nr, map->stripe_len);
3158
3159                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3160                         stripe_nr = stripe_nr * map->num_stripes + i;
3161                         do_div(stripe_nr, map->sub_stripes);
3162                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3163                         stripe_nr = stripe_nr * map->num_stripes + i;
3164                 }
3165                 bytenr = chunk_start + stripe_nr * map->stripe_len;
3166                 WARN_ON(nr >= map->num_stripes);
3167                 for (j = 0; j < nr; j++) {
3168                         if (buf[j] == bytenr)
3169                                 break;
3170                 }
3171                 if (j == nr) {
3172                         WARN_ON(nr >= map->num_stripes);
3173                         buf[nr++] = bytenr;
3174                 }
3175         }
3176
3177         *logical = buf;
3178         *naddrs = nr;
3179         *stripe_len = map->stripe_len;
3180
3181         free_extent_map(em);
3182         return 0;
3183 }
3184
3185 static void end_bio_multi_stripe(struct bio *bio, int err)
3186 {
3187         struct btrfs_multi_bio *multi = bio->bi_private;
3188         int is_orig_bio = 0;
3189
3190         if (err)
3191                 atomic_inc(&multi->error);
3192
3193         if (bio == multi->orig_bio)
3194                 is_orig_bio = 1;
3195
3196         if (atomic_dec_and_test(&multi->stripes_pending)) {
3197                 if (!is_orig_bio) {
3198                         bio_put(bio);
3199                         bio = multi->orig_bio;
3200                 }
3201                 bio->bi_private = multi->private;
3202                 bio->bi_end_io = multi->end_io;
3203                 /* only send an error to the higher layers if it is
3204                  * beyond the tolerance of the multi-bio
3205                  */
3206                 if (atomic_read(&multi->error) > multi->max_errors) {
3207                         err = -EIO;
3208                 } else if (err) {
3209                         /*
3210                          * this bio is actually up to date, we didn't
3211                          * go over the max number of errors
3212                          */
3213                         set_bit(BIO_UPTODATE, &bio->bi_flags);
3214                         err = 0;
3215                 }
3216                 kfree(multi);
3217
3218                 bio_endio(bio, err);
3219         } else if (!is_orig_bio) {
3220                 bio_put(bio);
3221         }
3222 }
3223
3224 struct async_sched {
3225         struct bio *bio;
3226         int rw;
3227         struct btrfs_fs_info *info;
3228         struct btrfs_work work;
3229 };
3230
3231 /*
3232  * see run_scheduled_bios for a description of why bios are collected for
3233  * async submit.
3234  *
3235  * This will add one bio to the pending list for a device and make sure
3236  * the work struct is scheduled.
3237  */
3238 static noinline int schedule_bio(struct btrfs_root *root,
3239                                  struct btrfs_device *device,
3240                                  int rw, struct bio *bio)
3241 {
3242         int should_queue = 1;
3243         struct btrfs_pending_bios *pending_bios;
3244
3245         /* don't bother with additional async steps for reads, right now */
3246         if (!(rw & REQ_WRITE)) {
3247                 bio_get(bio);
3248                 submit_bio(rw, bio);
3249                 bio_put(bio);
3250                 return 0;
3251         }
3252
3253         /*
3254          * nr_async_bios allows us to reliably return congestion to the
3255          * higher layers.  Otherwise, the async bio makes it appear we have
3256          * made progress against dirty pages when we've really just put it
3257          * on a queue for later
3258          */
3259         atomic_inc(&root->fs_info->nr_async_bios);
3260         WARN_ON(bio->bi_next);
3261         bio->bi_next = NULL;
3262         bio->bi_rw |= rw;
3263
3264         spin_lock(&device->io_lock);
3265         if (bio->bi_rw & REQ_SYNC)
3266                 pending_bios = &device->pending_sync_bios;
3267         else
3268                 pending_bios = &device->pending_bios;
3269
3270         if (pending_bios->tail)
3271                 pending_bios->tail->bi_next = bio;
3272
3273         pending_bios->tail = bio;
3274         if (!pending_bios->head)
3275                 pending_bios->head = bio;
3276         if (device->running_pending)
3277                 should_queue = 0;
3278
3279         spin_unlock(&device->io_lock);
3280
3281         if (should_queue)
3282                 btrfs_queue_worker(&root->fs_info->submit_workers,
3283                                    &device->work);
3284         return 0;
3285 }
3286
3287 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
3288                   int mirror_num, int async_submit)
3289 {
3290         struct btrfs_mapping_tree *map_tree;
3291         struct btrfs_device *dev;
3292         struct bio *first_bio = bio;
3293         u64 logical = (u64)bio->bi_sector << 9;
3294         u64 length = 0;
3295         u64 map_length;
3296         struct btrfs_multi_bio *multi = NULL;
3297         int ret;
3298         int dev_nr = 0;
3299         int total_devs = 1;
3300
3301         length = bio->bi_size;
3302         map_tree = &root->fs_info->mapping_tree;
3303         map_length = length;
3304
3305         ret = btrfs_map_block(map_tree, rw, logical, &map_length, &multi,
3306                               mirror_num);
3307         BUG_ON(ret);
3308
3309         total_devs = multi->num_stripes;
3310         if (map_length < length) {
3311                 printk(KERN_CRIT "mapping failed logical %llu bio len %llu "
3312                        "len %llu\n", (unsigned long long)logical,
3313                        (unsigned long long)length,
3314                        (unsigned long long)map_length);
3315                 BUG();
3316         }
3317         multi->end_io = first_bio->bi_end_io;
3318         multi->private = first_bio->bi_private;
3319         multi->orig_bio = first_bio;
3320         atomic_set(&multi->stripes_pending, multi->num_stripes);
3321
3322         while (dev_nr < total_devs) {
3323                 if (total_devs > 1) {
3324                         if (dev_nr < total_devs - 1) {
3325                                 bio = bio_clone(first_bio, GFP_NOFS);
3326                                 BUG_ON(!bio);
3327                         } else {
3328                                 bio = first_bio;
3329                         }
3330                         bio->bi_private = multi;
3331                         bio->bi_end_io = end_bio_multi_stripe;
3332                 }
3333                 bio->bi_sector = multi->stripes[dev_nr].physical >> 9;
3334                 dev = multi->stripes[dev_nr].dev;
3335                 if (dev && dev->bdev && (rw != WRITE || dev->writeable)) {
3336                         bio->bi_bdev = dev->bdev;
3337                         if (async_submit)
3338                                 schedule_bio(root, dev, rw, bio);
3339                         else
3340                                 submit_bio(rw, bio);
3341                 } else {
3342                         bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
3343                         bio->bi_sector = logical >> 9;
3344                         bio_endio(bio, -EIO);
3345                 }
3346                 dev_nr++;
3347         }
3348         if (total_devs == 1)
3349                 kfree(multi);
3350         return 0;
3351 }
3352
3353 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
3354                                        u8 *uuid, u8 *fsid)
3355 {
3356         struct btrfs_device *device;
3357         struct btrfs_fs_devices *cur_devices;
3358
3359         cur_devices = root->fs_info->fs_devices;
3360         while (cur_devices) {
3361                 if (!fsid ||
3362                     !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
3363                         device = __find_device(&cur_devices->devices,
3364                                                devid, uuid);
3365                         if (device)
3366                                 return device;
3367                 }
3368                 cur_devices = cur_devices->seed;
3369         }
3370         return NULL;
3371 }
3372
3373 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
3374                                             u64 devid, u8 *dev_uuid)
3375 {
3376         struct btrfs_device *device;
3377         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
3378
3379         device = kzalloc(sizeof(*device), GFP_NOFS);
3380         if (!device)
3381                 return NULL;
3382         list_add(&device->dev_list,
3383                  &fs_devices->devices);
3384         device->dev_root = root->fs_info->dev_root;
3385         device->devid = devid;
3386         device->work.func = pending_bios_fn;
3387         device->fs_devices = fs_devices;
3388         device->missing = 1;
3389         fs_devices->num_devices++;
3390         fs_devices->missing_devices++;
3391         spin_lock_init(&device->io_lock);
3392         INIT_LIST_HEAD(&device->dev_alloc_list);
3393         memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
3394         return device;
3395 }
3396
3397 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
3398                           struct extent_buffer *leaf,
3399                           struct btrfs_chunk *chunk)
3400 {
3401         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
3402         struct map_lookup *map;
3403         struct extent_map *em;
3404         u64 logical;
3405         u64 length;
3406         u64 devid;
3407         u8 uuid[BTRFS_UUID_SIZE];
3408         int num_stripes;
3409         int ret;
3410         int i;
3411
3412         logical = key->offset;
3413         length = btrfs_chunk_length(leaf, chunk);
3414
3415         read_lock(&map_tree->map_tree.lock);
3416         em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
3417         read_unlock(&map_tree->map_tree.lock);
3418
3419         /* already mapped? */
3420         if (em && em->start <= logical && em->start + em->len > logical) {
3421                 free_extent_map(em);
3422                 return 0;
3423         } else if (em) {
3424                 free_extent_map(em);
3425         }
3426
3427         em = alloc_extent_map();
3428         if (!em)
3429                 return -ENOMEM;
3430         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3431         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
3432         if (!map) {
3433                 free_extent_map(em);
3434                 return -ENOMEM;
3435         }
3436
3437         em->bdev = (struct block_device *)map;
3438         em->start = logical;
3439         em->len = length;
3440         em->block_start = 0;
3441         em->block_len = em->len;
3442
3443         map->num_stripes = num_stripes;
3444         map->io_width = btrfs_chunk_io_width(leaf, chunk);
3445         map->io_align = btrfs_chunk_io_align(leaf, chunk);
3446         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
3447         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
3448         map->type = btrfs_chunk_type(leaf, chunk);
3449         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
3450         for (i = 0; i < num_stripes; i++) {
3451                 map->stripes[i].physical =
3452                         btrfs_stripe_offset_nr(leaf, chunk, i);
3453                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
3454                 read_extent_buffer(leaf, uuid, (unsigned long)
3455                                    btrfs_stripe_dev_uuid_nr(chunk, i),
3456                                    BTRFS_UUID_SIZE);
3457                 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
3458                                                         NULL);
3459                 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
3460                         kfree(map);
3461                         free_extent_map(em);
3462                         return -EIO;
3463                 }
3464                 if (!map->stripes[i].dev) {
3465                         map->stripes[i].dev =
3466                                 add_missing_dev(root, devid, uuid);
3467                         if (!map->stripes[i].dev) {
3468                                 kfree(map);
3469                                 free_extent_map(em);
3470                                 return -EIO;
3471                         }
3472                 }
3473                 map->stripes[i].dev->in_fs_metadata = 1;
3474         }
3475
3476         write_lock(&map_tree->map_tree.lock);
3477         ret = add_extent_mapping(&map_tree->map_tree, em);
3478         write_unlock(&map_tree->map_tree.lock);
3479         BUG_ON(ret);
3480         free_extent_map(em);
3481
3482         return 0;
3483 }
3484
3485 static int fill_device_from_item(struct extent_buffer *leaf,
3486                                  struct btrfs_dev_item *dev_item,
3487                                  struct btrfs_device *device)
3488 {
3489         unsigned long ptr;
3490
3491         device->devid = btrfs_device_id(leaf, dev_item);
3492         device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
3493         device->total_bytes = device->disk_total_bytes;
3494         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
3495         device->type = btrfs_device_type(leaf, dev_item);
3496         device->io_align = btrfs_device_io_align(leaf, dev_item);
3497         device->io_width = btrfs_device_io_width(leaf, dev_item);
3498         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
3499
3500         ptr = (unsigned long)btrfs_device_uuid(dev_item);
3501         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
3502
3503         return 0;
3504 }
3505
3506 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
3507 {
3508         struct btrfs_fs_devices *fs_devices;
3509         int ret;
3510
3511         mutex_lock(&uuid_mutex);
3512
3513         fs_devices = root->fs_info->fs_devices->seed;
3514         while (fs_devices) {
3515                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
3516                         ret = 0;
3517                         goto out;
3518                 }
3519                 fs_devices = fs_devices->seed;
3520         }
3521
3522         fs_devices = find_fsid(fsid);
3523         if (!fs_devices) {
3524                 ret = -ENOENT;
3525                 goto out;
3526         }
3527
3528         fs_devices = clone_fs_devices(fs_devices);
3529         if (IS_ERR(fs_devices)) {
3530                 ret = PTR_ERR(fs_devices);
3531                 goto out;
3532         }
3533
3534         ret = __btrfs_open_devices(fs_devices, FMODE_READ,
3535                                    root->fs_info->bdev_holder);
3536         if (ret)
3537                 goto out;
3538
3539         if (!fs_devices->seeding) {
3540                 __btrfs_close_devices(fs_devices);
3541                 free_fs_devices(fs_devices);
3542                 ret = -EINVAL;
3543                 goto out;
3544         }
3545
3546         fs_devices->seed = root->fs_info->fs_devices->seed;
3547         root->fs_info->fs_devices->seed = fs_devices;
3548 out:
3549         mutex_unlock(&uuid_mutex);
3550         return ret;
3551 }
3552
3553 static int read_one_dev(struct btrfs_root *root,
3554                         struct extent_buffer *leaf,
3555                         struct btrfs_dev_item *dev_item)
3556 {
3557         struct btrfs_device *device;
3558         u64 devid;
3559         int ret;
3560         u8 fs_uuid[BTRFS_UUID_SIZE];
3561         u8 dev_uuid[BTRFS_UUID_SIZE];
3562
3563         devid = btrfs_device_id(leaf, dev_item);
3564         read_extent_buffer(leaf, dev_uuid,
3565                            (unsigned long)btrfs_device_uuid(dev_item),
3566                            BTRFS_UUID_SIZE);
3567         read_extent_buffer(leaf, fs_uuid,
3568                            (unsigned long)btrfs_device_fsid(dev_item),
3569                            BTRFS_UUID_SIZE);
3570
3571         if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
3572                 ret = open_seed_devices(root, fs_uuid);
3573                 if (ret && !btrfs_test_opt(root, DEGRADED))
3574                         return ret;
3575         }
3576
3577         device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
3578         if (!device || !device->bdev) {
3579                 if (!btrfs_test_opt(root, DEGRADED))
3580                         return -EIO;
3581
3582                 if (!device) {
3583                         printk(KERN_WARNING "warning devid %llu missing\n",
3584                                (unsigned long long)devid);
3585                         device = add_missing_dev(root, devid, dev_uuid);
3586                         if (!device)
3587                                 return -ENOMEM;
3588                 } else if (!device->missing) {
3589                         /*
3590                          * this happens when a device that was properly setup
3591                          * in the device info lists suddenly goes bad.
3592                          * device->bdev is NULL, and so we have to set
3593                          * device->missing to one here
3594                          */
3595                         root->fs_info->fs_devices->missing_devices++;
3596                         device->missing = 1;
3597                 }
3598         }
3599
3600         if (device->fs_devices != root->fs_info->fs_devices) {
3601                 BUG_ON(device->writeable);
3602                 if (device->generation !=
3603                     btrfs_device_generation(leaf, dev_item))
3604                         return -EINVAL;
3605         }
3606
3607         fill_device_from_item(leaf, dev_item, device);
3608         device->dev_root = root->fs_info->dev_root;
3609         device->in_fs_metadata = 1;
3610         if (device->writeable)
3611                 device->fs_devices->total_rw_bytes += device->total_bytes;
3612         ret = 0;
3613         return ret;
3614 }
3615
3616 int btrfs_read_sys_array(struct btrfs_root *root)
3617 {
3618         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
3619         struct extent_buffer *sb;
3620         struct btrfs_disk_key *disk_key;
3621         struct btrfs_chunk *chunk;
3622         u8 *ptr;
3623         unsigned long sb_ptr;
3624         int ret = 0;
3625         u32 num_stripes;
3626         u32 array_size;
3627         u32 len = 0;
3628         u32 cur;
3629         struct btrfs_key key;
3630
3631         sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
3632                                           BTRFS_SUPER_INFO_SIZE);
3633         if (!sb)
3634                 return -ENOMEM;
3635         btrfs_set_buffer_uptodate(sb);
3636         btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
3637
3638         write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
3639         array_size = btrfs_super_sys_array_size(super_copy);
3640
3641         ptr = super_copy->sys_chunk_array;
3642         sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
3643         cur = 0;
3644
3645         while (cur < array_size) {
3646                 disk_key = (struct btrfs_disk_key *)ptr;
3647                 btrfs_disk_key_to_cpu(&key, disk_key);
3648
3649                 len = sizeof(*disk_key); ptr += len;
3650                 sb_ptr += len;
3651                 cur += len;
3652
3653                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3654                         chunk = (struct btrfs_chunk *)sb_ptr;
3655                         ret = read_one_chunk(root, &key, sb, chunk);
3656                         if (ret)
3657                                 break;
3658                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
3659                         len = btrfs_chunk_item_size(num_stripes);
3660                 } else {
3661                         ret = -EIO;
3662                         break;
3663                 }
3664                 ptr += len;
3665                 sb_ptr += len;
3666                 cur += len;
3667         }
3668         free_extent_buffer(sb);
3669         return ret;
3670 }
3671
3672 int btrfs_read_chunk_tree(struct btrfs_root *root)
3673 {
3674         struct btrfs_path *path;
3675         struct extent_buffer *leaf;
3676         struct btrfs_key key;
3677         struct btrfs_key found_key;
3678         int ret;
3679         int slot;
3680
3681         root = root->fs_info->chunk_root;
3682
3683         path = btrfs_alloc_path();
3684         if (!path)
3685                 return -ENOMEM;
3686
3687         /* first we search for all of the device items, and then we
3688          * read in all of the chunk items.  This way we can create chunk
3689          * mappings that reference all of the devices that are afound
3690          */
3691         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
3692         key.offset = 0;
3693         key.type = 0;
3694 again:
3695         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3696         if (ret < 0)
3697                 goto error;
3698         while (1) {
3699                 leaf = path->nodes[0];
3700                 slot = path->slots[0];
3701                 if (slot >= btrfs_header_nritems(leaf)) {
3702                         ret = btrfs_next_leaf(root, path);
3703                         if (ret == 0)
3704                                 continue;
3705                         if (ret < 0)
3706                                 goto error;
3707                         break;
3708                 }
3709                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3710                 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
3711                         if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
3712                                 break;
3713                         if (found_key.type == BTRFS_DEV_ITEM_KEY) {
3714                                 struct btrfs_dev_item *dev_item;
3715                                 dev_item = btrfs_item_ptr(leaf, slot,
3716                                                   struct btrfs_dev_item);
3717                                 ret = read_one_dev(root, leaf, dev_item);
3718                                 if (ret)
3719                                         goto error;
3720                         }
3721                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
3722                         struct btrfs_chunk *chunk;
3723                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3724                         ret = read_one_chunk(root, &found_key, leaf, chunk);
3725                         if (ret)
3726                                 goto error;
3727                 }
3728                 path->slots[0]++;
3729         }
3730         if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
3731                 key.objectid = 0;
3732                 btrfs_release_path(path);
3733                 goto again;
3734         }
3735         ret = 0;
3736 error:
3737         btrfs_free_path(path);
3738         return ret;
3739 }