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