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