btrfs-progs: update CHANGES for v4.13.3
[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_fs_info *fs_info, u64 *offset)
509 {
510         struct btrfs_root *root = fs_info->chunk_root;
511         struct btrfs_path *path;
512         int ret;
513         struct btrfs_key key;
514         struct btrfs_chunk *chunk;
515         struct btrfs_key found_key;
516
517         path = btrfs_alloc_path();
518         if (!path)
519                 return -ENOMEM;
520
521         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
522         key.offset = (u64)-1;
523         key.type = BTRFS_CHUNK_ITEM_KEY;
524
525         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
526         if (ret < 0)
527                 goto error;
528
529         BUG_ON(ret == 0);
530
531         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
532         if (ret) {
533                 *offset = 0;
534         } else {
535                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
536                                       path->slots[0]);
537                 if (found_key.objectid != BTRFS_FIRST_CHUNK_TREE_OBJECTID)
538                         *offset = 0;
539                 else {
540                         chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
541                                                struct btrfs_chunk);
542                         *offset = found_key.offset +
543                                 btrfs_chunk_length(path->nodes[0], chunk);
544                 }
545         }
546         ret = 0;
547 error:
548         btrfs_free_path(path);
549         return ret;
550 }
551
552 static int find_next_devid(struct btrfs_root *root, struct btrfs_path *path,
553                            u64 *objectid)
554 {
555         int ret;
556         struct btrfs_key key;
557         struct btrfs_key found_key;
558
559         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
560         key.type = BTRFS_DEV_ITEM_KEY;
561         key.offset = (u64)-1;
562
563         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
564         if (ret < 0)
565                 goto error;
566
567         BUG_ON(ret == 0);
568
569         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
570                                   BTRFS_DEV_ITEM_KEY);
571         if (ret) {
572                 *objectid = 1;
573         } else {
574                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
575                                       path->slots[0]);
576                 *objectid = found_key.offset + 1;
577         }
578         ret = 0;
579 error:
580         btrfs_release_path(path);
581         return ret;
582 }
583
584 /*
585  * the device information is stored in the chunk root
586  * the btrfs_device struct should be fully filled in
587  */
588 int btrfs_add_device(struct btrfs_trans_handle *trans,
589                      struct btrfs_fs_info *fs_info,
590                      struct btrfs_device *device)
591 {
592         int ret;
593         struct btrfs_path *path;
594         struct btrfs_dev_item *dev_item;
595         struct extent_buffer *leaf;
596         struct btrfs_key key;
597         struct btrfs_root *root = fs_info->chunk_root;
598         unsigned long ptr;
599         u64 free_devid = 0;
600
601         path = btrfs_alloc_path();
602         if (!path)
603                 return -ENOMEM;
604
605         ret = find_next_devid(root, path, &free_devid);
606         if (ret)
607                 goto out;
608
609         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
610         key.type = BTRFS_DEV_ITEM_KEY;
611         key.offset = free_devid;
612
613         ret = btrfs_insert_empty_item(trans, root, path, &key,
614                                       sizeof(*dev_item));
615         if (ret)
616                 goto out;
617
618         leaf = path->nodes[0];
619         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
620
621         device->devid = free_devid;
622         btrfs_set_device_id(leaf, dev_item, device->devid);
623         btrfs_set_device_generation(leaf, dev_item, 0);
624         btrfs_set_device_type(leaf, dev_item, device->type);
625         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
626         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
627         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
628         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
629         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
630         btrfs_set_device_group(leaf, dev_item, 0);
631         btrfs_set_device_seek_speed(leaf, dev_item, 0);
632         btrfs_set_device_bandwidth(leaf, dev_item, 0);
633         btrfs_set_device_start_offset(leaf, dev_item, 0);
634
635         ptr = (unsigned long)btrfs_device_uuid(dev_item);
636         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
637         ptr = (unsigned long)btrfs_device_fsid(dev_item);
638         write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_UUID_SIZE);
639         btrfs_mark_buffer_dirty(leaf);
640         ret = 0;
641
642 out:
643         btrfs_free_path(path);
644         return ret;
645 }
646
647 int btrfs_update_device(struct btrfs_trans_handle *trans,
648                         struct btrfs_device *device)
649 {
650         int ret;
651         struct btrfs_path *path;
652         struct btrfs_root *root;
653         struct btrfs_dev_item *dev_item;
654         struct extent_buffer *leaf;
655         struct btrfs_key key;
656
657         root = device->dev_root->fs_info->chunk_root;
658
659         path = btrfs_alloc_path();
660         if (!path)
661                 return -ENOMEM;
662
663         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
664         key.type = BTRFS_DEV_ITEM_KEY;
665         key.offset = device->devid;
666
667         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
668         if (ret < 0)
669                 goto out;
670
671         if (ret > 0) {
672                 ret = -ENOENT;
673                 goto out;
674         }
675
676         leaf = path->nodes[0];
677         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
678
679         btrfs_set_device_id(leaf, dev_item, device->devid);
680         btrfs_set_device_type(leaf, dev_item, device->type);
681         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
682         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
683         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
684         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
685         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
686         btrfs_mark_buffer_dirty(leaf);
687
688 out:
689         btrfs_free_path(path);
690         return ret;
691 }
692
693 int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
694                            struct btrfs_chunk *chunk, int item_size)
695 {
696         struct btrfs_super_block *super_copy = fs_info->super_copy;
697         struct btrfs_disk_key disk_key;
698         u32 array_size;
699         u8 *ptr;
700
701         array_size = btrfs_super_sys_array_size(super_copy);
702         if (array_size + item_size + sizeof(disk_key)
703                         > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
704                 return -EFBIG;
705
706         ptr = super_copy->sys_chunk_array + array_size;
707         btrfs_cpu_key_to_disk(&disk_key, key);
708         memcpy(ptr, &disk_key, sizeof(disk_key));
709         ptr += sizeof(disk_key);
710         memcpy(ptr, chunk, item_size);
711         item_size += sizeof(disk_key);
712         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
713         return 0;
714 }
715
716 static u64 chunk_bytes_by_type(u64 type, u64 calc_size, int num_stripes,
717                                int sub_stripes)
718 {
719         if (type & (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP))
720                 return calc_size;
721         else if (type & BTRFS_BLOCK_GROUP_RAID10)
722                 return calc_size * (num_stripes / sub_stripes);
723         else if (type & BTRFS_BLOCK_GROUP_RAID5)
724                 return calc_size * (num_stripes - 1);
725         else if (type & BTRFS_BLOCK_GROUP_RAID6)
726                 return calc_size * (num_stripes - 2);
727         else
728                 return calc_size * num_stripes;
729 }
730
731
732 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
733 {
734         /* TODO, add a way to store the preferred stripe size */
735         return BTRFS_STRIPE_LEN;
736 }
737
738 /*
739  * btrfs_device_avail_bytes - count bytes available for alloc_chunk
740  *
741  * It is not equal to "device->total_bytes - device->bytes_used".
742  * We do not allocate any chunk in 1M at beginning of device, and not
743  * allowed to allocate any chunk before alloc_start if it is specified.
744  * So search holes from max(1M, alloc_start) to device->total_bytes.
745  */
746 static int btrfs_device_avail_bytes(struct btrfs_trans_handle *trans,
747                                     struct btrfs_device *device,
748                                     u64 *avail_bytes)
749 {
750         struct btrfs_path *path;
751         struct btrfs_root *root = device->dev_root;
752         struct btrfs_key key;
753         struct btrfs_dev_extent *dev_extent = NULL;
754         struct extent_buffer *l;
755         u64 search_start = root->fs_info->alloc_start;
756         u64 search_end = device->total_bytes;
757         u64 extent_end = 0;
758         u64 free_bytes = 0;
759         int ret;
760         int slot = 0;
761
762         search_start = max(BTRFS_BLOCK_RESERVED_1M_FOR_SUPER, search_start);
763
764         path = btrfs_alloc_path();
765         if (!path)
766                 return -ENOMEM;
767
768         key.objectid = device->devid;
769         key.offset = root->fs_info->alloc_start;
770         key.type = BTRFS_DEV_EXTENT_KEY;
771
772         path->reada = 2;
773         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
774         if (ret < 0)
775                 goto error;
776         ret = btrfs_previous_item(root, path, 0, key.type);
777         if (ret < 0)
778                 goto error;
779
780         while (1) {
781                 l = path->nodes[0];
782                 slot = path->slots[0];
783                 if (slot >= btrfs_header_nritems(l)) {
784                         ret = btrfs_next_leaf(root, path);
785                         if (ret == 0)
786                                 continue;
787                         if (ret < 0)
788                                 goto error;
789                         break;
790                 }
791                 btrfs_item_key_to_cpu(l, &key, slot);
792
793                 if (key.objectid < device->devid)
794                         goto next;
795                 if (key.objectid > device->devid)
796                         break;
797                 if (key.type != BTRFS_DEV_EXTENT_KEY)
798                         goto next;
799                 if (key.offset > search_end)
800                         break;
801                 if (key.offset > search_start)
802                         free_bytes += key.offset - search_start;
803
804                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
805                 extent_end = key.offset + btrfs_dev_extent_length(l,
806                                                                   dev_extent);
807                 if (extent_end > search_start)
808                         search_start = extent_end;
809                 if (search_start > search_end)
810                         break;
811 next:
812                 path->slots[0]++;
813                 cond_resched();
814         }
815
816         if (search_start < search_end)
817                 free_bytes += search_end - search_start;
818
819         *avail_bytes = free_bytes;
820         ret = 0;
821 error:
822         btrfs_free_path(path);
823         return ret;
824 }
825
826 #define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r)             \
827                         - sizeof(struct btrfs_item)             \
828                         - sizeof(struct btrfs_chunk))           \
829                         / sizeof(struct btrfs_stripe) + 1)
830
831 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE        \
832                                 - 2 * sizeof(struct btrfs_disk_key)     \
833                                 - 2 * sizeof(struct btrfs_chunk))       \
834                                 / sizeof(struct btrfs_stripe) + 1)
835
836 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
837                       struct btrfs_fs_info *info, u64 *start,
838                       u64 *num_bytes, u64 type)
839 {
840         u64 dev_offset;
841         struct btrfs_root *extent_root = info->extent_root;
842         struct btrfs_root *chunk_root = info->chunk_root;
843         struct btrfs_stripe *stripes;
844         struct btrfs_device *device = NULL;
845         struct btrfs_chunk *chunk;
846         struct list_head private_devs;
847         struct list_head *dev_list = &info->fs_devices->devices;
848         struct list_head *cur;
849         struct map_lookup *map;
850         int min_stripe_size = SZ_1M;
851         u64 calc_size = SZ_8M;
852         u64 min_free;
853         u64 max_chunk_size = 4 * calc_size;
854         u64 avail = 0;
855         u64 max_avail = 0;
856         u64 percent_max;
857         int num_stripes = 1;
858         int max_stripes = 0;
859         int min_stripes = 1;
860         int sub_stripes = 0;
861         int looped = 0;
862         int ret;
863         int index;
864         int stripe_len = BTRFS_STRIPE_LEN;
865         struct btrfs_key key;
866         u64 offset;
867
868         if (list_empty(dev_list)) {
869                 return -ENOSPC;
870         }
871
872         if (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
873                 if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
874                         calc_size = SZ_8M;
875                         max_chunk_size = calc_size * 2;
876                         min_stripe_size = SZ_1M;
877                         max_stripes = BTRFS_MAX_DEVS_SYS_CHUNK;
878                 } else if (type & BTRFS_BLOCK_GROUP_DATA) {
879                         calc_size = SZ_1G;
880                         max_chunk_size = 10 * calc_size;
881                         min_stripe_size = SZ_64M;
882                         max_stripes = BTRFS_MAX_DEVS(chunk_root);
883                 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
884                         calc_size = SZ_1G;
885                         max_chunk_size = 4 * calc_size;
886                         min_stripe_size = SZ_32M;
887                         max_stripes = BTRFS_MAX_DEVS(chunk_root);
888                 }
889         }
890         if (type & BTRFS_BLOCK_GROUP_RAID1) {
891                 num_stripes = min_t(u64, 2,
892                                   btrfs_super_num_devices(info->super_copy));
893                 if (num_stripes < 2)
894                         return -ENOSPC;
895                 min_stripes = 2;
896         }
897         if (type & BTRFS_BLOCK_GROUP_DUP) {
898                 num_stripes = 2;
899                 min_stripes = 2;
900         }
901         if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
902                 num_stripes = btrfs_super_num_devices(info->super_copy);
903                 if (num_stripes > max_stripes)
904                         num_stripes = max_stripes;
905                 min_stripes = 2;
906         }
907         if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
908                 num_stripes = btrfs_super_num_devices(info->super_copy);
909                 if (num_stripes > max_stripes)
910                         num_stripes = max_stripes;
911                 if (num_stripes < 4)
912                         return -ENOSPC;
913                 num_stripes &= ~(u32)1;
914                 sub_stripes = 2;
915                 min_stripes = 4;
916         }
917         if (type & (BTRFS_BLOCK_GROUP_RAID5)) {
918                 num_stripes = btrfs_super_num_devices(info->super_copy);
919                 if (num_stripes > max_stripes)
920                         num_stripes = max_stripes;
921                 if (num_stripes < 2)
922                         return -ENOSPC;
923                 min_stripes = 2;
924                 stripe_len = find_raid56_stripe_len(num_stripes - 1,
925                                     btrfs_super_stripesize(info->super_copy));
926         }
927         if (type & (BTRFS_BLOCK_GROUP_RAID6)) {
928                 num_stripes = btrfs_super_num_devices(info->super_copy);
929                 if (num_stripes > max_stripes)
930                         num_stripes = max_stripes;
931                 if (num_stripes < 3)
932                         return -ENOSPC;
933                 min_stripes = 3;
934                 stripe_len = find_raid56_stripe_len(num_stripes - 2,
935                                     btrfs_super_stripesize(info->super_copy));
936         }
937
938         /* we don't want a chunk larger than 10% of the FS */
939         percent_max = div_factor(btrfs_super_total_bytes(info->super_copy), 1);
940         max_chunk_size = min(percent_max, max_chunk_size);
941
942 again:
943         if (chunk_bytes_by_type(type, calc_size, num_stripes, sub_stripes) >
944             max_chunk_size) {
945                 calc_size = max_chunk_size;
946                 calc_size /= num_stripes;
947                 calc_size /= stripe_len;
948                 calc_size *= stripe_len;
949         }
950         /* we don't want tiny stripes */
951         calc_size = max_t(u64, calc_size, min_stripe_size);
952
953         calc_size /= stripe_len;
954         calc_size *= stripe_len;
955         INIT_LIST_HEAD(&private_devs);
956         cur = dev_list->next;
957         index = 0;
958
959         if (type & BTRFS_BLOCK_GROUP_DUP)
960                 min_free = calc_size * 2;
961         else
962                 min_free = calc_size;
963
964         /* build a private list of devices we will allocate from */
965         while(index < num_stripes) {
966                 device = list_entry(cur, struct btrfs_device, dev_list);
967                 ret = btrfs_device_avail_bytes(trans, device, &avail);
968                 if (ret)
969                         return ret;
970                 cur = cur->next;
971                 if (avail >= min_free) {
972                         list_move_tail(&device->dev_list, &private_devs);
973                         index++;
974                         if (type & BTRFS_BLOCK_GROUP_DUP)
975                                 index++;
976                 } else if (avail > max_avail)
977                         max_avail = avail;
978                 if (cur == dev_list)
979                         break;
980         }
981         if (index < num_stripes) {
982                 list_splice(&private_devs, dev_list);
983                 if (index >= min_stripes) {
984                         num_stripes = index;
985                         if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
986                                 num_stripes /= sub_stripes;
987                                 num_stripes *= sub_stripes;
988                         }
989                         looped = 1;
990                         goto again;
991                 }
992                 if (!looped && max_avail > 0) {
993                         looped = 1;
994                         calc_size = max_avail;
995                         goto again;
996                 }
997                 return -ENOSPC;
998         }
999         ret = find_next_chunk(info, &offset);
1000         if (ret)
1001                 return ret;
1002         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1003         key.type = BTRFS_CHUNK_ITEM_KEY;
1004         key.offset = offset;
1005
1006         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
1007         if (!chunk)
1008                 return -ENOMEM;
1009
1010         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
1011         if (!map) {
1012                 kfree(chunk);
1013                 return -ENOMEM;
1014         }
1015
1016         stripes = &chunk->stripe;
1017         *num_bytes = chunk_bytes_by_type(type, calc_size,
1018                                          num_stripes, sub_stripes);
1019         index = 0;
1020         while(index < num_stripes) {
1021                 struct btrfs_stripe *stripe;
1022                 BUG_ON(list_empty(&private_devs));
1023                 cur = private_devs.next;
1024                 device = list_entry(cur, struct btrfs_device, dev_list);
1025
1026                 /* loop over this device again if we're doing a dup group */
1027                 if (!(type & BTRFS_BLOCK_GROUP_DUP) ||
1028                     (index == num_stripes - 1))
1029                         list_move_tail(&device->dev_list, dev_list);
1030
1031                 ret = btrfs_alloc_dev_extent(trans, device,
1032                              info->chunk_root->root_key.objectid,
1033                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
1034                              calc_size, &dev_offset, 0);
1035                 BUG_ON(ret);
1036
1037                 device->bytes_used += calc_size;
1038                 ret = btrfs_update_device(trans, device);
1039                 BUG_ON(ret);
1040
1041                 map->stripes[index].dev = device;
1042                 map->stripes[index].physical = dev_offset;
1043                 stripe = stripes + index;
1044                 btrfs_set_stack_stripe_devid(stripe, device->devid);
1045                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
1046                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
1047                 index++;
1048         }
1049         BUG_ON(!list_empty(&private_devs));
1050
1051         /* key was set above */
1052         btrfs_set_stack_chunk_length(chunk, *num_bytes);
1053         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
1054         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
1055         btrfs_set_stack_chunk_type(chunk, type);
1056         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
1057         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
1058         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
1059         btrfs_set_stack_chunk_sector_size(chunk, info->sectorsize);
1060         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
1061         map->sector_size = info->sectorsize;
1062         map->stripe_len = stripe_len;
1063         map->io_align = stripe_len;
1064         map->io_width = stripe_len;
1065         map->type = type;
1066         map->num_stripes = num_stripes;
1067         map->sub_stripes = sub_stripes;
1068
1069         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1070                                 btrfs_chunk_item_size(num_stripes));
1071         BUG_ON(ret);
1072         *start = key.offset;;
1073
1074         map->ce.start = key.offset;
1075         map->ce.size = *num_bytes;
1076
1077         ret = insert_cache_extent(&info->mapping_tree.cache_tree, &map->ce);
1078         BUG_ON(ret);
1079
1080         if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
1081                 ret = btrfs_add_system_chunk(info, &key,
1082                                     chunk, btrfs_chunk_item_size(num_stripes));
1083                 BUG_ON(ret);
1084         }
1085
1086         kfree(chunk);
1087         return ret;
1088 }
1089
1090 /*
1091  * Alloc a DATA chunk with SINGLE profile.
1092  *
1093  * If 'convert' is set, it will alloc a chunk with 1:1 mapping
1094  * (btrfs logical bytenr == on-disk bytenr)
1095  * For that case, caller must make sure the chunk and dev_extent are not
1096  * occupied.
1097  */
1098 int btrfs_alloc_data_chunk(struct btrfs_trans_handle *trans,
1099                            struct btrfs_fs_info *info, u64 *start,
1100                            u64 num_bytes, u64 type, int convert)
1101 {
1102         u64 dev_offset;
1103         struct btrfs_root *extent_root = info->extent_root;
1104         struct btrfs_root *chunk_root = info->chunk_root;
1105         struct btrfs_stripe *stripes;
1106         struct btrfs_device *device = NULL;
1107         struct btrfs_chunk *chunk;
1108         struct list_head *dev_list = &info->fs_devices->devices;
1109         struct list_head *cur;
1110         struct map_lookup *map;
1111         u64 calc_size = SZ_8M;
1112         int num_stripes = 1;
1113         int sub_stripes = 0;
1114         int ret;
1115         int index;
1116         int stripe_len = BTRFS_STRIPE_LEN;
1117         struct btrfs_key key;
1118
1119         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1120         key.type = BTRFS_CHUNK_ITEM_KEY;
1121         if (convert) {
1122                 if (*start != round_down(*start, info->sectorsize)) {
1123                         error("DATA chunk start not sectorsize aligned: %llu",
1124                                         (unsigned long long)*start);
1125                         return -EINVAL;
1126                 }
1127                 key.offset = *start;
1128                 dev_offset = *start;
1129         } else {
1130                 u64 tmp;
1131
1132                 ret = find_next_chunk(info, &tmp);
1133                 key.offset = tmp;
1134                 if (ret)
1135                         return ret;
1136         }
1137
1138         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
1139         if (!chunk)
1140                 return -ENOMEM;
1141
1142         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
1143         if (!map) {
1144                 kfree(chunk);
1145                 return -ENOMEM;
1146         }
1147
1148         stripes = &chunk->stripe;
1149         calc_size = num_bytes;
1150
1151         index = 0;
1152         cur = dev_list->next;
1153         device = list_entry(cur, struct btrfs_device, dev_list);
1154
1155         while (index < num_stripes) {
1156                 struct btrfs_stripe *stripe;
1157
1158                 ret = btrfs_alloc_dev_extent(trans, device,
1159                              info->chunk_root->root_key.objectid,
1160                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
1161                              calc_size, &dev_offset, convert);
1162                 BUG_ON(ret);
1163
1164                 device->bytes_used += calc_size;
1165                 ret = btrfs_update_device(trans, device);
1166                 BUG_ON(ret);
1167
1168                 map->stripes[index].dev = device;
1169                 map->stripes[index].physical = dev_offset;
1170                 stripe = stripes + index;
1171                 btrfs_set_stack_stripe_devid(stripe, device->devid);
1172                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
1173                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
1174                 index++;
1175         }
1176
1177         /* key was set above */
1178         btrfs_set_stack_chunk_length(chunk, num_bytes);
1179         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
1180         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
1181         btrfs_set_stack_chunk_type(chunk, type);
1182         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
1183         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
1184         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
1185         btrfs_set_stack_chunk_sector_size(chunk, info->sectorsize);
1186         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
1187         map->sector_size = info->sectorsize;
1188         map->stripe_len = stripe_len;
1189         map->io_align = stripe_len;
1190         map->io_width = stripe_len;
1191         map->type = type;
1192         map->num_stripes = num_stripes;
1193         map->sub_stripes = sub_stripes;
1194
1195         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1196                                 btrfs_chunk_item_size(num_stripes));
1197         BUG_ON(ret);
1198         if (!convert)
1199                 *start = key.offset;
1200
1201         map->ce.start = key.offset;
1202         map->ce.size = num_bytes;
1203
1204         ret = insert_cache_extent(&info->mapping_tree.cache_tree, &map->ce);
1205         BUG_ON(ret);
1206
1207         kfree(chunk);
1208         return ret;
1209 }
1210
1211 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
1212 {
1213         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
1214         struct cache_extent *ce;
1215         struct map_lookup *map;
1216         int ret;
1217
1218         ce = search_cache_extent(&map_tree->cache_tree, logical);
1219         if (!ce) {
1220                 fprintf(stderr, "No mapping for %llu-%llu\n",
1221                         (unsigned long long)logical,
1222                         (unsigned long long)logical+len);
1223                 return 1;
1224         }
1225         if (ce->start > logical || ce->start + ce->size < logical) {
1226                 fprintf(stderr, "Invalid mapping for %llu-%llu, got "
1227                         "%llu-%llu\n", (unsigned long long)logical,
1228                         (unsigned long long)logical+len,
1229                         (unsigned long long)ce->start,
1230                         (unsigned long long)ce->start + ce->size);
1231                 return 1;
1232         }
1233         map = container_of(ce, struct map_lookup, ce);
1234
1235         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
1236                 ret = map->num_stripes;
1237         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1238                 ret = map->sub_stripes;
1239         else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
1240                 ret = 2;
1241         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1242                 ret = 3;
1243         else
1244                 ret = 1;
1245         return ret;
1246 }
1247
1248 int btrfs_next_bg(struct btrfs_fs_info *fs_info, u64 *logical,
1249                   u64 *size, u64 type)
1250 {
1251         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
1252         struct cache_extent *ce;
1253         struct map_lookup *map;
1254         u64 cur = *logical;
1255
1256         ce = search_cache_extent(&map_tree->cache_tree, cur);
1257
1258         while (ce) {
1259                 /*
1260                  * only jump to next bg if our cur is not 0
1261                  * As the initial logical for btrfs_next_bg() is 0, and
1262                  * if we jump to next bg, we skipped a valid bg.
1263                  */
1264                 if (cur) {
1265                         ce = next_cache_extent(ce);
1266                         if (!ce)
1267                                 return -ENOENT;
1268                 }
1269
1270                 cur = ce->start;
1271                 map = container_of(ce, struct map_lookup, ce);
1272                 if (map->type & type) {
1273                         *logical = ce->start;
1274                         *size = ce->size;
1275                         return 0;
1276                 }
1277                 if (!cur)
1278                         ce = next_cache_extent(ce);
1279         }
1280
1281         return -ENOENT;
1282 }
1283
1284 int btrfs_rmap_block(struct btrfs_fs_info *fs_info,
1285                      u64 chunk_start, u64 physical, u64 devid,
1286                      u64 **logical, int *naddrs, int *stripe_len)
1287 {
1288         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
1289         struct cache_extent *ce;
1290         struct map_lookup *map;
1291         u64 *buf;
1292         u64 bytenr;
1293         u64 length;
1294         u64 stripe_nr;
1295         u64 rmap_len;
1296         int i, j, nr = 0;
1297
1298         ce = search_cache_extent(&map_tree->cache_tree, chunk_start);
1299         BUG_ON(!ce);
1300         map = container_of(ce, struct map_lookup, ce);
1301
1302         length = ce->size;
1303         rmap_len = map->stripe_len;
1304         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1305                 length = ce->size / (map->num_stripes / map->sub_stripes);
1306         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
1307                 length = ce->size / map->num_stripes;
1308         else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1309                               BTRFS_BLOCK_GROUP_RAID6)) {
1310                 length = ce->size / nr_data_stripes(map);
1311                 rmap_len = map->stripe_len * nr_data_stripes(map);
1312         }
1313
1314         buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1315
1316         for (i = 0; i < map->num_stripes; i++) {
1317                 if (devid && map->stripes[i].dev->devid != devid)
1318                         continue;
1319                 if (map->stripes[i].physical > physical ||
1320                     map->stripes[i].physical + length <= physical)
1321                         continue;
1322
1323                 stripe_nr = (physical - map->stripes[i].physical) /
1324                             map->stripe_len;
1325
1326                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1327                         stripe_nr = (stripe_nr * map->num_stripes + i) /
1328                                     map->sub_stripes;
1329                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1330                         stripe_nr = stripe_nr * map->num_stripes + i;
1331                 } /* else if RAID[56], multiply by nr_data_stripes().
1332                    * Alternatively, just use rmap_len below instead of
1333                    * map->stripe_len */
1334
1335                 bytenr = ce->start + stripe_nr * rmap_len;
1336                 for (j = 0; j < nr; j++) {
1337                         if (buf[j] == bytenr)
1338                                 break;
1339                 }
1340                 if (j == nr)
1341                         buf[nr++] = bytenr;
1342         }
1343
1344         *logical = buf;
1345         *naddrs = nr;
1346         *stripe_len = rmap_len;
1347
1348         return 0;
1349 }
1350
1351 static inline int parity_smaller(u64 a, u64 b)
1352 {
1353         return a > b;
1354 }
1355
1356 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
1357 static void sort_parity_stripes(struct btrfs_multi_bio *bbio, u64 *raid_map)
1358 {
1359         struct btrfs_bio_stripe s;
1360         int i;
1361         u64 l;
1362         int again = 1;
1363
1364         while (again) {
1365                 again = 0;
1366                 for (i = 0; i < bbio->num_stripes - 1; i++) {
1367                         if (parity_smaller(raid_map[i], raid_map[i+1])) {
1368                                 s = bbio->stripes[i];
1369                                 l = raid_map[i];
1370                                 bbio->stripes[i] = bbio->stripes[i+1];
1371                                 raid_map[i] = raid_map[i+1];
1372                                 bbio->stripes[i+1] = s;
1373                                 raid_map[i+1] = l;
1374                                 again = 1;
1375                         }
1376                 }
1377         }
1378 }
1379
1380 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
1381                     u64 logical, u64 *length,
1382                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1383                     u64 **raid_map_ret)
1384 {
1385         return __btrfs_map_block(fs_info, rw, logical, length, NULL,
1386                                  multi_ret, mirror_num, raid_map_ret);
1387 }
1388
1389 int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
1390                       u64 logical, u64 *length, u64 *type,
1391                       struct btrfs_multi_bio **multi_ret, int mirror_num,
1392                       u64 **raid_map_ret)
1393 {
1394         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
1395         struct cache_extent *ce;
1396         struct map_lookup *map;
1397         u64 offset;
1398         u64 stripe_offset;
1399         u64 stripe_nr;
1400         u64 *raid_map = NULL;
1401         int stripes_allocated = 8;
1402         int stripes_required = 1;
1403         int stripe_index;
1404         int i;
1405         struct btrfs_multi_bio *multi = NULL;
1406
1407         if (multi_ret && rw == READ) {
1408                 stripes_allocated = 1;
1409         }
1410 again:
1411         ce = search_cache_extent(&map_tree->cache_tree, logical);
1412         if (!ce) {
1413                 kfree(multi);
1414                 *length = (u64)-1;
1415                 return -ENOENT;
1416         }
1417         if (ce->start > logical) {
1418                 kfree(multi);
1419                 *length = ce->start - logical;
1420                 return -ENOENT;
1421         }
1422
1423         if (multi_ret) {
1424                 multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
1425                                 GFP_NOFS);
1426                 if (!multi)
1427                         return -ENOMEM;
1428         }
1429         map = container_of(ce, struct map_lookup, ce);
1430         offset = logical - ce->start;
1431
1432         if (rw == WRITE) {
1433                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
1434                                  BTRFS_BLOCK_GROUP_DUP)) {
1435                         stripes_required = map->num_stripes;
1436                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1437                         stripes_required = map->sub_stripes;
1438                 }
1439         }
1440         if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)
1441             && multi_ret && ((rw & WRITE) || mirror_num > 1) && raid_map_ret) {
1442                     /* RAID[56] write or recovery. Return all stripes */
1443                     stripes_required = map->num_stripes;
1444
1445                     /* Only allocate the map if we've already got a large enough multi_ret */
1446                     if (stripes_allocated >= stripes_required) {
1447                             raid_map = kmalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1448                             if (!raid_map) {
1449                                     kfree(multi);
1450                                     return -ENOMEM;
1451                             }
1452                     }
1453         }
1454
1455         /* if our multi bio struct is too small, back off and try again */
1456         if (multi_ret && stripes_allocated < stripes_required) {
1457                 stripes_allocated = stripes_required;
1458                 kfree(multi);
1459                 multi = NULL;
1460                 goto again;
1461         }
1462         stripe_nr = offset;
1463         /*
1464          * stripe_nr counts the total number of stripes we have to stride
1465          * to get to this block
1466          */
1467         stripe_nr = stripe_nr / map->stripe_len;
1468
1469         stripe_offset = stripe_nr * map->stripe_len;
1470         BUG_ON(offset < stripe_offset);
1471
1472         /* stripe_offset is the offset of this block in its stripe*/
1473         stripe_offset = offset - stripe_offset;
1474
1475         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1476                          BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
1477                          BTRFS_BLOCK_GROUP_RAID10 |
1478                          BTRFS_BLOCK_GROUP_DUP)) {
1479                 /* we limit the length of each bio to what fits in a stripe */
1480                 *length = min_t(u64, ce->size - offset,
1481                               map->stripe_len - stripe_offset);
1482         } else {
1483                 *length = ce->size - offset;
1484         }
1485
1486         if (!multi_ret)
1487                 goto out;
1488
1489         multi->num_stripes = 1;
1490         stripe_index = 0;
1491         if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1492                 if (rw == WRITE)
1493                         multi->num_stripes = map->num_stripes;
1494                 else if (mirror_num)
1495                         stripe_index = mirror_num - 1;
1496                 else
1497                         stripe_index = stripe_nr % map->num_stripes;
1498         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1499                 int factor = map->num_stripes / map->sub_stripes;
1500
1501                 stripe_index = stripe_nr % factor;
1502                 stripe_index *= map->sub_stripes;
1503
1504                 if (rw == WRITE)
1505                         multi->num_stripes = map->sub_stripes;
1506                 else if (mirror_num)
1507                         stripe_index += mirror_num - 1;
1508
1509                 stripe_nr = stripe_nr / factor;
1510         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
1511                 if (rw == WRITE)
1512                         multi->num_stripes = map->num_stripes;
1513                 else if (mirror_num)
1514                         stripe_index = mirror_num - 1;
1515         } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1516                                 BTRFS_BLOCK_GROUP_RAID6)) {
1517
1518                 if (raid_map) {
1519                         int rot;
1520                         u64 tmp;
1521                         u64 raid56_full_stripe_start;
1522                         u64 full_stripe_len = nr_data_stripes(map) * map->stripe_len;
1523
1524                         /*
1525                          * align the start of our data stripe in the logical
1526                          * address space
1527                          */
1528                         raid56_full_stripe_start = offset / full_stripe_len;
1529                         raid56_full_stripe_start *= full_stripe_len;
1530
1531                         /* get the data stripe number */
1532                         stripe_nr = raid56_full_stripe_start / map->stripe_len;
1533                         stripe_nr = stripe_nr / nr_data_stripes(map);
1534
1535                         /* Work out the disk rotation on this stripe-set */
1536                         rot = stripe_nr % map->num_stripes;
1537
1538                         /* Fill in the logical address of each stripe */
1539                         tmp = stripe_nr * nr_data_stripes(map);
1540
1541                         for (i = 0; i < nr_data_stripes(map); i++)
1542                                 raid_map[(i+rot) % map->num_stripes] =
1543                                         ce->start + (tmp + i) * map->stripe_len;
1544
1545                         raid_map[(i+rot) % map->num_stripes] = BTRFS_RAID5_P_STRIPE;
1546                         if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1547                                 raid_map[(i+rot+1) % map->num_stripes] = BTRFS_RAID6_Q_STRIPE;
1548
1549                         *length = map->stripe_len;
1550                         stripe_index = 0;
1551                         stripe_offset = 0;
1552                         multi->num_stripes = map->num_stripes;
1553                 } else {
1554                         stripe_index = stripe_nr % nr_data_stripes(map);
1555                         stripe_nr = stripe_nr / nr_data_stripes(map);
1556
1557                         /*
1558                          * Mirror #0 or #1 means the original data block.
1559                          * Mirror #2 is RAID5 parity block.
1560                          * Mirror #3 is RAID6 Q block.
1561                          */
1562                         if (mirror_num > 1)
1563                                 stripe_index = nr_data_stripes(map) + mirror_num - 2;
1564
1565                         /* We distribute the parity blocks across stripes */
1566                         stripe_index = (stripe_nr + stripe_index) % map->num_stripes;
1567                 }
1568         } else {
1569                 /*
1570                  * after this do_div call, stripe_nr is the number of stripes
1571                  * on this device we have to walk to find the data, and
1572                  * stripe_index is the number of our device in the stripe array
1573                  */
1574                 stripe_index = stripe_nr % map->num_stripes;
1575                 stripe_nr = stripe_nr / map->num_stripes;
1576         }
1577         BUG_ON(stripe_index >= map->num_stripes);
1578
1579         for (i = 0; i < multi->num_stripes; i++) {
1580                 multi->stripes[i].physical =
1581                         map->stripes[stripe_index].physical + stripe_offset +
1582                         stripe_nr * map->stripe_len;
1583                 multi->stripes[i].dev = map->stripes[stripe_index].dev;
1584                 stripe_index++;
1585         }
1586         *multi_ret = multi;
1587
1588         if (type)
1589                 *type = map->type;
1590
1591         if (raid_map) {
1592                 sort_parity_stripes(multi, raid_map);
1593                 *raid_map_ret = raid_map;
1594         }
1595 out:
1596         return 0;
1597 }
1598
1599 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
1600                                        u8 *uuid, u8 *fsid)
1601 {
1602         struct btrfs_device *device;
1603         struct btrfs_fs_devices *cur_devices;
1604
1605         cur_devices = fs_info->fs_devices;
1606         while (cur_devices) {
1607                 if (!fsid ||
1608                     (!memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE) ||
1609                      fs_info->ignore_fsid_mismatch)) {
1610                         device = __find_device(&cur_devices->devices,
1611                                                devid, uuid);
1612                         if (device)
1613                                 return device;
1614                 }
1615                 cur_devices = cur_devices->seed;
1616         }
1617         return NULL;
1618 }
1619
1620 struct btrfs_device *
1621 btrfs_find_device_by_devid(struct btrfs_fs_devices *fs_devices,
1622                            u64 devid, int instance)
1623 {
1624         struct list_head *head = &fs_devices->devices;
1625         struct btrfs_device *dev;
1626         int num_found = 0;
1627
1628         list_for_each_entry(dev, head, dev_list) {
1629                 if (dev->devid == devid && num_found++ == instance)
1630                         return dev;
1631         }
1632         return NULL;
1633 }
1634
1635 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
1636 {
1637         struct cache_extent *ce;
1638         struct map_lookup *map;
1639         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
1640         int readonly = 0;
1641         int i;
1642
1643         /*
1644          * During chunk recovering, we may fail to find block group's
1645          * corresponding chunk, we will rebuild it later
1646          */
1647         ce = search_cache_extent(&map_tree->cache_tree, chunk_offset);
1648         if (!fs_info->is_chunk_recover)
1649                 BUG_ON(!ce);
1650         else
1651                 return 0;
1652
1653         map = container_of(ce, struct map_lookup, ce);
1654         for (i = 0; i < map->num_stripes; i++) {
1655                 if (!map->stripes[i].dev->writeable) {
1656                         readonly = 1;
1657                         break;
1658                 }
1659         }
1660
1661         return readonly;
1662 }
1663
1664 static struct btrfs_device *fill_missing_device(u64 devid)
1665 {
1666         struct btrfs_device *device;
1667
1668         device = kzalloc(sizeof(*device), GFP_NOFS);
1669         device->devid = devid;
1670         device->fd = -1;
1671         return device;
1672 }
1673
1674 /*
1675  * slot == -1: SYSTEM chunk
1676  * return -EIO on error, otherwise return 0
1677  */
1678 int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
1679                             struct extent_buffer *leaf,
1680                             struct btrfs_chunk *chunk,
1681                             int slot, u64 logical)
1682 {
1683         u64 length;
1684         u64 stripe_len;
1685         u16 num_stripes;
1686         u16 sub_stripes;
1687         u64 type;
1688         u32 chunk_ondisk_size;
1689         u32 sectorsize = fs_info->sectorsize;
1690
1691         length = btrfs_chunk_length(leaf, chunk);
1692         stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
1693         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1694         sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
1695         type = btrfs_chunk_type(leaf, chunk);
1696
1697         /*
1698          * These valid checks may be insufficient to cover every corner cases.
1699          */
1700         if (!IS_ALIGNED(logical, sectorsize)) {
1701                 error("invalid chunk logical %llu",  logical);
1702                 return -EIO;
1703         }
1704         if (btrfs_chunk_sector_size(leaf, chunk) != sectorsize) {
1705                 error("invalid chunk sectorsize %llu", 
1706                       (unsigned long long)btrfs_chunk_sector_size(leaf, chunk));
1707                 return -EIO;
1708         }
1709         if (!length || !IS_ALIGNED(length, sectorsize)) {
1710                 error("invalid chunk length %llu",  length);
1711                 return -EIO;
1712         }
1713         if (stripe_len != BTRFS_STRIPE_LEN) {
1714                 error("invalid chunk stripe length: %llu", stripe_len);
1715                 return -EIO;
1716         }
1717         /* Check on chunk item type */
1718         if (slot == -1 && (type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
1719                 error("invalid chunk type %llu", type);
1720                 return -EIO;
1721         }
1722         if (type & ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
1723                      BTRFS_BLOCK_GROUP_PROFILE_MASK)) {
1724                 error("unrecognized chunk type: %llu",
1725                       ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
1726                         BTRFS_BLOCK_GROUP_PROFILE_MASK) & type);
1727                 return -EIO;
1728         }
1729         if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1730                 error("missing chunk type flag: %llu", type);
1731                 return -EIO;
1732         }
1733         if (!(is_power_of_2(type & BTRFS_BLOCK_GROUP_PROFILE_MASK) ||
1734               (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0)) {
1735                 error("conflicting chunk type detected: %llu", type);
1736                 return -EIO;
1737         }
1738         if ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) &&
1739             !is_power_of_2(type & BTRFS_BLOCK_GROUP_PROFILE_MASK)) {
1740                 error("conflicting chunk profile detected: %llu", type);
1741                 return -EIO;
1742         }
1743
1744         chunk_ondisk_size = btrfs_chunk_item_size(num_stripes);
1745         /*
1746          * Btrfs_chunk contains at least one stripe, and for sys_chunk
1747          * it can't exceed the system chunk array size
1748          * For normal chunk, it should match its chunk item size.
1749          */
1750         if (num_stripes < 1 ||
1751             (slot == -1 && chunk_ondisk_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) ||
1752             (slot >= 0 && chunk_ondisk_size > btrfs_item_size_nr(leaf, slot))) {
1753                 error("invalid num_stripes: %u", num_stripes);
1754                 return -EIO;
1755         }
1756         /*
1757          * Device number check against profile
1758          */
1759         if ((type & BTRFS_BLOCK_GROUP_RAID10 && (sub_stripes != 2 ||
1760                   !IS_ALIGNED(num_stripes, sub_stripes))) ||
1761             (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
1762             (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
1763             (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
1764             (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
1765             ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
1766              num_stripes != 1)) {
1767                 error("Invalid num_stripes:sub_stripes %u:%u for profile %llu",
1768                       num_stripes, sub_stripes,
1769                       type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
1770                 return -EIO;
1771         }
1772
1773         return 0;
1774 }
1775
1776 /*
1777  * Slot is used to verify the chunk item is valid
1778  *
1779  * For sys chunk in superblock, pass -1 to indicate sys chunk.
1780  */
1781 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1782                           struct extent_buffer *leaf,
1783                           struct btrfs_chunk *chunk, int slot)
1784 {
1785         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
1786         struct map_lookup *map;
1787         struct cache_extent *ce;
1788         u64 logical;
1789         u64 length;
1790         u64 devid;
1791         u8 uuid[BTRFS_UUID_SIZE];
1792         int num_stripes;
1793         int ret;
1794         int i;
1795
1796         logical = key->offset;
1797         length = btrfs_chunk_length(leaf, chunk);
1798         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1799         /* Validation check */
1800         ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, slot, logical);
1801         if (ret) {
1802                 error("%s checksums match, but it has an invalid chunk, %s",
1803                       (slot == -1) ? "Superblock" : "Metadata",
1804                       (slot == -1) ? "try btrfsck --repair -s <superblock> ie, 0,1,2" : "");
1805                 return ret;
1806         }
1807
1808         ce = search_cache_extent(&map_tree->cache_tree, logical);
1809
1810         /* already mapped? */
1811         if (ce && ce->start <= logical && ce->start + ce->size > logical) {
1812                 return 0;
1813         }
1814
1815         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
1816         if (!map)
1817                 return -ENOMEM;
1818
1819         map->ce.start = logical;
1820         map->ce.size = length;
1821         map->num_stripes = num_stripes;
1822         map->io_width = btrfs_chunk_io_width(leaf, chunk);
1823         map->io_align = btrfs_chunk_io_align(leaf, chunk);
1824         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
1825         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
1826         map->type = btrfs_chunk_type(leaf, chunk);
1827         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
1828
1829         for (i = 0; i < num_stripes; i++) {
1830                 map->stripes[i].physical =
1831                         btrfs_stripe_offset_nr(leaf, chunk, i);
1832                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
1833                 read_extent_buffer(leaf, uuid, (unsigned long)
1834                                    btrfs_stripe_dev_uuid_nr(chunk, i),
1835                                    BTRFS_UUID_SIZE);
1836                 map->stripes[i].dev = btrfs_find_device(fs_info, devid, uuid,
1837                                                         NULL);
1838                 if (!map->stripes[i].dev) {
1839                         map->stripes[i].dev = fill_missing_device(devid);
1840                         printf("warning, device %llu is missing\n",
1841                                (unsigned long long)devid);
1842                         list_add(&map->stripes[i].dev->dev_list,
1843                                  &fs_info->fs_devices->devices);
1844                 }
1845
1846         }
1847         ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
1848         BUG_ON(ret);
1849
1850         return 0;
1851 }
1852
1853 static int fill_device_from_item(struct extent_buffer *leaf,
1854                                  struct btrfs_dev_item *dev_item,
1855                                  struct btrfs_device *device)
1856 {
1857         unsigned long ptr;
1858
1859         device->devid = btrfs_device_id(leaf, dev_item);
1860         device->total_bytes = btrfs_device_total_bytes(leaf, dev_item);
1861         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
1862         device->type = btrfs_device_type(leaf, dev_item);
1863         device->io_align = btrfs_device_io_align(leaf, dev_item);
1864         device->io_width = btrfs_device_io_width(leaf, dev_item);
1865         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
1866
1867         ptr = (unsigned long)btrfs_device_uuid(dev_item);
1868         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1869
1870         return 0;
1871 }
1872
1873 static int open_seed_devices(struct btrfs_fs_info *fs_info, u8 *fsid)
1874 {
1875         struct btrfs_fs_devices *fs_devices;
1876         int ret;
1877
1878         fs_devices = fs_info->fs_devices->seed;
1879         while (fs_devices) {
1880                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
1881                         ret = 0;
1882                         goto out;
1883                 }
1884                 fs_devices = fs_devices->seed;
1885         }
1886
1887         fs_devices = find_fsid(fsid);
1888         if (!fs_devices) {
1889                 /* missing all seed devices */
1890                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1891                 if (!fs_devices) {
1892                         ret = -ENOMEM;
1893                         goto out;
1894                 }
1895                 INIT_LIST_HEAD(&fs_devices->devices);
1896                 list_add(&fs_devices->list, &fs_uuids);
1897                 memcpy(fs_devices->fsid, fsid, BTRFS_FSID_SIZE);
1898         }
1899
1900         ret = btrfs_open_devices(fs_devices, O_RDONLY);
1901         if (ret)
1902                 goto out;
1903
1904         fs_devices->seed = fs_info->fs_devices->seed;
1905         fs_info->fs_devices->seed = fs_devices;
1906 out:
1907         return ret;
1908 }
1909
1910 static int read_one_dev(struct btrfs_fs_info *fs_info,
1911                         struct extent_buffer *leaf,
1912                         struct btrfs_dev_item *dev_item)
1913 {
1914         struct btrfs_device *device;
1915         u64 devid;
1916         int ret = 0;
1917         u8 fs_uuid[BTRFS_UUID_SIZE];
1918         u8 dev_uuid[BTRFS_UUID_SIZE];
1919
1920         devid = btrfs_device_id(leaf, dev_item);
1921         read_extent_buffer(leaf, dev_uuid,
1922                            (unsigned long)btrfs_device_uuid(dev_item),
1923                            BTRFS_UUID_SIZE);
1924         read_extent_buffer(leaf, fs_uuid,
1925                            (unsigned long)btrfs_device_fsid(dev_item),
1926                            BTRFS_UUID_SIZE);
1927
1928         if (memcmp(fs_uuid, fs_info->fsid, BTRFS_UUID_SIZE)) {
1929                 ret = open_seed_devices(fs_info, fs_uuid);
1930                 if (ret)
1931                         return ret;
1932         }
1933
1934         device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
1935         if (!device) {
1936                 device = kzalloc(sizeof(*device), GFP_NOFS);
1937                 if (!device)
1938                         return -ENOMEM;
1939                 device->fd = -1;
1940                 list_add(&device->dev_list,
1941                          &fs_info->fs_devices->devices);
1942         }
1943
1944         fill_device_from_item(leaf, dev_item, device);
1945         device->dev_root = fs_info->dev_root;
1946         return ret;
1947 }
1948
1949 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
1950 {
1951         struct btrfs_super_block *super_copy = fs_info->super_copy;
1952         struct extent_buffer *sb;
1953         struct btrfs_disk_key *disk_key;
1954         struct btrfs_chunk *chunk;
1955         u8 *array_ptr;
1956         unsigned long sb_array_offset;
1957         int ret = 0;
1958         u32 num_stripes;
1959         u32 array_size;
1960         u32 len = 0;
1961         u32 cur_offset;
1962         struct btrfs_key key;
1963
1964         if (fs_info->nodesize < BTRFS_SUPER_INFO_SIZE) {
1965                 printf("ERROR: nodesize %u too small to read superblock\n",
1966                                 fs_info->nodesize);
1967                 return -EINVAL;
1968         }
1969         sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
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 }