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