c0d02d1326c70f960f04d295e9fb9d975fd45d93
[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 #define map_lookup_size(n) (sizeof(struct map_lookup) + \
56                             (sizeof(struct btrfs_bio_stripe) * (n)))
57
58 static LIST_HEAD(fs_uuids);
59
60 static struct btrfs_device *__find_device(struct list_head *head, u64 devid,
61                                           u8 *uuid)
62 {
63         struct btrfs_device *dev;
64         struct list_head *cur;
65
66         list_for_each(cur, head) {
67                 dev = list_entry(cur, struct btrfs_device, dev_list);
68                 if (dev->devid == devid &&
69                     !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE)) {
70                         return dev;
71                 }
72         }
73         return NULL;
74 }
75
76 static struct btrfs_fs_devices *find_fsid(u8 *fsid)
77 {
78         struct list_head *cur;
79         struct btrfs_fs_devices *fs_devices;
80
81         list_for_each(cur, &fs_uuids) {
82                 fs_devices = list_entry(cur, struct btrfs_fs_devices, list);
83                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
84                         return fs_devices;
85         }
86         return NULL;
87 }
88
89 static int device_list_add(const char *path,
90                            struct btrfs_super_block *disk_super,
91                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
92 {
93         struct btrfs_device *device;
94         struct btrfs_fs_devices *fs_devices;
95         u64 found_transid = btrfs_super_generation(disk_super);
96
97         fs_devices = find_fsid(disk_super->fsid);
98         if (!fs_devices) {
99                 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
100                 if (!fs_devices)
101                         return -ENOMEM;
102                 INIT_LIST_HEAD(&fs_devices->devices);
103                 list_add(&fs_devices->list, &fs_uuids);
104                 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
105                 fs_devices->latest_devid = devid;
106                 fs_devices->latest_trans = found_transid;
107                 fs_devices->lowest_devid = (u64)-1;
108                 device = NULL;
109         } else {
110                 device = __find_device(&fs_devices->devices, devid,
111                                        disk_super->dev_item.uuid);
112         }
113         if (!device) {
114                 device = kzalloc(sizeof(*device), GFP_NOFS);
115                 if (!device) {
116                         /* we can safely leave the fs_devices entry around */
117                         return -ENOMEM;
118                 }
119                 device->devid = devid;
120                 memcpy(device->uuid, disk_super->dev_item.uuid,
121                        BTRFS_UUID_SIZE);
122                 device->name = kstrdup(path, GFP_NOFS);
123                 if (!device->name) {
124                         kfree(device);
125                         return -ENOMEM;
126                 }
127                 device->label = kstrdup(disk_super->label, GFP_NOFS);
128                 device->total_devs = btrfs_super_num_devices(disk_super);
129                 device->super_bytes_used = btrfs_super_bytes_used(disk_super);
130                 device->total_bytes =
131                         btrfs_stack_device_total_bytes(&disk_super->dev_item);
132                 device->bytes_used =
133                         btrfs_stack_device_bytes_used(&disk_super->dev_item);
134                 list_add(&device->dev_list, &fs_devices->devices);
135                 device->fs_devices = fs_devices;
136         } else if (!device->name || strcmp(device->name, path)) {
137                 char *name = strdup(path);
138                 if (!name)
139                         return -ENOMEM;
140                 kfree(device->name);
141                 device->name = name;
142         }
143
144
145         if (found_transid > fs_devices->latest_trans) {
146                 fs_devices->latest_devid = devid;
147                 fs_devices->latest_trans = found_transid;
148         }
149         if (fs_devices->lowest_devid > devid) {
150                 fs_devices->lowest_devid = devid;
151         }
152         *fs_devices_ret = fs_devices;
153         return 0;
154 }
155
156 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
157 {
158         struct btrfs_fs_devices *seed_devices;
159         struct list_head *cur;
160         struct btrfs_device *device;
161 again:
162         list_for_each(cur, &fs_devices->devices) {
163                 device = list_entry(cur, struct btrfs_device, dev_list);
164                 close(device->fd);
165                 device->fd = -1;
166                 device->writeable = 0;
167         }
168
169         seed_devices = fs_devices->seed;
170         fs_devices->seed = NULL;
171         if (seed_devices) {
172                 fs_devices = seed_devices;
173                 goto again;
174         }
175
176         return 0;
177 }
178
179 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices, int flags)
180 {
181         int fd;
182         struct list_head *head = &fs_devices->devices;
183         struct list_head *cur;
184         struct btrfs_device *device;
185         int ret;
186
187         list_for_each(cur, head) {
188                 device = list_entry(cur, struct btrfs_device, dev_list);
189
190                 fd = open(device->name, flags);
191                 if (fd < 0) {
192                         ret = -errno;
193                         goto fail;
194                 }
195
196                 if (posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED))
197                         fprintf(stderr, "Warning, could not drop caches\n");
198
199                 if (device->devid == fs_devices->latest_devid)
200                         fs_devices->latest_bdev = fd;
201                 if (device->devid == fs_devices->lowest_devid)
202                         fs_devices->lowest_bdev = fd;
203                 device->fd = fd;
204                 if (flags == O_RDWR)
205                         device->writeable = 1;
206         }
207         return 0;
208 fail:
209         btrfs_close_devices(fs_devices);
210         return ret;
211 }
212
213 int btrfs_scan_one_device(int fd, const char *path,
214                           struct btrfs_fs_devices **fs_devices_ret,
215                           u64 *total_devs, u64 super_offset)
216 {
217         struct btrfs_super_block *disk_super;
218         char *buf;
219         int ret;
220         u64 devid;
221         char uuidbuf[37];
222
223         buf = malloc(4096);
224         if (!buf) {
225                 ret = -ENOMEM;
226                 goto error;
227         }
228         disk_super = (struct btrfs_super_block *)buf;
229         ret = btrfs_read_dev_super(fd, disk_super, super_offset);
230         if (ret < 0) {
231                 ret = -EIO;
232                 goto error_brelse;
233         }
234         devid = le64_to_cpu(disk_super->dev_item.devid);
235         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_METADUMP)
236                 *total_devs = 1;
237         else
238                 *total_devs = btrfs_super_num_devices(disk_super);
239         uuid_unparse(disk_super->fsid, uuidbuf);
240
241         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
242
243 error_brelse:
244         free(buf);
245 error:
246         return ret;
247 }
248
249 /*
250  * this uses a pretty simple search, the expectation is that it is
251  * called very infrequently and that a given device has a small number
252  * of extents
253  */
254 static int find_free_dev_extent(struct btrfs_trans_handle *trans,
255                                 struct btrfs_device *device,
256                                 struct btrfs_path *path,
257                                 u64 num_bytes, u64 *start)
258 {
259         struct btrfs_key key;
260         struct btrfs_root *root = device->dev_root;
261         struct btrfs_dev_extent *dev_extent = NULL;
262         u64 hole_size = 0;
263         u64 last_byte = 0;
264         u64 search_start = 0;
265         u64 search_end = device->total_bytes;
266         int ret;
267         int slot = 0;
268         int start_found;
269         struct extent_buffer *l;
270
271         start_found = 0;
272         path->reada = 2;
273
274         /* FIXME use last free of some kind */
275
276         /* we don't want to overwrite the superblock on the drive,
277          * so we make sure to start at an offset of at least 1MB
278          */
279         search_start = max((u64)1024 * 1024, search_start);
280
281         if (root->fs_info->alloc_start + num_bytes <= device->total_bytes)
282                 search_start = max(root->fs_info->alloc_start, search_start);
283
284         key.objectid = device->devid;
285         key.offset = search_start;
286         key.type = BTRFS_DEV_EXTENT_KEY;
287         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
288         if (ret < 0)
289                 goto error;
290         ret = btrfs_previous_item(root, path, 0, key.type);
291         if (ret < 0)
292                 goto error;
293         l = path->nodes[0];
294         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
295         while (1) {
296                 l = path->nodes[0];
297                 slot = path->slots[0];
298                 if (slot >= btrfs_header_nritems(l)) {
299                         ret = btrfs_next_leaf(root, path);
300                         if (ret == 0)
301                                 continue;
302                         if (ret < 0)
303                                 goto error;
304 no_more_items:
305                         if (!start_found) {
306                                 if (search_start >= search_end) {
307                                         ret = -ENOSPC;
308                                         goto error;
309                                 }
310                                 *start = search_start;
311                                 start_found = 1;
312                                 goto check_pending;
313                         }
314                         *start = last_byte > search_start ?
315                                 last_byte : search_start;
316                         if (search_end <= *start) {
317                                 ret = -ENOSPC;
318                                 goto error;
319                         }
320                         goto check_pending;
321                 }
322                 btrfs_item_key_to_cpu(l, &key, slot);
323
324                 if (key.objectid < device->devid)
325                         goto next;
326
327                 if (key.objectid > device->devid)
328                         goto no_more_items;
329
330                 if (key.offset >= search_start && key.offset > last_byte &&
331                     start_found) {
332                         if (last_byte < search_start)
333                                 last_byte = search_start;
334                         hole_size = key.offset - last_byte;
335                         if (key.offset > last_byte &&
336                             hole_size >= num_bytes) {
337                                 *start = last_byte;
338                                 goto check_pending;
339                         }
340                 }
341                 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY) {
342                         goto next;
343                 }
344
345                 start_found = 1;
346                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
347                 last_byte = key.offset + btrfs_dev_extent_length(l, dev_extent);
348 next:
349                 path->slots[0]++;
350                 cond_resched();
351         }
352 check_pending:
353         /* we have to make sure we didn't find an extent that has already
354          * been allocated by the map tree or the original allocation
355          */
356         btrfs_release_path(root, path);
357         BUG_ON(*start < search_start);
358
359         if (*start + num_bytes > search_end) {
360                 ret = -ENOSPC;
361                 goto error;
362         }
363         /* check for pending inserts here */
364         return 0;
365
366 error:
367         btrfs_release_path(root, path);
368         return ret;
369 }
370
371 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
372                            struct btrfs_device *device,
373                            u64 chunk_tree, u64 chunk_objectid,
374                            u64 chunk_offset,
375                            u64 num_bytes, u64 *start)
376 {
377         int ret;
378         struct btrfs_path *path;
379         struct btrfs_root *root = device->dev_root;
380         struct btrfs_dev_extent *extent;
381         struct extent_buffer *leaf;
382         struct btrfs_key key;
383
384         path = btrfs_alloc_path();
385         if (!path)
386                 return -ENOMEM;
387
388         ret = find_free_dev_extent(trans, device, path, num_bytes, start);
389         if (ret) {
390                 goto err;
391         }
392
393         key.objectid = device->devid;
394         key.offset = *start;
395         key.type = BTRFS_DEV_EXTENT_KEY;
396         ret = btrfs_insert_empty_item(trans, root, path, &key,
397                                       sizeof(*extent));
398         BUG_ON(ret);
399
400         leaf = path->nodes[0];
401         extent = btrfs_item_ptr(leaf, path->slots[0],
402                                 struct btrfs_dev_extent);
403         btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
404         btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
405         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
406
407         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
408                     (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
409                     BTRFS_UUID_SIZE);
410
411         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
412         btrfs_mark_buffer_dirty(leaf);
413 err:
414         btrfs_free_path(path);
415         return ret;
416 }
417
418 static int find_next_chunk(struct btrfs_root *root, u64 objectid, u64 *offset)
419 {
420         struct btrfs_path *path;
421         int ret;
422         struct btrfs_key key;
423         struct btrfs_chunk *chunk;
424         struct btrfs_key found_key;
425
426         path = btrfs_alloc_path();
427         BUG_ON(!path);
428
429         key.objectid = objectid;
430         key.offset = (u64)-1;
431         key.type = BTRFS_CHUNK_ITEM_KEY;
432
433         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
434         if (ret < 0)
435                 goto error;
436
437         BUG_ON(ret == 0);
438
439         ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
440         if (ret) {
441                 *offset = 0;
442         } else {
443                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
444                                       path->slots[0]);
445                 if (found_key.objectid != objectid)
446                         *offset = 0;
447                 else {
448                         chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
449                                                struct btrfs_chunk);
450                         *offset = found_key.offset +
451                                 btrfs_chunk_length(path->nodes[0], chunk);
452                 }
453         }
454         ret = 0;
455 error:
456         btrfs_free_path(path);
457         return ret;
458 }
459
460 static int find_next_devid(struct btrfs_root *root, struct btrfs_path *path,
461                            u64 *objectid)
462 {
463         int ret;
464         struct btrfs_key key;
465         struct btrfs_key found_key;
466
467         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
468         key.type = BTRFS_DEV_ITEM_KEY;
469         key.offset = (u64)-1;
470
471         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
472         if (ret < 0)
473                 goto error;
474
475         BUG_ON(ret == 0);
476
477         ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
478                                   BTRFS_DEV_ITEM_KEY);
479         if (ret) {
480                 *objectid = 1;
481         } else {
482                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
483                                       path->slots[0]);
484                 *objectid = found_key.offset + 1;
485         }
486         ret = 0;
487 error:
488         btrfs_release_path(root, path);
489         return ret;
490 }
491
492 /*
493  * the device information is stored in the chunk root
494  * the btrfs_device struct should be fully filled in
495  */
496 int btrfs_add_device(struct btrfs_trans_handle *trans,
497                      struct btrfs_root *root,
498                      struct btrfs_device *device)
499 {
500         int ret;
501         struct btrfs_path *path;
502         struct btrfs_dev_item *dev_item;
503         struct extent_buffer *leaf;
504         struct btrfs_key key;
505         unsigned long ptr;
506         u64 free_devid = 0;
507
508         root = root->fs_info->chunk_root;
509
510         path = btrfs_alloc_path();
511         if (!path)
512                 return -ENOMEM;
513
514         ret = find_next_devid(root, path, &free_devid);
515         if (ret)
516                 goto out;
517
518         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
519         key.type = BTRFS_DEV_ITEM_KEY;
520         key.offset = free_devid;
521
522         ret = btrfs_insert_empty_item(trans, root, path, &key,
523                                       sizeof(*dev_item));
524         if (ret)
525                 goto out;
526
527         leaf = path->nodes[0];
528         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
529
530         device->devid = free_devid;
531         btrfs_set_device_id(leaf, dev_item, device->devid);
532         btrfs_set_device_generation(leaf, dev_item, 0);
533         btrfs_set_device_type(leaf, dev_item, device->type);
534         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
535         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
536         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
537         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
538         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
539         btrfs_set_device_group(leaf, dev_item, 0);
540         btrfs_set_device_seek_speed(leaf, dev_item, 0);
541         btrfs_set_device_bandwidth(leaf, dev_item, 0);
542         btrfs_set_device_start_offset(leaf, dev_item, 0);
543
544         ptr = (unsigned long)btrfs_device_uuid(dev_item);
545         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
546         ptr = (unsigned long)btrfs_device_fsid(dev_item);
547         write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
548         btrfs_mark_buffer_dirty(leaf);
549         ret = 0;
550
551 out:
552         btrfs_free_path(path);
553         return ret;
554 }
555
556 int btrfs_update_device(struct btrfs_trans_handle *trans,
557                         struct btrfs_device *device)
558 {
559         int ret;
560         struct btrfs_path *path;
561         struct btrfs_root *root;
562         struct btrfs_dev_item *dev_item;
563         struct extent_buffer *leaf;
564         struct btrfs_key key;
565
566         root = device->dev_root->fs_info->chunk_root;
567
568         path = btrfs_alloc_path();
569         if (!path)
570                 return -ENOMEM;
571
572         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
573         key.type = BTRFS_DEV_ITEM_KEY;
574         key.offset = device->devid;
575
576         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
577         if (ret < 0)
578                 goto out;
579
580         if (ret > 0) {
581                 ret = -ENOENT;
582                 goto out;
583         }
584
585         leaf = path->nodes[0];
586         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
587
588         btrfs_set_device_id(leaf, dev_item, device->devid);
589         btrfs_set_device_type(leaf, dev_item, device->type);
590         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
591         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
592         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
593         btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
594         btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
595         btrfs_mark_buffer_dirty(leaf);
596
597 out:
598         btrfs_free_path(path);
599         return ret;
600 }
601
602 int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
603                            struct btrfs_root *root,
604                            struct btrfs_key *key,
605                            struct btrfs_chunk *chunk, int item_size)
606 {
607         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
608         struct btrfs_disk_key disk_key;
609         u32 array_size;
610         u8 *ptr;
611
612         array_size = btrfs_super_sys_array_size(super_copy);
613         if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
614                 return -EFBIG;
615
616         ptr = super_copy->sys_chunk_array + array_size;
617         btrfs_cpu_key_to_disk(&disk_key, key);
618         memcpy(ptr, &disk_key, sizeof(disk_key));
619         ptr += sizeof(disk_key);
620         memcpy(ptr, chunk, item_size);
621         item_size += sizeof(disk_key);
622         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
623         return 0;
624 }
625
626 static u64 div_factor(u64 num, int factor)
627 {
628         if (factor == 10)
629                 return num;
630         num *= factor;
631         return num / 10;
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 = extent_root->fs_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 = &extent_root->fs_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(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_existing_cache_extent(
888                            &extent_root->fs_info->mapping_tree.cache_tree,
889                            &map->ce);
890         BUG_ON(ret);
891
892         if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
893                 ret = btrfs_add_system_chunk(trans, chunk_root, &key,
894                                     chunk, btrfs_chunk_item_size(num_stripes));
895                 BUG_ON(ret);
896         }
897
898         kfree(chunk);
899         return ret;
900 }
901
902 int btrfs_alloc_data_chunk(struct btrfs_trans_handle *trans,
903                            struct btrfs_root *extent_root, u64 *start,
904                            u64 num_bytes, u64 type)
905 {
906         u64 dev_offset;
907         struct btrfs_fs_info *info = extent_root->fs_info;
908         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
909         struct btrfs_stripe *stripes;
910         struct btrfs_device *device = NULL;
911         struct btrfs_chunk *chunk;
912         struct list_head *dev_list = &extent_root->fs_info->fs_devices->devices;
913         struct list_head *cur;
914         struct map_lookup *map;
915         u64 calc_size = 8 * 1024 * 1024;
916         int num_stripes = 1;
917         int sub_stripes = 0;
918         int ret;
919         int index;
920         int stripe_len = 64 * 1024;
921         struct btrfs_key key;
922
923         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
924         key.type = BTRFS_CHUNK_ITEM_KEY;
925         ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
926                               &key.offset);
927         if (ret)
928                 return ret;
929
930         chunk = kmalloc(btrfs_chunk_item_size(num_stripes), GFP_NOFS);
931         if (!chunk)
932                 return -ENOMEM;
933
934         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
935         if (!map) {
936                 kfree(chunk);
937                 return -ENOMEM;
938         }
939
940         stripes = &chunk->stripe;
941         calc_size = num_bytes;
942
943         index = 0;
944         cur = dev_list->next;
945         device = list_entry(cur, struct btrfs_device, dev_list);
946
947         while (index < num_stripes) {
948                 struct btrfs_stripe *stripe;
949
950                 ret = btrfs_alloc_dev_extent(trans, device,
951                              info->chunk_root->root_key.objectid,
952                              BTRFS_FIRST_CHUNK_TREE_OBJECTID, key.offset,
953                              calc_size, &dev_offset);
954                 BUG_ON(ret);
955
956                 device->bytes_used += calc_size;
957                 ret = btrfs_update_device(trans, device);
958                 BUG_ON(ret);
959
960                 map->stripes[index].dev = device;
961                 map->stripes[index].physical = dev_offset;
962                 stripe = stripes + index;
963                 btrfs_set_stack_stripe_devid(stripe, device->devid);
964                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
965                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
966                 index++;
967         }
968
969         /* key was set above */
970         btrfs_set_stack_chunk_length(chunk, num_bytes);
971         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
972         btrfs_set_stack_chunk_stripe_len(chunk, stripe_len);
973         btrfs_set_stack_chunk_type(chunk, type);
974         btrfs_set_stack_chunk_num_stripes(chunk, num_stripes);
975         btrfs_set_stack_chunk_io_align(chunk, stripe_len);
976         btrfs_set_stack_chunk_io_width(chunk, stripe_len);
977         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
978         btrfs_set_stack_chunk_sub_stripes(chunk, sub_stripes);
979         map->sector_size = extent_root->sectorsize;
980         map->stripe_len = stripe_len;
981         map->io_align = stripe_len;
982         map->io_width = stripe_len;
983         map->type = type;
984         map->num_stripes = num_stripes;
985         map->sub_stripes = sub_stripes;
986
987         ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
988                                 btrfs_chunk_item_size(num_stripes));
989         BUG_ON(ret);
990         *start = key.offset;
991
992         map->ce.start = key.offset;
993         map->ce.size = num_bytes;
994
995         ret = insert_existing_cache_extent(
996                            &extent_root->fs_info->mapping_tree.cache_tree,
997                            &map->ce);
998         BUG_ON(ret);
999
1000         kfree(chunk);
1001         return ret;
1002 }
1003
1004 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
1005 {
1006         cache_tree_init(&tree->cache_tree);
1007 }
1008
1009 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
1010 {
1011         struct cache_extent *ce;
1012         struct map_lookup *map;
1013         int ret;
1014
1015         ce = find_first_cache_extent(&map_tree->cache_tree, logical);
1016         BUG_ON(!ce);
1017         BUG_ON(ce->start > logical || ce->start + ce->size < logical);
1018         map = container_of(ce, struct map_lookup, ce);
1019
1020         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
1021                 ret = map->num_stripes;
1022         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1023                 ret = map->sub_stripes;
1024         else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
1025                 ret = 2;
1026         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1027                 ret = 3;
1028         else
1029                 ret = 1;
1030         return ret;
1031 }
1032
1033 int btrfs_next_metadata(struct btrfs_mapping_tree *map_tree, u64 *logical,
1034                         u64 *size)
1035 {
1036         struct cache_extent *ce;
1037         struct map_lookup *map;
1038
1039         ce = find_first_cache_extent(&map_tree->cache_tree, *logical);
1040
1041         while (ce) {
1042                 ce = next_cache_extent(ce);
1043                 if (!ce)
1044                         return -ENOENT;
1045
1046                 map = container_of(ce, struct map_lookup, ce);
1047                 if (map->type & BTRFS_BLOCK_GROUP_METADATA) {
1048                         *logical = ce->start;
1049                         *size = ce->size;
1050                         return 0;
1051                 }
1052         }
1053
1054         return -ENOENT;
1055 }
1056
1057 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
1058                      u64 chunk_start, u64 physical, u64 devid,
1059                      u64 **logical, int *naddrs, int *stripe_len)
1060 {
1061         struct cache_extent *ce;
1062         struct map_lookup *map;
1063         u64 *buf;
1064         u64 bytenr;
1065         u64 length;
1066         u64 stripe_nr;
1067         u64 rmap_len;
1068         int i, j, nr = 0;
1069
1070         ce = find_first_cache_extent(&map_tree->cache_tree, chunk_start);
1071         BUG_ON(!ce);
1072         map = container_of(ce, struct map_lookup, ce);
1073
1074         length = ce->size;
1075         rmap_len = map->stripe_len;
1076         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1077                 length = ce->size / (map->num_stripes / map->sub_stripes);
1078         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
1079                 length = ce->size / map->num_stripes;
1080         else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1081                               BTRFS_BLOCK_GROUP_RAID6)) {
1082                 length = ce->size / nr_data_stripes(map);
1083                 rmap_len = map->stripe_len * nr_data_stripes(map);
1084         }
1085
1086         buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1087
1088         for (i = 0; i < map->num_stripes; i++) {
1089                 if (devid && map->stripes[i].dev->devid != devid)
1090                         continue;
1091                 if (map->stripes[i].physical > physical ||
1092                     map->stripes[i].physical + length <= physical)
1093                         continue;
1094
1095                 stripe_nr = (physical - map->stripes[i].physical) /
1096                             map->stripe_len;
1097
1098                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1099                         stripe_nr = (stripe_nr * map->num_stripes + i) /
1100                                     map->sub_stripes;
1101                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1102                         stripe_nr = stripe_nr * map->num_stripes + i;
1103                 } /* else if RAID[56], multiply by nr_data_stripes().
1104                    * Alternatively, just use rmap_len below instead of
1105                    * map->stripe_len */
1106
1107                 bytenr = ce->start + stripe_nr * rmap_len;
1108                 for (j = 0; j < nr; j++) {
1109                         if (buf[j] == bytenr)
1110                                 break;
1111                 }
1112                 if (j == nr)
1113                         buf[nr++] = bytenr;
1114         }
1115
1116         *logical = buf;
1117         *naddrs = nr;
1118         *stripe_len = rmap_len;
1119
1120         return 0;
1121 }
1122
1123 static inline int parity_smaller(u64 a, u64 b)
1124 {
1125         return a > b;
1126 }
1127
1128 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
1129 static void sort_parity_stripes(struct btrfs_multi_bio *bbio, u64 *raid_map)
1130 {
1131         struct btrfs_bio_stripe s;
1132         int i;
1133         u64 l;
1134         int again = 1;
1135
1136         while (again) {
1137                 again = 0;
1138                 for (i = 0; i < bbio->num_stripes - 1; i++) {
1139                         if (parity_smaller(raid_map[i], raid_map[i+1])) {
1140                                 s = bbio->stripes[i];
1141                                 l = raid_map[i];
1142                                 bbio->stripes[i] = bbio->stripes[i+1];
1143                                 raid_map[i] = raid_map[i+1];
1144                                 bbio->stripes[i+1] = s;
1145                                 raid_map[i+1] = l;
1146                                 again = 1;
1147                         }
1148                 }
1149         }
1150 }
1151
1152 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1153                     u64 logical, u64 *length,
1154                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1155                     u64 **raid_map_ret)
1156 {
1157         return __btrfs_map_block(map_tree, rw, logical, length, NULL,
1158                                  multi_ret, mirror_num, raid_map_ret);
1159 }
1160
1161 int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
1162                     u64 logical, u64 *length, u64 *type,
1163                     struct btrfs_multi_bio **multi_ret, int mirror_num,
1164                     u64 **raid_map_ret)
1165 {
1166         struct cache_extent *ce;
1167         struct map_lookup *map;
1168         u64 offset;
1169         u64 stripe_offset;
1170         u64 stripe_nr;
1171         u64 *raid_map = NULL;
1172         int stripes_allocated = 8;
1173         int stripes_required = 1;
1174         int stripe_index;
1175         int i;
1176         struct btrfs_multi_bio *multi = NULL;
1177
1178         if (multi_ret && rw == READ) {
1179                 stripes_allocated = 1;
1180         }
1181 again:
1182         ce = find_first_cache_extent(&map_tree->cache_tree, logical);
1183         if (!ce) {
1184                 if (multi)
1185                         kfree(multi);
1186                 return -ENOENT;
1187         }
1188         if (ce->start > logical || ce->start + ce->size < logical) {
1189                 if (multi)
1190                         kfree(multi);
1191                 return -ENOENT;
1192         }
1193
1194         if (multi_ret) {
1195                 multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
1196                                 GFP_NOFS);
1197                 if (!multi)
1198                         return -ENOMEM;
1199         }
1200         map = container_of(ce, struct map_lookup, ce);
1201         offset = logical - ce->start;
1202
1203         if (rw == WRITE) {
1204                 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
1205                                  BTRFS_BLOCK_GROUP_DUP)) {
1206                         stripes_required = map->num_stripes;
1207                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1208                         stripes_required = map->sub_stripes;
1209                 }
1210         }
1211         if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)
1212             && multi_ret && ((rw & WRITE) || mirror_num > 1) && raid_map_ret) {
1213                     /* RAID[56] write or recovery. Return all stripes */
1214                     stripes_required = map->num_stripes;
1215
1216                     /* Only allocate the map if we've already got a large enough multi_ret */
1217                     if (stripes_allocated >= stripes_required) {
1218                             raid_map = kmalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
1219                             if (!raid_map) {
1220                                     kfree(multi);
1221                                     return -ENOMEM;
1222                             }
1223                     }
1224         }
1225
1226         /* if our multi bio struct is too small, back off and try again */
1227         if (multi_ret && stripes_allocated < stripes_required) {
1228                 stripes_allocated = stripes_required;
1229                 kfree(multi);
1230                 multi = NULL;
1231                 goto again;
1232         }
1233         stripe_nr = offset;
1234         /*
1235          * stripe_nr counts the total number of stripes we have to stride
1236          * to get to this block
1237          */
1238         stripe_nr = stripe_nr / map->stripe_len;
1239
1240         stripe_offset = stripe_nr * map->stripe_len;
1241         BUG_ON(offset < stripe_offset);
1242
1243         /* stripe_offset is the offset of this block in its stripe*/
1244         stripe_offset = offset - stripe_offset;
1245
1246         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
1247                          BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
1248                          BTRFS_BLOCK_GROUP_RAID10 |
1249                          BTRFS_BLOCK_GROUP_DUP)) {
1250                 /* we limit the length of each bio to what fits in a stripe */
1251                 *length = min_t(u64, ce->size - offset,
1252                               map->stripe_len - stripe_offset);
1253         } else {
1254                 *length = ce->size - offset;
1255         }
1256
1257         if (!multi_ret)
1258                 goto out;
1259
1260         multi->num_stripes = 1;
1261         stripe_index = 0;
1262         if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1263                 if (rw == WRITE)
1264                         multi->num_stripes = map->num_stripes;
1265                 else if (mirror_num)
1266                         stripe_index = mirror_num - 1;
1267                 else
1268                         stripe_index = stripe_nr % map->num_stripes;
1269         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1270                 int factor = map->num_stripes / map->sub_stripes;
1271
1272                 stripe_index = stripe_nr % factor;
1273                 stripe_index *= map->sub_stripes;
1274
1275                 if (rw == WRITE)
1276                         multi->num_stripes = map->sub_stripes;
1277                 else if (mirror_num)
1278                         stripe_index += mirror_num - 1;
1279
1280                 stripe_nr = stripe_nr / factor;
1281         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
1282                 if (rw == WRITE)
1283                         multi->num_stripes = map->num_stripes;
1284                 else if (mirror_num)
1285                         stripe_index = mirror_num - 1;
1286         } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
1287                                 BTRFS_BLOCK_GROUP_RAID6)) {
1288
1289                 if (raid_map) {
1290                         int i, rot;
1291                         u64 tmp;
1292                         u64 raid56_full_stripe_start;
1293                         u64 full_stripe_len = nr_data_stripes(map) * map->stripe_len;
1294
1295                         /*
1296                          * align the start of our data stripe in the logical
1297                          * address space
1298                          */
1299                         raid56_full_stripe_start = offset / full_stripe_len;
1300                         raid56_full_stripe_start *= full_stripe_len;
1301
1302                         /* get the data stripe number */
1303                         stripe_nr = raid56_full_stripe_start / map->stripe_len;
1304                         stripe_nr = stripe_nr / nr_data_stripes(map);
1305
1306                         /* Work out the disk rotation on this stripe-set */
1307                         rot = stripe_nr % map->num_stripes;
1308
1309                         /* Fill in the logical address of each stripe */
1310                         tmp = stripe_nr * nr_data_stripes(map);
1311
1312                         for (i = 0; i < nr_data_stripes(map); i++)
1313                                 raid_map[(i+rot) % map->num_stripes] =
1314                                         ce->start + (tmp + i) * map->stripe_len;
1315
1316                         raid_map[(i+rot) % map->num_stripes] = BTRFS_RAID5_P_STRIPE;
1317                         if (map->type & BTRFS_BLOCK_GROUP_RAID6)
1318                                 raid_map[(i+rot+1) % map->num_stripes] = BTRFS_RAID6_Q_STRIPE;
1319
1320                         *length = map->stripe_len;
1321                         stripe_index = 0;
1322                         stripe_offset = 0;
1323                         multi->num_stripes = map->num_stripes;
1324                 } else {
1325                         stripe_index = stripe_nr % nr_data_stripes(map);
1326                         stripe_nr = stripe_nr / nr_data_stripes(map);
1327
1328                         /*
1329                          * Mirror #0 or #1 means the original data block.
1330                          * Mirror #2 is RAID5 parity block.
1331                          * Mirror #3 is RAID6 Q block.
1332                          */
1333                         if (mirror_num > 1)
1334                                 stripe_index = nr_data_stripes(map) + mirror_num - 2;
1335
1336                         /* We distribute the parity blocks across stripes */
1337                         stripe_index = (stripe_nr + stripe_index) % map->num_stripes;
1338                 }
1339         } else {
1340                 /*
1341                  * after this do_div call, stripe_nr is the number of stripes
1342                  * on this device we have to walk to find the data, and
1343                  * stripe_index is the number of our device in the stripe array
1344                  */
1345                 stripe_index = stripe_nr % map->num_stripes;
1346                 stripe_nr = stripe_nr / map->num_stripes;
1347         }
1348         BUG_ON(stripe_index >= map->num_stripes);
1349
1350         for (i = 0; i < multi->num_stripes; i++) {
1351                 multi->stripes[i].physical =
1352                         map->stripes[stripe_index].physical + stripe_offset +
1353                         stripe_nr * map->stripe_len;
1354                 multi->stripes[i].dev = map->stripes[stripe_index].dev;
1355                 stripe_index++;
1356         }
1357         *multi_ret = multi;
1358
1359         if (type)
1360                 *type = map->type;
1361
1362         if (raid_map) {
1363                 sort_parity_stripes(multi, raid_map);
1364                 *raid_map_ret = raid_map;
1365         }
1366 out:
1367         return 0;
1368 }
1369
1370 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
1371                                        u8 *uuid, u8 *fsid)
1372 {
1373         struct btrfs_device *device;
1374         struct btrfs_fs_devices *cur_devices;
1375
1376         cur_devices = root->fs_info->fs_devices;
1377         while (cur_devices) {
1378                 if (!fsid ||
1379                     !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
1380                         device = __find_device(&cur_devices->devices,
1381                                                devid, uuid);
1382                         if (device)
1383                                 return device;
1384                 }
1385                 cur_devices = cur_devices->seed;
1386         }
1387         return NULL;
1388 }
1389
1390 struct btrfs_device *btrfs_find_device_by_devid(struct btrfs_root *root,
1391                                                 u64 devid, int instance)
1392 {
1393         struct list_head *head = &root->fs_info->fs_devices->devices;
1394         struct btrfs_device *dev;
1395         struct list_head *cur;
1396         int num_found = 0;
1397
1398         list_for_each(cur, head) {
1399                 dev = list_entry(cur, struct btrfs_device, dev_list);
1400                 if (dev->devid == devid && num_found++ == instance)
1401                         return dev;
1402         }
1403         return NULL;
1404 }
1405
1406 int btrfs_bootstrap_super_map(struct btrfs_mapping_tree *map_tree,
1407                               struct btrfs_fs_devices *fs_devices)
1408 {
1409         struct map_lookup *map;
1410         u64 logical = BTRFS_SUPER_INFO_OFFSET;
1411         u64 length = BTRFS_SUPER_INFO_SIZE;
1412         int num_stripes = 0;
1413         int sub_stripes = 0;
1414         int ret;
1415         int i;
1416         struct list_head *cur;
1417
1418         list_for_each(cur, &fs_devices->devices) {
1419                 num_stripes++;
1420         }
1421         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
1422         if (!map)
1423                 return -ENOMEM;
1424
1425         map->ce.start = logical;
1426         map->ce.size = length;
1427         map->num_stripes = num_stripes;
1428         map->sub_stripes = sub_stripes;
1429         map->io_width = length;
1430         map->io_align = length;
1431         map->sector_size = length;
1432         map->stripe_len = length;
1433         map->type = BTRFS_BLOCK_GROUP_RAID1;
1434
1435         i = 0;
1436         list_for_each(cur, &fs_devices->devices) {
1437                 struct btrfs_device *device = list_entry(cur,
1438                                                          struct btrfs_device,
1439                                                          dev_list);
1440                 map->stripes[i].physical = logical;
1441                 map->stripes[i].dev = device;
1442                 i++;
1443         }
1444         ret = insert_existing_cache_extent(&map_tree->cache_tree, &map->ce);
1445         if (ret == -EEXIST) {
1446                 struct cache_extent *old;
1447                 struct map_lookup *old_map;
1448                 old = find_cache_extent(&map_tree->cache_tree, 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_existing_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 = find_first_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 = find_first_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(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_existing_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_super_device(struct btrfs_root *root, struct extent_buffer *buf)
1645 {
1646         struct btrfs_dev_item *dev_item;
1647
1648         dev_item = (struct btrfs_dev_item *)offsetof(struct btrfs_super_block,
1649                                                      dev_item);
1650         return read_one_dev(root, buf, dev_item);
1651 }
1652
1653 int btrfs_read_sys_array(struct btrfs_root *root)
1654 {
1655         struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
1656         struct extent_buffer *sb;
1657         struct btrfs_disk_key *disk_key;
1658         struct btrfs_chunk *chunk;
1659         struct btrfs_key key;
1660         u32 num_stripes;
1661         u32 array_size;
1662         u32 len = 0;
1663         u8 *ptr;
1664         unsigned long sb_ptr;
1665         u32 cur;
1666         int ret = 0;
1667
1668         sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
1669                                           BTRFS_SUPER_INFO_SIZE);
1670         if (!sb)
1671                 return -ENOMEM;
1672         btrfs_set_buffer_uptodate(sb);
1673         write_extent_buffer(sb, super_copy, 0, sizeof(*super_copy));
1674         array_size = btrfs_super_sys_array_size(super_copy);
1675
1676         /*
1677          * we do this loop twice, once for the device items and
1678          * once for all of the chunks.  This way there are device
1679          * structs filled in for every chunk
1680          */
1681         ptr = super_copy->sys_chunk_array;
1682         sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
1683         cur = 0;
1684
1685         while (cur < array_size) {
1686                 disk_key = (struct btrfs_disk_key *)ptr;
1687                 btrfs_disk_key_to_cpu(&key, disk_key);
1688
1689                 len = sizeof(*disk_key);
1690                 ptr += len;
1691                 sb_ptr += len;
1692                 cur += len;
1693
1694                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1695                         chunk = (struct btrfs_chunk *)sb_ptr;
1696                         ret = read_one_chunk(root, &key, sb, chunk);
1697                         if (ret)
1698                                 break;
1699                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
1700                         len = btrfs_chunk_item_size(num_stripes);
1701                 } else {
1702                         BUG();
1703                 }
1704                 ptr += len;
1705                 sb_ptr += len;
1706                 cur += len;
1707         }
1708         free_extent_buffer(sb);
1709         return ret;
1710 }
1711
1712 int btrfs_read_chunk_tree(struct btrfs_root *root)
1713 {
1714         struct btrfs_path *path;
1715         struct extent_buffer *leaf;
1716         struct btrfs_key key;
1717         struct btrfs_key found_key;
1718         int ret;
1719         int slot;
1720
1721         root = root->fs_info->chunk_root;
1722
1723         path = btrfs_alloc_path();
1724         if (!path)
1725                 return -ENOMEM;
1726
1727         /* first we search for all of the device items, and then we
1728          * read in all of the chunk items.  This way we can create chunk
1729          * mappings that reference all of the devices that are afound
1730          */
1731         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1732         key.offset = 0;
1733         key.type = 0;
1734 again:
1735         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1736         while(1) {
1737                 leaf = path->nodes[0];
1738                 slot = path->slots[0];
1739                 if (slot >= btrfs_header_nritems(leaf)) {
1740                         ret = btrfs_next_leaf(root, path);
1741                         if (ret == 0)
1742                                 continue;
1743                         if (ret < 0)
1744                                 goto error;
1745                         break;
1746                 }
1747                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1748                 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
1749                         if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
1750                                 break;
1751                         if (found_key.type == BTRFS_DEV_ITEM_KEY) {
1752                                 struct btrfs_dev_item *dev_item;
1753                                 dev_item = btrfs_item_ptr(leaf, slot,
1754                                                   struct btrfs_dev_item);
1755                                 ret = read_one_dev(root, leaf, dev_item);
1756                                 BUG_ON(ret);
1757                         }
1758                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
1759                         struct btrfs_chunk *chunk;
1760                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
1761                         ret = read_one_chunk(root, &found_key, leaf, chunk);
1762                         BUG_ON(ret);
1763                 }
1764                 path->slots[0]++;
1765         }
1766         if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
1767                 key.objectid = 0;
1768                 btrfs_release_path(root, path);
1769                 goto again;
1770         }
1771
1772         ret = 0;
1773 error:
1774         btrfs_free_path(path);
1775         return ret;
1776 }
1777
1778 struct list_head *btrfs_scanned_uuids(void)
1779 {
1780         return &fs_uuids;
1781 }