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