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