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