b0edbacbea13c058fdc6e94f2966e2d3705fcdb9
[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                 if (*start != round_down(*start, extent_root->sectorsize)) {
1074                         error("DATA chunk start not sectorsize aligned: %llu",
1075                                         (unsigned long long)*start);
1076                         return -EINVAL;
1077                 }
1078                 key.offset = *start;
1079                 dev_offset = *start;
1080         } else {
1081                 ret = find_next_chunk(chunk_root,
1082                                       BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1083                                       &key.offset);
1084                 if (ret)
1085                         return ret;
1086         }
1087
1088         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
1089         if (!chunk)
1090                 return -ENOMEM;
1091
1092         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
1093         if (!map) {
1094                 kfree(chunk);
1095                 return -ENOMEM;
1096         }
1097
1098         stripes = &chunk->stripe;
1099         calc_size = num_bytes;
1100
1101         index = 0;
1102         cur = dev_list->next;
1103         device = list_entry(cur, struct btrfs_device, dev_list);
1104
1105         while (index < num_stripes) {
1106                 struct btrfs_stripe *stripe;
1107
1108                 ret = btrfs_alloc_dev_extent(trans, device,
1109                              info->chunk_root->root_key.objectid,
1110                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
1111                              calc_size, &dev_offset, convert);
1112                 BUG_ON(ret);
1113
1114                 device->bytes_used += calc_size;
1115                 ret = btrfs_update_device(trans, device);
1116                 BUG_ON(ret);
1117
1118                 map->stripes[index].dev = device;
1119                 map->stripes[index].physical = dev_offset;
1120                 stripe = stripes + index;
1121                 btrfs_set_stack_stripe_devid(stripe, device->devid);
1122                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
1123                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
1124                 index++;
1125         }
1126
1127         /* key was set above */
1128         btrfs_set_stack_chunk_length(chunk, num_bytes);
1129         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
1130         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
1131         btrfs_set_stack_chunk_type(chunk, type);
1132         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
1133         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
1134         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
1135         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
1136         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
1137         map->sector_size = extent_root->sectorsize;
1138         map->stripe_len = stripe_len;
1139         map->io_align = stripe_len;
1140         map->io_width = stripe_len;
1141         map->type = type;
1142         map->num_stripes = num_stripes;
1143         map->sub_stripes = sub_stripes;
1144
1145         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1146                                 btrfs_chunk_item_size(num_stripes));
1147         BUG_ON(ret);
1148         if (!convert)
1149                 *start = key.offset;
1150
1151         map->ce.start = key.offset;
1152         map->ce.size = num_bytes;
1153
1154         ret = insert_cache_extent(&info->mapping_tree.cache_tree, &map->ce);
1155         BUG_ON(ret);
1156
1157         kfree(chunk);
1158         return ret;
1159 }
1160
1161 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
1162 {
1163         struct cache_extent *ce;
1164         struct map_lookup *map;
1165         int ret;
1166
1167         ce = search_cache_extent(&map_tree->cache_tree, logical);
1168         if (!ce) {
1169                 fprintf(stderr, "No mapping for %llu-%llu\n",
1170                         (unsigned long long)logical,
1171                         (unsigned long long)logical+len);
1172                 return 1;
1173         }
1174         if (ce->start > logical || ce->start + ce->size < logical) {
1175                 fprintf(stderr, "Invalid mapping for %llu-%llu, got "
1176                         "%llu-%llu\n", (unsigned long long)logical,
1177                         (unsigned long long)logical+len,
1178                         (unsigned long long)ce->start,
1179                         (unsigned long long)ce->start + ce->size);
1180                 return 1;
1181         }
1182         map = container_of(ce, struct map_lookup, ce);
1183
1184         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
1185                 ret = map->num_stripes;
1186         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1187                 ret = map->sub_stripes;
1188         else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
1189                 ret = 2;
1190         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1191                 ret = 3;
1192         else
1193                 ret = 1;
1194         return ret;
1195 }
1196
1197 int btrfs_next_bg(struct btrfs_mapping_tree *map_tree, u64 *logical,
1198                      u64 *size, u64 type)
1199 {
1200         struct cache_extent *ce;
1201         struct map_lookup *map;
1202         u64 cur = *logical;
1203
1204         ce = search_cache_extent(&map_tree->cache_tree, cur);
1205
1206         while (ce) {
1207                 /*
1208                  * only jump to next bg if our cur is not 0
1209                  * As the initial logical for btrfs_next_bg() is 0, and
1210                  * if we jump to next bg, we skipped a valid bg.
1211                  */
1212                 if (cur) {
1213                         ce = next_cache_extent(ce);
1214                         if (!ce)
1215                                 return -ENOENT;
1216                 }
1217
1218                 cur = ce->start;
1219                 map = container_of(ce, struct map_lookup, ce);
1220                 if (map->type & type) {
1221                         *logical = ce->start;
1222                         *size = ce->size;
1223                         return 0;
1224                 }
1225         }
1226
1227         return -ENOENT;
1228 }
1229
1230 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
1231                      u64 chunk_start, u64 physical, u64 devid,
1232                      u64 **logical, int *naddrs, int *stripe_len)
1233 {
1234         struct cache_extent *ce;
1235         struct map_lookup *map;
1236         u64 *buf;
1237         u64 bytenr;
1238         u64 length;
1239         u64 stripe_nr;
1240         u64 rmap_len;
1241         int i, j, nr = 0;
1242
1243         ce = search_cache_extent(&map_tree->cache_tree, chunk_start);
1244         BUG_ON(!ce);
1245         map = container_of(ce, struct map_lookup, ce);
1246
1247         length = ce->size;
1248         rmap_len = map->stripe_len;
1249         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1250                 length = ce->size / (map->num_stripes / map->sub_stripes);
1251         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
1252                 length = ce->size / map->num_stripes;
1253         else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1254                               BTRFS_BLOCK_GROUP_RAID6)) {
1255                 length = ce->size / nr_data_stripes(map);
1256                 rmap_len = map->stripe_len * nr_data_stripes(map);
1257         }
1258
1259         buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1260
1261         for (i = 0; i < map->num_stripes; i++) {
1262                 if (devid && map->stripes[i].dev->devid != devid)
1263                         continue;
1264                 if (map->stripes[i].physical > physical ||
1265                     map->stripes[i].physical + length <= physical)
1266                         continue;
1267
1268                 stripe_nr = (physical - map->stripes[i].physical) /
1269                             map->stripe_len;
1270
1271                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1272                         stripe_nr = (stripe_nr * map->num_stripes + i) /
1273                                     map->sub_stripes;
1274                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1275                         stripe_nr = stripe_nr * map->num_stripes + i;
1276                 } /* else if RAID[56], multiply by nr_data_stripes().
1277                    * Alternatively, just use rmap_len below instead of
1278                    * map->stripe_len */
1279
1280                 bytenr = ce->start + stripe_nr * rmap_len;
1281                 for (j = 0; j < nr; j++) {
1282                         if (buf[j] == bytenr)
1283                                 break;
1284                 }
1285                 if (j == nr)
1286                         buf[nr++] = bytenr;
1287         }
1288
1289         *logical = buf;
1290         *naddrs = nr;
1291         *stripe_len = rmap_len;
1292
1293         return 0;
1294 }
1295
1296 static inline int parity_smaller(u64 a, u64 b)
1297 {
1298         return a > b;
1299 }
1300
1301 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
1302 static void sort_parity_stripes(struct btrfs_multi_bio *bbio, u64 *raid_map)
1303 {
1304         struct btrfs_bio_stripe s;
1305         int i;
1306         u64 l;
1307         int again = 1;
1308
1309         while (again) {
1310                 again = 0;
1311                 for (i = 0; i < bbio->num_stripes - 1; i++) {
1312                         if (parity_smaller(raid_map[i], raid_map[i+1])) {
1313                                 s = bbio->stripes[i];
1314                                 l = raid_map[i];
1315                                 bbio->stripes[i] = bbio->stripes[i+1];
1316                                 raid_map[i] = raid_map[i+1];
1317                                 bbio->stripes[i+1] = s;
1318                                 raid_map[i+1] = l;
1319                                 again = 1;
1320                         }
1321                 }
1322         }
1323 }
1324
1325 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1326                     u64 logical, u64 *length,
1327                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1328                     u64 **raid_map_ret)
1329 {
1330         return __btrfs_map_block(map_tree, rw, logical, length, NULL,
1331                                  multi_ret, mirror_num, raid_map_ret);
1332 }
1333
1334 int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1335                     u64 logical, u64 *length, u64 *type,
1336                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1337                     u64 **raid_map_ret)
1338 {
1339         struct cache_extent *ce;
1340         struct map_lookup *map;
1341         u64 offset;
1342         u64 stripe_offset;
1343         u64 stripe_nr;
1344         u64 *raid_map = NULL;
1345         int stripes_allocated = 8;
1346         int stripes_required = 1;
1347         int stripe_index;
1348         int i;
1349         struct btrfs_multi_bio *multi = NULL;
1350
1351         if (multi_ret && rw == READ) {
1352                 stripes_allocated = 1;
1353         }
1354 again:
1355         ce = search_cache_extent(&map_tree->cache_tree, logical);
1356         if (!ce) {
1357                 kfree(multi);
1358                 *length = (u64)-1;
1359                 return -ENOENT;
1360         }
1361         if (ce->start > logical) {
1362                 kfree(multi);
1363                 *length = ce->start - logical;
1364                 return -ENOENT;
1365         }
1366
1367         if (multi_ret) {
1368                 multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
1369                                 GFP_NOFS);
1370                 if (!multi)
1371                         return -ENOMEM;
1372         }
1373         map = container_of(ce, struct map_lookup, ce);
1374         offset = logical - ce->start;
1375
1376         if (rw == WRITE) {
1377                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
1378                                  BTRFS_BLOCK_GROUP_DUP)) {
1379                         stripes_required = map->num_stripes;
1380                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1381                         stripes_required = map->sub_stripes;
1382                 }
1383         }
1384         if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)
1385             && multi_ret && ((rw & WRITE) || mirror_num > 1) && raid_map_ret) {
1386                     /* RAID[56] write or recovery. Return all stripes */
1387                     stripes_required = map->num_stripes;
1388
1389                     /* Only allocate the map if we've already got a large enough multi_ret */
1390                     if (stripes_allocated >= stripes_required) {
1391                             raid_map = kmalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1392                             if (!raid_map) {
1393                                     kfree(multi);
1394                                     return -ENOMEM;
1395                             }
1396                     }
1397         }
1398
1399         /* if our multi bio struct is too small, back off and try again */
1400         if (multi_ret && stripes_allocated < stripes_required) {
1401                 stripes_allocated = stripes_required;
1402                 kfree(multi);
1403                 multi = NULL;
1404                 goto again;
1405         }
1406         stripe_nr = offset;
1407         /*
1408          * stripe_nr counts the total number of stripes we have to stride
1409          * to get to this block
1410          */
1411         stripe_nr = stripe_nr / map->stripe_len;
1412
1413         stripe_offset = stripe_nr * map->stripe_len;
1414         BUG_ON(offset < stripe_offset);
1415
1416         /* stripe_offset is the offset of this block in its stripe*/
1417         stripe_offset = offset - stripe_offset;
1418
1419         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1420                          BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
1421                          BTRFS_BLOCK_GROUP_RAID10 |
1422                          BTRFS_BLOCK_GROUP_DUP)) {
1423                 /* we limit the length of each bio to what fits in a stripe */
1424                 *length = min_t(u64, ce->size - offset,
1425                               map->stripe_len - stripe_offset);
1426         } else {
1427                 *length = ce->size - offset;
1428         }
1429
1430         if (!multi_ret)
1431                 goto out;
1432
1433         multi->num_stripes = 1;
1434         stripe_index = 0;
1435         if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1436                 if (rw == WRITE)
1437                         multi->num_stripes = map->num_stripes;
1438                 else if (mirror_num)
1439                         stripe_index = mirror_num - 1;
1440                 else
1441                         stripe_index = stripe_nr % map->num_stripes;
1442         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1443                 int factor = map->num_stripes / map->sub_stripes;
1444
1445                 stripe_index = stripe_nr % factor;
1446                 stripe_index *= map->sub_stripes;
1447
1448                 if (rw == WRITE)
1449                         multi->num_stripes = map->sub_stripes;
1450                 else if (mirror_num)
1451                         stripe_index += mirror_num - 1;
1452
1453                 stripe_nr = stripe_nr / factor;
1454         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
1455                 if (rw == WRITE)
1456                         multi->num_stripes = map->num_stripes;
1457                 else if (mirror_num)
1458                         stripe_index = mirror_num - 1;
1459         } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1460                                 BTRFS_BLOCK_GROUP_RAID6)) {
1461
1462                 if (raid_map) {
1463                         int rot;
1464                         u64 tmp;
1465                         u64 raid56_full_stripe_start;
1466                         u64 full_stripe_len = nr_data_stripes(map) * map->stripe_len;
1467
1468                         /*
1469                          * align the start of our data stripe in the logical
1470                          * address space
1471                          */
1472                         raid56_full_stripe_start = offset / full_stripe_len;
1473                         raid56_full_stripe_start *= full_stripe_len;
1474
1475                         /* get the data stripe number */
1476                         stripe_nr = raid56_full_stripe_start / map->stripe_len;
1477                         stripe_nr = stripe_nr / nr_data_stripes(map);
1478
1479                         /* Work out the disk rotation on this stripe-set */
1480                         rot = stripe_nr % map->num_stripes;
1481
1482                         /* Fill in the logical address of each stripe */
1483                         tmp = stripe_nr * nr_data_stripes(map);
1484
1485                         for (i = 0; i < nr_data_stripes(map); i++)
1486                                 raid_map[(i+rot) % map->num_stripes] =
1487                                         ce->start + (tmp + i) * map->stripe_len;
1488
1489                         raid_map[(i+rot) % map->num_stripes] = BTRFS_RAID5_P_STRIPE;
1490                         if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1491                                 raid_map[(i+rot+1) % map->num_stripes] = BTRFS_RAID6_Q_STRIPE;
1492
1493                         *length = map->stripe_len;
1494                         stripe_index = 0;
1495                         stripe_offset = 0;
1496                         multi->num_stripes = map->num_stripes;
1497                 } else {
1498                         stripe_index = stripe_nr % nr_data_stripes(map);
1499                         stripe_nr = stripe_nr / nr_data_stripes(map);
1500
1501                         /*
1502                          * Mirror #0 or #1 means the original data block.
1503                          * Mirror #2 is RAID5 parity block.
1504                          * Mirror #3 is RAID6 Q block.
1505                          */
1506                         if (mirror_num > 1)
1507                                 stripe_index = nr_data_stripes(map) + mirror_num - 2;
1508
1509                         /* We distribute the parity blocks across stripes */
1510                         stripe_index = (stripe_nr + stripe_index) % map->num_stripes;
1511                 }
1512         } else {
1513                 /*
1514                  * after this do_div call, stripe_nr is the number of stripes
1515                  * on this device we have to walk to find the data, and
1516                  * stripe_index is the number of our device in the stripe array
1517                  */
1518                 stripe_index = stripe_nr % map->num_stripes;
1519                 stripe_nr = stripe_nr / map->num_stripes;
1520         }
1521         BUG_ON(stripe_index >= map->num_stripes);
1522
1523         for (i = 0; i < multi->num_stripes; i++) {
1524                 multi->stripes[i].physical =
1525                         map->stripes[stripe_index].physical + stripe_offset +
1526                         stripe_nr * map->stripe_len;
1527                 multi->stripes[i].dev = map->stripes[stripe_index].dev;
1528                 stripe_index++;
1529         }
1530         *multi_ret = multi;
1531
1532         if (type)
1533                 *type = map->type;
1534
1535         if (raid_map) {
1536                 sort_parity_stripes(multi, raid_map);
1537                 *raid_map_ret = raid_map;
1538         }
1539 out:
1540         return 0;
1541 }
1542
1543 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
1544                                        u8 *uuid, u8 *fsid)
1545 {
1546         struct btrfs_device *device;
1547         struct btrfs_fs_devices *cur_devices;
1548
1549         cur_devices = root->fs_info->fs_devices;
1550         while (cur_devices) {
1551                 if (!fsid ||
1552                     (!memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE) ||
1553                      root->fs_info->ignore_fsid_mismatch)) {
1554                         device = __find_device(&cur_devices->devices,
1555                                                devid, uuid);
1556                         if (device)
1557                                 return device;
1558                 }
1559                 cur_devices = cur_devices->seed;
1560         }
1561         return NULL;
1562 }
1563
1564 struct btrfs_device *
1565 btrfs_find_device_by_devid(struct btrfs_fs_devices *fs_devices,
1566                            u64 devid, int instance)
1567 {
1568         struct list_head *head = &fs_devices->devices;
1569         struct btrfs_device *dev;
1570         int num_found = 0;
1571
1572         list_for_each_entry(dev, head, dev_list) {
1573                 if (dev->devid == devid && num_found++ == instance)
1574                         return dev;
1575         }
1576         return NULL;
1577 }
1578
1579 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
1580 {
1581         struct cache_extent *ce;
1582         struct map_lookup *map;
1583         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
1584         int readonly = 0;
1585         int i;
1586
1587         /*
1588          * During chunk recovering, we may fail to find block group's
1589          * corresponding chunk, we will rebuild it later
1590          */
1591         ce = search_cache_extent(&map_tree->cache_tree, chunk_offset);
1592         if (!root->fs_info->is_chunk_recover)
1593                 BUG_ON(!ce);
1594         else
1595                 return 0;
1596
1597         map = container_of(ce, struct map_lookup, ce);
1598         for (i = 0; i < map->num_stripes; i++) {
1599                 if (!map->stripes[i].dev->writeable) {
1600                         readonly = 1;
1601                         break;
1602                 }
1603         }
1604
1605         return readonly;
1606 }
1607
1608 static struct btrfs_device *fill_missing_device(u64 devid)
1609 {
1610         struct btrfs_device *device;
1611
1612         device = kzalloc(sizeof(*device), GFP_NOFS);
1613         device->devid = devid;
1614         device->fd = -1;
1615         return device;
1616 }
1617
1618 /*
1619  * slot == -1: SYSTEM chunk
1620  * return -EIO on error, otherwise return 0
1621  */
1622 int btrfs_check_chunk_valid(struct btrfs_root *root,
1623                             struct extent_buffer *leaf,
1624                             struct btrfs_chunk *chunk,
1625                             int slot, u64 logical)
1626 {
1627         u64 length;
1628         u64 stripe_len;
1629         u16 num_stripes;
1630         u16 sub_stripes;
1631         u64 type;
1632
1633         length = btrfs_chunk_length(leaf, chunk);
1634         stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
1635         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1636         sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
1637         type = btrfs_chunk_type(leaf, chunk);
1638
1639         /*
1640          * These valid checks may be insufficient to cover every corner cases.
1641          */
1642         if (!IS_ALIGNED(logical, root->sectorsize)) {
1643                 error("invalid chunk logical %llu",  logical);
1644                 return -EIO;
1645         }
1646         if (btrfs_chunk_sector_size(leaf, chunk) != root->sectorsize) {
1647                 error("invalid chunk sectorsize %llu", 
1648                       (unsigned long long)btrfs_chunk_sector_size(leaf, chunk));
1649                 return -EIO;
1650         }
1651         if (!length || !IS_ALIGNED(length, root->sectorsize)) {
1652                 error("invalid chunk length %llu",  length);
1653                 return -EIO;
1654         }
1655         if (stripe_len != BTRFS_STRIPE_LEN) {
1656                 error("invalid chunk stripe length: %llu", stripe_len);
1657                 return -EIO;
1658         }
1659         /* Check on chunk item type */
1660         if (slot == -1 && (type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
1661                 error("invalid chunk type %llu", type);
1662                 return -EIO;
1663         }
1664         if (type & ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
1665                      BTRFS_BLOCK_GROUP_PROFILE_MASK)) {
1666                 error("unrecognized chunk type: %llu",
1667                       ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
1668                         BTRFS_BLOCK_GROUP_PROFILE_MASK) & type);
1669                 return -EIO;
1670         }
1671         /*
1672          * Btrfs_chunk contains at least one stripe, and for sys_chunk
1673          * it can't exceed the system chunk array size
1674          * For normal chunk, it should match its chunk item size.
1675          */
1676         if (num_stripes < 1 ||
1677             (slot == -1 && sizeof(struct btrfs_stripe) * num_stripes >
1678              BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) ||
1679             (slot >= 0 && sizeof(struct btrfs_stripe) * (num_stripes - 1) >
1680              btrfs_item_size_nr(leaf, slot))) {
1681                 error("invalid num_stripes: %u", num_stripes);
1682                 return -EIO;
1683         }
1684         /*
1685          * Device number check against profile
1686          */
1687         if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes == 0) ||
1688             (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
1689             (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
1690             (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
1691             (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
1692             ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
1693              num_stripes != 1)) {
1694                 error("Invalid num_stripes:sub_stripes %u:%u for profile %llu",
1695                       num_stripes, sub_stripes,
1696                       type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
1697                 return -EIO;
1698         }
1699
1700         return 0;
1701 }
1702
1703 /*
1704  * Slot is used to verify the chunk item is valid
1705  *
1706  * For sys chunk in superblock, pass -1 to indicate sys chunk.
1707  */
1708 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
1709                           struct extent_buffer *leaf,
1710                           struct btrfs_chunk *chunk, int slot)
1711 {
1712         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
1713         struct map_lookup *map;
1714         struct cache_extent *ce;
1715         u64 logical;
1716         u64 length;
1717         u64 devid;
1718         u8 uuid[BTRFS_UUID_SIZE];
1719         int num_stripes;
1720         int ret;
1721         int i;
1722
1723         logical = key->offset;
1724         length = btrfs_chunk_length(leaf, chunk);
1725         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1726         /* Validation check */
1727         ret = btrfs_check_chunk_valid(root, leaf, chunk, slot, logical);
1728         if (ret) {
1729                 error("%s checksums match, but it has an invalid chunk, %s",
1730                       (slot == -1) ? "Superblock" : "Metadata",
1731                       (slot == -1) ? "try btrfsck --repair -s <superblock> ie, 0,1,2" : "");
1732                 return ret;
1733         }
1734
1735         ce = search_cache_extent(&map_tree->cache_tree, logical);
1736
1737         /* already mapped? */
1738         if (ce && ce->start <= logical && ce->start + ce->size > logical) {
1739                 return 0;
1740         }
1741
1742         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
1743         if (!map)
1744                 return -ENOMEM;
1745
1746         map->ce.start = logical;
1747         map->ce.size = length;
1748         map->num_stripes = num_stripes;
1749         map->io_width = btrfs_chunk_io_width(leaf, chunk);
1750         map->io_align = btrfs_chunk_io_align(leaf, chunk);
1751         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
1752         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
1753         map->type = btrfs_chunk_type(leaf, chunk);
1754         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
1755
1756         for (i = 0; i < num_stripes; i++) {
1757                 map->stripes[i].physical =
1758                         btrfs_stripe_offset_nr(leaf, chunk, i);
1759                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
1760                 read_extent_buffer(leaf, uuid, (unsigned long)
1761                                    btrfs_stripe_dev_uuid_nr(chunk, i),
1762                                    BTRFS_UUID_SIZE);
1763                 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
1764                                                         NULL);
1765                 if (!map->stripes[i].dev) {
1766                         map->stripes[i].dev = fill_missing_device(devid);
1767                         printf("warning, device %llu is missing\n",
1768                                (unsigned long long)devid);
1769                         list_add(&map->stripes[i].dev->dev_list,
1770                                  &root->fs_info->fs_devices->devices);
1771                 }
1772
1773         }
1774         ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
1775         BUG_ON(ret);
1776
1777         return 0;
1778 }
1779
1780 static int fill_device_from_item(struct extent_buffer *leaf,
1781                                  struct btrfs_dev_item *dev_item,
1782                                  struct btrfs_device *device)
1783 {
1784         unsigned long ptr;
1785
1786         device->devid = btrfs_device_id(leaf, dev_item);
1787         device->total_bytes = btrfs_device_total_bytes(leaf, dev_item);
1788         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
1789         device->type = btrfs_device_type(leaf, dev_item);
1790         device->io_align = btrfs_device_io_align(leaf, dev_item);
1791         device->io_width = btrfs_device_io_width(leaf, dev_item);
1792         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
1793
1794         ptr = (unsigned long)btrfs_device_uuid(dev_item);
1795         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1796
1797         return 0;
1798 }
1799
1800 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
1801 {
1802         struct btrfs_fs_devices *fs_devices;
1803         int ret;
1804
1805         fs_devices = root->fs_info->fs_devices->seed;
1806         while (fs_devices) {
1807                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
1808                         ret = 0;
1809                         goto out;
1810                 }
1811                 fs_devices = fs_devices->seed;
1812         }
1813
1814         fs_devices = find_fsid(fsid);
1815         if (!fs_devices) {
1816                 /* missing all seed devices */
1817                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1818                 if (!fs_devices) {
1819                         ret = -ENOMEM;
1820                         goto out;
1821                 }
1822                 INIT_LIST_HEAD(&fs_devices->devices);
1823                 list_add(&fs_devices->list, &fs_uuids);
1824                 memcpy(fs_devices->fsid, fsid, BTRFS_FSID_SIZE);
1825         }
1826
1827         ret = btrfs_open_devices(fs_devices, O_RDONLY);
1828         if (ret)
1829                 goto out;
1830
1831         fs_devices->seed = root->fs_info->fs_devices->seed;
1832         root->fs_info->fs_devices->seed = fs_devices;
1833 out:
1834         return ret;
1835 }
1836
1837 static int read_one_dev(struct btrfs_root *root,
1838                         struct extent_buffer *leaf,
1839                         struct btrfs_dev_item *dev_item)
1840 {
1841         struct btrfs_device *device;
1842         u64 devid;
1843         int ret = 0;
1844         u8 fs_uuid[BTRFS_UUID_SIZE];
1845         u8 dev_uuid[BTRFS_UUID_SIZE];
1846
1847         devid = btrfs_device_id(leaf, dev_item);
1848         read_extent_buffer(leaf, dev_uuid,
1849                            (unsigned long)btrfs_device_uuid(dev_item),
1850                            BTRFS_UUID_SIZE);
1851         read_extent_buffer(leaf, fs_uuid,
1852                            (unsigned long)btrfs_device_fsid(dev_item),
1853                            BTRFS_UUID_SIZE);
1854
1855         if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
1856                 ret = open_seed_devices(root, fs_uuid);
1857                 if (ret)
1858                         return ret;
1859         }
1860
1861         device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1862         if (!device) {
1863                 device = kzalloc(sizeof(*device), GFP_NOFS);
1864                 if (!device)
1865                         return -ENOMEM;
1866                 device->fd = -1;
1867                 list_add(&device->dev_list,
1868                          &root->fs_info->fs_devices->devices);
1869         }
1870
1871         fill_device_from_item(leaf, dev_item, device);
1872         device->dev_root = root->fs_info->dev_root;
1873         return ret;
1874 }
1875
1876 int btrfs_read_sys_array(struct btrfs_root *root)
1877 {
1878         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
1879         struct extent_buffer *sb;
1880         struct btrfs_disk_key *disk_key;
1881         struct btrfs_chunk *chunk;
1882         u8 *array_ptr;
1883         unsigned long sb_array_offset;
1884         int ret = 0;
1885         u32 num_stripes;
1886         u32 array_size;
1887         u32 len = 0;
1888         u32 cur_offset;
1889         struct btrfs_key key;
1890
1891         sb = btrfs_find_create_tree_block(root->fs_info,
1892                                           BTRFS_SUPER_INFO_OFFSET,
1893                                           BTRFS_SUPER_INFO_SIZE);
1894         if (!sb)
1895                 return -ENOMEM;
1896         btrfs_set_buffer_uptodate(sb);
1897         write_extent_buffer(sb, super_copy, 0, sizeof(*super_copy));
1898         array_size = btrfs_super_sys_array_size(super_copy);
1899
1900         array_ptr = super_copy->sys_chunk_array;
1901         sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
1902         cur_offset = 0;
1903
1904         while (cur_offset < array_size) {
1905                 disk_key = (struct btrfs_disk_key *)array_ptr;
1906                 len = sizeof(*disk_key);
1907                 if (cur_offset + len > array_size)
1908                         goto out_short_read;
1909
1910                 btrfs_disk_key_to_cpu(&key, disk_key);
1911
1912                 array_ptr += len;
1913                 sb_array_offset += len;
1914                 cur_offset += len;
1915
1916                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1917                         chunk = (struct btrfs_chunk *)sb_array_offset;
1918                         /*
1919                          * At least one btrfs_chunk with one stripe must be
1920                          * present, exact stripe count check comes afterwards
1921                          */
1922                         len = btrfs_chunk_item_size(1);
1923                         if (cur_offset + len > array_size)
1924                                 goto out_short_read;
1925
1926                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
1927                         if (!num_stripes) {
1928                                 printk(
1929             "ERROR: invalid number of stripes %u in sys_array at offset %u\n",
1930                                         num_stripes, cur_offset);
1931                                 ret = -EIO;
1932                                 break;
1933                         }
1934
1935                         len = btrfs_chunk_item_size(num_stripes);
1936                         if (cur_offset + len > array_size)
1937                                 goto out_short_read;
1938
1939                         ret = read_one_chunk(root, &key, sb, chunk, -1);
1940                         if (ret)
1941                                 break;
1942                 } else {
1943                         printk(
1944                 "ERROR: unexpected item type %u in sys_array at offset %u\n",
1945                                 (u32)key.type, cur_offset);
1946                         ret = -EIO;
1947                         break;
1948                 }
1949                 array_ptr += len;
1950                 sb_array_offset += len;
1951                 cur_offset += len;
1952         }
1953         free_extent_buffer(sb);
1954         return ret;
1955
1956 out_short_read:
1957         printk("ERROR: sys_array too short to read %u bytes at offset %u\n",
1958                         len, cur_offset);
1959         free_extent_buffer(sb);
1960         return -EIO;
1961 }
1962
1963 int btrfs_read_chunk_tree(struct btrfs_root *root)
1964 {
1965         struct btrfs_path *path;
1966         struct extent_buffer *leaf;
1967         struct btrfs_key key;
1968         struct btrfs_key found_key;
1969         int ret;
1970         int slot;
1971
1972         root = root->fs_info->chunk_root;
1973
1974         path = btrfs_alloc_path();
1975         if (!path)
1976                 return -ENOMEM;
1977
1978         /*
1979          * Read all device items, and then all the chunk items. All
1980          * device items are found before any chunk item (their object id
1981          * is smaller than the lowest possible object id for a chunk
1982          * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
1983          */
1984         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1985         key.offset = 0;
1986         key.type = 0;
1987         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1988         if (ret < 0)
1989                 goto error;
1990         while(1) {
1991                 leaf = path->nodes[0];
1992                 slot = path->slots[0];
1993                 if (slot >= btrfs_header_nritems(leaf)) {
1994                         ret = btrfs_next_leaf(root, path);
1995                         if (ret == 0)
1996                                 continue;
1997                         if (ret < 0)
1998                                 goto error;
1999                         break;
2000                 }
2001                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2002                 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
2003                         struct btrfs_dev_item *dev_item;
2004                         dev_item = btrfs_item_ptr(leaf, slot,
2005                                                   struct btrfs_dev_item);
2006                         ret = read_one_dev(root, leaf, dev_item);
2007                         BUG_ON(ret);
2008                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
2009                         struct btrfs_chunk *chunk;
2010                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2011                         ret = read_one_chunk(root, &found_key, leaf, chunk,
2012                                              slot);
2013                         BUG_ON(ret);
2014                 }
2015                 path->slots[0]++;
2016         }
2017
2018         ret = 0;
2019 error:
2020         btrfs_free_path(path);
2021         return ret;
2022 }
2023
2024 struct list_head *btrfs_scanned_uuids(void)
2025 {
2026         return &fs_uuids;
2027 }
2028
2029 static int rmw_eb(struct btrfs_fs_info *info,
2030                   struct extent_buffer *eb, struct extent_buffer *orig_eb)
2031 {
2032         int ret;
2033         unsigned long orig_off = 0;
2034         unsigned long dest_off = 0;
2035         unsigned long copy_len = eb->len;
2036
2037         ret = read_whole_eb(info, eb, 0);
2038         if (ret)
2039                 return ret;
2040
2041         if (eb->start + eb->len <= orig_eb->start ||
2042             eb->start >= orig_eb->start + orig_eb->len)
2043                 return 0;
2044         /*
2045          * | ----- orig_eb ------- |
2046          *         | ----- stripe -------  |
2047          *         | ----- orig_eb ------- |
2048          *              | ----- orig_eb ------- |
2049          */
2050         if (eb->start > orig_eb->start)
2051                 orig_off = eb->start - orig_eb->start;
2052         if (orig_eb->start > eb->start)
2053                 dest_off = orig_eb->start - eb->start;
2054
2055         if (copy_len > orig_eb->len - orig_off)
2056                 copy_len = orig_eb->len - orig_off;
2057         if (copy_len > eb->len - dest_off)
2058                 copy_len = eb->len - dest_off;
2059
2060         memcpy(eb->data + dest_off, orig_eb->data + orig_off, copy_len);
2061         return 0;
2062 }
2063
2064 static void split_eb_for_raid56(struct btrfs_fs_info *info,
2065                                 struct extent_buffer *orig_eb,
2066                                struct extent_buffer **ebs,
2067                                u64 stripe_len, u64 *raid_map,
2068                                int num_stripes)
2069 {
2070         struct extent_buffer *eb;
2071         u64 start = orig_eb->start;
2072         u64 this_eb_start;
2073         int i;
2074         int ret;
2075
2076         for (i = 0; i < num_stripes; i++) {
2077                 if (raid_map[i] >= BTRFS_RAID5_P_STRIPE)
2078                         break;
2079
2080                 eb = calloc(1, sizeof(struct extent_buffer) + stripe_len);
2081                 if (!eb)
2082                         BUG();
2083
2084                 eb->start = raid_map[i];
2085                 eb->len = stripe_len;
2086                 eb->refs = 1;
2087                 eb->flags = 0;
2088                 eb->fd = -1;
2089                 eb->dev_bytenr = (u64)-1;
2090
2091                 this_eb_start = raid_map[i];
2092
2093                 if (start > this_eb_start ||
2094                     start + orig_eb->len < this_eb_start + stripe_len) {
2095                         ret = rmw_eb(info, eb, orig_eb);
2096                         BUG_ON(ret);
2097                 } else {
2098                         memcpy(eb->data, orig_eb->data + eb->start - start, stripe_len);
2099                 }
2100                 ebs[i] = eb;
2101         }
2102 }
2103
2104 int write_raid56_with_parity(struct btrfs_fs_info *info,
2105                              struct extent_buffer *eb,
2106                              struct btrfs_multi_bio *multi,
2107                              u64 stripe_len, u64 *raid_map)
2108 {
2109         struct extent_buffer **ebs, *p_eb = NULL, *q_eb = NULL;
2110         int i;
2111         int j;
2112         int ret;
2113         int alloc_size = eb->len;
2114
2115         ebs = kmalloc(sizeof(*ebs) * multi->num_stripes, GFP_NOFS);
2116         BUG_ON(!ebs);
2117
2118         if (stripe_len > alloc_size)
2119                 alloc_size = stripe_len;
2120
2121         split_eb_for_raid56(info, eb, ebs, stripe_len, raid_map,
2122                             multi->num_stripes);
2123
2124         for (i = 0; i < multi->num_stripes; i++) {
2125                 struct extent_buffer *new_eb;
2126                 if (raid_map[i] < BTRFS_RAID5_P_STRIPE) {
2127                         ebs[i]->dev_bytenr = multi->stripes[i].physical;
2128                         ebs[i]->fd = multi->stripes[i].dev->fd;
2129                         multi->stripes[i].dev->total_ios++;
2130                         BUG_ON(ebs[i]->start != raid_map[i]);
2131                         continue;
2132                 }
2133                 new_eb = kmalloc(sizeof(*eb) + alloc_size, GFP_NOFS);
2134                 BUG_ON(!new_eb);
2135                 new_eb->dev_bytenr = multi->stripes[i].physical;
2136                 new_eb->fd = multi->stripes[i].dev->fd;
2137                 multi->stripes[i].dev->total_ios++;
2138                 new_eb->len = stripe_len;
2139
2140                 if (raid_map[i] == BTRFS_RAID5_P_STRIPE)
2141                         p_eb = new_eb;
2142                 else if (raid_map[i] == BTRFS_RAID6_Q_STRIPE)
2143                         q_eb = new_eb;
2144         }
2145         if (q_eb) {
2146                 void **pointers;
2147
2148                 pointers = kmalloc(sizeof(*pointers) * multi->num_stripes,
2149                                    GFP_NOFS);
2150                 BUG_ON(!pointers);
2151
2152                 ebs[multi->num_stripes - 2] = p_eb;
2153                 ebs[multi->num_stripes - 1] = q_eb;
2154
2155                 for (i = 0; i < multi->num_stripes; i++)
2156                         pointers[i] = ebs[i]->data;
2157
2158                 raid6_gen_syndrome(multi->num_stripes, stripe_len, pointers);
2159                 kfree(pointers);
2160         } else {
2161                 ebs[multi->num_stripes - 1] = p_eb;
2162                 memcpy(p_eb->data, ebs[0]->data, stripe_len);
2163                 for (j = 1; j < multi->num_stripes - 1; j++) {
2164                         for (i = 0; i < stripe_len; i += sizeof(u64)) {
2165                                 u64 p_eb_data;
2166                                 u64 ebs_data;
2167
2168                                 p_eb_data = get_unaligned_64(p_eb->data + i);
2169                                 ebs_data = get_unaligned_64(ebs[j]->data + i);
2170                                 p_eb_data ^= ebs_data;
2171                                 put_unaligned_64(p_eb_data, p_eb->data + i);
2172                         }
2173                 }
2174         }
2175
2176         for (i = 0; i < multi->num_stripes; i++) {
2177                 ret = write_extent_to_disk(ebs[i]);
2178                 BUG_ON(ret);
2179                 if (ebs[i] != eb)
2180                         kfree(ebs[i]);
2181         }
2182
2183         kfree(ebs);
2184
2185         return 0;
2186 }