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