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