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