2 * Copyright (C) 2007 Oracle. All rights reserved.
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.
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.
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.
18 #include <linux/sched.h>
19 #include <linux/bio.h>
20 #include <linux/slab.h>
21 #include <linux/buffer_head.h>
22 #include <linux/blkdev.h>
23 #include <linux/random.h>
24 #include <linux/iocontext.h>
25 #include <linux/capability.h>
26 #include <linux/ratelimit.h>
27 #include <linux/kthread.h>
28 #include <asm/div64.h>
31 #include "extent_map.h"
33 #include "transaction.h"
34 #include "print-tree.h"
36 #include "async-thread.h"
37 #include "check-integrity.h"
38 #include "rcu-string.h"
40 static int init_first_rw_device(struct btrfs_trans_handle *trans,
41 struct btrfs_root *root,
42 struct btrfs_device *device);
43 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
44 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
45 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
47 static DEFINE_MUTEX(uuid_mutex);
48 static LIST_HEAD(fs_uuids);
50 static void lock_chunks(struct btrfs_root *root)
52 mutex_lock(&root->fs_info->chunk_mutex);
55 static void unlock_chunks(struct btrfs_root *root)
57 mutex_unlock(&root->fs_info->chunk_mutex);
60 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
62 struct btrfs_device *device;
63 WARN_ON(fs_devices->opened);
64 while (!list_empty(&fs_devices->devices)) {
65 device = list_entry(fs_devices->devices.next,
66 struct btrfs_device, dev_list);
67 list_del(&device->dev_list);
68 rcu_string_free(device->name);
74 void btrfs_cleanup_fs_uuids(void)
76 struct btrfs_fs_devices *fs_devices;
78 while (!list_empty(&fs_uuids)) {
79 fs_devices = list_entry(fs_uuids.next,
80 struct btrfs_fs_devices, list);
81 list_del(&fs_devices->list);
82 free_fs_devices(fs_devices);
86 static noinline struct btrfs_device *__find_device(struct list_head *head,
89 struct btrfs_device *dev;
91 list_for_each_entry(dev, head, dev_list) {
92 if (dev->devid == devid &&
93 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
100 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
102 struct btrfs_fs_devices *fs_devices;
104 list_for_each_entry(fs_devices, &fs_uuids, list) {
105 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
111 static void requeue_list(struct btrfs_pending_bios *pending_bios,
112 struct bio *head, struct bio *tail)
115 struct bio *old_head;
117 old_head = pending_bios->head;
118 pending_bios->head = head;
119 if (pending_bios->tail)
120 tail->bi_next = old_head;
122 pending_bios->tail = tail;
126 * we try to collect pending bios for a device so we don't get a large
127 * number of procs sending bios down to the same device. This greatly
128 * improves the schedulers ability to collect and merge the bios.
130 * But, it also turns into a long list of bios to process and that is sure
131 * to eventually make the worker thread block. The solution here is to
132 * make some progress and then put this work struct back at the end of
133 * the list if the block device is congested. This way, multiple devices
134 * can make progress from a single worker thread.
136 static noinline void run_scheduled_bios(struct btrfs_device *device)
139 struct backing_dev_info *bdi;
140 struct btrfs_fs_info *fs_info;
141 struct btrfs_pending_bios *pending_bios;
145 unsigned long num_run;
146 unsigned long batch_run = 0;
148 unsigned long last_waited = 0;
150 int sync_pending = 0;
151 struct blk_plug plug;
154 * this function runs all the bios we've collected for
155 * a particular device. We don't want to wander off to
156 * another device without first sending all of these down.
157 * So, setup a plug here and finish it off before we return
159 blk_start_plug(&plug);
161 bdi = blk_get_backing_dev_info(device->bdev);
162 fs_info = device->dev_root->fs_info;
163 limit = btrfs_async_submit_limit(fs_info);
164 limit = limit * 2 / 3;
167 spin_lock(&device->io_lock);
172 /* take all the bios off the list at once and process them
173 * later on (without the lock held). But, remember the
174 * tail and other pointers so the bios can be properly reinserted
175 * into the list if we hit congestion
177 if (!force_reg && device->pending_sync_bios.head) {
178 pending_bios = &device->pending_sync_bios;
181 pending_bios = &device->pending_bios;
185 pending = pending_bios->head;
186 tail = pending_bios->tail;
187 WARN_ON(pending && !tail);
190 * if pending was null this time around, no bios need processing
191 * at all and we can stop. Otherwise it'll loop back up again
192 * and do an additional check so no bios are missed.
194 * device->running_pending is used to synchronize with the
197 if (device->pending_sync_bios.head == NULL &&
198 device->pending_bios.head == NULL) {
200 device->running_pending = 0;
203 device->running_pending = 1;
206 pending_bios->head = NULL;
207 pending_bios->tail = NULL;
209 spin_unlock(&device->io_lock);
214 /* we want to work on both lists, but do more bios on the
215 * sync list than the regular list
218 pending_bios != &device->pending_sync_bios &&
219 device->pending_sync_bios.head) ||
220 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
221 device->pending_bios.head)) {
222 spin_lock(&device->io_lock);
223 requeue_list(pending_bios, pending, tail);
228 pending = pending->bi_next;
230 atomic_dec(&fs_info->nr_async_bios);
232 if (atomic_read(&fs_info->nr_async_bios) < limit &&
233 waitqueue_active(&fs_info->async_submit_wait))
234 wake_up(&fs_info->async_submit_wait);
236 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
239 * if we're doing the sync list, record that our
240 * plug has some sync requests on it
242 * If we're doing the regular list and there are
243 * sync requests sitting around, unplug before
246 if (pending_bios == &device->pending_sync_bios) {
248 } else if (sync_pending) {
249 blk_finish_plug(&plug);
250 blk_start_plug(&plug);
254 btrfsic_submit_bio(cur->bi_rw, cur);
261 * we made progress, there is more work to do and the bdi
262 * is now congested. Back off and let other work structs
265 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
266 fs_info->fs_devices->open_devices > 1) {
267 struct io_context *ioc;
269 ioc = current->io_context;
272 * the main goal here is that we don't want to
273 * block if we're going to be able to submit
274 * more requests without blocking.
276 * This code does two great things, it pokes into
277 * the elevator code from a filesystem _and_
278 * it makes assumptions about how batching works.
280 if (ioc && ioc->nr_batch_requests > 0 &&
281 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
283 ioc->last_waited == last_waited)) {
285 * we want to go through our batch of
286 * requests and stop. So, we copy out
287 * the ioc->last_waited time and test
288 * against it before looping
290 last_waited = ioc->last_waited;
295 spin_lock(&device->io_lock);
296 requeue_list(pending_bios, pending, tail);
297 device->running_pending = 1;
299 spin_unlock(&device->io_lock);
300 btrfs_requeue_work(&device->work);
303 /* unplug every 64 requests just for good measure */
304 if (batch_run % 64 == 0) {
305 blk_finish_plug(&plug);
306 blk_start_plug(&plug);
315 spin_lock(&device->io_lock);
316 if (device->pending_bios.head || device->pending_sync_bios.head)
318 spin_unlock(&device->io_lock);
321 blk_finish_plug(&plug);
324 static void pending_bios_fn(struct btrfs_work *work)
326 struct btrfs_device *device;
328 device = container_of(work, struct btrfs_device, work);
329 run_scheduled_bios(device);
332 static noinline int device_list_add(const char *path,
333 struct btrfs_super_block *disk_super,
334 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
336 struct btrfs_device *device;
337 struct btrfs_fs_devices *fs_devices;
338 struct rcu_string *name;
339 u64 found_transid = btrfs_super_generation(disk_super);
341 fs_devices = find_fsid(disk_super->fsid);
343 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
346 INIT_LIST_HEAD(&fs_devices->devices);
347 INIT_LIST_HEAD(&fs_devices->alloc_list);
348 list_add(&fs_devices->list, &fs_uuids);
349 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
350 fs_devices->latest_devid = devid;
351 fs_devices->latest_trans = found_transid;
352 mutex_init(&fs_devices->device_list_mutex);
355 device = __find_device(&fs_devices->devices, devid,
356 disk_super->dev_item.uuid);
359 if (fs_devices->opened)
362 device = kzalloc(sizeof(*device), GFP_NOFS);
364 /* we can safely leave the fs_devices entry around */
367 device->devid = devid;
368 device->dev_stats_valid = 0;
369 device->work.func = pending_bios_fn;
370 memcpy(device->uuid, disk_super->dev_item.uuid,
372 spin_lock_init(&device->io_lock);
374 name = rcu_string_strdup(path, GFP_NOFS);
379 rcu_assign_pointer(device->name, name);
380 INIT_LIST_HEAD(&device->dev_alloc_list);
382 /* init readahead state */
383 spin_lock_init(&device->reada_lock);
384 device->reada_curr_zone = NULL;
385 atomic_set(&device->reada_in_flight, 0);
386 device->reada_next = 0;
387 INIT_RADIX_TREE(&device->reada_zones, GFP_NOFS & ~__GFP_WAIT);
388 INIT_RADIX_TREE(&device->reada_extents, GFP_NOFS & ~__GFP_WAIT);
390 mutex_lock(&fs_devices->device_list_mutex);
391 list_add_rcu(&device->dev_list, &fs_devices->devices);
392 mutex_unlock(&fs_devices->device_list_mutex);
394 device->fs_devices = fs_devices;
395 fs_devices->num_devices++;
396 } else if (!device->name || strcmp(device->name->str, path)) {
397 name = rcu_string_strdup(path, GFP_NOFS);
400 rcu_string_free(device->name);
401 rcu_assign_pointer(device->name, name);
402 if (device->missing) {
403 fs_devices->missing_devices--;
408 if (found_transid > fs_devices->latest_trans) {
409 fs_devices->latest_devid = devid;
410 fs_devices->latest_trans = found_transid;
412 *fs_devices_ret = fs_devices;
416 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
418 struct btrfs_fs_devices *fs_devices;
419 struct btrfs_device *device;
420 struct btrfs_device *orig_dev;
422 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
424 return ERR_PTR(-ENOMEM);
426 INIT_LIST_HEAD(&fs_devices->devices);
427 INIT_LIST_HEAD(&fs_devices->alloc_list);
428 INIT_LIST_HEAD(&fs_devices->list);
429 mutex_init(&fs_devices->device_list_mutex);
430 fs_devices->latest_devid = orig->latest_devid;
431 fs_devices->latest_trans = orig->latest_trans;
432 fs_devices->total_devices = orig->total_devices;
433 memcpy(fs_devices->fsid, orig->fsid, sizeof(fs_devices->fsid));
435 /* We have held the volume lock, it is safe to get the devices. */
436 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
437 struct rcu_string *name;
439 device = kzalloc(sizeof(*device), GFP_NOFS);
444 * This is ok to do without rcu read locked because we hold the
445 * uuid mutex so nothing we touch in here is going to disappear.
447 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
452 rcu_assign_pointer(device->name, name);
454 device->devid = orig_dev->devid;
455 device->work.func = pending_bios_fn;
456 memcpy(device->uuid, orig_dev->uuid, sizeof(device->uuid));
457 spin_lock_init(&device->io_lock);
458 INIT_LIST_HEAD(&device->dev_list);
459 INIT_LIST_HEAD(&device->dev_alloc_list);
461 list_add(&device->dev_list, &fs_devices->devices);
462 device->fs_devices = fs_devices;
463 fs_devices->num_devices++;
467 free_fs_devices(fs_devices);
468 return ERR_PTR(-ENOMEM);
471 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
473 struct btrfs_device *device, *next;
475 struct block_device *latest_bdev = NULL;
476 u64 latest_devid = 0;
477 u64 latest_transid = 0;
479 mutex_lock(&uuid_mutex);
481 /* This is the initialized path, it is safe to release the devices. */
482 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
483 if (device->in_fs_metadata) {
484 if (!latest_transid ||
485 device->generation > latest_transid) {
486 latest_devid = device->devid;
487 latest_transid = device->generation;
488 latest_bdev = device->bdev;
494 blkdev_put(device->bdev, device->mode);
496 fs_devices->open_devices--;
498 if (device->writeable) {
499 list_del_init(&device->dev_alloc_list);
500 device->writeable = 0;
501 fs_devices->rw_devices--;
503 list_del_init(&device->dev_list);
504 fs_devices->num_devices--;
505 rcu_string_free(device->name);
509 if (fs_devices->seed) {
510 fs_devices = fs_devices->seed;
514 fs_devices->latest_bdev = latest_bdev;
515 fs_devices->latest_devid = latest_devid;
516 fs_devices->latest_trans = latest_transid;
518 mutex_unlock(&uuid_mutex);
521 static void __free_device(struct work_struct *work)
523 struct btrfs_device *device;
525 device = container_of(work, struct btrfs_device, rcu_work);
528 blkdev_put(device->bdev, device->mode);
530 rcu_string_free(device->name);
534 static void free_device(struct rcu_head *head)
536 struct btrfs_device *device;
538 device = container_of(head, struct btrfs_device, rcu);
540 INIT_WORK(&device->rcu_work, __free_device);
541 schedule_work(&device->rcu_work);
544 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
546 struct btrfs_device *device;
548 if (--fs_devices->opened > 0)
551 mutex_lock(&fs_devices->device_list_mutex);
552 list_for_each_entry(device, &fs_devices->devices, dev_list) {
553 struct btrfs_device *new_device;
554 struct rcu_string *name;
557 fs_devices->open_devices--;
559 if (device->writeable) {
560 list_del_init(&device->dev_alloc_list);
561 fs_devices->rw_devices--;
564 if (device->can_discard)
565 fs_devices->num_can_discard--;
567 new_device = kmalloc(sizeof(*new_device), GFP_NOFS);
568 BUG_ON(!new_device); /* -ENOMEM */
569 memcpy(new_device, device, sizeof(*new_device));
571 /* Safe because we are under uuid_mutex */
572 name = rcu_string_strdup(device->name->str, GFP_NOFS);
573 BUG_ON(device->name && !name); /* -ENOMEM */
574 rcu_assign_pointer(new_device->name, name);
575 new_device->bdev = NULL;
576 new_device->writeable = 0;
577 new_device->in_fs_metadata = 0;
578 new_device->can_discard = 0;
579 list_replace_rcu(&device->dev_list, &new_device->dev_list);
581 call_rcu(&device->rcu, free_device);
583 mutex_unlock(&fs_devices->device_list_mutex);
585 WARN_ON(fs_devices->open_devices);
586 WARN_ON(fs_devices->rw_devices);
587 fs_devices->opened = 0;
588 fs_devices->seeding = 0;
593 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
595 struct btrfs_fs_devices *seed_devices = NULL;
598 mutex_lock(&uuid_mutex);
599 ret = __btrfs_close_devices(fs_devices);
600 if (!fs_devices->opened) {
601 seed_devices = fs_devices->seed;
602 fs_devices->seed = NULL;
604 mutex_unlock(&uuid_mutex);
606 while (seed_devices) {
607 fs_devices = seed_devices;
608 seed_devices = fs_devices->seed;
609 __btrfs_close_devices(fs_devices);
610 free_fs_devices(fs_devices);
615 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
616 fmode_t flags, void *holder)
618 struct request_queue *q;
619 struct block_device *bdev;
620 struct list_head *head = &fs_devices->devices;
621 struct btrfs_device *device;
622 struct block_device *latest_bdev = NULL;
623 struct buffer_head *bh;
624 struct btrfs_super_block *disk_super;
625 u64 latest_devid = 0;
626 u64 latest_transid = 0;
633 list_for_each_entry(device, head, dev_list) {
639 bdev = blkdev_get_by_path(device->name->str, flags, holder);
641 printk(KERN_INFO "open %s failed\n", device->name->str);
644 filemap_write_and_wait(bdev->bd_inode->i_mapping);
645 invalidate_bdev(bdev);
646 set_blocksize(bdev, 4096);
648 bh = btrfs_read_dev_super(bdev);
652 disk_super = (struct btrfs_super_block *)bh->b_data;
653 devid = btrfs_stack_device_id(&disk_super->dev_item);
654 if (devid != device->devid)
657 if (memcmp(device->uuid, disk_super->dev_item.uuid,
661 device->generation = btrfs_super_generation(disk_super);
662 if (!latest_transid || device->generation > latest_transid) {
663 latest_devid = devid;
664 latest_transid = device->generation;
668 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
669 device->writeable = 0;
671 device->writeable = !bdev_read_only(bdev);
675 q = bdev_get_queue(bdev);
676 if (blk_queue_discard(q)) {
677 device->can_discard = 1;
678 fs_devices->num_can_discard++;
682 device->in_fs_metadata = 0;
683 device->mode = flags;
685 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
686 fs_devices->rotating = 1;
688 fs_devices->open_devices++;
689 if (device->writeable) {
690 fs_devices->rw_devices++;
691 list_add(&device->dev_alloc_list,
692 &fs_devices->alloc_list);
700 blkdev_put(bdev, flags);
704 if (fs_devices->open_devices == 0) {
708 fs_devices->seeding = seeding;
709 fs_devices->opened = 1;
710 fs_devices->latest_bdev = latest_bdev;
711 fs_devices->latest_devid = latest_devid;
712 fs_devices->latest_trans = latest_transid;
713 fs_devices->total_rw_bytes = 0;
718 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
719 fmode_t flags, void *holder)
723 mutex_lock(&uuid_mutex);
724 if (fs_devices->opened) {
725 fs_devices->opened++;
728 ret = __btrfs_open_devices(fs_devices, flags, holder);
730 mutex_unlock(&uuid_mutex);
734 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
735 struct btrfs_fs_devices **fs_devices_ret)
737 struct btrfs_super_block *disk_super;
738 struct block_device *bdev;
739 struct buffer_head *bh;
746 bdev = blkdev_get_by_path(path, flags, holder);
753 mutex_lock(&uuid_mutex);
754 ret = set_blocksize(bdev, 4096);
757 bh = btrfs_read_dev_super(bdev);
762 disk_super = (struct btrfs_super_block *)bh->b_data;
763 devid = btrfs_stack_device_id(&disk_super->dev_item);
764 transid = btrfs_super_generation(disk_super);
765 total_devices = btrfs_super_num_devices(disk_super);
766 if (disk_super->label[0])
767 printk(KERN_INFO "device label %s ", disk_super->label);
769 printk(KERN_INFO "device fsid %pU ", disk_super->fsid);
770 printk(KERN_CONT "devid %llu transid %llu %s\n",
771 (unsigned long long)devid, (unsigned long long)transid, path);
772 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
773 if (!ret && fs_devices_ret)
774 (*fs_devices_ret)->total_devices = total_devices;
777 mutex_unlock(&uuid_mutex);
778 blkdev_put(bdev, flags);
783 /* helper to account the used device space in the range */
784 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
785 u64 end, u64 *length)
787 struct btrfs_key key;
788 struct btrfs_root *root = device->dev_root;
789 struct btrfs_dev_extent *dev_extent;
790 struct btrfs_path *path;
794 struct extent_buffer *l;
798 if (start >= device->total_bytes)
801 path = btrfs_alloc_path();
806 key.objectid = device->devid;
808 key.type = BTRFS_DEV_EXTENT_KEY;
810 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
814 ret = btrfs_previous_item(root, path, key.objectid, key.type);
821 slot = path->slots[0];
822 if (slot >= btrfs_header_nritems(l)) {
823 ret = btrfs_next_leaf(root, path);
831 btrfs_item_key_to_cpu(l, &key, slot);
833 if (key.objectid < device->devid)
836 if (key.objectid > device->devid)
839 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
842 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
843 extent_end = key.offset + btrfs_dev_extent_length(l,
845 if (key.offset <= start && extent_end > end) {
846 *length = end - start + 1;
848 } else if (key.offset <= start && extent_end > start)
849 *length += extent_end - start;
850 else if (key.offset > start && extent_end <= end)
851 *length += extent_end - key.offset;
852 else if (key.offset > start && key.offset <= end) {
853 *length += end - key.offset + 1;
855 } else if (key.offset > end)
863 btrfs_free_path(path);
868 * find_free_dev_extent - find free space in the specified device
869 * @device: the device which we search the free space in
870 * @num_bytes: the size of the free space that we need
871 * @start: store the start of the free space.
872 * @len: the size of the free space. that we find, or the size of the max
873 * free space if we don't find suitable free space
875 * this uses a pretty simple search, the expectation is that it is
876 * called very infrequently and that a given device has a small number
879 * @start is used to store the start of the free space if we find. But if we
880 * don't find suitable free space, it will be used to store the start position
881 * of the max free space.
883 * @len is used to store the size of the free space that we find.
884 * But if we don't find suitable free space, it is used to store the size of
885 * the max free space.
887 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
888 u64 *start, u64 *len)
890 struct btrfs_key key;
891 struct btrfs_root *root = device->dev_root;
892 struct btrfs_dev_extent *dev_extent;
893 struct btrfs_path *path;
899 u64 search_end = device->total_bytes;
902 struct extent_buffer *l;
904 /* FIXME use last free of some kind */
906 /* we don't want to overwrite the superblock on the drive,
907 * so we make sure to start at an offset of at least 1MB
909 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
911 max_hole_start = search_start;
915 if (search_start >= search_end) {
920 path = btrfs_alloc_path();
927 key.objectid = device->devid;
928 key.offset = search_start;
929 key.type = BTRFS_DEV_EXTENT_KEY;
931 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
935 ret = btrfs_previous_item(root, path, key.objectid, key.type);
942 slot = path->slots[0];
943 if (slot >= btrfs_header_nritems(l)) {
944 ret = btrfs_next_leaf(root, path);
952 btrfs_item_key_to_cpu(l, &key, slot);
954 if (key.objectid < device->devid)
957 if (key.objectid > device->devid)
960 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
963 if (key.offset > search_start) {
964 hole_size = key.offset - search_start;
966 if (hole_size > max_hole_size) {
967 max_hole_start = search_start;
968 max_hole_size = hole_size;
972 * If this free space is greater than which we need,
973 * it must be the max free space that we have found
974 * until now, so max_hole_start must point to the start
975 * of this free space and the length of this free space
976 * is stored in max_hole_size. Thus, we return
977 * max_hole_start and max_hole_size and go back to the
980 if (hole_size >= num_bytes) {
986 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
987 extent_end = key.offset + btrfs_dev_extent_length(l,
989 if (extent_end > search_start)
990 search_start = extent_end;
997 * At this point, search_start should be the end of
998 * allocated dev extents, and when shrinking the device,
999 * search_end may be smaller than search_start.
1001 if (search_end > search_start)
1002 hole_size = search_end - search_start;
1004 if (hole_size > max_hole_size) {
1005 max_hole_start = search_start;
1006 max_hole_size = hole_size;
1010 if (hole_size < num_bytes)
1016 btrfs_free_path(path);
1018 *start = max_hole_start;
1020 *len = max_hole_size;
1024 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1025 struct btrfs_device *device,
1029 struct btrfs_path *path;
1030 struct btrfs_root *root = device->dev_root;
1031 struct btrfs_key key;
1032 struct btrfs_key found_key;
1033 struct extent_buffer *leaf = NULL;
1034 struct btrfs_dev_extent *extent = NULL;
1036 path = btrfs_alloc_path();
1040 key.objectid = device->devid;
1042 key.type = BTRFS_DEV_EXTENT_KEY;
1044 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1046 ret = btrfs_previous_item(root, path, key.objectid,
1047 BTRFS_DEV_EXTENT_KEY);
1050 leaf = path->nodes[0];
1051 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1052 extent = btrfs_item_ptr(leaf, path->slots[0],
1053 struct btrfs_dev_extent);
1054 BUG_ON(found_key.offset > start || found_key.offset +
1055 btrfs_dev_extent_length(leaf, extent) < start);
1057 btrfs_release_path(path);
1059 } else if (ret == 0) {
1060 leaf = path->nodes[0];
1061 extent = btrfs_item_ptr(leaf, path->slots[0],
1062 struct btrfs_dev_extent);
1064 btrfs_error(root->fs_info, ret, "Slot search failed");
1068 if (device->bytes_used > 0) {
1069 u64 len = btrfs_dev_extent_length(leaf, extent);
1070 device->bytes_used -= len;
1071 spin_lock(&root->fs_info->free_chunk_lock);
1072 root->fs_info->free_chunk_space += len;
1073 spin_unlock(&root->fs_info->free_chunk_lock);
1075 ret = btrfs_del_item(trans, root, path);
1077 btrfs_error(root->fs_info, ret,
1078 "Failed to remove dev extent item");
1081 btrfs_free_path(path);
1085 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1086 struct btrfs_device *device,
1087 u64 chunk_tree, u64 chunk_objectid,
1088 u64 chunk_offset, u64 start, u64 num_bytes)
1091 struct btrfs_path *path;
1092 struct btrfs_root *root = device->dev_root;
1093 struct btrfs_dev_extent *extent;
1094 struct extent_buffer *leaf;
1095 struct btrfs_key key;
1097 WARN_ON(!device->in_fs_metadata);
1098 path = btrfs_alloc_path();
1102 key.objectid = device->devid;
1104 key.type = BTRFS_DEV_EXTENT_KEY;
1105 ret = btrfs_insert_empty_item(trans, root, path, &key,
1110 leaf = path->nodes[0];
1111 extent = btrfs_item_ptr(leaf, path->slots[0],
1112 struct btrfs_dev_extent);
1113 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1114 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1115 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1117 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1118 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1121 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1122 btrfs_mark_buffer_dirty(leaf);
1124 btrfs_free_path(path);
1128 static noinline int find_next_chunk(struct btrfs_root *root,
1129 u64 objectid, u64 *offset)
1131 struct btrfs_path *path;
1133 struct btrfs_key key;
1134 struct btrfs_chunk *chunk;
1135 struct btrfs_key found_key;
1137 path = btrfs_alloc_path();
1141 key.objectid = objectid;
1142 key.offset = (u64)-1;
1143 key.type = BTRFS_CHUNK_ITEM_KEY;
1145 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1149 BUG_ON(ret == 0); /* Corruption */
1151 ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
1155 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1157 if (found_key.objectid != objectid)
1160 chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
1161 struct btrfs_chunk);
1162 *offset = found_key.offset +
1163 btrfs_chunk_length(path->nodes[0], chunk);
1168 btrfs_free_path(path);
1172 static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
1175 struct btrfs_key key;
1176 struct btrfs_key found_key;
1177 struct btrfs_path *path;
1179 root = root->fs_info->chunk_root;
1181 path = btrfs_alloc_path();
1185 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1186 key.type = BTRFS_DEV_ITEM_KEY;
1187 key.offset = (u64)-1;
1189 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1193 BUG_ON(ret == 0); /* Corruption */
1195 ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
1196 BTRFS_DEV_ITEM_KEY);
1200 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1202 *objectid = found_key.offset + 1;
1206 btrfs_free_path(path);
1211 * the device information is stored in the chunk root
1212 * the btrfs_device struct should be fully filled in
1214 int btrfs_add_device(struct btrfs_trans_handle *trans,
1215 struct btrfs_root *root,
1216 struct btrfs_device *device)
1219 struct btrfs_path *path;
1220 struct btrfs_dev_item *dev_item;
1221 struct extent_buffer *leaf;
1222 struct btrfs_key key;
1225 root = root->fs_info->chunk_root;
1227 path = btrfs_alloc_path();
1231 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1232 key.type = BTRFS_DEV_ITEM_KEY;
1233 key.offset = device->devid;
1235 ret = btrfs_insert_empty_item(trans, root, path, &key,
1240 leaf = path->nodes[0];
1241 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1243 btrfs_set_device_id(leaf, dev_item, device->devid);
1244 btrfs_set_device_generation(leaf, dev_item, 0);
1245 btrfs_set_device_type(leaf, dev_item, device->type);
1246 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1247 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1248 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1249 btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1250 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1251 btrfs_set_device_group(leaf, dev_item, 0);
1252 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1253 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1254 btrfs_set_device_start_offset(leaf, dev_item, 0);
1256 ptr = (unsigned long)btrfs_device_uuid(dev_item);
1257 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1258 ptr = (unsigned long)btrfs_device_fsid(dev_item);
1259 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1260 btrfs_mark_buffer_dirty(leaf);
1264 btrfs_free_path(path);
1268 static int btrfs_rm_dev_item(struct btrfs_root *root,
1269 struct btrfs_device *device)
1272 struct btrfs_path *path;
1273 struct btrfs_key key;
1274 struct btrfs_trans_handle *trans;
1276 root = root->fs_info->chunk_root;
1278 path = btrfs_alloc_path();
1282 trans = btrfs_start_transaction(root, 0);
1283 if (IS_ERR(trans)) {
1284 btrfs_free_path(path);
1285 return PTR_ERR(trans);
1287 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1288 key.type = BTRFS_DEV_ITEM_KEY;
1289 key.offset = device->devid;
1292 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1301 ret = btrfs_del_item(trans, root, path);
1305 btrfs_free_path(path);
1306 unlock_chunks(root);
1307 btrfs_commit_transaction(trans, root);
1311 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1313 struct btrfs_device *device;
1314 struct btrfs_device *next_device;
1315 struct block_device *bdev;
1316 struct buffer_head *bh = NULL;
1317 struct btrfs_super_block *disk_super;
1318 struct btrfs_fs_devices *cur_devices;
1324 bool clear_super = false;
1326 mutex_lock(&uuid_mutex);
1328 all_avail = root->fs_info->avail_data_alloc_bits |
1329 root->fs_info->avail_system_alloc_bits |
1330 root->fs_info->avail_metadata_alloc_bits;
1332 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
1333 root->fs_info->fs_devices->num_devices <= 4) {
1334 printk(KERN_ERR "btrfs: unable to go below four devices "
1340 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
1341 root->fs_info->fs_devices->num_devices <= 2) {
1342 printk(KERN_ERR "btrfs: unable to go below two "
1343 "devices on raid1\n");
1348 if (strcmp(device_path, "missing") == 0) {
1349 struct list_head *devices;
1350 struct btrfs_device *tmp;
1353 devices = &root->fs_info->fs_devices->devices;
1355 * It is safe to read the devices since the volume_mutex
1358 list_for_each_entry(tmp, devices, dev_list) {
1359 if (tmp->in_fs_metadata && !tmp->bdev) {
1368 printk(KERN_ERR "btrfs: no missing devices found to "
1373 bdev = blkdev_get_by_path(device_path, FMODE_READ | FMODE_EXCL,
1374 root->fs_info->bdev_holder);
1376 ret = PTR_ERR(bdev);
1380 set_blocksize(bdev, 4096);
1381 invalidate_bdev(bdev);
1382 bh = btrfs_read_dev_super(bdev);
1387 disk_super = (struct btrfs_super_block *)bh->b_data;
1388 devid = btrfs_stack_device_id(&disk_super->dev_item);
1389 dev_uuid = disk_super->dev_item.uuid;
1390 device = btrfs_find_device(root, devid, dev_uuid,
1398 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1399 printk(KERN_ERR "btrfs: unable to remove the only writeable "
1405 if (device->writeable) {
1407 list_del_init(&device->dev_alloc_list);
1408 unlock_chunks(root);
1409 root->fs_info->fs_devices->rw_devices--;
1413 ret = btrfs_shrink_device(device, 0);
1417 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1421 spin_lock(&root->fs_info->free_chunk_lock);
1422 root->fs_info->free_chunk_space = device->total_bytes -
1424 spin_unlock(&root->fs_info->free_chunk_lock);
1426 device->in_fs_metadata = 0;
1427 btrfs_scrub_cancel_dev(root, device);
1430 * the device list mutex makes sure that we don't change
1431 * the device list while someone else is writing out all
1432 * the device supers.
1435 cur_devices = device->fs_devices;
1436 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1437 list_del_rcu(&device->dev_list);
1439 device->fs_devices->num_devices--;
1440 device->fs_devices->total_devices--;
1442 if (device->missing)
1443 root->fs_info->fs_devices->missing_devices--;
1445 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1446 struct btrfs_device, dev_list);
1447 if (device->bdev == root->fs_info->sb->s_bdev)
1448 root->fs_info->sb->s_bdev = next_device->bdev;
1449 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1450 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1453 device->fs_devices->open_devices--;
1455 call_rcu(&device->rcu, free_device);
1456 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1458 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1459 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1461 if (cur_devices->open_devices == 0) {
1462 struct btrfs_fs_devices *fs_devices;
1463 fs_devices = root->fs_info->fs_devices;
1464 while (fs_devices) {
1465 if (fs_devices->seed == cur_devices)
1467 fs_devices = fs_devices->seed;
1469 fs_devices->seed = cur_devices->seed;
1470 cur_devices->seed = NULL;
1472 __btrfs_close_devices(cur_devices);
1473 unlock_chunks(root);
1474 free_fs_devices(cur_devices);
1478 * at this point, the device is zero sized. We want to
1479 * remove it from the devices list and zero out the old super
1482 /* make sure this device isn't detected as part of
1485 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1486 set_buffer_dirty(bh);
1487 sync_dirty_buffer(bh);
1496 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1498 mutex_unlock(&uuid_mutex);
1501 if (device->writeable) {
1503 list_add(&device->dev_alloc_list,
1504 &root->fs_info->fs_devices->alloc_list);
1505 unlock_chunks(root);
1506 root->fs_info->fs_devices->rw_devices++;
1512 * does all the dirty work required for changing file system's UUID.
1514 static int btrfs_prepare_sprout(struct btrfs_root *root)
1516 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1517 struct btrfs_fs_devices *old_devices;
1518 struct btrfs_fs_devices *seed_devices;
1519 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1520 struct btrfs_device *device;
1523 BUG_ON(!mutex_is_locked(&uuid_mutex));
1524 if (!fs_devices->seeding)
1527 seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1531 old_devices = clone_fs_devices(fs_devices);
1532 if (IS_ERR(old_devices)) {
1533 kfree(seed_devices);
1534 return PTR_ERR(old_devices);
1537 list_add(&old_devices->list, &fs_uuids);
1539 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1540 seed_devices->opened = 1;
1541 INIT_LIST_HEAD(&seed_devices->devices);
1542 INIT_LIST_HEAD(&seed_devices->alloc_list);
1543 mutex_init(&seed_devices->device_list_mutex);
1545 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1546 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1548 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1550 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1551 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1552 device->fs_devices = seed_devices;
1555 fs_devices->seeding = 0;
1556 fs_devices->num_devices = 0;
1557 fs_devices->open_devices = 0;
1558 fs_devices->total_devices = 0;
1559 fs_devices->seed = seed_devices;
1561 generate_random_uuid(fs_devices->fsid);
1562 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1563 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1564 super_flags = btrfs_super_flags(disk_super) &
1565 ~BTRFS_SUPER_FLAG_SEEDING;
1566 btrfs_set_super_flags(disk_super, super_flags);
1572 * strore the expected generation for seed devices in device items.
1574 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1575 struct btrfs_root *root)
1577 struct btrfs_path *path;
1578 struct extent_buffer *leaf;
1579 struct btrfs_dev_item *dev_item;
1580 struct btrfs_device *device;
1581 struct btrfs_key key;
1582 u8 fs_uuid[BTRFS_UUID_SIZE];
1583 u8 dev_uuid[BTRFS_UUID_SIZE];
1587 path = btrfs_alloc_path();
1591 root = root->fs_info->chunk_root;
1592 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1594 key.type = BTRFS_DEV_ITEM_KEY;
1597 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1601 leaf = path->nodes[0];
1603 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1604 ret = btrfs_next_leaf(root, path);
1609 leaf = path->nodes[0];
1610 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1611 btrfs_release_path(path);
1615 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1616 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1617 key.type != BTRFS_DEV_ITEM_KEY)
1620 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1621 struct btrfs_dev_item);
1622 devid = btrfs_device_id(leaf, dev_item);
1623 read_extent_buffer(leaf, dev_uuid,
1624 (unsigned long)btrfs_device_uuid(dev_item),
1626 read_extent_buffer(leaf, fs_uuid,
1627 (unsigned long)btrfs_device_fsid(dev_item),
1629 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1630 BUG_ON(!device); /* Logic error */
1632 if (device->fs_devices->seeding) {
1633 btrfs_set_device_generation(leaf, dev_item,
1634 device->generation);
1635 btrfs_mark_buffer_dirty(leaf);
1643 btrfs_free_path(path);
1647 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1649 struct request_queue *q;
1650 struct btrfs_trans_handle *trans;
1651 struct btrfs_device *device;
1652 struct block_device *bdev;
1653 struct list_head *devices;
1654 struct super_block *sb = root->fs_info->sb;
1655 struct rcu_string *name;
1657 int seeding_dev = 0;
1660 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1663 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
1664 root->fs_info->bdev_holder);
1666 return PTR_ERR(bdev);
1668 if (root->fs_info->fs_devices->seeding) {
1670 down_write(&sb->s_umount);
1671 mutex_lock(&uuid_mutex);
1674 filemap_write_and_wait(bdev->bd_inode->i_mapping);
1676 devices = &root->fs_info->fs_devices->devices;
1678 * we have the volume lock, so we don't need the extra
1679 * device list mutex while reading the list here.
1681 list_for_each_entry(device, devices, dev_list) {
1682 if (device->bdev == bdev) {
1688 device = kzalloc(sizeof(*device), GFP_NOFS);
1690 /* we can safely leave the fs_devices entry around */
1695 name = rcu_string_strdup(device_path, GFP_NOFS);
1701 rcu_assign_pointer(device->name, name);
1703 ret = find_next_devid(root, &device->devid);
1705 rcu_string_free(device->name);
1710 trans = btrfs_start_transaction(root, 0);
1711 if (IS_ERR(trans)) {
1712 rcu_string_free(device->name);
1714 ret = PTR_ERR(trans);
1720 q = bdev_get_queue(bdev);
1721 if (blk_queue_discard(q))
1722 device->can_discard = 1;
1723 device->writeable = 1;
1724 device->work.func = pending_bios_fn;
1725 generate_random_uuid(device->uuid);
1726 spin_lock_init(&device->io_lock);
1727 device->generation = trans->transid;
1728 device->io_width = root->sectorsize;
1729 device->io_align = root->sectorsize;
1730 device->sector_size = root->sectorsize;
1731 device->total_bytes = i_size_read(bdev->bd_inode);
1732 device->disk_total_bytes = device->total_bytes;
1733 device->dev_root = root->fs_info->dev_root;
1734 device->bdev = bdev;
1735 device->in_fs_metadata = 1;
1736 device->mode = FMODE_EXCL;
1737 set_blocksize(device->bdev, 4096);
1740 sb->s_flags &= ~MS_RDONLY;
1741 ret = btrfs_prepare_sprout(root);
1742 BUG_ON(ret); /* -ENOMEM */
1745 device->fs_devices = root->fs_info->fs_devices;
1748 * we don't want write_supers to jump in here with our device
1751 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1752 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
1753 list_add(&device->dev_alloc_list,
1754 &root->fs_info->fs_devices->alloc_list);
1755 root->fs_info->fs_devices->num_devices++;
1756 root->fs_info->fs_devices->open_devices++;
1757 root->fs_info->fs_devices->rw_devices++;
1758 root->fs_info->fs_devices->total_devices++;
1759 if (device->can_discard)
1760 root->fs_info->fs_devices->num_can_discard++;
1761 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
1763 spin_lock(&root->fs_info->free_chunk_lock);
1764 root->fs_info->free_chunk_space += device->total_bytes;
1765 spin_unlock(&root->fs_info->free_chunk_lock);
1767 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
1768 root->fs_info->fs_devices->rotating = 1;
1770 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1771 btrfs_set_super_total_bytes(root->fs_info->super_copy,
1772 total_bytes + device->total_bytes);
1774 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
1775 btrfs_set_super_num_devices(root->fs_info->super_copy,
1777 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1780 ret = init_first_rw_device(trans, root, device);
1783 ret = btrfs_finish_sprout(trans, root);
1787 ret = btrfs_add_device(trans, root, device);
1793 * we've got more storage, clear any full flags on the space
1796 btrfs_clear_space_info_full(root->fs_info);
1798 unlock_chunks(root);
1799 ret = btrfs_commit_transaction(trans, root);
1802 mutex_unlock(&uuid_mutex);
1803 up_write(&sb->s_umount);
1805 if (ret) /* transaction commit */
1808 ret = btrfs_relocate_sys_chunks(root);
1810 btrfs_error(root->fs_info, ret,
1811 "Failed to relocate sys chunks after "
1812 "device initialization. This can be fixed "
1813 "using the \"btrfs balance\" command.");
1819 unlock_chunks(root);
1820 btrfs_abort_transaction(trans, root, ret);
1821 btrfs_end_transaction(trans, root);
1822 rcu_string_free(device->name);
1825 blkdev_put(bdev, FMODE_EXCL);
1827 mutex_unlock(&uuid_mutex);
1828 up_write(&sb->s_umount);
1833 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
1834 struct btrfs_device *device)
1837 struct btrfs_path *path;
1838 struct btrfs_root *root;
1839 struct btrfs_dev_item *dev_item;
1840 struct extent_buffer *leaf;
1841 struct btrfs_key key;
1843 root = device->dev_root->fs_info->chunk_root;
1845 path = btrfs_alloc_path();
1849 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1850 key.type = BTRFS_DEV_ITEM_KEY;
1851 key.offset = device->devid;
1853 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1862 leaf = path->nodes[0];
1863 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1865 btrfs_set_device_id(leaf, dev_item, device->devid);
1866 btrfs_set_device_type(leaf, dev_item, device->type);
1867 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1868 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1869 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1870 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
1871 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1872 btrfs_mark_buffer_dirty(leaf);
1875 btrfs_free_path(path);
1879 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
1880 struct btrfs_device *device, u64 new_size)
1882 struct btrfs_super_block *super_copy =
1883 device->dev_root->fs_info->super_copy;
1884 u64 old_total = btrfs_super_total_bytes(super_copy);
1885 u64 diff = new_size - device->total_bytes;
1887 if (!device->writeable)
1889 if (new_size <= device->total_bytes)
1892 btrfs_set_super_total_bytes(super_copy, old_total + diff);
1893 device->fs_devices->total_rw_bytes += diff;
1895 device->total_bytes = new_size;
1896 device->disk_total_bytes = new_size;
1897 btrfs_clear_space_info_full(device->dev_root->fs_info);
1899 return btrfs_update_device(trans, device);
1902 int btrfs_grow_device(struct btrfs_trans_handle *trans,
1903 struct btrfs_device *device, u64 new_size)
1906 lock_chunks(device->dev_root);
1907 ret = __btrfs_grow_device(trans, device, new_size);
1908 unlock_chunks(device->dev_root);
1912 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1913 struct btrfs_root *root,
1914 u64 chunk_tree, u64 chunk_objectid,
1918 struct btrfs_path *path;
1919 struct btrfs_key key;
1921 root = root->fs_info->chunk_root;
1922 path = btrfs_alloc_path();
1926 key.objectid = chunk_objectid;
1927 key.offset = chunk_offset;
1928 key.type = BTRFS_CHUNK_ITEM_KEY;
1930 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1933 else if (ret > 0) { /* Logic error or corruption */
1934 btrfs_error(root->fs_info, -ENOENT,
1935 "Failed lookup while freeing chunk.");
1940 ret = btrfs_del_item(trans, root, path);
1942 btrfs_error(root->fs_info, ret,
1943 "Failed to delete chunk item.");
1945 btrfs_free_path(path);
1949 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
1952 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
1953 struct btrfs_disk_key *disk_key;
1954 struct btrfs_chunk *chunk;
1961 struct btrfs_key key;
1963 array_size = btrfs_super_sys_array_size(super_copy);
1965 ptr = super_copy->sys_chunk_array;
1968 while (cur < array_size) {
1969 disk_key = (struct btrfs_disk_key *)ptr;
1970 btrfs_disk_key_to_cpu(&key, disk_key);
1972 len = sizeof(*disk_key);
1974 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1975 chunk = (struct btrfs_chunk *)(ptr + len);
1976 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1977 len += btrfs_chunk_item_size(num_stripes);
1982 if (key.objectid == chunk_objectid &&
1983 key.offset == chunk_offset) {
1984 memmove(ptr, ptr + len, array_size - (cur + len));
1986 btrfs_set_super_sys_array_size(super_copy, array_size);
1995 static int btrfs_relocate_chunk(struct btrfs_root *root,
1996 u64 chunk_tree, u64 chunk_objectid,
1999 struct extent_map_tree *em_tree;
2000 struct btrfs_root *extent_root;
2001 struct btrfs_trans_handle *trans;
2002 struct extent_map *em;
2003 struct map_lookup *map;
2007 root = root->fs_info->chunk_root;
2008 extent_root = root->fs_info->extent_root;
2009 em_tree = &root->fs_info->mapping_tree.map_tree;
2011 ret = btrfs_can_relocate(extent_root, chunk_offset);
2015 /* step one, relocate all the extents inside this chunk */
2016 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2020 trans = btrfs_start_transaction(root, 0);
2021 BUG_ON(IS_ERR(trans));
2026 * step two, delete the device extents and the
2027 * chunk tree entries
2029 read_lock(&em_tree->lock);
2030 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2031 read_unlock(&em_tree->lock);
2033 BUG_ON(!em || em->start > chunk_offset ||
2034 em->start + em->len < chunk_offset);
2035 map = (struct map_lookup *)em->bdev;
2037 for (i = 0; i < map->num_stripes; i++) {
2038 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
2039 map->stripes[i].physical);
2042 if (map->stripes[i].dev) {
2043 ret = btrfs_update_device(trans, map->stripes[i].dev);
2047 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2052 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2054 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2055 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2059 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2062 write_lock(&em_tree->lock);
2063 remove_extent_mapping(em_tree, em);
2064 write_unlock(&em_tree->lock);
2069 /* once for the tree */
2070 free_extent_map(em);
2072 free_extent_map(em);
2074 unlock_chunks(root);
2075 btrfs_end_transaction(trans, root);
2079 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2081 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2082 struct btrfs_path *path;
2083 struct extent_buffer *leaf;
2084 struct btrfs_chunk *chunk;
2085 struct btrfs_key key;
2086 struct btrfs_key found_key;
2087 u64 chunk_tree = chunk_root->root_key.objectid;
2089 bool retried = false;
2093 path = btrfs_alloc_path();
2098 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2099 key.offset = (u64)-1;
2100 key.type = BTRFS_CHUNK_ITEM_KEY;
2103 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2106 BUG_ON(ret == 0); /* Corruption */
2108 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2115 leaf = path->nodes[0];
2116 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2118 chunk = btrfs_item_ptr(leaf, path->slots[0],
2119 struct btrfs_chunk);
2120 chunk_type = btrfs_chunk_type(leaf, chunk);
2121 btrfs_release_path(path);
2123 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2124 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2133 if (found_key.offset == 0)
2135 key.offset = found_key.offset - 1;
2138 if (failed && !retried) {
2142 } else if (failed && retried) {
2147 btrfs_free_path(path);
2151 static int insert_balance_item(struct btrfs_root *root,
2152 struct btrfs_balance_control *bctl)
2154 struct btrfs_trans_handle *trans;
2155 struct btrfs_balance_item *item;
2156 struct btrfs_disk_balance_args disk_bargs;
2157 struct btrfs_path *path;
2158 struct extent_buffer *leaf;
2159 struct btrfs_key key;
2162 path = btrfs_alloc_path();
2166 trans = btrfs_start_transaction(root, 0);
2167 if (IS_ERR(trans)) {
2168 btrfs_free_path(path);
2169 return PTR_ERR(trans);
2172 key.objectid = BTRFS_BALANCE_OBJECTID;
2173 key.type = BTRFS_BALANCE_ITEM_KEY;
2176 ret = btrfs_insert_empty_item(trans, root, path, &key,
2181 leaf = path->nodes[0];
2182 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2184 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2186 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2187 btrfs_set_balance_data(leaf, item, &disk_bargs);
2188 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2189 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2190 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2191 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2193 btrfs_set_balance_flags(leaf, item, bctl->flags);
2195 btrfs_mark_buffer_dirty(leaf);
2197 btrfs_free_path(path);
2198 err = btrfs_commit_transaction(trans, root);
2204 static int del_balance_item(struct btrfs_root *root)
2206 struct btrfs_trans_handle *trans;
2207 struct btrfs_path *path;
2208 struct btrfs_key key;
2211 path = btrfs_alloc_path();
2215 trans = btrfs_start_transaction(root, 0);
2216 if (IS_ERR(trans)) {
2217 btrfs_free_path(path);
2218 return PTR_ERR(trans);
2221 key.objectid = BTRFS_BALANCE_OBJECTID;
2222 key.type = BTRFS_BALANCE_ITEM_KEY;
2225 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2233 ret = btrfs_del_item(trans, root, path);
2235 btrfs_free_path(path);
2236 err = btrfs_commit_transaction(trans, root);
2243 * This is a heuristic used to reduce the number of chunks balanced on
2244 * resume after balance was interrupted.
2246 static void update_balance_args(struct btrfs_balance_control *bctl)
2249 * Turn on soft mode for chunk types that were being converted.
2251 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2252 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2253 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2254 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2255 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2256 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2259 * Turn on usage filter if is not already used. The idea is
2260 * that chunks that we have already balanced should be
2261 * reasonably full. Don't do it for chunks that are being
2262 * converted - that will keep us from relocating unconverted
2263 * (albeit full) chunks.
2265 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2266 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2267 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2268 bctl->data.usage = 90;
2270 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2271 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2272 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2273 bctl->sys.usage = 90;
2275 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2276 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2277 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2278 bctl->meta.usage = 90;
2283 * Should be called with both balance and volume mutexes held to
2284 * serialize other volume operations (add_dev/rm_dev/resize) with
2285 * restriper. Same goes for unset_balance_control.
2287 static void set_balance_control(struct btrfs_balance_control *bctl)
2289 struct btrfs_fs_info *fs_info = bctl->fs_info;
2291 BUG_ON(fs_info->balance_ctl);
2293 spin_lock(&fs_info->balance_lock);
2294 fs_info->balance_ctl = bctl;
2295 spin_unlock(&fs_info->balance_lock);
2298 static void unset_balance_control(struct btrfs_fs_info *fs_info)
2300 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2302 BUG_ON(!fs_info->balance_ctl);
2304 spin_lock(&fs_info->balance_lock);
2305 fs_info->balance_ctl = NULL;
2306 spin_unlock(&fs_info->balance_lock);
2312 * Balance filters. Return 1 if chunk should be filtered out
2313 * (should not be balanced).
2315 static int chunk_profiles_filter(u64 chunk_type,
2316 struct btrfs_balance_args *bargs)
2318 chunk_type = chunk_to_extended(chunk_type) &
2319 BTRFS_EXTENDED_PROFILE_MASK;
2321 if (bargs->profiles & chunk_type)
2327 static u64 div_factor_fine(u64 num, int factor)
2339 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2340 struct btrfs_balance_args *bargs)
2342 struct btrfs_block_group_cache *cache;
2343 u64 chunk_used, user_thresh;
2346 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2347 chunk_used = btrfs_block_group_used(&cache->item);
2349 user_thresh = div_factor_fine(cache->key.offset, bargs->usage);
2350 if (chunk_used < user_thresh)
2353 btrfs_put_block_group(cache);
2357 static int chunk_devid_filter(struct extent_buffer *leaf,
2358 struct btrfs_chunk *chunk,
2359 struct btrfs_balance_args *bargs)
2361 struct btrfs_stripe *stripe;
2362 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2365 for (i = 0; i < num_stripes; i++) {
2366 stripe = btrfs_stripe_nr(chunk, i);
2367 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2374 /* [pstart, pend) */
2375 static int chunk_drange_filter(struct extent_buffer *leaf,
2376 struct btrfs_chunk *chunk,
2378 struct btrfs_balance_args *bargs)
2380 struct btrfs_stripe *stripe;
2381 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2387 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2390 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2391 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10))
2395 factor = num_stripes / factor;
2397 for (i = 0; i < num_stripes; i++) {
2398 stripe = btrfs_stripe_nr(chunk, i);
2399 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2402 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2403 stripe_length = btrfs_chunk_length(leaf, chunk);
2404 do_div(stripe_length, factor);
2406 if (stripe_offset < bargs->pend &&
2407 stripe_offset + stripe_length > bargs->pstart)
2414 /* [vstart, vend) */
2415 static int chunk_vrange_filter(struct extent_buffer *leaf,
2416 struct btrfs_chunk *chunk,
2418 struct btrfs_balance_args *bargs)
2420 if (chunk_offset < bargs->vend &&
2421 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2422 /* at least part of the chunk is inside this vrange */
2428 static int chunk_soft_convert_filter(u64 chunk_type,
2429 struct btrfs_balance_args *bargs)
2431 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2434 chunk_type = chunk_to_extended(chunk_type) &
2435 BTRFS_EXTENDED_PROFILE_MASK;
2437 if (bargs->target == chunk_type)
2443 static int should_balance_chunk(struct btrfs_root *root,
2444 struct extent_buffer *leaf,
2445 struct btrfs_chunk *chunk, u64 chunk_offset)
2447 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2448 struct btrfs_balance_args *bargs = NULL;
2449 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2452 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2453 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
2457 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
2458 bargs = &bctl->data;
2459 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
2461 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
2462 bargs = &bctl->meta;
2464 /* profiles filter */
2465 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
2466 chunk_profiles_filter(chunk_type, bargs)) {
2471 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
2472 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
2477 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
2478 chunk_devid_filter(leaf, chunk, bargs)) {
2482 /* drange filter, makes sense only with devid filter */
2483 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
2484 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
2489 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
2490 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
2494 /* soft profile changing mode */
2495 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
2496 chunk_soft_convert_filter(chunk_type, bargs)) {
2503 static u64 div_factor(u64 num, int factor)
2512 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
2514 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2515 struct btrfs_root *chunk_root = fs_info->chunk_root;
2516 struct btrfs_root *dev_root = fs_info->dev_root;
2517 struct list_head *devices;
2518 struct btrfs_device *device;
2521 struct btrfs_chunk *chunk;
2522 struct btrfs_path *path;
2523 struct btrfs_key key;
2524 struct btrfs_key found_key;
2525 struct btrfs_trans_handle *trans;
2526 struct extent_buffer *leaf;
2529 int enospc_errors = 0;
2530 bool counting = true;
2532 /* step one make some room on all the devices */
2533 devices = &fs_info->fs_devices->devices;
2534 list_for_each_entry(device, devices, dev_list) {
2535 old_size = device->total_bytes;
2536 size_to_free = div_factor(old_size, 1);
2537 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2538 if (!device->writeable ||
2539 device->total_bytes - device->bytes_used > size_to_free)
2542 ret = btrfs_shrink_device(device, old_size - size_to_free);
2547 trans = btrfs_start_transaction(dev_root, 0);
2548 BUG_ON(IS_ERR(trans));
2550 ret = btrfs_grow_device(trans, device, old_size);
2553 btrfs_end_transaction(trans, dev_root);
2556 /* step two, relocate all the chunks */
2557 path = btrfs_alloc_path();
2563 /* zero out stat counters */
2564 spin_lock(&fs_info->balance_lock);
2565 memset(&bctl->stat, 0, sizeof(bctl->stat));
2566 spin_unlock(&fs_info->balance_lock);
2568 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2569 key.offset = (u64)-1;
2570 key.type = BTRFS_CHUNK_ITEM_KEY;
2573 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
2574 atomic_read(&fs_info->balance_cancel_req)) {
2579 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2584 * this shouldn't happen, it means the last relocate
2588 BUG(); /* FIXME break ? */
2590 ret = btrfs_previous_item(chunk_root, path, 0,
2591 BTRFS_CHUNK_ITEM_KEY);
2597 leaf = path->nodes[0];
2598 slot = path->slots[0];
2599 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2601 if (found_key.objectid != key.objectid)
2604 /* chunk zero is special */
2605 if (found_key.offset == 0)
2608 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2611 spin_lock(&fs_info->balance_lock);
2612 bctl->stat.considered++;
2613 spin_unlock(&fs_info->balance_lock);
2616 ret = should_balance_chunk(chunk_root, leaf, chunk,
2618 btrfs_release_path(path);
2623 spin_lock(&fs_info->balance_lock);
2624 bctl->stat.expected++;
2625 spin_unlock(&fs_info->balance_lock);
2629 ret = btrfs_relocate_chunk(chunk_root,
2630 chunk_root->root_key.objectid,
2633 if (ret && ret != -ENOSPC)
2635 if (ret == -ENOSPC) {
2638 spin_lock(&fs_info->balance_lock);
2639 bctl->stat.completed++;
2640 spin_unlock(&fs_info->balance_lock);
2643 key.offset = found_key.offset - 1;
2647 btrfs_release_path(path);
2652 btrfs_free_path(path);
2653 if (enospc_errors) {
2654 printk(KERN_INFO "btrfs: %d enospc errors during balance\n",
2664 * alloc_profile_is_valid - see if a given profile is valid and reduced
2665 * @flags: profile to validate
2666 * @extended: if true @flags is treated as an extended profile
2668 static int alloc_profile_is_valid(u64 flags, int extended)
2670 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
2671 BTRFS_BLOCK_GROUP_PROFILE_MASK);
2673 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
2675 /* 1) check that all other bits are zeroed */
2679 /* 2) see if profile is reduced */
2681 return !extended; /* "0" is valid for usual profiles */
2683 /* true if exactly one bit set */
2684 return (flags & (flags - 1)) == 0;
2687 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
2689 /* cancel requested || normal exit path */
2690 return atomic_read(&fs_info->balance_cancel_req) ||
2691 (atomic_read(&fs_info->balance_pause_req) == 0 &&
2692 atomic_read(&fs_info->balance_cancel_req) == 0);
2695 static void __cancel_balance(struct btrfs_fs_info *fs_info)
2699 unset_balance_control(fs_info);
2700 ret = del_balance_item(fs_info->tree_root);
2704 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
2705 struct btrfs_ioctl_balance_args *bargs);
2708 * Should be called with both balance and volume mutexes held
2710 int btrfs_balance(struct btrfs_balance_control *bctl,
2711 struct btrfs_ioctl_balance_args *bargs)
2713 struct btrfs_fs_info *fs_info = bctl->fs_info;
2718 if (btrfs_fs_closing(fs_info) ||
2719 atomic_read(&fs_info->balance_pause_req) ||
2720 atomic_read(&fs_info->balance_cancel_req)) {
2725 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
2726 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
2730 * In case of mixed groups both data and meta should be picked,
2731 * and identical options should be given for both of them.
2733 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
2734 if (mixed && (bctl->flags & allowed)) {
2735 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
2736 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
2737 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
2738 printk(KERN_ERR "btrfs: with mixed groups data and "
2739 "metadata balance options must be the same\n");
2745 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2746 if (fs_info->fs_devices->num_devices == 1)
2747 allowed |= BTRFS_BLOCK_GROUP_DUP;
2748 else if (fs_info->fs_devices->num_devices < 4)
2749 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
2751 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2752 BTRFS_BLOCK_GROUP_RAID10);
2754 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2755 (!alloc_profile_is_valid(bctl->data.target, 1) ||
2756 (bctl->data.target & ~allowed))) {
2757 printk(KERN_ERR "btrfs: unable to start balance with target "
2758 "data profile %llu\n",
2759 (unsigned long long)bctl->data.target);
2763 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2764 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
2765 (bctl->meta.target & ~allowed))) {
2766 printk(KERN_ERR "btrfs: unable to start balance with target "
2767 "metadata profile %llu\n",
2768 (unsigned long long)bctl->meta.target);
2772 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2773 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
2774 (bctl->sys.target & ~allowed))) {
2775 printk(KERN_ERR "btrfs: unable to start balance with target "
2776 "system profile %llu\n",
2777 (unsigned long long)bctl->sys.target);
2782 /* allow dup'ed data chunks only in mixed mode */
2783 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2784 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
2785 printk(KERN_ERR "btrfs: dup for data is not allowed\n");
2790 /* allow to reduce meta or sys integrity only if force set */
2791 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
2792 BTRFS_BLOCK_GROUP_RAID10;
2793 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2794 (fs_info->avail_system_alloc_bits & allowed) &&
2795 !(bctl->sys.target & allowed)) ||
2796 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2797 (fs_info->avail_metadata_alloc_bits & allowed) &&
2798 !(bctl->meta.target & allowed))) {
2799 if (bctl->flags & BTRFS_BALANCE_FORCE) {
2800 printk(KERN_INFO "btrfs: force reducing metadata "
2803 printk(KERN_ERR "btrfs: balance will reduce metadata "
2804 "integrity, use force if you want this\n");
2810 ret = insert_balance_item(fs_info->tree_root, bctl);
2811 if (ret && ret != -EEXIST)
2814 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
2815 BUG_ON(ret == -EEXIST);
2816 set_balance_control(bctl);
2818 BUG_ON(ret != -EEXIST);
2819 spin_lock(&fs_info->balance_lock);
2820 update_balance_args(bctl);
2821 spin_unlock(&fs_info->balance_lock);
2824 atomic_inc(&fs_info->balance_running);
2825 mutex_unlock(&fs_info->balance_mutex);
2827 ret = __btrfs_balance(fs_info);
2829 mutex_lock(&fs_info->balance_mutex);
2830 atomic_dec(&fs_info->balance_running);
2833 memset(bargs, 0, sizeof(*bargs));
2834 update_ioctl_balance_args(fs_info, 0, bargs);
2837 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
2838 balance_need_close(fs_info)) {
2839 __cancel_balance(fs_info);
2842 wake_up(&fs_info->balance_wait_q);
2846 if (bctl->flags & BTRFS_BALANCE_RESUME)
2847 __cancel_balance(fs_info);
2853 static int balance_kthread(void *data)
2855 struct btrfs_fs_info *fs_info = data;
2858 mutex_lock(&fs_info->volume_mutex);
2859 mutex_lock(&fs_info->balance_mutex);
2861 if (fs_info->balance_ctl) {
2862 printk(KERN_INFO "btrfs: continuing balance\n");
2863 ret = btrfs_balance(fs_info->balance_ctl, NULL);
2866 mutex_unlock(&fs_info->balance_mutex);
2867 mutex_unlock(&fs_info->volume_mutex);
2872 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
2874 struct task_struct *tsk;
2876 spin_lock(&fs_info->balance_lock);
2877 if (!fs_info->balance_ctl) {
2878 spin_unlock(&fs_info->balance_lock);
2881 spin_unlock(&fs_info->balance_lock);
2883 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
2884 printk(KERN_INFO "btrfs: force skipping balance\n");
2888 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
2890 return PTR_ERR(tsk);
2895 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
2897 struct btrfs_balance_control *bctl;
2898 struct btrfs_balance_item *item;
2899 struct btrfs_disk_balance_args disk_bargs;
2900 struct btrfs_path *path;
2901 struct extent_buffer *leaf;
2902 struct btrfs_key key;
2905 path = btrfs_alloc_path();
2909 key.objectid = BTRFS_BALANCE_OBJECTID;
2910 key.type = BTRFS_BALANCE_ITEM_KEY;
2913 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2916 if (ret > 0) { /* ret = -ENOENT; */
2921 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
2927 leaf = path->nodes[0];
2928 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2930 bctl->fs_info = fs_info;
2931 bctl->flags = btrfs_balance_flags(leaf, item);
2932 bctl->flags |= BTRFS_BALANCE_RESUME;
2934 btrfs_balance_data(leaf, item, &disk_bargs);
2935 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
2936 btrfs_balance_meta(leaf, item, &disk_bargs);
2937 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
2938 btrfs_balance_sys(leaf, item, &disk_bargs);
2939 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
2941 mutex_lock(&fs_info->volume_mutex);
2942 mutex_lock(&fs_info->balance_mutex);
2944 set_balance_control(bctl);
2946 mutex_unlock(&fs_info->balance_mutex);
2947 mutex_unlock(&fs_info->volume_mutex);
2949 btrfs_free_path(path);
2953 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
2957 mutex_lock(&fs_info->balance_mutex);
2958 if (!fs_info->balance_ctl) {
2959 mutex_unlock(&fs_info->balance_mutex);
2963 if (atomic_read(&fs_info->balance_running)) {
2964 atomic_inc(&fs_info->balance_pause_req);
2965 mutex_unlock(&fs_info->balance_mutex);
2967 wait_event(fs_info->balance_wait_q,
2968 atomic_read(&fs_info->balance_running) == 0);
2970 mutex_lock(&fs_info->balance_mutex);
2971 /* we are good with balance_ctl ripped off from under us */
2972 BUG_ON(atomic_read(&fs_info->balance_running));
2973 atomic_dec(&fs_info->balance_pause_req);
2978 mutex_unlock(&fs_info->balance_mutex);
2982 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
2984 mutex_lock(&fs_info->balance_mutex);
2985 if (!fs_info->balance_ctl) {
2986 mutex_unlock(&fs_info->balance_mutex);
2990 atomic_inc(&fs_info->balance_cancel_req);
2992 * if we are running just wait and return, balance item is
2993 * deleted in btrfs_balance in this case
2995 if (atomic_read(&fs_info->balance_running)) {
2996 mutex_unlock(&fs_info->balance_mutex);
2997 wait_event(fs_info->balance_wait_q,
2998 atomic_read(&fs_info->balance_running) == 0);
2999 mutex_lock(&fs_info->balance_mutex);
3001 /* __cancel_balance needs volume_mutex */
3002 mutex_unlock(&fs_info->balance_mutex);
3003 mutex_lock(&fs_info->volume_mutex);
3004 mutex_lock(&fs_info->balance_mutex);
3006 if (fs_info->balance_ctl)
3007 __cancel_balance(fs_info);
3009 mutex_unlock(&fs_info->volume_mutex);
3012 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3013 atomic_dec(&fs_info->balance_cancel_req);
3014 mutex_unlock(&fs_info->balance_mutex);
3019 * shrinking a device means finding all of the device extents past
3020 * the new size, and then following the back refs to the chunks.
3021 * The chunk relocation code actually frees the device extent
3023 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3025 struct btrfs_trans_handle *trans;
3026 struct btrfs_root *root = device->dev_root;
3027 struct btrfs_dev_extent *dev_extent = NULL;
3028 struct btrfs_path *path;
3036 bool retried = false;
3037 struct extent_buffer *l;
3038 struct btrfs_key key;
3039 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3040 u64 old_total = btrfs_super_total_bytes(super_copy);
3041 u64 old_size = device->total_bytes;
3042 u64 diff = device->total_bytes - new_size;
3044 if (new_size >= device->total_bytes)
3047 path = btrfs_alloc_path();
3055 device->total_bytes = new_size;
3056 if (device->writeable) {
3057 device->fs_devices->total_rw_bytes -= diff;
3058 spin_lock(&root->fs_info->free_chunk_lock);
3059 root->fs_info->free_chunk_space -= diff;
3060 spin_unlock(&root->fs_info->free_chunk_lock);
3062 unlock_chunks(root);
3065 key.objectid = device->devid;
3066 key.offset = (u64)-1;
3067 key.type = BTRFS_DEV_EXTENT_KEY;
3070 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3074 ret = btrfs_previous_item(root, path, 0, key.type);
3079 btrfs_release_path(path);
3084 slot = path->slots[0];
3085 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3087 if (key.objectid != device->devid) {
3088 btrfs_release_path(path);
3092 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3093 length = btrfs_dev_extent_length(l, dev_extent);
3095 if (key.offset + length <= new_size) {
3096 btrfs_release_path(path);
3100 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3101 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3102 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3103 btrfs_release_path(path);
3105 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3107 if (ret && ret != -ENOSPC)
3111 } while (key.offset-- > 0);
3113 if (failed && !retried) {
3117 } else if (failed && retried) {
3121 device->total_bytes = old_size;
3122 if (device->writeable)
3123 device->fs_devices->total_rw_bytes += diff;
3124 spin_lock(&root->fs_info->free_chunk_lock);
3125 root->fs_info->free_chunk_space += diff;
3126 spin_unlock(&root->fs_info->free_chunk_lock);
3127 unlock_chunks(root);
3131 /* Shrinking succeeded, else we would be at "done". */
3132 trans = btrfs_start_transaction(root, 0);
3133 if (IS_ERR(trans)) {
3134 ret = PTR_ERR(trans);
3140 device->disk_total_bytes = new_size;
3141 /* Now btrfs_update_device() will change the on-disk size. */
3142 ret = btrfs_update_device(trans, device);
3144 unlock_chunks(root);
3145 btrfs_end_transaction(trans, root);
3148 WARN_ON(diff > old_total);
3149 btrfs_set_super_total_bytes(super_copy, old_total - diff);
3150 unlock_chunks(root);
3151 btrfs_end_transaction(trans, root);
3153 btrfs_free_path(path);
3157 static int btrfs_add_system_chunk(struct btrfs_root *root,
3158 struct btrfs_key *key,
3159 struct btrfs_chunk *chunk, int item_size)
3161 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3162 struct btrfs_disk_key disk_key;
3166 array_size = btrfs_super_sys_array_size(super_copy);
3167 if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
3170 ptr = super_copy->sys_chunk_array + array_size;
3171 btrfs_cpu_key_to_disk(&disk_key, key);
3172 memcpy(ptr, &disk_key, sizeof(disk_key));
3173 ptr += sizeof(disk_key);
3174 memcpy(ptr, chunk, item_size);
3175 item_size += sizeof(disk_key);
3176 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
3181 * sort the devices in descending order by max_avail, total_avail
3183 static int btrfs_cmp_device_info(const void *a, const void *b)
3185 const struct btrfs_device_info *di_a = a;
3186 const struct btrfs_device_info *di_b = b;
3188 if (di_a->max_avail > di_b->max_avail)
3190 if (di_a->max_avail < di_b->max_avail)
3192 if (di_a->total_avail > di_b->total_avail)
3194 if (di_a->total_avail < di_b->total_avail)
3199 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3200 struct btrfs_root *extent_root,
3201 struct map_lookup **map_ret,
3202 u64 *num_bytes_out, u64 *stripe_size_out,
3203 u64 start, u64 type)
3205 struct btrfs_fs_info *info = extent_root->fs_info;
3206 struct btrfs_fs_devices *fs_devices = info->fs_devices;
3207 struct list_head *cur;
3208 struct map_lookup *map = NULL;
3209 struct extent_map_tree *em_tree;
3210 struct extent_map *em;
3211 struct btrfs_device_info *devices_info = NULL;
3213 int num_stripes; /* total number of stripes to allocate */
3214 int sub_stripes; /* sub_stripes info for map */
3215 int dev_stripes; /* stripes per dev */
3216 int devs_max; /* max devs to use */
3217 int devs_min; /* min devs needed */
3218 int devs_increment; /* ndevs has to be a multiple of this */
3219 int ncopies; /* how many copies to data has */
3221 u64 max_stripe_size;
3229 BUG_ON(!alloc_profile_is_valid(type, 0));
3231 if (list_empty(&fs_devices->alloc_list))
3238 devs_max = 0; /* 0 == as many as possible */
3242 * define the properties of each RAID type.
3243 * FIXME: move this to a global table and use it in all RAID
3246 if (type & (BTRFS_BLOCK_GROUP_DUP)) {
3250 } else if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
3252 } else if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
3257 } else if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
3266 if (type & BTRFS_BLOCK_GROUP_DATA) {
3267 max_stripe_size = 1024 * 1024 * 1024;
3268 max_chunk_size = 10 * max_stripe_size;
3269 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
3270 /* for larger filesystems, use larger metadata chunks */
3271 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
3272 max_stripe_size = 1024 * 1024 * 1024;
3274 max_stripe_size = 256 * 1024 * 1024;
3275 max_chunk_size = max_stripe_size;
3276 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
3277 max_stripe_size = 32 * 1024 * 1024;
3278 max_chunk_size = 2 * max_stripe_size;
3280 printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
3285 /* we don't want a chunk larger than 10% of writeable space */
3286 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
3289 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
3294 cur = fs_devices->alloc_list.next;
3297 * in the first pass through the devices list, we gather information
3298 * about the available holes on each device.
3301 while (cur != &fs_devices->alloc_list) {
3302 struct btrfs_device *device;
3306 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
3310 if (!device->writeable) {
3312 "btrfs: read-only device in alloc_list\n");
3317 if (!device->in_fs_metadata)
3320 if (device->total_bytes > device->bytes_used)
3321 total_avail = device->total_bytes - device->bytes_used;
3325 /* If there is no space on this device, skip it. */
3326 if (total_avail == 0)
3329 ret = find_free_dev_extent(device,
3330 max_stripe_size * dev_stripes,
3331 &dev_offset, &max_avail);
3332 if (ret && ret != -ENOSPC)
3336 max_avail = max_stripe_size * dev_stripes;
3338 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
3341 devices_info[ndevs].dev_offset = dev_offset;
3342 devices_info[ndevs].max_avail = max_avail;
3343 devices_info[ndevs].total_avail = total_avail;
3344 devices_info[ndevs].dev = device;
3349 * now sort the devices by hole size / available space
3351 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
3352 btrfs_cmp_device_info, NULL);
3354 /* round down to number of usable stripes */
3355 ndevs -= ndevs % devs_increment;
3357 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
3362 if (devs_max && ndevs > devs_max)
3365 * the primary goal is to maximize the number of stripes, so use as many
3366 * devices as possible, even if the stripes are not maximum sized.
3368 stripe_size = devices_info[ndevs-1].max_avail;
3369 num_stripes = ndevs * dev_stripes;
3371 if (stripe_size * ndevs > max_chunk_size * ncopies) {
3372 stripe_size = max_chunk_size * ncopies;
3373 do_div(stripe_size, ndevs);
3376 do_div(stripe_size, dev_stripes);
3378 /* align to BTRFS_STRIPE_LEN */
3379 do_div(stripe_size, BTRFS_STRIPE_LEN);
3380 stripe_size *= BTRFS_STRIPE_LEN;
3382 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
3387 map->num_stripes = num_stripes;
3389 for (i = 0; i < ndevs; ++i) {
3390 for (j = 0; j < dev_stripes; ++j) {
3391 int s = i * dev_stripes + j;
3392 map->stripes[s].dev = devices_info[i].dev;
3393 map->stripes[s].physical = devices_info[i].dev_offset +
3397 map->sector_size = extent_root->sectorsize;
3398 map->stripe_len = BTRFS_STRIPE_LEN;
3399 map->io_align = BTRFS_STRIPE_LEN;
3400 map->io_width = BTRFS_STRIPE_LEN;
3402 map->sub_stripes = sub_stripes;
3405 num_bytes = stripe_size * (num_stripes / ncopies);
3407 *stripe_size_out = stripe_size;
3408 *num_bytes_out = num_bytes;
3410 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
3412 em = alloc_extent_map();
3417 em->bdev = (struct block_device *)map;
3419 em->len = num_bytes;
3420 em->block_start = 0;
3421 em->block_len = em->len;
3423 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
3424 write_lock(&em_tree->lock);
3425 ret = add_extent_mapping(em_tree, em);
3426 write_unlock(&em_tree->lock);
3427 free_extent_map(em);
3431 ret = btrfs_make_block_group(trans, extent_root, 0, type,
3432 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3437 for (i = 0; i < map->num_stripes; ++i) {
3438 struct btrfs_device *device;
3441 device = map->stripes[i].dev;
3442 dev_offset = map->stripes[i].physical;
3444 ret = btrfs_alloc_dev_extent(trans, device,
3445 info->chunk_root->root_key.objectid,
3446 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3447 start, dev_offset, stripe_size);
3449 btrfs_abort_transaction(trans, extent_root, ret);
3454 kfree(devices_info);
3459 kfree(devices_info);
3463 static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
3464 struct btrfs_root *extent_root,
3465 struct map_lookup *map, u64 chunk_offset,
3466 u64 chunk_size, u64 stripe_size)
3469 struct btrfs_key key;
3470 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3471 struct btrfs_device *device;
3472 struct btrfs_chunk *chunk;
3473 struct btrfs_stripe *stripe;
3474 size_t item_size = btrfs_chunk_item_size(map->num_stripes);
3478 chunk = kzalloc(item_size, GFP_NOFS);
3483 while (index < map->num_stripes) {
3484 device = map->stripes[index].dev;
3485 device->bytes_used += stripe_size;
3486 ret = btrfs_update_device(trans, device);
3492 spin_lock(&extent_root->fs_info->free_chunk_lock);
3493 extent_root->fs_info->free_chunk_space -= (stripe_size *
3495 spin_unlock(&extent_root->fs_info->free_chunk_lock);
3498 stripe = &chunk->stripe;
3499 while (index < map->num_stripes) {
3500 device = map->stripes[index].dev;
3501 dev_offset = map->stripes[index].physical;
3503 btrfs_set_stack_stripe_devid(stripe, device->devid);
3504 btrfs_set_stack_stripe_offset(stripe, dev_offset);
3505 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
3510 btrfs_set_stack_chunk_length(chunk, chunk_size);
3511 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
3512 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
3513 btrfs_set_stack_chunk_type(chunk, map->type);
3514 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
3515 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
3516 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
3517 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
3518 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
3520 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3521 key.type = BTRFS_CHUNK_ITEM_KEY;
3522 key.offset = chunk_offset;
3524 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
3526 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3528 * TODO: Cleanup of inserted chunk root in case of
3531 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
3541 * Chunk allocation falls into two parts. The first part does works
3542 * that make the new allocated chunk useable, but not do any operation
3543 * that modifies the chunk tree. The second part does the works that
3544 * require modifying the chunk tree. This division is important for the
3545 * bootstrap process of adding storage to a seed btrfs.
3547 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3548 struct btrfs_root *extent_root, u64 type)
3553 struct map_lookup *map;
3554 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3557 ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3562 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3563 &stripe_size, chunk_offset, type);
3567 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3568 chunk_size, stripe_size);
3574 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
3575 struct btrfs_root *root,
3576 struct btrfs_device *device)
3579 u64 sys_chunk_offset;
3583 u64 sys_stripe_size;
3585 struct map_lookup *map;
3586 struct map_lookup *sys_map;
3587 struct btrfs_fs_info *fs_info = root->fs_info;
3588 struct btrfs_root *extent_root = fs_info->extent_root;
3591 ret = find_next_chunk(fs_info->chunk_root,
3592 BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
3596 alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
3597 fs_info->avail_metadata_alloc_bits;
3598 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3600 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3601 &stripe_size, chunk_offset, alloc_profile);
3605 sys_chunk_offset = chunk_offset + chunk_size;
3607 alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
3608 fs_info->avail_system_alloc_bits;
3609 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3611 ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
3612 &sys_chunk_size, &sys_stripe_size,
3613 sys_chunk_offset, alloc_profile);
3617 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
3622 * Modifying chunk tree needs allocating new blocks from both
3623 * system block group and metadata block group. So we only can
3624 * do operations require modifying the chunk tree after both
3625 * block groups were created.
3627 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3628 chunk_size, stripe_size);
3632 ret = __finish_chunk_alloc(trans, extent_root, sys_map,
3633 sys_chunk_offset, sys_chunk_size,
3641 btrfs_abort_transaction(trans, root, ret);
3645 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
3647 struct extent_map *em;
3648 struct map_lookup *map;
3649 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
3653 read_lock(&map_tree->map_tree.lock);
3654 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
3655 read_unlock(&map_tree->map_tree.lock);
3659 if (btrfs_test_opt(root, DEGRADED)) {
3660 free_extent_map(em);
3664 map = (struct map_lookup *)em->bdev;
3665 for (i = 0; i < map->num_stripes; i++) {
3666 if (!map->stripes[i].dev->writeable) {
3671 free_extent_map(em);
3675 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
3677 extent_map_tree_init(&tree->map_tree);
3680 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
3682 struct extent_map *em;
3685 write_lock(&tree->map_tree.lock);
3686 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
3688 remove_extent_mapping(&tree->map_tree, em);
3689 write_unlock(&tree->map_tree.lock);
3694 free_extent_map(em);
3695 /* once for the tree */
3696 free_extent_map(em);
3700 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
3702 struct extent_map *em;
3703 struct map_lookup *map;
3704 struct extent_map_tree *em_tree = &map_tree->map_tree;
3707 read_lock(&em_tree->lock);
3708 em = lookup_extent_mapping(em_tree, logical, len);
3709 read_unlock(&em_tree->lock);
3712 BUG_ON(em->start > logical || em->start + em->len < logical);
3713 map = (struct map_lookup *)em->bdev;
3714 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
3715 ret = map->num_stripes;
3716 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3717 ret = map->sub_stripes;
3720 free_extent_map(em);
3724 static int find_live_mirror(struct map_lookup *map, int first, int num,
3728 if (map->stripes[optimal].dev->bdev)
3730 for (i = first; i < first + num; i++) {
3731 if (map->stripes[i].dev->bdev)
3734 /* we couldn't find one that doesn't fail. Just return something
3735 * and the io error handling code will clean up eventually
3740 static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3741 u64 logical, u64 *length,
3742 struct btrfs_bio **bbio_ret,
3745 struct extent_map *em;
3746 struct map_lookup *map;
3747 struct extent_map_tree *em_tree = &map_tree->map_tree;
3750 u64 stripe_end_offset;
3759 struct btrfs_bio *bbio = NULL;
3761 read_lock(&em_tree->lock);
3762 em = lookup_extent_mapping(em_tree, logical, *length);
3763 read_unlock(&em_tree->lock);
3766 printk(KERN_CRIT "unable to find logical %llu len %llu\n",
3767 (unsigned long long)logical,
3768 (unsigned long long)*length);
3772 BUG_ON(em->start > logical || em->start + em->len < logical);
3773 map = (struct map_lookup *)em->bdev;
3774 offset = logical - em->start;
3776 if (mirror_num > map->num_stripes)
3781 * stripe_nr counts the total number of stripes we have to stride
3782 * to get to this block
3784 do_div(stripe_nr, map->stripe_len);
3786 stripe_offset = stripe_nr * map->stripe_len;
3787 BUG_ON(offset < stripe_offset);
3789 /* stripe_offset is the offset of this block in its stripe*/
3790 stripe_offset = offset - stripe_offset;
3792 if (rw & REQ_DISCARD)
3793 *length = min_t(u64, em->len - offset, *length);
3794 else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3795 /* we limit the length of each bio to what fits in a stripe */
3796 *length = min_t(u64, em->len - offset,
3797 map->stripe_len - stripe_offset);
3799 *length = em->len - offset;
3807 stripe_nr_orig = stripe_nr;
3808 stripe_nr_end = (offset + *length + map->stripe_len - 1) &
3809 (~(map->stripe_len - 1));
3810 do_div(stripe_nr_end, map->stripe_len);
3811 stripe_end_offset = stripe_nr_end * map->stripe_len -
3813 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3814 if (rw & REQ_DISCARD)
3815 num_stripes = min_t(u64, map->num_stripes,
3816 stripe_nr_end - stripe_nr_orig);
3817 stripe_index = do_div(stripe_nr, map->num_stripes);
3818 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
3819 if (rw & (REQ_WRITE | REQ_DISCARD))
3820 num_stripes = map->num_stripes;
3821 else if (mirror_num)
3822 stripe_index = mirror_num - 1;
3824 stripe_index = find_live_mirror(map, 0,
3826 current->pid % map->num_stripes);
3827 mirror_num = stripe_index + 1;
3830 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
3831 if (rw & (REQ_WRITE | REQ_DISCARD)) {
3832 num_stripes = map->num_stripes;
3833 } else if (mirror_num) {
3834 stripe_index = mirror_num - 1;
3839 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3840 int factor = map->num_stripes / map->sub_stripes;
3842 stripe_index = do_div(stripe_nr, factor);
3843 stripe_index *= map->sub_stripes;
3846 num_stripes = map->sub_stripes;
3847 else if (rw & REQ_DISCARD)
3848 num_stripes = min_t(u64, map->sub_stripes *
3849 (stripe_nr_end - stripe_nr_orig),
3851 else if (mirror_num)
3852 stripe_index += mirror_num - 1;
3854 int old_stripe_index = stripe_index;
3855 stripe_index = find_live_mirror(map, stripe_index,
3856 map->sub_stripes, stripe_index +
3857 current->pid % map->sub_stripes);
3858 mirror_num = stripe_index - old_stripe_index + 1;
3862 * after this do_div call, stripe_nr is the number of stripes
3863 * on this device we have to walk to find the data, and
3864 * stripe_index is the number of our device in the stripe array
3866 stripe_index = do_div(stripe_nr, map->num_stripes);
3867 mirror_num = stripe_index + 1;
3869 BUG_ON(stripe_index >= map->num_stripes);
3871 bbio = kzalloc(btrfs_bio_size(num_stripes), GFP_NOFS);
3876 atomic_set(&bbio->error, 0);
3878 if (rw & REQ_DISCARD) {
3880 int sub_stripes = 0;
3881 u64 stripes_per_dev = 0;
3882 u32 remaining_stripes = 0;
3883 u32 last_stripe = 0;
3886 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
3887 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3890 sub_stripes = map->sub_stripes;
3892 factor = map->num_stripes / sub_stripes;
3893 stripes_per_dev = div_u64_rem(stripe_nr_end -
3896 &remaining_stripes);
3897 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
3898 last_stripe *= sub_stripes;
3901 for (i = 0; i < num_stripes; i++) {
3902 bbio->stripes[i].physical =
3903 map->stripes[stripe_index].physical +
3904 stripe_offset + stripe_nr * map->stripe_len;
3905 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
3907 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
3908 BTRFS_BLOCK_GROUP_RAID10)) {
3909 bbio->stripes[i].length = stripes_per_dev *
3912 if (i / sub_stripes < remaining_stripes)
3913 bbio->stripes[i].length +=
3917 * Special for the first stripe and
3920 * |-------|...|-------|
3924 if (i < sub_stripes)
3925 bbio->stripes[i].length -=
3928 if (stripe_index >= last_stripe &&
3929 stripe_index <= (last_stripe +
3931 bbio->stripes[i].length -=
3934 if (i == sub_stripes - 1)
3937 bbio->stripes[i].length = *length;
3940 if (stripe_index == map->num_stripes) {
3941 /* This could only happen for RAID0/10 */
3947 for (i = 0; i < num_stripes; i++) {
3948 bbio->stripes[i].physical =
3949 map->stripes[stripe_index].physical +
3951 stripe_nr * map->stripe_len;
3952 bbio->stripes[i].dev =
3953 map->stripes[stripe_index].dev;
3958 if (rw & REQ_WRITE) {
3959 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
3960 BTRFS_BLOCK_GROUP_RAID10 |
3961 BTRFS_BLOCK_GROUP_DUP)) {
3967 bbio->num_stripes = num_stripes;
3968 bbio->max_errors = max_errors;
3969 bbio->mirror_num = mirror_num;
3971 free_extent_map(em);
3975 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3976 u64 logical, u64 *length,
3977 struct btrfs_bio **bbio_ret, int mirror_num)
3979 return __btrfs_map_block(map_tree, rw, logical, length, bbio_ret,
3983 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
3984 u64 chunk_start, u64 physical, u64 devid,
3985 u64 **logical, int *naddrs, int *stripe_len)
3987 struct extent_map_tree *em_tree = &map_tree->map_tree;
3988 struct extent_map *em;
3989 struct map_lookup *map;
3996 read_lock(&em_tree->lock);
3997 em = lookup_extent_mapping(em_tree, chunk_start, 1);
3998 read_unlock(&em_tree->lock);
4000 BUG_ON(!em || em->start != chunk_start);
4001 map = (struct map_lookup *)em->bdev;
4004 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4005 do_div(length, map->num_stripes / map->sub_stripes);
4006 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
4007 do_div(length, map->num_stripes);
4009 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
4010 BUG_ON(!buf); /* -ENOMEM */
4012 for (i = 0; i < map->num_stripes; i++) {
4013 if (devid && map->stripes[i].dev->devid != devid)
4015 if (map->stripes[i].physical > physical ||
4016 map->stripes[i].physical + length <= physical)
4019 stripe_nr = physical - map->stripes[i].physical;
4020 do_div(stripe_nr, map->stripe_len);
4022 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
4023 stripe_nr = stripe_nr * map->num_stripes + i;
4024 do_div(stripe_nr, map->sub_stripes);
4025 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
4026 stripe_nr = stripe_nr * map->num_stripes + i;
4028 bytenr = chunk_start + stripe_nr * map->stripe_len;
4029 WARN_ON(nr >= map->num_stripes);
4030 for (j = 0; j < nr; j++) {
4031 if (buf[j] == bytenr)
4035 WARN_ON(nr >= map->num_stripes);
4042 *stripe_len = map->stripe_len;
4044 free_extent_map(em);
4048 static void *merge_stripe_index_into_bio_private(void *bi_private,
4049 unsigned int stripe_index)
4052 * with single, dup, RAID0, RAID1 and RAID10, stripe_index is
4054 * The alternative solution (instead of stealing bits from the
4055 * pointer) would be to allocate an intermediate structure
4056 * that contains the old private pointer plus the stripe_index.
4058 BUG_ON((((uintptr_t)bi_private) & 3) != 0);
4059 BUG_ON(stripe_index > 3);
4060 return (void *)(((uintptr_t)bi_private) | stripe_index);
4063 static struct btrfs_bio *extract_bbio_from_bio_private(void *bi_private)
4065 return (struct btrfs_bio *)(((uintptr_t)bi_private) & ~((uintptr_t)3));
4068 static unsigned int extract_stripe_index_from_bio_private(void *bi_private)
4070 return (unsigned int)((uintptr_t)bi_private) & 3;
4073 static void btrfs_end_bio(struct bio *bio, int err)
4075 struct btrfs_bio *bbio = extract_bbio_from_bio_private(bio->bi_private);
4076 int is_orig_bio = 0;
4079 atomic_inc(&bbio->error);
4080 if (err == -EIO || err == -EREMOTEIO) {
4081 unsigned int stripe_index =
4082 extract_stripe_index_from_bio_private(
4084 struct btrfs_device *dev;
4086 BUG_ON(stripe_index >= bbio->num_stripes);
4087 dev = bbio->stripes[stripe_index].dev;
4089 if (bio->bi_rw & WRITE)
4090 btrfs_dev_stat_inc(dev,
4091 BTRFS_DEV_STAT_WRITE_ERRS);
4093 btrfs_dev_stat_inc(dev,
4094 BTRFS_DEV_STAT_READ_ERRS);
4095 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
4096 btrfs_dev_stat_inc(dev,
4097 BTRFS_DEV_STAT_FLUSH_ERRS);
4098 btrfs_dev_stat_print_on_error(dev);
4103 if (bio == bbio->orig_bio)
4106 if (atomic_dec_and_test(&bbio->stripes_pending)) {
4109 bio = bbio->orig_bio;
4111 bio->bi_private = bbio->private;
4112 bio->bi_end_io = bbio->end_io;
4113 bio->bi_bdev = (struct block_device *)
4114 (unsigned long)bbio->mirror_num;
4115 /* only send an error to the higher layers if it is
4116 * beyond the tolerance of the multi-bio
4118 if (atomic_read(&bbio->error) > bbio->max_errors) {
4122 * this bio is actually up to date, we didn't
4123 * go over the max number of errors
4125 set_bit(BIO_UPTODATE, &bio->bi_flags);
4130 bio_endio(bio, err);
4131 } else if (!is_orig_bio) {
4136 struct async_sched {
4139 struct btrfs_fs_info *info;
4140 struct btrfs_work work;
4144 * see run_scheduled_bios for a description of why bios are collected for
4147 * This will add one bio to the pending list for a device and make sure
4148 * the work struct is scheduled.
4150 static noinline void schedule_bio(struct btrfs_root *root,
4151 struct btrfs_device *device,
4152 int rw, struct bio *bio)
4154 int should_queue = 1;
4155 struct btrfs_pending_bios *pending_bios;
4157 /* don't bother with additional async steps for reads, right now */
4158 if (!(rw & REQ_WRITE)) {
4160 btrfsic_submit_bio(rw, bio);
4166 * nr_async_bios allows us to reliably return congestion to the
4167 * higher layers. Otherwise, the async bio makes it appear we have
4168 * made progress against dirty pages when we've really just put it
4169 * on a queue for later
4171 atomic_inc(&root->fs_info->nr_async_bios);
4172 WARN_ON(bio->bi_next);
4173 bio->bi_next = NULL;
4176 spin_lock(&device->io_lock);
4177 if (bio->bi_rw & REQ_SYNC)
4178 pending_bios = &device->pending_sync_bios;
4180 pending_bios = &device->pending_bios;
4182 if (pending_bios->tail)
4183 pending_bios->tail->bi_next = bio;
4185 pending_bios->tail = bio;
4186 if (!pending_bios->head)
4187 pending_bios->head = bio;
4188 if (device->running_pending)
4191 spin_unlock(&device->io_lock);
4194 btrfs_queue_worker(&root->fs_info->submit_workers,
4198 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
4199 int mirror_num, int async_submit)
4201 struct btrfs_mapping_tree *map_tree;
4202 struct btrfs_device *dev;
4203 struct bio *first_bio = bio;
4204 u64 logical = (u64)bio->bi_sector << 9;
4210 struct btrfs_bio *bbio = NULL;
4212 length = bio->bi_size;
4213 map_tree = &root->fs_info->mapping_tree;
4214 map_length = length;
4216 ret = btrfs_map_block(map_tree, rw, logical, &map_length, &bbio,
4218 if (ret) /* -ENOMEM */
4221 total_devs = bbio->num_stripes;
4222 if (map_length < length) {
4223 printk(KERN_CRIT "mapping failed logical %llu bio len %llu "
4224 "len %llu\n", (unsigned long long)logical,
4225 (unsigned long long)length,
4226 (unsigned long long)map_length);
4230 bbio->orig_bio = first_bio;
4231 bbio->private = first_bio->bi_private;
4232 bbio->end_io = first_bio->bi_end_io;
4233 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
4235 while (dev_nr < total_devs) {
4236 if (dev_nr < total_devs - 1) {
4237 bio = bio_clone(first_bio, GFP_NOFS);
4238 BUG_ON(!bio); /* -ENOMEM */
4242 bio->bi_private = bbio;
4243 bio->bi_private = merge_stripe_index_into_bio_private(
4244 bio->bi_private, (unsigned int)dev_nr);
4245 bio->bi_end_io = btrfs_end_bio;
4246 bio->bi_sector = bbio->stripes[dev_nr].physical >> 9;
4247 dev = bbio->stripes[dev_nr].dev;
4248 if (dev && dev->bdev && (rw != WRITE || dev->writeable)) {
4250 struct rcu_string *name;
4253 name = rcu_dereference(dev->name);
4254 pr_debug("btrfs_map_bio: rw %d, secor=%llu, dev=%lu "
4255 "(%s id %llu), size=%u\n", rw,
4256 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
4257 name->str, dev->devid, bio->bi_size);
4260 bio->bi_bdev = dev->bdev;
4262 schedule_bio(root, dev, rw, bio);
4264 btrfsic_submit_bio(rw, bio);
4266 bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
4267 bio->bi_sector = logical >> 9;
4268 bio_endio(bio, -EIO);
4275 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
4278 struct btrfs_device *device;
4279 struct btrfs_fs_devices *cur_devices;
4281 cur_devices = root->fs_info->fs_devices;
4282 while (cur_devices) {
4284 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
4285 device = __find_device(&cur_devices->devices,
4290 cur_devices = cur_devices->seed;
4295 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
4296 u64 devid, u8 *dev_uuid)
4298 struct btrfs_device *device;
4299 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
4301 device = kzalloc(sizeof(*device), GFP_NOFS);
4304 list_add(&device->dev_list,
4305 &fs_devices->devices);
4306 device->dev_root = root->fs_info->dev_root;
4307 device->devid = devid;
4308 device->work.func = pending_bios_fn;
4309 device->fs_devices = fs_devices;
4310 device->missing = 1;
4311 fs_devices->num_devices++;
4312 fs_devices->missing_devices++;
4313 spin_lock_init(&device->io_lock);
4314 INIT_LIST_HEAD(&device->dev_alloc_list);
4315 memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
4319 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
4320 struct extent_buffer *leaf,
4321 struct btrfs_chunk *chunk)
4323 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4324 struct map_lookup *map;
4325 struct extent_map *em;
4329 u8 uuid[BTRFS_UUID_SIZE];
4334 logical = key->offset;
4335 length = btrfs_chunk_length(leaf, chunk);
4337 read_lock(&map_tree->map_tree.lock);
4338 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
4339 read_unlock(&map_tree->map_tree.lock);
4341 /* already mapped? */
4342 if (em && em->start <= logical && em->start + em->len > logical) {
4343 free_extent_map(em);
4346 free_extent_map(em);
4349 em = alloc_extent_map();
4352 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4353 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4355 free_extent_map(em);
4359 em->bdev = (struct block_device *)map;
4360 em->start = logical;
4362 em->block_start = 0;
4363 em->block_len = em->len;
4365 map->num_stripes = num_stripes;
4366 map->io_width = btrfs_chunk_io_width(leaf, chunk);
4367 map->io_align = btrfs_chunk_io_align(leaf, chunk);
4368 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
4369 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
4370 map->type = btrfs_chunk_type(leaf, chunk);
4371 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
4372 for (i = 0; i < num_stripes; i++) {
4373 map->stripes[i].physical =
4374 btrfs_stripe_offset_nr(leaf, chunk, i);
4375 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
4376 read_extent_buffer(leaf, uuid, (unsigned long)
4377 btrfs_stripe_dev_uuid_nr(chunk, i),
4379 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
4381 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
4383 free_extent_map(em);
4386 if (!map->stripes[i].dev) {
4387 map->stripes[i].dev =
4388 add_missing_dev(root, devid, uuid);
4389 if (!map->stripes[i].dev) {
4391 free_extent_map(em);
4395 map->stripes[i].dev->in_fs_metadata = 1;
4398 write_lock(&map_tree->map_tree.lock);
4399 ret = add_extent_mapping(&map_tree->map_tree, em);
4400 write_unlock(&map_tree->map_tree.lock);
4401 BUG_ON(ret); /* Tree corruption */
4402 free_extent_map(em);
4407 static void fill_device_from_item(struct extent_buffer *leaf,
4408 struct btrfs_dev_item *dev_item,
4409 struct btrfs_device *device)
4413 device->devid = btrfs_device_id(leaf, dev_item);
4414 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
4415 device->total_bytes = device->disk_total_bytes;
4416 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
4417 device->type = btrfs_device_type(leaf, dev_item);
4418 device->io_align = btrfs_device_io_align(leaf, dev_item);
4419 device->io_width = btrfs_device_io_width(leaf, dev_item);
4420 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
4422 ptr = (unsigned long)btrfs_device_uuid(dev_item);
4423 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
4426 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
4428 struct btrfs_fs_devices *fs_devices;
4431 BUG_ON(!mutex_is_locked(&uuid_mutex));
4433 fs_devices = root->fs_info->fs_devices->seed;
4434 while (fs_devices) {
4435 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
4439 fs_devices = fs_devices->seed;
4442 fs_devices = find_fsid(fsid);
4448 fs_devices = clone_fs_devices(fs_devices);
4449 if (IS_ERR(fs_devices)) {
4450 ret = PTR_ERR(fs_devices);
4454 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
4455 root->fs_info->bdev_holder);
4457 free_fs_devices(fs_devices);
4461 if (!fs_devices->seeding) {
4462 __btrfs_close_devices(fs_devices);
4463 free_fs_devices(fs_devices);
4468 fs_devices->seed = root->fs_info->fs_devices->seed;
4469 root->fs_info->fs_devices->seed = fs_devices;
4474 static int read_one_dev(struct btrfs_root *root,
4475 struct extent_buffer *leaf,
4476 struct btrfs_dev_item *dev_item)
4478 struct btrfs_device *device;
4481 u8 fs_uuid[BTRFS_UUID_SIZE];
4482 u8 dev_uuid[BTRFS_UUID_SIZE];
4484 devid = btrfs_device_id(leaf, dev_item);
4485 read_extent_buffer(leaf, dev_uuid,
4486 (unsigned long)btrfs_device_uuid(dev_item),
4488 read_extent_buffer(leaf, fs_uuid,
4489 (unsigned long)btrfs_device_fsid(dev_item),
4492 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
4493 ret = open_seed_devices(root, fs_uuid);
4494 if (ret && !btrfs_test_opt(root, DEGRADED))
4498 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
4499 if (!device || !device->bdev) {
4500 if (!btrfs_test_opt(root, DEGRADED))
4504 printk(KERN_WARNING "warning devid %llu missing\n",
4505 (unsigned long long)devid);
4506 device = add_missing_dev(root, devid, dev_uuid);
4509 } else if (!device->missing) {
4511 * this happens when a device that was properly setup
4512 * in the device info lists suddenly goes bad.
4513 * device->bdev is NULL, and so we have to set
4514 * device->missing to one here
4516 root->fs_info->fs_devices->missing_devices++;
4517 device->missing = 1;
4521 if (device->fs_devices != root->fs_info->fs_devices) {
4522 BUG_ON(device->writeable);
4523 if (device->generation !=
4524 btrfs_device_generation(leaf, dev_item))
4528 fill_device_from_item(leaf, dev_item, device);
4529 device->dev_root = root->fs_info->dev_root;
4530 device->in_fs_metadata = 1;
4531 if (device->writeable) {
4532 device->fs_devices->total_rw_bytes += device->total_bytes;
4533 spin_lock(&root->fs_info->free_chunk_lock);
4534 root->fs_info->free_chunk_space += device->total_bytes -
4536 spin_unlock(&root->fs_info->free_chunk_lock);
4542 int btrfs_read_sys_array(struct btrfs_root *root)
4544 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4545 struct extent_buffer *sb;
4546 struct btrfs_disk_key *disk_key;
4547 struct btrfs_chunk *chunk;
4549 unsigned long sb_ptr;
4555 struct btrfs_key key;
4557 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
4558 BTRFS_SUPER_INFO_SIZE);
4561 btrfs_set_buffer_uptodate(sb);
4562 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
4564 * The sb extent buffer is artifical and just used to read the system array.
4565 * btrfs_set_buffer_uptodate() call does not properly mark all it's
4566 * pages up-to-date when the page is larger: extent does not cover the
4567 * whole page and consequently check_page_uptodate does not find all
4568 * the page's extents up-to-date (the hole beyond sb),
4569 * write_extent_buffer then triggers a WARN_ON.
4571 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
4572 * but sb spans only this function. Add an explicit SetPageUptodate call
4573 * to silence the warning eg. on PowerPC 64.
4575 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
4576 SetPageUptodate(sb->pages[0]);
4578 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
4579 array_size = btrfs_super_sys_array_size(super_copy);
4581 ptr = super_copy->sys_chunk_array;
4582 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
4585 while (cur < array_size) {
4586 disk_key = (struct btrfs_disk_key *)ptr;
4587 btrfs_disk_key_to_cpu(&key, disk_key);
4589 len = sizeof(*disk_key); ptr += len;
4593 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
4594 chunk = (struct btrfs_chunk *)sb_ptr;
4595 ret = read_one_chunk(root, &key, sb, chunk);
4598 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
4599 len = btrfs_chunk_item_size(num_stripes);
4608 free_extent_buffer(sb);
4612 struct btrfs_device *btrfs_find_device_for_logical(struct btrfs_root *root,
4613 u64 logical, int mirror_num)
4615 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4618 struct btrfs_bio *bbio = NULL;
4619 struct btrfs_device *device;
4621 BUG_ON(mirror_num == 0);
4622 ret = btrfs_map_block(map_tree, WRITE, logical, &map_length, &bbio,
4625 BUG_ON(bbio != NULL);
4628 BUG_ON(mirror_num != bbio->mirror_num);
4629 device = bbio->stripes[mirror_num - 1].dev;
4634 int btrfs_read_chunk_tree(struct btrfs_root *root)
4636 struct btrfs_path *path;
4637 struct extent_buffer *leaf;
4638 struct btrfs_key key;
4639 struct btrfs_key found_key;
4643 root = root->fs_info->chunk_root;
4645 path = btrfs_alloc_path();
4649 mutex_lock(&uuid_mutex);
4652 /* first we search for all of the device items, and then we
4653 * read in all of the chunk items. This way we can create chunk
4654 * mappings that reference all of the devices that are afound
4656 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
4660 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4664 leaf = path->nodes[0];
4665 slot = path->slots[0];
4666 if (slot >= btrfs_header_nritems(leaf)) {
4667 ret = btrfs_next_leaf(root, path);
4674 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4675 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
4676 if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
4678 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
4679 struct btrfs_dev_item *dev_item;
4680 dev_item = btrfs_item_ptr(leaf, slot,
4681 struct btrfs_dev_item);
4682 ret = read_one_dev(root, leaf, dev_item);
4686 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
4687 struct btrfs_chunk *chunk;
4688 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4689 ret = read_one_chunk(root, &found_key, leaf, chunk);
4695 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
4697 btrfs_release_path(path);
4702 unlock_chunks(root);
4703 mutex_unlock(&uuid_mutex);
4705 btrfs_free_path(path);
4709 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
4713 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
4714 btrfs_dev_stat_reset(dev, i);
4717 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
4719 struct btrfs_key key;
4720 struct btrfs_key found_key;
4721 struct btrfs_root *dev_root = fs_info->dev_root;
4722 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
4723 struct extent_buffer *eb;
4726 struct btrfs_device *device;
4727 struct btrfs_path *path = NULL;
4730 path = btrfs_alloc_path();
4736 mutex_lock(&fs_devices->device_list_mutex);
4737 list_for_each_entry(device, &fs_devices->devices, dev_list) {
4739 struct btrfs_dev_stats_item *ptr;
4742 key.type = BTRFS_DEV_STATS_KEY;
4743 key.offset = device->devid;
4744 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
4746 __btrfs_reset_dev_stats(device);
4747 device->dev_stats_valid = 1;
4748 btrfs_release_path(path);
4751 slot = path->slots[0];
4752 eb = path->nodes[0];
4753 btrfs_item_key_to_cpu(eb, &found_key, slot);
4754 item_size = btrfs_item_size_nr(eb, slot);
4756 ptr = btrfs_item_ptr(eb, slot,
4757 struct btrfs_dev_stats_item);
4759 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
4760 if (item_size >= (1 + i) * sizeof(__le64))
4761 btrfs_dev_stat_set(device, i,
4762 btrfs_dev_stats_value(eb, ptr, i));
4764 btrfs_dev_stat_reset(device, i);
4767 device->dev_stats_valid = 1;
4768 btrfs_dev_stat_print_on_load(device);
4769 btrfs_release_path(path);
4771 mutex_unlock(&fs_devices->device_list_mutex);
4774 btrfs_free_path(path);
4775 return ret < 0 ? ret : 0;
4778 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
4779 struct btrfs_root *dev_root,
4780 struct btrfs_device *device)
4782 struct btrfs_path *path;
4783 struct btrfs_key key;
4784 struct extent_buffer *eb;
4785 struct btrfs_dev_stats_item *ptr;
4790 key.type = BTRFS_DEV_STATS_KEY;
4791 key.offset = device->devid;
4793 path = btrfs_alloc_path();
4795 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
4797 printk_in_rcu(KERN_WARNING "btrfs: error %d while searching for dev_stats item for device %s!\n",
4798 ret, rcu_str_deref(device->name));
4803 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
4804 /* need to delete old one and insert a new one */
4805 ret = btrfs_del_item(trans, dev_root, path);
4807 printk_in_rcu(KERN_WARNING "btrfs: delete too small dev_stats item for device %s failed %d!\n",
4808 rcu_str_deref(device->name), ret);
4815 /* need to insert a new item */
4816 btrfs_release_path(path);
4817 ret = btrfs_insert_empty_item(trans, dev_root, path,
4818 &key, sizeof(*ptr));
4820 printk_in_rcu(KERN_WARNING "btrfs: insert dev_stats item for device %s failed %d!\n",
4821 rcu_str_deref(device->name), ret);
4826 eb = path->nodes[0];
4827 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
4828 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
4829 btrfs_set_dev_stats_value(eb, ptr, i,
4830 btrfs_dev_stat_read(device, i));
4831 btrfs_mark_buffer_dirty(eb);
4834 btrfs_free_path(path);
4839 * called from commit_transaction. Writes all changed device stats to disk.
4841 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
4842 struct btrfs_fs_info *fs_info)
4844 struct btrfs_root *dev_root = fs_info->dev_root;
4845 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
4846 struct btrfs_device *device;
4849 mutex_lock(&fs_devices->device_list_mutex);
4850 list_for_each_entry(device, &fs_devices->devices, dev_list) {
4851 if (!device->dev_stats_valid || !device->dev_stats_dirty)
4854 ret = update_dev_stat_item(trans, dev_root, device);
4856 device->dev_stats_dirty = 0;
4858 mutex_unlock(&fs_devices->device_list_mutex);
4863 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
4865 btrfs_dev_stat_inc(dev, index);
4866 btrfs_dev_stat_print_on_error(dev);
4869 void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
4871 if (!dev->dev_stats_valid)
4873 printk_ratelimited_in_rcu(KERN_ERR
4874 "btrfs: bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
4875 rcu_str_deref(dev->name),
4876 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
4877 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
4878 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
4879 btrfs_dev_stat_read(dev,
4880 BTRFS_DEV_STAT_CORRUPTION_ERRS),
4881 btrfs_dev_stat_read(dev,
4882 BTRFS_DEV_STAT_GENERATION_ERRS));
4885 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
4889 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
4890 if (btrfs_dev_stat_read(dev, i) != 0)
4892 if (i == BTRFS_DEV_STAT_VALUES_MAX)
4893 return; /* all values == 0, suppress message */
4895 printk_in_rcu(KERN_INFO "btrfs: bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
4896 rcu_str_deref(dev->name),
4897 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
4898 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
4899 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
4900 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
4901 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
4904 int btrfs_get_dev_stats(struct btrfs_root *root,
4905 struct btrfs_ioctl_get_dev_stats *stats)
4907 struct btrfs_device *dev;
4908 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
4911 mutex_lock(&fs_devices->device_list_mutex);
4912 dev = btrfs_find_device(root, stats->devid, NULL, NULL);
4913 mutex_unlock(&fs_devices->device_list_mutex);
4917 "btrfs: get dev_stats failed, device not found\n");
4919 } else if (!dev->dev_stats_valid) {
4921 "btrfs: get dev_stats failed, not yet valid\n");
4923 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
4924 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
4925 if (stats->nr_items > i)
4927 btrfs_dev_stat_read_and_reset(dev, i);
4929 btrfs_dev_stat_reset(dev, i);
4932 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
4933 if (stats->nr_items > i)
4934 stats->values[i] = btrfs_dev_stat_read(dev, i);
4936 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
4937 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;