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