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