Btrfs: Add support for mirroring across drives
[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 <asm/div64.h>
22 #include "ctree.h"
23 #include "extent_map.h"
24 #include "disk-io.h"
25 #include "transaction.h"
26 #include "print-tree.h"
27 #include "volumes.h"
28
29 struct stripe {
30         struct btrfs_device *dev;
31         u64 physical;
32 };
33
34 struct multi_bio {
35         atomic_t stripes;
36         bio_end_io_t *end_io;
37         void *private;
38         int error;
39 };
40
41 struct map_lookup {
42         u64 type;
43         int io_align;
44         int io_width;
45         int stripe_len;
46         int sector_size;
47         int num_stripes;
48         struct stripe stripes[];
49 };
50
51 #define map_lookup_size(n) (sizeof(struct map_lookup) + \
52                             (sizeof(struct stripe) * (n)))
53
54 static DEFINE_MUTEX(uuid_mutex);
55 static LIST_HEAD(fs_uuids);
56
57 int btrfs_cleanup_fs_uuids(void)
58 {
59         struct btrfs_fs_devices *fs_devices;
60         struct list_head *uuid_cur;
61         struct list_head *devices_cur;
62         struct btrfs_device *dev;
63
64         list_for_each(uuid_cur, &fs_uuids) {
65                 fs_devices = list_entry(uuid_cur, struct btrfs_fs_devices,
66                                         list);
67                 while(!list_empty(&fs_devices->devices)) {
68                         devices_cur = fs_devices->devices.next;
69                         dev = list_entry(devices_cur, struct btrfs_device,
70                                          dev_list);
71                         printk("uuid cleanup finds %s\n", dev->name);
72                         if (dev->bdev) {
73                                 printk("closing\n");
74                                 close_bdev_excl(dev->bdev);
75                         }
76                         list_del(&dev->dev_list);
77                         kfree(dev);
78                 }
79         }
80         return 0;
81 }
82
83 static struct btrfs_device *__find_device(struct list_head *head, u64 devid)
84 {
85         struct btrfs_device *dev;
86         struct list_head *cur;
87
88         list_for_each(cur, head) {
89                 dev = list_entry(cur, struct btrfs_device, dev_list);
90                 if (dev->devid == devid)
91                         return dev;
92         }
93         return NULL;
94 }
95
96 static struct btrfs_fs_devices *find_fsid(u8 *fsid)
97 {
98         struct list_head *cur;
99         struct btrfs_fs_devices *fs_devices;
100
101         list_for_each(cur, &fs_uuids) {
102                 fs_devices = list_entry(cur, struct btrfs_fs_devices, list);
103                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
104                         return fs_devices;
105         }
106         return NULL;
107 }
108
109 static int device_list_add(const char *path,
110                            struct btrfs_super_block *disk_super,
111                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
112 {
113         struct btrfs_device *device;
114         struct btrfs_fs_devices *fs_devices;
115         u64 found_transid = btrfs_super_generation(disk_super);
116
117         fs_devices = find_fsid(disk_super->fsid);
118         if (!fs_devices) {
119                 fs_devices = kmalloc(sizeof(*fs_devices), GFP_NOFS);
120                 if (!fs_devices)
121                         return -ENOMEM;
122                 INIT_LIST_HEAD(&fs_devices->devices);
123                 list_add(&fs_devices->list, &fs_uuids);
124                 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
125                 fs_devices->latest_devid = devid;
126                 fs_devices->latest_trans = found_transid;
127                 fs_devices->lowest_devid = (u64)-1;
128                 fs_devices->num_devices = 0;
129                 device = NULL;
130         } else {
131                 device = __find_device(&fs_devices->devices, devid);
132         }
133         if (!device) {
134                 device = kzalloc(sizeof(*device), GFP_NOFS);
135                 if (!device) {
136                         /* we can safely leave the fs_devices entry around */
137                         return -ENOMEM;
138                 }
139                 device->devid = devid;
140                 device->name = kstrdup(path, GFP_NOFS);
141                 if (!device->name) {
142                         kfree(device);
143                         return -ENOMEM;
144                 }
145                 list_add(&device->dev_list, &fs_devices->devices);
146                 fs_devices->num_devices++;
147         }
148
149         if (found_transid > fs_devices->latest_trans) {
150                 fs_devices->latest_devid = devid;
151                 fs_devices->latest_trans = found_transid;
152         }
153         if (fs_devices->lowest_devid > devid) {
154                 fs_devices->lowest_devid = devid;
155                 printk("lowest devid now %Lu\n", devid);
156         }
157         *fs_devices_ret = fs_devices;
158         return 0;
159 }
160
161 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
162 {
163         struct list_head *head = &fs_devices->devices;
164         struct list_head *cur;
165         struct btrfs_device *device;
166
167         mutex_lock(&uuid_mutex);
168         list_for_each(cur, head) {
169                 device = list_entry(cur, struct btrfs_device, dev_list);
170                 if (device->bdev) {
171                         close_bdev_excl(device->bdev);
172                         printk("close devices closes %s\n", device->name);
173                 }
174                 device->bdev = NULL;
175         }
176         mutex_unlock(&uuid_mutex);
177         return 0;
178 }
179
180 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
181                        int flags, void *holder)
182 {
183         struct block_device *bdev;
184         struct list_head *head = &fs_devices->devices;
185         struct list_head *cur;
186         struct btrfs_device *device;
187         int ret;
188
189         mutex_lock(&uuid_mutex);
190         list_for_each(cur, head) {
191                 device = list_entry(cur, struct btrfs_device, dev_list);
192                 bdev = open_bdev_excl(device->name, flags, holder);
193 printk("opening %s devid %Lu\n", device->name, device->devid);
194                 if (IS_ERR(bdev)) {
195                         printk("open %s failed\n", device->name);
196                         ret = PTR_ERR(bdev);
197                         goto fail;
198                 }
199                 if (device->devid == fs_devices->latest_devid)
200                         fs_devices->latest_bdev = bdev;
201                 if (device->devid == fs_devices->lowest_devid) {
202                         fs_devices->lowest_bdev = bdev;
203 printk("lowest bdev %s\n", device->name);
204                 }
205                 device->bdev = bdev;
206         }
207         mutex_unlock(&uuid_mutex);
208         return 0;
209 fail:
210         mutex_unlock(&uuid_mutex);
211         btrfs_close_devices(fs_devices);
212         return ret;
213 }
214
215 int btrfs_scan_one_device(const char *path, int flags, void *holder,
216                           struct btrfs_fs_devices **fs_devices_ret)
217 {
218         struct btrfs_super_block *disk_super;
219         struct block_device *bdev;
220         struct buffer_head *bh;
221         int ret;
222         u64 devid;
223
224         mutex_lock(&uuid_mutex);
225
226         printk("scan one opens %s\n", path);
227         bdev = open_bdev_excl(path, flags, holder);
228
229         if (IS_ERR(bdev)) {
230                 printk("open failed\n");
231                 ret = PTR_ERR(bdev);
232                 goto error;
233         }
234
235         ret = set_blocksize(bdev, 4096);
236         if (ret)
237                 goto error_close;
238         bh = __bread(bdev, BTRFS_SUPER_INFO_OFFSET / 4096, 4096);
239         if (!bh) {
240                 ret = -EIO;
241                 goto error_close;
242         }
243         disk_super = (struct btrfs_super_block *)bh->b_data;
244         if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
245             sizeof(disk_super->magic))) {
246                 printk("no btrfs found on %s\n", path);
247                 ret = -EINVAL;
248                 goto error_brelse;
249         }
250         devid = le64_to_cpu(disk_super->dev_item.devid);
251         printk("found device %Lu on %s\n", devid, path);
252         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
253
254 error_brelse:
255         brelse(bh);
256 error_close:
257         close_bdev_excl(bdev);
258         printk("scan one closes bdev %s\n", path);
259 error:
260         mutex_unlock(&uuid_mutex);
261         return ret;
262 }
263
264 /*
265  * this uses a pretty simple search, the expectation is that it is
266  * called very infrequently and that a given device has a small number
267  * of extents
268  */
269 static int find_free_dev_extent(struct btrfs_trans_handle *trans,
270                                 struct btrfs_device *device,
271                                 struct btrfs_path *path,
272                                 u64 num_bytes, u64 *start)
273 {
274         struct btrfs_key key;
275         struct btrfs_root *root = device->dev_root;
276         struct btrfs_dev_extent *dev_extent = NULL;
277         u64 hole_size = 0;
278         u64 last_byte = 0;
279         u64 search_start = 0;
280         u64 search_end = device->total_bytes;
281         int ret;
282         int slot = 0;
283         int start_found;
284         struct extent_buffer *l;
285
286         start_found = 0;
287         path->reada = 2;
288
289         /* FIXME use last free of some kind */
290
291         /* we don't want to overwrite the superblock on the drive,
292          * so we make sure to start at an offset of at least 1MB
293          */
294         search_start = max((u64)1024 * 1024, search_start);
295         key.objectid = device->devid;
296         key.offset = search_start;
297         key.type = BTRFS_DEV_EXTENT_KEY;
298         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
299         if (ret < 0)
300                 goto error;
301         ret = btrfs_previous_item(root, path, 0, key.type);
302         if (ret < 0)
303                 goto error;
304         l = path->nodes[0];
305         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
306         while (1) {
307                 l = path->nodes[0];
308                 slot = path->slots[0];
309                 if (slot >= btrfs_header_nritems(l)) {
310                         ret = btrfs_next_leaf(root, path);
311                         if (ret == 0)
312                                 continue;
313                         if (ret < 0)
314                                 goto error;
315 no_more_items:
316                         if (!start_found) {
317                                 if (search_start >= search_end) {
318                                         ret = -ENOSPC;
319                                         goto error;
320                                 }
321                                 *start = search_start;
322                                 start_found = 1;
323                                 goto check_pending;
324                         }
325                         *start = last_byte > search_start ?
326                                 last_byte : search_start;
327                         if (search_end <= *start) {
328                                 ret = -ENOSPC;
329                                 goto error;
330                         }
331                         goto check_pending;
332                 }
333                 btrfs_item_key_to_cpu(l, &key, slot);
334
335                 if (key.objectid < device->devid)
336                         goto next;
337
338                 if (key.objectid > device->devid)
339                         goto no_more_items;
340
341                 if (key.offset >= search_start && key.offset > last_byte &&
342                     start_found) {
343                         if (last_byte < search_start)
344                                 last_byte = search_start;
345                         hole_size = key.offset - last_byte;
346                         if (key.offset > last_byte &&
347                             hole_size >= num_bytes) {
348                                 *start = last_byte;
349                                 goto check_pending;
350                         }
351                 }
352                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY) {
353                         goto next;
354                 }
355
356                 start_found = 1;
357                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
358                 last_byte = key.offset + btrfs_dev_extent_length(l, dev_extent);
359 next:
360                 path->slots[0]++;
361                 cond_resched();
362         }
363 check_pending:
364         /* we have to make sure we didn't find an extent that has already
365          * been allocated by the map tree or the original allocation
366          */
367         btrfs_release_path(root, path);
368         BUG_ON(*start < search_start);
369
370         if (*start + num_bytes > search_end) {
371                 ret = -ENOSPC;
372                 goto error;
373         }
374         /* check for pending inserts here */
375         return 0;
376
377 error:
378         btrfs_release_path(root, path);
379         return ret;
380 }
381
382 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
383                            struct btrfs_device *device,
384                            u64 owner, u64 num_bytes, u64 *start)
385 {
386         int ret;
387         struct btrfs_path *path;
388         struct btrfs_root *root = device->dev_root;
389         struct btrfs_dev_extent *extent;
390         struct extent_buffer *leaf;
391         struct btrfs_key key;
392
393         path = btrfs_alloc_path();
394         if (!path)
395                 return -ENOMEM;
396
397         ret = find_free_dev_extent(trans, device, path, num_bytes, start);
398         if (ret) {
399                 goto err;
400         }
401
402         key.objectid = device->devid;
403         key.offset = *start;
404         key.type = BTRFS_DEV_EXTENT_KEY;
405         ret = btrfs_insert_empty_item(trans, root, path, &key,
406                                       sizeof(*extent));
407         BUG_ON(ret);
408
409         leaf = path->nodes[0];
410         extent = btrfs_item_ptr(leaf, path->slots[0],
411                                 struct btrfs_dev_extent);
412         btrfs_set_dev_extent_owner(leaf, extent, owner);
413         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
414         btrfs_mark_buffer_dirty(leaf);
415 err:
416         btrfs_free_path(path);
417         return ret;
418 }
419
420 static int find_next_chunk(struct btrfs_root *root, u64 *objectid)
421 {
422         struct btrfs_path *path;
423         int ret;
424         struct btrfs_key key;
425         struct btrfs_key found_key;
426
427         path = btrfs_alloc_path();
428         BUG_ON(!path);
429
430         key.objectid = (u64)-1;
431         key.offset = (u64)-1;
432         key.type = BTRFS_CHUNK_ITEM_KEY;
433
434         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
435         if (ret < 0)
436                 goto error;
437
438         BUG_ON(ret == 0);
439
440         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
441         if (ret) {
442                 *objectid = 0;
443         } else {
444                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
445                                       path->slots[0]);
446                 *objectid = found_key.objectid + found_key.offset;
447         }
448         ret = 0;
449 error:
450         btrfs_free_path(path);
451         return ret;
452 }
453
454 static int find_next_devid(struct btrfs_root *root, struct btrfs_path *path,
455                            u64 *objectid)
456 {
457         int ret;
458         struct btrfs_key key;
459         struct btrfs_key found_key;
460
461         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
462         key.type = BTRFS_DEV_ITEM_KEY;
463         key.offset = (u64)-1;
464
465         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
466         if (ret < 0)
467                 goto error;
468
469         BUG_ON(ret == 0);
470
471         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
472                                   BTRFS_DEV_ITEM_KEY);
473         if (ret) {
474                 *objectid = 1;
475         } else {
476                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
477                                       path->slots[0]);
478                 *objectid = found_key.offset + 1;
479         }
480         ret = 0;
481 error:
482         btrfs_release_path(root, path);
483         return ret;
484 }
485
486 /*
487  * the device information is stored in the chunk root
488  * the btrfs_device struct should be fully filled in
489  */
490 int btrfs_add_device(struct btrfs_trans_handle *trans,
491                      struct btrfs_root *root,
492                      struct btrfs_device *device)
493 {
494         int ret;
495         struct btrfs_path *path;
496         struct btrfs_dev_item *dev_item;
497         struct extent_buffer *leaf;
498         struct btrfs_key key;
499         unsigned long ptr;
500         u64 free_devid;
501
502         root = root->fs_info->chunk_root;
503
504         path = btrfs_alloc_path();
505         if (!path)
506                 return -ENOMEM;
507
508         ret = find_next_devid(root, path, &free_devid);
509         if (ret)
510                 goto out;
511
512         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
513         key.type = BTRFS_DEV_ITEM_KEY;
514         key.offset = free_devid;
515
516         ret = btrfs_insert_empty_item(trans, root, path, &key,
517                                       sizeof(*dev_item));
518         if (ret)
519                 goto out;
520
521         leaf = path->nodes[0];
522         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
523
524         device->devid = free_devid;
525         btrfs_set_device_id(leaf, dev_item, device->devid);
526         btrfs_set_device_type(leaf, dev_item, device->type);
527         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
528         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
529         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
530         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
531         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
532
533         ptr = (unsigned long)btrfs_device_uuid(dev_item);
534         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_DEV_UUID_SIZE);
535         btrfs_mark_buffer_dirty(leaf);
536         ret = 0;
537
538 out:
539         btrfs_free_path(path);
540         return ret;
541 }
542 int btrfs_update_device(struct btrfs_trans_handle *trans,
543                         struct btrfs_device *device)
544 {
545         int ret;
546         struct btrfs_path *path;
547         struct btrfs_root *root;
548         struct btrfs_dev_item *dev_item;
549         struct extent_buffer *leaf;
550         struct btrfs_key key;
551
552         root = device->dev_root->fs_info->chunk_root;
553
554         path = btrfs_alloc_path();
555         if (!path)
556                 return -ENOMEM;
557
558         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
559         key.type = BTRFS_DEV_ITEM_KEY;
560         key.offset = device->devid;
561
562         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
563         if (ret < 0)
564                 goto out;
565
566         if (ret > 0) {
567                 ret = -ENOENT;
568                 goto out;
569         }
570
571         leaf = path->nodes[0];
572         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
573
574         btrfs_set_device_id(leaf, dev_item, device->devid);
575         btrfs_set_device_type(leaf, dev_item, device->type);
576         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
577         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
578         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
579         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
580         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
581         btrfs_mark_buffer_dirty(leaf);
582
583 out:
584         btrfs_free_path(path);
585         return ret;
586 }
587
588 int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
589                            struct btrfs_root *root,
590                            struct btrfs_key *key,
591                            struct btrfs_chunk *chunk, int item_size)
592 {
593         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
594         struct btrfs_disk_key disk_key;
595         u32 array_size;
596         u8 *ptr;
597
598         array_size = btrfs_super_sys_array_size(super_copy);
599         if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
600                 return -EFBIG;
601
602         ptr = super_copy->sys_chunk_array + array_size;
603         btrfs_cpu_key_to_disk(&disk_key, key);
604         memcpy(ptr, &disk_key, sizeof(disk_key));
605         ptr += sizeof(disk_key);
606         memcpy(ptr, chunk, item_size);
607         item_size += sizeof(disk_key);
608         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
609         return 0;
610 }
611
612 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
613                       struct btrfs_root *extent_root, u64 *start,
614                       u64 *num_bytes, u64 type)
615 {
616         u64 dev_offset;
617         struct btrfs_fs_info *info = extent_root->fs_info;
618         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
619         struct btrfs_stripe *stripes;
620         struct btrfs_device *device = NULL;
621         struct btrfs_chunk *chunk;
622         struct list_head private_devs;
623         struct list_head *dev_list = &extent_root->fs_info->fs_devices->devices;
624         struct list_head *cur;
625         struct extent_map_tree *em_tree;
626         struct map_lookup *map;
627         struct extent_map *em;
628         u64 physical;
629         u64 calc_size = 1024 * 1024 * 1024;
630         u64 avail;
631         u64 max_avail = 0;
632         int num_stripes = 1;
633         int looped = 0;
634         int ret;
635         int index;
636         int stripe_len = 64 * 1024;
637         struct btrfs_key key;
638
639         if (list_empty(dev_list))
640                 return -ENOSPC;
641
642         if (type & (BTRFS_BLOCK_GROUP_RAID0))
643                 num_stripes = btrfs_super_num_devices(&info->super_copy);
644         if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
645                 num_stripes = min_t(u64, 2,
646                                   btrfs_super_num_devices(&info->super_copy));
647         }
648 again:
649         INIT_LIST_HEAD(&private_devs);
650         cur = dev_list->next;
651         index = 0;
652         /* build a private list of devices we will allocate from */
653         while(index < num_stripes) {
654                 device = list_entry(cur, struct btrfs_device, dev_list);
655                 avail = device->total_bytes - device->bytes_used;
656                 cur = cur->next;
657                 if (avail > max_avail)
658                         max_avail = avail;
659                 if (avail >= calc_size) {
660                         list_move_tail(&device->dev_list, &private_devs);
661                         index++;
662                 }
663                 if (cur == dev_list)
664                         break;
665         }
666         if (index < num_stripes) {
667                 list_splice(&private_devs, dev_list);
668                 if (!looped && max_avail > 0) {
669                         looped = 1;
670                         calc_size = max_avail;
671                         goto again;
672                 }
673                 return -ENOSPC;
674         }
675
676         ret = find_next_chunk(chunk_root, &key.objectid);
677         if (ret)
678                 return ret;
679
680         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
681         if (!chunk)
682                 return -ENOMEM;
683
684         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
685         if (!map) {
686                 kfree(chunk);
687                 return -ENOMEM;
688         }
689
690         stripes = &chunk->stripe;
691
692         if (type & BTRFS_BLOCK_GROUP_RAID1)
693                 *num_bytes = calc_size;
694         else
695                 *num_bytes = calc_size * num_stripes;
696
697         index = 0;
698         while(index < num_stripes) {
699                 BUG_ON(list_empty(&private_devs));
700                 cur = private_devs.next;
701                 device = list_entry(cur, struct btrfs_device, dev_list);
702                 list_move_tail(&device->dev_list, dev_list);
703
704                 ret = btrfs_alloc_dev_extent(trans, device,
705                                              key.objectid,
706                                              calc_size, &dev_offset);
707                 BUG_ON(ret);
708 printk("alloc chunk start %Lu size %Lu from dev %Lu type %Lu\n", key.objectid, calc_size, device->devid, type);
709                 device->bytes_used += calc_size;
710                 ret = btrfs_update_device(trans, device);
711                 BUG_ON(ret);
712
713                 map->stripes[index].dev = device;
714                 map->stripes[index].physical = dev_offset;
715                 btrfs_set_stack_stripe_devid(stripes + index, device->devid);
716                 btrfs_set_stack_stripe_offset(stripes + index, dev_offset);
717                 physical = dev_offset;
718                 index++;
719         }
720         BUG_ON(!list_empty(&private_devs));
721
722         /* key.objectid was set above */
723         key.offset = *num_bytes;
724         key.type = BTRFS_CHUNK_ITEM_KEY;
725         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
726         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
727         btrfs_set_stack_chunk_type(chunk, type);
728         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
729         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
730         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
731         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
732         map->sector_size = extent_root->sectorsize;
733         map->stripe_len = stripe_len;
734         map->io_align = stripe_len;
735         map->io_width = stripe_len;
736         map->type = type;
737         map->num_stripes = num_stripes;
738
739         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
740                                 btrfs_chunk_item_size(num_stripes));
741         BUG_ON(ret);
742         *start = key.objectid;
743
744         em = alloc_extent_map(GFP_NOFS);
745         if (!em)
746                 return -ENOMEM;
747         em->bdev = (struct block_device *)map;
748         em->start = key.objectid;
749         em->len = key.offset;
750         em->block_start = 0;
751
752         kfree(chunk);
753
754         em_tree = &extent_root->fs_info->mapping_tree.map_tree;
755         spin_lock(&em_tree->lock);
756         ret = add_extent_mapping(em_tree, em);
757         BUG_ON(ret);
758         spin_unlock(&em_tree->lock);
759         free_extent_map(em);
760         return ret;
761 }
762
763 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
764 {
765         extent_map_tree_init(&tree->map_tree, GFP_NOFS);
766 }
767
768 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
769 {
770         struct extent_map *em;
771
772         while(1) {
773                 spin_lock(&tree->map_tree.lock);
774                 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
775                 if (em)
776                         remove_extent_mapping(&tree->map_tree, em);
777                 spin_unlock(&tree->map_tree.lock);
778                 if (!em)
779                         break;
780                 kfree(em->bdev);
781                 /* once for us */
782                 free_extent_map(em);
783                 /* once for the tree */
784                 free_extent_map(em);
785         }
786 }
787
788 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
789                     int dev_nr, u64 logical, u64 *phys, u64 *length,
790                     struct btrfs_device **dev, int *total_devs)
791 {
792         struct extent_map *em;
793         struct map_lookup *map;
794         struct extent_map_tree *em_tree = &map_tree->map_tree;
795         u64 offset;
796         u64 stripe_offset;
797         u64 stripe_nr;
798         int stripe_index;
799
800
801         spin_lock(&em_tree->lock);
802         em = lookup_extent_mapping(em_tree, logical, *length);
803         BUG_ON(!em);
804
805         BUG_ON(em->start > logical || em->start + em->len < logical);
806         map = (struct map_lookup *)em->bdev;
807         offset = logical - em->start;
808
809         stripe_nr = offset;
810         /*
811          * stripe_nr counts the total number of stripes we have to stride
812          * to get to this block
813          */
814         do_div(stripe_nr, map->stripe_len);
815
816         stripe_offset = stripe_nr * map->stripe_len;
817         BUG_ON(offset < stripe_offset);
818
819         /* stripe_offset is the offset of this block in its stripe*/
820         stripe_offset = offset - stripe_offset;
821
822         if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
823                 stripe_index = dev_nr;
824                 if (rw & (1 << BIO_RW))
825                         *total_devs = map->num_stripes;
826                 else {
827                         int i;
828                         u64 least = (u64)-1;
829                         struct btrfs_device *cur;
830
831                         for (i = 0; i < map->num_stripes; i++) {
832                                 cur = map->stripes[i].dev;
833                                 spin_lock(&cur->io_lock);
834                                 if (cur->total_ios < least) {
835                                         least = cur->total_ios;
836                                         stripe_index = i;
837                                 }
838                                 spin_unlock(&cur->io_lock);
839                         }
840                         *total_devs = 1;
841                 }
842         } else {
843                 /*
844                  * after this do_div call, stripe_nr is the number of stripes
845                  * on this device we have to walk to find the data, and
846                  * stripe_index is the number of our device in the stripe array
847                  */
848                 stripe_index = do_div(stripe_nr, map->num_stripes);
849         }
850         BUG_ON(stripe_index >= map->num_stripes);
851         *phys = map->stripes[stripe_index].physical + stripe_offset +
852                 stripe_nr * map->stripe_len;
853
854         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1)) {
855                 /* we limit the length of each bio to what fits in a stripe */
856                 *length = min_t(u64, em->len - offset,
857                               map->stripe_len - stripe_offset);
858         } else {
859                 *length = em->len - offset;
860         }
861         *dev = map->stripes[stripe_index].dev;
862         free_extent_map(em);
863         spin_unlock(&em_tree->lock);
864         return 0;
865 }
866
867 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,23)
868 static void end_bio_multi_stripe(struct bio *bio, int err)
869 #else
870 static int end_bio_multi_stripe(struct bio *bio,
871                                    unsigned int bytes_done, int err)
872 #endif
873 {
874         struct multi_bio *multi = bio->bi_private;
875
876 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23)
877         if (bio->bi_size)
878                 return 1;
879 #endif
880         if (err)
881                 multi->error = err;
882
883         if (atomic_dec_and_test(&multi->stripes)) {
884                 bio->bi_private = multi->private;
885                 bio->bi_end_io = multi->end_io;
886
887                 if (!err && multi->error)
888                         err = multi->error;
889                 kfree(multi);
890
891                 bio_endio(bio, err);
892         } else {
893                 bio_put(bio);
894         }
895 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23)
896         return 0;
897 #endif
898 }
899
900 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio)
901 {
902         struct btrfs_mapping_tree *map_tree;
903         struct btrfs_device *dev;
904         struct bio *first_bio = bio;
905         u64 logical = bio->bi_sector << 9;
906         u64 physical;
907         u64 length = 0;
908         u64 map_length;
909         struct bio_vec *bvec;
910         struct multi_bio *multi = NULL;
911         int i;
912         int ret;
913         int dev_nr = 0;
914         int total_devs = 1;
915
916         bio_for_each_segment(bvec, bio, i) {
917                 length += bvec->bv_len;
918         }
919
920         map_tree = &root->fs_info->mapping_tree;
921         map_length = length;
922         while(dev_nr < total_devs) {
923                 ret = btrfs_map_block(map_tree, rw, dev_nr, logical,
924                                       &physical, &map_length, &dev,
925                                       &total_devs);
926                 if (map_length < length) {
927                         printk("mapping failed logical %Lu bio len %Lu physical %Lu "
928                                "len %Lu\n", logical, length, physical, map_length);
929                         BUG();
930                 }
931                 BUG_ON(map_length < length);
932                 if (total_devs > 1) {
933                         if (!multi) {
934                                 multi = kmalloc(sizeof(*multi), GFP_NOFS);
935                                 atomic_set(&multi->stripes, 1);
936                                 multi->end_io = bio->bi_end_io;
937                                 multi->private = first_bio->bi_private;
938                                 multi->error = 0;
939                         } else {
940                                 atomic_inc(&multi->stripes);
941                         }
942                         if (dev_nr < total_devs - 1) {
943                                 bio = bio_clone(first_bio, GFP_NOFS);
944                                 BUG_ON(!bio);
945                         } else {
946                                 bio = first_bio;
947                         }
948                         bio->bi_private = multi;
949                         bio->bi_end_io = end_bio_multi_stripe;
950                 }
951                 bio->bi_sector = physical >> 9;
952                 bio->bi_bdev = dev->bdev;
953                 spin_lock(&dev->io_lock);
954                 dev->total_ios++;
955                 spin_unlock(&dev->io_lock);
956                 submit_bio(rw, bio);
957                 dev_nr++;
958         }
959         return 0;
960 }
961
962 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid)
963 {
964         struct list_head *head = &root->fs_info->fs_devices->devices;
965
966         return __find_device(head, devid);
967 }
968
969 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
970                           struct extent_buffer *leaf,
971                           struct btrfs_chunk *chunk)
972 {
973         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
974         struct map_lookup *map;
975         struct extent_map *em;
976         u64 logical;
977         u64 length;
978         u64 devid;
979         int num_stripes;
980         int ret;
981         int i;
982
983         logical = key->objectid;
984         length = key->offset;
985         spin_lock(&map_tree->map_tree.lock);
986         em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
987
988         /* already mapped? */
989         if (em && em->start <= logical && em->start + em->len > logical) {
990                 free_extent_map(em);
991                 spin_unlock(&map_tree->map_tree.lock);
992                 return 0;
993         } else if (em) {
994                 free_extent_map(em);
995         }
996         spin_unlock(&map_tree->map_tree.lock);
997
998         map = kzalloc(sizeof(*map), GFP_NOFS);
999         if (!map)
1000                 return -ENOMEM;
1001
1002         em = alloc_extent_map(GFP_NOFS);
1003         if (!em)
1004                 return -ENOMEM;
1005         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1006         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
1007         if (!map) {
1008                 free_extent_map(em);
1009                 return -ENOMEM;
1010         }
1011
1012         em->bdev = (struct block_device *)map;
1013         em->start = logical;
1014         em->len = length;
1015         em->block_start = 0;
1016
1017         map->num_stripes = num_stripes;
1018         map->io_width = btrfs_chunk_io_width(leaf, chunk);
1019         map->io_align = btrfs_chunk_io_align(leaf, chunk);
1020         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
1021         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
1022         map->type = btrfs_chunk_type(leaf, chunk);
1023         for (i = 0; i < num_stripes; i++) {
1024                 map->stripes[i].physical =
1025                         btrfs_stripe_offset_nr(leaf, chunk, i);
1026                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
1027                 map->stripes[i].dev = btrfs_find_device(root, devid);
1028                 if (!map->stripes[i].dev) {
1029                         kfree(map);
1030                         free_extent_map(em);
1031                         return -EIO;
1032                 }
1033         }
1034
1035         spin_lock(&map_tree->map_tree.lock);
1036         ret = add_extent_mapping(&map_tree->map_tree, em);
1037         BUG_ON(ret);
1038         spin_unlock(&map_tree->map_tree.lock);
1039         free_extent_map(em);
1040
1041         return 0;
1042 }
1043
1044 static int fill_device_from_item(struct extent_buffer *leaf,
1045                                  struct btrfs_dev_item *dev_item,
1046                                  struct btrfs_device *device)
1047 {
1048         unsigned long ptr;
1049
1050         device->devid = btrfs_device_id(leaf, dev_item);
1051         device->total_bytes = btrfs_device_total_bytes(leaf, dev_item);
1052         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
1053         device->type = btrfs_device_type(leaf, dev_item);
1054         device->io_align = btrfs_device_io_align(leaf, dev_item);
1055         device->io_width = btrfs_device_io_width(leaf, dev_item);
1056         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
1057
1058         ptr = (unsigned long)btrfs_device_uuid(dev_item);
1059         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_DEV_UUID_SIZE);
1060
1061         return 0;
1062 }
1063
1064 static int read_one_dev(struct btrfs_root *root,
1065                         struct extent_buffer *leaf,
1066                         struct btrfs_dev_item *dev_item)
1067 {
1068         struct btrfs_device *device;
1069         u64 devid;
1070         int ret;
1071
1072         devid = btrfs_device_id(leaf, dev_item);
1073         device = btrfs_find_device(root, devid);
1074         if (!device) {
1075                 printk("warning devid %Lu not found already\n", devid);
1076                 device = kmalloc(sizeof(*device), GFP_NOFS);
1077                 if (!device)
1078                         return -ENOMEM;
1079                 list_add(&device->dev_list,
1080                          &root->fs_info->fs_devices->devices);
1081                 device->total_ios = 0;
1082                 spin_lock_init(&device->io_lock);
1083         }
1084
1085         fill_device_from_item(leaf, dev_item, device);
1086         device->dev_root = root->fs_info->dev_root;
1087         ret = 0;
1088 #if 0
1089         ret = btrfs_open_device(device);
1090         if (ret) {
1091                 kfree(device);
1092         }
1093 #endif
1094         return ret;
1095 }
1096
1097 int btrfs_read_super_device(struct btrfs_root *root, struct extent_buffer *buf)
1098 {
1099         struct btrfs_dev_item *dev_item;
1100
1101         dev_item = (struct btrfs_dev_item *)offsetof(struct btrfs_super_block,
1102                                                      dev_item);
1103         return read_one_dev(root, buf, dev_item);
1104 }
1105
1106 int btrfs_read_sys_array(struct btrfs_root *root)
1107 {
1108         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1109         struct extent_buffer *sb = root->fs_info->sb_buffer;
1110         struct btrfs_disk_key *disk_key;
1111         struct btrfs_chunk *chunk;
1112         struct btrfs_key key;
1113         u32 num_stripes;
1114         u32 array_size;
1115         u32 len = 0;
1116         u8 *ptr;
1117         unsigned long sb_ptr;
1118         u32 cur;
1119         int ret;
1120
1121         array_size = btrfs_super_sys_array_size(super_copy);
1122
1123         /*
1124          * we do this loop twice, once for the device items and
1125          * once for all of the chunks.  This way there are device
1126          * structs filled in for every chunk
1127          */
1128         ptr = super_copy->sys_chunk_array;
1129         sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
1130         cur = 0;
1131
1132         while (cur < array_size) {
1133                 disk_key = (struct btrfs_disk_key *)ptr;
1134                 btrfs_disk_key_to_cpu(&key, disk_key);
1135
1136                 len = sizeof(*disk_key);
1137                 ptr += len;
1138                 sb_ptr += len;
1139                 cur += len;
1140
1141                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1142                         chunk = (struct btrfs_chunk *)sb_ptr;
1143                         ret = read_one_chunk(root, &key, sb, chunk);
1144                         BUG_ON(ret);
1145                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
1146                         len = btrfs_chunk_item_size(num_stripes);
1147                 } else {
1148                         BUG();
1149                 }
1150                 ptr += len;
1151                 sb_ptr += len;
1152                 cur += len;
1153         }
1154         return 0;
1155 }
1156
1157 int btrfs_read_chunk_tree(struct btrfs_root *root)
1158 {
1159         struct btrfs_path *path;
1160         struct extent_buffer *leaf;
1161         struct btrfs_key key;
1162         struct btrfs_key found_key;
1163         int ret;
1164         int slot;
1165
1166         root = root->fs_info->chunk_root;
1167
1168         path = btrfs_alloc_path();
1169         if (!path)
1170                 return -ENOMEM;
1171
1172         /* first we search for all of the device items, and then we
1173          * read in all of the chunk items.  This way we can create chunk
1174          * mappings that reference all of the devices that are afound
1175          */
1176         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1177         key.offset = 0;
1178         key.type = 0;
1179 again:
1180         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1181         while(1) {
1182                 leaf = path->nodes[0];
1183                 slot = path->slots[0];
1184                 if (slot >= btrfs_header_nritems(leaf)) {
1185                         ret = btrfs_next_leaf(root, path);
1186                         if (ret == 0)
1187                                 continue;
1188                         if (ret < 0)
1189                                 goto error;
1190                         break;
1191                 }
1192                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1193                 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
1194                         if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
1195                                 break;
1196                         if (found_key.type == BTRFS_DEV_ITEM_KEY) {
1197                                 struct btrfs_dev_item *dev_item;
1198                                 dev_item = btrfs_item_ptr(leaf, slot,
1199                                                   struct btrfs_dev_item);
1200                                 ret = read_one_dev(root, leaf, dev_item);
1201                                 BUG_ON(ret);
1202                         }
1203                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
1204                         struct btrfs_chunk *chunk;
1205                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
1206                         ret = read_one_chunk(root, &found_key, leaf, chunk);
1207                 }
1208                 path->slots[0]++;
1209         }
1210         if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
1211                 key.objectid = 0;
1212                 btrfs_release_path(root, path);
1213                 goto again;
1214         }
1215
1216         btrfs_free_path(path);
1217         ret = 0;
1218 error:
1219         return ret;
1220 }
1221