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