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