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