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