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