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