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