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