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