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