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