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