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;
231 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
232 waitqueue_active(&fs_info->async_submit_wait))
233 wake_up(&fs_info->async_submit_wait);
235 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
238 * if we're doing the sync list, record that our
239 * plug has some sync requests on it
241 * If we're doing the regular list and there are
242 * sync requests sitting around, unplug before
245 if (pending_bios == &device->pending_sync_bios) {
247 } else if (sync_pending) {
248 blk_finish_plug(&plug);
249 blk_start_plug(&plug);
253 btrfsic_submit_bio(cur->bi_rw, cur);
260 * we made progress, there is more work to do and the bdi
261 * is now congested. Back off and let other work structs
264 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
265 fs_info->fs_devices->open_devices > 1) {
266 struct io_context *ioc;
268 ioc = current->io_context;
271 * the main goal here is that we don't want to
272 * block if we're going to be able to submit
273 * more requests without blocking.
275 * This code does two great things, it pokes into
276 * the elevator code from a filesystem _and_
277 * it makes assumptions about how batching works.
279 if (ioc && ioc->nr_batch_requests > 0 &&
280 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
282 ioc->last_waited == last_waited)) {
284 * we want to go through our batch of
285 * requests and stop. So, we copy out
286 * the ioc->last_waited time and test
287 * against it before looping
289 last_waited = ioc->last_waited;
294 spin_lock(&device->io_lock);
295 requeue_list(pending_bios, pending, tail);
296 device->running_pending = 1;
298 spin_unlock(&device->io_lock);
299 btrfs_requeue_work(&device->work);
302 /* unplug every 64 requests just for good measure */
303 if (batch_run % 64 == 0) {
304 blk_finish_plug(&plug);
305 blk_start_plug(&plug);
314 spin_lock(&device->io_lock);
315 if (device->pending_bios.head || device->pending_sync_bios.head)
317 spin_unlock(&device->io_lock);
320 blk_finish_plug(&plug);
323 static void pending_bios_fn(struct btrfs_work *work)
325 struct btrfs_device *device;
327 device = container_of(work, struct btrfs_device, work);
328 run_scheduled_bios(device);
331 static noinline int device_list_add(const char *path,
332 struct btrfs_super_block *disk_super,
333 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
335 struct btrfs_device *device;
336 struct btrfs_fs_devices *fs_devices;
337 struct rcu_string *name;
338 u64 found_transid = btrfs_super_generation(disk_super);
340 fs_devices = find_fsid(disk_super->fsid);
342 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
345 INIT_LIST_HEAD(&fs_devices->devices);
346 INIT_LIST_HEAD(&fs_devices->alloc_list);
347 list_add(&fs_devices->list, &fs_uuids);
348 memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
349 fs_devices->latest_devid = devid;
350 fs_devices->latest_trans = found_transid;
351 mutex_init(&fs_devices->device_list_mutex);
354 device = __find_device(&fs_devices->devices, devid,
355 disk_super->dev_item.uuid);
358 if (fs_devices->opened)
361 device = kzalloc(sizeof(*device), GFP_NOFS);
363 /* we can safely leave the fs_devices entry around */
366 device->devid = devid;
367 device->dev_stats_valid = 0;
368 device->work.func = pending_bios_fn;
369 memcpy(device->uuid, disk_super->dev_item.uuid,
371 spin_lock_init(&device->io_lock);
373 name = rcu_string_strdup(path, GFP_NOFS);
378 rcu_assign_pointer(device->name, name);
379 INIT_LIST_HEAD(&device->dev_alloc_list);
381 /* init readahead state */
382 spin_lock_init(&device->reada_lock);
383 device->reada_curr_zone = NULL;
384 atomic_set(&device->reada_in_flight, 0);
385 device->reada_next = 0;
386 INIT_RADIX_TREE(&device->reada_zones, GFP_NOFS & ~__GFP_WAIT);
387 INIT_RADIX_TREE(&device->reada_extents, GFP_NOFS & ~__GFP_WAIT);
389 mutex_lock(&fs_devices->device_list_mutex);
390 list_add_rcu(&device->dev_list, &fs_devices->devices);
391 mutex_unlock(&fs_devices->device_list_mutex);
393 device->fs_devices = fs_devices;
394 fs_devices->num_devices++;
395 } else if (!device->name || strcmp(device->name->str, path)) {
396 name = rcu_string_strdup(path, GFP_NOFS);
399 rcu_string_free(device->name);
400 rcu_assign_pointer(device->name, name);
401 if (device->missing) {
402 fs_devices->missing_devices--;
407 if (found_transid > fs_devices->latest_trans) {
408 fs_devices->latest_devid = devid;
409 fs_devices->latest_trans = found_transid;
411 *fs_devices_ret = fs_devices;
415 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
417 struct btrfs_fs_devices *fs_devices;
418 struct btrfs_device *device;
419 struct btrfs_device *orig_dev;
421 fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
423 return ERR_PTR(-ENOMEM);
425 INIT_LIST_HEAD(&fs_devices->devices);
426 INIT_LIST_HEAD(&fs_devices->alloc_list);
427 INIT_LIST_HEAD(&fs_devices->list);
428 mutex_init(&fs_devices->device_list_mutex);
429 fs_devices->latest_devid = orig->latest_devid;
430 fs_devices->latest_trans = orig->latest_trans;
431 fs_devices->total_devices = orig->total_devices;
432 memcpy(fs_devices->fsid, orig->fsid, sizeof(fs_devices->fsid));
434 /* We have held the volume lock, it is safe to get the devices. */
435 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
436 struct rcu_string *name;
438 device = kzalloc(sizeof(*device), GFP_NOFS);
443 * This is ok to do without rcu read locked because we hold the
444 * uuid mutex so nothing we touch in here is going to disappear.
446 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
451 rcu_assign_pointer(device->name, name);
453 device->devid = orig_dev->devid;
454 device->work.func = pending_bios_fn;
455 memcpy(device->uuid, orig_dev->uuid, sizeof(device->uuid));
456 spin_lock_init(&device->io_lock);
457 INIT_LIST_HEAD(&device->dev_list);
458 INIT_LIST_HEAD(&device->dev_alloc_list);
460 list_add(&device->dev_list, &fs_devices->devices);
461 device->fs_devices = fs_devices;
462 fs_devices->num_devices++;
466 free_fs_devices(fs_devices);
467 return ERR_PTR(-ENOMEM);
470 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
472 struct btrfs_device *device, *next;
474 struct block_device *latest_bdev = NULL;
475 u64 latest_devid = 0;
476 u64 latest_transid = 0;
478 mutex_lock(&uuid_mutex);
480 /* This is the initialized path, it is safe to release the devices. */
481 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
482 if (device->in_fs_metadata) {
483 if (!latest_transid ||
484 device->generation > latest_transid) {
485 latest_devid = device->devid;
486 latest_transid = device->generation;
487 latest_bdev = device->bdev;
493 blkdev_put(device->bdev, device->mode);
495 fs_devices->open_devices--;
497 if (device->writeable) {
498 list_del_init(&device->dev_alloc_list);
499 device->writeable = 0;
500 fs_devices->rw_devices--;
502 list_del_init(&device->dev_list);
503 fs_devices->num_devices--;
504 rcu_string_free(device->name);
508 if (fs_devices->seed) {
509 fs_devices = fs_devices->seed;
513 fs_devices->latest_bdev = latest_bdev;
514 fs_devices->latest_devid = latest_devid;
515 fs_devices->latest_trans = latest_transid;
517 mutex_unlock(&uuid_mutex);
520 static void __free_device(struct work_struct *work)
522 struct btrfs_device *device;
524 device = container_of(work, struct btrfs_device, rcu_work);
527 blkdev_put(device->bdev, device->mode);
529 rcu_string_free(device->name);
533 static void free_device(struct rcu_head *head)
535 struct btrfs_device *device;
537 device = container_of(head, struct btrfs_device, rcu);
539 INIT_WORK(&device->rcu_work, __free_device);
540 schedule_work(&device->rcu_work);
543 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
545 struct btrfs_device *device;
547 if (--fs_devices->opened > 0)
550 mutex_lock(&fs_devices->device_list_mutex);
551 list_for_each_entry(device, &fs_devices->devices, dev_list) {
552 struct btrfs_device *new_device;
553 struct rcu_string *name;
556 fs_devices->open_devices--;
558 if (device->writeable) {
559 list_del_init(&device->dev_alloc_list);
560 fs_devices->rw_devices--;
563 if (device->can_discard)
564 fs_devices->num_can_discard--;
566 new_device = kmalloc(sizeof(*new_device), GFP_NOFS);
567 BUG_ON(!new_device); /* -ENOMEM */
568 memcpy(new_device, device, sizeof(*new_device));
570 /* 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);
576 new_device->bdev = NULL;
577 new_device->writeable = 0;
578 new_device->in_fs_metadata = 0;
579 new_device->can_discard = 0;
580 list_replace_rcu(&device->dev_list, &new_device->dev_list);
582 call_rcu(&device->rcu, free_device);
584 mutex_unlock(&fs_devices->device_list_mutex);
586 WARN_ON(fs_devices->open_devices);
587 WARN_ON(fs_devices->rw_devices);
588 fs_devices->opened = 0;
589 fs_devices->seeding = 0;
594 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
596 struct btrfs_fs_devices *seed_devices = NULL;
599 mutex_lock(&uuid_mutex);
600 ret = __btrfs_close_devices(fs_devices);
601 if (!fs_devices->opened) {
602 seed_devices = fs_devices->seed;
603 fs_devices->seed = NULL;
605 mutex_unlock(&uuid_mutex);
607 while (seed_devices) {
608 fs_devices = seed_devices;
609 seed_devices = fs_devices->seed;
610 __btrfs_close_devices(fs_devices);
611 free_fs_devices(fs_devices);
616 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
617 fmode_t flags, void *holder)
619 struct request_queue *q;
620 struct block_device *bdev;
621 struct list_head *head = &fs_devices->devices;
622 struct btrfs_device *device;
623 struct block_device *latest_bdev = NULL;
624 struct buffer_head *bh;
625 struct btrfs_super_block *disk_super;
626 u64 latest_devid = 0;
627 u64 latest_transid = 0;
634 list_for_each_entry(device, head, dev_list) {
640 bdev = blkdev_get_by_path(device->name->str, flags, holder);
642 printk(KERN_INFO "open %s failed\n", device->name->str);
645 filemap_write_and_wait(bdev->bd_inode->i_mapping);
646 invalidate_bdev(bdev);
647 set_blocksize(bdev, 4096);
649 bh = btrfs_read_dev_super(bdev);
653 disk_super = (struct btrfs_super_block *)bh->b_data;
654 devid = btrfs_stack_device_id(&disk_super->dev_item);
655 if (devid != device->devid)
658 if (memcmp(device->uuid, disk_super->dev_item.uuid,
662 device->generation = btrfs_super_generation(disk_super);
663 if (!latest_transid || device->generation > latest_transid) {
664 latest_devid = devid;
665 latest_transid = device->generation;
669 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
670 device->writeable = 0;
672 device->writeable = !bdev_read_only(bdev);
676 q = bdev_get_queue(bdev);
677 if (blk_queue_discard(q)) {
678 device->can_discard = 1;
679 fs_devices->num_can_discard++;
683 device->in_fs_metadata = 0;
684 device->mode = flags;
686 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
687 fs_devices->rotating = 1;
689 fs_devices->open_devices++;
690 if (device->writeable) {
691 fs_devices->rw_devices++;
692 list_add(&device->dev_alloc_list,
693 &fs_devices->alloc_list);
701 blkdev_put(bdev, flags);
705 if (fs_devices->open_devices == 0) {
709 fs_devices->seeding = seeding;
710 fs_devices->opened = 1;
711 fs_devices->latest_bdev = latest_bdev;
712 fs_devices->latest_devid = latest_devid;
713 fs_devices->latest_trans = latest_transid;
714 fs_devices->total_rw_bytes = 0;
719 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
720 fmode_t flags, void *holder)
724 mutex_lock(&uuid_mutex);
725 if (fs_devices->opened) {
726 fs_devices->opened++;
729 ret = __btrfs_open_devices(fs_devices, flags, holder);
731 mutex_unlock(&uuid_mutex);
735 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
736 struct btrfs_fs_devices **fs_devices_ret)
738 struct btrfs_super_block *disk_super;
739 struct block_device *bdev;
740 struct buffer_head *bh;
747 bdev = blkdev_get_by_path(path, flags, holder);
754 mutex_lock(&uuid_mutex);
755 ret = set_blocksize(bdev, 4096);
758 bh = btrfs_read_dev_super(bdev);
763 disk_super = (struct btrfs_super_block *)bh->b_data;
764 devid = btrfs_stack_device_id(&disk_super->dev_item);
765 transid = btrfs_super_generation(disk_super);
766 total_devices = btrfs_super_num_devices(disk_super);
767 if (disk_super->label[0])
768 printk(KERN_INFO "device label %s ", disk_super->label);
770 printk(KERN_INFO "device fsid %pU ", disk_super->fsid);
771 printk(KERN_CONT "devid %llu transid %llu %s\n",
772 (unsigned long long)devid, (unsigned long long)transid, path);
773 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
774 if (!ret && fs_devices_ret)
775 (*fs_devices_ret)->total_devices = total_devices;
778 mutex_unlock(&uuid_mutex);
779 blkdev_put(bdev, flags);
784 /* helper to account the used device space in the range */
785 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
786 u64 end, u64 *length)
788 struct btrfs_key key;
789 struct btrfs_root *root = device->dev_root;
790 struct btrfs_dev_extent *dev_extent;
791 struct btrfs_path *path;
795 struct extent_buffer *l;
799 if (start >= device->total_bytes)
802 path = btrfs_alloc_path();
807 key.objectid = device->devid;
809 key.type = BTRFS_DEV_EXTENT_KEY;
811 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
815 ret = btrfs_previous_item(root, path, key.objectid, key.type);
822 slot = path->slots[0];
823 if (slot >= btrfs_header_nritems(l)) {
824 ret = btrfs_next_leaf(root, path);
832 btrfs_item_key_to_cpu(l, &key, slot);
834 if (key.objectid < device->devid)
837 if (key.objectid > device->devid)
840 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
843 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
844 extent_end = key.offset + btrfs_dev_extent_length(l,
846 if (key.offset <= start && extent_end > end) {
847 *length = end - start + 1;
849 } else if (key.offset <= start && extent_end > start)
850 *length += extent_end - start;
851 else if (key.offset > start && extent_end <= end)
852 *length += extent_end - key.offset;
853 else if (key.offset > start && key.offset <= end) {
854 *length += end - key.offset + 1;
856 } else if (key.offset > end)
864 btrfs_free_path(path);
869 * find_free_dev_extent - find free space in the specified device
870 * @device: the device which we search the free space in
871 * @num_bytes: the size of the free space that we need
872 * @start: store the start of the free space.
873 * @len: the size of the free space. that we find, or the size of the max
874 * free space if we don't find suitable free space
876 * this uses a pretty simple search, the expectation is that it is
877 * called very infrequently and that a given device has a small number
880 * @start is used to store the start of the free space if we find. But if we
881 * don't find suitable free space, it will be used to store the start position
882 * of the max free space.
884 * @len is used to store the size of the free space that we find.
885 * But if we don't find suitable free space, it is used to store the size of
886 * the max free space.
888 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
889 u64 *start, u64 *len)
891 struct btrfs_key key;
892 struct btrfs_root *root = device->dev_root;
893 struct btrfs_dev_extent *dev_extent;
894 struct btrfs_path *path;
900 u64 search_end = device->total_bytes;
903 struct extent_buffer *l;
905 /* FIXME use last free of some kind */
907 /* we don't want to overwrite the superblock on the drive,
908 * so we make sure to start at an offset of at least 1MB
910 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
912 max_hole_start = search_start;
916 if (search_start >= search_end) {
921 path = btrfs_alloc_path();
928 key.objectid = device->devid;
929 key.offset = search_start;
930 key.type = BTRFS_DEV_EXTENT_KEY;
932 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
936 ret = btrfs_previous_item(root, path, key.objectid, key.type);
943 slot = path->slots[0];
944 if (slot >= btrfs_header_nritems(l)) {
945 ret = btrfs_next_leaf(root, path);
953 btrfs_item_key_to_cpu(l, &key, slot);
955 if (key.objectid < device->devid)
958 if (key.objectid > device->devid)
961 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
964 if (key.offset > search_start) {
965 hole_size = key.offset - search_start;
967 if (hole_size > max_hole_size) {
968 max_hole_start = search_start;
969 max_hole_size = hole_size;
973 * If this free space is greater than which we need,
974 * it must be the max free space that we have found
975 * until now, so max_hole_start must point to the start
976 * of this free space and the length of this free space
977 * is stored in max_hole_size. Thus, we return
978 * max_hole_start and max_hole_size and go back to the
981 if (hole_size >= num_bytes) {
987 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
988 extent_end = key.offset + btrfs_dev_extent_length(l,
990 if (extent_end > search_start)
991 search_start = extent_end;
998 * At this point, search_start should be the end of
999 * allocated dev extents, and when shrinking the device,
1000 * search_end may be smaller than search_start.
1002 if (search_end > search_start)
1003 hole_size = search_end - search_start;
1005 if (hole_size > max_hole_size) {
1006 max_hole_start = search_start;
1007 max_hole_size = hole_size;
1011 if (hole_size < num_bytes)
1017 btrfs_free_path(path);
1019 *start = max_hole_start;
1021 *len = max_hole_size;
1025 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1026 struct btrfs_device *device,
1030 struct btrfs_path *path;
1031 struct btrfs_root *root = device->dev_root;
1032 struct btrfs_key key;
1033 struct btrfs_key found_key;
1034 struct extent_buffer *leaf = NULL;
1035 struct btrfs_dev_extent *extent = NULL;
1037 path = btrfs_alloc_path();
1041 key.objectid = device->devid;
1043 key.type = BTRFS_DEV_EXTENT_KEY;
1045 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1047 ret = btrfs_previous_item(root, path, key.objectid,
1048 BTRFS_DEV_EXTENT_KEY);
1051 leaf = path->nodes[0];
1052 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1053 extent = btrfs_item_ptr(leaf, path->slots[0],
1054 struct btrfs_dev_extent);
1055 BUG_ON(found_key.offset > start || found_key.offset +
1056 btrfs_dev_extent_length(leaf, extent) < start);
1058 btrfs_release_path(path);
1060 } else if (ret == 0) {
1061 leaf = path->nodes[0];
1062 extent = btrfs_item_ptr(leaf, path->slots[0],
1063 struct btrfs_dev_extent);
1065 btrfs_error(root->fs_info, ret, "Slot search failed");
1069 if (device->bytes_used > 0) {
1070 u64 len = btrfs_dev_extent_length(leaf, extent);
1071 device->bytes_used -= len;
1072 spin_lock(&root->fs_info->free_chunk_lock);
1073 root->fs_info->free_chunk_space += len;
1074 spin_unlock(&root->fs_info->free_chunk_lock);
1076 ret = btrfs_del_item(trans, root, path);
1078 btrfs_error(root->fs_info, ret,
1079 "Failed to remove dev extent item");
1082 btrfs_free_path(path);
1086 int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1087 struct btrfs_device *device,
1088 u64 chunk_tree, u64 chunk_objectid,
1089 u64 chunk_offset, u64 start, u64 num_bytes)
1092 struct btrfs_path *path;
1093 struct btrfs_root *root = device->dev_root;
1094 struct btrfs_dev_extent *extent;
1095 struct extent_buffer *leaf;
1096 struct btrfs_key key;
1098 WARN_ON(!device->in_fs_metadata);
1099 path = btrfs_alloc_path();
1103 key.objectid = device->devid;
1105 key.type = BTRFS_DEV_EXTENT_KEY;
1106 ret = btrfs_insert_empty_item(trans, root, path, &key,
1111 leaf = path->nodes[0];
1112 extent = btrfs_item_ptr(leaf, path->slots[0],
1113 struct btrfs_dev_extent);
1114 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1115 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1116 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1118 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1119 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1122 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1123 btrfs_mark_buffer_dirty(leaf);
1125 btrfs_free_path(path);
1129 static noinline int find_next_chunk(struct btrfs_root *root,
1130 u64 objectid, u64 *offset)
1132 struct btrfs_path *path;
1134 struct btrfs_key key;
1135 struct btrfs_chunk *chunk;
1136 struct btrfs_key found_key;
1138 path = btrfs_alloc_path();
1142 key.objectid = objectid;
1143 key.offset = (u64)-1;
1144 key.type = BTRFS_CHUNK_ITEM_KEY;
1146 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1150 BUG_ON(ret == 0); /* Corruption */
1152 ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
1156 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1158 if (found_key.objectid != objectid)
1161 chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
1162 struct btrfs_chunk);
1163 *offset = found_key.offset +
1164 btrfs_chunk_length(path->nodes[0], chunk);
1169 btrfs_free_path(path);
1173 static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
1176 struct btrfs_key key;
1177 struct btrfs_key found_key;
1178 struct btrfs_path *path;
1180 root = root->fs_info->chunk_root;
1182 path = btrfs_alloc_path();
1186 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1187 key.type = BTRFS_DEV_ITEM_KEY;
1188 key.offset = (u64)-1;
1190 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1194 BUG_ON(ret == 0); /* Corruption */
1196 ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
1197 BTRFS_DEV_ITEM_KEY);
1201 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1203 *objectid = found_key.offset + 1;
1207 btrfs_free_path(path);
1212 * the device information is stored in the chunk root
1213 * the btrfs_device struct should be fully filled in
1215 int btrfs_add_device(struct btrfs_trans_handle *trans,
1216 struct btrfs_root *root,
1217 struct btrfs_device *device)
1220 struct btrfs_path *path;
1221 struct btrfs_dev_item *dev_item;
1222 struct extent_buffer *leaf;
1223 struct btrfs_key key;
1226 root = root->fs_info->chunk_root;
1228 path = btrfs_alloc_path();
1232 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1233 key.type = BTRFS_DEV_ITEM_KEY;
1234 key.offset = device->devid;
1236 ret = btrfs_insert_empty_item(trans, root, path, &key,
1241 leaf = path->nodes[0];
1242 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1244 btrfs_set_device_id(leaf, dev_item, device->devid);
1245 btrfs_set_device_generation(leaf, dev_item, 0);
1246 btrfs_set_device_type(leaf, dev_item, device->type);
1247 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1248 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1249 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1250 btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1251 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1252 btrfs_set_device_group(leaf, dev_item, 0);
1253 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1254 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1255 btrfs_set_device_start_offset(leaf, dev_item, 0);
1257 ptr = (unsigned long)btrfs_device_uuid(dev_item);
1258 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1259 ptr = (unsigned long)btrfs_device_fsid(dev_item);
1260 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1261 btrfs_mark_buffer_dirty(leaf);
1265 btrfs_free_path(path);
1269 static int btrfs_rm_dev_item(struct btrfs_root *root,
1270 struct btrfs_device *device)
1273 struct btrfs_path *path;
1274 struct btrfs_key key;
1275 struct btrfs_trans_handle *trans;
1277 root = root->fs_info->chunk_root;
1279 path = btrfs_alloc_path();
1283 trans = btrfs_start_transaction(root, 0);
1284 if (IS_ERR(trans)) {
1285 btrfs_free_path(path);
1286 return PTR_ERR(trans);
1288 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1289 key.type = BTRFS_DEV_ITEM_KEY;
1290 key.offset = device->devid;
1293 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1302 ret = btrfs_del_item(trans, root, path);
1306 btrfs_free_path(path);
1307 unlock_chunks(root);
1308 btrfs_commit_transaction(trans, root);
1312 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1314 struct btrfs_device *device;
1315 struct btrfs_device *next_device;
1316 struct block_device *bdev;
1317 struct buffer_head *bh = NULL;
1318 struct btrfs_super_block *disk_super;
1319 struct btrfs_fs_devices *cur_devices;
1325 bool clear_super = false;
1327 mutex_lock(&uuid_mutex);
1329 all_avail = root->fs_info->avail_data_alloc_bits |
1330 root->fs_info->avail_system_alloc_bits |
1331 root->fs_info->avail_metadata_alloc_bits;
1333 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
1334 root->fs_info->fs_devices->num_devices <= 4) {
1335 printk(KERN_ERR "btrfs: unable to go below four devices "
1341 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
1342 root->fs_info->fs_devices->num_devices <= 2) {
1343 printk(KERN_ERR "btrfs: unable to go below two "
1344 "devices on raid1\n");
1349 if (strcmp(device_path, "missing") == 0) {
1350 struct list_head *devices;
1351 struct btrfs_device *tmp;
1354 devices = &root->fs_info->fs_devices->devices;
1356 * It is safe to read the devices since the volume_mutex
1359 list_for_each_entry(tmp, devices, dev_list) {
1360 if (tmp->in_fs_metadata && !tmp->bdev) {
1369 printk(KERN_ERR "btrfs: no missing devices found to "
1374 bdev = blkdev_get_by_path(device_path, FMODE_READ | FMODE_EXCL,
1375 root->fs_info->bdev_holder);
1377 ret = PTR_ERR(bdev);
1381 set_blocksize(bdev, 4096);
1382 invalidate_bdev(bdev);
1383 bh = btrfs_read_dev_super(bdev);
1388 disk_super = (struct btrfs_super_block *)bh->b_data;
1389 devid = btrfs_stack_device_id(&disk_super->dev_item);
1390 dev_uuid = disk_super->dev_item.uuid;
1391 device = btrfs_find_device(root, devid, dev_uuid,
1399 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1400 printk(KERN_ERR "btrfs: unable to remove the only writeable "
1406 if (device->writeable) {
1408 list_del_init(&device->dev_alloc_list);
1409 unlock_chunks(root);
1410 root->fs_info->fs_devices->rw_devices--;
1414 ret = btrfs_shrink_device(device, 0);
1418 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1422 spin_lock(&root->fs_info->free_chunk_lock);
1423 root->fs_info->free_chunk_space = device->total_bytes -
1425 spin_unlock(&root->fs_info->free_chunk_lock);
1427 device->in_fs_metadata = 0;
1428 btrfs_scrub_cancel_dev(root, device);
1431 * the device list mutex makes sure that we don't change
1432 * the device list while someone else is writing out all
1433 * the device supers.
1436 cur_devices = device->fs_devices;
1437 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1438 list_del_rcu(&device->dev_list);
1440 device->fs_devices->num_devices--;
1441 device->fs_devices->total_devices--;
1443 if (device->missing)
1444 root->fs_info->fs_devices->missing_devices--;
1446 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1447 struct btrfs_device, dev_list);
1448 if (device->bdev == root->fs_info->sb->s_bdev)
1449 root->fs_info->sb->s_bdev = next_device->bdev;
1450 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1451 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1454 device->fs_devices->open_devices--;
1456 call_rcu(&device->rcu, free_device);
1457 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1459 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1460 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1462 if (cur_devices->open_devices == 0) {
1463 struct btrfs_fs_devices *fs_devices;
1464 fs_devices = root->fs_info->fs_devices;
1465 while (fs_devices) {
1466 if (fs_devices->seed == cur_devices)
1468 fs_devices = fs_devices->seed;
1470 fs_devices->seed = cur_devices->seed;
1471 cur_devices->seed = NULL;
1473 __btrfs_close_devices(cur_devices);
1474 unlock_chunks(root);
1475 free_fs_devices(cur_devices);
1479 * at this point, the device is zero sized. We want to
1480 * remove it from the devices list and zero out the old super
1483 /* make sure this device isn't detected as part of
1486 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1487 set_buffer_dirty(bh);
1488 sync_dirty_buffer(bh);
1497 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1499 mutex_unlock(&uuid_mutex);
1502 if (device->writeable) {
1504 list_add(&device->dev_alloc_list,
1505 &root->fs_info->fs_devices->alloc_list);
1506 unlock_chunks(root);
1507 root->fs_info->fs_devices->rw_devices++;
1513 * does all the dirty work required for changing file system's UUID.
1515 static int btrfs_prepare_sprout(struct btrfs_root *root)
1517 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1518 struct btrfs_fs_devices *old_devices;
1519 struct btrfs_fs_devices *seed_devices;
1520 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1521 struct btrfs_device *device;
1524 BUG_ON(!mutex_is_locked(&uuid_mutex));
1525 if (!fs_devices->seeding)
1528 seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
1532 old_devices = clone_fs_devices(fs_devices);
1533 if (IS_ERR(old_devices)) {
1534 kfree(seed_devices);
1535 return PTR_ERR(old_devices);
1538 list_add(&old_devices->list, &fs_uuids);
1540 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1541 seed_devices->opened = 1;
1542 INIT_LIST_HEAD(&seed_devices->devices);
1543 INIT_LIST_HEAD(&seed_devices->alloc_list);
1544 mutex_init(&seed_devices->device_list_mutex);
1546 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1547 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1549 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1551 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1552 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1553 device->fs_devices = seed_devices;
1556 fs_devices->seeding = 0;
1557 fs_devices->num_devices = 0;
1558 fs_devices->open_devices = 0;
1559 fs_devices->total_devices = 0;
1560 fs_devices->seed = seed_devices;
1562 generate_random_uuid(fs_devices->fsid);
1563 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1564 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1565 super_flags = btrfs_super_flags(disk_super) &
1566 ~BTRFS_SUPER_FLAG_SEEDING;
1567 btrfs_set_super_flags(disk_super, super_flags);
1573 * strore the expected generation for seed devices in device items.
1575 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1576 struct btrfs_root *root)
1578 struct btrfs_path *path;
1579 struct extent_buffer *leaf;
1580 struct btrfs_dev_item *dev_item;
1581 struct btrfs_device *device;
1582 struct btrfs_key key;
1583 u8 fs_uuid[BTRFS_UUID_SIZE];
1584 u8 dev_uuid[BTRFS_UUID_SIZE];
1588 path = btrfs_alloc_path();
1592 root = root->fs_info->chunk_root;
1593 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1595 key.type = BTRFS_DEV_ITEM_KEY;
1598 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1602 leaf = path->nodes[0];
1604 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1605 ret = btrfs_next_leaf(root, path);
1610 leaf = path->nodes[0];
1611 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1612 btrfs_release_path(path);
1616 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1617 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1618 key.type != BTRFS_DEV_ITEM_KEY)
1621 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1622 struct btrfs_dev_item);
1623 devid = btrfs_device_id(leaf, dev_item);
1624 read_extent_buffer(leaf, dev_uuid,
1625 (unsigned long)btrfs_device_uuid(dev_item),
1627 read_extent_buffer(leaf, fs_uuid,
1628 (unsigned long)btrfs_device_fsid(dev_item),
1630 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
1631 BUG_ON(!device); /* Logic error */
1633 if (device->fs_devices->seeding) {
1634 btrfs_set_device_generation(leaf, dev_item,
1635 device->generation);
1636 btrfs_mark_buffer_dirty(leaf);
1644 btrfs_free_path(path);
1648 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1650 struct request_queue *q;
1651 struct btrfs_trans_handle *trans;
1652 struct btrfs_device *device;
1653 struct block_device *bdev;
1654 struct list_head *devices;
1655 struct super_block *sb = root->fs_info->sb;
1656 struct rcu_string *name;
1658 int seeding_dev = 0;
1661 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1664 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
1665 root->fs_info->bdev_holder);
1667 return PTR_ERR(bdev);
1669 if (root->fs_info->fs_devices->seeding) {
1671 down_write(&sb->s_umount);
1672 mutex_lock(&uuid_mutex);
1675 filemap_write_and_wait(bdev->bd_inode->i_mapping);
1677 devices = &root->fs_info->fs_devices->devices;
1679 * we have the volume lock, so we don't need the extra
1680 * device list mutex while reading the list here.
1682 list_for_each_entry(device, devices, dev_list) {
1683 if (device->bdev == bdev) {
1689 device = kzalloc(sizeof(*device), GFP_NOFS);
1691 /* we can safely leave the fs_devices entry around */
1696 name = rcu_string_strdup(device_path, GFP_NOFS);
1702 rcu_assign_pointer(device->name, name);
1704 ret = find_next_devid(root, &device->devid);
1706 rcu_string_free(device->name);
1711 trans = btrfs_start_transaction(root, 0);
1712 if (IS_ERR(trans)) {
1713 rcu_string_free(device->name);
1715 ret = PTR_ERR(trans);
1721 q = bdev_get_queue(bdev);
1722 if (blk_queue_discard(q))
1723 device->can_discard = 1;
1724 device->writeable = 1;
1725 device->work.func = pending_bios_fn;
1726 generate_random_uuid(device->uuid);
1727 spin_lock_init(&device->io_lock);
1728 device->generation = trans->transid;
1729 device->io_width = root->sectorsize;
1730 device->io_align = root->sectorsize;
1731 device->sector_size = root->sectorsize;
1732 device->total_bytes = i_size_read(bdev->bd_inode);
1733 device->disk_total_bytes = device->total_bytes;
1734 device->dev_root = root->fs_info->dev_root;
1735 device->bdev = bdev;
1736 device->in_fs_metadata = 1;
1737 device->mode = FMODE_EXCL;
1738 set_blocksize(device->bdev, 4096);
1741 sb->s_flags &= ~MS_RDONLY;
1742 ret = btrfs_prepare_sprout(root);
1743 BUG_ON(ret); /* -ENOMEM */
1746 device->fs_devices = root->fs_info->fs_devices;
1749 * we don't want write_supers to jump in here with our device
1752 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1753 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
1754 list_add(&device->dev_alloc_list,
1755 &root->fs_info->fs_devices->alloc_list);
1756 root->fs_info->fs_devices->num_devices++;
1757 root->fs_info->fs_devices->open_devices++;
1758 root->fs_info->fs_devices->rw_devices++;
1759 root->fs_info->fs_devices->total_devices++;
1760 if (device->can_discard)
1761 root->fs_info->fs_devices->num_can_discard++;
1762 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
1764 spin_lock(&root->fs_info->free_chunk_lock);
1765 root->fs_info->free_chunk_space += device->total_bytes;
1766 spin_unlock(&root->fs_info->free_chunk_lock);
1768 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
1769 root->fs_info->fs_devices->rotating = 1;
1771 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1772 btrfs_set_super_total_bytes(root->fs_info->super_copy,
1773 total_bytes + device->total_bytes);
1775 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
1776 btrfs_set_super_num_devices(root->fs_info->super_copy,
1778 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1781 ret = init_first_rw_device(trans, root, device);
1784 ret = btrfs_finish_sprout(trans, root);
1788 ret = btrfs_add_device(trans, root, device);
1794 * we've got more storage, clear any full flags on the space
1797 btrfs_clear_space_info_full(root->fs_info);
1799 unlock_chunks(root);
1800 ret = btrfs_commit_transaction(trans, root);
1803 mutex_unlock(&uuid_mutex);
1804 up_write(&sb->s_umount);
1806 if (ret) /* transaction commit */
1809 ret = btrfs_relocate_sys_chunks(root);
1811 btrfs_error(root->fs_info, ret,
1812 "Failed to relocate sys chunks after "
1813 "device initialization. This can be fixed "
1814 "using the \"btrfs balance\" command.");
1820 unlock_chunks(root);
1821 btrfs_abort_transaction(trans, root, ret);
1822 btrfs_end_transaction(trans, root);
1823 rcu_string_free(device->name);
1826 blkdev_put(bdev, FMODE_EXCL);
1828 mutex_unlock(&uuid_mutex);
1829 up_write(&sb->s_umount);
1834 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
1835 struct btrfs_device *device)
1838 struct btrfs_path *path;
1839 struct btrfs_root *root;
1840 struct btrfs_dev_item *dev_item;
1841 struct extent_buffer *leaf;
1842 struct btrfs_key key;
1844 root = device->dev_root->fs_info->chunk_root;
1846 path = btrfs_alloc_path();
1850 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1851 key.type = BTRFS_DEV_ITEM_KEY;
1852 key.offset = device->devid;
1854 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1863 leaf = path->nodes[0];
1864 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1866 btrfs_set_device_id(leaf, dev_item, device->devid);
1867 btrfs_set_device_type(leaf, dev_item, device->type);
1868 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1869 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1870 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1871 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
1872 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1873 btrfs_mark_buffer_dirty(leaf);
1876 btrfs_free_path(path);
1880 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
1881 struct btrfs_device *device, u64 new_size)
1883 struct btrfs_super_block *super_copy =
1884 device->dev_root->fs_info->super_copy;
1885 u64 old_total = btrfs_super_total_bytes(super_copy);
1886 u64 diff = new_size - device->total_bytes;
1888 if (!device->writeable)
1890 if (new_size <= device->total_bytes)
1893 btrfs_set_super_total_bytes(super_copy, old_total + diff);
1894 device->fs_devices->total_rw_bytes += diff;
1896 device->total_bytes = new_size;
1897 device->disk_total_bytes = new_size;
1898 btrfs_clear_space_info_full(device->dev_root->fs_info);
1900 return btrfs_update_device(trans, device);
1903 int btrfs_grow_device(struct btrfs_trans_handle *trans,
1904 struct btrfs_device *device, u64 new_size)
1907 lock_chunks(device->dev_root);
1908 ret = __btrfs_grow_device(trans, device, new_size);
1909 unlock_chunks(device->dev_root);
1913 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
1914 struct btrfs_root *root,
1915 u64 chunk_tree, u64 chunk_objectid,
1919 struct btrfs_path *path;
1920 struct btrfs_key key;
1922 root = root->fs_info->chunk_root;
1923 path = btrfs_alloc_path();
1927 key.objectid = chunk_objectid;
1928 key.offset = chunk_offset;
1929 key.type = BTRFS_CHUNK_ITEM_KEY;
1931 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1934 else if (ret > 0) { /* Logic error or corruption */
1935 btrfs_error(root->fs_info, -ENOENT,
1936 "Failed lookup while freeing chunk.");
1941 ret = btrfs_del_item(trans, root, path);
1943 btrfs_error(root->fs_info, ret,
1944 "Failed to delete chunk item.");
1946 btrfs_free_path(path);
1950 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
1953 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
1954 struct btrfs_disk_key *disk_key;
1955 struct btrfs_chunk *chunk;
1962 struct btrfs_key key;
1964 array_size = btrfs_super_sys_array_size(super_copy);
1966 ptr = super_copy->sys_chunk_array;
1969 while (cur < array_size) {
1970 disk_key = (struct btrfs_disk_key *)ptr;
1971 btrfs_disk_key_to_cpu(&key, disk_key);
1973 len = sizeof(*disk_key);
1975 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1976 chunk = (struct btrfs_chunk *)(ptr + len);
1977 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1978 len += btrfs_chunk_item_size(num_stripes);
1983 if (key.objectid == chunk_objectid &&
1984 key.offset == chunk_offset) {
1985 memmove(ptr, ptr + len, array_size - (cur + len));
1987 btrfs_set_super_sys_array_size(super_copy, array_size);
1996 static int btrfs_relocate_chunk(struct btrfs_root *root,
1997 u64 chunk_tree, u64 chunk_objectid,
2000 struct extent_map_tree *em_tree;
2001 struct btrfs_root *extent_root;
2002 struct btrfs_trans_handle *trans;
2003 struct extent_map *em;
2004 struct map_lookup *map;
2008 root = root->fs_info->chunk_root;
2009 extent_root = root->fs_info->extent_root;
2010 em_tree = &root->fs_info->mapping_tree.map_tree;
2012 ret = btrfs_can_relocate(extent_root, chunk_offset);
2016 /* step one, relocate all the extents inside this chunk */
2017 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2021 trans = btrfs_start_transaction(root, 0);
2022 BUG_ON(IS_ERR(trans));
2027 * step two, delete the device extents and the
2028 * chunk tree entries
2030 read_lock(&em_tree->lock);
2031 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2032 read_unlock(&em_tree->lock);
2034 BUG_ON(!em || em->start > chunk_offset ||
2035 em->start + em->len < chunk_offset);
2036 map = (struct map_lookup *)em->bdev;
2038 for (i = 0; i < map->num_stripes; i++) {
2039 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
2040 map->stripes[i].physical);
2043 if (map->stripes[i].dev) {
2044 ret = btrfs_update_device(trans, map->stripes[i].dev);
2048 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2053 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2055 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2056 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2060 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2063 write_lock(&em_tree->lock);
2064 remove_extent_mapping(em_tree, em);
2065 write_unlock(&em_tree->lock);
2070 /* once for the tree */
2071 free_extent_map(em);
2073 free_extent_map(em);
2075 unlock_chunks(root);
2076 btrfs_end_transaction(trans, root);
2080 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2082 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2083 struct btrfs_path *path;
2084 struct extent_buffer *leaf;
2085 struct btrfs_chunk *chunk;
2086 struct btrfs_key key;
2087 struct btrfs_key found_key;
2088 u64 chunk_tree = chunk_root->root_key.objectid;
2090 bool retried = false;
2094 path = btrfs_alloc_path();
2099 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2100 key.offset = (u64)-1;
2101 key.type = BTRFS_CHUNK_ITEM_KEY;
2104 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2107 BUG_ON(ret == 0); /* Corruption */
2109 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2116 leaf = path->nodes[0];
2117 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2119 chunk = btrfs_item_ptr(leaf, path->slots[0],
2120 struct btrfs_chunk);
2121 chunk_type = btrfs_chunk_type(leaf, chunk);
2122 btrfs_release_path(path);
2124 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2125 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2134 if (found_key.offset == 0)
2136 key.offset = found_key.offset - 1;
2139 if (failed && !retried) {
2143 } else if (failed && retried) {
2148 btrfs_free_path(path);
2152 static int insert_balance_item(struct btrfs_root *root,
2153 struct btrfs_balance_control *bctl)
2155 struct btrfs_trans_handle *trans;
2156 struct btrfs_balance_item *item;
2157 struct btrfs_disk_balance_args disk_bargs;
2158 struct btrfs_path *path;
2159 struct extent_buffer *leaf;
2160 struct btrfs_key key;
2163 path = btrfs_alloc_path();
2167 trans = btrfs_start_transaction(root, 0);
2168 if (IS_ERR(trans)) {
2169 btrfs_free_path(path);
2170 return PTR_ERR(trans);
2173 key.objectid = BTRFS_BALANCE_OBJECTID;
2174 key.type = BTRFS_BALANCE_ITEM_KEY;
2177 ret = btrfs_insert_empty_item(trans, root, path, &key,
2182 leaf = path->nodes[0];
2183 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2185 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2187 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2188 btrfs_set_balance_data(leaf, item, &disk_bargs);
2189 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2190 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2191 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2192 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2194 btrfs_set_balance_flags(leaf, item, bctl->flags);
2196 btrfs_mark_buffer_dirty(leaf);
2198 btrfs_free_path(path);
2199 err = btrfs_commit_transaction(trans, root);
2205 static int del_balance_item(struct btrfs_root *root)
2207 struct btrfs_trans_handle *trans;
2208 struct btrfs_path *path;
2209 struct btrfs_key key;
2212 path = btrfs_alloc_path();
2216 trans = btrfs_start_transaction(root, 0);
2217 if (IS_ERR(trans)) {
2218 btrfs_free_path(path);
2219 return PTR_ERR(trans);
2222 key.objectid = BTRFS_BALANCE_OBJECTID;
2223 key.type = BTRFS_BALANCE_ITEM_KEY;
2226 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2234 ret = btrfs_del_item(trans, root, path);
2236 btrfs_free_path(path);
2237 err = btrfs_commit_transaction(trans, root);
2244 * This is a heuristic used to reduce the number of chunks balanced on
2245 * resume after balance was interrupted.
2247 static void update_balance_args(struct btrfs_balance_control *bctl)
2250 * Turn on soft mode for chunk types that were being converted.
2252 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2253 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2254 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2255 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2256 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2257 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2260 * Turn on usage filter if is not already used. The idea is
2261 * that chunks that we have already balanced should be
2262 * reasonably full. Don't do it for chunks that are being
2263 * converted - that will keep us from relocating unconverted
2264 * (albeit full) chunks.
2266 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2267 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2268 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2269 bctl->data.usage = 90;
2271 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2272 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2273 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2274 bctl->sys.usage = 90;
2276 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2277 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2278 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2279 bctl->meta.usage = 90;
2284 * Should be called with both balance and volume mutexes held to
2285 * serialize other volume operations (add_dev/rm_dev/resize) with
2286 * restriper. Same goes for unset_balance_control.
2288 static void set_balance_control(struct btrfs_balance_control *bctl)
2290 struct btrfs_fs_info *fs_info = bctl->fs_info;
2292 BUG_ON(fs_info->balance_ctl);
2294 spin_lock(&fs_info->balance_lock);
2295 fs_info->balance_ctl = bctl;
2296 spin_unlock(&fs_info->balance_lock);
2299 static void unset_balance_control(struct btrfs_fs_info *fs_info)
2301 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2303 BUG_ON(!fs_info->balance_ctl);
2305 spin_lock(&fs_info->balance_lock);
2306 fs_info->balance_ctl = NULL;
2307 spin_unlock(&fs_info->balance_lock);
2313 * Balance filters. Return 1 if chunk should be filtered out
2314 * (should not be balanced).
2316 static int chunk_profiles_filter(u64 chunk_type,
2317 struct btrfs_balance_args *bargs)
2319 chunk_type = chunk_to_extended(chunk_type) &
2320 BTRFS_EXTENDED_PROFILE_MASK;
2322 if (bargs->profiles & chunk_type)
2328 static u64 div_factor_fine(u64 num, int factor)
2340 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2341 struct btrfs_balance_args *bargs)
2343 struct btrfs_block_group_cache *cache;
2344 u64 chunk_used, user_thresh;
2347 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2348 chunk_used = btrfs_block_group_used(&cache->item);
2350 user_thresh = div_factor_fine(cache->key.offset, bargs->usage);
2351 if (chunk_used < user_thresh)
2354 btrfs_put_block_group(cache);
2358 static int chunk_devid_filter(struct extent_buffer *leaf,
2359 struct btrfs_chunk *chunk,
2360 struct btrfs_balance_args *bargs)
2362 struct btrfs_stripe *stripe;
2363 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2366 for (i = 0; i < num_stripes; i++) {
2367 stripe = btrfs_stripe_nr(chunk, i);
2368 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2375 /* [pstart, pend) */
2376 static int chunk_drange_filter(struct extent_buffer *leaf,
2377 struct btrfs_chunk *chunk,
2379 struct btrfs_balance_args *bargs)
2381 struct btrfs_stripe *stripe;
2382 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2388 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2391 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2392 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10))
2396 factor = num_stripes / factor;
2398 for (i = 0; i < num_stripes; i++) {
2399 stripe = btrfs_stripe_nr(chunk, i);
2400 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2403 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2404 stripe_length = btrfs_chunk_length(leaf, chunk);
2405 do_div(stripe_length, factor);
2407 if (stripe_offset < bargs->pend &&
2408 stripe_offset + stripe_length > bargs->pstart)
2415 /* [vstart, vend) */
2416 static int chunk_vrange_filter(struct extent_buffer *leaf,
2417 struct btrfs_chunk *chunk,
2419 struct btrfs_balance_args *bargs)
2421 if (chunk_offset < bargs->vend &&
2422 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2423 /* at least part of the chunk is inside this vrange */
2429 static int chunk_soft_convert_filter(u64 chunk_type,
2430 struct btrfs_balance_args *bargs)
2432 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2435 chunk_type = chunk_to_extended(chunk_type) &
2436 BTRFS_EXTENDED_PROFILE_MASK;
2438 if (bargs->target == chunk_type)
2444 static int should_balance_chunk(struct btrfs_root *root,
2445 struct extent_buffer *leaf,
2446 struct btrfs_chunk *chunk, u64 chunk_offset)
2448 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2449 struct btrfs_balance_args *bargs = NULL;
2450 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2453 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2454 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
2458 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
2459 bargs = &bctl->data;
2460 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
2462 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
2463 bargs = &bctl->meta;
2465 /* profiles filter */
2466 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
2467 chunk_profiles_filter(chunk_type, bargs)) {
2472 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
2473 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
2478 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
2479 chunk_devid_filter(leaf, chunk, bargs)) {
2483 /* drange filter, makes sense only with devid filter */
2484 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
2485 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
2490 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
2491 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
2495 /* soft profile changing mode */
2496 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
2497 chunk_soft_convert_filter(chunk_type, bargs)) {
2504 static u64 div_factor(u64 num, int factor)
2513 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
2515 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2516 struct btrfs_root *chunk_root = fs_info->chunk_root;
2517 struct btrfs_root *dev_root = fs_info->dev_root;
2518 struct list_head *devices;
2519 struct btrfs_device *device;
2522 struct btrfs_chunk *chunk;
2523 struct btrfs_path *path;
2524 struct btrfs_key key;
2525 struct btrfs_key found_key;
2526 struct btrfs_trans_handle *trans;
2527 struct extent_buffer *leaf;
2530 int enospc_errors = 0;
2531 bool counting = true;
2533 /* step one make some room on all the devices */
2534 devices = &fs_info->fs_devices->devices;
2535 list_for_each_entry(device, devices, dev_list) {
2536 old_size = device->total_bytes;
2537 size_to_free = div_factor(old_size, 1);
2538 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2539 if (!device->writeable ||
2540 device->total_bytes - device->bytes_used > size_to_free)
2543 ret = btrfs_shrink_device(device, old_size - size_to_free);
2548 trans = btrfs_start_transaction(dev_root, 0);
2549 BUG_ON(IS_ERR(trans));
2551 ret = btrfs_grow_device(trans, device, old_size);
2554 btrfs_end_transaction(trans, dev_root);
2557 /* step two, relocate all the chunks */
2558 path = btrfs_alloc_path();
2564 /* zero out stat counters */
2565 spin_lock(&fs_info->balance_lock);
2566 memset(&bctl->stat, 0, sizeof(bctl->stat));
2567 spin_unlock(&fs_info->balance_lock);
2569 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2570 key.offset = (u64)-1;
2571 key.type = BTRFS_CHUNK_ITEM_KEY;
2574 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
2575 atomic_read(&fs_info->balance_cancel_req)) {
2580 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2585 * this shouldn't happen, it means the last relocate
2589 BUG(); /* FIXME break ? */
2591 ret = btrfs_previous_item(chunk_root, path, 0,
2592 BTRFS_CHUNK_ITEM_KEY);
2598 leaf = path->nodes[0];
2599 slot = path->slots[0];
2600 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2602 if (found_key.objectid != key.objectid)
2605 /* chunk zero is special */
2606 if (found_key.offset == 0)
2609 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2612 spin_lock(&fs_info->balance_lock);
2613 bctl->stat.considered++;
2614 spin_unlock(&fs_info->balance_lock);
2617 ret = should_balance_chunk(chunk_root, leaf, chunk,
2619 btrfs_release_path(path);
2624 spin_lock(&fs_info->balance_lock);
2625 bctl->stat.expected++;
2626 spin_unlock(&fs_info->balance_lock);
2630 ret = btrfs_relocate_chunk(chunk_root,
2631 chunk_root->root_key.objectid,
2634 if (ret && ret != -ENOSPC)
2636 if (ret == -ENOSPC) {
2639 spin_lock(&fs_info->balance_lock);
2640 bctl->stat.completed++;
2641 spin_unlock(&fs_info->balance_lock);
2644 key.offset = found_key.offset - 1;
2648 btrfs_release_path(path);
2653 btrfs_free_path(path);
2654 if (enospc_errors) {
2655 printk(KERN_INFO "btrfs: %d enospc errors during balance\n",
2665 * alloc_profile_is_valid - see if a given profile is valid and reduced
2666 * @flags: profile to validate
2667 * @extended: if true @flags is treated as an extended profile
2669 static int alloc_profile_is_valid(u64 flags, int extended)
2671 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
2672 BTRFS_BLOCK_GROUP_PROFILE_MASK);
2674 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
2676 /* 1) check that all other bits are zeroed */
2680 /* 2) see if profile is reduced */
2682 return !extended; /* "0" is valid for usual profiles */
2684 /* true if exactly one bit set */
2685 return (flags & (flags - 1)) == 0;
2688 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
2690 /* cancel requested || normal exit path */
2691 return atomic_read(&fs_info->balance_cancel_req) ||
2692 (atomic_read(&fs_info->balance_pause_req) == 0 &&
2693 atomic_read(&fs_info->balance_cancel_req) == 0);
2696 static void __cancel_balance(struct btrfs_fs_info *fs_info)
2700 unset_balance_control(fs_info);
2701 ret = del_balance_item(fs_info->tree_root);
2705 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
2706 struct btrfs_ioctl_balance_args *bargs);
2709 * Should be called with both balance and volume mutexes held
2711 int btrfs_balance(struct btrfs_balance_control *bctl,
2712 struct btrfs_ioctl_balance_args *bargs)
2714 struct btrfs_fs_info *fs_info = bctl->fs_info;
2719 if (btrfs_fs_closing(fs_info) ||
2720 atomic_read(&fs_info->balance_pause_req) ||
2721 atomic_read(&fs_info->balance_cancel_req)) {
2726 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
2727 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
2731 * In case of mixed groups both data and meta should be picked,
2732 * and identical options should be given for both of them.
2734 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
2735 if (mixed && (bctl->flags & allowed)) {
2736 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
2737 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
2738 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
2739 printk(KERN_ERR "btrfs: with mixed groups data and "
2740 "metadata balance options must be the same\n");
2746 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
2747 if (fs_info->fs_devices->num_devices == 1)
2748 allowed |= BTRFS_BLOCK_GROUP_DUP;
2749 else if (fs_info->fs_devices->num_devices < 4)
2750 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
2752 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1 |
2753 BTRFS_BLOCK_GROUP_RAID10);
2755 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2756 (!alloc_profile_is_valid(bctl->data.target, 1) ||
2757 (bctl->data.target & ~allowed))) {
2758 printk(KERN_ERR "btrfs: unable to start balance with target "
2759 "data profile %llu\n",
2760 (unsigned long long)bctl->data.target);
2764 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2765 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
2766 (bctl->meta.target & ~allowed))) {
2767 printk(KERN_ERR "btrfs: unable to start balance with target "
2768 "metadata profile %llu\n",
2769 (unsigned long long)bctl->meta.target);
2773 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2774 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
2775 (bctl->sys.target & ~allowed))) {
2776 printk(KERN_ERR "btrfs: unable to start balance with target "
2777 "system profile %llu\n",
2778 (unsigned long long)bctl->sys.target);
2783 /* allow dup'ed data chunks only in mixed mode */
2784 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2785 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
2786 printk(KERN_ERR "btrfs: dup for data is not allowed\n");
2791 /* allow to reduce meta or sys integrity only if force set */
2792 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
2793 BTRFS_BLOCK_GROUP_RAID10;
2794 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2795 (fs_info->avail_system_alloc_bits & allowed) &&
2796 !(bctl->sys.target & allowed)) ||
2797 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
2798 (fs_info->avail_metadata_alloc_bits & allowed) &&
2799 !(bctl->meta.target & allowed))) {
2800 if (bctl->flags & BTRFS_BALANCE_FORCE) {
2801 printk(KERN_INFO "btrfs: force reducing metadata "
2804 printk(KERN_ERR "btrfs: balance will reduce metadata "
2805 "integrity, use force if you want this\n");
2811 ret = insert_balance_item(fs_info->tree_root, bctl);
2812 if (ret && ret != -EEXIST)
2815 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
2816 BUG_ON(ret == -EEXIST);
2817 set_balance_control(bctl);
2819 BUG_ON(ret != -EEXIST);
2820 spin_lock(&fs_info->balance_lock);
2821 update_balance_args(bctl);
2822 spin_unlock(&fs_info->balance_lock);
2825 atomic_inc(&fs_info->balance_running);
2826 mutex_unlock(&fs_info->balance_mutex);
2828 ret = __btrfs_balance(fs_info);
2830 mutex_lock(&fs_info->balance_mutex);
2831 atomic_dec(&fs_info->balance_running);
2834 memset(bargs, 0, sizeof(*bargs));
2835 update_ioctl_balance_args(fs_info, 0, bargs);
2838 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
2839 balance_need_close(fs_info)) {
2840 __cancel_balance(fs_info);
2843 wake_up(&fs_info->balance_wait_q);
2847 if (bctl->flags & BTRFS_BALANCE_RESUME)
2848 __cancel_balance(fs_info);
2854 static int balance_kthread(void *data)
2856 struct btrfs_fs_info *fs_info = data;
2859 mutex_lock(&fs_info->volume_mutex);
2860 mutex_lock(&fs_info->balance_mutex);
2862 if (fs_info->balance_ctl) {
2863 printk(KERN_INFO "btrfs: continuing balance\n");
2864 ret = btrfs_balance(fs_info->balance_ctl, NULL);
2867 mutex_unlock(&fs_info->balance_mutex);
2868 mutex_unlock(&fs_info->volume_mutex);
2873 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
2875 struct task_struct *tsk;
2877 spin_lock(&fs_info->balance_lock);
2878 if (!fs_info->balance_ctl) {
2879 spin_unlock(&fs_info->balance_lock);
2882 spin_unlock(&fs_info->balance_lock);
2884 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
2885 printk(KERN_INFO "btrfs: force skipping balance\n");
2889 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
2891 return PTR_ERR(tsk);
2896 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
2898 struct btrfs_balance_control *bctl;
2899 struct btrfs_balance_item *item;
2900 struct btrfs_disk_balance_args disk_bargs;
2901 struct btrfs_path *path;
2902 struct extent_buffer *leaf;
2903 struct btrfs_key key;
2906 path = btrfs_alloc_path();
2910 key.objectid = BTRFS_BALANCE_OBJECTID;
2911 key.type = BTRFS_BALANCE_ITEM_KEY;
2914 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
2917 if (ret > 0) { /* ret = -ENOENT; */
2922 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
2928 leaf = path->nodes[0];
2929 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2931 bctl->fs_info = fs_info;
2932 bctl->flags = btrfs_balance_flags(leaf, item);
2933 bctl->flags |= BTRFS_BALANCE_RESUME;
2935 btrfs_balance_data(leaf, item, &disk_bargs);
2936 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
2937 btrfs_balance_meta(leaf, item, &disk_bargs);
2938 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
2939 btrfs_balance_sys(leaf, item, &disk_bargs);
2940 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
2942 mutex_lock(&fs_info->volume_mutex);
2943 mutex_lock(&fs_info->balance_mutex);
2945 set_balance_control(bctl);
2947 mutex_unlock(&fs_info->balance_mutex);
2948 mutex_unlock(&fs_info->volume_mutex);
2950 btrfs_free_path(path);
2954 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
2958 mutex_lock(&fs_info->balance_mutex);
2959 if (!fs_info->balance_ctl) {
2960 mutex_unlock(&fs_info->balance_mutex);
2964 if (atomic_read(&fs_info->balance_running)) {
2965 atomic_inc(&fs_info->balance_pause_req);
2966 mutex_unlock(&fs_info->balance_mutex);
2968 wait_event(fs_info->balance_wait_q,
2969 atomic_read(&fs_info->balance_running) == 0);
2971 mutex_lock(&fs_info->balance_mutex);
2972 /* we are good with balance_ctl ripped off from under us */
2973 BUG_ON(atomic_read(&fs_info->balance_running));
2974 atomic_dec(&fs_info->balance_pause_req);
2979 mutex_unlock(&fs_info->balance_mutex);
2983 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
2985 mutex_lock(&fs_info->balance_mutex);
2986 if (!fs_info->balance_ctl) {
2987 mutex_unlock(&fs_info->balance_mutex);
2991 atomic_inc(&fs_info->balance_cancel_req);
2993 * if we are running just wait and return, balance item is
2994 * deleted in btrfs_balance in this case
2996 if (atomic_read(&fs_info->balance_running)) {
2997 mutex_unlock(&fs_info->balance_mutex);
2998 wait_event(fs_info->balance_wait_q,
2999 atomic_read(&fs_info->balance_running) == 0);
3000 mutex_lock(&fs_info->balance_mutex);
3002 /* __cancel_balance needs volume_mutex */
3003 mutex_unlock(&fs_info->balance_mutex);
3004 mutex_lock(&fs_info->volume_mutex);
3005 mutex_lock(&fs_info->balance_mutex);
3007 if (fs_info->balance_ctl)
3008 __cancel_balance(fs_info);
3010 mutex_unlock(&fs_info->volume_mutex);
3013 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3014 atomic_dec(&fs_info->balance_cancel_req);
3015 mutex_unlock(&fs_info->balance_mutex);
3020 * shrinking a device means finding all of the device extents past
3021 * the new size, and then following the back refs to the chunks.
3022 * The chunk relocation code actually frees the device extent
3024 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3026 struct btrfs_trans_handle *trans;
3027 struct btrfs_root *root = device->dev_root;
3028 struct btrfs_dev_extent *dev_extent = NULL;
3029 struct btrfs_path *path;
3037 bool retried = false;
3038 struct extent_buffer *l;
3039 struct btrfs_key key;
3040 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3041 u64 old_total = btrfs_super_total_bytes(super_copy);
3042 u64 old_size = device->total_bytes;
3043 u64 diff = device->total_bytes - new_size;
3045 if (new_size >= device->total_bytes)
3048 path = btrfs_alloc_path();
3056 device->total_bytes = new_size;
3057 if (device->writeable) {
3058 device->fs_devices->total_rw_bytes -= diff;
3059 spin_lock(&root->fs_info->free_chunk_lock);
3060 root->fs_info->free_chunk_space -= diff;
3061 spin_unlock(&root->fs_info->free_chunk_lock);
3063 unlock_chunks(root);
3066 key.objectid = device->devid;
3067 key.offset = (u64)-1;
3068 key.type = BTRFS_DEV_EXTENT_KEY;
3071 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3075 ret = btrfs_previous_item(root, path, 0, key.type);
3080 btrfs_release_path(path);
3085 slot = path->slots[0];
3086 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3088 if (key.objectid != device->devid) {
3089 btrfs_release_path(path);
3093 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3094 length = btrfs_dev_extent_length(l, dev_extent);
3096 if (key.offset + length <= new_size) {
3097 btrfs_release_path(path);
3101 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3102 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3103 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3104 btrfs_release_path(path);
3106 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3108 if (ret && ret != -ENOSPC)
3112 } while (key.offset-- > 0);
3114 if (failed && !retried) {
3118 } else if (failed && retried) {
3122 device->total_bytes = old_size;
3123 if (device->writeable)
3124 device->fs_devices->total_rw_bytes += diff;
3125 spin_lock(&root->fs_info->free_chunk_lock);
3126 root->fs_info->free_chunk_space += diff;
3127 spin_unlock(&root->fs_info->free_chunk_lock);
3128 unlock_chunks(root);
3132 /* Shrinking succeeded, else we would be at "done". */
3133 trans = btrfs_start_transaction(root, 0);
3134 if (IS_ERR(trans)) {
3135 ret = PTR_ERR(trans);
3141 device->disk_total_bytes = new_size;
3142 /* Now btrfs_update_device() will change the on-disk size. */
3143 ret = btrfs_update_device(trans, device);
3145 unlock_chunks(root);
3146 btrfs_end_transaction(trans, root);
3149 WARN_ON(diff > old_total);
3150 btrfs_set_super_total_bytes(super_copy, old_total - diff);
3151 unlock_chunks(root);
3152 btrfs_end_transaction(trans, root);
3154 btrfs_free_path(path);
3158 static int btrfs_add_system_chunk(struct btrfs_root *root,
3159 struct btrfs_key *key,
3160 struct btrfs_chunk *chunk, int item_size)
3162 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3163 struct btrfs_disk_key disk_key;
3167 array_size = btrfs_super_sys_array_size(super_copy);
3168 if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
3171 ptr = super_copy->sys_chunk_array + array_size;
3172 btrfs_cpu_key_to_disk(&disk_key, key);
3173 memcpy(ptr, &disk_key, sizeof(disk_key));
3174 ptr += sizeof(disk_key);
3175 memcpy(ptr, chunk, item_size);
3176 item_size += sizeof(disk_key);
3177 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
3182 * sort the devices in descending order by max_avail, total_avail
3184 static int btrfs_cmp_device_info(const void *a, const void *b)
3186 const struct btrfs_device_info *di_a = a;
3187 const struct btrfs_device_info *di_b = b;
3189 if (di_a->max_avail > di_b->max_avail)
3191 if (di_a->max_avail < di_b->max_avail)
3193 if (di_a->total_avail > di_b->total_avail)
3195 if (di_a->total_avail < di_b->total_avail)
3200 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3201 struct btrfs_root *extent_root,
3202 struct map_lookup **map_ret,
3203 u64 *num_bytes_out, u64 *stripe_size_out,
3204 u64 start, u64 type)
3206 struct btrfs_fs_info *info = extent_root->fs_info;
3207 struct btrfs_fs_devices *fs_devices = info->fs_devices;
3208 struct list_head *cur;
3209 struct map_lookup *map = NULL;
3210 struct extent_map_tree *em_tree;
3211 struct extent_map *em;
3212 struct btrfs_device_info *devices_info = NULL;
3214 int num_stripes; /* total number of stripes to allocate */
3215 int sub_stripes; /* sub_stripes info for map */
3216 int dev_stripes; /* stripes per dev */
3217 int devs_max; /* max devs to use */
3218 int devs_min; /* min devs needed */
3219 int devs_increment; /* ndevs has to be a multiple of this */
3220 int ncopies; /* how many copies to data has */
3222 u64 max_stripe_size;
3230 BUG_ON(!alloc_profile_is_valid(type, 0));
3232 if (list_empty(&fs_devices->alloc_list))
3239 devs_max = 0; /* 0 == as many as possible */
3243 * define the properties of each RAID type.
3244 * FIXME: move this to a global table and use it in all RAID
3247 if (type & (BTRFS_BLOCK_GROUP_DUP)) {
3251 } else if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
3253 } else if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
3258 } else if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
3267 if (type & BTRFS_BLOCK_GROUP_DATA) {
3268 max_stripe_size = 1024 * 1024 * 1024;
3269 max_chunk_size = 10 * max_stripe_size;
3270 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
3271 /* for larger filesystems, use larger metadata chunks */
3272 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
3273 max_stripe_size = 1024 * 1024 * 1024;
3275 max_stripe_size = 256 * 1024 * 1024;
3276 max_chunk_size = max_stripe_size;
3277 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
3278 max_stripe_size = 32 * 1024 * 1024;
3279 max_chunk_size = 2 * max_stripe_size;
3281 printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
3286 /* we don't want a chunk larger than 10% of writeable space */
3287 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
3290 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
3295 cur = fs_devices->alloc_list.next;
3298 * in the first pass through the devices list, we gather information
3299 * about the available holes on each device.
3302 while (cur != &fs_devices->alloc_list) {
3303 struct btrfs_device *device;
3307 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
3311 if (!device->writeable) {
3313 "btrfs: read-only device in alloc_list\n");
3318 if (!device->in_fs_metadata)
3321 if (device->total_bytes > device->bytes_used)
3322 total_avail = device->total_bytes - device->bytes_used;
3326 /* If there is no space on this device, skip it. */
3327 if (total_avail == 0)
3330 ret = find_free_dev_extent(device,
3331 max_stripe_size * dev_stripes,
3332 &dev_offset, &max_avail);
3333 if (ret && ret != -ENOSPC)
3337 max_avail = max_stripe_size * dev_stripes;
3339 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
3342 devices_info[ndevs].dev_offset = dev_offset;
3343 devices_info[ndevs].max_avail = max_avail;
3344 devices_info[ndevs].total_avail = total_avail;
3345 devices_info[ndevs].dev = device;
3350 * now sort the devices by hole size / available space
3352 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
3353 btrfs_cmp_device_info, NULL);
3355 /* round down to number of usable stripes */
3356 ndevs -= ndevs % devs_increment;
3358 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
3363 if (devs_max && ndevs > devs_max)
3366 * the primary goal is to maximize the number of stripes, so use as many
3367 * devices as possible, even if the stripes are not maximum sized.
3369 stripe_size = devices_info[ndevs-1].max_avail;
3370 num_stripes = ndevs * dev_stripes;
3372 if (stripe_size * ndevs > max_chunk_size * ncopies) {
3373 stripe_size = max_chunk_size * ncopies;
3374 do_div(stripe_size, ndevs);
3377 do_div(stripe_size, dev_stripes);
3379 /* align to BTRFS_STRIPE_LEN */
3380 do_div(stripe_size, BTRFS_STRIPE_LEN);
3381 stripe_size *= BTRFS_STRIPE_LEN;
3383 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
3388 map->num_stripes = num_stripes;
3390 for (i = 0; i < ndevs; ++i) {
3391 for (j = 0; j < dev_stripes; ++j) {
3392 int s = i * dev_stripes + j;
3393 map->stripes[s].dev = devices_info[i].dev;
3394 map->stripes[s].physical = devices_info[i].dev_offset +
3398 map->sector_size = extent_root->sectorsize;
3399 map->stripe_len = BTRFS_STRIPE_LEN;
3400 map->io_align = BTRFS_STRIPE_LEN;
3401 map->io_width = BTRFS_STRIPE_LEN;
3403 map->sub_stripes = sub_stripes;
3406 num_bytes = stripe_size * (num_stripes / ncopies);
3408 *stripe_size_out = stripe_size;
3409 *num_bytes_out = num_bytes;
3411 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
3413 em = alloc_extent_map();
3418 em->bdev = (struct block_device *)map;
3420 em->len = num_bytes;
3421 em->block_start = 0;
3422 em->block_len = em->len;
3424 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
3425 write_lock(&em_tree->lock);
3426 ret = add_extent_mapping(em_tree, em);
3427 write_unlock(&em_tree->lock);
3428 free_extent_map(em);
3432 ret = btrfs_make_block_group(trans, extent_root, 0, type,
3433 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3438 for (i = 0; i < map->num_stripes; ++i) {
3439 struct btrfs_device *device;
3442 device = map->stripes[i].dev;
3443 dev_offset = map->stripes[i].physical;
3445 ret = btrfs_alloc_dev_extent(trans, device,
3446 info->chunk_root->root_key.objectid,
3447 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3448 start, dev_offset, stripe_size);
3450 btrfs_abort_transaction(trans, extent_root, ret);
3455 kfree(devices_info);
3460 kfree(devices_info);
3464 static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
3465 struct btrfs_root *extent_root,
3466 struct map_lookup *map, u64 chunk_offset,
3467 u64 chunk_size, u64 stripe_size)
3470 struct btrfs_key key;
3471 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3472 struct btrfs_device *device;
3473 struct btrfs_chunk *chunk;
3474 struct btrfs_stripe *stripe;
3475 size_t item_size = btrfs_chunk_item_size(map->num_stripes);
3479 chunk = kzalloc(item_size, GFP_NOFS);
3484 while (index < map->num_stripes) {
3485 device = map->stripes[index].dev;
3486 device->bytes_used += stripe_size;
3487 ret = btrfs_update_device(trans, device);
3493 spin_lock(&extent_root->fs_info->free_chunk_lock);
3494 extent_root->fs_info->free_chunk_space -= (stripe_size *
3496 spin_unlock(&extent_root->fs_info->free_chunk_lock);
3499 stripe = &chunk->stripe;
3500 while (index < map->num_stripes) {
3501 device = map->stripes[index].dev;
3502 dev_offset = map->stripes[index].physical;
3504 btrfs_set_stack_stripe_devid(stripe, device->devid);
3505 btrfs_set_stack_stripe_offset(stripe, dev_offset);
3506 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
3511 btrfs_set_stack_chunk_length(chunk, chunk_size);
3512 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
3513 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
3514 btrfs_set_stack_chunk_type(chunk, map->type);
3515 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
3516 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
3517 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
3518 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
3519 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
3521 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3522 key.type = BTRFS_CHUNK_ITEM_KEY;
3523 key.offset = chunk_offset;
3525 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
3527 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3529 * TODO: Cleanup of inserted chunk root in case of
3532 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
3542 * Chunk allocation falls into two parts. The first part does works
3543 * that make the new allocated chunk useable, but not do any operation
3544 * that modifies the chunk tree. The second part does the works that
3545 * require modifying the chunk tree. This division is important for the
3546 * bootstrap process of adding storage to a seed btrfs.
3548 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3549 struct btrfs_root *extent_root, u64 type)
3554 struct map_lookup *map;
3555 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
3558 ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
3563 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3564 &stripe_size, chunk_offset, type);
3568 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3569 chunk_size, stripe_size);
3575 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
3576 struct btrfs_root *root,
3577 struct btrfs_device *device)
3580 u64 sys_chunk_offset;
3584 u64 sys_stripe_size;
3586 struct map_lookup *map;
3587 struct map_lookup *sys_map;
3588 struct btrfs_fs_info *fs_info = root->fs_info;
3589 struct btrfs_root *extent_root = fs_info->extent_root;
3592 ret = find_next_chunk(fs_info->chunk_root,
3593 BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
3597 alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
3598 fs_info->avail_metadata_alloc_bits;
3599 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3601 ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
3602 &stripe_size, chunk_offset, alloc_profile);
3606 sys_chunk_offset = chunk_offset + chunk_size;
3608 alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
3609 fs_info->avail_system_alloc_bits;
3610 alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
3612 ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
3613 &sys_chunk_size, &sys_stripe_size,
3614 sys_chunk_offset, alloc_profile);
3618 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
3623 * Modifying chunk tree needs allocating new blocks from both
3624 * system block group and metadata block group. So we only can
3625 * do operations require modifying the chunk tree after both
3626 * block groups were created.
3628 ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
3629 chunk_size, stripe_size);
3633 ret = __finish_chunk_alloc(trans, extent_root, sys_map,
3634 sys_chunk_offset, sys_chunk_size,
3642 btrfs_abort_transaction(trans, root, ret);
3646 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
3648 struct extent_map *em;
3649 struct map_lookup *map;
3650 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
3654 read_lock(&map_tree->map_tree.lock);
3655 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
3656 read_unlock(&map_tree->map_tree.lock);
3660 if (btrfs_test_opt(root, DEGRADED)) {
3661 free_extent_map(em);
3665 map = (struct map_lookup *)em->bdev;
3666 for (i = 0; i < map->num_stripes; i++) {
3667 if (!map->stripes[i].dev->writeable) {
3672 free_extent_map(em);
3676 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
3678 extent_map_tree_init(&tree->map_tree);
3681 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
3683 struct extent_map *em;
3686 write_lock(&tree->map_tree.lock);
3687 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
3689 remove_extent_mapping(&tree->map_tree, em);
3690 write_unlock(&tree->map_tree.lock);
3695 free_extent_map(em);
3696 /* once for the tree */
3697 free_extent_map(em);
3701 int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
3703 struct extent_map *em;
3704 struct map_lookup *map;
3705 struct extent_map_tree *em_tree = &map_tree->map_tree;
3708 read_lock(&em_tree->lock);
3709 em = lookup_extent_mapping(em_tree, logical, len);
3710 read_unlock(&em_tree->lock);
3713 BUG_ON(em->start > logical || em->start + em->len < logical);
3714 map = (struct map_lookup *)em->bdev;
3715 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
3716 ret = map->num_stripes;
3717 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
3718 ret = map->sub_stripes;
3721 free_extent_map(em);
3725 static int find_live_mirror(struct map_lookup *map, int first, int num,
3729 if (map->stripes[optimal].dev->bdev)
3731 for (i = first; i < first + num; i++) {
3732 if (map->stripes[i].dev->bdev)
3735 /* we couldn't find one that doesn't fail. Just return something
3736 * and the io error handling code will clean up eventually
3741 static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3742 u64 logical, u64 *length,
3743 struct btrfs_bio **bbio_ret,
3746 struct extent_map *em;
3747 struct map_lookup *map;
3748 struct extent_map_tree *em_tree = &map_tree->map_tree;
3751 u64 stripe_end_offset;
3760 struct btrfs_bio *bbio = NULL;
3762 read_lock(&em_tree->lock);
3763 em = lookup_extent_mapping(em_tree, logical, *length);
3764 read_unlock(&em_tree->lock);
3767 printk(KERN_CRIT "unable to find logical %llu len %llu\n",
3768 (unsigned long long)logical,
3769 (unsigned long long)*length);
3773 BUG_ON(em->start > logical || em->start + em->len < logical);
3774 map = (struct map_lookup *)em->bdev;
3775 offset = logical - em->start;
3777 if (mirror_num > map->num_stripes)
3782 * stripe_nr counts the total number of stripes we have to stride
3783 * to get to this block
3785 do_div(stripe_nr, map->stripe_len);
3787 stripe_offset = stripe_nr * map->stripe_len;
3788 BUG_ON(offset < stripe_offset);
3790 /* stripe_offset is the offset of this block in its stripe*/
3791 stripe_offset = offset - stripe_offset;
3793 if (rw & REQ_DISCARD)
3794 *length = min_t(u64, em->len - offset, *length);
3795 else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
3796 /* we limit the length of each bio to what fits in a stripe */
3797 *length = min_t(u64, em->len - offset,
3798 map->stripe_len - stripe_offset);
3800 *length = em->len - offset;
3808 stripe_nr_orig = stripe_nr;
3809 stripe_nr_end = (offset + *length + map->stripe_len - 1) &
3810 (~(map->stripe_len - 1));
3811 do_div(stripe_nr_end, map->stripe_len);
3812 stripe_end_offset = stripe_nr_end * map->stripe_len -
3814 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
3815 if (rw & REQ_DISCARD)
3816 num_stripes = min_t(u64, map->num_stripes,
3817 stripe_nr_end - stripe_nr_orig);
3818 stripe_index = do_div(stripe_nr, map->num_stripes);
3819 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
3820 if (rw & (REQ_WRITE | REQ_DISCARD))
3821 num_stripes = map->num_stripes;
3822 else if (mirror_num)
3823 stripe_index = mirror_num - 1;
3825 stripe_index = find_live_mirror(map, 0,
3827 current->pid % map->num_stripes);
3828 mirror_num = stripe_index + 1;
3831 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
3832 if (rw & (REQ_WRITE | REQ_DISCARD)) {
3833 num_stripes = map->num_stripes;
3834 } else if (mirror_num) {
3835 stripe_index = mirror_num - 1;
3840 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
3841 int factor = map->num_stripes / map->sub_stripes;
3843 stripe_index = do_div(stripe_nr, factor);
3844 stripe_index *= map->sub_stripes;
3847 num_stripes = map->sub_stripes;
3848 else if (rw & REQ_DISCARD)
3849 num_stripes = min_t(u64, map->sub_stripes *
3850 (stripe_nr_end - stripe_nr_orig),
3852 else if (mirror_num)
3853 stripe_index += mirror_num - 1;
3855 int old_stripe_index = stripe_index;
3856 stripe_index = find_live_mirror(map, stripe_index,
3857 map->sub_stripes, stripe_index +
3858 current->pid % map->sub_stripes);
3859 mirror_num = stripe_index - old_stripe_index + 1;
3863 * after this do_div call, stripe_nr is the number of stripes
3864 * on this device we have to walk to find the data, and
3865 * stripe_index is the number of our device in the stripe array
3867 stripe_index = do_div(stripe_nr, map->num_stripes);
3868 mirror_num = stripe_index + 1;
3870 BUG_ON(stripe_index >= map->num_stripes);
3872 bbio = kzalloc(btrfs_bio_size(num_stripes), GFP_NOFS);
3877 atomic_set(&bbio->error, 0);
3879 if (rw & REQ_DISCARD) {
3881 int sub_stripes = 0;
3882 u64 stripes_per_dev = 0;
3883 u32 remaining_stripes = 0;
3884 u32 last_stripe = 0;
3887 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
3888 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
3891 sub_stripes = map->sub_stripes;
3893 factor = map->num_stripes / sub_stripes;
3894 stripes_per_dev = div_u64_rem(stripe_nr_end -
3897 &remaining_stripes);
3898 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
3899 last_stripe *= sub_stripes;
3902 for (i = 0; i < num_stripes; i++) {
3903 bbio->stripes[i].physical =
3904 map->stripes[stripe_index].physical +
3905 stripe_offset + stripe_nr * map->stripe_len;
3906 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
3908 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
3909 BTRFS_BLOCK_GROUP_RAID10)) {
3910 bbio->stripes[i].length = stripes_per_dev *
3913 if (i / sub_stripes < remaining_stripes)
3914 bbio->stripes[i].length +=
3918 * Special for the first stripe and
3921 * |-------|...|-------|
3925 if (i < sub_stripes)
3926 bbio->stripes[i].length -=
3929 if (stripe_index >= last_stripe &&
3930 stripe_index <= (last_stripe +
3932 bbio->stripes[i].length -=
3935 if (i == sub_stripes - 1)
3938 bbio->stripes[i].length = *length;
3941 if (stripe_index == map->num_stripes) {
3942 /* This could only happen for RAID0/10 */
3948 for (i = 0; i < num_stripes; i++) {
3949 bbio->stripes[i].physical =
3950 map->stripes[stripe_index].physical +
3952 stripe_nr * map->stripe_len;
3953 bbio->stripes[i].dev =
3954 map->stripes[stripe_index].dev;
3959 if (rw & REQ_WRITE) {
3960 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
3961 BTRFS_BLOCK_GROUP_RAID10 |
3962 BTRFS_BLOCK_GROUP_DUP)) {
3968 bbio->num_stripes = num_stripes;
3969 bbio->max_errors = max_errors;
3970 bbio->mirror_num = mirror_num;
3972 free_extent_map(em);
3976 int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
3977 u64 logical, u64 *length,
3978 struct btrfs_bio **bbio_ret, int mirror_num)
3980 return __btrfs_map_block(map_tree, rw, logical, length, bbio_ret,
3984 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
3985 u64 chunk_start, u64 physical, u64 devid,
3986 u64 **logical, int *naddrs, int *stripe_len)
3988 struct extent_map_tree *em_tree = &map_tree->map_tree;
3989 struct extent_map *em;
3990 struct map_lookup *map;
3997 read_lock(&em_tree->lock);
3998 em = lookup_extent_mapping(em_tree, chunk_start, 1);
3999 read_unlock(&em_tree->lock);
4001 BUG_ON(!em || em->start != chunk_start);
4002 map = (struct map_lookup *)em->bdev;
4005 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4006 do_div(length, map->num_stripes / map->sub_stripes);
4007 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
4008 do_div(length, map->num_stripes);
4010 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
4011 BUG_ON(!buf); /* -ENOMEM */
4013 for (i = 0; i < map->num_stripes; i++) {
4014 if (devid && map->stripes[i].dev->devid != devid)
4016 if (map->stripes[i].physical > physical ||
4017 map->stripes[i].physical + length <= physical)
4020 stripe_nr = physical - map->stripes[i].physical;
4021 do_div(stripe_nr, map->stripe_len);
4023 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
4024 stripe_nr = stripe_nr * map->num_stripes + i;
4025 do_div(stripe_nr, map->sub_stripes);
4026 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
4027 stripe_nr = stripe_nr * map->num_stripes + i;
4029 bytenr = chunk_start + stripe_nr * map->stripe_len;
4030 WARN_ON(nr >= map->num_stripes);
4031 for (j = 0; j < nr; j++) {
4032 if (buf[j] == bytenr)
4036 WARN_ON(nr >= map->num_stripes);
4043 *stripe_len = map->stripe_len;
4045 free_extent_map(em);
4049 static void *merge_stripe_index_into_bio_private(void *bi_private,
4050 unsigned int stripe_index)
4053 * with single, dup, RAID0, RAID1 and RAID10, stripe_index is
4055 * The alternative solution (instead of stealing bits from the
4056 * pointer) would be to allocate an intermediate structure
4057 * that contains the old private pointer plus the stripe_index.
4059 BUG_ON((((uintptr_t)bi_private) & 3) != 0);
4060 BUG_ON(stripe_index > 3);
4061 return (void *)(((uintptr_t)bi_private) | stripe_index);
4064 static struct btrfs_bio *extract_bbio_from_bio_private(void *bi_private)
4066 return (struct btrfs_bio *)(((uintptr_t)bi_private) & ~((uintptr_t)3));
4069 static unsigned int extract_stripe_index_from_bio_private(void *bi_private)
4071 return (unsigned int)((uintptr_t)bi_private) & 3;
4074 static void btrfs_end_bio(struct bio *bio, int err)
4076 struct btrfs_bio *bbio = extract_bbio_from_bio_private(bio->bi_private);
4077 int is_orig_bio = 0;
4080 atomic_inc(&bbio->error);
4081 if (err == -EIO || err == -EREMOTEIO) {
4082 unsigned int stripe_index =
4083 extract_stripe_index_from_bio_private(
4085 struct btrfs_device *dev;
4087 BUG_ON(stripe_index >= bbio->num_stripes);
4088 dev = bbio->stripes[stripe_index].dev;
4090 if (bio->bi_rw & WRITE)
4091 btrfs_dev_stat_inc(dev,
4092 BTRFS_DEV_STAT_WRITE_ERRS);
4094 btrfs_dev_stat_inc(dev,
4095 BTRFS_DEV_STAT_READ_ERRS);
4096 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
4097 btrfs_dev_stat_inc(dev,
4098 BTRFS_DEV_STAT_FLUSH_ERRS);
4099 btrfs_dev_stat_print_on_error(dev);
4104 if (bio == bbio->orig_bio)
4107 if (atomic_dec_and_test(&bbio->stripes_pending)) {
4110 bio = bbio->orig_bio;
4112 bio->bi_private = bbio->private;
4113 bio->bi_end_io = bbio->end_io;
4114 bio->bi_bdev = (struct block_device *)
4115 (unsigned long)bbio->mirror_num;
4116 /* only send an error to the higher layers if it is
4117 * beyond the tolerance of the multi-bio
4119 if (atomic_read(&bbio->error) > bbio->max_errors) {
4123 * this bio is actually up to date, we didn't
4124 * go over the max number of errors
4126 set_bit(BIO_UPTODATE, &bio->bi_flags);
4131 bio_endio(bio, err);
4132 } else if (!is_orig_bio) {
4137 struct async_sched {
4140 struct btrfs_fs_info *info;
4141 struct btrfs_work work;
4145 * see run_scheduled_bios for a description of why bios are collected for
4148 * This will add one bio to the pending list for a device and make sure
4149 * the work struct is scheduled.
4151 static noinline void schedule_bio(struct btrfs_root *root,
4152 struct btrfs_device *device,
4153 int rw, struct bio *bio)
4155 int should_queue = 1;
4156 struct btrfs_pending_bios *pending_bios;
4158 /* don't bother with additional async steps for reads, right now */
4159 if (!(rw & REQ_WRITE)) {
4161 btrfsic_submit_bio(rw, bio);
4167 * nr_async_bios allows us to reliably return congestion to the
4168 * higher layers. Otherwise, the async bio makes it appear we have
4169 * made progress against dirty pages when we've really just put it
4170 * on a queue for later
4172 atomic_inc(&root->fs_info->nr_async_bios);
4173 WARN_ON(bio->bi_next);
4174 bio->bi_next = NULL;
4177 spin_lock(&device->io_lock);
4178 if (bio->bi_rw & REQ_SYNC)
4179 pending_bios = &device->pending_sync_bios;
4181 pending_bios = &device->pending_bios;
4183 if (pending_bios->tail)
4184 pending_bios->tail->bi_next = bio;
4186 pending_bios->tail = bio;
4187 if (!pending_bios->head)
4188 pending_bios->head = bio;
4189 if (device->running_pending)
4192 spin_unlock(&device->io_lock);
4195 btrfs_queue_worker(&root->fs_info->submit_workers,
4199 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
4200 int mirror_num, int async_submit)
4202 struct btrfs_mapping_tree *map_tree;
4203 struct btrfs_device *dev;
4204 struct bio *first_bio = bio;
4205 u64 logical = (u64)bio->bi_sector << 9;
4211 struct btrfs_bio *bbio = NULL;
4213 length = bio->bi_size;
4214 map_tree = &root->fs_info->mapping_tree;
4215 map_length = length;
4217 ret = btrfs_map_block(map_tree, rw, logical, &map_length, &bbio,
4219 if (ret) /* -ENOMEM */
4222 total_devs = bbio->num_stripes;
4223 if (map_length < length) {
4224 printk(KERN_CRIT "mapping failed logical %llu bio len %llu "
4225 "len %llu\n", (unsigned long long)logical,
4226 (unsigned long long)length,
4227 (unsigned long long)map_length);
4231 bbio->orig_bio = first_bio;
4232 bbio->private = first_bio->bi_private;
4233 bbio->end_io = first_bio->bi_end_io;
4234 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
4236 while (dev_nr < total_devs) {
4237 if (dev_nr < total_devs - 1) {
4238 bio = bio_clone(first_bio, GFP_NOFS);
4239 BUG_ON(!bio); /* -ENOMEM */
4243 bio->bi_private = bbio;
4244 bio->bi_private = merge_stripe_index_into_bio_private(
4245 bio->bi_private, (unsigned int)dev_nr);
4246 bio->bi_end_io = btrfs_end_bio;
4247 bio->bi_sector = bbio->stripes[dev_nr].physical >> 9;
4248 dev = bbio->stripes[dev_nr].dev;
4249 if (dev && dev->bdev && (rw != WRITE || dev->writeable)) {
4251 struct rcu_string *name;
4254 name = rcu_dereference(dev->name);
4255 pr_debug("btrfs_map_bio: rw %d, secor=%llu, dev=%lu "
4256 "(%s id %llu), size=%u\n", rw,
4257 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
4258 name->str, dev->devid, bio->bi_size);
4261 bio->bi_bdev = dev->bdev;
4263 schedule_bio(root, dev, rw, bio);
4265 btrfsic_submit_bio(rw, bio);
4267 bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
4268 bio->bi_sector = logical >> 9;
4269 bio_endio(bio, -EIO);
4276 struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
4279 struct btrfs_device *device;
4280 struct btrfs_fs_devices *cur_devices;
4282 cur_devices = root->fs_info->fs_devices;
4283 while (cur_devices) {
4285 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
4286 device = __find_device(&cur_devices->devices,
4291 cur_devices = cur_devices->seed;
4296 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
4297 u64 devid, u8 *dev_uuid)
4299 struct btrfs_device *device;
4300 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
4302 device = kzalloc(sizeof(*device), GFP_NOFS);
4305 list_add(&device->dev_list,
4306 &fs_devices->devices);
4307 device->dev_root = root->fs_info->dev_root;
4308 device->devid = devid;
4309 device->work.func = pending_bios_fn;
4310 device->fs_devices = fs_devices;
4311 device->missing = 1;
4312 fs_devices->num_devices++;
4313 fs_devices->missing_devices++;
4314 spin_lock_init(&device->io_lock);
4315 INIT_LIST_HEAD(&device->dev_alloc_list);
4316 memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
4320 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
4321 struct extent_buffer *leaf,
4322 struct btrfs_chunk *chunk)
4324 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4325 struct map_lookup *map;
4326 struct extent_map *em;
4330 u8 uuid[BTRFS_UUID_SIZE];
4335 logical = key->offset;
4336 length = btrfs_chunk_length(leaf, chunk);
4338 read_lock(&map_tree->map_tree.lock);
4339 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
4340 read_unlock(&map_tree->map_tree.lock);
4342 /* already mapped? */
4343 if (em && em->start <= logical && em->start + em->len > logical) {
4344 free_extent_map(em);
4347 free_extent_map(em);
4350 em = alloc_extent_map();
4353 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4354 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4356 free_extent_map(em);
4360 em->bdev = (struct block_device *)map;
4361 em->start = logical;
4363 em->block_start = 0;
4364 em->block_len = em->len;
4366 map->num_stripes = num_stripes;
4367 map->io_width = btrfs_chunk_io_width(leaf, chunk);
4368 map->io_align = btrfs_chunk_io_align(leaf, chunk);
4369 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
4370 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
4371 map->type = btrfs_chunk_type(leaf, chunk);
4372 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
4373 for (i = 0; i < num_stripes; i++) {
4374 map->stripes[i].physical =
4375 btrfs_stripe_offset_nr(leaf, chunk, i);
4376 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
4377 read_extent_buffer(leaf, uuid, (unsigned long)
4378 btrfs_stripe_dev_uuid_nr(chunk, i),
4380 map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
4382 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
4384 free_extent_map(em);
4387 if (!map->stripes[i].dev) {
4388 map->stripes[i].dev =
4389 add_missing_dev(root, devid, uuid);
4390 if (!map->stripes[i].dev) {
4392 free_extent_map(em);
4396 map->stripes[i].dev->in_fs_metadata = 1;
4399 write_lock(&map_tree->map_tree.lock);
4400 ret = add_extent_mapping(&map_tree->map_tree, em);
4401 write_unlock(&map_tree->map_tree.lock);
4402 BUG_ON(ret); /* Tree corruption */
4403 free_extent_map(em);
4408 static void fill_device_from_item(struct extent_buffer *leaf,
4409 struct btrfs_dev_item *dev_item,
4410 struct btrfs_device *device)
4414 device->devid = btrfs_device_id(leaf, dev_item);
4415 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
4416 device->total_bytes = device->disk_total_bytes;
4417 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
4418 device->type = btrfs_device_type(leaf, dev_item);
4419 device->io_align = btrfs_device_io_align(leaf, dev_item);
4420 device->io_width = btrfs_device_io_width(leaf, dev_item);
4421 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
4423 ptr = (unsigned long)btrfs_device_uuid(dev_item);
4424 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
4427 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
4429 struct btrfs_fs_devices *fs_devices;
4432 BUG_ON(!mutex_is_locked(&uuid_mutex));
4434 fs_devices = root->fs_info->fs_devices->seed;
4435 while (fs_devices) {
4436 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
4440 fs_devices = fs_devices->seed;
4443 fs_devices = find_fsid(fsid);
4449 fs_devices = clone_fs_devices(fs_devices);
4450 if (IS_ERR(fs_devices)) {
4451 ret = PTR_ERR(fs_devices);
4455 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
4456 root->fs_info->bdev_holder);
4458 free_fs_devices(fs_devices);
4462 if (!fs_devices->seeding) {
4463 __btrfs_close_devices(fs_devices);
4464 free_fs_devices(fs_devices);
4469 fs_devices->seed = root->fs_info->fs_devices->seed;
4470 root->fs_info->fs_devices->seed = fs_devices;
4475 static int read_one_dev(struct btrfs_root *root,
4476 struct extent_buffer *leaf,
4477 struct btrfs_dev_item *dev_item)
4479 struct btrfs_device *device;
4482 u8 fs_uuid[BTRFS_UUID_SIZE];
4483 u8 dev_uuid[BTRFS_UUID_SIZE];
4485 devid = btrfs_device_id(leaf, dev_item);
4486 read_extent_buffer(leaf, dev_uuid,
4487 (unsigned long)btrfs_device_uuid(dev_item),
4489 read_extent_buffer(leaf, fs_uuid,
4490 (unsigned long)btrfs_device_fsid(dev_item),
4493 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
4494 ret = open_seed_devices(root, fs_uuid);
4495 if (ret && !btrfs_test_opt(root, DEGRADED))
4499 device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
4500 if (!device || !device->bdev) {
4501 if (!btrfs_test_opt(root, DEGRADED))
4505 printk(KERN_WARNING "warning devid %llu missing\n",
4506 (unsigned long long)devid);
4507 device = add_missing_dev(root, devid, dev_uuid);
4510 } else if (!device->missing) {
4512 * this happens when a device that was properly setup
4513 * in the device info lists suddenly goes bad.
4514 * device->bdev is NULL, and so we have to set
4515 * device->missing to one here
4517 root->fs_info->fs_devices->missing_devices++;
4518 device->missing = 1;
4522 if (device->fs_devices != root->fs_info->fs_devices) {
4523 BUG_ON(device->writeable);
4524 if (device->generation !=
4525 btrfs_device_generation(leaf, dev_item))
4529 fill_device_from_item(leaf, dev_item, device);
4530 device->dev_root = root->fs_info->dev_root;
4531 device->in_fs_metadata = 1;
4532 if (device->writeable) {
4533 device->fs_devices->total_rw_bytes += device->total_bytes;
4534 spin_lock(&root->fs_info->free_chunk_lock);
4535 root->fs_info->free_chunk_space += device->total_bytes -
4537 spin_unlock(&root->fs_info->free_chunk_lock);
4543 int btrfs_read_sys_array(struct btrfs_root *root)
4545 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4546 struct extent_buffer *sb;
4547 struct btrfs_disk_key *disk_key;
4548 struct btrfs_chunk *chunk;
4550 unsigned long sb_ptr;
4556 struct btrfs_key key;
4558 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
4559 BTRFS_SUPER_INFO_SIZE);
4562 btrfs_set_buffer_uptodate(sb);
4563 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
4565 * The sb extent buffer is artifical and just used to read the system array.
4566 * btrfs_set_buffer_uptodate() call does not properly mark all it's
4567 * pages up-to-date when the page is larger: extent does not cover the
4568 * whole page and consequently check_page_uptodate does not find all
4569 * the page's extents up-to-date (the hole beyond sb),
4570 * write_extent_buffer then triggers a WARN_ON.
4572 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
4573 * but sb spans only this function. Add an explicit SetPageUptodate call
4574 * to silence the warning eg. on PowerPC 64.
4576 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
4577 SetPageUptodate(sb->pages[0]);
4579 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
4580 array_size = btrfs_super_sys_array_size(super_copy);
4582 ptr = super_copy->sys_chunk_array;
4583 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
4586 while (cur < array_size) {
4587 disk_key = (struct btrfs_disk_key *)ptr;
4588 btrfs_disk_key_to_cpu(&key, disk_key);
4590 len = sizeof(*disk_key); ptr += len;
4594 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
4595 chunk = (struct btrfs_chunk *)sb_ptr;
4596 ret = read_one_chunk(root, &key, sb, chunk);
4599 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
4600 len = btrfs_chunk_item_size(num_stripes);
4609 free_extent_buffer(sb);
4613 struct btrfs_device *btrfs_find_device_for_logical(struct btrfs_root *root,
4614 u64 logical, int mirror_num)
4616 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4619 struct btrfs_bio *bbio = NULL;
4620 struct btrfs_device *device;
4622 BUG_ON(mirror_num == 0);
4623 ret = btrfs_map_block(map_tree, WRITE, logical, &map_length, &bbio,
4626 BUG_ON(bbio != NULL);
4629 BUG_ON(mirror_num != bbio->mirror_num);
4630 device = bbio->stripes[mirror_num - 1].dev;
4635 int btrfs_read_chunk_tree(struct btrfs_root *root)
4637 struct btrfs_path *path;
4638 struct extent_buffer *leaf;
4639 struct btrfs_key key;
4640 struct btrfs_key found_key;
4644 root = root->fs_info->chunk_root;
4646 path = btrfs_alloc_path();
4650 mutex_lock(&uuid_mutex);
4653 /* first we search for all of the device items, and then we
4654 * read in all of the chunk items. This way we can create chunk
4655 * mappings that reference all of the devices that are afound
4657 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
4661 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4665 leaf = path->nodes[0];
4666 slot = path->slots[0];
4667 if (slot >= btrfs_header_nritems(leaf)) {
4668 ret = btrfs_next_leaf(root, path);
4675 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4676 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
4677 if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
4679 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
4680 struct btrfs_dev_item *dev_item;
4681 dev_item = btrfs_item_ptr(leaf, slot,
4682 struct btrfs_dev_item);
4683 ret = read_one_dev(root, leaf, dev_item);
4687 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
4688 struct btrfs_chunk *chunk;
4689 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4690 ret = read_one_chunk(root, &found_key, leaf, chunk);
4696 if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
4698 btrfs_release_path(path);
4703 unlock_chunks(root);
4704 mutex_unlock(&uuid_mutex);
4706 btrfs_free_path(path);
4710 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
4714 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
4715 btrfs_dev_stat_reset(dev, i);
4718 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
4720 struct btrfs_key key;
4721 struct btrfs_key found_key;
4722 struct btrfs_root *dev_root = fs_info->dev_root;
4723 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
4724 struct extent_buffer *eb;
4727 struct btrfs_device *device;
4728 struct btrfs_path *path = NULL;
4731 path = btrfs_alloc_path();
4737 mutex_lock(&fs_devices->device_list_mutex);
4738 list_for_each_entry(device, &fs_devices->devices, dev_list) {
4740 struct btrfs_dev_stats_item *ptr;
4743 key.type = BTRFS_DEV_STATS_KEY;
4744 key.offset = device->devid;
4745 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
4747 __btrfs_reset_dev_stats(device);
4748 device->dev_stats_valid = 1;
4749 btrfs_release_path(path);
4752 slot = path->slots[0];
4753 eb = path->nodes[0];
4754 btrfs_item_key_to_cpu(eb, &found_key, slot);
4755 item_size = btrfs_item_size_nr(eb, slot);
4757 ptr = btrfs_item_ptr(eb, slot,
4758 struct btrfs_dev_stats_item);
4760 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
4761 if (item_size >= (1 + i) * sizeof(__le64))
4762 btrfs_dev_stat_set(device, i,
4763 btrfs_dev_stats_value(eb, ptr, i));
4765 btrfs_dev_stat_reset(device, i);
4768 device->dev_stats_valid = 1;
4769 btrfs_dev_stat_print_on_load(device);
4770 btrfs_release_path(path);
4772 mutex_unlock(&fs_devices->device_list_mutex);
4775 btrfs_free_path(path);
4776 return ret < 0 ? ret : 0;
4779 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
4780 struct btrfs_root *dev_root,
4781 struct btrfs_device *device)
4783 struct btrfs_path *path;
4784 struct btrfs_key key;
4785 struct extent_buffer *eb;
4786 struct btrfs_dev_stats_item *ptr;
4791 key.type = BTRFS_DEV_STATS_KEY;
4792 key.offset = device->devid;
4794 path = btrfs_alloc_path();
4796 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
4798 printk_in_rcu(KERN_WARNING "btrfs: error %d while searching for dev_stats item for device %s!\n",
4799 ret, rcu_str_deref(device->name));
4804 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
4805 /* need to delete old one and insert a new one */
4806 ret = btrfs_del_item(trans, dev_root, path);
4808 printk_in_rcu(KERN_WARNING "btrfs: delete too small dev_stats item for device %s failed %d!\n",
4809 rcu_str_deref(device->name), ret);
4816 /* need to insert a new item */
4817 btrfs_release_path(path);
4818 ret = btrfs_insert_empty_item(trans, dev_root, path,
4819 &key, sizeof(*ptr));
4821 printk_in_rcu(KERN_WARNING "btrfs: insert dev_stats item for device %s failed %d!\n",
4822 rcu_str_deref(device->name), ret);
4827 eb = path->nodes[0];
4828 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
4829 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
4830 btrfs_set_dev_stats_value(eb, ptr, i,
4831 btrfs_dev_stat_read(device, i));
4832 btrfs_mark_buffer_dirty(eb);
4835 btrfs_free_path(path);
4840 * called from commit_transaction. Writes all changed device stats to disk.
4842 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
4843 struct btrfs_fs_info *fs_info)
4845 struct btrfs_root *dev_root = fs_info->dev_root;
4846 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
4847 struct btrfs_device *device;
4850 mutex_lock(&fs_devices->device_list_mutex);
4851 list_for_each_entry(device, &fs_devices->devices, dev_list) {
4852 if (!device->dev_stats_valid || !device->dev_stats_dirty)
4855 ret = update_dev_stat_item(trans, dev_root, device);
4857 device->dev_stats_dirty = 0;
4859 mutex_unlock(&fs_devices->device_list_mutex);
4864 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
4866 btrfs_dev_stat_inc(dev, index);
4867 btrfs_dev_stat_print_on_error(dev);
4870 void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
4872 if (!dev->dev_stats_valid)
4874 printk_ratelimited_in_rcu(KERN_ERR
4875 "btrfs: bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
4876 rcu_str_deref(dev->name),
4877 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
4878 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
4879 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
4880 btrfs_dev_stat_read(dev,
4881 BTRFS_DEV_STAT_CORRUPTION_ERRS),
4882 btrfs_dev_stat_read(dev,
4883 BTRFS_DEV_STAT_GENERATION_ERRS));
4886 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
4890 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
4891 if (btrfs_dev_stat_read(dev, i) != 0)
4893 if (i == BTRFS_DEV_STAT_VALUES_MAX)
4894 return; /* all values == 0, suppress message */
4896 printk_in_rcu(KERN_INFO "btrfs: bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
4897 rcu_str_deref(dev->name),
4898 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
4899 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
4900 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
4901 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
4902 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
4905 int btrfs_get_dev_stats(struct btrfs_root *root,
4906 struct btrfs_ioctl_get_dev_stats *stats)
4908 struct btrfs_device *dev;
4909 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
4912 mutex_lock(&fs_devices->device_list_mutex);
4913 dev = btrfs_find_device(root, stats->devid, NULL, NULL);
4914 mutex_unlock(&fs_devices->device_list_mutex);
4918 "btrfs: get dev_stats failed, device not found\n");
4920 } else if (!dev->dev_stats_valid) {
4922 "btrfs: get dev_stats failed, not yet valid\n");
4924 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
4925 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
4926 if (stats->nr_items > i)
4928 btrfs_dev_stat_read_and_reset(dev, i);
4930 btrfs_dev_stat_reset(dev, i);
4933 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
4934 if (stats->nr_items > i)
4935 stats->values[i] = btrfs_dev_stat_read(dev, i);
4937 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
4938 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;