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