Btrfs: Add a missing return pointer check
[safe/jmp/linux-2.6] / fs / btrfs / volumes.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18 #include <linux/sched.h>
19 #include <linux/bio.h>
20 #include <linux/buffer_head.h>
21 #include <linux/blkdev.h>
22 #include <linux/random.h>
23 #include <asm/div64.h>
24 #include "ctree.h"
25 #include "extent_map.h"
26 #include "disk-io.h"
27 #include "transaction.h"
28 #include "print-tree.h"
29 #include "volumes.h"
30 #include "async-thread.h"
31
32 struct map_lookup {
33         u64 type;
34         int io_align;
35         int io_width;
36         int stripe_len;
37         int sector_size;
38         int num_stripes;
39         int sub_stripes;
40         struct btrfs_bio_stripe stripes[];
41 };
42
43 static int init_first_rw_device(struct btrfs_trans_handle *trans,
44                                 struct btrfs_root *root,
45                                 struct btrfs_device *device);
46 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
47
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 int btrfs_cleanup_fs_uuids(void)
76 {
77         struct btrfs_fs_devices *fs_devices;
78         struct btrfs_device *dev;
79
80         while (!list_empty(&fs_uuids)) {
81                 fs_devices = list_entry(fs_uuids.next,
82                                         struct btrfs_fs_devices, list);
83                 list_del(&fs_devices->list);
84                 while(!list_empty(&fs_devices->devices)) {
85                         dev = list_entry(fs_devices->devices.next,
86                                          struct btrfs_device, dev_list);
87                         if (dev->bdev) {
88                                 close_bdev_excl(dev->bdev);
89                                 fs_devices->open_devices--;
90                         }
91                         fs_devices->num_devices--;
92                         if (dev->writeable)
93                                 fs_devices->rw_devices--;
94                         list_del(&dev->dev_list);
95                         list_del(&dev->dev_alloc_list);
96                         kfree(dev->name);
97                         kfree(dev);
98                 }
99                 WARN_ON(fs_devices->num_devices);
100                 WARN_ON(fs_devices->open_devices);
101                 WARN_ON(fs_devices->rw_devices);
102                 kfree(fs_devices);
103         }
104         return 0;
105 }
106
107 static noinline struct btrfs_device *__find_device(struct list_head *head,
108                                                    u64 devid, u8 *uuid)
109 {
110         struct btrfs_device *dev;
111         struct list_head *cur;
112
113         list_for_each(cur, head) {
114                 dev = list_entry(cur, struct btrfs_device, dev_list);
115                 if (dev->devid == devid &&
116                     (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
117                         return dev;
118                 }
119         }
120         return NULL;
121 }
122
123 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
124 {
125         struct list_head *cur;
126         struct btrfs_fs_devices *fs_devices;
127
128         list_for_each(cur, &fs_uuids) {
129                 fs_devices = list_entry(cur, struct btrfs_fs_devices, list);
130                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
131                         return fs_devices;
132         }
133         return NULL;
134 }
135
136 /*
137  * we try to collect pending bios for a device so we don't get a large
138  * number of procs sending bios down to the same device.  This greatly
139  * improves the schedulers ability to collect and merge the bios.
140  *
141  * But, it also turns into a long list of bios to process and that is sure
142  * to eventually make the worker thread block.  The solution here is to
143  * make some progress and then put this work struct back at the end of
144  * the list if the block device is congested.  This way, multiple devices
145  * can make progress from a single worker thread.
146  */
147 static int noinline run_scheduled_bios(struct btrfs_device *device)
148 {
149         struct bio *pending;
150         struct backing_dev_info *bdi;
151         struct btrfs_fs_info *fs_info;
152         struct bio *tail;
153         struct bio *cur;
154         int again = 0;
155         unsigned long num_run = 0;
156         unsigned long limit;
157
158         bdi = device->bdev->bd_inode->i_mapping->backing_dev_info;
159         fs_info = device->dev_root->fs_info;
160         limit = btrfs_async_submit_limit(fs_info);
161         limit = limit * 2 / 3;
162
163 loop:
164         spin_lock(&device->io_lock);
165
166         /* take all the bios off the list at once and process them
167          * later on (without the lock held).  But, remember the
168          * tail and other pointers so the bios can be properly reinserted
169          * into the list if we hit congestion
170          */
171         pending = device->pending_bios;
172         tail = device->pending_bio_tail;
173         WARN_ON(pending && !tail);
174         device->pending_bios = NULL;
175         device->pending_bio_tail = NULL;
176
177         /*
178          * if pending was null this time around, no bios need processing
179          * at all and we can stop.  Otherwise it'll loop back up again
180          * and do an additional check so no bios are missed.
181          *
182          * device->running_pending is used to synchronize with the
183          * schedule_bio code.
184          */
185         if (pending) {
186                 again = 1;
187                 device->running_pending = 1;
188         } else {
189                 again = 0;
190                 device->running_pending = 0;
191         }
192         spin_unlock(&device->io_lock);
193
194         while(pending) {
195                 cur = pending;
196                 pending = pending->bi_next;
197                 cur->bi_next = NULL;
198                 atomic_dec(&fs_info->nr_async_bios);
199
200                 if (atomic_read(&fs_info->nr_async_bios) < limit &&
201                     waitqueue_active(&fs_info->async_submit_wait))
202                         wake_up(&fs_info->async_submit_wait);
203
204                 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
205                 bio_get(cur);
206                 submit_bio(cur->bi_rw, cur);
207                 bio_put(cur);
208                 num_run++;
209
210                 /*
211                  * we made progress, there is more work to do and the bdi
212                  * is now congested.  Back off and let other work structs
213                  * run instead
214                  */
215                 if (pending && bdi_write_congested(bdi) &&
216                     fs_info->fs_devices->open_devices > 1) {
217                         struct bio *old_head;
218
219                         spin_lock(&device->io_lock);
220
221                         old_head = device->pending_bios;
222                         device->pending_bios = pending;
223                         if (device->pending_bio_tail)
224                                 tail->bi_next = old_head;
225                         else
226                                 device->pending_bio_tail = tail;
227
228                         spin_unlock(&device->io_lock);
229                         btrfs_requeue_work(&device->work);
230                         goto done;
231                 }
232         }
233         if (again)
234                 goto loop;
235 done:
236         return 0;
237 }
238
239 void pending_bios_fn(struct btrfs_work *work)
240 {
241         struct btrfs_device *device;
242
243         device = container_of(work, struct btrfs_device, work);
244         run_scheduled_bios(device);
245 }
246
247 static noinline int device_list_add(const char *path,
248                            struct btrfs_super_block *disk_super,
249                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
250 {
251         struct btrfs_device *device;
252         struct btrfs_fs_devices *fs_devices;
253         u64 found_transid = btrfs_super_generation(disk_super);
254
255         fs_devices = find_fsid(disk_super->fsid);
256         if (!fs_devices) {
257                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
258                 if (!fs_devices)
259                         return -ENOMEM;
260                 INIT_LIST_HEAD(&fs_devices->devices);
261                 INIT_LIST_HEAD(&fs_devices->alloc_list);
262                 list_add(&fs_devices->list, &fs_uuids);
263                 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
264                 fs_devices->latest_devid = devid;
265                 fs_devices->latest_trans = found_transid;
266                 device = NULL;
267         } else {
268                 device = __find_device(&fs_devices->devices, devid,
269                                        disk_super->dev_item.uuid);
270         }
271         if (!device) {
272                 if (fs_devices->opened)
273                         return -EBUSY;
274
275                 device = kzalloc(sizeof(*device), GFP_NOFS);
276                 if (!device) {
277                         /* we can safely leave the fs_devices entry around */
278                         return -ENOMEM;
279                 }
280                 device->devid = devid;
281                 device->work.func = pending_bios_fn;
282                 memcpy(device->uuid, disk_super->dev_item.uuid,
283                        BTRFS_UUID_SIZE);
284                 device->barriers = 1;
285                 spin_lock_init(&device->io_lock);
286                 device->name = kstrdup(path, GFP_NOFS);
287                 if (!device->name) {
288                         kfree(device);
289                         return -ENOMEM;
290                 }
291                 INIT_LIST_HEAD(&device->dev_alloc_list);
292                 list_add(&device->dev_list, &fs_devices->devices);
293                 device->fs_devices = fs_devices;
294                 fs_devices->num_devices++;
295         }
296
297         if (found_transid > fs_devices->latest_trans) {
298                 fs_devices->latest_devid = devid;
299                 fs_devices->latest_trans = found_transid;
300         }
301         *fs_devices_ret = fs_devices;
302         return 0;
303 }
304
305 int btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
306 {
307         struct list_head *tmp;
308         struct list_head *cur;
309         struct btrfs_device *device;
310         int seed_devices = 0;
311
312         mutex_lock(&uuid_mutex);
313 again:
314         list_for_each_safe(cur, tmp, &fs_devices->devices) {
315                 device = list_entry(cur, struct btrfs_device, dev_list);
316                 if (device->in_fs_metadata)
317                         continue;
318
319                 if (device->bdev) {
320                         close_bdev_excl(device->bdev);
321                         device->bdev = NULL;
322                         fs_devices->open_devices--;
323                 }
324                 if (device->writeable) {
325                         list_del_init(&device->dev_alloc_list);
326                         device->writeable = 0;
327                         fs_devices->rw_devices--;
328                 }
329                 if (!seed_devices) {
330                         list_del_init(&device->dev_list);
331                         fs_devices->num_devices--;
332                         kfree(device->name);
333                         kfree(device);
334                 }
335         }
336
337         if (fs_devices->seed) {
338                 fs_devices = fs_devices->seed;
339                 seed_devices = 1;
340                 goto again;
341         }
342
343         mutex_unlock(&uuid_mutex);
344         return 0;
345 }
346
347 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
348 {
349         struct btrfs_fs_devices *seed_devices;
350         struct list_head *cur;
351         struct btrfs_device *device;
352 again:
353         if (--fs_devices->opened > 0)
354                 return 0;
355
356         list_for_each(cur, &fs_devices->devices) {
357                 device = list_entry(cur, struct btrfs_device, dev_list);
358                 if (device->bdev) {
359                         close_bdev_excl(device->bdev);
360                         fs_devices->open_devices--;
361                 }
362                 if (device->writeable) {
363                         list_del_init(&device->dev_alloc_list);
364                         fs_devices->rw_devices--;
365                 }
366
367                 device->bdev = NULL;
368                 device->writeable = 0;
369                 device->in_fs_metadata = 0;
370         }
371         fs_devices->opened = 0;
372         fs_devices->seeding = 0;
373         fs_devices->sprouted = 0;
374
375         seed_devices = fs_devices->seed;
376         fs_devices->seed = NULL;
377         if (seed_devices) {
378                 fs_devices = seed_devices;
379                 goto again;
380         }
381         return 0;
382 }
383
384 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
385 {
386         int ret;
387
388         mutex_lock(&uuid_mutex);
389         ret = __btrfs_close_devices(fs_devices);
390         mutex_unlock(&uuid_mutex);
391         return ret;
392 }
393
394 int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices, void *holder)
395 {
396         struct block_device *bdev;
397         struct list_head *head = &fs_devices->devices;
398         struct list_head *cur;
399         struct btrfs_device *device;
400         struct block_device *latest_bdev = NULL;
401         struct buffer_head *bh;
402         struct btrfs_super_block *disk_super;
403         u64 latest_devid = 0;
404         u64 latest_transid = 0;
405         u64 devid;
406         int seeding = 1;
407         int ret = 0;
408
409         list_for_each(cur, head) {
410                 device = list_entry(cur, struct btrfs_device, dev_list);
411                 if (device->bdev)
412                         continue;
413                 if (!device->name)
414                         continue;
415
416                 bdev = open_bdev_excl(device->name, MS_RDONLY, holder);
417                 if (IS_ERR(bdev)) {
418                         printk("open %s failed\n", device->name);
419                         goto error;
420                 }
421                 set_blocksize(bdev, 4096);
422
423                 bh = __bread(bdev, BTRFS_SUPER_INFO_OFFSET / 4096, 4096);
424                 if (!bh)
425                         goto error_close;
426
427                 disk_super = (struct btrfs_super_block *)bh->b_data;
428                 if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
429                     sizeof(disk_super->magic)))
430                         goto error_brelse;
431
432                 devid = le64_to_cpu(disk_super->dev_item.devid);
433                 if (devid != device->devid)
434                         goto error_brelse;
435
436                 if (memcmp(device->uuid, disk_super->dev_item.uuid,
437                            BTRFS_UUID_SIZE))
438                         goto error_brelse;
439
440                 device->generation = btrfs_super_generation(disk_super);
441                 if (!latest_transid || device->generation > latest_transid) {
442                         latest_devid = devid;
443                         latest_transid = device->generation;
444                         latest_bdev = bdev;
445                 }
446
447                 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
448                         device->writeable = 0;
449                 } else {
450                         device->writeable = !bdev_read_only(bdev);
451                         seeding = 0;
452                 }
453
454                 device->bdev = bdev;
455                 device->in_fs_metadata = 0;
456                 fs_devices->open_devices++;
457                 if (device->writeable) {
458                         fs_devices->rw_devices++;
459                         list_add(&device->dev_alloc_list,
460                                  &fs_devices->alloc_list);
461                 }
462                 continue;
463
464 error_brelse:
465                 brelse(bh);
466 error_close:
467                 close_bdev_excl(bdev);
468 error:
469                 continue;
470         }
471         if (fs_devices->open_devices == 0) {
472                 ret = -EIO;
473                 goto out;
474         }
475         fs_devices->seeding = seeding;
476         fs_devices->opened = 1;
477         fs_devices->latest_bdev = latest_bdev;
478         fs_devices->latest_devid = latest_devid;
479         fs_devices->latest_trans = latest_transid;
480         fs_devices->total_rw_bytes = 0;
481 out:
482         return ret;
483 }
484
485 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
486                        int flags, void *holder)
487 {
488         int ret;
489
490         mutex_lock(&uuid_mutex);
491         if (fs_devices->opened) {
492                 if (fs_devices->sprouted) {
493                         ret = -EBUSY;
494                 } else {
495                         fs_devices->opened++;
496                         ret = 0;
497                 }
498         } else {
499                 ret = __btrfs_open_devices(fs_devices, holder);
500         }
501         mutex_unlock(&uuid_mutex);
502         return ret;
503 }
504
505 int btrfs_scan_one_device(const char *path, int flags, void *holder,
506                           struct btrfs_fs_devices **fs_devices_ret)
507 {
508         struct btrfs_super_block *disk_super;
509         struct block_device *bdev;
510         struct buffer_head *bh;
511         int ret;
512         u64 devid;
513         u64 transid;
514
515         mutex_lock(&uuid_mutex);
516
517         bdev = open_bdev_excl(path, flags, holder);
518
519         if (IS_ERR(bdev)) {
520                 ret = PTR_ERR(bdev);
521                 goto error;
522         }
523
524         ret = set_blocksize(bdev, 4096);
525         if (ret)
526                 goto error_close;
527         bh = __bread(bdev, BTRFS_SUPER_INFO_OFFSET / 4096, 4096);
528         if (!bh) {
529                 ret = -EIO;
530                 goto error_close;
531         }
532         disk_super = (struct btrfs_super_block *)bh->b_data;
533         if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
534             sizeof(disk_super->magic))) {
535                 ret = -EINVAL;
536                 goto error_brelse;
537         }
538         devid = le64_to_cpu(disk_super->dev_item.devid);
539         transid = btrfs_super_generation(disk_super);
540         if (disk_super->label[0])
541                 printk("device label %s ", disk_super->label);
542         else {
543                 /* FIXME, make a readl uuid parser */
544                 printk("device fsid %llx-%llx ",
545                        *(unsigned long long *)disk_super->fsid,
546                        *(unsigned long long *)(disk_super->fsid + 8));
547         }
548         printk("devid %Lu transid %Lu %s\n", devid, transid, path);
549         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
550
551 error_brelse:
552         brelse(bh);
553 error_close:
554         close_bdev_excl(bdev);
555 error:
556         mutex_unlock(&uuid_mutex);
557         return ret;
558 }
559
560 /*
561  * this uses a pretty simple search, the expectation is that it is
562  * called very infrequently and that a given device has a small number
563  * of extents
564  */
565 static noinline int find_free_dev_extent(struct btrfs_trans_handle *trans,
566                                          struct btrfs_device *device,
567                                          u64 num_bytes, u64 *start)
568 {
569         struct btrfs_key key;
570         struct btrfs_root *root = device->dev_root;
571         struct btrfs_dev_extent *dev_extent = NULL;
572         struct btrfs_path *path;
573         u64 hole_size = 0;
574         u64 last_byte = 0;
575         u64 search_start = 0;
576         u64 search_end = device->total_bytes;
577         int ret;
578         int slot = 0;
579         int start_found;
580         struct extent_buffer *l;
581
582         path = btrfs_alloc_path();
583         if (!path)
584                 return -ENOMEM;
585         path->reada = 2;
586         start_found = 0;
587
588         /* FIXME use last free of some kind */
589
590         /* we don't want to overwrite the superblock on the drive,
591          * so we make sure to start at an offset of at least 1MB
592          */
593         search_start = max((u64)1024 * 1024, search_start);
594
595         if (root->fs_info->alloc_start + num_bytes <= device->total_bytes)
596                 search_start = max(root->fs_info->alloc_start, search_start);
597
598         key.objectid = device->devid;
599         key.offset = search_start;
600         key.type = BTRFS_DEV_EXTENT_KEY;
601         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
602         if (ret < 0)
603                 goto error;
604         ret = btrfs_previous_item(root, path, 0, key.type);
605         if (ret < 0)
606                 goto error;
607         l = path->nodes[0];
608         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
609         while (1) {
610                 l = path->nodes[0];
611                 slot = path->slots[0];
612                 if (slot >= btrfs_header_nritems(l)) {
613                         ret = btrfs_next_leaf(root, path);
614                         if (ret == 0)
615                                 continue;
616                         if (ret < 0)
617                                 goto error;
618 no_more_items:
619                         if (!start_found) {
620                                 if (search_start >= search_end) {
621                                         ret = -ENOSPC;
622                                         goto error;
623                                 }
624                                 *start = search_start;
625                                 start_found = 1;
626                                 goto check_pending;
627                         }
628                         *start = last_byte > search_start ?
629                                 last_byte : search_start;
630                         if (search_end <= *start) {
631                                 ret = -ENOSPC;
632                                 goto error;
633                         }
634                         goto check_pending;
635                 }
636                 btrfs_item_key_to_cpu(l, &key, slot);
637
638                 if (key.objectid < device->devid)
639                         goto next;
640
641                 if (key.objectid > device->devid)
642                         goto no_more_items;
643
644                 if (key.offset >= search_start && key.offset > last_byte &&
645                     start_found) {
646                         if (last_byte < search_start)
647                                 last_byte = search_start;
648                         hole_size = key.offset - last_byte;
649                         if (key.offset > last_byte &&
650                             hole_size >= num_bytes) {
651                                 *start = last_byte;
652                                 goto check_pending;
653                         }
654                 }
655                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY) {
656                         goto next;
657                 }
658
659                 start_found = 1;
660                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
661                 last_byte = key.offset + btrfs_dev_extent_length(l, dev_extent);
662 next:
663                 path->slots[0]++;
664                 cond_resched();
665         }
666 check_pending:
667         /* we have to make sure we didn't find an extent that has already
668          * been allocated by the map tree or the original allocation
669          */
670         BUG_ON(*start < search_start);
671
672         if (*start + num_bytes > search_end) {
673                 ret = -ENOSPC;
674                 goto error;
675         }
676         /* check for pending inserts here */
677         ret = 0;
678
679 error:
680         btrfs_free_path(path);
681         return ret;
682 }
683
684 int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
685                           struct btrfs_device *device,
686                           u64 start)
687 {
688         int ret;
689         struct btrfs_path *path;
690         struct btrfs_root *root = device->dev_root;
691         struct btrfs_key key;
692         struct btrfs_key found_key;
693         struct extent_buffer *leaf = NULL;
694         struct btrfs_dev_extent *extent = NULL;
695
696         path = btrfs_alloc_path();
697         if (!path)
698                 return -ENOMEM;
699
700         key.objectid = device->devid;
701         key.offset = start;
702         key.type = BTRFS_DEV_EXTENT_KEY;
703
704         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
705         if (ret > 0) {
706                 ret = btrfs_previous_item(root, path, key.objectid,
707                                           BTRFS_DEV_EXTENT_KEY);
708                 BUG_ON(ret);
709                 leaf = path->nodes[0];
710                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
711                 extent = btrfs_item_ptr(leaf, path->slots[0],
712                                         struct btrfs_dev_extent);
713                 BUG_ON(found_key.offset > start || found_key.offset +
714                        btrfs_dev_extent_length(leaf, extent) < start);
715                 ret = 0;
716         } else if (ret == 0) {
717                 leaf = path->nodes[0];
718                 extent = btrfs_item_ptr(leaf, path->slots[0],
719                                         struct btrfs_dev_extent);
720         }
721         BUG_ON(ret);
722
723         if (device->bytes_used > 0)
724                 device->bytes_used -= btrfs_dev_extent_length(leaf, extent);
725         ret = btrfs_del_item(trans, root, path);
726         BUG_ON(ret);
727
728         btrfs_free_path(path);
729         return ret;
730 }
731
732 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
733                            struct btrfs_device *device,
734                            u64 chunk_tree, u64 chunk_objectid,
735                            u64 chunk_offset, u64 start, u64 num_bytes)
736 {
737         int ret;
738         struct btrfs_path *path;
739         struct btrfs_root *root = device->dev_root;
740         struct btrfs_dev_extent *extent;
741         struct extent_buffer *leaf;
742         struct btrfs_key key;
743
744         WARN_ON(!device->in_fs_metadata);
745         path = btrfs_alloc_path();
746         if (!path)
747                 return -ENOMEM;
748
749         key.objectid = device->devid;
750         key.offset = start;
751         key.type = BTRFS_DEV_EXTENT_KEY;
752         ret = btrfs_insert_empty_item(trans, root, path, &key,
753                                       sizeof(*extent));
754         BUG_ON(ret);
755
756         leaf = path->nodes[0];
757         extent = btrfs_item_ptr(leaf, path->slots[0],
758                                 struct btrfs_dev_extent);
759         btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
760         btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
761         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
762
763         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
764                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
765                     BTRFS_UUID_SIZE);
766
767         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
768         btrfs_mark_buffer_dirty(leaf);
769         btrfs_free_path(path);
770         return ret;
771 }
772
773 static noinline int find_next_chunk(struct btrfs_root *root,
774                                     u64 objectid, u64 *offset)
775 {
776         struct btrfs_path *path;
777         int ret;
778         struct btrfs_key key;
779         struct btrfs_chunk *chunk;
780         struct btrfs_key found_key;
781
782         path = btrfs_alloc_path();
783         BUG_ON(!path);
784
785         key.objectid = objectid;
786         key.offset = (u64)-1;
787         key.type = BTRFS_CHUNK_ITEM_KEY;
788
789         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
790         if (ret < 0)
791                 goto error;
792
793         BUG_ON(ret == 0);
794
795         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
796         if (ret) {
797                 *offset = 0;
798         } else {
799                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
800                                       path->slots[0]);
801                 if (found_key.objectid != objectid)
802                         *offset = 0;
803                 else {
804                         chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
805                                                struct btrfs_chunk);
806                         *offset = found_key.offset +
807                                 btrfs_chunk_length(path->nodes[0], chunk);
808                 }
809         }
810         ret = 0;
811 error:
812         btrfs_free_path(path);
813         return ret;
814 }
815
816 static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
817 {
818         int ret;
819         struct btrfs_key key;
820         struct btrfs_key found_key;
821         struct btrfs_path *path;
822
823         root = root->fs_info->chunk_root;
824
825         path = btrfs_alloc_path();
826         if (!path)
827                 return -ENOMEM;
828
829         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
830         key.type = BTRFS_DEV_ITEM_KEY;
831         key.offset = (u64)-1;
832
833         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
834         if (ret < 0)
835                 goto error;
836
837         BUG_ON(ret == 0);
838
839         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
840                                   BTRFS_DEV_ITEM_KEY);
841         if (ret) {
842                 *objectid = 1;
843         } else {
844                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
845                                       path->slots[0]);
846                 *objectid = found_key.offset + 1;
847         }
848         ret = 0;
849 error:
850         btrfs_free_path(path);
851         return ret;
852 }
853
854 /*
855  * the device information is stored in the chunk root
856  * the btrfs_device struct should be fully filled in
857  */
858 int btrfs_add_device(struct btrfs_trans_handle *trans,
859                      struct btrfs_root *root,
860                      struct btrfs_device *device)
861 {
862         int ret;
863         struct btrfs_path *path;
864         struct btrfs_dev_item *dev_item;
865         struct extent_buffer *leaf;
866         struct btrfs_key key;
867         unsigned long ptr;
868
869         root = root->fs_info->chunk_root;
870
871         path = btrfs_alloc_path();
872         if (!path)
873                 return -ENOMEM;
874
875         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
876         key.type = BTRFS_DEV_ITEM_KEY;
877         key.offset = device->devid;
878
879         ret = btrfs_insert_empty_item(trans, root, path, &key,
880                                       sizeof(*dev_item));
881         if (ret)
882                 goto out;
883
884         leaf = path->nodes[0];
885         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
886
887         btrfs_set_device_id(leaf, dev_item, device->devid);
888         btrfs_set_device_generation(leaf, dev_item, 0);
889         btrfs_set_device_type(leaf, dev_item, device->type);
890         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
891         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
892         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
893         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
894         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
895         btrfs_set_device_group(leaf, dev_item, 0);
896         btrfs_set_device_seek_speed(leaf, dev_item, 0);
897         btrfs_set_device_bandwidth(leaf, dev_item, 0);
898
899         ptr = (unsigned long)btrfs_device_uuid(dev_item);
900         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
901         ptr = (unsigned long)btrfs_device_fsid(dev_item);
902         write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
903         btrfs_mark_buffer_dirty(leaf);
904
905         ret = 0;
906 out:
907         btrfs_free_path(path);
908         return ret;
909 }
910
911 static int btrfs_rm_dev_item(struct btrfs_root *root,
912                              struct btrfs_device *device)
913 {
914         int ret;
915         struct btrfs_path *path;
916         struct btrfs_key key;
917         struct btrfs_trans_handle *trans;
918
919         root = root->fs_info->chunk_root;
920
921         path = btrfs_alloc_path();
922         if (!path)
923                 return -ENOMEM;
924
925         trans = btrfs_start_transaction(root, 1);
926         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
927         key.type = BTRFS_DEV_ITEM_KEY;
928         key.offset = device->devid;
929         lock_chunks(root);
930
931         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
932         if (ret < 0)
933                 goto out;
934
935         if (ret > 0) {
936                 ret = -ENOENT;
937                 goto out;
938         }
939
940         ret = btrfs_del_item(trans, root, path);
941         if (ret)
942                 goto out;
943 out:
944         btrfs_free_path(path);
945         unlock_chunks(root);
946         btrfs_commit_transaction(trans, root);
947         return ret;
948 }
949
950 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
951 {
952         struct btrfs_device *device;
953         struct btrfs_device *next_device;
954         struct block_device *bdev;
955         struct buffer_head *bh = NULL;
956         struct btrfs_super_block *disk_super;
957         u64 all_avail;
958         u64 devid;
959         u64 num_devices;
960         u8 *dev_uuid;
961         int ret = 0;
962
963         mutex_lock(&uuid_mutex);
964         mutex_lock(&root->fs_info->volume_mutex);
965
966         all_avail = root->fs_info->avail_data_alloc_bits |
967                 root->fs_info->avail_system_alloc_bits |
968                 root->fs_info->avail_metadata_alloc_bits;
969
970         if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
971             root->fs_info->fs_devices->rw_devices <= 4) {
972                 printk("btrfs: unable to go below four devices on raid10\n");
973                 ret = -EINVAL;
974                 goto out;
975         }
976
977         if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
978             root->fs_info->fs_devices->rw_devices <= 2) {
979                 printk("btrfs: unable to go below two devices on raid1\n");
980                 ret = -EINVAL;
981                 goto out;
982         }
983
984         if (strcmp(device_path, "missing") == 0) {
985                 struct list_head *cur;
986                 struct list_head *devices;
987                 struct btrfs_device *tmp;
988
989                 device = NULL;
990                 devices = &root->fs_info->fs_devices->devices;
991                 list_for_each(cur, devices) {
992                         tmp = list_entry(cur, struct btrfs_device, dev_list);
993                         if (tmp->in_fs_metadata && !tmp->bdev) {
994                                 device = tmp;
995                                 break;
996                         }
997                 }
998                 bdev = NULL;
999                 bh = NULL;
1000                 disk_super = NULL;
1001                 if (!device) {
1002                         printk("btrfs: no missing devices found to remove\n");
1003                         goto out;
1004                 }
1005         } else {
1006                 bdev = open_bdev_excl(device_path, MS_RDONLY,
1007                                       root->fs_info->bdev_holder);
1008                 if (IS_ERR(bdev)) {
1009                         ret = PTR_ERR(bdev);
1010                         goto out;
1011                 }
1012
1013                 set_blocksize(bdev, 4096);
1014                 bh = __bread(bdev, BTRFS_SUPER_INFO_OFFSET / 4096, 4096);
1015                 if (!bh) {
1016                         ret = -EIO;
1017                         goto error_close;
1018                 }
1019                 disk_super = (struct btrfs_super_block *)bh->b_data;
1020                 if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
1021                             sizeof(disk_super->magic))) {
1022                         ret = -ENOENT;
1023                         goto error_brelse;
1024                 }
1025                 devid = le64_to_cpu(disk_super->dev_item.devid);
1026                 dev_uuid = disk_super->dev_item.uuid;
1027                 device = btrfs_find_device(root, devid, dev_uuid,
1028                                            disk_super->fsid);
1029                 if (!device) {
1030                         ret = -ENOENT;
1031                         goto error_brelse;
1032                 }
1033         }
1034
1035         if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1036                 printk("btrfs: unable to remove the only writeable device\n");
1037                 ret = -EINVAL;
1038                 goto error_brelse;
1039         }
1040
1041         if (device->writeable) {
1042                 list_del_init(&device->dev_alloc_list);
1043                 root->fs_info->fs_devices->rw_devices--;
1044         }
1045
1046         ret = btrfs_shrink_device(device, 0);
1047         if (ret)
1048                 goto error_brelse;
1049
1050         ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1051         if (ret)
1052                 goto error_brelse;
1053
1054         device->in_fs_metadata = 0;
1055         if (device->fs_devices == root->fs_info->fs_devices) {
1056                 list_del_init(&device->dev_list);
1057                 root->fs_info->fs_devices->num_devices--;
1058                 if (device->bdev)
1059                         device->fs_devices->open_devices--;
1060         }
1061
1062         next_device = list_entry(root->fs_info->fs_devices->devices.next,
1063                                  struct btrfs_device, dev_list);
1064         if (device->bdev == root->fs_info->sb->s_bdev)
1065                 root->fs_info->sb->s_bdev = next_device->bdev;
1066         if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1067                 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1068
1069         num_devices = btrfs_super_num_devices(&root->fs_info->super_copy) - 1;
1070         btrfs_set_super_num_devices(&root->fs_info->super_copy, num_devices);
1071
1072         if (device->fs_devices != root->fs_info->fs_devices) {
1073                 BUG_ON(device->writeable);
1074                 brelse(bh);
1075                 if (bdev)
1076                         close_bdev_excl(bdev);
1077
1078                 if (device->bdev) {
1079                         close_bdev_excl(device->bdev);
1080                         device->bdev = NULL;
1081                         device->fs_devices->open_devices--;
1082                 }
1083                 if (device->fs_devices->open_devices == 0) {
1084                         struct btrfs_fs_devices *fs_devices;
1085                         fs_devices = root->fs_info->fs_devices;
1086                         while (fs_devices) {
1087                                 if (fs_devices->seed == device->fs_devices)
1088                                         break;
1089                                 fs_devices = fs_devices->seed;
1090                         }
1091                         fs_devices->seed = device->fs_devices->seed;
1092                         device->fs_devices->seed = NULL;
1093                         __btrfs_close_devices(device->fs_devices);
1094                 }
1095                 ret = 0;
1096                 goto out;
1097         }
1098
1099         /*
1100          * at this point, the device is zero sized.  We want to
1101          * remove it from the devices list and zero out the old super
1102          */
1103         if (device->writeable) {
1104                 /* make sure this device isn't detected as part of
1105                  * the FS anymore
1106                  */
1107                 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1108                 set_buffer_dirty(bh);
1109                 sync_dirty_buffer(bh);
1110         }
1111         brelse(bh);
1112
1113         if (device->bdev) {
1114                 /* one close for the device struct or super_block */
1115                 close_bdev_excl(device->bdev);
1116         }
1117         if (bdev) {
1118                 /* one close for us */
1119                 close_bdev_excl(bdev);
1120         }
1121         kfree(device->name);
1122         kfree(device);
1123         ret = 0;
1124         goto out;
1125
1126 error_brelse:
1127         brelse(bh);
1128 error_close:
1129         if (bdev)
1130                 close_bdev_excl(bdev);
1131 out:
1132         mutex_unlock(&root->fs_info->volume_mutex);
1133         mutex_unlock(&uuid_mutex);
1134         return ret;
1135 }
1136
1137 /*
1138  * does all the dirty work required for changing file system's UUID.
1139  */
1140 static int btrfs_prepare_sprout(struct btrfs_trans_handle *trans,
1141                                 struct btrfs_root *root)
1142 {
1143         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1144         struct btrfs_fs_devices *old_devices;
1145         struct btrfs_super_block *disk_super = &root->fs_info->super_copy;
1146         struct btrfs_device *device;
1147         u64 super_flags;
1148
1149         BUG_ON(!mutex_is_locked(&uuid_mutex));
1150         if (!fs_devices->seeding || fs_devices->opened != 1)
1151                 return -EINVAL;
1152
1153         old_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1154         if (!old_devices)
1155                 return -ENOMEM;
1156
1157         memcpy(old_devices, fs_devices, sizeof(*old_devices));
1158         old_devices->opened = 1;
1159         old_devices->sprouted = 1;
1160         INIT_LIST_HEAD(&old_devices->devices);
1161         INIT_LIST_HEAD(&old_devices->alloc_list);
1162         list_splice_init(&fs_devices->devices, &old_devices->devices);
1163         list_splice_init(&fs_devices->alloc_list, &old_devices->alloc_list);
1164         list_for_each_entry(device, &old_devices->devices, dev_list) {
1165                 device->fs_devices = old_devices;
1166         }
1167         list_add(&old_devices->list, &fs_uuids);
1168
1169         fs_devices->seeding = 0;
1170         fs_devices->num_devices = 0;
1171         fs_devices->open_devices = 0;
1172         fs_devices->seed = old_devices;
1173
1174         generate_random_uuid(fs_devices->fsid);
1175         memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1176         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1177         super_flags = btrfs_super_flags(disk_super) &
1178                       ~BTRFS_SUPER_FLAG_SEEDING;
1179         btrfs_set_super_flags(disk_super, super_flags);
1180
1181         return 0;
1182 }
1183
1184 /*
1185  * strore the expected generation for seed devices in device items.
1186  */
1187 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1188                                struct btrfs_root *root)
1189 {
1190         struct btrfs_path *path;
1191         struct extent_buffer *leaf;
1192         struct btrfs_dev_item *dev_item;
1193         struct btrfs_device *device;
1194         struct btrfs_key key;
1195         u8 fs_uuid[BTRFS_UUID_SIZE];
1196         u8 dev_uuid[BTRFS_UUID_SIZE];
1197         u64 devid;
1198         int ret;
1199
1200         path = btrfs_alloc_path();
1201         if (!path)
1202                 return -ENOMEM;
1203
1204         root = root->fs_info->chunk_root;
1205         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1206         key.offset = 0;
1207         key.type = BTRFS_DEV_ITEM_KEY;
1208
1209         while (1) {
1210                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1211                 if (ret < 0)
1212                         goto error;
1213
1214                 leaf = path->nodes[0];
1215 next_slot:
1216                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1217                         ret = btrfs_next_leaf(root, path);
1218                         if (ret > 0)
1219                                 break;
1220                         if (ret < 0)
1221                                 goto error;
1222                         leaf = path->nodes[0];
1223                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1224                         btrfs_release_path(root, path);
1225                         continue;
1226                 }
1227
1228                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1229                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1230                     key.type != BTRFS_DEV_ITEM_KEY)
1231                         break;
1232
1233                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1234                                           struct btrfs_dev_item);
1235                 devid = btrfs_device_id(leaf, dev_item);
1236                 read_extent_buffer(leaf, dev_uuid,
1237                                    (unsigned long)btrfs_device_uuid(dev_item),
1238                                    BTRFS_UUID_SIZE);
1239                 read_extent_buffer(leaf, fs_uuid,
1240                                    (unsigned long)btrfs_device_fsid(dev_item),
1241                                    BTRFS_UUID_SIZE);
1242                 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1243                 BUG_ON(!device);
1244
1245                 if (device->fs_devices->seeding) {
1246                         btrfs_set_device_generation(leaf, dev_item,
1247                                                     device->generation);
1248                         btrfs_mark_buffer_dirty(leaf);
1249                 }
1250
1251                 path->slots[0]++;
1252                 goto next_slot;
1253         }
1254         ret = 0;
1255 error:
1256         btrfs_free_path(path);
1257         return ret;
1258 }
1259
1260 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1261 {
1262         struct btrfs_trans_handle *trans;
1263         struct btrfs_device *device;
1264         struct block_device *bdev;
1265         struct list_head *cur;
1266         struct list_head *devices;
1267         struct super_block *sb = root->fs_info->sb;
1268         u64 total_bytes;
1269         int seeding_dev = 0;
1270         int ret = 0;
1271
1272         if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1273                 return -EINVAL;
1274
1275         bdev = open_bdev_excl(device_path, 0, root->fs_info->bdev_holder);
1276         if (!bdev) {
1277                 return -EIO;
1278         }
1279
1280         if (root->fs_info->fs_devices->seeding) {
1281                 seeding_dev = 1;
1282                 down_write(&sb->s_umount);
1283                 mutex_lock(&uuid_mutex);
1284         }
1285
1286         filemap_write_and_wait(bdev->bd_inode->i_mapping);
1287         mutex_lock(&root->fs_info->volume_mutex);
1288
1289         devices = &root->fs_info->fs_devices->devices;
1290         list_for_each(cur, devices) {
1291                 device = list_entry(cur, struct btrfs_device, dev_list);
1292                 if (device->bdev == bdev) {
1293                         ret = -EEXIST;
1294                         goto error;
1295                 }
1296         }
1297
1298         device = kzalloc(sizeof(*device), GFP_NOFS);
1299         if (!device) {
1300                 /* we can safely leave the fs_devices entry around */
1301                 ret = -ENOMEM;
1302                 goto error;
1303         }
1304
1305         device->name = kstrdup(device_path, GFP_NOFS);
1306         if (!device->name) {
1307                 kfree(device);
1308                 ret = -ENOMEM;
1309                 goto error;
1310         }
1311
1312         ret = find_next_devid(root, &device->devid);
1313         if (ret) {
1314                 kfree(device);
1315                 goto error;
1316         }
1317
1318         trans = btrfs_start_transaction(root, 1);
1319         lock_chunks(root);
1320
1321         device->barriers = 1;
1322         device->writeable = 1;
1323         device->work.func = pending_bios_fn;
1324         generate_random_uuid(device->uuid);
1325         spin_lock_init(&device->io_lock);
1326         device->generation = trans->transid;
1327         device->io_width = root->sectorsize;
1328         device->io_align = root->sectorsize;
1329         device->sector_size = root->sectorsize;
1330         device->total_bytes = i_size_read(bdev->bd_inode);
1331         device->dev_root = root->fs_info->dev_root;
1332         device->bdev = bdev;
1333         device->in_fs_metadata = 1;
1334         set_blocksize(device->bdev, 4096);
1335
1336         if (seeding_dev) {
1337                 sb->s_flags &= ~MS_RDONLY;
1338                 ret = btrfs_prepare_sprout(trans, root);
1339                 BUG_ON(ret);
1340         }
1341
1342         device->fs_devices = root->fs_info->fs_devices;
1343         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
1344         list_add(&device->dev_alloc_list,
1345                  &root->fs_info->fs_devices->alloc_list);
1346         root->fs_info->fs_devices->num_devices++;
1347         root->fs_info->fs_devices->open_devices++;
1348         root->fs_info->fs_devices->rw_devices++;
1349         root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
1350
1351         total_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
1352         btrfs_set_super_total_bytes(&root->fs_info->super_copy,
1353                                     total_bytes + device->total_bytes);
1354
1355         total_bytes = btrfs_super_num_devices(&root->fs_info->super_copy);
1356         btrfs_set_super_num_devices(&root->fs_info->super_copy,
1357                                     total_bytes + 1);
1358
1359         if (seeding_dev) {
1360                 ret = init_first_rw_device(trans, root, device);
1361                 BUG_ON(ret);
1362                 ret = btrfs_finish_sprout(trans, root);
1363                 BUG_ON(ret);
1364         } else {
1365                 ret = btrfs_add_device(trans, root, device);
1366         }
1367
1368         unlock_chunks(root);
1369         btrfs_commit_transaction(trans, root);
1370
1371         if (seeding_dev) {
1372                 mutex_unlock(&uuid_mutex);
1373                 up_write(&sb->s_umount);
1374
1375                 ret = btrfs_relocate_sys_chunks(root);
1376                 BUG_ON(ret);
1377         }
1378 out:
1379         mutex_unlock(&root->fs_info->volume_mutex);
1380         return ret;
1381 error:
1382         close_bdev_excl(bdev);
1383         if (seeding_dev) {
1384                 mutex_unlock(&uuid_mutex);
1385                 up_write(&sb->s_umount);
1386         }
1387         goto out;
1388 }
1389
1390 int noinline btrfs_update_device(struct btrfs_trans_handle *trans,
1391                                  struct btrfs_device *device)
1392 {
1393         int ret;
1394         struct btrfs_path *path;
1395         struct btrfs_root *root;
1396         struct btrfs_dev_item *dev_item;
1397         struct extent_buffer *leaf;
1398         struct btrfs_key key;
1399
1400         root = device->dev_root->fs_info->chunk_root;
1401
1402         path = btrfs_alloc_path();
1403         if (!path)
1404                 return -ENOMEM;
1405
1406         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1407         key.type = BTRFS_DEV_ITEM_KEY;
1408         key.offset = device->devid;
1409
1410         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1411         if (ret < 0)
1412                 goto out;
1413
1414         if (ret > 0) {
1415                 ret = -ENOENT;
1416                 goto out;
1417         }
1418
1419         leaf = path->nodes[0];
1420         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1421
1422         btrfs_set_device_id(leaf, dev_item, device->devid);
1423         btrfs_set_device_type(leaf, dev_item, device->type);
1424         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1425         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1426         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1427         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1428         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1429         btrfs_mark_buffer_dirty(leaf);
1430
1431 out:
1432         btrfs_free_path(path);
1433         return ret;
1434 }
1435
1436 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
1437                       struct btrfs_device *device, u64 new_size)
1438 {
1439         struct btrfs_super_block *super_copy =
1440                 &device->dev_root->fs_info->super_copy;
1441         u64 old_total = btrfs_super_total_bytes(super_copy);
1442         u64 diff = new_size - device->total_bytes;
1443
1444         if (!device->writeable)
1445                 return -EACCES;
1446         if (new_size <= device->total_bytes)
1447                 return -EINVAL;
1448
1449         btrfs_set_super_total_bytes(super_copy, old_total + diff);
1450         device->fs_devices->total_rw_bytes += diff;
1451
1452         device->total_bytes = new_size;
1453         return btrfs_update_device(trans, device);
1454 }
1455
1456 int btrfs_grow_device(struct btrfs_trans_handle *trans,
1457                       struct btrfs_device *device, u64 new_size)
1458 {
1459         int ret;
1460         lock_chunks(device->dev_root);
1461         ret = __btrfs_grow_device(trans, device, new_size);
1462         unlock_chunks(device->dev_root);
1463         return ret;
1464 }
1465
1466 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1467                             struct btrfs_root *root,
1468                             u64 chunk_tree, u64 chunk_objectid,
1469                             u64 chunk_offset)
1470 {
1471         int ret;
1472         struct btrfs_path *path;
1473         struct btrfs_key key;
1474
1475         root = root->fs_info->chunk_root;
1476         path = btrfs_alloc_path();
1477         if (!path)
1478                 return -ENOMEM;
1479
1480         key.objectid = chunk_objectid;
1481         key.offset = chunk_offset;
1482         key.type = BTRFS_CHUNK_ITEM_KEY;
1483
1484         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1485         BUG_ON(ret);
1486
1487         ret = btrfs_del_item(trans, root, path);
1488         BUG_ON(ret);
1489
1490         btrfs_free_path(path);
1491         return 0;
1492 }
1493
1494 int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
1495                         chunk_offset)
1496 {
1497         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1498         struct btrfs_disk_key *disk_key;
1499         struct btrfs_chunk *chunk;
1500         u8 *ptr;
1501         int ret = 0;
1502         u32 num_stripes;
1503         u32 array_size;
1504         u32 len = 0;
1505         u32 cur;
1506         struct btrfs_key key;
1507
1508         array_size = btrfs_super_sys_array_size(super_copy);
1509
1510         ptr = super_copy->sys_chunk_array;
1511         cur = 0;
1512
1513         while (cur < array_size) {
1514                 disk_key = (struct btrfs_disk_key *)ptr;
1515                 btrfs_disk_key_to_cpu(&key, disk_key);
1516
1517                 len = sizeof(*disk_key);
1518
1519                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1520                         chunk = (struct btrfs_chunk *)(ptr + len);
1521                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1522                         len += btrfs_chunk_item_size(num_stripes);
1523                 } else {
1524                         ret = -EIO;
1525                         break;
1526                 }
1527                 if (key.objectid == chunk_objectid &&
1528                     key.offset == chunk_offset) {
1529                         memmove(ptr, ptr + len, array_size - (cur + len));
1530                         array_size -= len;
1531                         btrfs_set_super_sys_array_size(super_copy, array_size);
1532                 } else {
1533                         ptr += len;
1534                         cur += len;
1535                 }
1536         }
1537         return ret;
1538 }
1539
1540 int btrfs_relocate_chunk(struct btrfs_root *root,
1541                          u64 chunk_tree, u64 chunk_objectid,
1542                          u64 chunk_offset)
1543 {
1544         struct extent_map_tree *em_tree;
1545         struct btrfs_root *extent_root;
1546         struct btrfs_trans_handle *trans;
1547         struct extent_map *em;
1548         struct map_lookup *map;
1549         int ret;
1550         int i;
1551
1552         printk("btrfs relocating chunk %llu\n",
1553                (unsigned long long)chunk_offset);
1554         root = root->fs_info->chunk_root;
1555         extent_root = root->fs_info->extent_root;
1556         em_tree = &root->fs_info->mapping_tree.map_tree;
1557
1558         /* step one, relocate all the extents inside this chunk */
1559         ret = btrfs_relocate_block_group(extent_root, chunk_offset);
1560         BUG_ON(ret);
1561
1562         trans = btrfs_start_transaction(root, 1);
1563         BUG_ON(!trans);
1564
1565         lock_chunks(root);
1566
1567         /*
1568          * step two, delete the device extents and the
1569          * chunk tree entries
1570          */
1571         spin_lock(&em_tree->lock);
1572         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1573         spin_unlock(&em_tree->lock);
1574
1575         BUG_ON(em->start > chunk_offset ||
1576                em->start + em->len < chunk_offset);
1577         map = (struct map_lookup *)em->bdev;
1578
1579         for (i = 0; i < map->num_stripes; i++) {
1580                 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
1581                                             map->stripes[i].physical);
1582                 BUG_ON(ret);
1583
1584                 if (map->stripes[i].dev) {
1585                         ret = btrfs_update_device(trans, map->stripes[i].dev);
1586                         BUG_ON(ret);
1587                 }
1588         }
1589         ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
1590                                chunk_offset);
1591
1592         BUG_ON(ret);
1593
1594         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
1595                 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
1596                 BUG_ON(ret);
1597         }
1598
1599         ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
1600         BUG_ON(ret);
1601
1602         spin_lock(&em_tree->lock);
1603         remove_extent_mapping(em_tree, em);
1604         spin_unlock(&em_tree->lock);
1605
1606         kfree(map);
1607         em->bdev = NULL;
1608
1609         /* once for the tree */
1610         free_extent_map(em);
1611         /* once for us */
1612         free_extent_map(em);
1613
1614         unlock_chunks(root);
1615         btrfs_end_transaction(trans, root);
1616         return 0;
1617 }
1618
1619 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
1620 {
1621         struct btrfs_root *chunk_root = root->fs_info->chunk_root;
1622         struct btrfs_path *path;
1623         struct extent_buffer *leaf;
1624         struct btrfs_chunk *chunk;
1625         struct btrfs_key key;
1626         struct btrfs_key found_key;
1627         u64 chunk_tree = chunk_root->root_key.objectid;
1628         u64 chunk_type;
1629         int ret;
1630
1631         path = btrfs_alloc_path();
1632         if (!path)
1633                 return -ENOMEM;
1634
1635         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1636         key.offset = (u64)-1;
1637         key.type = BTRFS_CHUNK_ITEM_KEY;
1638
1639         while (1) {
1640                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
1641                 if (ret < 0)
1642                         goto error;
1643                 BUG_ON(ret == 0);
1644
1645                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
1646                                           key.type);
1647                 if (ret < 0)
1648                         goto error;
1649                 if (ret > 0)
1650                         break;
1651
1652                 leaf = path->nodes[0];
1653                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1654
1655                 chunk = btrfs_item_ptr(leaf, path->slots[0],
1656                                        struct btrfs_chunk);
1657                 chunk_type = btrfs_chunk_type(leaf, chunk);
1658                 btrfs_release_path(chunk_root, path);
1659
1660                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
1661                         ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
1662                                                    found_key.objectid,
1663                                                    found_key.offset);
1664                         BUG_ON(ret);
1665                 }
1666
1667                 if (found_key.offset == 0)
1668                         break;
1669                 key.offset = found_key.offset - 1;
1670         }
1671         ret = 0;
1672 error:
1673         btrfs_free_path(path);
1674         return ret;
1675 }
1676
1677 static u64 div_factor(u64 num, int factor)
1678 {
1679         if (factor == 10)
1680                 return num;
1681         num *= factor;
1682         do_div(num, 10);
1683         return num;
1684 }
1685
1686 int btrfs_balance(struct btrfs_root *dev_root)
1687 {
1688         int ret;
1689         struct list_head *cur;
1690         struct list_head *devices = &dev_root->fs_info->fs_devices->devices;
1691         struct btrfs_device *device;
1692         u64 old_size;
1693         u64 size_to_free;
1694         struct btrfs_path *path;
1695         struct btrfs_key key;
1696         struct btrfs_chunk *chunk;
1697         struct btrfs_root *chunk_root = dev_root->fs_info->chunk_root;
1698         struct btrfs_trans_handle *trans;
1699         struct btrfs_key found_key;
1700
1701         if (dev_root->fs_info->sb->s_flags & MS_RDONLY)
1702                 return -EROFS;
1703
1704         mutex_lock(&dev_root->fs_info->volume_mutex);
1705         dev_root = dev_root->fs_info->dev_root;
1706
1707         /* step one make some room on all the devices */
1708         list_for_each(cur, devices) {
1709                 device = list_entry(cur, struct btrfs_device, 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 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 u64 noinline 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 int noinline 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         }
2405 again:
2406         if (multi_ret) {
2407                 multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
2408                                 GFP_NOFS);
2409                 if (!multi)
2410                         return -ENOMEM;
2411
2412                 atomic_set(&multi->error, 0);
2413         }
2414
2415         spin_lock(&em_tree->lock);
2416         em = lookup_extent_mapping(em_tree, logical, *length);
2417         spin_unlock(&em_tree->lock);
2418
2419         if (!em && unplug_page)
2420                 return 0;
2421
2422         if (!em) {
2423                 printk("unable to find logical %Lu len %Lu\n", logical, *length);
2424                 BUG();
2425         }
2426
2427         BUG_ON(em->start > logical || em->start + em->len < logical);
2428         map = (struct map_lookup *)em->bdev;
2429         offset = logical - em->start;
2430
2431         if (mirror_num > map->num_stripes)
2432                 mirror_num = 0;
2433
2434         /* if our multi bio struct is too small, back off and try again */
2435         if (rw & (1 << BIO_RW)) {
2436                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
2437                                  BTRFS_BLOCK_GROUP_DUP)) {
2438                         stripes_required = map->num_stripes;
2439                         max_errors = 1;
2440                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
2441                         stripes_required = map->sub_stripes;
2442                         max_errors = 1;
2443                 }
2444         }
2445         if (multi_ret && rw == WRITE &&
2446             stripes_allocated < stripes_required) {
2447                 stripes_allocated = map->num_stripes;
2448                 free_extent_map(em);
2449                 kfree(multi);
2450                 goto again;
2451         }
2452         stripe_nr = offset;
2453         /*
2454          * stripe_nr counts the total number of stripes we have to stride
2455          * to get to this block
2456          */
2457         do_div(stripe_nr, map->stripe_len);
2458
2459         stripe_offset = stripe_nr * map->stripe_len;
2460         BUG_ON(offset < stripe_offset);
2461
2462         /* stripe_offset is the offset of this block in its stripe*/
2463         stripe_offset = offset - stripe_offset;
2464
2465         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2466                          BTRFS_BLOCK_GROUP_RAID10 |
2467                          BTRFS_BLOCK_GROUP_DUP)) {
2468                 /* we limit the length of each bio to what fits in a stripe */
2469                 *length = min_t(u64, em->len - offset,
2470                               map->stripe_len - stripe_offset);
2471         } else {
2472                 *length = em->len - offset;
2473         }
2474
2475         if (!multi_ret && !unplug_page)
2476                 goto out;
2477
2478         num_stripes = 1;
2479         stripe_index = 0;
2480         if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
2481                 if (unplug_page || (rw & (1 << BIO_RW)))
2482                         num_stripes = map->num_stripes;
2483                 else if (mirror_num)
2484                         stripe_index = mirror_num - 1;
2485                 else {
2486                         stripe_index = find_live_mirror(map, 0,
2487                                             map->num_stripes,
2488                                             current->pid % map->num_stripes);
2489                 }
2490
2491         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
2492                 if (rw & (1 << BIO_RW))
2493                         num_stripes = map->num_stripes;
2494                 else if (mirror_num)
2495                         stripe_index = mirror_num - 1;
2496
2497         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
2498                 int factor = map->num_stripes / map->sub_stripes;
2499
2500                 stripe_index = do_div(stripe_nr, factor);
2501                 stripe_index *= map->sub_stripes;
2502
2503                 if (unplug_page || (rw & (1 << BIO_RW)))
2504                         num_stripes = map->sub_stripes;
2505                 else if (mirror_num)
2506                         stripe_index += mirror_num - 1;
2507                 else {
2508                         stripe_index = find_live_mirror(map, stripe_index,
2509                                               map->sub_stripes, stripe_index +
2510                                               current->pid % map->sub_stripes);
2511                 }
2512         } else {
2513                 /*
2514                  * after this do_div call, stripe_nr is the number of stripes
2515                  * on this device we have to walk to find the data, and
2516                  * stripe_index is the number of our device in the stripe array
2517                  */
2518                 stripe_index = do_div(stripe_nr, map->num_stripes);
2519         }
2520         BUG_ON(stripe_index >= map->num_stripes);
2521
2522         for (i = 0; i < num_stripes; i++) {
2523                 if (unplug_page) {
2524                         struct btrfs_device *device;
2525                         struct backing_dev_info *bdi;
2526
2527                         device = map->stripes[stripe_index].dev;
2528                         if (device->bdev) {
2529                                 bdi = blk_get_backing_dev_info(device->bdev);
2530                                 if (bdi->unplug_io_fn) {
2531                                         bdi->unplug_io_fn(bdi, unplug_page);
2532                                 }
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_unplug_page(struct btrfs_mapping_tree *map_tree,
2561                       u64 logical, struct page *page)
2562 {
2563         u64 length = PAGE_CACHE_SIZE;
2564         return __btrfs_map_block(map_tree, READ, logical, &length,
2565                                  NULL, 0, page);
2566 }
2567
2568
2569 static void end_bio_multi_stripe(struct bio *bio, int err)
2570 {
2571         struct btrfs_multi_bio *multi = bio->bi_private;
2572         int is_orig_bio = 0;
2573
2574         if (err)
2575                 atomic_inc(&multi->error);
2576
2577         if (bio == multi->orig_bio)
2578                 is_orig_bio = 1;
2579
2580         if (atomic_dec_and_test(&multi->stripes_pending)) {
2581                 if (!is_orig_bio) {
2582                         bio_put(bio);
2583                         bio = multi->orig_bio;
2584                 }
2585                 bio->bi_private = multi->private;
2586                 bio->bi_end_io = multi->end_io;
2587                 /* only send an error to the higher layers if it is
2588                  * beyond the tolerance of the multi-bio
2589                  */
2590                 if (atomic_read(&multi->error) > multi->max_errors) {
2591                         err = -EIO;
2592                 } else if (err) {
2593                         /*
2594                          * this bio is actually up to date, we didn't
2595                          * go over the max number of errors
2596                          */
2597                         set_bit(BIO_UPTODATE, &bio->bi_flags);
2598                         err = 0;
2599                 }
2600                 kfree(multi);
2601
2602                 bio_endio(bio, err);
2603         } else if (!is_orig_bio) {
2604                 bio_put(bio);
2605         }
2606 }
2607
2608 struct async_sched {
2609         struct bio *bio;
2610         int rw;
2611         struct btrfs_fs_info *info;
2612         struct btrfs_work work;
2613 };
2614
2615 /*
2616  * see run_scheduled_bios for a description of why bios are collected for
2617  * async submit.
2618  *
2619  * This will add one bio to the pending list for a device and make sure
2620  * the work struct is scheduled.
2621  */
2622 static int noinline schedule_bio(struct btrfs_root *root,
2623                                  struct btrfs_device *device,
2624                                  int rw, struct bio *bio)
2625 {
2626         int should_queue = 1;
2627
2628         /* don't bother with additional async steps for reads, right now */
2629         if (!(rw & (1 << BIO_RW))) {
2630                 bio_get(bio);
2631                 submit_bio(rw, bio);
2632                 bio_put(bio);
2633                 return 0;
2634         }
2635
2636         /*
2637          * nr_async_bios allows us to reliably return congestion to the
2638          * higher layers.  Otherwise, the async bio makes it appear we have
2639          * made progress against dirty pages when we've really just put it
2640          * on a queue for later
2641          */
2642         atomic_inc(&root->fs_info->nr_async_bios);
2643         WARN_ON(bio->bi_next);
2644         bio->bi_next = NULL;
2645         bio->bi_rw |= rw;
2646
2647         spin_lock(&device->io_lock);
2648
2649         if (device->pending_bio_tail)
2650                 device->pending_bio_tail->bi_next = bio;
2651
2652         device->pending_bio_tail = bio;
2653         if (!device->pending_bios)
2654                 device->pending_bios = bio;
2655         if (device->running_pending)
2656                 should_queue = 0;
2657
2658         spin_unlock(&device->io_lock);
2659
2660         if (should_queue)
2661                 btrfs_queue_worker(&root->fs_info->submit_workers,
2662                                    &device->work);
2663         return 0;
2664 }
2665
2666 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
2667                   int mirror_num, int async_submit)
2668 {
2669         struct btrfs_mapping_tree *map_tree;
2670         struct btrfs_device *dev;
2671         struct bio *first_bio = bio;
2672         u64 logical = (u64)bio->bi_sector << 9;
2673         u64 length = 0;
2674         u64 map_length;
2675         struct btrfs_multi_bio *multi = NULL;
2676         int ret;
2677         int dev_nr = 0;
2678         int total_devs = 1;
2679
2680         length = bio->bi_size;
2681         map_tree = &root->fs_info->mapping_tree;
2682         map_length = length;
2683
2684         ret = btrfs_map_block(map_tree, rw, logical, &map_length, &multi,
2685                               mirror_num);
2686         BUG_ON(ret);
2687
2688         total_devs = multi->num_stripes;
2689         if (map_length < length) {
2690                 printk("mapping failed logical %Lu bio len %Lu "
2691                        "len %Lu\n", logical, length, map_length);
2692                 BUG();
2693         }
2694         multi->end_io = first_bio->bi_end_io;
2695         multi->private = first_bio->bi_private;
2696         multi->orig_bio = first_bio;
2697         atomic_set(&multi->stripes_pending, multi->num_stripes);
2698
2699         while(dev_nr < total_devs) {
2700                 if (total_devs > 1) {
2701                         if (dev_nr < total_devs - 1) {
2702                                 bio = bio_clone(first_bio, GFP_NOFS);
2703                                 BUG_ON(!bio);
2704                         } else {
2705                                 bio = first_bio;
2706                         }
2707                         bio->bi_private = multi;
2708                         bio->bi_end_io = end_bio_multi_stripe;
2709                 }
2710                 bio->bi_sector = multi->stripes[dev_nr].physical >> 9;
2711                 dev = multi->stripes[dev_nr].dev;
2712                 BUG_ON(rw == WRITE && !dev->writeable);
2713                 if (dev && dev->bdev) {
2714                         bio->bi_bdev = dev->bdev;
2715                         if (async_submit)
2716                                 schedule_bio(root, dev, rw, bio);
2717                         else
2718                                 submit_bio(rw, bio);
2719                 } else {
2720                         bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
2721                         bio->bi_sector = logical >> 9;
2722                         bio_endio(bio, -EIO);
2723                 }
2724                 dev_nr++;
2725         }
2726         if (total_devs == 1)
2727                 kfree(multi);
2728         return 0;
2729 }
2730
2731 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
2732                                        u8 *uuid, u8 *fsid)
2733 {
2734         struct btrfs_device *device;
2735         struct btrfs_fs_devices *cur_devices;
2736
2737         cur_devices = root->fs_info->fs_devices;
2738         while (cur_devices) {
2739                 if (!fsid ||
2740                     !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
2741                         device = __find_device(&cur_devices->devices,
2742                                                devid, uuid);
2743                         if (device)
2744                                 return device;
2745                 }
2746                 cur_devices = cur_devices->seed;
2747         }
2748         return NULL;
2749 }
2750
2751 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
2752                                             u64 devid, u8 *dev_uuid)
2753 {
2754         struct btrfs_device *device;
2755         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2756
2757         device = kzalloc(sizeof(*device), GFP_NOFS);
2758         if (!device)
2759                 return NULL;
2760         list_add(&device->dev_list,
2761                  &fs_devices->devices);
2762         device->barriers = 1;
2763         device->dev_root = root->fs_info->dev_root;
2764         device->devid = devid;
2765         device->work.func = pending_bios_fn;
2766         fs_devices->num_devices++;
2767         spin_lock_init(&device->io_lock);
2768         memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
2769         return device;
2770 }
2771
2772 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
2773                           struct extent_buffer *leaf,
2774                           struct btrfs_chunk *chunk)
2775 {
2776         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
2777         struct map_lookup *map;
2778         struct extent_map *em;
2779         u64 logical;
2780         u64 length;
2781         u64 devid;
2782         u8 uuid[BTRFS_UUID_SIZE];
2783         int num_stripes;
2784         int ret;
2785         int i;
2786
2787         logical = key->offset;
2788         length = btrfs_chunk_length(leaf, chunk);
2789
2790         spin_lock(&map_tree->map_tree.lock);
2791         em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
2792         spin_unlock(&map_tree->map_tree.lock);
2793
2794         /* already mapped? */
2795         if (em && em->start <= logical && em->start + em->len > logical) {
2796                 free_extent_map(em);
2797                 return 0;
2798         } else if (em) {
2799                 free_extent_map(em);
2800         }
2801
2802         map = kzalloc(sizeof(*map), GFP_NOFS);
2803         if (!map)
2804                 return -ENOMEM;
2805
2806         em = alloc_extent_map(GFP_NOFS);
2807         if (!em)
2808                 return -ENOMEM;
2809         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2810         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
2811         if (!map) {
2812                 free_extent_map(em);
2813                 return -ENOMEM;
2814         }
2815
2816         em->bdev = (struct block_device *)map;
2817         em->start = logical;
2818         em->len = length;
2819         em->block_start = 0;
2820         em->block_len = em->len;
2821
2822         map->num_stripes = num_stripes;
2823         map->io_width = btrfs_chunk_io_width(leaf, chunk);
2824         map->io_align = btrfs_chunk_io_align(leaf, chunk);
2825         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
2826         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
2827         map->type = btrfs_chunk_type(leaf, chunk);
2828         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
2829         for (i = 0; i < num_stripes; i++) {
2830                 map->stripes[i].physical =
2831                         btrfs_stripe_offset_nr(leaf, chunk, i);
2832                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
2833                 read_extent_buffer(leaf, uuid, (unsigned long)
2834                                    btrfs_stripe_dev_uuid_nr(chunk, i),
2835                                    BTRFS_UUID_SIZE);
2836                 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
2837                                                         NULL);
2838                 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
2839                         kfree(map);
2840                         free_extent_map(em);
2841                         return -EIO;
2842                 }
2843                 if (!map->stripes[i].dev) {
2844                         map->stripes[i].dev =
2845                                 add_missing_dev(root, devid, uuid);
2846                         if (!map->stripes[i].dev) {
2847                                 kfree(map);
2848                                 free_extent_map(em);
2849                                 return -EIO;
2850                         }
2851                 }
2852                 map->stripes[i].dev->in_fs_metadata = 1;
2853         }
2854
2855         spin_lock(&map_tree->map_tree.lock);
2856         ret = add_extent_mapping(&map_tree->map_tree, em);
2857         spin_unlock(&map_tree->map_tree.lock);
2858         BUG_ON(ret);
2859         free_extent_map(em);
2860
2861         return 0;
2862 }
2863
2864 static int fill_device_from_item(struct extent_buffer *leaf,
2865                                  struct btrfs_dev_item *dev_item,
2866                                  struct btrfs_device *device)
2867 {
2868         unsigned long ptr;
2869
2870         device->devid = btrfs_device_id(leaf, dev_item);
2871         device->total_bytes = btrfs_device_total_bytes(leaf, dev_item);
2872         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
2873         device->type = btrfs_device_type(leaf, dev_item);
2874         device->io_align = btrfs_device_io_align(leaf, dev_item);
2875         device->io_width = btrfs_device_io_width(leaf, dev_item);
2876         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
2877
2878         ptr = (unsigned long)btrfs_device_uuid(dev_item);
2879         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
2880
2881         return 0;
2882 }
2883
2884 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
2885 {
2886         struct btrfs_fs_devices *fs_devices;
2887         int ret;
2888
2889         mutex_lock(&uuid_mutex);
2890
2891         fs_devices = root->fs_info->fs_devices->seed;
2892         while (fs_devices) {
2893                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
2894                         ret = 0;
2895                         goto out;
2896                 }
2897                 fs_devices = fs_devices->seed;
2898         }
2899
2900         fs_devices = find_fsid(fsid);
2901         if (!fs_devices) {
2902                 ret = -ENOENT;
2903                 goto out;
2904         }
2905         if (fs_devices->opened) {
2906                 ret = -EBUSY;
2907                 goto out;
2908         }
2909
2910         ret = __btrfs_open_devices(fs_devices, root->fs_info->bdev_holder);
2911         if (ret)
2912                 goto out;
2913
2914         if (!fs_devices->seeding) {
2915                 __btrfs_close_devices(fs_devices);
2916                 ret = -EINVAL;
2917                 goto out;
2918         }
2919
2920         fs_devices->seed = root->fs_info->fs_devices->seed;
2921         root->fs_info->fs_devices->seed = fs_devices;
2922         fs_devices->sprouted = 1;
2923 out:
2924         mutex_unlock(&uuid_mutex);
2925         return ret;
2926 }
2927
2928 static int read_one_dev(struct btrfs_root *root,
2929                         struct extent_buffer *leaf,
2930                         struct btrfs_dev_item *dev_item)
2931 {
2932         struct btrfs_device *device;
2933         u64 devid;
2934         int ret;
2935         int seed_devices = 0;
2936         u8 fs_uuid[BTRFS_UUID_SIZE];
2937         u8 dev_uuid[BTRFS_UUID_SIZE];
2938
2939         devid = btrfs_device_id(leaf, dev_item);
2940         read_extent_buffer(leaf, dev_uuid,
2941                            (unsigned long)btrfs_device_uuid(dev_item),
2942                            BTRFS_UUID_SIZE);
2943         read_extent_buffer(leaf, fs_uuid,
2944                            (unsigned long)btrfs_device_fsid(dev_item),
2945                            BTRFS_UUID_SIZE);
2946
2947         if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
2948                 ret = open_seed_devices(root, fs_uuid);
2949                 if (ret)
2950                         return ret;
2951                 seed_devices = 1;
2952         }
2953
2954         device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
2955         if (!device || !device->bdev) {
2956                 if (!btrfs_test_opt(root, DEGRADED) || seed_devices)
2957                         return -EIO;
2958
2959                 if (!device) {
2960                         printk("warning devid %Lu missing\n", devid);
2961                         device = add_missing_dev(root, devid, dev_uuid);
2962                         if (!device)
2963                                 return -ENOMEM;
2964                 }
2965         }
2966
2967         if (device->fs_devices != root->fs_info->fs_devices) {
2968                 BUG_ON(device->writeable);
2969                 if (device->generation !=
2970                     btrfs_device_generation(leaf, dev_item))
2971                         return -EINVAL;
2972         }
2973
2974         fill_device_from_item(leaf, dev_item, device);
2975         device->dev_root = root->fs_info->dev_root;
2976         device->in_fs_metadata = 1;
2977         if (device->writeable)
2978                 device->fs_devices->total_rw_bytes += device->total_bytes;
2979         ret = 0;
2980 #if 0
2981         ret = btrfs_open_device(device);
2982         if (ret) {
2983                 kfree(device);
2984         }
2985 #endif
2986         return ret;
2987 }
2988
2989 int btrfs_read_super_device(struct btrfs_root *root, struct extent_buffer *buf)
2990 {
2991         struct btrfs_dev_item *dev_item;
2992
2993         dev_item = (struct btrfs_dev_item *)offsetof(struct btrfs_super_block,
2994                                                      dev_item);
2995         return read_one_dev(root, buf, dev_item);
2996 }
2997
2998 int btrfs_read_sys_array(struct btrfs_root *root)
2999 {
3000         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
3001         struct extent_buffer *sb;
3002         struct btrfs_disk_key *disk_key;
3003         struct btrfs_chunk *chunk;
3004         u8 *ptr;
3005         unsigned long sb_ptr;
3006         int ret = 0;
3007         u32 num_stripes;
3008         u32 array_size;
3009         u32 len = 0;
3010         u32 cur;
3011         struct btrfs_key key;
3012
3013         sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
3014                                           BTRFS_SUPER_INFO_SIZE);
3015         if (!sb)
3016                 return -ENOMEM;
3017         btrfs_set_buffer_uptodate(sb);
3018         write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
3019         array_size = btrfs_super_sys_array_size(super_copy);
3020
3021         ptr = super_copy->sys_chunk_array;
3022         sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
3023         cur = 0;
3024
3025         while (cur < array_size) {
3026                 disk_key = (struct btrfs_disk_key *)ptr;
3027                 btrfs_disk_key_to_cpu(&key, disk_key);
3028
3029                 len = sizeof(*disk_key); ptr += len;
3030                 sb_ptr += len;
3031                 cur += len;
3032
3033                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3034                         chunk = (struct btrfs_chunk *)sb_ptr;
3035                         ret = read_one_chunk(root, &key, sb, chunk);
3036                         if (ret)
3037                                 break;
3038                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
3039                         len = btrfs_chunk_item_size(num_stripes);
3040                 } else {
3041                         ret = -EIO;
3042                         break;
3043                 }
3044                 ptr += len;
3045                 sb_ptr += len;
3046                 cur += len;
3047         }
3048         free_extent_buffer(sb);
3049         return ret;
3050 }
3051
3052 int btrfs_read_chunk_tree(struct btrfs_root *root)
3053 {
3054         struct btrfs_path *path;
3055         struct extent_buffer *leaf;
3056         struct btrfs_key key;
3057         struct btrfs_key found_key;
3058         int ret;
3059         int slot;
3060
3061         root = root->fs_info->chunk_root;
3062
3063         path = btrfs_alloc_path();
3064         if (!path)
3065                 return -ENOMEM;
3066
3067         /* first we search for all of the device items, and then we
3068          * read in all of the chunk items.  This way we can create chunk
3069          * mappings that reference all of the devices that are afound
3070          */
3071         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
3072         key.offset = 0;
3073         key.type = 0;
3074 again:
3075         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3076         while(1) {
3077                 leaf = path->nodes[0];
3078                 slot = path->slots[0];
3079                 if (slot >= btrfs_header_nritems(leaf)) {
3080                         ret = btrfs_next_leaf(root, path);
3081                         if (ret == 0)
3082                                 continue;
3083                         if (ret < 0)
3084                                 goto error;
3085                         break;
3086                 }
3087                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3088                 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
3089                         if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
3090                                 break;
3091                         if (found_key.type == BTRFS_DEV_ITEM_KEY) {
3092                                 struct btrfs_dev_item *dev_item;
3093                                 dev_item = btrfs_item_ptr(leaf, slot,
3094                                                   struct btrfs_dev_item);
3095                                 ret = read_one_dev(root, leaf, dev_item);
3096                                 if (ret)
3097                                         goto error;
3098                         }
3099                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
3100                         struct btrfs_chunk *chunk;
3101                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3102                         ret = read_one_chunk(root, &found_key, leaf, chunk);
3103                         if (ret)
3104                                 goto error;
3105                 }
3106                 path->slots[0]++;
3107         }
3108         if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
3109                 key.objectid = 0;
3110                 btrfs_release_path(root, path);
3111                 goto again;
3112         }
3113         ret = 0;
3114 error:
3115         btrfs_free_path(path);
3116         return ret;
3117 }