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