Merge branch 'liubo-image-restore'
[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 #define _XOPEN_SOURCE 600
19 #define __USE_XOPEN2K
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <uuid/uuid.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include "ctree.h"
28 #include "disk-io.h"
29 #include "transaction.h"
30 #include "print-tree.h"
31 #include "volumes.h"
32
33 struct stripe {
34         struct btrfs_device *dev;
35         u64 physical;
36 };
37
38 static inline int nr_parity_stripes(struct map_lookup *map)
39 {
40         if (map->type & BTRFS_BLOCK_GROUP_RAID5)
41                 return 1;
42         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
43                 return 2;
44         else
45                 return 0;
46 }
47
48 static inline int nr_data_stripes(struct map_lookup *map)
49 {
50         return map->num_stripes - nr_parity_stripes(map);
51 }
52
53 #define is_parity_stripe(x) ( ((x) == BTRFS_RAID5_P_STRIPE) || ((x) == BTRFS_RAID6_Q_STRIPE) )
54
55 static LIST_HEAD(fs_uuids);
56
57 static struct btrfs_device *__find_device(struct list_head *head, u64 devid,
58                                           u8 *uuid)
59 {
60         struct btrfs_device *dev;
61         struct list_head *cur;
62
63         list_for_each(cur, head) {
64                 dev = list_entry(cur, struct btrfs_device, dev_list);
65                 if (dev->devid == devid &&
66                     !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE)) {
67                         return dev;
68                 }
69         }
70         return NULL;
71 }
72
73 static struct btrfs_fs_devices *find_fsid(u8 *fsid)
74 {
75         struct list_head *cur;
76         struct btrfs_fs_devices *fs_devices;
77
78         list_for_each(cur, &fs_uuids) {
79                 fs_devices = list_entry(cur, struct btrfs_fs_devices, list);
80                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
81                         return fs_devices;
82         }
83         return NULL;
84 }
85
86 static int device_list_add(const char *path,
87                            struct btrfs_super_block *disk_super,
88                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
89 {
90         struct btrfs_device *device;
91         struct btrfs_fs_devices *fs_devices;
92         u64 found_transid = btrfs_super_generation(disk_super);
93
94         fs_devices = find_fsid(disk_super->fsid);
95         if (!fs_devices) {
96                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
97                 if (!fs_devices)
98                         return -ENOMEM;
99                 INIT_LIST_HEAD(&fs_devices->devices);
100                 list_add(&fs_devices->list, &fs_uuids);
101                 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
102                 fs_devices->latest_devid = devid;
103                 fs_devices->latest_trans = found_transid;
104                 fs_devices->lowest_devid = (u64)-1;
105                 device = NULL;
106         } else {
107                 device = __find_device(&fs_devices->devices, devid,
108                                        disk_super->dev_item.uuid);
109         }
110         if (!device) {
111                 device = kzalloc(sizeof(*device), GFP_NOFS);
112                 if (!device) {
113                         /* we can safely leave the fs_devices entry around */
114                         return -ENOMEM;
115                 }
116                 device->fd = -1;
117                 device->devid = devid;
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                 device->total_devs = btrfs_super_num_devices(disk_super);
127                 device->super_bytes_used = btrfs_super_bytes_used(disk_super);
128                 device->total_bytes =
129                         btrfs_stack_device_total_bytes(&disk_super->dev_item);
130                 device->bytes_used =
131                         btrfs_stack_device_bytes_used(&disk_super->dev_item);
132                 list_add(&device->dev_list, &fs_devices->devices);
133                 device->fs_devices = fs_devices;
134         } else if (!device->name || strcmp(device->name, path)) {
135                 char *name = strdup(path);
136                 if (!name)
137                         return -ENOMEM;
138                 kfree(device->name);
139                 device->name = name;
140         }
141
142
143         if (found_transid > fs_devices->latest_trans) {
144                 fs_devices->latest_devid = devid;
145                 fs_devices->latest_trans = found_transid;
146         }
147         if (fs_devices->lowest_devid > devid) {
148                 fs_devices->lowest_devid = devid;
149         }
150         *fs_devices_ret = fs_devices;
151         return 0;
152 }
153
154 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
155 {
156         struct btrfs_fs_devices *seed_devices;
157         struct list_head *cur;
158         struct btrfs_device *device;
159 again:
160         list_for_each(cur, &fs_devices->devices) {
161                 device = list_entry(cur, struct btrfs_device, dev_list);
162                 if (device->fd != -1) {
163                         fsync(device->fd);
164                         if (posix_fadvise(device->fd, 0, 0, POSIX_FADV_DONTNEED))
165                                 fprintf(stderr, "Warning, could not drop caches\n");
166                         close(device->fd);
167                         device->fd = -1;
168                 }
169                 device->writeable = 0;
170         }
171
172         seed_devices = fs_devices->seed;
173         fs_devices->seed = NULL;
174         if (seed_devices) {
175                 fs_devices = seed_devices;
176                 goto again;
177         }
178
179         return 0;
180 }
181
182 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices, int flags)
183 {
184         int fd;
185         struct list_head *head = &fs_devices->devices;
186         struct list_head *cur;
187         struct btrfs_device *device;
188         int ret;
189
190         list_for_each(cur, head) {
191                 device = list_entry(cur, struct btrfs_device, dev_list);
192                 if (!device->name) {
193                         printk("no name for device %llu, skip it now\n", device->devid);
194                         continue;
195                 }
196
197                 fd = open(device->name, flags);
198                 if (fd < 0) {
199                         ret = -errno;
200                         goto fail;
201                 }
202
203                 if (posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED))
204                         fprintf(stderr, "Warning, could not drop caches\n");
205
206                 if (device->devid == fs_devices->latest_devid)
207                         fs_devices->latest_bdev = fd;
208                 if (device->devid == fs_devices->lowest_devid)
209                         fs_devices->lowest_bdev = fd;
210                 device->fd = fd;
211                 if (flags == O_RDWR)
212                         device->writeable = 1;
213         }
214         return 0;
215 fail:
216         btrfs_close_devices(fs_devices);
217         return ret;
218 }
219
220 int btrfs_scan_one_device(int fd, const char *path,
221                           struct btrfs_fs_devices **fs_devices_ret,
222                           u64 *total_devs, u64 super_offset)
223 {
224         struct btrfs_super_block *disk_super;
225         char *buf;
226         int ret;
227         u64 devid;
228         char uuidbuf[37];
229
230         buf = malloc(4096);
231         if (!buf) {
232                 ret = -ENOMEM;
233                 goto error;
234         }
235         disk_super = (struct btrfs_super_block *)buf;
236         ret = btrfs_read_dev_super(fd, disk_super, super_offset);
237         if (ret < 0) {
238                 ret = -EIO;
239                 goto error_brelse;
240         }
241         devid = le64_to_cpu(disk_super->dev_item.devid);
242         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_METADUMP)
243                 *total_devs = 1;
244         else
245                 *total_devs = btrfs_super_num_devices(disk_super);
246         uuid_unparse(disk_super->fsid, uuidbuf);
247
248         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
249
250 error_brelse:
251         free(buf);
252 error:
253         return ret;
254 }
255
256 /*
257  * this uses a pretty simple search, the expectation is that it is
258  * called very infrequently and that a given device has a small number
259  * of extents
260  */
261 static int find_free_dev_extent(struct btrfs_trans_handle *trans,
262                                 struct btrfs_device *device,
263                                 struct btrfs_path *path,
264                                 u64 num_bytes, u64 *start)
265 {
266         struct btrfs_key key;
267         struct btrfs_root *root = device->dev_root;
268         struct btrfs_dev_extent *dev_extent = NULL;
269         u64 hole_size = 0;
270         u64 last_byte = 0;
271         u64 search_start = 0;
272         u64 search_end = device->total_bytes;
273         int ret;
274         int slot = 0;
275         int start_found;
276         struct extent_buffer *l;
277
278         start_found = 0;
279         path->reada = 2;
280
281         /* FIXME use last free of some kind */
282
283         /* we don't want to overwrite the superblock on the drive,
284          * so we make sure to start at an offset of at least 1MB
285          */
286         search_start = max((u64)1024 * 1024, search_start);
287
288         if (root->fs_info->alloc_start + num_bytes <= device->total_bytes)
289                 search_start = max(root->fs_info->alloc_start, search_start);
290
291         key.objectid = device->devid;
292         key.offset = search_start;
293         key.type = BTRFS_DEV_EXTENT_KEY;
294         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
295         if (ret < 0)
296                 goto error;
297         ret = btrfs_previous_item(root, path, 0, key.type);
298         if (ret < 0)
299                 goto error;
300         l = path->nodes[0];
301         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
302         while (1) {
303                 l = path->nodes[0];
304                 slot = path->slots[0];
305                 if (slot >= btrfs_header_nritems(l)) {
306                         ret = btrfs_next_leaf(root, path);
307                         if (ret == 0)
308                                 continue;
309                         if (ret < 0)
310                                 goto error;
311 no_more_items:
312                         if (!start_found) {
313                                 if (search_start >= search_end) {
314                                         ret = -ENOSPC;
315                                         goto error;
316                                 }
317                                 *start = search_start;
318                                 start_found = 1;
319                                 goto check_pending;
320                         }
321                         *start = last_byte > search_start ?
322                                 last_byte : search_start;
323                         if (search_end <= *start) {
324                                 ret = -ENOSPC;
325                                 goto error;
326                         }
327                         goto check_pending;
328                 }
329                 btrfs_item_key_to_cpu(l, &key, slot);
330
331                 if (key.objectid < device->devid)
332                         goto next;
333
334                 if (key.objectid > device->devid)
335                         goto no_more_items;
336
337                 if (key.offset >= search_start && key.offset > last_byte &&
338                     start_found) {
339                         if (last_byte < search_start)
340                                 last_byte = search_start;
341                         hole_size = key.offset - last_byte;
342                         if (key.offset > last_byte &&
343                             hole_size >= num_bytes) {
344                                 *start = last_byte;
345                                 goto check_pending;
346                         }
347                 }
348                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY) {
349                         goto next;
350                 }
351
352                 start_found = 1;
353                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
354                 last_byte = key.offset + btrfs_dev_extent_length(l, dev_extent);
355 next:
356                 path->slots[0]++;
357                 cond_resched();
358         }
359 check_pending:
360         /* we have to make sure we didn't find an extent that has already
361          * been allocated by the map tree or the original allocation
362          */
363         btrfs_release_path(root, path);
364         BUG_ON(*start < search_start);
365
366         if (*start + num_bytes > search_end) {
367                 ret = -ENOSPC;
368                 goto error;
369         }
370         /* check for pending inserts here */
371         return 0;
372
373 error:
374         btrfs_release_path(root, path);
375         return ret;
376 }
377
378 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
379                            struct btrfs_device *device,
380                            u64 chunk_tree, u64 chunk_objectid,
381                            u64 chunk_offset,
382                            u64 num_bytes, u64 *start)
383 {
384         int ret;
385         struct btrfs_path *path;
386         struct btrfs_root *root = device->dev_root;
387         struct btrfs_dev_extent *extent;
388         struct extent_buffer *leaf;
389         struct btrfs_key key;
390
391         path = btrfs_alloc_path();
392         if (!path)
393                 return -ENOMEM;
394
395         ret = find_free_dev_extent(trans, device, path, num_bytes, start);
396         if (ret) {
397                 goto err;
398         }
399
400         key.objectid = device->devid;
401         key.offset = *start;
402         key.type = BTRFS_DEV_EXTENT_KEY;
403         ret = btrfs_insert_empty_item(trans, root, path, &key,
404                                       sizeof(*extent));
405         BUG_ON(ret);
406
407         leaf = path->nodes[0];
408         extent = btrfs_item_ptr(leaf, path->slots[0],
409                                 struct btrfs_dev_extent);
410         btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
411         btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
412         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
413
414         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
415                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
416                     BTRFS_UUID_SIZE);
417
418         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
419         btrfs_mark_buffer_dirty(leaf);
420 err:
421         btrfs_free_path(path);
422         return ret;
423 }
424
425 static int find_next_chunk(struct btrfs_root *root, u64 objectid, u64 *offset)
426 {
427         struct btrfs_path *path;
428         int ret;
429         struct btrfs_key key;
430         struct btrfs_chunk *chunk;
431         struct btrfs_key found_key;
432
433         path = btrfs_alloc_path();
434         BUG_ON(!path);
435
436         key.objectid = objectid;
437         key.offset = (u64)-1;
438         key.type = BTRFS_CHUNK_ITEM_KEY;
439
440         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
441         if (ret < 0)
442                 goto error;
443
444         BUG_ON(ret == 0);
445
446         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
447         if (ret) {
448                 *offset = 0;
449         } else {
450                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
451                                       path->slots[0]);
452                 if (found_key.objectid != objectid)
453                         *offset = 0;
454                 else {
455                         chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
456                                                struct btrfs_chunk);
457                         *offset = found_key.offset +
458                                 btrfs_chunk_length(path->nodes[0], chunk);
459                 }
460         }
461         ret = 0;
462 error:
463         btrfs_free_path(path);
464         return ret;
465 }
466
467 static int find_next_devid(struct btrfs_root *root, struct btrfs_path *path,
468                            u64 *objectid)
469 {
470         int ret;
471         struct btrfs_key key;
472         struct btrfs_key found_key;
473
474         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
475         key.type = BTRFS_DEV_ITEM_KEY;
476         key.offset = (u64)-1;
477
478         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
479         if (ret < 0)
480                 goto error;
481
482         BUG_ON(ret == 0);
483
484         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
485                                   BTRFS_DEV_ITEM_KEY);
486         if (ret) {
487                 *objectid = 1;
488         } else {
489                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
490                                       path->slots[0]);
491                 *objectid = found_key.offset + 1;
492         }
493         ret = 0;
494 error:
495         btrfs_release_path(root, path);
496         return ret;
497 }
498
499 /*
500  * the device information is stored in the chunk root
501  * the btrfs_device struct should be fully filled in
502  */
503 int btrfs_add_device(struct btrfs_trans_handle *trans,
504                      struct btrfs_root *root,
505                      struct btrfs_device *device)
506 {
507         int ret;
508         struct btrfs_path *path;
509         struct btrfs_dev_item *dev_item;
510         struct extent_buffer *leaf;
511         struct btrfs_key key;
512         unsigned long ptr;
513         u64 free_devid = 0;
514
515         root = root->fs_info->chunk_root;
516
517         path = btrfs_alloc_path();
518         if (!path)
519                 return -ENOMEM;
520
521         ret = find_next_devid(root, path, &free_devid);
522         if (ret)
523                 goto out;
524
525         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
526         key.type = BTRFS_DEV_ITEM_KEY;
527         key.offset = free_devid;
528
529         ret = btrfs_insert_empty_item(trans, root, path, &key,
530                                       sizeof(*dev_item));
531         if (ret)
532                 goto out;
533
534         leaf = path->nodes[0];
535         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
536
537         device->devid = free_devid;
538         btrfs_set_device_id(leaf, dev_item, device->devid);
539         btrfs_set_device_generation(leaf, dev_item, 0);
540         btrfs_set_device_type(leaf, dev_item, device->type);
541         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
542         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
543         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
544         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
545         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
546         btrfs_set_device_group(leaf, dev_item, 0);
547         btrfs_set_device_seek_speed(leaf, dev_item, 0);
548         btrfs_set_device_bandwidth(leaf, dev_item, 0);
549         btrfs_set_device_start_offset(leaf, dev_item, 0);
550
551         ptr = (unsigned long)btrfs_device_uuid(dev_item);
552         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
553         ptr = (unsigned long)btrfs_device_fsid(dev_item);
554         write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
555         btrfs_mark_buffer_dirty(leaf);
556         ret = 0;
557
558 out:
559         btrfs_free_path(path);
560         return ret;
561 }
562
563 int btrfs_update_device(struct btrfs_trans_handle *trans,
564                         struct btrfs_device *device)
565 {
566         int ret;
567         struct btrfs_path *path;
568         struct btrfs_root *root;
569         struct btrfs_dev_item *dev_item;
570         struct extent_buffer *leaf;
571         struct btrfs_key key;
572
573         root = device->dev_root->fs_info->chunk_root;
574
575         path = btrfs_alloc_path();
576         if (!path)
577                 return -ENOMEM;
578
579         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
580         key.type = BTRFS_DEV_ITEM_KEY;
581         key.offset = device->devid;
582
583         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
584         if (ret < 0)
585                 goto out;
586
587         if (ret > 0) {
588                 ret = -ENOENT;
589                 goto out;
590         }
591
592         leaf = path->nodes[0];
593         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
594
595         btrfs_set_device_id(leaf, dev_item, device->devid);
596         btrfs_set_device_type(leaf, dev_item, device->type);
597         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
598         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
599         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
600         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
601         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
602         btrfs_mark_buffer_dirty(leaf);
603
604 out:
605         btrfs_free_path(path);
606         return ret;
607 }
608
609 int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
610                            struct btrfs_root *root,
611                            struct btrfs_key *key,
612                            struct btrfs_chunk *chunk, int item_size)
613 {
614         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
615         struct btrfs_disk_key disk_key;
616         u32 array_size;
617         u8 *ptr;
618
619         array_size = btrfs_super_sys_array_size(super_copy);
620         if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
621                 return -EFBIG;
622
623         ptr = super_copy->sys_chunk_array + array_size;
624         btrfs_cpu_key_to_disk(&disk_key, key);
625         memcpy(ptr, &disk_key, sizeof(disk_key));
626         ptr += sizeof(disk_key);
627         memcpy(ptr, chunk, item_size);
628         item_size += sizeof(disk_key);
629         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
630         return 0;
631 }
632
633 static u64 div_factor(u64 num, int factor)
634 {
635         if (factor == 10)
636                 return num;
637         num *= factor;
638         return num / 10;
639 }
640
641 static u64 chunk_bytes_by_type(u64 type, u64 calc_size, int num_stripes,
642                                int sub_stripes)
643 {
644         if (type & (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_DUP))
645                 return calc_size;
646         else if (type & BTRFS_BLOCK_GROUP_RAID10)
647                 return calc_size * (num_stripes / sub_stripes);
648         else if (type & BTRFS_BLOCK_GROUP_RAID5)
649                 return calc_size * (num_stripes - 1);
650         else if (type & BTRFS_BLOCK_GROUP_RAID6)
651                 return calc_size * (num_stripes - 2);
652         else
653                 return calc_size * num_stripes;
654 }
655
656
657 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
658 {
659         /* TODO, add a way to store the preferred stripe size */
660         return 64 * 1024;
661 }
662
663 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
664                       struct btrfs_root *extent_root, u64 *start,
665                       u64 *num_bytes, u64 type)
666 {
667         u64 dev_offset;
668         struct btrfs_fs_info *info = extent_root->fs_info;
669         struct btrfs_root *chunk_root = info->chunk_root;
670         struct btrfs_stripe *stripes;
671         struct btrfs_device *device = NULL;
672         struct btrfs_chunk *chunk;
673         struct list_head private_devs;
674         struct list_head *dev_list = &info->fs_devices->devices;
675         struct list_head *cur;
676         struct map_lookup *map;
677         int min_stripe_size = 1 * 1024 * 1024;
678         u64 calc_size = 8 * 1024 * 1024;
679         u64 min_free;
680         u64 max_chunk_size = 4 * calc_size;
681         u64 avail;
682         u64 max_avail = 0;
683         u64 percent_max;
684         int num_stripes = 1;
685         int min_stripes = 1;
686         int sub_stripes = 0;
687         int looped = 0;
688         int ret;
689         int index;
690         int stripe_len = 64 * 1024;
691         struct btrfs_key key;
692         u64 offset;
693
694         if (list_empty(dev_list)) {
695                 return -ENOSPC;
696         }
697
698         if (type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
699                     BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
700                     BTRFS_BLOCK_GROUP_RAID10 |
701                     BTRFS_BLOCK_GROUP_DUP)) {
702                 if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
703                         calc_size = 8 * 1024 * 1024;
704                         max_chunk_size = calc_size * 2;
705                         min_stripe_size = 1 * 1024 * 1024;
706                 } else if (type & BTRFS_BLOCK_GROUP_DATA) {
707                         calc_size = 1024 * 1024 * 1024;
708                         max_chunk_size = 10 * calc_size;
709                         min_stripe_size = 64 * 1024 * 1024;
710                 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
711                         calc_size = 1024 * 1024 * 1024;
712                         max_chunk_size = 4 * calc_size;
713                         min_stripe_size = 32 * 1024 * 1024;
714                 }
715         }
716         if (type & BTRFS_BLOCK_GROUP_RAID1) {
717                 num_stripes = min_t(u64, 2,
718                                   btrfs_super_num_devices(info->super_copy));
719                 if (num_stripes < 2)
720                         return -ENOSPC;
721                 min_stripes = 2;
722         }
723         if (type & BTRFS_BLOCK_GROUP_DUP) {
724                 num_stripes = 2;
725                 min_stripes = 2;
726         }
727         if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
728                 num_stripes = btrfs_super_num_devices(info->super_copy);
729                 min_stripes = 2;
730         }
731         if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
732                 num_stripes = btrfs_super_num_devices(info->super_copy);
733                 if (num_stripes < 4)
734                         return -ENOSPC;
735                 num_stripes &= ~(u32)1;
736                 sub_stripes = 2;
737                 min_stripes = 4;
738         }
739         if (type & (BTRFS_BLOCK_GROUP_RAID5)) {
740                 num_stripes = btrfs_super_num_devices(info->super_copy);
741                 if (num_stripes < 2)
742                         return -ENOSPC;
743                 min_stripes = 2;
744                 stripe_len = find_raid56_stripe_len(num_stripes - 1,
745                                     btrfs_super_stripesize(info->super_copy));
746         }
747         if (type & (BTRFS_BLOCK_GROUP_RAID6)) {
748                 num_stripes = btrfs_super_num_devices(info->super_copy);
749                 if (num_stripes < 3)
750                         return -ENOSPC;
751                 min_stripes = 3;
752                 stripe_len = find_raid56_stripe_len(num_stripes - 2,
753                                     btrfs_super_stripesize(info->super_copy));
754         }
755
756         /* we don't want a chunk larger than 10% of the FS */
757         percent_max = div_factor(btrfs_super_total_bytes(info->super_copy), 1);
758         max_chunk_size = min(percent_max, max_chunk_size);
759
760 again:
761         if (chunk_bytes_by_type(type, calc_size, num_stripes, sub_stripes) >
762             max_chunk_size) {
763                 calc_size = max_chunk_size;
764                 calc_size /= num_stripes;
765                 calc_size /= stripe_len;
766                 calc_size *= stripe_len;
767         }
768         /* we don't want tiny stripes */
769         calc_size = max_t(u64, calc_size, min_stripe_size);
770
771         calc_size /= stripe_len;
772         calc_size *= stripe_len;
773         INIT_LIST_HEAD(&private_devs);
774         cur = dev_list->next;
775         index = 0;
776
777         if (type & BTRFS_BLOCK_GROUP_DUP)
778                 min_free = calc_size * 2;
779         else
780                 min_free = calc_size;
781
782         /* build a private list of devices we will allocate from */
783         while(index < num_stripes) {
784                 device = list_entry(cur, struct btrfs_device, dev_list);
785                 avail = device->total_bytes - device->bytes_used;
786                 cur = cur->next;
787                 if (avail >= min_free) {
788                         list_move_tail(&device->dev_list, &private_devs);
789                         index++;
790                         if (type & BTRFS_BLOCK_GROUP_DUP)
791                                 index++;
792                 } else if (avail > max_avail)
793                         max_avail = avail;
794                 if (cur == dev_list)
795                         break;
796         }
797         if (index < num_stripes) {
798                 list_splice(&private_devs, dev_list);
799                 if (index >= min_stripes) {
800                         num_stripes = index;
801                         if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
802                                 num_stripes /= sub_stripes;
803                                 num_stripes *= sub_stripes;
804                         }
805                         looped = 1;
806                         goto again;
807                 }
808                 if (!looped && max_avail > 0) {
809                         looped = 1;
810                         calc_size = max_avail;
811                         goto again;
812                 }
813                 return -ENOSPC;
814         }
815         ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
816                               &offset);
817         if (ret)
818                 return ret;
819         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
820         key.type = BTRFS_CHUNK_ITEM_KEY;
821         key.offset = offset;
822
823         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
824         if (!chunk)
825                 return -ENOMEM;
826
827         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
828         if (!map) {
829                 kfree(chunk);
830                 return -ENOMEM;
831         }
832
833         stripes = &chunk->stripe;
834         *num_bytes = chunk_bytes_by_type(type, calc_size,
835                                          num_stripes, sub_stripes);
836         index = 0;
837         while(index < num_stripes) {
838                 struct btrfs_stripe *stripe;
839                 BUG_ON(list_empty(&private_devs));
840                 cur = private_devs.next;
841                 device = list_entry(cur, struct btrfs_device, dev_list);
842
843                 /* loop over this device again if we're doing a dup group */
844                 if (!(type & BTRFS_BLOCK_GROUP_DUP) ||
845                     (index == num_stripes - 1))
846                         list_move_tail(&device->dev_list, dev_list);
847
848                 ret = btrfs_alloc_dev_extent(trans, device,
849                              info->chunk_root->root_key.objectid,
850                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
851                              calc_size, &dev_offset);
852                 BUG_ON(ret);
853
854                 device->bytes_used += calc_size;
855                 ret = btrfs_update_device(trans, device);
856                 BUG_ON(ret);
857
858                 map->stripes[index].dev = device;
859                 map->stripes[index].physical = dev_offset;
860                 stripe = stripes + index;
861                 btrfs_set_stack_stripe_devid(stripe, device->devid);
862                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
863                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
864                 index++;
865         }
866         BUG_ON(!list_empty(&private_devs));
867
868         /* key was set above */
869         btrfs_set_stack_chunk_length(chunk, *num_bytes);
870         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
871         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
872         btrfs_set_stack_chunk_type(chunk, type);
873         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
874         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
875         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
876         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
877         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
878         map->sector_size = extent_root->sectorsize;
879         map->stripe_len = stripe_len;
880         map->io_align = stripe_len;
881         map->io_width = stripe_len;
882         map->type = type;
883         map->num_stripes = num_stripes;
884         map->sub_stripes = sub_stripes;
885
886         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
887                                 btrfs_chunk_item_size(num_stripes));
888         BUG_ON(ret);
889         *start = key.offset;;
890
891         map->ce.start = key.offset;
892         map->ce.size = *num_bytes;
893
894         ret = insert_cache_extent(&info->mapping_tree.cache_tree, &map->ce);
895         BUG_ON(ret);
896
897         if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
898                 ret = btrfs_add_system_chunk(trans, chunk_root, &key,
899                                     chunk, btrfs_chunk_item_size(num_stripes));
900                 BUG_ON(ret);
901         }
902
903         kfree(chunk);
904         return ret;
905 }
906
907 int btrfs_alloc_data_chunk(struct btrfs_trans_handle *trans,
908                            struct btrfs_root *extent_root, u64 *start,
909                            u64 num_bytes, u64 type)
910 {
911         u64 dev_offset;
912         struct btrfs_fs_info *info = extent_root->fs_info;
913         struct btrfs_root *chunk_root = info->chunk_root;
914         struct btrfs_stripe *stripes;
915         struct btrfs_device *device = NULL;
916         struct btrfs_chunk *chunk;
917         struct list_head *dev_list = &info->fs_devices->devices;
918         struct list_head *cur;
919         struct map_lookup *map;
920         u64 calc_size = 8 * 1024 * 1024;
921         int num_stripes = 1;
922         int sub_stripes = 0;
923         int ret;
924         int index;
925         int stripe_len = 64 * 1024;
926         struct btrfs_key key;
927
928         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
929         key.type = BTRFS_CHUNK_ITEM_KEY;
930         ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
931                               &key.offset);
932         if (ret)
933                 return ret;
934
935         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
936         if (!chunk)
937                 return -ENOMEM;
938
939         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
940         if (!map) {
941                 kfree(chunk);
942                 return -ENOMEM;
943         }
944
945         stripes = &chunk->stripe;
946         calc_size = num_bytes;
947
948         index = 0;
949         cur = dev_list->next;
950         device = list_entry(cur, struct btrfs_device, dev_list);
951
952         while (index < num_stripes) {
953                 struct btrfs_stripe *stripe;
954
955                 ret = btrfs_alloc_dev_extent(trans, device,
956                              info->chunk_root->root_key.objectid,
957                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
958                              calc_size, &dev_offset);
959                 BUG_ON(ret);
960
961                 device->bytes_used += calc_size;
962                 ret = btrfs_update_device(trans, device);
963                 BUG_ON(ret);
964
965                 map->stripes[index].dev = device;
966                 map->stripes[index].physical = dev_offset;
967                 stripe = stripes + index;
968                 btrfs_set_stack_stripe_devid(stripe, device->devid);
969                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
970                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
971                 index++;
972         }
973
974         /* key was set above */
975         btrfs_set_stack_chunk_length(chunk, num_bytes);
976         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
977         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
978         btrfs_set_stack_chunk_type(chunk, type);
979         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
980         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
981         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
982         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
983         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
984         map->sector_size = extent_root->sectorsize;
985         map->stripe_len = stripe_len;
986         map->io_align = stripe_len;
987         map->io_width = stripe_len;
988         map->type = type;
989         map->num_stripes = num_stripes;
990         map->sub_stripes = sub_stripes;
991
992         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
993                                 btrfs_chunk_item_size(num_stripes));
994         BUG_ON(ret);
995         *start = key.offset;
996
997         map->ce.start = key.offset;
998         map->ce.size = num_bytes;
999
1000         ret = insert_cache_extent(&info->mapping_tree.cache_tree, &map->ce);
1001         BUG_ON(ret);
1002
1003         kfree(chunk);
1004         return ret;
1005 }
1006
1007 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
1008 {
1009         cache_tree_init(&tree->cache_tree);
1010 }
1011
1012 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
1013 {
1014         struct cache_extent *ce;
1015         struct map_lookup *map;
1016         int ret;
1017
1018         ce = search_cache_extent(&map_tree->cache_tree, logical);
1019         BUG_ON(!ce);
1020         BUG_ON(ce->start > logical || ce->start + ce->size < logical);
1021         map = container_of(ce, struct map_lookup, ce);
1022
1023         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
1024                 ret = map->num_stripes;
1025         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1026                 ret = map->sub_stripes;
1027         else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
1028                 ret = 2;
1029         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1030                 ret = 3;
1031         else
1032                 ret = 1;
1033         return ret;
1034 }
1035
1036 int btrfs_next_metadata(struct btrfs_mapping_tree *map_tree, u64 *logical,
1037                         u64 *size)
1038 {
1039         struct cache_extent *ce;
1040         struct map_lookup *map;
1041
1042         ce = search_cache_extent(&map_tree->cache_tree, *logical);
1043
1044         while (ce) {
1045                 ce = next_cache_extent(ce);
1046                 if (!ce)
1047                         return -ENOENT;
1048
1049                 map = container_of(ce, struct map_lookup, ce);
1050                 if (map->type & BTRFS_BLOCK_GROUP_METADATA) {
1051                         *logical = ce->start;
1052                         *size = ce->size;
1053                         return 0;
1054                 }
1055         }
1056
1057         return -ENOENT;
1058 }
1059
1060 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
1061                      u64 chunk_start, u64 physical, u64 devid,
1062                      u64 **logical, int *naddrs, int *stripe_len)
1063 {
1064         struct cache_extent *ce;
1065         struct map_lookup *map;
1066         u64 *buf;
1067         u64 bytenr;
1068         u64 length;
1069         u64 stripe_nr;
1070         u64 rmap_len;
1071         int i, j, nr = 0;
1072
1073         ce = search_cache_extent(&map_tree->cache_tree, chunk_start);
1074         BUG_ON(!ce);
1075         map = container_of(ce, struct map_lookup, ce);
1076
1077         length = ce->size;
1078         rmap_len = map->stripe_len;
1079         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1080                 length = ce->size / (map->num_stripes / map->sub_stripes);
1081         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
1082                 length = ce->size / map->num_stripes;
1083         else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1084                               BTRFS_BLOCK_GROUP_RAID6)) {
1085                 length = ce->size / nr_data_stripes(map);
1086                 rmap_len = map->stripe_len * nr_data_stripes(map);
1087         }
1088
1089         buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1090
1091         for (i = 0; i < map->num_stripes; i++) {
1092                 if (devid && map->stripes[i].dev->devid != devid)
1093                         continue;
1094                 if (map->stripes[i].physical > physical ||
1095                     map->stripes[i].physical + length <= physical)
1096                         continue;
1097
1098                 stripe_nr = (physical - map->stripes[i].physical) /
1099                             map->stripe_len;
1100
1101                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1102                         stripe_nr = (stripe_nr * map->num_stripes + i) /
1103                                     map->sub_stripes;
1104                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1105                         stripe_nr = stripe_nr * map->num_stripes + i;
1106                 } /* else if RAID[56], multiply by nr_data_stripes().
1107                    * Alternatively, just use rmap_len below instead of
1108                    * map->stripe_len */
1109
1110                 bytenr = ce->start + stripe_nr * rmap_len;
1111                 for (j = 0; j < nr; j++) {
1112                         if (buf[j] == bytenr)
1113                                 break;
1114                 }
1115                 if (j == nr)
1116                         buf[nr++] = bytenr;
1117         }
1118
1119         *logical = buf;
1120         *naddrs = nr;
1121         *stripe_len = rmap_len;
1122
1123         return 0;
1124 }
1125
1126 static inline int parity_smaller(u64 a, u64 b)
1127 {
1128         return a > b;
1129 }
1130
1131 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
1132 static void sort_parity_stripes(struct btrfs_multi_bio *bbio, u64 *raid_map)
1133 {
1134         struct btrfs_bio_stripe s;
1135         int i;
1136         u64 l;
1137         int again = 1;
1138
1139         while (again) {
1140                 again = 0;
1141                 for (i = 0; i < bbio->num_stripes - 1; i++) {
1142                         if (parity_smaller(raid_map[i], raid_map[i+1])) {
1143                                 s = bbio->stripes[i];
1144                                 l = raid_map[i];
1145                                 bbio->stripes[i] = bbio->stripes[i+1];
1146                                 raid_map[i] = raid_map[i+1];
1147                                 bbio->stripes[i+1] = s;
1148                                 raid_map[i+1] = l;
1149                                 again = 1;
1150                         }
1151                 }
1152         }
1153 }
1154
1155 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1156                     u64 logical, u64 *length,
1157                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1158                     u64 **raid_map_ret)
1159 {
1160         return __btrfs_map_block(map_tree, rw, logical, length, NULL,
1161                                  multi_ret, mirror_num, raid_map_ret);
1162 }
1163
1164 int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1165                     u64 logical, u64 *length, u64 *type,
1166                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1167                     u64 **raid_map_ret)
1168 {
1169         struct cache_extent *ce;
1170         struct map_lookup *map;
1171         u64 offset;
1172         u64 stripe_offset;
1173         u64 stripe_nr;
1174         u64 *raid_map = NULL;
1175         int stripes_allocated = 8;
1176         int stripes_required = 1;
1177         int stripe_index;
1178         int i;
1179         struct btrfs_multi_bio *multi = NULL;
1180
1181         if (multi_ret && rw == READ) {
1182                 stripes_allocated = 1;
1183         }
1184 again:
1185         ce = search_cache_extent(&map_tree->cache_tree, logical);
1186         if (!ce) {
1187                 if (multi)
1188                         kfree(multi);
1189                 return -ENOENT;
1190         }
1191         if (ce->start > logical || ce->start + ce->size < logical) {
1192                 if (multi)
1193                         kfree(multi);
1194                 return -ENOENT;
1195         }
1196
1197         if (multi_ret) {
1198                 multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
1199                                 GFP_NOFS);
1200                 if (!multi)
1201                         return -ENOMEM;
1202         }
1203         map = container_of(ce, struct map_lookup, ce);
1204         offset = logical - ce->start;
1205
1206         if (rw == WRITE) {
1207                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
1208                                  BTRFS_BLOCK_GROUP_DUP)) {
1209                         stripes_required = map->num_stripes;
1210                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1211                         stripes_required = map->sub_stripes;
1212                 }
1213         }
1214         if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)
1215             && multi_ret && ((rw & WRITE) || mirror_num > 1) && raid_map_ret) {
1216                     /* RAID[56] write or recovery. Return all stripes */
1217                     stripes_required = map->num_stripes;
1218
1219                     /* Only allocate the map if we've already got a large enough multi_ret */
1220                     if (stripes_allocated >= stripes_required) {
1221                             raid_map = kmalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1222                             if (!raid_map) {
1223                                     kfree(multi);
1224                                     return -ENOMEM;
1225                             }
1226                     }
1227         }
1228
1229         /* if our multi bio struct is too small, back off and try again */
1230         if (multi_ret && stripes_allocated < stripes_required) {
1231                 stripes_allocated = stripes_required;
1232                 kfree(multi);
1233                 multi = NULL;
1234                 goto again;
1235         }
1236         stripe_nr = offset;
1237         /*
1238          * stripe_nr counts the total number of stripes we have to stride
1239          * to get to this block
1240          */
1241         stripe_nr = stripe_nr / map->stripe_len;
1242
1243         stripe_offset = stripe_nr * map->stripe_len;
1244         BUG_ON(offset < stripe_offset);
1245
1246         /* stripe_offset is the offset of this block in its stripe*/
1247         stripe_offset = offset - stripe_offset;
1248
1249         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1250                          BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
1251                          BTRFS_BLOCK_GROUP_RAID10 |
1252                          BTRFS_BLOCK_GROUP_DUP)) {
1253                 /* we limit the length of each bio to what fits in a stripe */
1254                 *length = min_t(u64, ce->size - offset,
1255                               map->stripe_len - stripe_offset);
1256         } else {
1257                 *length = ce->size - offset;
1258         }
1259
1260         if (!multi_ret)
1261                 goto out;
1262
1263         multi->num_stripes = 1;
1264         stripe_index = 0;
1265         if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1266                 if (rw == WRITE)
1267                         multi->num_stripes = map->num_stripes;
1268                 else if (mirror_num)
1269                         stripe_index = mirror_num - 1;
1270                 else
1271                         stripe_index = stripe_nr % map->num_stripes;
1272         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1273                 int factor = map->num_stripes / map->sub_stripes;
1274
1275                 stripe_index = stripe_nr % factor;
1276                 stripe_index *= map->sub_stripes;
1277
1278                 if (rw == WRITE)
1279                         multi->num_stripes = map->sub_stripes;
1280                 else if (mirror_num)
1281                         stripe_index += mirror_num - 1;
1282
1283                 stripe_nr = stripe_nr / factor;
1284         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
1285                 if (rw == WRITE)
1286                         multi->num_stripes = map->num_stripes;
1287                 else if (mirror_num)
1288                         stripe_index = mirror_num - 1;
1289         } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1290                                 BTRFS_BLOCK_GROUP_RAID6)) {
1291
1292                 if (raid_map) {
1293                         int i, rot;
1294                         u64 tmp;
1295                         u64 raid56_full_stripe_start;
1296                         u64 full_stripe_len = nr_data_stripes(map) * map->stripe_len;
1297
1298                         /*
1299                          * align the start of our data stripe in the logical
1300                          * address space
1301                          */
1302                         raid56_full_stripe_start = offset / full_stripe_len;
1303                         raid56_full_stripe_start *= full_stripe_len;
1304
1305                         /* get the data stripe number */
1306                         stripe_nr = raid56_full_stripe_start / map->stripe_len;
1307                         stripe_nr = stripe_nr / nr_data_stripes(map);
1308
1309                         /* Work out the disk rotation on this stripe-set */
1310                         rot = stripe_nr % map->num_stripes;
1311
1312                         /* Fill in the logical address of each stripe */
1313                         tmp = stripe_nr * nr_data_stripes(map);
1314
1315                         for (i = 0; i < nr_data_stripes(map); i++)
1316                                 raid_map[(i+rot) % map->num_stripes] =
1317                                         ce->start + (tmp + i) * map->stripe_len;
1318
1319                         raid_map[(i+rot) % map->num_stripes] = BTRFS_RAID5_P_STRIPE;
1320                         if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1321                                 raid_map[(i+rot+1) % map->num_stripes] = BTRFS_RAID6_Q_STRIPE;
1322
1323                         *length = map->stripe_len;
1324                         stripe_index = 0;
1325                         stripe_offset = 0;
1326                         multi->num_stripes = map->num_stripes;
1327                 } else {
1328                         stripe_index = stripe_nr % nr_data_stripes(map);
1329                         stripe_nr = stripe_nr / nr_data_stripes(map);
1330
1331                         /*
1332                          * Mirror #0 or #1 means the original data block.
1333                          * Mirror #2 is RAID5 parity block.
1334                          * Mirror #3 is RAID6 Q block.
1335                          */
1336                         if (mirror_num > 1)
1337                                 stripe_index = nr_data_stripes(map) + mirror_num - 2;
1338
1339                         /* We distribute the parity blocks across stripes */
1340                         stripe_index = (stripe_nr + stripe_index) % map->num_stripes;
1341                 }
1342         } else {
1343                 /*
1344                  * after this do_div call, stripe_nr is the number of stripes
1345                  * on this device we have to walk to find the data, and
1346                  * stripe_index is the number of our device in the stripe array
1347                  */
1348                 stripe_index = stripe_nr % map->num_stripes;
1349                 stripe_nr = stripe_nr / map->num_stripes;
1350         }
1351         BUG_ON(stripe_index >= map->num_stripes);
1352
1353         for (i = 0; i < multi->num_stripes; i++) {
1354                 multi->stripes[i].physical =
1355                         map->stripes[stripe_index].physical + stripe_offset +
1356                         stripe_nr * map->stripe_len;
1357                 multi->stripes[i].dev = map->stripes[stripe_index].dev;
1358                 stripe_index++;
1359         }
1360         *multi_ret = multi;
1361
1362         if (type)
1363                 *type = map->type;
1364
1365         if (raid_map) {
1366                 sort_parity_stripes(multi, raid_map);
1367                 *raid_map_ret = raid_map;
1368         }
1369 out:
1370         return 0;
1371 }
1372
1373 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
1374                                        u8 *uuid, u8 *fsid)
1375 {
1376         struct btrfs_device *device;
1377         struct btrfs_fs_devices *cur_devices;
1378
1379         cur_devices = root->fs_info->fs_devices;
1380         while (cur_devices) {
1381                 if (!fsid ||
1382                     !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
1383                         device = __find_device(&cur_devices->devices,
1384                                                devid, uuid);
1385                         if (device)
1386                                 return device;
1387                 }
1388                 cur_devices = cur_devices->seed;
1389         }
1390         return NULL;
1391 }
1392
1393 struct btrfs_device *
1394 btrfs_find_device_by_devid(struct btrfs_fs_devices *fs_devices,
1395                            u64 devid, int instance)
1396 {
1397         struct list_head *head = &fs_devices->devices;
1398         struct btrfs_device *dev;
1399         int num_found = 0;
1400
1401         list_for_each_entry(dev, head, dev_list) {
1402                 if (dev->devid == devid && num_found++ == instance)
1403                         return dev;
1404         }
1405         return NULL;
1406 }
1407
1408 int btrfs_bootstrap_super_map(struct btrfs_mapping_tree *map_tree,
1409                               struct btrfs_fs_devices *fs_devices)
1410 {
1411         struct map_lookup *map;
1412         u64 logical = BTRFS_SUPER_INFO_OFFSET;
1413         u64 length = BTRFS_SUPER_INFO_SIZE;
1414         int num_stripes = 0;
1415         int sub_stripes = 0;
1416         int ret;
1417         int i;
1418         struct list_head *cur;
1419
1420         list_for_each(cur, &fs_devices->devices) {
1421                 num_stripes++;
1422         }
1423         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
1424         if (!map)
1425                 return -ENOMEM;
1426
1427         map->ce.start = logical;
1428         map->ce.size = length;
1429         map->num_stripes = num_stripes;
1430         map->sub_stripes = sub_stripes;
1431         map->io_width = length;
1432         map->io_align = length;
1433         map->sector_size = length;
1434         map->stripe_len = length;
1435         map->type = BTRFS_BLOCK_GROUP_RAID1;
1436
1437         i = 0;
1438         list_for_each(cur, &fs_devices->devices) {
1439                 struct btrfs_device *device = list_entry(cur,
1440                                                          struct btrfs_device,
1441                                                          dev_list);
1442                 map->stripes[i].physical = logical;
1443                 map->stripes[i].dev = device;
1444                 i++;
1445         }
1446         ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
1447         if (ret == -EEXIST) {
1448                 struct cache_extent *old;
1449                 struct map_lookup *old_map;
1450                 old = lookup_cache_extent(&map_tree->cache_tree,
1451                                           logical, length);
1452                 old_map = container_of(old, struct map_lookup, ce);
1453                 remove_cache_extent(&map_tree->cache_tree, old);
1454                 kfree(old_map);
1455                 ret = insert_cache_extent(&map_tree->cache_tree,
1456                                                    &map->ce);
1457         }
1458         BUG_ON(ret);
1459         return 0;
1460 }
1461
1462 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
1463 {
1464         struct cache_extent *ce;
1465         struct map_lookup *map;
1466         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
1467         int readonly = 0;
1468         int i;
1469
1470         ce = search_cache_extent(&map_tree->cache_tree, chunk_offset);
1471         BUG_ON(!ce);
1472
1473         map = container_of(ce, struct map_lookup, ce);
1474         for (i = 0; i < map->num_stripes; i++) {
1475                 if (!map->stripes[i].dev->writeable) {
1476                         readonly = 1;
1477                         break;
1478                 }
1479         }
1480
1481         return readonly;
1482 }
1483
1484 static struct btrfs_device *fill_missing_device(u64 devid)
1485 {
1486         struct btrfs_device *device;
1487
1488         device = kzalloc(sizeof(*device), GFP_NOFS);
1489         device->devid = devid;
1490         device->fd = -1;
1491         return device;
1492 }
1493
1494 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
1495                           struct extent_buffer *leaf,
1496                           struct btrfs_chunk *chunk)
1497 {
1498         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
1499         struct map_lookup *map;
1500         struct cache_extent *ce;
1501         u64 logical;
1502         u64 length;
1503         u64 devid;
1504         u8 uuid[BTRFS_UUID_SIZE];
1505         int num_stripes;
1506         int ret;
1507         int i;
1508
1509         logical = key->offset;
1510         length = btrfs_chunk_length(leaf, chunk);
1511
1512         ce = search_cache_extent(&map_tree->cache_tree, logical);
1513
1514         /* already mapped? */
1515         if (ce && ce->start <= logical && ce->start + ce->size > logical) {
1516                 return 0;
1517         }
1518
1519         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1520         map = kmalloc(btrfs_map_lookup_size(num_stripes), GFP_NOFS);
1521         if (!map)
1522                 return -ENOMEM;
1523
1524         map->ce.start = logical;
1525         map->ce.size = length;
1526         map->num_stripes = num_stripes;
1527         map->io_width = btrfs_chunk_io_width(leaf, chunk);
1528         map->io_align = btrfs_chunk_io_align(leaf, chunk);
1529         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
1530         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
1531         map->type = btrfs_chunk_type(leaf, chunk);
1532         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
1533
1534         for (i = 0; i < num_stripes; i++) {
1535                 map->stripes[i].physical =
1536                         btrfs_stripe_offset_nr(leaf, chunk, i);
1537                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
1538                 read_extent_buffer(leaf, uuid, (unsigned long)
1539                                    btrfs_stripe_dev_uuid_nr(chunk, i),
1540                                    BTRFS_UUID_SIZE);
1541                 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
1542                                                         NULL);
1543                 if (!map->stripes[i].dev) {
1544                         map->stripes[i].dev = fill_missing_device(devid);
1545                         printf("warning, device %llu is missing\n",
1546                                (unsigned long long)devid);
1547                 }
1548
1549         }
1550         ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
1551         BUG_ON(ret);
1552
1553         return 0;
1554 }
1555
1556 static int fill_device_from_item(struct extent_buffer *leaf,
1557                                  struct btrfs_dev_item *dev_item,
1558                                  struct btrfs_device *device)
1559 {
1560         unsigned long ptr;
1561
1562         device->devid = btrfs_device_id(leaf, dev_item);
1563         device->total_bytes = btrfs_device_total_bytes(leaf, dev_item);
1564         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
1565         device->type = btrfs_device_type(leaf, dev_item);
1566         device->io_align = btrfs_device_io_align(leaf, dev_item);
1567         device->io_width = btrfs_device_io_width(leaf, dev_item);
1568         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
1569
1570         ptr = (unsigned long)btrfs_device_uuid(dev_item);
1571         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1572
1573         return 0;
1574 }
1575
1576 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
1577 {
1578         struct btrfs_fs_devices *fs_devices;
1579         int ret;
1580
1581         fs_devices = root->fs_info->fs_devices->seed;
1582         while (fs_devices) {
1583                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
1584                         ret = 0;
1585                         goto out;
1586                 }
1587                 fs_devices = fs_devices->seed;
1588         }
1589
1590         fs_devices = find_fsid(fsid);
1591         if (!fs_devices) {
1592                 ret = -ENOENT;
1593                 goto out;
1594         }
1595
1596         ret = btrfs_open_devices(fs_devices, O_RDONLY);
1597         if (ret)
1598                 goto out;
1599
1600         fs_devices->seed = root->fs_info->fs_devices->seed;
1601         root->fs_info->fs_devices->seed = fs_devices;
1602 out:
1603         return ret;
1604 }
1605
1606 static int read_one_dev(struct btrfs_root *root,
1607                         struct extent_buffer *leaf,
1608                         struct btrfs_dev_item *dev_item)
1609 {
1610         struct btrfs_device *device;
1611         u64 devid;
1612         int ret = 0;
1613         u8 fs_uuid[BTRFS_UUID_SIZE];
1614         u8 dev_uuid[BTRFS_UUID_SIZE];
1615
1616         devid = btrfs_device_id(leaf, dev_item);
1617         read_extent_buffer(leaf, dev_uuid,
1618                            (unsigned long)btrfs_device_uuid(dev_item),
1619                            BTRFS_UUID_SIZE);
1620         read_extent_buffer(leaf, fs_uuid,
1621                            (unsigned long)btrfs_device_fsid(dev_item),
1622                            BTRFS_UUID_SIZE);
1623
1624         if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
1625                 ret = open_seed_devices(root, fs_uuid);
1626                 if (ret)
1627                         return ret;
1628         }
1629
1630         device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1631         if (!device) {
1632                 printk("warning devid %llu not found already\n",
1633                         (unsigned long long)devid);
1634                 device = kmalloc(sizeof(*device), GFP_NOFS);
1635                 if (!device)
1636                         return -ENOMEM;
1637                 device->total_ios = 0;
1638                 list_add(&device->dev_list,
1639                          &root->fs_info->fs_devices->devices);
1640         }
1641
1642         fill_device_from_item(leaf, dev_item, device);
1643         device->dev_root = root->fs_info->dev_root;
1644         return ret;
1645 }
1646
1647 int btrfs_read_sys_array(struct btrfs_root *root)
1648 {
1649         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
1650         struct extent_buffer *sb;
1651         struct btrfs_disk_key *disk_key;
1652         struct btrfs_chunk *chunk;
1653         struct btrfs_key key;
1654         u32 num_stripes;
1655         u32 array_size;
1656         u32 len = 0;
1657         u8 *ptr;
1658         unsigned long sb_ptr;
1659         u32 cur;
1660         int ret = 0;
1661
1662         sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
1663                                           BTRFS_SUPER_INFO_SIZE);
1664         if (!sb)
1665                 return -ENOMEM;
1666         btrfs_set_buffer_uptodate(sb);
1667         write_extent_buffer(sb, super_copy, 0, sizeof(*super_copy));
1668         array_size = btrfs_super_sys_array_size(super_copy);
1669
1670         /*
1671          * we do this loop twice, once for the device items and
1672          * once for all of the chunks.  This way there are device
1673          * structs filled in for every chunk
1674          */
1675         ptr = super_copy->sys_chunk_array;
1676         sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
1677         cur = 0;
1678
1679         while (cur < array_size) {
1680                 disk_key = (struct btrfs_disk_key *)ptr;
1681                 btrfs_disk_key_to_cpu(&key, disk_key);
1682
1683                 len = sizeof(*disk_key);
1684                 ptr += len;
1685                 sb_ptr += len;
1686                 cur += len;
1687
1688                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1689                         chunk = (struct btrfs_chunk *)sb_ptr;
1690                         ret = read_one_chunk(root, &key, sb, chunk);
1691                         if (ret)
1692                                 break;
1693                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
1694                         len = btrfs_chunk_item_size(num_stripes);
1695                 } else {
1696                         BUG();
1697                 }
1698                 ptr += len;
1699                 sb_ptr += len;
1700                 cur += len;
1701         }
1702         free_extent_buffer(sb);
1703         return ret;
1704 }
1705
1706 int btrfs_read_chunk_tree(struct btrfs_root *root)
1707 {
1708         struct btrfs_path *path;
1709         struct extent_buffer *leaf;
1710         struct btrfs_key key;
1711         struct btrfs_key found_key;
1712         int ret;
1713         int slot;
1714
1715         root = root->fs_info->chunk_root;
1716
1717         path = btrfs_alloc_path();
1718         if (!path)
1719                 return -ENOMEM;
1720
1721         /* first we search for all of the device items, and then we
1722          * read in all of the chunk items.  This way we can create chunk
1723          * mappings that reference all of the devices that are afound
1724          */
1725         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1726         key.offset = 0;
1727         key.type = 0;
1728 again:
1729         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1730         while(1) {
1731                 leaf = path->nodes[0];
1732                 slot = path->slots[0];
1733                 if (slot >= btrfs_header_nritems(leaf)) {
1734                         ret = btrfs_next_leaf(root, path);
1735                         if (ret == 0)
1736                                 continue;
1737                         if (ret < 0)
1738                                 goto error;
1739                         break;
1740                 }
1741                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1742                 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
1743                         if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
1744                                 break;
1745                         if (found_key.type == BTRFS_DEV_ITEM_KEY) {
1746                                 struct btrfs_dev_item *dev_item;
1747                                 dev_item = btrfs_item_ptr(leaf, slot,
1748                                                   struct btrfs_dev_item);
1749                                 ret = read_one_dev(root, leaf, dev_item);
1750                                 BUG_ON(ret);
1751                         }
1752                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
1753                         struct btrfs_chunk *chunk;
1754                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
1755                         ret = read_one_chunk(root, &found_key, leaf, chunk);
1756                         BUG_ON(ret);
1757                 }
1758                 path->slots[0]++;
1759         }
1760         if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
1761                 key.objectid = 0;
1762                 btrfs_release_path(root, path);
1763                 goto again;
1764         }
1765
1766         ret = 0;
1767 error:
1768         btrfs_free_path(path);
1769         return ret;
1770 }
1771
1772 struct list_head *btrfs_scanned_uuids(void)
1773 {
1774         return &fs_uuids;
1775 }
1776
1777 static int rmw_eb(struct btrfs_fs_info *info,
1778                   struct extent_buffer *eb, struct extent_buffer *orig_eb)
1779 {
1780         int ret;
1781         unsigned long orig_off = 0;
1782         unsigned long dest_off = 0;
1783         unsigned long copy_len = eb->len;
1784
1785         ret = read_whole_eb(info, eb, 0);
1786         if (ret)
1787                 return ret;
1788
1789         if (eb->start + eb->len <= orig_eb->start ||
1790             eb->start >= orig_eb->start + orig_eb->len)
1791                 return 0;
1792         /*
1793          * | ----- orig_eb ------- |
1794          *         | ----- stripe -------  |
1795          *         | ----- orig_eb ------- |
1796          *              | ----- orig_eb ------- |
1797          */
1798         if (eb->start > orig_eb->start)
1799                 orig_off = eb->start - orig_eb->start;
1800         if (orig_eb->start > eb->start)
1801                 dest_off = orig_eb->start - eb->start;
1802
1803         if (copy_len > orig_eb->len - orig_off)
1804                 copy_len = orig_eb->len - orig_off;
1805         if (copy_len > eb->len - dest_off)
1806                 copy_len = eb->len - dest_off;
1807
1808         memcpy(eb->data + dest_off, orig_eb->data + orig_off, copy_len);
1809         return 0;
1810 }
1811
1812 static void split_eb_for_raid56(struct btrfs_fs_info *info,
1813                                 struct extent_buffer *orig_eb,
1814                                struct extent_buffer **ebs,
1815                                u64 stripe_len, u64 *raid_map,
1816                                int num_stripes)
1817 {
1818         struct extent_buffer *eb;
1819         u64 start = orig_eb->start;
1820         u64 this_eb_start;
1821         int i;
1822         int ret;
1823
1824         for (i = 0; i < num_stripes; i++) {
1825                 if (raid_map[i] >= BTRFS_RAID5_P_STRIPE)
1826                         break;
1827
1828                 eb = malloc(sizeof(struct extent_buffer) + stripe_len);
1829                 if (!eb)
1830                         BUG();
1831                 memset(eb, 0, sizeof(struct extent_buffer) + stripe_len);
1832
1833                 eb->start = raid_map[i];
1834                 eb->len = stripe_len;
1835                 eb->refs = 1;
1836                 eb->flags = 0;
1837                 eb->fd = -1;
1838                 eb->dev_bytenr = (u64)-1;
1839
1840                 this_eb_start = raid_map[i];
1841
1842                 if (start > this_eb_start ||
1843                     start + orig_eb->len < this_eb_start + stripe_len) {
1844                         ret = rmw_eb(info, eb, orig_eb);
1845                         BUG_ON(ret);
1846                 } else {
1847                         memcpy(eb->data, orig_eb->data + eb->start - start, stripe_len);
1848                 }
1849                 ebs[i] = eb;
1850         }
1851 }
1852
1853 int write_raid56_with_parity(struct btrfs_fs_info *info,
1854                              struct extent_buffer *eb,
1855                              struct btrfs_multi_bio *multi,
1856                              u64 stripe_len, u64 *raid_map)
1857 {
1858         struct extent_buffer *ebs[multi->num_stripes], *p_eb = NULL, *q_eb = NULL;
1859         int i;
1860         int j;
1861         int ret;
1862         int alloc_size = eb->len;
1863
1864         if (stripe_len > alloc_size)
1865                 alloc_size = stripe_len;
1866
1867         split_eb_for_raid56(info, eb, ebs, stripe_len, raid_map,
1868                             multi->num_stripes);
1869
1870         for (i = 0; i < multi->num_stripes; i++) {
1871                 struct extent_buffer *new_eb;
1872                 if (raid_map[i] < BTRFS_RAID5_P_STRIPE) {
1873                         ebs[i]->dev_bytenr = multi->stripes[i].physical;
1874                         ebs[i]->fd = multi->stripes[i].dev->fd;
1875                         multi->stripes[i].dev->total_ios++;
1876                         BUG_ON(ebs[i]->start != raid_map[i]);
1877                         continue;
1878                 }
1879                 new_eb = kmalloc(sizeof(*eb) + alloc_size, GFP_NOFS);
1880                 BUG_ON(!new_eb);
1881                 new_eb->dev_bytenr = multi->stripes[i].physical;
1882                 new_eb->fd = multi->stripes[i].dev->fd;
1883                 multi->stripes[i].dev->total_ios++;
1884                 new_eb->len = stripe_len;
1885
1886                 if (raid_map[i] == BTRFS_RAID5_P_STRIPE)
1887                         p_eb = new_eb;
1888                 else if (raid_map[i] == BTRFS_RAID6_Q_STRIPE)
1889                         q_eb = new_eb;
1890         }
1891         if (q_eb) {
1892                 void *pointers[multi->num_stripes];
1893                 ebs[multi->num_stripes - 2] = p_eb;
1894                 ebs[multi->num_stripes - 1] = q_eb;
1895
1896                 for (i = 0; i < multi->num_stripes; i++)
1897                         pointers[i] = ebs[i]->data;
1898
1899                 raid6_gen_syndrome(multi->num_stripes, stripe_len, pointers);
1900         } else {
1901                 ebs[multi->num_stripes - 1] = p_eb;
1902                 memcpy(p_eb->data, ebs[0]->data, stripe_len);
1903                 for (j = 1; j < multi->num_stripes - 1; j++) {
1904                         for (i = 0; i < stripe_len; i += sizeof(unsigned long)) {
1905                                 *(unsigned long *)(p_eb->data + i) ^=
1906                                         *(unsigned long *)(ebs[j]->data + i);
1907                         }
1908                 }
1909         }
1910
1911         for (i = 0; i < multi->num_stripes; i++) {
1912                 ret = write_extent_to_disk(ebs[i]);
1913                 BUG_ON(ret);
1914                 if (ebs[i] != eb)
1915                         kfree(ebs[i]);
1916         }
1917         return 0;
1918 }