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