btrfs-progs: btrfs_list_get_path_rootid error handling
[platform/upstream/btrfs-progs.git] / 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 #define _XOPEN_SOURCE 600
19 #define __USE_XOPEN2K
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <uuid/uuid.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include "ctree.h"
28 #include "disk-io.h"
29 #include "transaction.h"
30 #include "print-tree.h"
31 #include "volumes.h"
32
33 struct stripe {
34         struct btrfs_device *dev;
35         u64 physical;
36 };
37
38 static inline int nr_parity_stripes(struct map_lookup *map)
39 {
40         if (map->type & BTRFS_BLOCK_GROUP_RAID5)
41                 return 1;
42         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
43                 return 2;
44         else
45                 return 0;
46 }
47
48 static inline int nr_data_stripes(struct map_lookup *map)
49 {
50         return map->num_stripes - nr_parity_stripes(map);
51 }
52
53 #define is_parity_stripe(x) ( ((x) == BTRFS_RAID5_P_STRIPE) || ((x) == BTRFS_RAID6_Q_STRIPE) )
54
55 #define map_lookup_size(n) (sizeof(struct map_lookup) + \
56                             (sizeof(struct btrfs_bio_stripe) * (n)))
57
58 static LIST_HEAD(fs_uuids);
59
60 static struct btrfs_device *__find_device(struct list_head *head, u64 devid,
61                                           u8 *uuid)
62 {
63         struct btrfs_device *dev;
64         struct list_head *cur;
65
66         list_for_each(cur, head) {
67                 dev = list_entry(cur, struct btrfs_device, dev_list);
68                 if (dev->devid == devid &&
69                     !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE)) {
70                         return dev;
71                 }
72         }
73         return NULL;
74 }
75
76 static struct btrfs_fs_devices *find_fsid(u8 *fsid)
77 {
78         struct list_head *cur;
79         struct btrfs_fs_devices *fs_devices;
80
81         list_for_each(cur, &fs_uuids) {
82                 fs_devices = list_entry(cur, struct btrfs_fs_devices, list);
83                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
84                         return fs_devices;
85         }
86         return NULL;
87 }
88
89 static int device_list_add(const char *path,
90                            struct btrfs_super_block *disk_super,
91                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
92 {
93         struct btrfs_device *device;
94         struct btrfs_fs_devices *fs_devices;
95         u64 found_transid = btrfs_super_generation(disk_super);
96
97         fs_devices = find_fsid(disk_super->fsid);
98         if (!fs_devices) {
99                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
100                 if (!fs_devices)
101                         return -ENOMEM;
102                 INIT_LIST_HEAD(&fs_devices->devices);
103                 list_add(&fs_devices->list, &fs_uuids);
104                 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
105                 fs_devices->latest_devid = devid;
106                 fs_devices->latest_trans = found_transid;
107                 fs_devices->lowest_devid = (u64)-1;
108                 device = NULL;
109         } else {
110                 device = __find_device(&fs_devices->devices, devid,
111                                        disk_super->dev_item.uuid);
112         }
113         if (!device) {
114                 device = kzalloc(sizeof(*device), GFP_NOFS);
115                 if (!device) {
116                         /* we can safely leave the fs_devices entry around */
117                         return -ENOMEM;
118                 }
119                 device->devid = devid;
120                 memcpy(device->uuid, disk_super->dev_item.uuid,
121                        BTRFS_UUID_SIZE);
122                 device->name = kstrdup(path, GFP_NOFS);
123                 if (!device->name) {
124                         kfree(device);
125                         return -ENOMEM;
126                 }
127                 device->label = kstrdup(disk_super->label, GFP_NOFS);
128                 device->total_devs = btrfs_super_num_devices(disk_super);
129                 device->super_bytes_used = btrfs_super_bytes_used(disk_super);
130                 device->total_bytes =
131                         btrfs_stack_device_total_bytes(&disk_super->dev_item);
132                 device->bytes_used =
133                         btrfs_stack_device_bytes_used(&disk_super->dev_item);
134                 list_add(&device->dev_list, &fs_devices->devices);
135                 device->fs_devices = fs_devices;
136         } else if (!device->name || strcmp(device->name, path)) {
137                 char *name = strdup(path);
138                 if (!name)
139                         return -ENOMEM;
140                 kfree(device->name);
141                 device->name = name;
142         }
143
144
145         if (found_transid > fs_devices->latest_trans) {
146                 fs_devices->latest_devid = devid;
147                 fs_devices->latest_trans = found_transid;
148         }
149         if (fs_devices->lowest_devid > devid) {
150                 fs_devices->lowest_devid = devid;
151         }
152         *fs_devices_ret = fs_devices;
153         return 0;
154 }
155
156 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
157 {
158         struct btrfs_fs_devices *seed_devices;
159         struct list_head *cur;
160         struct btrfs_device *device;
161 again:
162         list_for_each(cur, &fs_devices->devices) {
163                 device = list_entry(cur, struct btrfs_device, dev_list);
164                 close(device->fd);
165                 device->fd = -1;
166                 device->writeable = 0;
167         }
168
169         seed_devices = fs_devices->seed;
170         fs_devices->seed = NULL;
171         if (seed_devices) {
172                 fs_devices = seed_devices;
173                 goto again;
174         }
175
176         return 0;
177 }
178
179 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices, int flags)
180 {
181         int fd;
182         struct list_head *head = &fs_devices->devices;
183         struct list_head *cur;
184         struct btrfs_device *device;
185         int ret;
186
187         list_for_each(cur, head) {
188                 device = list_entry(cur, struct btrfs_device, dev_list);
189
190                 fd = open(device->name, flags);
191                 if (fd < 0) {
192                         ret = -errno;
193                         goto fail;
194                 }
195
196                 posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
197
198                 if (device->devid == fs_devices->latest_devid)
199                         fs_devices->latest_bdev = fd;
200                 if (device->devid == fs_devices->lowest_devid)
201                         fs_devices->lowest_bdev = fd;
202                 device->fd = fd;
203                 if (flags == O_RDWR)
204                         device->writeable = 1;
205         }
206         return 0;
207 fail:
208         btrfs_close_devices(fs_devices);
209         return ret;
210 }
211
212 int btrfs_scan_one_device(int fd, const char *path,
213                           struct btrfs_fs_devices **fs_devices_ret,
214                           u64 *total_devs, u64 super_offset)
215 {
216         struct btrfs_super_block *disk_super;
217         char *buf;
218         int ret;
219         u64 devid;
220         char uuidbuf[37];
221
222         buf = malloc(4096);
223         if (!buf) {
224                 ret = -ENOMEM;
225                 goto error;
226         }
227         disk_super = (struct btrfs_super_block *)buf;
228         ret = btrfs_read_dev_super(fd, disk_super, super_offset);
229         if (ret < 0) {
230                 ret = -EIO;
231                 goto error_brelse;
232         }
233         devid = le64_to_cpu(disk_super->dev_item.devid);
234         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_METADUMP)
235                 *total_devs = 1;
236         else
237                 *total_devs = btrfs_super_num_devices(disk_super);
238         uuid_unparse(disk_super->fsid, uuidbuf);
239
240         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
241
242 error_brelse:
243         free(buf);
244 error:
245         return ret;
246 }
247
248 /*
249  * this uses a pretty simple search, the expectation is that it is
250  * called very infrequently and that a given device has a small number
251  * of extents
252  */
253 static int find_free_dev_extent(struct btrfs_trans_handle *trans,
254                                 struct btrfs_device *device,
255                                 struct btrfs_path *path,
256                                 u64 num_bytes, u64 *start)
257 {
258         struct btrfs_key key;
259         struct btrfs_root *root = device->dev_root;
260         struct btrfs_dev_extent *dev_extent = NULL;
261         u64 hole_size = 0;
262         u64 last_byte = 0;
263         u64 search_start = 0;
264         u64 search_end = device->total_bytes;
265         int ret;
266         int slot = 0;
267         int start_found;
268         struct extent_buffer *l;
269
270         start_found = 0;
271         path->reada = 2;
272
273         /* FIXME use last free of some kind */
274
275         /* we don't want to overwrite the superblock on the drive,
276          * so we make sure to start at an offset of at least 1MB
277          */
278         search_start = max((u64)1024 * 1024, search_start);
279
280         if (root->fs_info->alloc_start + num_bytes <= device->total_bytes)
281                 search_start = max(root->fs_info->alloc_start, search_start);
282
283         key.objectid = device->devid;
284         key.offset = search_start;
285         key.type = BTRFS_DEV_EXTENT_KEY;
286         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
287         if (ret < 0)
288                 goto error;
289         ret = btrfs_previous_item(root, path, 0, key.type);
290         if (ret < 0)
291                 goto error;
292         l = path->nodes[0];
293         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
294         while (1) {
295                 l = path->nodes[0];
296                 slot = path->slots[0];
297                 if (slot >= btrfs_header_nritems(l)) {
298                         ret = btrfs_next_leaf(root, path);
299                         if (ret == 0)
300                                 continue;
301                         if (ret < 0)
302                                 goto error;
303 no_more_items:
304                         if (!start_found) {
305                                 if (search_start >= search_end) {
306                                         ret = -ENOSPC;
307                                         goto error;
308                                 }
309                                 *start = search_start;
310                                 start_found = 1;
311                                 goto check_pending;
312                         }
313                         *start = last_byte > search_start ?
314                                 last_byte : search_start;
315                         if (search_end <= *start) {
316                                 ret = -ENOSPC;
317                                 goto error;
318                         }
319                         goto check_pending;
320                 }
321                 btrfs_item_key_to_cpu(l, &key, slot);
322
323                 if (key.objectid < device->devid)
324                         goto next;
325
326                 if (key.objectid > device->devid)
327                         goto no_more_items;
328
329                 if (key.offset >= search_start && key.offset > last_byte &&
330                     start_found) {
331                         if (last_byte < search_start)
332                                 last_byte = search_start;
333                         hole_size = key.offset - last_byte;
334                         if (key.offset > last_byte &&
335                             hole_size >= num_bytes) {
336                                 *start = last_byte;
337                                 goto check_pending;
338                         }
339                 }
340                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY) {
341                         goto next;
342                 }
343
344                 start_found = 1;
345                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
346                 last_byte = key.offset + btrfs_dev_extent_length(l, dev_extent);
347 next:
348                 path->slots[0]++;
349                 cond_resched();
350         }
351 check_pending:
352         /* we have to make sure we didn't find an extent that has already
353          * been allocated by the map tree or the original allocation
354          */
355         btrfs_release_path(root, path);
356         BUG_ON(*start < search_start);
357
358         if (*start + num_bytes > search_end) {
359                 ret = -ENOSPC;
360                 goto error;
361         }
362         /* check for pending inserts here */
363         return 0;
364
365 error:
366         btrfs_release_path(root, path);
367         return ret;
368 }
369
370 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
371                            struct btrfs_device *device,
372                            u64 chunk_tree, u64 chunk_objectid,
373                            u64 chunk_offset,
374                            u64 num_bytes, u64 *start)
375 {
376         int ret;
377         struct btrfs_path *path;
378         struct btrfs_root *root = device->dev_root;
379         struct btrfs_dev_extent *extent;
380         struct extent_buffer *leaf;
381         struct btrfs_key key;
382
383         path = btrfs_alloc_path();
384         if (!path)
385                 return -ENOMEM;
386
387         ret = find_free_dev_extent(trans, device, path, num_bytes, start);
388         if (ret) {
389                 goto err;
390         }
391
392         key.objectid = device->devid;
393         key.offset = *start;
394         key.type = BTRFS_DEV_EXTENT_KEY;
395         ret = btrfs_insert_empty_item(trans, root, path, &key,
396                                       sizeof(*extent));
397         BUG_ON(ret);
398
399         leaf = path->nodes[0];
400         extent = btrfs_item_ptr(leaf, path->slots[0],
401                                 struct btrfs_dev_extent);
402         btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
403         btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
404         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
405
406         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
407                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
408                     BTRFS_UUID_SIZE);
409
410         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
411         btrfs_mark_buffer_dirty(leaf);
412 err:
413         btrfs_free_path(path);
414         return ret;
415 }
416
417 static int find_next_chunk(struct btrfs_root *root, u64 objectid, u64 *offset)
418 {
419         struct btrfs_path *path;
420         int ret;
421         struct btrfs_key key;
422         struct btrfs_chunk *chunk;
423         struct btrfs_key found_key;
424
425         path = btrfs_alloc_path();
426         BUG_ON(!path);
427
428         key.objectid = objectid;
429         key.offset = (u64)-1;
430         key.type = BTRFS_CHUNK_ITEM_KEY;
431
432         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
433         if (ret < 0)
434                 goto error;
435
436         BUG_ON(ret == 0);
437
438         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
439         if (ret) {
440                 *offset = 0;
441         } else {
442                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
443                                       path->slots[0]);
444                 if (found_key.objectid != objectid)
445                         *offset = 0;
446                 else {
447                         chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
448                                                struct btrfs_chunk);
449                         *offset = found_key.offset +
450                                 btrfs_chunk_length(path->nodes[0], chunk);
451                 }
452         }
453         ret = 0;
454 error:
455         btrfs_free_path(path);
456         return ret;
457 }
458
459 static int find_next_devid(struct btrfs_root *root, struct btrfs_path *path,
460                            u64 *objectid)
461 {
462         int ret;
463         struct btrfs_key key;
464         struct btrfs_key found_key;
465
466         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
467         key.type = BTRFS_DEV_ITEM_KEY;
468         key.offset = (u64)-1;
469
470         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
471         if (ret < 0)
472                 goto error;
473
474         BUG_ON(ret == 0);
475
476         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
477                                   BTRFS_DEV_ITEM_KEY);
478         if (ret) {
479                 *objectid = 1;
480         } else {
481                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
482                                       path->slots[0]);
483                 *objectid = found_key.offset + 1;
484         }
485         ret = 0;
486 error:
487         btrfs_release_path(root, path);
488         return ret;
489 }
490
491 /*
492  * the device information is stored in the chunk root
493  * the btrfs_device struct should be fully filled in
494  */
495 int btrfs_add_device(struct btrfs_trans_handle *trans,
496                      struct btrfs_root *root,
497                      struct btrfs_device *device)
498 {
499         int ret;
500         struct btrfs_path *path;
501         struct btrfs_dev_item *dev_item;
502         struct extent_buffer *leaf;
503         struct btrfs_key key;
504         unsigned long ptr;
505         u64 free_devid = 0;
506
507         root = root->fs_info->chunk_root;
508
509         path = btrfs_alloc_path();
510         if (!path)
511                 return -ENOMEM;
512
513         ret = find_next_devid(root, path, &free_devid);
514         if (ret)
515                 goto out;
516
517         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
518         key.type = BTRFS_DEV_ITEM_KEY;
519         key.offset = free_devid;
520
521         ret = btrfs_insert_empty_item(trans, root, path, &key,
522                                       sizeof(*dev_item));
523         if (ret)
524                 goto out;
525
526         leaf = path->nodes[0];
527         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
528
529         device->devid = free_devid;
530         btrfs_set_device_id(leaf, dev_item, device->devid);
531         btrfs_set_device_generation(leaf, dev_item, 0);
532         btrfs_set_device_type(leaf, dev_item, device->type);
533         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
534         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
535         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
536         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
537         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
538         btrfs_set_device_group(leaf, dev_item, 0);
539         btrfs_set_device_seek_speed(leaf, dev_item, 0);
540         btrfs_set_device_bandwidth(leaf, dev_item, 0);
541         btrfs_set_device_start_offset(leaf, dev_item, 0);
542
543         ptr = (unsigned long)btrfs_device_uuid(dev_item);
544         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
545         ptr = (unsigned long)btrfs_device_fsid(dev_item);
546         write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
547         btrfs_mark_buffer_dirty(leaf);
548         ret = 0;
549
550 out:
551         btrfs_free_path(path);
552         return ret;
553 }
554
555 int btrfs_update_device(struct btrfs_trans_handle *trans,
556                         struct btrfs_device *device)
557 {
558         int ret;
559         struct btrfs_path *path;
560         struct btrfs_root *root;
561         struct btrfs_dev_item *dev_item;
562         struct extent_buffer *leaf;
563         struct btrfs_key key;
564
565         root = device->dev_root->fs_info->chunk_root;
566
567         path = btrfs_alloc_path();
568         if (!path)
569                 return -ENOMEM;
570
571         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
572         key.type = BTRFS_DEV_ITEM_KEY;
573         key.offset = device->devid;
574
575         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
576         if (ret < 0)
577                 goto out;
578
579         if (ret > 0) {
580                 ret = -ENOENT;
581                 goto out;
582         }
583
584         leaf = path->nodes[0];
585         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
586
587         btrfs_set_device_id(leaf, dev_item, device->devid);
588         btrfs_set_device_type(leaf, dev_item, device->type);
589         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
590         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
591         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
592         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
593         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
594         btrfs_mark_buffer_dirty(leaf);
595
596 out:
597         btrfs_free_path(path);
598         return ret;
599 }
600
601 int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
602                            struct btrfs_root *root,
603                            struct btrfs_key *key,
604                            struct btrfs_chunk *chunk, int item_size)
605 {
606         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
607         struct btrfs_disk_key disk_key;
608         u32 array_size;
609         u8 *ptr;
610
611         array_size = btrfs_super_sys_array_size(super_copy);
612         if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
613                 return -EFBIG;
614
615         ptr = super_copy->sys_chunk_array + array_size;
616         btrfs_cpu_key_to_disk(&disk_key, key);
617         memcpy(ptr, &disk_key, sizeof(disk_key));
618         ptr += sizeof(disk_key);
619         memcpy(ptr, chunk, item_size);
620         item_size += sizeof(disk_key);
621         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
622         return 0;
623 }
624
625 static u64 div_factor(u64 num, int factor)
626 {
627         if (factor == 10)
628                 return num;
629         num *= factor;
630         return num / 10;
631 }
632
633 static u64 chunk_bytes_by_type(u64 type, u64 calc_size, int num_stripes,
634                                int sub_stripes)
635 {
636         if (type & (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP))
637                 return calc_size;
638         else if (type & BTRFS_BLOCK_GROUP_RAID10)
639                 return calc_size * (num_stripes / sub_stripes);
640         else if (type & BTRFS_BLOCK_GROUP_RAID5)
641                 return calc_size * (num_stripes - 1);
642         else if (type & BTRFS_BLOCK_GROUP_RAID6)
643                 return calc_size * (num_stripes - 2);
644         else
645                 return calc_size * num_stripes;
646 }
647
648
649 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
650 {
651         /* TODO, add a way to store the preferred stripe size */
652         return 64 * 1024;
653 }
654
655 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
656                       struct btrfs_root *extent_root, u64 *start,
657                       u64 *num_bytes, u64 type)
658 {
659         u64 dev_offset;
660         struct btrfs_fs_info *info = extent_root->fs_info;
661         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
662         struct btrfs_stripe *stripes;
663         struct btrfs_device *device = NULL;
664         struct btrfs_chunk *chunk;
665         struct list_head private_devs;
666         struct list_head *dev_list = &extent_root->fs_info->fs_devices->devices;
667         struct list_head *cur;
668         struct map_lookup *map;
669         int min_stripe_size = 1 * 1024 * 1024;
670         u64 calc_size = 8 * 1024 * 1024;
671         u64 min_free;
672         u64 max_chunk_size = 4 * calc_size;
673         u64 avail;
674         u64 max_avail = 0;
675         u64 percent_max;
676         int num_stripes = 1;
677         int min_stripes = 1;
678         int sub_stripes = 0;
679         int looped = 0;
680         int ret;
681         int index;
682         int stripe_len = 64 * 1024;
683         struct btrfs_key key;
684         u64 offset;
685
686         if (list_empty(dev_list)) {
687                 return -ENOSPC;
688         }
689
690         if (type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
691                     BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
692                     BTRFS_BLOCK_GROUP_RAID10 |
693                     BTRFS_BLOCK_GROUP_DUP)) {
694                 if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
695                         calc_size = 8 * 1024 * 1024;
696                         max_chunk_size = calc_size * 2;
697                         min_stripe_size = 1 * 1024 * 1024;
698                 } else if (type & BTRFS_BLOCK_GROUP_DATA) {
699                         calc_size = 1024 * 1024 * 1024;
700                         max_chunk_size = 10 * calc_size;
701                         min_stripe_size = 64 * 1024 * 1024;
702                 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
703                         calc_size = 1024 * 1024 * 1024;
704                         max_chunk_size = 4 * calc_size;
705                         min_stripe_size = 32 * 1024 * 1024;
706                 }
707         }
708         if (type & BTRFS_BLOCK_GROUP_RAID1) {
709                 num_stripes = min_t(u64, 2,
710                                   btrfs_super_num_devices(&info->super_copy));
711                 if (num_stripes < 2)
712                         return -ENOSPC;
713                 min_stripes = 2;
714         }
715         if (type & BTRFS_BLOCK_GROUP_DUP) {
716                 num_stripes = 2;
717                 min_stripes = 2;
718         }
719         if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
720                 num_stripes = btrfs_super_num_devices(&info->super_copy);
721                 min_stripes = 2;
722         }
723         if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
724                 num_stripes = btrfs_super_num_devices(&info->super_copy);
725                 if (num_stripes < 4)
726                         return -ENOSPC;
727                 num_stripes &= ~(u32)1;
728                 sub_stripes = 2;
729                 min_stripes = 4;
730         }
731         if (type & (BTRFS_BLOCK_GROUP_RAID5)) {
732                 num_stripes = btrfs_super_num_devices(&info->super_copy);
733                 if (num_stripes < 2)
734                         return -ENOSPC;
735                 min_stripes = 2;
736                 stripe_len = find_raid56_stripe_len(num_stripes - 1,
737                                     btrfs_super_stripesize(&info->super_copy));
738         }
739         if (type & (BTRFS_BLOCK_GROUP_RAID6)) {
740                 num_stripes = btrfs_super_num_devices(&info->super_copy);
741                 if (num_stripes < 3)
742                         return -ENOSPC;
743                 min_stripes = 3;
744                 stripe_len = find_raid56_stripe_len(num_stripes - 2,
745                                     btrfs_super_stripesize(&info->super_copy));
746         }
747
748         /* we don't want a chunk larger than 10% of the FS */
749         percent_max = div_factor(btrfs_super_total_bytes(&info->super_copy), 1);
750         max_chunk_size = min(percent_max, max_chunk_size);
751
752 again:
753         if (chunk_bytes_by_type(type, calc_size, num_stripes, sub_stripes) >
754             max_chunk_size) {
755                 calc_size = max_chunk_size;
756                 calc_size /= num_stripes;
757                 calc_size /= stripe_len;
758                 calc_size *= stripe_len;
759         }
760         /* we don't want tiny stripes */
761         calc_size = max_t(u64, calc_size, min_stripe_size);
762
763         calc_size /= stripe_len;
764         calc_size *= stripe_len;
765         INIT_LIST_HEAD(&private_devs);
766         cur = dev_list->next;
767         index = 0;
768
769         if (type & BTRFS_BLOCK_GROUP_DUP)
770                 min_free = calc_size * 2;
771         else
772                 min_free = calc_size;
773
774         /* build a private list of devices we will allocate from */
775         while(index < num_stripes) {
776                 device = list_entry(cur, struct btrfs_device, dev_list);
777                 avail = device->total_bytes - device->bytes_used;
778                 cur = cur->next;
779                 if (avail >= min_free) {
780                         list_move_tail(&device->dev_list, &private_devs);
781                         index++;
782                         if (type & BTRFS_BLOCK_GROUP_DUP)
783                                 index++;
784                 } else if (avail > max_avail)
785                         max_avail = avail;
786                 if (cur == dev_list)
787                         break;
788         }
789         if (index < num_stripes) {
790                 list_splice(&private_devs, dev_list);
791                 if (index >= min_stripes) {
792                         num_stripes = index;
793                         if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
794                                 num_stripes /= sub_stripes;
795                                 num_stripes *= sub_stripes;
796                         }
797                         looped = 1;
798                         goto again;
799                 }
800                 if (!looped && max_avail > 0) {
801                         looped = 1;
802                         calc_size = max_avail;
803                         goto again;
804                 }
805                 return -ENOSPC;
806         }
807         ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
808                               &offset);
809         if (ret)
810                 return ret;
811         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
812         key.type = BTRFS_CHUNK_ITEM_KEY;
813         key.offset = offset;
814
815         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
816         if (!chunk)
817                 return -ENOMEM;
818
819         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
820         if (!map) {
821                 kfree(chunk);
822                 return -ENOMEM;
823         }
824
825         stripes = &chunk->stripe;
826         *num_bytes = chunk_bytes_by_type(type, calc_size,
827                                          num_stripes, sub_stripes);
828         index = 0;
829         while(index < num_stripes) {
830                 struct btrfs_stripe *stripe;
831                 BUG_ON(list_empty(&private_devs));
832                 cur = private_devs.next;
833                 device = list_entry(cur, struct btrfs_device, dev_list);
834
835                 /* loop over this device again if we're doing a dup group */
836                 if (!(type & BTRFS_BLOCK_GROUP_DUP) ||
837                     (index == num_stripes - 1))
838                         list_move_tail(&device->dev_list, dev_list);
839
840                 ret = btrfs_alloc_dev_extent(trans, device,
841                              info->chunk_root->root_key.objectid,
842                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
843                              calc_size, &dev_offset);
844                 BUG_ON(ret);
845
846                 device->bytes_used += calc_size;
847                 ret = btrfs_update_device(trans, device);
848                 BUG_ON(ret);
849
850                 map->stripes[index].dev = device;
851                 map->stripes[index].physical = dev_offset;
852                 stripe = stripes + index;
853                 btrfs_set_stack_stripe_devid(stripe, device->devid);
854                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
855                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
856                 index++;
857         }
858         BUG_ON(!list_empty(&private_devs));
859
860         /* key was set above */
861         btrfs_set_stack_chunk_length(chunk, *num_bytes);
862         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
863         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
864         btrfs_set_stack_chunk_type(chunk, type);
865         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
866         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
867         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
868         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
869         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
870         map->sector_size = extent_root->sectorsize;
871         map->stripe_len = stripe_len;
872         map->io_align = stripe_len;
873         map->io_width = stripe_len;
874         map->type = type;
875         map->num_stripes = num_stripes;
876         map->sub_stripes = sub_stripes;
877
878         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
879                                 btrfs_chunk_item_size(num_stripes));
880         BUG_ON(ret);
881         *start = key.offset;;
882
883         map->ce.start = key.offset;
884         map->ce.size = *num_bytes;
885
886         ret = insert_existing_cache_extent(
887                            &extent_root->fs_info->mapping_tree.cache_tree,
888                            &map->ce);
889         BUG_ON(ret);
890
891         if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
892                 ret = btrfs_add_system_chunk(trans, chunk_root, &key,
893                                     chunk, btrfs_chunk_item_size(num_stripes));
894                 BUG_ON(ret);
895         }
896
897         kfree(chunk);
898         return ret;
899 }
900
901 int btrfs_alloc_data_chunk(struct btrfs_trans_handle *trans,
902                            struct btrfs_root *extent_root, u64 *start,
903                            u64 num_bytes, u64 type)
904 {
905         u64 dev_offset;
906         struct btrfs_fs_info *info = extent_root->fs_info;
907         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
908         struct btrfs_stripe *stripes;
909         struct btrfs_device *device = NULL;
910         struct btrfs_chunk *chunk;
911         struct list_head *dev_list = &extent_root->fs_info->fs_devices->devices;
912         struct list_head *cur;
913         struct map_lookup *map;
914         u64 calc_size = 8 * 1024 * 1024;
915         int num_stripes = 1;
916         int sub_stripes = 0;
917         int ret;
918         int index;
919         int stripe_len = 64 * 1024;
920         struct btrfs_key key;
921
922         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
923         key.type = BTRFS_CHUNK_ITEM_KEY;
924         ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
925                               &key.offset);
926         if (ret)
927                 return ret;
928
929         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
930         if (!chunk)
931                 return -ENOMEM;
932
933         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
934         if (!map) {
935                 kfree(chunk);
936                 return -ENOMEM;
937         }
938
939         stripes = &chunk->stripe;
940         calc_size = num_bytes;
941
942         index = 0;
943         cur = dev_list->next;
944         device = list_entry(cur, struct btrfs_device, dev_list);
945
946         while (index < num_stripes) {
947                 struct btrfs_stripe *stripe;
948
949                 ret = btrfs_alloc_dev_extent(trans, device,
950                              info->chunk_root->root_key.objectid,
951                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
952                              calc_size, &dev_offset);
953                 BUG_ON(ret);
954
955                 device->bytes_used += calc_size;
956                 ret = btrfs_update_device(trans, device);
957                 BUG_ON(ret);
958
959                 map->stripes[index].dev = device;
960                 map->stripes[index].physical = dev_offset;
961                 stripe = stripes + index;
962                 btrfs_set_stack_stripe_devid(stripe, device->devid);
963                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
964                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
965                 index++;
966         }
967
968         /* key was set above */
969         btrfs_set_stack_chunk_length(chunk, num_bytes);
970         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
971         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
972         btrfs_set_stack_chunk_type(chunk, type);
973         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
974         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
975         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
976         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
977         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
978         map->sector_size = extent_root->sectorsize;
979         map->stripe_len = stripe_len;
980         map->io_align = stripe_len;
981         map->io_width = stripe_len;
982         map->type = type;
983         map->num_stripes = num_stripes;
984         map->sub_stripes = sub_stripes;
985
986         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
987                                 btrfs_chunk_item_size(num_stripes));
988         BUG_ON(ret);
989         *start = key.offset;
990
991         map->ce.start = key.offset;
992         map->ce.size = num_bytes;
993
994         ret = insert_existing_cache_extent(
995                            &extent_root->fs_info->mapping_tree.cache_tree,
996                            &map->ce);
997         BUG_ON(ret);
998
999         kfree(chunk);
1000         return ret;
1001 }
1002
1003 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
1004 {
1005         cache_tree_init(&tree->cache_tree);
1006 }
1007
1008 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
1009 {
1010         struct cache_extent *ce;
1011         struct map_lookup *map;
1012         int ret;
1013
1014         ce = find_first_cache_extent(&map_tree->cache_tree, logical);
1015         BUG_ON(!ce);
1016         BUG_ON(ce->start > logical || ce->start + ce->size < logical);
1017         map = container_of(ce, struct map_lookup, ce);
1018
1019         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
1020                 ret = map->num_stripes;
1021         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1022                 ret = map->sub_stripes;
1023         else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
1024                 ret = 2;
1025         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1026                 ret = 3;
1027         else
1028                 ret = 1;
1029         return ret;
1030 }
1031
1032 int btrfs_next_metadata(struct btrfs_mapping_tree *map_tree, u64 *logical,
1033                         u64 *size)
1034 {
1035         struct cache_extent *ce;
1036         struct map_lookup *map;
1037
1038         ce = find_first_cache_extent(&map_tree->cache_tree, *logical);
1039
1040         while (ce) {
1041                 ce = next_cache_extent(ce);
1042                 if (!ce)
1043                         return -ENOENT;
1044
1045                 map = container_of(ce, struct map_lookup, ce);
1046                 if (map->type & BTRFS_BLOCK_GROUP_METADATA) {
1047                         *logical = ce->start;
1048                         *size = ce->size;
1049                         return 0;
1050                 }
1051         }
1052
1053         return -ENOENT;
1054 }
1055
1056 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
1057                      u64 chunk_start, u64 physical, u64 devid,
1058                      u64 **logical, int *naddrs, int *stripe_len)
1059 {
1060         struct cache_extent *ce;
1061         struct map_lookup *map;
1062         u64 *buf;
1063         u64 bytenr;
1064         u64 length;
1065         u64 stripe_nr;
1066         u64 rmap_len;
1067         int i, j, nr = 0;
1068
1069         ce = find_first_cache_extent(&map_tree->cache_tree, chunk_start);
1070         BUG_ON(!ce);
1071         map = container_of(ce, struct map_lookup, ce);
1072
1073         length = ce->size;
1074         rmap_len = map->stripe_len;
1075         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1076                 length = ce->size / (map->num_stripes / map->sub_stripes);
1077         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
1078                 length = ce->size / map->num_stripes;
1079         else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1080                               BTRFS_BLOCK_GROUP_RAID6)) {
1081                 length = ce->size / nr_data_stripes(map);
1082                 rmap_len = map->stripe_len * nr_data_stripes(map);
1083         }
1084
1085         buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1086
1087         for (i = 0; i < map->num_stripes; i++) {
1088                 if (devid && map->stripes[i].dev->devid != devid)
1089                         continue;
1090                 if (map->stripes[i].physical > physical ||
1091                     map->stripes[i].physical + length <= physical)
1092                         continue;
1093
1094                 stripe_nr = (physical - map->stripes[i].physical) /
1095                             map->stripe_len;
1096
1097                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1098                         stripe_nr = (stripe_nr * map->num_stripes + i) /
1099                                     map->sub_stripes;
1100                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1101                         stripe_nr = stripe_nr * map->num_stripes + i;
1102                 } /* else if RAID[56], multiply by nr_data_stripes().
1103                    * Alternatively, just use rmap_len below instead of
1104                    * map->stripe_len */
1105
1106                 bytenr = ce->start + stripe_nr * rmap_len;
1107                 for (j = 0; j < nr; j++) {
1108                         if (buf[j] == bytenr)
1109                                 break;
1110                 }
1111                 if (j == nr)
1112                         buf[nr++] = bytenr;
1113         }
1114
1115         *logical = buf;
1116         *naddrs = nr;
1117         *stripe_len = rmap_len;
1118
1119         return 0;
1120 }
1121
1122 static inline int parity_smaller(u64 a, u64 b)
1123 {
1124         return a > b;
1125 }
1126
1127 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
1128 static void sort_parity_stripes(struct btrfs_multi_bio *bbio, u64 *raid_map)
1129 {
1130         struct btrfs_bio_stripe s;
1131         int i;
1132         u64 l;
1133         int again = 1;
1134
1135         while (again) {
1136                 again = 0;
1137                 for (i = 0; i < bbio->num_stripes - 1; i++) {
1138                         if (parity_smaller(raid_map[i], raid_map[i+1])) {
1139                                 s = bbio->stripes[i];
1140                                 l = raid_map[i];
1141                                 bbio->stripes[i] = bbio->stripes[i+1];
1142                                 raid_map[i] = raid_map[i+1];
1143                                 bbio->stripes[i+1] = s;
1144                                 raid_map[i+1] = l;
1145                                 again = 1;
1146                         }
1147                 }
1148         }
1149 }
1150
1151 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1152                     u64 logical, u64 *length,
1153                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1154                     u64 **raid_map_ret)
1155 {
1156         return __btrfs_map_block(map_tree, rw, logical, length, NULL,
1157                                  multi_ret, mirror_num, raid_map_ret);
1158 }
1159
1160 int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1161                     u64 logical, u64 *length, u64 *type,
1162                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1163                     u64 **raid_map_ret)
1164 {
1165         struct cache_extent *ce;
1166         struct map_lookup *map;
1167         u64 offset;
1168         u64 stripe_offset;
1169         u64 stripe_nr;
1170         u64 *raid_map = NULL;
1171         int stripes_allocated = 8;
1172         int stripes_required = 1;
1173         int stripe_index;
1174         int i;
1175         struct btrfs_multi_bio *multi = NULL;
1176
1177         if (multi_ret && rw == READ) {
1178                 stripes_allocated = 1;
1179         }
1180 again:
1181         ce = find_first_cache_extent(&map_tree->cache_tree, logical);
1182         if (!ce) {
1183                 if (multi)
1184                         kfree(multi);
1185                 return -ENOENT;
1186         }
1187         if (ce->start > logical || ce->start + ce->size < logical) {
1188                 if (multi)
1189                         kfree(multi);
1190                 return -ENOENT;
1191         }
1192
1193         if (multi_ret) {
1194                 multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
1195                                 GFP_NOFS);
1196                 if (!multi)
1197                         return -ENOMEM;
1198         }
1199         map = container_of(ce, struct map_lookup, ce);
1200         offset = logical - ce->start;
1201
1202         if (rw == WRITE) {
1203                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
1204                                  BTRFS_BLOCK_GROUP_DUP)) {
1205                         stripes_required = map->num_stripes;
1206                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1207                         stripes_required = map->sub_stripes;
1208                 }
1209         }
1210         if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)
1211             && multi_ret && ((rw & WRITE) || mirror_num > 1) && raid_map_ret) {
1212                     /* RAID[56] write or recovery. Return all stripes */
1213                     stripes_required = map->num_stripes;
1214
1215                     /* Only allocate the map if we've already got a large enough multi_ret */
1216                     if (stripes_allocated >= stripes_required) {
1217                             raid_map = kmalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1218                             if (!raid_map) {
1219                                     kfree(multi);
1220                                     return -ENOMEM;
1221                             }
1222                     }
1223         }
1224
1225         /* if our multi bio struct is too small, back off and try again */
1226         if (multi_ret && stripes_allocated < stripes_required) {
1227                 stripes_allocated = stripes_required;
1228                 kfree(multi);
1229                 goto again;
1230         }
1231         stripe_nr = offset;
1232         /*
1233          * stripe_nr counts the total number of stripes we have to stride
1234          * to get to this block
1235          */
1236         stripe_nr = stripe_nr / map->stripe_len;
1237
1238         stripe_offset = stripe_nr * map->stripe_len;
1239         BUG_ON(offset < stripe_offset);
1240
1241         /* stripe_offset is the offset of this block in its stripe*/
1242         stripe_offset = offset - stripe_offset;
1243
1244         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1245                          BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
1246                          BTRFS_BLOCK_GROUP_RAID10 |
1247                          BTRFS_BLOCK_GROUP_DUP)) {
1248                 /* we limit the length of each bio to what fits in a stripe */
1249                 *length = min_t(u64, ce->size - offset,
1250                               map->stripe_len - stripe_offset);
1251         } else {
1252                 *length = ce->size - offset;
1253         }
1254
1255         if (!multi_ret)
1256                 goto out;
1257
1258         multi->num_stripes = 1;
1259         stripe_index = 0;
1260         if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1261                 if (rw == WRITE)
1262                         multi->num_stripes = map->num_stripes;
1263                 else if (mirror_num)
1264                         stripe_index = mirror_num - 1;
1265                 else
1266                         stripe_index = stripe_nr % map->num_stripes;
1267         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1268                 int factor = map->num_stripes / map->sub_stripes;
1269
1270                 stripe_index = stripe_nr % factor;
1271                 stripe_index *= map->sub_stripes;
1272
1273                 if (rw == WRITE)
1274                         multi->num_stripes = map->sub_stripes;
1275                 else if (mirror_num)
1276                         stripe_index += mirror_num - 1;
1277
1278                 stripe_nr = stripe_nr / factor;
1279         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
1280                 if (rw == WRITE)
1281                         multi->num_stripes = map->num_stripes;
1282                 else if (mirror_num)
1283                         stripe_index = mirror_num - 1;
1284         } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1285                                 BTRFS_BLOCK_GROUP_RAID6)) {
1286
1287                 if (raid_map) {
1288                         int i, rot;
1289                         u64 tmp;
1290                         u64 raid56_full_stripe_start;
1291                         u64 full_stripe_len = nr_data_stripes(map) * map->stripe_len;
1292
1293                         /*
1294                          * align the start of our data stripe in the logical
1295                          * address space
1296                          */
1297                         raid56_full_stripe_start = offset / full_stripe_len;
1298                         raid56_full_stripe_start *= full_stripe_len;
1299
1300                         /* get the data stripe number */
1301                         stripe_nr = raid56_full_stripe_start / map->stripe_len;
1302                         stripe_nr = stripe_nr / nr_data_stripes(map);
1303
1304                         /* Work out the disk rotation on this stripe-set */
1305                         rot = stripe_nr % map->num_stripes;
1306
1307                         /* Fill in the logical address of each stripe */
1308                         tmp = stripe_nr * nr_data_stripes(map);
1309
1310                         for (i = 0; i < nr_data_stripes(map); i++)
1311                                 raid_map[(i+rot) % map->num_stripes] =
1312                                         ce->start + (tmp + i) * map->stripe_len;
1313
1314                         raid_map[(i+rot) % map->num_stripes] = BTRFS_RAID5_P_STRIPE;
1315                         if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1316                                 raid_map[(i+rot+1) % map->num_stripes] = BTRFS_RAID6_Q_STRIPE;
1317
1318                         *length = map->stripe_len;
1319                         stripe_index = 0;
1320                         stripe_offset = 0;
1321                         multi->num_stripes = map->num_stripes;
1322                 } else {
1323                         stripe_index = stripe_nr % nr_data_stripes(map);
1324                         stripe_nr = stripe_nr / nr_data_stripes(map);
1325
1326                         /*
1327                          * Mirror #0 or #1 means the original data block.
1328                          * Mirror #2 is RAID5 parity block.
1329                          * Mirror #3 is RAID6 Q block.
1330                          */
1331                         if (mirror_num > 1)
1332                                 stripe_index = nr_data_stripes(map) + mirror_num - 2;
1333
1334                         /* We distribute the parity blocks across stripes */
1335                         stripe_index = (stripe_nr + stripe_index) % map->num_stripes;
1336                 }
1337         } else {
1338                 /*
1339                  * after this do_div call, stripe_nr is the number of stripes
1340                  * on this device we have to walk to find the data, and
1341                  * stripe_index is the number of our device in the stripe array
1342                  */
1343                 stripe_index = stripe_nr % map->num_stripes;
1344                 stripe_nr = stripe_nr / map->num_stripes;
1345         }
1346         BUG_ON(stripe_index >= map->num_stripes);
1347
1348         for (i = 0; i < multi->num_stripes; i++) {
1349                 multi->stripes[i].physical =
1350                         map->stripes[stripe_index].physical + stripe_offset +
1351                         stripe_nr * map->stripe_len;
1352                 multi->stripes[i].dev = map->stripes[stripe_index].dev;
1353                 stripe_index++;
1354         }
1355         *multi_ret = multi;
1356
1357         if (type)
1358                 *type = map->type;
1359
1360         if (raid_map) {
1361                 sort_parity_stripes(multi, raid_map);
1362                 *raid_map_ret = raid_map;
1363         }
1364 out:
1365         return 0;
1366 }
1367
1368 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
1369                                        u8 *uuid, u8 *fsid)
1370 {
1371         struct btrfs_device *device;
1372         struct btrfs_fs_devices *cur_devices;
1373
1374         cur_devices = root->fs_info->fs_devices;
1375         while (cur_devices) {
1376                 if (!fsid ||
1377                     !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
1378                         device = __find_device(&cur_devices->devices,
1379                                                devid, uuid);
1380                         if (device)
1381                                 return device;
1382                 }
1383                 cur_devices = cur_devices->seed;
1384         }
1385         return NULL;
1386 }
1387
1388 struct btrfs_device *btrfs_find_device_by_devid(struct btrfs_root *root,
1389                                                 u64 devid, int instance)
1390 {
1391         struct list_head *head = &root->fs_info->fs_devices->devices;
1392         struct btrfs_device *dev;
1393         struct list_head *cur;
1394         int num_found = 0;
1395
1396         list_for_each(cur, head) {
1397                 dev = list_entry(cur, struct btrfs_device, dev_list);
1398                 if (dev->devid == devid && num_found++ == instance)
1399                         return dev;
1400         }
1401         return NULL;
1402 }
1403
1404 int btrfs_bootstrap_super_map(struct btrfs_mapping_tree *map_tree,
1405                               struct btrfs_fs_devices *fs_devices)
1406 {
1407         struct map_lookup *map;
1408         u64 logical = BTRFS_SUPER_INFO_OFFSET;
1409         u64 length = BTRFS_SUPER_INFO_SIZE;
1410         int num_stripes = 0;
1411         int sub_stripes = 0;
1412         int ret;
1413         int i;
1414         struct list_head *cur;
1415
1416         list_for_each(cur, &fs_devices->devices) {
1417                 num_stripes++;
1418         }
1419         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
1420         if (!map)
1421                 return -ENOMEM;
1422
1423         map->ce.start = logical;
1424         map->ce.size = length;
1425         map->num_stripes = num_stripes;
1426         map->sub_stripes = sub_stripes;
1427         map->io_width = length;
1428         map->io_align = length;
1429         map->sector_size = length;
1430         map->stripe_len = length;
1431         map->type = BTRFS_BLOCK_GROUP_RAID1;
1432
1433         i = 0;
1434         list_for_each(cur, &fs_devices->devices) {
1435                 struct btrfs_device *device = list_entry(cur,
1436                                                          struct btrfs_device,
1437                                                          dev_list);
1438                 map->stripes[i].physical = logical;
1439                 map->stripes[i].dev = device;
1440                 i++;
1441         }
1442         ret = insert_existing_cache_extent(&map_tree->cache_tree, &map->ce);
1443         if (ret == -EEXIST) {
1444                 struct cache_extent *old;
1445                 struct map_lookup *old_map;
1446                 old = find_cache_extent(&map_tree->cache_tree, logical, length);
1447                 old_map = container_of(old, struct map_lookup, ce);
1448                 remove_cache_extent(&map_tree->cache_tree, old);
1449                 kfree(old_map);
1450                 ret = insert_existing_cache_extent(&map_tree->cache_tree,
1451                                                    &map->ce);
1452         }
1453         BUG_ON(ret);
1454         return 0;
1455 }
1456
1457 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
1458 {
1459         struct cache_extent *ce;
1460         struct map_lookup *map;
1461         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
1462         int readonly = 0;
1463         int i;
1464
1465         ce = find_first_cache_extent(&map_tree->cache_tree, chunk_offset);
1466         BUG_ON(!ce);
1467
1468         map = container_of(ce, struct map_lookup, ce);
1469         for (i = 0; i < map->num_stripes; i++) {
1470                 if (!map->stripes[i].dev->writeable) {
1471                         readonly = 1;
1472                         break;
1473                 }
1474         }
1475
1476         return readonly;
1477 }
1478
1479 static struct btrfs_device *fill_missing_device(u64 devid)
1480 {
1481         struct btrfs_device *device;
1482
1483         device = kzalloc(sizeof(*device), GFP_NOFS);
1484         device->devid = devid;
1485         device->fd = -1;
1486         return device;
1487 }
1488
1489 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
1490                           struct extent_buffer *leaf,
1491                           struct btrfs_chunk *chunk)
1492 {
1493         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
1494         struct map_lookup *map;
1495         struct cache_extent *ce;
1496         u64 logical;
1497         u64 length;
1498         u64 devid;
1499         u8 uuid[BTRFS_UUID_SIZE];
1500         int num_stripes;
1501         int ret;
1502         int i;
1503
1504         logical = key->offset;
1505         length = btrfs_chunk_length(leaf, chunk);
1506
1507         ce = find_first_cache_extent(&map_tree->cache_tree, logical);
1508
1509         /* already mapped? */
1510         if (ce && ce->start <= logical && ce->start + ce->size > logical) {
1511                 return 0;
1512         }
1513
1514         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1515         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
1516         if (!map)
1517                 return -ENOMEM;
1518
1519         map->ce.start = logical;
1520         map->ce.size = length;
1521         map->num_stripes = num_stripes;
1522         map->io_width = btrfs_chunk_io_width(leaf, chunk);
1523         map->io_align = btrfs_chunk_io_align(leaf, chunk);
1524         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
1525         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
1526         map->type = btrfs_chunk_type(leaf, chunk);
1527         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
1528
1529         for (i = 0; i < num_stripes; i++) {
1530                 map->stripes[i].physical =
1531                         btrfs_stripe_offset_nr(leaf, chunk, i);
1532                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
1533                 read_extent_buffer(leaf, uuid, (unsigned long)
1534                                    btrfs_stripe_dev_uuid_nr(chunk, i),
1535                                    BTRFS_UUID_SIZE);
1536                 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
1537                                                         NULL);
1538                 if (!map->stripes[i].dev) {
1539                         map->stripes[i].dev = fill_missing_device(devid);
1540                         printf("warning, device %llu is missing\n",
1541                                (unsigned long long)devid);
1542                 }
1543
1544         }
1545         ret = insert_existing_cache_extent(&map_tree->cache_tree, &map->ce);
1546         BUG_ON(ret);
1547
1548         return 0;
1549 }
1550
1551 static int fill_device_from_item(struct extent_buffer *leaf,
1552                                  struct btrfs_dev_item *dev_item,
1553                                  struct btrfs_device *device)
1554 {
1555         unsigned long ptr;
1556
1557         device->devid = btrfs_device_id(leaf, dev_item);
1558         device->total_bytes = btrfs_device_total_bytes(leaf, dev_item);
1559         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
1560         device->type = btrfs_device_type(leaf, dev_item);
1561         device->io_align = btrfs_device_io_align(leaf, dev_item);
1562         device->io_width = btrfs_device_io_width(leaf, dev_item);
1563         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
1564
1565         ptr = (unsigned long)btrfs_device_uuid(dev_item);
1566         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1567
1568         return 0;
1569 }
1570
1571 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
1572 {
1573         struct btrfs_fs_devices *fs_devices;
1574         int ret;
1575
1576         fs_devices = root->fs_info->fs_devices->seed;
1577         while (fs_devices) {
1578                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
1579                         ret = 0;
1580                         goto out;
1581                 }
1582                 fs_devices = fs_devices->seed;
1583         }
1584
1585         fs_devices = find_fsid(fsid);
1586         if (!fs_devices) {
1587                 ret = -ENOENT;
1588                 goto out;
1589         }
1590
1591         ret = btrfs_open_devices(fs_devices, O_RDONLY);
1592         if (ret)
1593                 goto out;
1594
1595         fs_devices->seed = root->fs_info->fs_devices->seed;
1596         root->fs_info->fs_devices->seed = fs_devices;
1597 out:
1598         return ret;
1599 }
1600
1601 static int read_one_dev(struct btrfs_root *root,
1602                         struct extent_buffer *leaf,
1603                         struct btrfs_dev_item *dev_item)
1604 {
1605         struct btrfs_device *device;
1606         u64 devid;
1607         int ret = 0;
1608         u8 fs_uuid[BTRFS_UUID_SIZE];
1609         u8 dev_uuid[BTRFS_UUID_SIZE];
1610
1611         devid = btrfs_device_id(leaf, dev_item);
1612         read_extent_buffer(leaf, dev_uuid,
1613                            (unsigned long)btrfs_device_uuid(dev_item),
1614                            BTRFS_UUID_SIZE);
1615         read_extent_buffer(leaf, fs_uuid,
1616                            (unsigned long)btrfs_device_fsid(dev_item),
1617                            BTRFS_UUID_SIZE);
1618
1619         if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
1620                 ret = open_seed_devices(root, fs_uuid);
1621                 if (ret)
1622                         return ret;
1623         }
1624
1625         device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1626         if (!device) {
1627                 printk("warning devid %llu not found already\n",
1628                         (unsigned long long)devid);
1629                 device = kmalloc(sizeof(*device), GFP_NOFS);
1630                 if (!device)
1631                         return -ENOMEM;
1632                 device->total_ios = 0;
1633                 list_add(&device->dev_list,
1634                          &root->fs_info->fs_devices->devices);
1635         }
1636
1637         fill_device_from_item(leaf, dev_item, device);
1638         device->dev_root = root->fs_info->dev_root;
1639         return ret;
1640 }
1641
1642 int btrfs_read_super_device(struct btrfs_root *root, struct extent_buffer *buf)
1643 {
1644         struct btrfs_dev_item *dev_item;
1645
1646         dev_item = (struct btrfs_dev_item *)offsetof(struct btrfs_super_block,
1647                                                      dev_item);
1648         return read_one_dev(root, buf, dev_item);
1649 }
1650
1651 int btrfs_read_sys_array(struct btrfs_root *root)
1652 {
1653         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1654         struct extent_buffer *sb;
1655         struct btrfs_disk_key *disk_key;
1656         struct btrfs_chunk *chunk;
1657         struct btrfs_key key;
1658         u32 num_stripes;
1659         u32 array_size;
1660         u32 len = 0;
1661         u8 *ptr;
1662         unsigned long sb_ptr;
1663         u32 cur;
1664         int ret = 0;
1665
1666         sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
1667                                           BTRFS_SUPER_INFO_SIZE);
1668         if (!sb)
1669                 return -ENOMEM;
1670         btrfs_set_buffer_uptodate(sb);
1671         write_extent_buffer(sb, super_copy, 0, sizeof(*super_copy));
1672         array_size = btrfs_super_sys_array_size(super_copy);
1673
1674         /*
1675          * we do this loop twice, once for the device items and
1676          * once for all of the chunks.  This way there are device
1677          * structs filled in for every chunk
1678          */
1679         ptr = super_copy->sys_chunk_array;
1680         sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
1681         cur = 0;
1682
1683         while (cur < array_size) {
1684                 disk_key = (struct btrfs_disk_key *)ptr;
1685                 btrfs_disk_key_to_cpu(&key, disk_key);
1686
1687                 len = sizeof(*disk_key);
1688                 ptr += len;
1689                 sb_ptr += len;
1690                 cur += len;
1691
1692                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1693                         chunk = (struct btrfs_chunk *)sb_ptr;
1694                         ret = read_one_chunk(root, &key, sb, chunk);
1695                         if (ret)
1696                                 break;
1697                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
1698                         len = btrfs_chunk_item_size(num_stripes);
1699                 } else {
1700                         BUG();
1701                 }
1702                 ptr += len;
1703                 sb_ptr += len;
1704                 cur += len;
1705         }
1706         free_extent_buffer(sb);
1707         return ret;
1708 }
1709
1710 int btrfs_read_chunk_tree(struct btrfs_root *root)
1711 {
1712         struct btrfs_path *path;
1713         struct extent_buffer *leaf;
1714         struct btrfs_key key;
1715         struct btrfs_key found_key;
1716         int ret;
1717         int slot;
1718
1719         root = root->fs_info->chunk_root;
1720
1721         path = btrfs_alloc_path();
1722         if (!path)
1723                 return -ENOMEM;
1724
1725         /* first we search for all of the device items, and then we
1726          * read in all of the chunk items.  This way we can create chunk
1727          * mappings that reference all of the devices that are afound
1728          */
1729         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1730         key.offset = 0;
1731         key.type = 0;
1732 again:
1733         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1734         while(1) {
1735                 leaf = path->nodes[0];
1736                 slot = path->slots[0];
1737                 if (slot >= btrfs_header_nritems(leaf)) {
1738                         ret = btrfs_next_leaf(root, path);
1739                         if (ret == 0)
1740                                 continue;
1741                         if (ret < 0)
1742                                 goto error;
1743                         break;
1744                 }
1745                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1746                 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
1747                         if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
1748                                 break;
1749                         if (found_key.type == BTRFS_DEV_ITEM_KEY) {
1750                                 struct btrfs_dev_item *dev_item;
1751                                 dev_item = btrfs_item_ptr(leaf, slot,
1752                                                   struct btrfs_dev_item);
1753                                 ret = read_one_dev(root, leaf, dev_item);
1754                                 BUG_ON(ret);
1755                         }
1756                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
1757                         struct btrfs_chunk *chunk;
1758                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
1759                         ret = read_one_chunk(root, &found_key, leaf, chunk);
1760                         BUG_ON(ret);
1761                 }
1762                 path->slots[0]++;
1763         }
1764         if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
1765                 key.objectid = 0;
1766                 btrfs_release_path(root, path);
1767                 goto again;
1768         }
1769
1770         ret = 0;
1771 error:
1772         btrfs_free_path(path);
1773         return ret;
1774 }
1775
1776 struct list_head *btrfs_scanned_uuids(void)
1777 {
1778         return &fs_uuids;
1779 }