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