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