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