]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - fs/btrfs/volumes.c
Btrfs: Add ordered async work queues
[linux-2.6-omap-h63xx.git] / fs / btrfs / volumes.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18 #include <linux/sched.h>
19 #include <linux/bio.h>
20 #include <linux/buffer_head.h>
21 #include <linux/blkdev.h>
22 #include <linux/random.h>
23 #include <asm/div64.h>
24 #include "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 #define map_lookup_size(n) (sizeof(struct map_lookup) + \
44                             (sizeof(struct btrfs_bio_stripe) * (n)))
45
46 static DEFINE_MUTEX(uuid_mutex);
47 static LIST_HEAD(fs_uuids);
48
49 void btrfs_lock_volumes(void)
50 {
51         mutex_lock(&uuid_mutex);
52 }
53
54 void btrfs_unlock_volumes(void)
55 {
56         mutex_unlock(&uuid_mutex);
57 }
58
59 static void lock_chunks(struct btrfs_root *root)
60 {
61         mutex_lock(&root->fs_info->chunk_mutex);
62 }
63
64 static void unlock_chunks(struct btrfs_root *root)
65 {
66         mutex_unlock(&root->fs_info->chunk_mutex);
67 }
68
69 int btrfs_cleanup_fs_uuids(void)
70 {
71         struct btrfs_fs_devices *fs_devices;
72         struct list_head *uuid_cur;
73         struct list_head *devices_cur;
74         struct btrfs_device *dev;
75
76         list_for_each(uuid_cur, &fs_uuids) {
77                 fs_devices = list_entry(uuid_cur, struct btrfs_fs_devices,
78                                         list);
79                 while(!list_empty(&fs_devices->devices)) {
80                         devices_cur = fs_devices->devices.next;
81                         dev = list_entry(devices_cur, struct btrfs_device,
82                                          dev_list);
83                         if (dev->bdev) {
84                                 close_bdev_excl(dev->bdev);
85                                 fs_devices->open_devices--;
86                         }
87                         list_del(&dev->dev_list);
88                         kfree(dev->name);
89                         kfree(dev);
90                 }
91         }
92         return 0;
93 }
94
95 static noinline struct btrfs_device *__find_device(struct list_head *head,
96                                                    u64 devid, u8 *uuid)
97 {
98         struct btrfs_device *dev;
99         struct list_head *cur;
100
101         list_for_each(cur, head) {
102                 dev = list_entry(cur, struct btrfs_device, dev_list);
103                 if (dev->devid == devid &&
104                     (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
105                         return dev;
106                 }
107         }
108         return NULL;
109 }
110
111 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
112 {
113         struct list_head *cur;
114         struct btrfs_fs_devices *fs_devices;
115
116         list_for_each(cur, &fs_uuids) {
117                 fs_devices = list_entry(cur, struct btrfs_fs_devices, list);
118                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
119                         return fs_devices;
120         }
121         return NULL;
122 }
123
124 /*
125  * we try to collect pending bios for a device so we don't get a large
126  * number of procs sending bios down to the same device.  This greatly
127  * improves the schedulers ability to collect and merge the bios.
128  *
129  * But, it also turns into a long list of bios to process and that is sure
130  * to eventually make the worker thread block.  The solution here is to
131  * make some progress and then put this work struct back at the end of
132  * the list if the block device is congested.  This way, multiple devices
133  * can make progress from a single worker thread.
134  */
135 static int noinline run_scheduled_bios(struct btrfs_device *device)
136 {
137         struct bio *pending;
138         struct backing_dev_info *bdi;
139         struct btrfs_fs_info *fs_info;
140         struct bio *tail;
141         struct bio *cur;
142         int again = 0;
143         unsigned long num_run = 0;
144         unsigned long limit;
145
146         bdi = device->bdev->bd_inode->i_mapping->backing_dev_info;
147         fs_info = device->dev_root->fs_info;
148         limit = btrfs_async_submit_limit(fs_info);
149         limit = limit * 2 / 3;
150
151 loop:
152         spin_lock(&device->io_lock);
153
154         /* take all the bios off the list at once and process them
155          * later on (without the lock held).  But, remember the
156          * tail and other pointers so the bios can be properly reinserted
157          * into the list if we hit congestion
158          */
159         pending = device->pending_bios;
160         tail = device->pending_bio_tail;
161         WARN_ON(pending && !tail);
162         device->pending_bios = NULL;
163         device->pending_bio_tail = NULL;
164
165         /*
166          * if pending was null this time around, no bios need processing
167          * at all and we can stop.  Otherwise it'll loop back up again
168          * and do an additional check so no bios are missed.
169          *
170          * device->running_pending is used to synchronize with the
171          * schedule_bio code.
172          */
173         if (pending) {
174                 again = 1;
175                 device->running_pending = 1;
176         } else {
177                 again = 0;
178                 device->running_pending = 0;
179         }
180         spin_unlock(&device->io_lock);
181
182         while(pending) {
183                 cur = pending;
184                 pending = pending->bi_next;
185                 cur->bi_next = NULL;
186                 atomic_dec(&fs_info->nr_async_bios);
187
188                 if (atomic_read(&fs_info->nr_async_bios) < limit &&
189                     waitqueue_active(&fs_info->async_submit_wait))
190                         wake_up(&fs_info->async_submit_wait);
191
192                 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
193                 bio_get(cur);
194                 submit_bio(cur->bi_rw, cur);
195                 bio_put(cur);
196                 num_run++;
197
198                 /*
199                  * we made progress, there is more work to do and the bdi
200                  * is now congested.  Back off and let other work structs
201                  * run instead
202                  */
203                 if (pending && bdi_write_congested(bdi)) {
204                         struct bio *old_head;
205
206                         spin_lock(&device->io_lock);
207
208                         old_head = device->pending_bios;
209                         device->pending_bios = pending;
210                         if (device->pending_bio_tail)
211                                 tail->bi_next = old_head;
212                         else
213                                 device->pending_bio_tail = tail;
214
215                         spin_unlock(&device->io_lock);
216                         btrfs_requeue_work(&device->work);
217                         goto done;
218                 }
219         }
220         if (again)
221                 goto loop;
222 done:
223         return 0;
224 }
225
226 void pending_bios_fn(struct btrfs_work *work)
227 {
228         struct btrfs_device *device;
229
230         device = container_of(work, struct btrfs_device, work);
231         run_scheduled_bios(device);
232 }
233
234 static noinline int device_list_add(const char *path,
235                            struct btrfs_super_block *disk_super,
236                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
237 {
238         struct btrfs_device *device;
239         struct btrfs_fs_devices *fs_devices;
240         u64 found_transid = btrfs_super_generation(disk_super);
241
242         fs_devices = find_fsid(disk_super->fsid);
243         if (!fs_devices) {
244                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
245                 if (!fs_devices)
246                         return -ENOMEM;
247                 INIT_LIST_HEAD(&fs_devices->devices);
248                 INIT_LIST_HEAD(&fs_devices->alloc_list);
249                 list_add(&fs_devices->list, &fs_uuids);
250                 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
251                 fs_devices->latest_devid = devid;
252                 fs_devices->latest_trans = found_transid;
253                 device = NULL;
254         } else {
255                 device = __find_device(&fs_devices->devices, devid,
256                                        disk_super->dev_item.uuid);
257         }
258         if (!device) {
259                 device = kzalloc(sizeof(*device), GFP_NOFS);
260                 if (!device) {
261                         /* we can safely leave the fs_devices entry around */
262                         return -ENOMEM;
263                 }
264                 device->devid = devid;
265                 device->work.func = pending_bios_fn;
266                 memcpy(device->uuid, disk_super->dev_item.uuid,
267                        BTRFS_UUID_SIZE);
268                 device->barriers = 1;
269                 spin_lock_init(&device->io_lock);
270                 device->name = kstrdup(path, GFP_NOFS);
271                 if (!device->name) {
272                         kfree(device);
273                         return -ENOMEM;
274                 }
275                 list_add(&device->dev_list, &fs_devices->devices);
276                 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
277                 fs_devices->num_devices++;
278         }
279
280         if (found_transid > fs_devices->latest_trans) {
281                 fs_devices->latest_devid = devid;
282                 fs_devices->latest_trans = found_transid;
283         }
284         *fs_devices_ret = fs_devices;
285         return 0;
286 }
287
288 int btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
289 {
290         struct list_head *head = &fs_devices->devices;
291         struct list_head *cur;
292         struct btrfs_device *device;
293
294         mutex_lock(&uuid_mutex);
295 again:
296         list_for_each(cur, head) {
297                 device = list_entry(cur, struct btrfs_device, dev_list);
298                 if (!device->in_fs_metadata) {
299                         struct block_device *bdev;
300                         list_del(&device->dev_list);
301                         list_del(&device->dev_alloc_list);
302                         fs_devices->num_devices--;
303                         if (device->bdev) {
304                                 bdev = device->bdev;
305                                 fs_devices->open_devices--;
306                                 mutex_unlock(&uuid_mutex);
307                                 close_bdev_excl(bdev);
308                                 mutex_lock(&uuid_mutex);
309                         }
310                         kfree(device->name);
311                         kfree(device);
312                         goto again;
313                 }
314         }
315         mutex_unlock(&uuid_mutex);
316         return 0;
317 }
318
319 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
320 {
321         struct list_head *head = &fs_devices->devices;
322         struct list_head *cur;
323         struct btrfs_device *device;
324
325         mutex_lock(&uuid_mutex);
326         list_for_each(cur, head) {
327                 device = list_entry(cur, struct btrfs_device, dev_list);
328                 if (device->bdev) {
329                         close_bdev_excl(device->bdev);
330                         fs_devices->open_devices--;
331                 }
332                 device->bdev = NULL;
333                 device->in_fs_metadata = 0;
334         }
335         fs_devices->mounted = 0;
336         mutex_unlock(&uuid_mutex);
337         return 0;
338 }
339
340 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
341                        int flags, void *holder)
342 {
343         struct block_device *bdev;
344         struct list_head *head = &fs_devices->devices;
345         struct list_head *cur;
346         struct btrfs_device *device;
347         struct block_device *latest_bdev = NULL;
348         struct buffer_head *bh;
349         struct btrfs_super_block *disk_super;
350         u64 latest_devid = 0;
351         u64 latest_transid = 0;
352         u64 transid;
353         u64 devid;
354         int ret = 0;
355
356         mutex_lock(&uuid_mutex);
357         if (fs_devices->mounted)
358                 goto out;
359
360         list_for_each(cur, head) {
361                 device = list_entry(cur, struct btrfs_device, dev_list);
362                 if (device->bdev)
363                         continue;
364
365                 if (!device->name)
366                         continue;
367
368                 bdev = open_bdev_excl(device->name, flags, holder);
369
370                 if (IS_ERR(bdev)) {
371                         printk("open %s failed\n", device->name);
372                         goto error;
373                 }
374                 set_blocksize(bdev, 4096);
375
376                 bh = __bread(bdev, BTRFS_SUPER_INFO_OFFSET / 4096, 4096);
377                 if (!bh)
378                         goto error_close;
379
380                 disk_super = (struct btrfs_super_block *)bh->b_data;
381                 if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
382                     sizeof(disk_super->magic)))
383                         goto error_brelse;
384
385                 devid = le64_to_cpu(disk_super->dev_item.devid);
386                 if (devid != device->devid)
387                         goto error_brelse;
388
389                 transid = btrfs_super_generation(disk_super);
390                 if (!latest_transid || transid > latest_transid) {
391                         latest_devid = devid;
392                         latest_transid = transid;
393                         latest_bdev = bdev;
394                 }
395
396                 device->bdev = bdev;
397                 device->in_fs_metadata = 0;
398                 fs_devices->open_devices++;
399                 continue;
400
401 error_brelse:
402                 brelse(bh);
403 error_close:
404                 close_bdev_excl(bdev);
405 error:
406                 continue;
407         }
408         if (fs_devices->open_devices == 0) {
409                 ret = -EIO;
410                 goto out;
411         }
412         fs_devices->mounted = 1;
413         fs_devices->latest_bdev = latest_bdev;
414         fs_devices->latest_devid = latest_devid;
415         fs_devices->latest_trans = latest_transid;
416 out:
417         mutex_unlock(&uuid_mutex);
418         return ret;
419 }
420
421 int btrfs_scan_one_device(const char *path, int flags, void *holder,
422                           struct btrfs_fs_devices **fs_devices_ret)
423 {
424         struct btrfs_super_block *disk_super;
425         struct block_device *bdev;
426         struct buffer_head *bh;
427         int ret;
428         u64 devid;
429         u64 transid;
430
431         mutex_lock(&uuid_mutex);
432
433         bdev = open_bdev_excl(path, flags, holder);
434
435         if (IS_ERR(bdev)) {
436                 ret = PTR_ERR(bdev);
437                 goto error;
438         }
439
440         ret = set_blocksize(bdev, 4096);
441         if (ret)
442                 goto error_close;
443         bh = __bread(bdev, BTRFS_SUPER_INFO_OFFSET / 4096, 4096);
444         if (!bh) {
445                 ret = -EIO;
446                 goto error_close;
447         }
448         disk_super = (struct btrfs_super_block *)bh->b_data;
449         if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
450             sizeof(disk_super->magic))) {
451                 ret = -EINVAL;
452                 goto error_brelse;
453         }
454         devid = le64_to_cpu(disk_super->dev_item.devid);
455         transid = btrfs_super_generation(disk_super);
456         if (disk_super->label[0])
457                 printk("device label %s ", disk_super->label);
458         else {
459                 /* FIXME, make a readl uuid parser */
460                 printk("device fsid %llx-%llx ",
461                        *(unsigned long long *)disk_super->fsid,
462                        *(unsigned long long *)(disk_super->fsid + 8));
463         }
464         printk("devid %Lu transid %Lu %s\n", devid, transid, path);
465         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
466
467 error_brelse:
468         brelse(bh);
469 error_close:
470         close_bdev_excl(bdev);
471 error:
472         mutex_unlock(&uuid_mutex);
473         return ret;
474 }
475
476 /*
477  * this uses a pretty simple search, the expectation is that it is
478  * called very infrequently and that a given device has a small number
479  * of extents
480  */
481 static noinline int find_free_dev_extent(struct btrfs_trans_handle *trans,
482                                          struct btrfs_device *device,
483                                          struct btrfs_path *path,
484                                          u64 num_bytes, u64 *start)
485 {
486         struct btrfs_key key;
487         struct btrfs_root *root = device->dev_root;
488         struct btrfs_dev_extent *dev_extent = NULL;
489         u64 hole_size = 0;
490         u64 last_byte = 0;
491         u64 search_start = 0;
492         u64 search_end = device->total_bytes;
493         int ret;
494         int slot = 0;
495         int start_found;
496         struct extent_buffer *l;
497
498         start_found = 0;
499         path->reada = 2;
500
501         /* FIXME use last free of some kind */
502
503         /* we don't want to overwrite the superblock on the drive,
504          * so we make sure to start at an offset of at least 1MB
505          */
506         search_start = max((u64)1024 * 1024, search_start);
507
508         if (root->fs_info->alloc_start + num_bytes <= device->total_bytes)
509                 search_start = max(root->fs_info->alloc_start, search_start);
510
511         key.objectid = device->devid;
512         key.offset = search_start;
513         key.type = BTRFS_DEV_EXTENT_KEY;
514         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
515         if (ret < 0)
516                 goto error;
517         ret = btrfs_previous_item(root, path, 0, key.type);
518         if (ret < 0)
519                 goto error;
520         l = path->nodes[0];
521         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
522         while (1) {
523                 l = path->nodes[0];
524                 slot = path->slots[0];
525                 if (slot >= btrfs_header_nritems(l)) {
526                         ret = btrfs_next_leaf(root, path);
527                         if (ret == 0)
528                                 continue;
529                         if (ret < 0)
530                                 goto error;
531 no_more_items:
532                         if (!start_found) {
533                                 if (search_start >= search_end) {
534                                         ret = -ENOSPC;
535                                         goto error;
536                                 }
537                                 *start = search_start;
538                                 start_found = 1;
539                                 goto check_pending;
540                         }
541                         *start = last_byte > search_start ?
542                                 last_byte : search_start;
543                         if (search_end <= *start) {
544                                 ret = -ENOSPC;
545                                 goto error;
546                         }
547                         goto check_pending;
548                 }
549                 btrfs_item_key_to_cpu(l, &key, slot);
550
551                 if (key.objectid < device->devid)
552                         goto next;
553
554                 if (key.objectid > device->devid)
555                         goto no_more_items;
556
557                 if (key.offset >= search_start && key.offset > last_byte &&
558                     start_found) {
559                         if (last_byte < search_start)
560                                 last_byte = search_start;
561                         hole_size = key.offset - last_byte;
562                         if (key.offset > last_byte &&
563                             hole_size >= num_bytes) {
564                                 *start = last_byte;
565                                 goto check_pending;
566                         }
567                 }
568                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY) {
569                         goto next;
570                 }
571
572                 start_found = 1;
573                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
574                 last_byte = key.offset + btrfs_dev_extent_length(l, dev_extent);
575 next:
576                 path->slots[0]++;
577                 cond_resched();
578         }
579 check_pending:
580         /* we have to make sure we didn't find an extent that has already
581          * been allocated by the map tree or the original allocation
582          */
583         btrfs_release_path(root, path);
584         BUG_ON(*start < search_start);
585
586         if (*start + num_bytes > search_end) {
587                 ret = -ENOSPC;
588                 goto error;
589         }
590         /* check for pending inserts here */
591         return 0;
592
593 error:
594         btrfs_release_path(root, path);
595         return ret;
596 }
597
598 int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
599                           struct btrfs_device *device,
600                           u64 start)
601 {
602         int ret;
603         struct btrfs_path *path;
604         struct btrfs_root *root = device->dev_root;
605         struct btrfs_key key;
606         struct btrfs_key found_key;
607         struct extent_buffer *leaf = NULL;
608         struct btrfs_dev_extent *extent = NULL;
609
610         path = btrfs_alloc_path();
611         if (!path)
612                 return -ENOMEM;
613
614         key.objectid = device->devid;
615         key.offset = start;
616         key.type = BTRFS_DEV_EXTENT_KEY;
617
618         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
619         if (ret > 0) {
620                 ret = btrfs_previous_item(root, path, key.objectid,
621                                           BTRFS_DEV_EXTENT_KEY);
622                 BUG_ON(ret);
623                 leaf = path->nodes[0];
624                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
625                 extent = btrfs_item_ptr(leaf, path->slots[0],
626                                         struct btrfs_dev_extent);
627                 BUG_ON(found_key.offset > start || found_key.offset +
628                        btrfs_dev_extent_length(leaf, extent) < start);
629                 ret = 0;
630         } else if (ret == 0) {
631                 leaf = path->nodes[0];
632                 extent = btrfs_item_ptr(leaf, path->slots[0],
633                                         struct btrfs_dev_extent);
634         }
635         BUG_ON(ret);
636
637         if (device->bytes_used > 0)
638                 device->bytes_used -= btrfs_dev_extent_length(leaf, extent);
639         ret = btrfs_del_item(trans, root, path);
640         BUG_ON(ret);
641
642         btrfs_free_path(path);
643         return ret;
644 }
645
646 int noinline btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
647                            struct btrfs_device *device,
648                            u64 chunk_tree, u64 chunk_objectid,
649                            u64 chunk_offset,
650                            u64 num_bytes, u64 *start)
651 {
652         int ret;
653         struct btrfs_path *path;
654         struct btrfs_root *root = device->dev_root;
655         struct btrfs_dev_extent *extent;
656         struct extent_buffer *leaf;
657         struct btrfs_key key;
658
659         WARN_ON(!device->in_fs_metadata);
660         path = btrfs_alloc_path();
661         if (!path)
662                 return -ENOMEM;
663
664         ret = find_free_dev_extent(trans, device, path, num_bytes, start);
665         if (ret) {
666                 goto err;
667         }
668
669         key.objectid = device->devid;
670         key.offset = *start;
671         key.type = BTRFS_DEV_EXTENT_KEY;
672         ret = btrfs_insert_empty_item(trans, root, path, &key,
673                                       sizeof(*extent));
674         BUG_ON(ret);
675
676         leaf = path->nodes[0];
677         extent = btrfs_item_ptr(leaf, path->slots[0],
678                                 struct btrfs_dev_extent);
679         btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
680         btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
681         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
682
683         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
684                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
685                     BTRFS_UUID_SIZE);
686
687         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
688         btrfs_mark_buffer_dirty(leaf);
689 err:
690         btrfs_free_path(path);
691         return ret;
692 }
693
694 static noinline int find_next_chunk(struct btrfs_root *root,
695                                     u64 objectid, u64 *offset)
696 {
697         struct btrfs_path *path;
698         int ret;
699         struct btrfs_key key;
700         struct btrfs_chunk *chunk;
701         struct btrfs_key found_key;
702
703         path = btrfs_alloc_path();
704         BUG_ON(!path);
705
706         key.objectid = objectid;
707         key.offset = (u64)-1;
708         key.type = BTRFS_CHUNK_ITEM_KEY;
709
710         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
711         if (ret < 0)
712                 goto error;
713
714         BUG_ON(ret == 0);
715
716         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
717         if (ret) {
718                 *offset = 0;
719         } else {
720                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
721                                       path->slots[0]);
722                 if (found_key.objectid != objectid)
723                         *offset = 0;
724                 else {
725                         chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
726                                                struct btrfs_chunk);
727                         *offset = found_key.offset +
728                                 btrfs_chunk_length(path->nodes[0], chunk);
729                 }
730         }
731         ret = 0;
732 error:
733         btrfs_free_path(path);
734         return ret;
735 }
736
737 static noinline int find_next_devid(struct btrfs_root *root,
738                                     struct btrfs_path *path, u64 *objectid)
739 {
740         int ret;
741         struct btrfs_key key;
742         struct btrfs_key found_key;
743
744         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
745         key.type = BTRFS_DEV_ITEM_KEY;
746         key.offset = (u64)-1;
747
748         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
749         if (ret < 0)
750                 goto error;
751
752         BUG_ON(ret == 0);
753
754         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
755                                   BTRFS_DEV_ITEM_KEY);
756         if (ret) {
757                 *objectid = 1;
758         } else {
759                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
760                                       path->slots[0]);
761                 *objectid = found_key.offset + 1;
762         }
763         ret = 0;
764 error:
765         btrfs_release_path(root, path);
766         return ret;
767 }
768
769 /*
770  * the device information is stored in the chunk root
771  * the btrfs_device struct should be fully filled in
772  */
773 int btrfs_add_device(struct btrfs_trans_handle *trans,
774                      struct btrfs_root *root,
775                      struct btrfs_device *device)
776 {
777         int ret;
778         struct btrfs_path *path;
779         struct btrfs_dev_item *dev_item;
780         struct extent_buffer *leaf;
781         struct btrfs_key key;
782         unsigned long ptr;
783         u64 free_devid = 0;
784
785         root = root->fs_info->chunk_root;
786
787         path = btrfs_alloc_path();
788         if (!path)
789                 return -ENOMEM;
790
791         ret = find_next_devid(root, path, &free_devid);
792         if (ret)
793                 goto out;
794
795         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
796         key.type = BTRFS_DEV_ITEM_KEY;
797         key.offset = free_devid;
798
799         ret = btrfs_insert_empty_item(trans, root, path, &key,
800                                       sizeof(*dev_item));
801         if (ret)
802                 goto out;
803
804         leaf = path->nodes[0];
805         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
806
807         device->devid = free_devid;
808         btrfs_set_device_id(leaf, dev_item, device->devid);
809         btrfs_set_device_type(leaf, dev_item, device->type);
810         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
811         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
812         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
813         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
814         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
815         btrfs_set_device_group(leaf, dev_item, 0);
816         btrfs_set_device_seek_speed(leaf, dev_item, 0);
817         btrfs_set_device_bandwidth(leaf, dev_item, 0);
818
819         ptr = (unsigned long)btrfs_device_uuid(dev_item);
820         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
821         btrfs_mark_buffer_dirty(leaf);
822         ret = 0;
823
824 out:
825         btrfs_free_path(path);
826         return ret;
827 }
828
829 static int btrfs_rm_dev_item(struct btrfs_root *root,
830                              struct btrfs_device *device)
831 {
832         int ret;
833         struct btrfs_path *path;
834         struct block_device *bdev = device->bdev;
835         struct btrfs_device *next_dev;
836         struct btrfs_key key;
837         u64 total_bytes;
838         struct btrfs_fs_devices *fs_devices;
839         struct btrfs_trans_handle *trans;
840
841         root = root->fs_info->chunk_root;
842
843         path = btrfs_alloc_path();
844         if (!path)
845                 return -ENOMEM;
846
847         trans = btrfs_start_transaction(root, 1);
848         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
849         key.type = BTRFS_DEV_ITEM_KEY;
850         key.offset = device->devid;
851         lock_chunks(root);
852
853         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
854         if (ret < 0)
855                 goto out;
856
857         if (ret > 0) {
858                 ret = -ENOENT;
859                 goto out;
860         }
861
862         ret = btrfs_del_item(trans, root, path);
863         if (ret)
864                 goto out;
865
866         /*
867          * at this point, the device is zero sized.  We want to
868          * remove it from the devices list and zero out the old super
869          */
870         list_del_init(&device->dev_list);
871         list_del_init(&device->dev_alloc_list);
872         fs_devices = root->fs_info->fs_devices;
873
874         next_dev = list_entry(fs_devices->devices.next, struct btrfs_device,
875                               dev_list);
876         if (bdev == root->fs_info->sb->s_bdev)
877                 root->fs_info->sb->s_bdev = next_dev->bdev;
878         if (bdev == fs_devices->latest_bdev)
879                 fs_devices->latest_bdev = next_dev->bdev;
880
881         total_bytes = btrfs_super_num_devices(&root->fs_info->super_copy);
882         btrfs_set_super_num_devices(&root->fs_info->super_copy,
883                                     total_bytes - 1);
884 out:
885         btrfs_free_path(path);
886         unlock_chunks(root);
887         btrfs_commit_transaction(trans, root);
888         return ret;
889 }
890
891 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
892 {
893         struct btrfs_device *device;
894         struct block_device *bdev;
895         struct buffer_head *bh = NULL;
896         struct btrfs_super_block *disk_super;
897         u64 all_avail;
898         u64 devid;
899         int ret = 0;
900
901         mutex_lock(&uuid_mutex);
902         mutex_lock(&root->fs_info->volume_mutex);
903
904         all_avail = root->fs_info->avail_data_alloc_bits |
905                 root->fs_info->avail_system_alloc_bits |
906                 root->fs_info->avail_metadata_alloc_bits;
907
908         if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
909             btrfs_super_num_devices(&root->fs_info->super_copy) <= 4) {
910                 printk("btrfs: unable to go below four devices on raid10\n");
911                 ret = -EINVAL;
912                 goto out;
913         }
914
915         if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
916             btrfs_super_num_devices(&root->fs_info->super_copy) <= 2) {
917                 printk("btrfs: unable to go below two devices on raid1\n");
918                 ret = -EINVAL;
919                 goto out;
920         }
921
922         if (strcmp(device_path, "missing") == 0) {
923                 struct list_head *cur;
924                 struct list_head *devices;
925                 struct btrfs_device *tmp;
926
927                 device = NULL;
928                 devices = &root->fs_info->fs_devices->devices;
929                 list_for_each(cur, devices) {
930                         tmp = list_entry(cur, struct btrfs_device, dev_list);
931                         if (tmp->in_fs_metadata && !tmp->bdev) {
932                                 device = tmp;
933                                 break;
934                         }
935                 }
936                 bdev = NULL;
937                 bh = NULL;
938                 disk_super = NULL;
939                 if (!device) {
940                         printk("btrfs: no missing devices found to remove\n");
941                         goto out;
942                 }
943
944         } else {
945                 bdev = open_bdev_excl(device_path, 0,
946                                       root->fs_info->bdev_holder);
947                 if (IS_ERR(bdev)) {
948                         ret = PTR_ERR(bdev);
949                         goto out;
950                 }
951
952                 bh = __bread(bdev, BTRFS_SUPER_INFO_OFFSET / 4096, 4096);
953                 if (!bh) {
954                         ret = -EIO;
955                         goto error_close;
956                 }
957                 disk_super = (struct btrfs_super_block *)bh->b_data;
958                 if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
959                     sizeof(disk_super->magic))) {
960                         ret = -ENOENT;
961                         goto error_brelse;
962                 }
963                 if (memcmp(disk_super->fsid, root->fs_info->fsid,
964                            BTRFS_FSID_SIZE)) {
965                         ret = -ENOENT;
966                         goto error_brelse;
967                 }
968                 devid = le64_to_cpu(disk_super->dev_item.devid);
969                 device = btrfs_find_device(root, devid, NULL);
970                 if (!device) {
971                         ret = -ENOENT;
972                         goto error_brelse;
973                 }
974
975         }
976         root->fs_info->fs_devices->num_devices--;
977         root->fs_info->fs_devices->open_devices--;
978
979         ret = btrfs_shrink_device(device, 0);
980         if (ret)
981                 goto error_brelse;
982
983
984         ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
985         if (ret)
986                 goto error_brelse;
987
988         if (bh) {
989                 /* make sure this device isn't detected as part of
990                  * the FS anymore
991                  */
992                 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
993                 set_buffer_dirty(bh);
994                 sync_dirty_buffer(bh);
995
996                 brelse(bh);
997         }
998
999         if (device->bdev) {
1000                 /* one close for the device struct or super_block */
1001                 close_bdev_excl(device->bdev);
1002         }
1003         if (bdev) {
1004                 /* one close for us */
1005                 close_bdev_excl(bdev);
1006         }
1007         kfree(device->name);
1008         kfree(device);
1009         ret = 0;
1010         goto out;
1011
1012 error_brelse:
1013         brelse(bh);
1014 error_close:
1015         if (bdev)
1016                 close_bdev_excl(bdev);
1017 out:
1018         mutex_unlock(&root->fs_info->volume_mutex);
1019         mutex_unlock(&uuid_mutex);
1020         return ret;
1021 }
1022
1023 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1024 {
1025         struct btrfs_trans_handle *trans;
1026         struct btrfs_device *device;
1027         struct block_device *bdev;
1028         struct list_head *cur;
1029         struct list_head *devices;
1030         u64 total_bytes;
1031         int ret = 0;
1032
1033
1034         bdev = open_bdev_excl(device_path, 0, root->fs_info->bdev_holder);
1035         if (!bdev) {
1036                 return -EIO;
1037         }
1038
1039         filemap_write_and_wait(bdev->bd_inode->i_mapping);
1040         mutex_lock(&root->fs_info->volume_mutex);
1041
1042         trans = btrfs_start_transaction(root, 1);
1043         lock_chunks(root);
1044         devices = &root->fs_info->fs_devices->devices;
1045         list_for_each(cur, devices) {
1046                 device = list_entry(cur, struct btrfs_device, dev_list);
1047                 if (device->bdev == bdev) {
1048                         ret = -EEXIST;
1049                         goto out;
1050                 }
1051         }
1052
1053         device = kzalloc(sizeof(*device), GFP_NOFS);
1054         if (!device) {
1055                 /* we can safely leave the fs_devices entry around */
1056                 ret = -ENOMEM;
1057                 goto out_close_bdev;
1058         }
1059
1060         device->barriers = 1;
1061         device->work.func = pending_bios_fn;
1062         generate_random_uuid(device->uuid);
1063         spin_lock_init(&device->io_lock);
1064         device->name = kstrdup(device_path, GFP_NOFS);
1065         if (!device->name) {
1066                 kfree(device);
1067                 goto out_close_bdev;
1068         }
1069         device->io_width = root->sectorsize;
1070         device->io_align = root->sectorsize;
1071         device->sector_size = root->sectorsize;
1072         device->total_bytes = i_size_read(bdev->bd_inode);
1073         device->dev_root = root->fs_info->dev_root;
1074         device->bdev = bdev;
1075         device->in_fs_metadata = 1;
1076
1077         ret = btrfs_add_device(trans, root, device);
1078         if (ret)
1079                 goto out_close_bdev;
1080
1081         set_blocksize(device->bdev, 4096);
1082
1083         total_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
1084         btrfs_set_super_total_bytes(&root->fs_info->super_copy,
1085                                     total_bytes + device->total_bytes);
1086
1087         total_bytes = btrfs_super_num_devices(&root->fs_info->super_copy);
1088         btrfs_set_super_num_devices(&root->fs_info->super_copy,
1089                                     total_bytes + 1);
1090
1091         list_add(&device->dev_list, &root->fs_info->fs_devices->devices);
1092         list_add(&device->dev_alloc_list,
1093                  &root->fs_info->fs_devices->alloc_list);
1094         root->fs_info->fs_devices->num_devices++;
1095         root->fs_info->fs_devices->open_devices++;
1096 out:
1097         unlock_chunks(root);
1098         btrfs_end_transaction(trans, root);
1099         mutex_unlock(&root->fs_info->volume_mutex);
1100
1101         return ret;
1102
1103 out_close_bdev:
1104         close_bdev_excl(bdev);
1105         goto out;
1106 }
1107
1108 int noinline btrfs_update_device(struct btrfs_trans_handle *trans,
1109                                  struct btrfs_device *device)
1110 {
1111         int ret;
1112         struct btrfs_path *path;
1113         struct btrfs_root *root;
1114         struct btrfs_dev_item *dev_item;
1115         struct extent_buffer *leaf;
1116         struct btrfs_key key;
1117
1118         root = device->dev_root->fs_info->chunk_root;
1119
1120         path = btrfs_alloc_path();
1121         if (!path)
1122                 return -ENOMEM;
1123
1124         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1125         key.type = BTRFS_DEV_ITEM_KEY;
1126         key.offset = device->devid;
1127
1128         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1129         if (ret < 0)
1130                 goto out;
1131
1132         if (ret > 0) {
1133                 ret = -ENOENT;
1134                 goto out;
1135         }
1136
1137         leaf = path->nodes[0];
1138         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1139
1140         btrfs_set_device_id(leaf, dev_item, device->devid);
1141         btrfs_set_device_type(leaf, dev_item, device->type);
1142         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1143         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1144         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1145         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1146         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1147         btrfs_mark_buffer_dirty(leaf);
1148
1149 out:
1150         btrfs_free_path(path);
1151         return ret;
1152 }
1153
1154 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
1155                       struct btrfs_device *device, u64 new_size)
1156 {
1157         struct btrfs_super_block *super_copy =
1158                 &device->dev_root->fs_info->super_copy;
1159         u64 old_total = btrfs_super_total_bytes(super_copy);
1160         u64 diff = new_size - device->total_bytes;
1161
1162         btrfs_set_super_total_bytes(super_copy, old_total + diff);
1163         return btrfs_update_device(trans, device);
1164 }
1165
1166 int btrfs_grow_device(struct btrfs_trans_handle *trans,
1167                       struct btrfs_device *device, u64 new_size)
1168 {
1169         int ret;
1170         lock_chunks(device->dev_root);
1171         ret = __btrfs_grow_device(trans, device, new_size);
1172         unlock_chunks(device->dev_root);
1173         return ret;
1174 }
1175
1176 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1177                             struct btrfs_root *root,
1178                             u64 chunk_tree, u64 chunk_objectid,
1179                             u64 chunk_offset)
1180 {
1181         int ret;
1182         struct btrfs_path *path;
1183         struct btrfs_key key;
1184
1185         root = root->fs_info->chunk_root;
1186         path = btrfs_alloc_path();
1187         if (!path)
1188                 return -ENOMEM;
1189
1190         key.objectid = chunk_objectid;
1191         key.offset = chunk_offset;
1192         key.type = BTRFS_CHUNK_ITEM_KEY;
1193
1194         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1195         BUG_ON(ret);
1196
1197         ret = btrfs_del_item(trans, root, path);
1198         BUG_ON(ret);
1199
1200         btrfs_free_path(path);
1201         return 0;
1202 }
1203
1204 int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
1205                         chunk_offset)
1206 {
1207         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1208         struct btrfs_disk_key *disk_key;
1209         struct btrfs_chunk *chunk;
1210         u8 *ptr;
1211         int ret = 0;
1212         u32 num_stripes;
1213         u32 array_size;
1214         u32 len = 0;
1215         u32 cur;
1216         struct btrfs_key key;
1217
1218         array_size = btrfs_super_sys_array_size(super_copy);
1219
1220         ptr = super_copy->sys_chunk_array;
1221         cur = 0;
1222
1223         while (cur < array_size) {
1224                 disk_key = (struct btrfs_disk_key *)ptr;
1225                 btrfs_disk_key_to_cpu(&key, disk_key);
1226
1227                 len = sizeof(*disk_key);
1228
1229                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1230                         chunk = (struct btrfs_chunk *)(ptr + len);
1231                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1232                         len += btrfs_chunk_item_size(num_stripes);
1233                 } else {
1234                         ret = -EIO;
1235                         break;
1236                 }
1237                 if (key.objectid == chunk_objectid &&
1238                     key.offset == chunk_offset) {
1239                         memmove(ptr, ptr + len, array_size - (cur + len));
1240                         array_size -= len;
1241                         btrfs_set_super_sys_array_size(super_copy, array_size);
1242                 } else {
1243                         ptr += len;
1244                         cur += len;
1245                 }
1246         }
1247         return ret;
1248 }
1249
1250
1251 int btrfs_relocate_chunk(struct btrfs_root *root,
1252                          u64 chunk_tree, u64 chunk_objectid,
1253                          u64 chunk_offset)
1254 {
1255         struct extent_map_tree *em_tree;
1256         struct btrfs_root *extent_root;
1257         struct btrfs_trans_handle *trans;
1258         struct extent_map *em;
1259         struct map_lookup *map;
1260         int ret;
1261         int i;
1262
1263         printk("btrfs relocating chunk %llu\n",
1264                (unsigned long long)chunk_offset);
1265         root = root->fs_info->chunk_root;
1266         extent_root = root->fs_info->extent_root;
1267         em_tree = &root->fs_info->mapping_tree.map_tree;
1268
1269         /* step one, relocate all the extents inside this chunk */
1270         ret = btrfs_relocate_block_group(extent_root, chunk_offset);
1271         BUG_ON(ret);
1272
1273         trans = btrfs_start_transaction(root, 1);
1274         BUG_ON(!trans);
1275
1276         lock_chunks(root);
1277
1278         /*
1279          * step two, delete the device extents and the
1280          * chunk tree entries
1281          */
1282         spin_lock(&em_tree->lock);
1283         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1284         spin_unlock(&em_tree->lock);
1285
1286         BUG_ON(em->start > chunk_offset ||
1287                em->start + em->len < chunk_offset);
1288         map = (struct map_lookup *)em->bdev;
1289
1290         for (i = 0; i < map->num_stripes; i++) {
1291                 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
1292                                             map->stripes[i].physical);
1293                 BUG_ON(ret);
1294
1295                 if (map->stripes[i].dev) {
1296                         ret = btrfs_update_device(trans, map->stripes[i].dev);
1297                         BUG_ON(ret);
1298                 }
1299         }
1300         ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
1301                                chunk_offset);
1302
1303         BUG_ON(ret);
1304
1305         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
1306                 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
1307                 BUG_ON(ret);
1308         }
1309
1310         ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
1311         BUG_ON(ret);
1312
1313         spin_lock(&em_tree->lock);
1314         remove_extent_mapping(em_tree, em);
1315         spin_unlock(&em_tree->lock);
1316
1317         kfree(map);
1318         em->bdev = NULL;
1319
1320         /* once for the tree */
1321         free_extent_map(em);
1322         /* once for us */
1323         free_extent_map(em);
1324
1325         unlock_chunks(root);
1326         btrfs_end_transaction(trans, root);
1327         return 0;
1328 }
1329
1330 static u64 div_factor(u64 num, int factor)
1331 {
1332         if (factor == 10)
1333                 return num;
1334         num *= factor;
1335         do_div(num, 10);
1336         return num;
1337 }
1338
1339
1340 int btrfs_balance(struct btrfs_root *dev_root)
1341 {
1342         int ret;
1343         struct list_head *cur;
1344         struct list_head *devices = &dev_root->fs_info->fs_devices->devices;
1345         struct btrfs_device *device;
1346         u64 old_size;
1347         u64 size_to_free;
1348         struct btrfs_path *path;
1349         struct btrfs_key key;
1350         struct btrfs_chunk *chunk;
1351         struct btrfs_root *chunk_root = dev_root->fs_info->chunk_root;
1352         struct btrfs_trans_handle *trans;
1353         struct btrfs_key found_key;
1354
1355
1356         mutex_lock(&dev_root->fs_info->volume_mutex);
1357         dev_root = dev_root->fs_info->dev_root;
1358
1359         /* step one make some room on all the devices */
1360         list_for_each(cur, devices) {
1361                 device = list_entry(cur, struct btrfs_device, dev_list);
1362                 old_size = device->total_bytes;
1363                 size_to_free = div_factor(old_size, 1);
1364                 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
1365                 if (device->total_bytes - device->bytes_used > size_to_free)
1366                         continue;
1367
1368                 ret = btrfs_shrink_device(device, old_size - size_to_free);
1369                 BUG_ON(ret);
1370
1371                 trans = btrfs_start_transaction(dev_root, 1);
1372                 BUG_ON(!trans);
1373
1374                 ret = btrfs_grow_device(trans, device, old_size);
1375                 BUG_ON(ret);
1376
1377                 btrfs_end_transaction(trans, dev_root);
1378         }
1379
1380         /* step two, relocate all the chunks */
1381         path = btrfs_alloc_path();
1382         BUG_ON(!path);
1383
1384         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1385         key.offset = (u64)-1;
1386         key.type = BTRFS_CHUNK_ITEM_KEY;
1387
1388         while(1) {
1389                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
1390                 if (ret < 0)
1391                         goto error;
1392
1393                 /*
1394                  * this shouldn't happen, it means the last relocate
1395                  * failed
1396                  */
1397                 if (ret == 0)
1398                         break;
1399
1400                 ret = btrfs_previous_item(chunk_root, path, 0,
1401                                           BTRFS_CHUNK_ITEM_KEY);
1402                 if (ret)
1403                         break;
1404
1405                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1406                                       path->slots[0]);
1407                 if (found_key.objectid != key.objectid)
1408                         break;
1409
1410                 chunk = btrfs_item_ptr(path->nodes[0],
1411                                        path->slots[0],
1412                                        struct btrfs_chunk);
1413                 key.offset = found_key.offset;
1414                 /* chunk zero is special */
1415                 if (key.offset == 0)
1416                         break;
1417
1418                 btrfs_release_path(chunk_root, path);
1419                 ret = btrfs_relocate_chunk(chunk_root,
1420                                            chunk_root->root_key.objectid,
1421                                            found_key.objectid,
1422                                            found_key.offset);
1423                 BUG_ON(ret);
1424         }
1425         ret = 0;
1426 error:
1427         btrfs_free_path(path);
1428         mutex_unlock(&dev_root->fs_info->volume_mutex);
1429         return ret;
1430 }
1431
1432 /*
1433  * shrinking a device means finding all of the device extents past
1434  * the new size, and then following the back refs to the chunks.
1435  * The chunk relocation code actually frees the device extent
1436  */
1437 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
1438 {
1439         struct btrfs_trans_handle *trans;
1440         struct btrfs_root *root = device->dev_root;
1441         struct btrfs_dev_extent *dev_extent = NULL;
1442         struct btrfs_path *path;
1443         u64 length;
1444         u64 chunk_tree;
1445         u64 chunk_objectid;
1446         u64 chunk_offset;
1447         int ret;
1448         int slot;
1449         struct extent_buffer *l;
1450         struct btrfs_key key;
1451         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1452         u64 old_total = btrfs_super_total_bytes(super_copy);
1453         u64 diff = device->total_bytes - new_size;
1454
1455
1456         path = btrfs_alloc_path();
1457         if (!path)
1458                 return -ENOMEM;
1459
1460         trans = btrfs_start_transaction(root, 1);
1461         if (!trans) {
1462                 ret = -ENOMEM;
1463                 goto done;
1464         }
1465
1466         path->reada = 2;
1467
1468         lock_chunks(root);
1469
1470         device->total_bytes = new_size;
1471         ret = btrfs_update_device(trans, device);
1472         if (ret) {
1473                 unlock_chunks(root);
1474                 btrfs_end_transaction(trans, root);
1475                 goto done;
1476         }
1477         WARN_ON(diff > old_total);
1478         btrfs_set_super_total_bytes(super_copy, old_total - diff);
1479         unlock_chunks(root);
1480         btrfs_end_transaction(trans, root);
1481
1482         key.objectid = device->devid;
1483         key.offset = (u64)-1;
1484         key.type = BTRFS_DEV_EXTENT_KEY;
1485
1486         while (1) {
1487                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1488                 if (ret < 0)
1489                         goto done;
1490
1491                 ret = btrfs_previous_item(root, path, 0, key.type);
1492                 if (ret < 0)
1493                         goto done;
1494                 if (ret) {
1495                         ret = 0;
1496                         goto done;
1497                 }
1498
1499                 l = path->nodes[0];
1500                 slot = path->slots[0];
1501                 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
1502
1503                 if (key.objectid != device->devid)
1504                         goto done;
1505
1506                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1507                 length = btrfs_dev_extent_length(l, dev_extent);
1508
1509                 if (key.offset + length <= new_size)
1510                         goto done;
1511
1512                 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
1513                 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
1514                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
1515                 btrfs_release_path(root, path);
1516
1517                 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
1518                                            chunk_offset);
1519                 if (ret)
1520                         goto done;
1521         }
1522
1523 done:
1524         btrfs_free_path(path);
1525         return ret;
1526 }
1527
1528 int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
1529                            struct btrfs_root *root,
1530                            struct btrfs_key *key,
1531                            struct btrfs_chunk *chunk, int item_size)
1532 {
1533         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1534         struct btrfs_disk_key disk_key;
1535         u32 array_size;
1536         u8 *ptr;
1537
1538         array_size = btrfs_super_sys_array_size(super_copy);
1539         if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
1540                 return -EFBIG;
1541
1542         ptr = super_copy->sys_chunk_array + array_size;
1543         btrfs_cpu_key_to_disk(&disk_key, key);
1544         memcpy(ptr, &disk_key, sizeof(disk_key));
1545         ptr += sizeof(disk_key);
1546         memcpy(ptr, chunk, item_size);
1547         item_size += sizeof(disk_key);
1548         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
1549         return 0;
1550 }
1551
1552 static u64 noinline chunk_bytes_by_type(u64 type, u64 calc_size,
1553                                         int num_stripes, int sub_stripes)
1554 {
1555         if (type & (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP))
1556                 return calc_size;
1557         else if (type & BTRFS_BLOCK_GROUP_RAID10)
1558                 return calc_size * (num_stripes / sub_stripes);
1559         else
1560                 return calc_size * num_stripes;
1561 }
1562
1563
1564 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
1565                       struct btrfs_root *extent_root, u64 *start,
1566                       u64 *num_bytes, u64 type)
1567 {
1568         u64 dev_offset;
1569         struct btrfs_fs_info *info = extent_root->fs_info;
1570         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
1571         struct btrfs_path *path;
1572         struct btrfs_stripe *stripes;
1573         struct btrfs_device *device = NULL;
1574         struct btrfs_chunk *chunk;
1575         struct list_head private_devs;
1576         struct list_head *dev_list;
1577         struct list_head *cur;
1578         struct extent_map_tree *em_tree;
1579         struct map_lookup *map;
1580         struct extent_map *em;
1581         int min_stripe_size = 1 * 1024 * 1024;
1582         u64 physical;
1583         u64 calc_size = 1024 * 1024 * 1024;
1584         u64 max_chunk_size = calc_size;
1585         u64 min_free;
1586         u64 avail;
1587         u64 max_avail = 0;
1588         u64 percent_max;
1589         int num_stripes = 1;
1590         int min_stripes = 1;
1591         int sub_stripes = 0;
1592         int looped = 0;
1593         int ret;
1594         int index;
1595         int stripe_len = 64 * 1024;
1596         struct btrfs_key key;
1597
1598         if ((type & BTRFS_BLOCK_GROUP_RAID1) &&
1599             (type & BTRFS_BLOCK_GROUP_DUP)) {
1600                 WARN_ON(1);
1601                 type &= ~BTRFS_BLOCK_GROUP_DUP;
1602         }
1603         dev_list = &extent_root->fs_info->fs_devices->alloc_list;
1604         if (list_empty(dev_list))
1605                 return -ENOSPC;
1606
1607         if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
1608                 num_stripes = extent_root->fs_info->fs_devices->open_devices;
1609                 min_stripes = 2;
1610         }
1611         if (type & (BTRFS_BLOCK_GROUP_DUP)) {
1612                 num_stripes = 2;
1613                 min_stripes = 2;
1614         }
1615         if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
1616                 num_stripes = min_t(u64, 2,
1617                             extent_root->fs_info->fs_devices->open_devices);
1618                 if (num_stripes < 2)
1619                         return -ENOSPC;
1620                 min_stripes = 2;
1621         }
1622         if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
1623                 num_stripes = extent_root->fs_info->fs_devices->open_devices;
1624                 if (num_stripes < 4)
1625                         return -ENOSPC;
1626                 num_stripes &= ~(u32)1;
1627                 sub_stripes = 2;
1628                 min_stripes = 4;
1629         }
1630
1631         if (type & BTRFS_BLOCK_GROUP_DATA) {
1632                 max_chunk_size = 10 * calc_size;
1633                 min_stripe_size = 64 * 1024 * 1024;
1634         } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
1635                 max_chunk_size = 4 * calc_size;
1636                 min_stripe_size = 32 * 1024 * 1024;
1637         } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
1638                 calc_size = 8 * 1024 * 1024;
1639                 max_chunk_size = calc_size * 2;
1640                 min_stripe_size = 1 * 1024 * 1024;
1641         }
1642
1643         path = btrfs_alloc_path();
1644         if (!path)
1645                 return -ENOMEM;
1646
1647         /* we don't want a chunk larger than 10% of the FS */
1648         percent_max = div_factor(btrfs_super_total_bytes(&info->super_copy), 1);
1649         max_chunk_size = min(percent_max, max_chunk_size);
1650
1651 again:
1652         if (calc_size * num_stripes > max_chunk_size) {
1653                 calc_size = max_chunk_size;
1654                 do_div(calc_size, num_stripes);
1655                 do_div(calc_size, stripe_len);
1656                 calc_size *= stripe_len;
1657         }
1658         /* we don't want tiny stripes */
1659         calc_size = max_t(u64, min_stripe_size, calc_size);
1660
1661         do_div(calc_size, stripe_len);
1662         calc_size *= stripe_len;
1663
1664         INIT_LIST_HEAD(&private_devs);
1665         cur = dev_list->next;
1666         index = 0;
1667
1668         if (type & BTRFS_BLOCK_GROUP_DUP)
1669                 min_free = calc_size * 2;
1670         else
1671                 min_free = calc_size;
1672
1673         /*
1674          * we add 1MB because we never use the first 1MB of the device, unless
1675          * we've looped, then we are likely allocating the maximum amount of
1676          * space left already
1677          */
1678         if (!looped)
1679                 min_free += 1024 * 1024;
1680
1681         /* build a private list of devices we will allocate from */
1682         while(index < num_stripes) {
1683                 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
1684
1685                 if (device->total_bytes > device->bytes_used)
1686                         avail = device->total_bytes - device->bytes_used;
1687                 else
1688                         avail = 0;
1689                 cur = cur->next;
1690
1691                 if (device->in_fs_metadata && avail >= min_free) {
1692                         u64 ignored_start = 0;
1693                         ret = find_free_dev_extent(trans, device, path,
1694                                                    min_free,
1695                                                    &ignored_start);
1696                         if (ret == 0) {
1697                                 list_move_tail(&device->dev_alloc_list,
1698                                                &private_devs);
1699                                 index++;
1700                                 if (type & BTRFS_BLOCK_GROUP_DUP)
1701                                         index++;
1702                         }
1703                 } else if (device->in_fs_metadata && avail > max_avail)
1704                         max_avail = avail;
1705                 if (cur == dev_list)
1706                         break;
1707         }
1708         if (index < num_stripes) {
1709                 list_splice(&private_devs, dev_list);
1710                 if (index >= min_stripes) {
1711                         num_stripes = index;
1712                         if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
1713                                 num_stripes /= sub_stripes;
1714                                 num_stripes *= sub_stripes;
1715                         }
1716                         looped = 1;
1717                         goto again;
1718                 }
1719                 if (!looped && max_avail > 0) {
1720                         looped = 1;
1721                         calc_size = max_avail;
1722                         goto again;
1723                 }
1724                 btrfs_free_path(path);
1725                 return -ENOSPC;
1726         }
1727         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1728         key.type = BTRFS_CHUNK_ITEM_KEY;
1729         ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1730                               &key.offset);
1731         if (ret) {
1732                 btrfs_free_path(path);
1733                 return ret;
1734         }
1735
1736         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
1737         if (!chunk) {
1738                 btrfs_free_path(path);
1739                 return -ENOMEM;
1740         }
1741
1742         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
1743         if (!map) {
1744                 kfree(chunk);
1745                 btrfs_free_path(path);
1746                 return -ENOMEM;
1747         }
1748         btrfs_free_path(path);
1749         path = NULL;
1750
1751         stripes = &chunk->stripe;
1752         *num_bytes = chunk_bytes_by_type(type, calc_size,
1753                                          num_stripes, sub_stripes);
1754
1755         index = 0;
1756         while(index < num_stripes) {
1757                 struct btrfs_stripe *stripe;
1758                 BUG_ON(list_empty(&private_devs));
1759                 cur = private_devs.next;
1760                 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
1761
1762                 /* loop over this device again if we're doing a dup group */
1763                 if (!(type & BTRFS_BLOCK_GROUP_DUP) ||
1764                     (index == num_stripes - 1))
1765                         list_move_tail(&device->dev_alloc_list, dev_list);
1766
1767                 ret = btrfs_alloc_dev_extent(trans, device,
1768                              info->chunk_root->root_key.objectid,
1769                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
1770                              calc_size, &dev_offset);
1771                 BUG_ON(ret);
1772                 device->bytes_used += calc_size;
1773                 ret = btrfs_update_device(trans, device);
1774                 BUG_ON(ret);
1775
1776                 map->stripes[index].dev = device;
1777                 map->stripes[index].physical = dev_offset;
1778                 stripe = stripes + index;
1779                 btrfs_set_stack_stripe_devid(stripe, device->devid);
1780                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
1781                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
1782                 physical = dev_offset;
1783                 index++;
1784         }
1785         BUG_ON(!list_empty(&private_devs));
1786
1787         /* key was set above */
1788         btrfs_set_stack_chunk_length(chunk, *num_bytes);
1789         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
1790         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
1791         btrfs_set_stack_chunk_type(chunk, type);
1792         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
1793         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
1794         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
1795         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
1796         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
1797         map->sector_size = extent_root->sectorsize;
1798         map->stripe_len = stripe_len;
1799         map->io_align = stripe_len;
1800         map->io_width = stripe_len;
1801         map->type = type;
1802         map->num_stripes = num_stripes;
1803         map->sub_stripes = sub_stripes;
1804
1805         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1806                                 btrfs_chunk_item_size(num_stripes));
1807         BUG_ON(ret);
1808         *start = key.offset;;
1809
1810         em = alloc_extent_map(GFP_NOFS);
1811         if (!em)
1812                 return -ENOMEM;
1813         em->bdev = (struct block_device *)map;
1814         em->start = key.offset;
1815         em->len = *num_bytes;
1816         em->block_start = 0;
1817         em->block_len = em->len;
1818
1819         if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
1820                 ret = btrfs_add_system_chunk(trans, chunk_root, &key,
1821                                     chunk, btrfs_chunk_item_size(num_stripes));
1822                 BUG_ON(ret);
1823         }
1824         kfree(chunk);
1825
1826         em_tree = &extent_root->fs_info->mapping_tree.map_tree;
1827         spin_lock(&em_tree->lock);
1828         ret = add_extent_mapping(em_tree, em);
1829         spin_unlock(&em_tree->lock);
1830         BUG_ON(ret);
1831         free_extent_map(em);
1832         return ret;
1833 }
1834
1835 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
1836 {
1837         extent_map_tree_init(&tree->map_tree, GFP_NOFS);
1838 }
1839
1840 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
1841 {
1842         struct extent_map *em;
1843
1844         while(1) {
1845                 spin_lock(&tree->map_tree.lock);
1846                 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
1847                 if (em)
1848                         remove_extent_mapping(&tree->map_tree, em);
1849                 spin_unlock(&tree->map_tree.lock);
1850                 if (!em)
1851                         break;
1852                 kfree(em->bdev);
1853                 /* once for us */
1854                 free_extent_map(em);
1855                 /* once for the tree */
1856                 free_extent_map(em);
1857         }
1858 }
1859
1860 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
1861 {
1862         struct extent_map *em;
1863         struct map_lookup *map;
1864         struct extent_map_tree *em_tree = &map_tree->map_tree;
1865         int ret;
1866
1867         spin_lock(&em_tree->lock);
1868         em = lookup_extent_mapping(em_tree, logical, len);
1869         spin_unlock(&em_tree->lock);
1870         BUG_ON(!em);
1871
1872         BUG_ON(em->start > logical || em->start + em->len < logical);
1873         map = (struct map_lookup *)em->bdev;
1874         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
1875                 ret = map->num_stripes;
1876         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1877                 ret = map->sub_stripes;
1878         else
1879                 ret = 1;
1880         free_extent_map(em);
1881         return ret;
1882 }
1883
1884 static int find_live_mirror(struct map_lookup *map, int first, int num,
1885                             int optimal)
1886 {
1887         int i;
1888         if (map->stripes[optimal].dev->bdev)
1889                 return optimal;
1890         for (i = first; i < first + num; i++) {
1891                 if (map->stripes[i].dev->bdev)
1892                         return i;
1893         }
1894         /* we couldn't find one that doesn't fail.  Just return something
1895          * and the io error handling code will clean up eventually
1896          */
1897         return optimal;
1898 }
1899
1900 static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1901                              u64 logical, u64 *length,
1902                              struct btrfs_multi_bio **multi_ret,
1903                              int mirror_num, struct page *unplug_page)
1904 {
1905         struct extent_map *em;
1906         struct map_lookup *map;
1907         struct extent_map_tree *em_tree = &map_tree->map_tree;
1908         u64 offset;
1909         u64 stripe_offset;
1910         u64 stripe_nr;
1911         int stripes_allocated = 8;
1912         int stripes_required = 1;
1913         int stripe_index;
1914         int i;
1915         int num_stripes;
1916         int max_errors = 0;
1917         struct btrfs_multi_bio *multi = NULL;
1918
1919         if (multi_ret && !(rw & (1 << BIO_RW))) {
1920                 stripes_allocated = 1;
1921         }
1922 again:
1923         if (multi_ret) {
1924                 multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
1925                                 GFP_NOFS);
1926                 if (!multi)
1927                         return -ENOMEM;
1928
1929                 atomic_set(&multi->error, 0);
1930         }
1931
1932         spin_lock(&em_tree->lock);
1933         em = lookup_extent_mapping(em_tree, logical, *length);
1934         spin_unlock(&em_tree->lock);
1935
1936         if (!em && unplug_page)
1937                 return 0;
1938
1939         if (!em) {
1940                 printk("unable to find logical %Lu len %Lu\n", logical, *length);
1941                 BUG();
1942         }
1943
1944         BUG_ON(em->start > logical || em->start + em->len < logical);
1945         map = (struct map_lookup *)em->bdev;
1946         offset = logical - em->start;
1947
1948         if (mirror_num > map->num_stripes)
1949                 mirror_num = 0;
1950
1951         /* if our multi bio struct is too small, back off and try again */
1952         if (rw & (1 << BIO_RW)) {
1953                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
1954                                  BTRFS_BLOCK_GROUP_DUP)) {
1955                         stripes_required = map->num_stripes;
1956                         max_errors = 1;
1957                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1958                         stripes_required = map->sub_stripes;
1959                         max_errors = 1;
1960                 }
1961         }
1962         if (multi_ret && rw == WRITE &&
1963             stripes_allocated < stripes_required) {
1964                 stripes_allocated = map->num_stripes;
1965                 free_extent_map(em);
1966                 kfree(multi);
1967                 goto again;
1968         }
1969         stripe_nr = offset;
1970         /*
1971          * stripe_nr counts the total number of stripes we have to stride
1972          * to get to this block
1973          */
1974         do_div(stripe_nr, map->stripe_len);
1975
1976         stripe_offset = stripe_nr * map->stripe_len;
1977         BUG_ON(offset < stripe_offset);
1978
1979         /* stripe_offset is the offset of this block in its stripe*/
1980         stripe_offset = offset - stripe_offset;
1981
1982         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1983                          BTRFS_BLOCK_GROUP_RAID10 |
1984                          BTRFS_BLOCK_GROUP_DUP)) {
1985                 /* we limit the length of each bio to what fits in a stripe */
1986                 *length = min_t(u64, em->len - offset,
1987                               map->stripe_len - stripe_offset);
1988         } else {
1989                 *length = em->len - offset;
1990         }
1991
1992         if (!multi_ret && !unplug_page)
1993                 goto out;
1994
1995         num_stripes = 1;
1996         stripe_index = 0;
1997         if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1998                 if (unplug_page || (rw & (1 << BIO_RW)))
1999                         num_stripes = map->num_stripes;
2000                 else if (mirror_num)
2001                         stripe_index = mirror_num - 1;
2002                 else {
2003                         stripe_index = find_live_mirror(map, 0,
2004                                             map->num_stripes,
2005                                             current->pid % map->num_stripes);
2006                 }
2007
2008         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
2009                 if (rw & (1 << BIO_RW))
2010                         num_stripes = map->num_stripes;
2011                 else if (mirror_num)
2012                         stripe_index = mirror_num - 1;
2013
2014         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
2015                 int factor = map->num_stripes / map->sub_stripes;
2016
2017                 stripe_index = do_div(stripe_nr, factor);
2018                 stripe_index *= map->sub_stripes;
2019
2020                 if (unplug_page || (rw & (1 << BIO_RW)))
2021                         num_stripes = map->sub_stripes;
2022                 else if (mirror_num)
2023                         stripe_index += mirror_num - 1;
2024                 else {
2025                         stripe_index = find_live_mirror(map, stripe_index,
2026                                               map->sub_stripes, stripe_index +
2027                                               current->pid % map->sub_stripes);
2028                 }
2029         } else {
2030                 /*
2031                  * after this do_div call, stripe_nr is the number of stripes
2032                  * on this device we have to walk to find the data, and
2033                  * stripe_index is the number of our device in the stripe array
2034                  */
2035                 stripe_index = do_div(stripe_nr, map->num_stripes);
2036         }
2037         BUG_ON(stripe_index >= map->num_stripes);
2038
2039         for (i = 0; i < num_stripes; i++) {
2040                 if (unplug_page) {
2041                         struct btrfs_device *device;
2042                         struct backing_dev_info *bdi;
2043
2044                         device = map->stripes[stripe_index].dev;
2045                         if (device->bdev) {
2046                                 bdi = blk_get_backing_dev_info(device->bdev);
2047                                 if (bdi->unplug_io_fn) {
2048                                         bdi->unplug_io_fn(bdi, unplug_page);
2049                                 }
2050                         }
2051                 } else {
2052                         multi->stripes[i].physical =
2053                                 map->stripes[stripe_index].physical +
2054                                 stripe_offset + stripe_nr * map->stripe_len;
2055                         multi->stripes[i].dev = map->stripes[stripe_index].dev;
2056                 }
2057                 stripe_index++;
2058         }
2059         if (multi_ret) {
2060                 *multi_ret = multi;
2061                 multi->num_stripes = num_stripes;
2062                 multi->max_errors = max_errors;
2063         }
2064 out:
2065         free_extent_map(em);
2066         return 0;
2067 }
2068
2069 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
2070                       u64 logical, u64 *length,
2071                       struct btrfs_multi_bio **multi_ret, int mirror_num)
2072 {
2073         return __btrfs_map_block(map_tree, rw, logical, length, multi_ret,
2074                                  mirror_num, NULL);
2075 }
2076
2077 int btrfs_unplug_page(struct btrfs_mapping_tree *map_tree,
2078                       u64 logical, struct page *page)
2079 {
2080         u64 length = PAGE_CACHE_SIZE;
2081         return __btrfs_map_block(map_tree, READ, logical, &length,
2082                                  NULL, 0, page);
2083 }
2084
2085
2086 static void end_bio_multi_stripe(struct bio *bio, int err)
2087 {
2088         struct btrfs_multi_bio *multi = bio->bi_private;
2089         int is_orig_bio = 0;
2090
2091         if (err)
2092                 atomic_inc(&multi->error);
2093
2094         if (bio == multi->orig_bio)
2095                 is_orig_bio = 1;
2096
2097         if (atomic_dec_and_test(&multi->stripes_pending)) {
2098                 if (!is_orig_bio) {
2099                         bio_put(bio);
2100                         bio = multi->orig_bio;
2101                 }
2102                 bio->bi_private = multi->private;
2103                 bio->bi_end_io = multi->end_io;
2104                 /* only send an error to the higher layers if it is
2105                  * beyond the tolerance of the multi-bio
2106                  */
2107                 if (atomic_read(&multi->error) > multi->max_errors) {
2108                         err = -EIO;
2109                 } else if (err) {
2110                         /*
2111                          * this bio is actually up to date, we didn't
2112                          * go over the max number of errors
2113                          */
2114                         set_bit(BIO_UPTODATE, &bio->bi_flags);
2115                         err = 0;
2116                 }
2117                 kfree(multi);
2118
2119                 bio_endio(bio, err);
2120         } else if (!is_orig_bio) {
2121                 bio_put(bio);
2122         }
2123 }
2124
2125 struct async_sched {
2126         struct bio *bio;
2127         int rw;
2128         struct btrfs_fs_info *info;
2129         struct btrfs_work work;
2130 };
2131
2132 /*
2133  * see run_scheduled_bios for a description of why bios are collected for
2134  * async submit.
2135  *
2136  * This will add one bio to the pending list for a device and make sure
2137  * the work struct is scheduled.
2138  */
2139 static int noinline schedule_bio(struct btrfs_root *root,
2140                                  struct btrfs_device *device,
2141                                  int rw, struct bio *bio)
2142 {
2143         int should_queue = 1;
2144
2145         /* don't bother with additional async steps for reads, right now */
2146         if (!(rw & (1 << BIO_RW))) {
2147                 bio_get(bio);
2148                 submit_bio(rw, bio);
2149                 bio_put(bio);
2150                 return 0;
2151         }
2152
2153         /*
2154          * nr_async_bios allows us to reliably return congestion to the
2155          * higher layers.  Otherwise, the async bio makes it appear we have
2156          * made progress against dirty pages when we've really just put it
2157          * on a queue for later
2158          */
2159         atomic_inc(&root->fs_info->nr_async_bios);
2160         WARN_ON(bio->bi_next);
2161         bio->bi_next = NULL;
2162         bio->bi_rw |= rw;
2163
2164         spin_lock(&device->io_lock);
2165
2166         if (device->pending_bio_tail)
2167                 device->pending_bio_tail->bi_next = bio;
2168
2169         device->pending_bio_tail = bio;
2170         if (!device->pending_bios)
2171                 device->pending_bios = bio;
2172         if (device->running_pending)
2173                 should_queue = 0;
2174
2175         spin_unlock(&device->io_lock);
2176
2177         if (should_queue)
2178                 btrfs_queue_worker(&root->fs_info->submit_workers,
2179                                    &device->work);
2180         return 0;
2181 }
2182
2183 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
2184                   int mirror_num, int async_submit)
2185 {
2186         struct btrfs_mapping_tree *map_tree;
2187         struct btrfs_device *dev;
2188         struct bio *first_bio = bio;
2189         u64 logical = (u64)bio->bi_sector << 9;
2190         u64 length = 0;
2191         u64 map_length;
2192         struct btrfs_multi_bio *multi = NULL;
2193         int ret;
2194         int dev_nr = 0;
2195         int total_devs = 1;
2196
2197         length = bio->bi_size;
2198         map_tree = &root->fs_info->mapping_tree;
2199         map_length = length;
2200
2201         ret = btrfs_map_block(map_tree, rw, logical, &map_length, &multi,
2202                               mirror_num);
2203         BUG_ON(ret);
2204
2205         total_devs = multi->num_stripes;
2206         if (map_length < length) {
2207                 printk("mapping failed logical %Lu bio len %Lu "
2208                        "len %Lu\n", logical, length, map_length);
2209                 BUG();
2210         }
2211         multi->end_io = first_bio->bi_end_io;
2212         multi->private = first_bio->bi_private;
2213         multi->orig_bio = first_bio;
2214         atomic_set(&multi->stripes_pending, multi->num_stripes);
2215
2216         while(dev_nr < total_devs) {
2217                 if (total_devs > 1) {
2218                         if (dev_nr < total_devs - 1) {
2219                                 bio = bio_clone(first_bio, GFP_NOFS);
2220                                 BUG_ON(!bio);
2221                         } else {
2222                                 bio = first_bio;
2223                         }
2224                         bio->bi_private = multi;
2225                         bio->bi_end_io = end_bio_multi_stripe;
2226                 }
2227                 bio->bi_sector = multi->stripes[dev_nr].physical >> 9;
2228                 dev = multi->stripes[dev_nr].dev;
2229                 if (dev && dev->bdev) {
2230                         bio->bi_bdev = dev->bdev;
2231                         if (async_submit)
2232                                 schedule_bio(root, dev, rw, bio);
2233                         else
2234                                 submit_bio(rw, bio);
2235                 } else {
2236                         bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
2237                         bio->bi_sector = logical >> 9;
2238                         bio_endio(bio, -EIO);
2239                 }
2240                 dev_nr++;
2241         }
2242         if (total_devs == 1)
2243                 kfree(multi);
2244         return 0;
2245 }
2246
2247 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
2248                                        u8 *uuid)
2249 {
2250         struct list_head *head = &root->fs_info->fs_devices->devices;
2251
2252         return __find_device(head, devid, uuid);
2253 }
2254
2255 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
2256                                             u64 devid, u8 *dev_uuid)
2257 {
2258         struct btrfs_device *device;
2259         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2260
2261         device = kzalloc(sizeof(*device), GFP_NOFS);
2262         list_add(&device->dev_list,
2263                  &fs_devices->devices);
2264         list_add(&device->dev_alloc_list,
2265                  &fs_devices->alloc_list);
2266         device->barriers = 1;
2267         device->dev_root = root->fs_info->dev_root;
2268         device->devid = devid;
2269         device->work.func = pending_bios_fn;
2270         fs_devices->num_devices++;
2271         spin_lock_init(&device->io_lock);
2272         memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
2273         return device;
2274 }
2275
2276
2277 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
2278                           struct extent_buffer *leaf,
2279                           struct btrfs_chunk *chunk)
2280 {
2281         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
2282         struct map_lookup *map;
2283         struct extent_map *em;
2284         u64 logical;
2285         u64 length;
2286         u64 devid;
2287         u8 uuid[BTRFS_UUID_SIZE];
2288         int num_stripes;
2289         int ret;
2290         int i;
2291
2292         logical = key->offset;
2293         length = btrfs_chunk_length(leaf, chunk);
2294
2295         spin_lock(&map_tree->map_tree.lock);
2296         em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
2297         spin_unlock(&map_tree->map_tree.lock);
2298
2299         /* already mapped? */
2300         if (em && em->start <= logical && em->start + em->len > logical) {
2301                 free_extent_map(em);
2302                 return 0;
2303         } else if (em) {
2304                 free_extent_map(em);
2305         }
2306
2307         map = kzalloc(sizeof(*map), GFP_NOFS);
2308         if (!map)
2309                 return -ENOMEM;
2310
2311         em = alloc_extent_map(GFP_NOFS);
2312         if (!em)
2313                 return -ENOMEM;
2314         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2315         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
2316         if (!map) {
2317                 free_extent_map(em);
2318                 return -ENOMEM;
2319         }
2320
2321         em->bdev = (struct block_device *)map;
2322         em->start = logical;
2323         em->len = length;
2324         em->block_start = 0;
2325         em->block_len = em->len;
2326
2327         map->num_stripes = num_stripes;
2328         map->io_width = btrfs_chunk_io_width(leaf, chunk);
2329         map->io_align = btrfs_chunk_io_align(leaf, chunk);
2330         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
2331         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
2332         map->type = btrfs_chunk_type(leaf, chunk);
2333         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
2334         for (i = 0; i < num_stripes; i++) {
2335                 map->stripes[i].physical =
2336                         btrfs_stripe_offset_nr(leaf, chunk, i);
2337                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
2338                 read_extent_buffer(leaf, uuid, (unsigned long)
2339                                    btrfs_stripe_dev_uuid_nr(chunk, i),
2340                                    BTRFS_UUID_SIZE);
2341                 map->stripes[i].dev = btrfs_find_device(root, devid, uuid);
2342
2343                 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
2344                         kfree(map);
2345                         free_extent_map(em);
2346                         return -EIO;
2347                 }
2348                 if (!map->stripes[i].dev) {
2349                         map->stripes[i].dev =
2350                                 add_missing_dev(root, devid, uuid);
2351                         if (!map->stripes[i].dev) {
2352                                 kfree(map);
2353                                 free_extent_map(em);
2354                                 return -EIO;
2355                         }
2356                 }
2357                 map->stripes[i].dev->in_fs_metadata = 1;
2358         }
2359
2360         spin_lock(&map_tree->map_tree.lock);
2361         ret = add_extent_mapping(&map_tree->map_tree, em);
2362         spin_unlock(&map_tree->map_tree.lock);
2363         BUG_ON(ret);
2364         free_extent_map(em);
2365
2366         return 0;
2367 }
2368
2369 static int fill_device_from_item(struct extent_buffer *leaf,
2370                                  struct btrfs_dev_item *dev_item,
2371                                  struct btrfs_device *device)
2372 {
2373         unsigned long ptr;
2374
2375         device->devid = btrfs_device_id(leaf, dev_item);
2376         device->total_bytes = btrfs_device_total_bytes(leaf, dev_item);
2377         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
2378         device->type = btrfs_device_type(leaf, dev_item);
2379         device->io_align = btrfs_device_io_align(leaf, dev_item);
2380         device->io_width = btrfs_device_io_width(leaf, dev_item);
2381         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
2382
2383         ptr = (unsigned long)btrfs_device_uuid(dev_item);
2384         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
2385
2386         return 0;
2387 }
2388
2389 static int read_one_dev(struct btrfs_root *root,
2390                         struct extent_buffer *leaf,
2391                         struct btrfs_dev_item *dev_item)
2392 {
2393         struct btrfs_device *device;
2394         u64 devid;
2395         int ret;
2396         u8 dev_uuid[BTRFS_UUID_SIZE];
2397
2398         devid = btrfs_device_id(leaf, dev_item);
2399         read_extent_buffer(leaf, dev_uuid,
2400                            (unsigned long)btrfs_device_uuid(dev_item),
2401                            BTRFS_UUID_SIZE);
2402         device = btrfs_find_device(root, devid, dev_uuid);
2403         if (!device) {
2404                 printk("warning devid %Lu missing\n", devid);
2405                 device = add_missing_dev(root, devid, dev_uuid);
2406                 if (!device)
2407                         return -ENOMEM;
2408         }
2409
2410         fill_device_from_item(leaf, dev_item, device);
2411         device->dev_root = root->fs_info->dev_root;
2412         device->in_fs_metadata = 1;
2413         ret = 0;
2414 #if 0
2415         ret = btrfs_open_device(device);
2416         if (ret) {
2417                 kfree(device);
2418         }
2419 #endif
2420         return ret;
2421 }
2422
2423 int btrfs_read_super_device(struct btrfs_root *root, struct extent_buffer *buf)
2424 {
2425         struct btrfs_dev_item *dev_item;
2426
2427         dev_item = (struct btrfs_dev_item *)offsetof(struct btrfs_super_block,
2428                                                      dev_item);
2429         return read_one_dev(root, buf, dev_item);
2430 }
2431
2432 int btrfs_read_sys_array(struct btrfs_root *root)
2433 {
2434         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
2435         struct extent_buffer *sb;
2436         struct btrfs_disk_key *disk_key;
2437         struct btrfs_chunk *chunk;
2438         u8 *ptr;
2439         unsigned long sb_ptr;
2440         int ret = 0;
2441         u32 num_stripes;
2442         u32 array_size;
2443         u32 len = 0;
2444         u32 cur;
2445         struct btrfs_key key;
2446
2447         sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
2448                                           BTRFS_SUPER_INFO_SIZE);
2449         if (!sb)
2450                 return -ENOMEM;
2451         btrfs_set_buffer_uptodate(sb);
2452         write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
2453         array_size = btrfs_super_sys_array_size(super_copy);
2454
2455         ptr = super_copy->sys_chunk_array;
2456         sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
2457         cur = 0;
2458
2459         while (cur < array_size) {
2460                 disk_key = (struct btrfs_disk_key *)ptr;
2461                 btrfs_disk_key_to_cpu(&key, disk_key);
2462
2463                 len = sizeof(*disk_key); ptr += len;
2464                 sb_ptr += len;
2465                 cur += len;
2466
2467                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2468                         chunk = (struct btrfs_chunk *)sb_ptr;
2469                         ret = read_one_chunk(root, &key, sb, chunk);
2470                         if (ret)
2471                                 break;
2472                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
2473                         len = btrfs_chunk_item_size(num_stripes);
2474                 } else {
2475                         ret = -EIO;
2476                         break;
2477                 }
2478                 ptr += len;
2479                 sb_ptr += len;
2480                 cur += len;
2481         }
2482         free_extent_buffer(sb);
2483         return ret;
2484 }
2485
2486 int btrfs_read_chunk_tree(struct btrfs_root *root)
2487 {
2488         struct btrfs_path *path;
2489         struct extent_buffer *leaf;
2490         struct btrfs_key key;
2491         struct btrfs_key found_key;
2492         int ret;
2493         int slot;
2494
2495         root = root->fs_info->chunk_root;
2496
2497         path = btrfs_alloc_path();
2498         if (!path)
2499                 return -ENOMEM;
2500
2501         /* first we search for all of the device items, and then we
2502          * read in all of the chunk items.  This way we can create chunk
2503          * mappings that reference all of the devices that are afound
2504          */
2505         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2506         key.offset = 0;
2507         key.type = 0;
2508 again:
2509         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2510         while(1) {
2511                 leaf = path->nodes[0];
2512                 slot = path->slots[0];
2513                 if (slot >= btrfs_header_nritems(leaf)) {
2514                         ret = btrfs_next_leaf(root, path);
2515                         if (ret == 0)
2516                                 continue;
2517                         if (ret < 0)
2518                                 goto error;
2519                         break;
2520                 }
2521                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2522                 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
2523                         if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
2524                                 break;
2525                         if (found_key.type == BTRFS_DEV_ITEM_KEY) {
2526                                 struct btrfs_dev_item *dev_item;
2527                                 dev_item = btrfs_item_ptr(leaf, slot,
2528                                                   struct btrfs_dev_item);
2529                                 ret = read_one_dev(root, leaf, dev_item);
2530                                 BUG_ON(ret);
2531                         }
2532                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
2533                         struct btrfs_chunk *chunk;
2534                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2535                         ret = read_one_chunk(root, &found_key, leaf, chunk);
2536                 }
2537                 path->slots[0]++;
2538         }
2539         if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
2540                 key.objectid = 0;
2541                 btrfs_release_path(root, path);
2542                 goto again;
2543         }
2544
2545         btrfs_free_path(path);
2546         ret = 0;
2547 error:
2548         return ret;
2549 }