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