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