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 <linux/raid/pq.h>
29 #include <linux/semaphore.h>
30 #include <asm/div64.h>
32 #include "extent_map.h"
34 #include "transaction.h"
35 #include "print-tree.h"
38 #include "async-thread.h"
39 #include "check-integrity.h"
40 #include "rcu-string.h"
42 #include "dev-replace.h"
45 static int init_first_rw_device(struct btrfs_trans_handle *trans,
46 struct btrfs_root *root,
47 struct btrfs_device *device);
48 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
49 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
50 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
51 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
53 static DEFINE_MUTEX(uuid_mutex);
54 static LIST_HEAD(fs_uuids);
56 static void lock_chunks(struct btrfs_root *root)
58 mutex_lock(&root->fs_info->chunk_mutex);
61 static void unlock_chunks(struct btrfs_root *root)
63 mutex_unlock(&root->fs_info->chunk_mutex);
66 static struct btrfs_fs_devices *__alloc_fs_devices(void)
68 struct btrfs_fs_devices *fs_devs;
70 fs_devs = kzalloc(sizeof(*fs_devs), GFP_NOFS);
72 return ERR_PTR(-ENOMEM);
74 mutex_init(&fs_devs->device_list_mutex);
76 INIT_LIST_HEAD(&fs_devs->devices);
77 INIT_LIST_HEAD(&fs_devs->alloc_list);
78 INIT_LIST_HEAD(&fs_devs->list);
84 * alloc_fs_devices - allocate struct btrfs_fs_devices
85 * @fsid: a pointer to UUID for this FS. If NULL a new UUID is
88 * Return: a pointer to a new &struct btrfs_fs_devices on success;
89 * ERR_PTR() on error. Returned struct is not linked onto any lists and
90 * can be destroyed with kfree() right away.
92 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
94 struct btrfs_fs_devices *fs_devs;
96 fs_devs = __alloc_fs_devices();
101 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
103 generate_random_uuid(fs_devs->fsid);
108 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
110 struct btrfs_device *device;
111 WARN_ON(fs_devices->opened);
112 while (!list_empty(&fs_devices->devices)) {
113 device = list_entry(fs_devices->devices.next,
114 struct btrfs_device, dev_list);
115 list_del(&device->dev_list);
116 rcu_string_free(device->name);
122 static void btrfs_kobject_uevent(struct block_device *bdev,
123 enum kobject_action action)
127 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
129 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
131 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
132 &disk_to_dev(bdev->bd_disk)->kobj);
135 void btrfs_cleanup_fs_uuids(void)
137 struct btrfs_fs_devices *fs_devices;
139 while (!list_empty(&fs_uuids)) {
140 fs_devices = list_entry(fs_uuids.next,
141 struct btrfs_fs_devices, list);
142 list_del(&fs_devices->list);
143 free_fs_devices(fs_devices);
147 static struct btrfs_device *__alloc_device(void)
149 struct btrfs_device *dev;
151 dev = kzalloc(sizeof(*dev), GFP_NOFS);
153 return ERR_PTR(-ENOMEM);
155 INIT_LIST_HEAD(&dev->dev_list);
156 INIT_LIST_HEAD(&dev->dev_alloc_list);
158 spin_lock_init(&dev->io_lock);
160 spin_lock_init(&dev->reada_lock);
161 atomic_set(&dev->reada_in_flight, 0);
162 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_WAIT);
163 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_WAIT);
168 static noinline struct btrfs_device *__find_device(struct list_head *head,
171 struct btrfs_device *dev;
173 list_for_each_entry(dev, head, dev_list) {
174 if (dev->devid == devid &&
175 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
182 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
184 struct btrfs_fs_devices *fs_devices;
186 list_for_each_entry(fs_devices, &fs_uuids, list) {
187 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
194 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
195 int flush, struct block_device **bdev,
196 struct buffer_head **bh)
200 *bdev = blkdev_get_by_path(device_path, flags, holder);
203 ret = PTR_ERR(*bdev);
204 printk(KERN_INFO "BTRFS: open %s failed\n", device_path);
209 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
210 ret = set_blocksize(*bdev, 4096);
212 blkdev_put(*bdev, flags);
215 invalidate_bdev(*bdev);
216 *bh = btrfs_read_dev_super(*bdev);
219 blkdev_put(*bdev, flags);
231 static void requeue_list(struct btrfs_pending_bios *pending_bios,
232 struct bio *head, struct bio *tail)
235 struct bio *old_head;
237 old_head = pending_bios->head;
238 pending_bios->head = head;
239 if (pending_bios->tail)
240 tail->bi_next = old_head;
242 pending_bios->tail = tail;
246 * we try to collect pending bios for a device so we don't get a large
247 * number of procs sending bios down to the same device. This greatly
248 * improves the schedulers ability to collect and merge the bios.
250 * But, it also turns into a long list of bios to process and that is sure
251 * to eventually make the worker thread block. The solution here is to
252 * make some progress and then put this work struct back at the end of
253 * the list if the block device is congested. This way, multiple devices
254 * can make progress from a single worker thread.
256 static noinline void run_scheduled_bios(struct btrfs_device *device)
259 struct backing_dev_info *bdi;
260 struct btrfs_fs_info *fs_info;
261 struct btrfs_pending_bios *pending_bios;
265 unsigned long num_run;
266 unsigned long batch_run = 0;
268 unsigned long last_waited = 0;
270 int sync_pending = 0;
271 struct blk_plug plug;
274 * this function runs all the bios we've collected for
275 * a particular device. We don't want to wander off to
276 * another device without first sending all of these down.
277 * So, setup a plug here and finish it off before we return
279 blk_start_plug(&plug);
281 bdi = blk_get_backing_dev_info(device->bdev);
282 fs_info = device->dev_root->fs_info;
283 limit = btrfs_async_submit_limit(fs_info);
284 limit = limit * 2 / 3;
287 spin_lock(&device->io_lock);
292 /* take all the bios off the list at once and process them
293 * later on (without the lock held). But, remember the
294 * tail and other pointers so the bios can be properly reinserted
295 * into the list if we hit congestion
297 if (!force_reg && device->pending_sync_bios.head) {
298 pending_bios = &device->pending_sync_bios;
301 pending_bios = &device->pending_bios;
305 pending = pending_bios->head;
306 tail = pending_bios->tail;
307 WARN_ON(pending && !tail);
310 * if pending was null this time around, no bios need processing
311 * at all and we can stop. Otherwise it'll loop back up again
312 * and do an additional check so no bios are missed.
314 * device->running_pending is used to synchronize with the
317 if (device->pending_sync_bios.head == NULL &&
318 device->pending_bios.head == NULL) {
320 device->running_pending = 0;
323 device->running_pending = 1;
326 pending_bios->head = NULL;
327 pending_bios->tail = NULL;
329 spin_unlock(&device->io_lock);
334 /* we want to work on both lists, but do more bios on the
335 * sync list than the regular list
338 pending_bios != &device->pending_sync_bios &&
339 device->pending_sync_bios.head) ||
340 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
341 device->pending_bios.head)) {
342 spin_lock(&device->io_lock);
343 requeue_list(pending_bios, pending, tail);
348 pending = pending->bi_next;
351 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
352 waitqueue_active(&fs_info->async_submit_wait))
353 wake_up(&fs_info->async_submit_wait);
355 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
358 * if we're doing the sync list, record that our
359 * plug has some sync requests on it
361 * If we're doing the regular list and there are
362 * sync requests sitting around, unplug before
365 if (pending_bios == &device->pending_sync_bios) {
367 } else if (sync_pending) {
368 blk_finish_plug(&plug);
369 blk_start_plug(&plug);
373 btrfsic_submit_bio(cur->bi_rw, cur);
380 * we made progress, there is more work to do and the bdi
381 * is now congested. Back off and let other work structs
384 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
385 fs_info->fs_devices->open_devices > 1) {
386 struct io_context *ioc;
388 ioc = current->io_context;
391 * the main goal here is that we don't want to
392 * block if we're going to be able to submit
393 * more requests without blocking.
395 * This code does two great things, it pokes into
396 * the elevator code from a filesystem _and_
397 * it makes assumptions about how batching works.
399 if (ioc && ioc->nr_batch_requests > 0 &&
400 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
402 ioc->last_waited == last_waited)) {
404 * we want to go through our batch of
405 * requests and stop. So, we copy out
406 * the ioc->last_waited time and test
407 * against it before looping
409 last_waited = ioc->last_waited;
414 spin_lock(&device->io_lock);
415 requeue_list(pending_bios, pending, tail);
416 device->running_pending = 1;
418 spin_unlock(&device->io_lock);
419 btrfs_queue_work(fs_info->submit_workers,
423 /* unplug every 64 requests just for good measure */
424 if (batch_run % 64 == 0) {
425 blk_finish_plug(&plug);
426 blk_start_plug(&plug);
435 spin_lock(&device->io_lock);
436 if (device->pending_bios.head || device->pending_sync_bios.head)
438 spin_unlock(&device->io_lock);
441 blk_finish_plug(&plug);
444 static void pending_bios_fn(struct btrfs_work *work)
446 struct btrfs_device *device;
448 device = container_of(work, struct btrfs_device, work);
449 run_scheduled_bios(device);
453 * Add new device to list of registered devices
456 * 1 - first time device is seen
457 * 0 - device already known
460 static noinline int device_list_add(const char *path,
461 struct btrfs_super_block *disk_super,
462 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
464 struct btrfs_device *device;
465 struct btrfs_fs_devices *fs_devices;
466 struct rcu_string *name;
468 u64 found_transid = btrfs_super_generation(disk_super);
470 fs_devices = find_fsid(disk_super->fsid);
472 fs_devices = alloc_fs_devices(disk_super->fsid);
473 if (IS_ERR(fs_devices))
474 return PTR_ERR(fs_devices);
476 list_add(&fs_devices->list, &fs_uuids);
477 fs_devices->latest_devid = devid;
478 fs_devices->latest_trans = found_transid;
482 device = __find_device(&fs_devices->devices, devid,
483 disk_super->dev_item.uuid);
486 if (fs_devices->opened)
489 device = btrfs_alloc_device(NULL, &devid,
490 disk_super->dev_item.uuid);
491 if (IS_ERR(device)) {
492 /* we can safely leave the fs_devices entry around */
493 return PTR_ERR(device);
496 name = rcu_string_strdup(path, GFP_NOFS);
501 rcu_assign_pointer(device->name, name);
503 mutex_lock(&fs_devices->device_list_mutex);
504 list_add_rcu(&device->dev_list, &fs_devices->devices);
505 fs_devices->num_devices++;
506 mutex_unlock(&fs_devices->device_list_mutex);
509 device->fs_devices = fs_devices;
510 } else if (!device->name || strcmp(device->name->str, path)) {
512 * When FS is already mounted.
513 * 1. If you are here and if the device->name is NULL that
514 * means this device was missing at time of FS mount.
515 * 2. If you are here and if the device->name is different
516 * from 'path' that means either
517 * a. The same device disappeared and reappeared with
519 * b. The missing-disk-which-was-replaced, has
522 * We must allow 1 and 2a above. But 2b would be a spurious
525 * Further in case of 1 and 2a above, the disk at 'path'
526 * would have missed some transaction when it was away and
527 * in case of 2a the stale bdev has to be updated as well.
528 * 2b must not be allowed at all time.
532 * As of now don't allow update to btrfs_fs_device through
533 * the btrfs dev scan cli, after FS has been mounted.
535 if (fs_devices->opened) {
539 * That is if the FS is _not_ mounted and if you
540 * are here, that means there is more than one
541 * disk with same uuid and devid.We keep the one
542 * with larger generation number or the last-in if
543 * generation are equal.
545 if (found_transid < device->generation)
549 name = rcu_string_strdup(path, GFP_NOFS);
552 rcu_string_free(device->name);
553 rcu_assign_pointer(device->name, name);
554 if (device->missing) {
555 fs_devices->missing_devices--;
561 * Unmount does not free the btrfs_device struct but would zero
562 * generation along with most of the other members. So just update
563 * it back. We need it to pick the disk with largest generation
566 if (!fs_devices->opened)
567 device->generation = found_transid;
569 if (found_transid > fs_devices->latest_trans) {
570 fs_devices->latest_devid = devid;
571 fs_devices->latest_trans = found_transid;
573 *fs_devices_ret = fs_devices;
578 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
580 struct btrfs_fs_devices *fs_devices;
581 struct btrfs_device *device;
582 struct btrfs_device *orig_dev;
584 fs_devices = alloc_fs_devices(orig->fsid);
585 if (IS_ERR(fs_devices))
588 fs_devices->latest_devid = orig->latest_devid;
589 fs_devices->latest_trans = orig->latest_trans;
590 fs_devices->total_devices = orig->total_devices;
592 /* We have held the volume lock, it is safe to get the devices. */
593 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
594 struct rcu_string *name;
596 device = btrfs_alloc_device(NULL, &orig_dev->devid,
602 * This is ok to do without rcu read locked because we hold the
603 * uuid mutex so nothing we touch in here is going to disappear.
605 if (orig_dev->name) {
606 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
611 rcu_assign_pointer(device->name, name);
614 list_add(&device->dev_list, &fs_devices->devices);
615 device->fs_devices = fs_devices;
616 fs_devices->num_devices++;
620 free_fs_devices(fs_devices);
621 return ERR_PTR(-ENOMEM);
624 void btrfs_close_extra_devices(struct btrfs_fs_info *fs_info,
625 struct btrfs_fs_devices *fs_devices, int step)
627 struct btrfs_device *device, *next;
629 struct block_device *latest_bdev = NULL;
630 u64 latest_devid = 0;
631 u64 latest_transid = 0;
633 mutex_lock(&uuid_mutex);
635 /* This is the initialized path, it is safe to release the devices. */
636 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
637 if (device->in_fs_metadata) {
638 if (!device->is_tgtdev_for_dev_replace &&
640 device->generation > latest_transid)) {
641 latest_devid = device->devid;
642 latest_transid = device->generation;
643 latest_bdev = device->bdev;
648 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
650 * In the first step, keep the device which has
651 * the correct fsid and the devid that is used
652 * for the dev_replace procedure.
653 * In the second step, the dev_replace state is
654 * read from the device tree and it is known
655 * whether the procedure is really active or
656 * not, which means whether this device is
657 * used or whether it should be removed.
659 if (step == 0 || device->is_tgtdev_for_dev_replace) {
664 blkdev_put(device->bdev, device->mode);
666 fs_devices->open_devices--;
668 if (device->writeable) {
669 list_del_init(&device->dev_alloc_list);
670 device->writeable = 0;
671 if (!device->is_tgtdev_for_dev_replace)
672 fs_devices->rw_devices--;
674 list_del_init(&device->dev_list);
675 fs_devices->num_devices--;
676 rcu_string_free(device->name);
680 if (fs_devices->seed) {
681 fs_devices = fs_devices->seed;
685 fs_devices->latest_bdev = latest_bdev;
686 fs_devices->latest_devid = latest_devid;
687 fs_devices->latest_trans = latest_transid;
689 mutex_unlock(&uuid_mutex);
692 static void __free_device(struct work_struct *work)
694 struct btrfs_device *device;
696 device = container_of(work, struct btrfs_device, rcu_work);
699 blkdev_put(device->bdev, device->mode);
701 rcu_string_free(device->name);
705 static void free_device(struct rcu_head *head)
707 struct btrfs_device *device;
709 device = container_of(head, struct btrfs_device, rcu);
711 INIT_WORK(&device->rcu_work, __free_device);
712 schedule_work(&device->rcu_work);
715 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
717 struct btrfs_device *device;
719 if (--fs_devices->opened > 0)
722 mutex_lock(&fs_devices->device_list_mutex);
723 list_for_each_entry(device, &fs_devices->devices, dev_list) {
724 struct btrfs_device *new_device;
725 struct rcu_string *name;
728 fs_devices->open_devices--;
730 if (device->writeable &&
731 device->devid != BTRFS_DEV_REPLACE_DEVID) {
732 list_del_init(&device->dev_alloc_list);
733 fs_devices->rw_devices--;
736 if (device->can_discard)
737 fs_devices->num_can_discard--;
739 fs_devices->missing_devices--;
741 new_device = btrfs_alloc_device(NULL, &device->devid,
743 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
745 /* Safe because we are under uuid_mutex */
747 name = rcu_string_strdup(device->name->str, GFP_NOFS);
748 BUG_ON(!name); /* -ENOMEM */
749 rcu_assign_pointer(new_device->name, name);
752 list_replace_rcu(&device->dev_list, &new_device->dev_list);
753 new_device->fs_devices = device->fs_devices;
755 call_rcu(&device->rcu, free_device);
757 mutex_unlock(&fs_devices->device_list_mutex);
759 WARN_ON(fs_devices->open_devices);
760 WARN_ON(fs_devices->rw_devices);
761 fs_devices->opened = 0;
762 fs_devices->seeding = 0;
767 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
769 struct btrfs_fs_devices *seed_devices = NULL;
772 mutex_lock(&uuid_mutex);
773 ret = __btrfs_close_devices(fs_devices);
774 if (!fs_devices->opened) {
775 seed_devices = fs_devices->seed;
776 fs_devices->seed = NULL;
778 mutex_unlock(&uuid_mutex);
780 while (seed_devices) {
781 fs_devices = seed_devices;
782 seed_devices = fs_devices->seed;
783 __btrfs_close_devices(fs_devices);
784 free_fs_devices(fs_devices);
787 * Wait for rcu kworkers under __btrfs_close_devices
788 * to finish all blkdev_puts so device is really
789 * free when umount is done.
795 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
796 fmode_t flags, void *holder)
798 struct request_queue *q;
799 struct block_device *bdev;
800 struct list_head *head = &fs_devices->devices;
801 struct btrfs_device *device;
802 struct block_device *latest_bdev = NULL;
803 struct buffer_head *bh;
804 struct btrfs_super_block *disk_super;
805 u64 latest_devid = 0;
806 u64 latest_transid = 0;
813 list_for_each_entry(device, head, dev_list) {
819 /* Just open everything we can; ignore failures here */
820 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
824 disk_super = (struct btrfs_super_block *)bh->b_data;
825 devid = btrfs_stack_device_id(&disk_super->dev_item);
826 if (devid != device->devid)
829 if (memcmp(device->uuid, disk_super->dev_item.uuid,
833 device->generation = btrfs_super_generation(disk_super);
834 if (!latest_transid || device->generation > latest_transid) {
835 latest_devid = devid;
836 latest_transid = device->generation;
840 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
841 device->writeable = 0;
843 device->writeable = !bdev_read_only(bdev);
847 q = bdev_get_queue(bdev);
848 if (blk_queue_discard(q)) {
849 device->can_discard = 1;
850 fs_devices->num_can_discard++;
854 device->in_fs_metadata = 0;
855 device->mode = flags;
857 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
858 fs_devices->rotating = 1;
860 fs_devices->open_devices++;
861 if (device->writeable &&
862 device->devid != BTRFS_DEV_REPLACE_DEVID) {
863 fs_devices->rw_devices++;
864 list_add(&device->dev_alloc_list,
865 &fs_devices->alloc_list);
872 blkdev_put(bdev, flags);
875 if (fs_devices->open_devices == 0) {
879 fs_devices->seeding = seeding;
880 fs_devices->opened = 1;
881 fs_devices->latest_bdev = latest_bdev;
882 fs_devices->latest_devid = latest_devid;
883 fs_devices->latest_trans = latest_transid;
884 fs_devices->total_rw_bytes = 0;
889 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
890 fmode_t flags, void *holder)
894 mutex_lock(&uuid_mutex);
895 if (fs_devices->opened) {
896 fs_devices->opened++;
899 ret = __btrfs_open_devices(fs_devices, flags, holder);
901 mutex_unlock(&uuid_mutex);
906 * Look for a btrfs signature on a device. This may be called out of the mount path
907 * and we are not allowed to call set_blocksize during the scan. The superblock
908 * is read via pagecache
910 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
911 struct btrfs_fs_devices **fs_devices_ret)
913 struct btrfs_super_block *disk_super;
914 struct block_device *bdev;
925 * we would like to check all the supers, but that would make
926 * a btrfs mount succeed after a mkfs from a different FS.
927 * So, we need to add a special mount option to scan for
928 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
930 bytenr = btrfs_sb_offset(0);
932 mutex_lock(&uuid_mutex);
934 bdev = blkdev_get_by_path(path, flags, holder);
941 /* make sure our super fits in the device */
942 if (bytenr + PAGE_CACHE_SIZE >= i_size_read(bdev->bd_inode))
945 /* make sure our super fits in the page */
946 if (sizeof(*disk_super) > PAGE_CACHE_SIZE)
949 /* make sure our super doesn't straddle pages on disk */
950 index = bytenr >> PAGE_CACHE_SHIFT;
951 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_CACHE_SHIFT != index)
954 /* pull in the page with our super */
955 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
958 if (IS_ERR_OR_NULL(page))
963 /* align our pointer to the offset of the super block */
964 disk_super = p + (bytenr & ~PAGE_CACHE_MASK);
966 if (btrfs_super_bytenr(disk_super) != bytenr ||
967 btrfs_super_magic(disk_super) != BTRFS_MAGIC)
970 devid = btrfs_stack_device_id(&disk_super->dev_item);
971 transid = btrfs_super_generation(disk_super);
972 total_devices = btrfs_super_num_devices(disk_super);
974 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
976 if (disk_super->label[0]) {
977 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
978 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
979 printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
981 printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
984 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
987 if (!ret && fs_devices_ret)
988 (*fs_devices_ret)->total_devices = total_devices;
992 page_cache_release(page);
995 blkdev_put(bdev, flags);
997 mutex_unlock(&uuid_mutex);
1001 /* helper to account the used device space in the range */
1002 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1003 u64 end, u64 *length)
1005 struct btrfs_key key;
1006 struct btrfs_root *root = device->dev_root;
1007 struct btrfs_dev_extent *dev_extent;
1008 struct btrfs_path *path;
1012 struct extent_buffer *l;
1016 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1019 path = btrfs_alloc_path();
1024 key.objectid = device->devid;
1026 key.type = BTRFS_DEV_EXTENT_KEY;
1028 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1032 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1039 slot = path->slots[0];
1040 if (slot >= btrfs_header_nritems(l)) {
1041 ret = btrfs_next_leaf(root, path);
1049 btrfs_item_key_to_cpu(l, &key, slot);
1051 if (key.objectid < device->devid)
1054 if (key.objectid > device->devid)
1057 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
1060 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1061 extent_end = key.offset + btrfs_dev_extent_length(l,
1063 if (key.offset <= start && extent_end > end) {
1064 *length = end - start + 1;
1066 } else if (key.offset <= start && extent_end > start)
1067 *length += extent_end - start;
1068 else if (key.offset > start && extent_end <= end)
1069 *length += extent_end - key.offset;
1070 else if (key.offset > start && key.offset <= end) {
1071 *length += end - key.offset + 1;
1073 } else if (key.offset > end)
1081 btrfs_free_path(path);
1085 static int contains_pending_extent(struct btrfs_trans_handle *trans,
1086 struct btrfs_device *device,
1087 u64 *start, u64 len)
1089 struct extent_map *em;
1092 list_for_each_entry(em, &trans->transaction->pending_chunks, list) {
1093 struct map_lookup *map;
1096 map = (struct map_lookup *)em->bdev;
1097 for (i = 0; i < map->num_stripes; i++) {
1098 if (map->stripes[i].dev != device)
1100 if (map->stripes[i].physical >= *start + len ||
1101 map->stripes[i].physical + em->orig_block_len <=
1104 *start = map->stripes[i].physical +
1115 * find_free_dev_extent - find free space in the specified device
1116 * @device: the device which we search the free space in
1117 * @num_bytes: the size of the free space that we need
1118 * @start: store the start of the free space.
1119 * @len: the size of the free space. that we find, or the size of the max
1120 * free space if we don't find suitable free space
1122 * this uses a pretty simple search, the expectation is that it is
1123 * called very infrequently and that a given device has a small number
1126 * @start is used to store the start of the free space if we find. But if we
1127 * don't find suitable free space, it will be used to store the start position
1128 * of the max free space.
1130 * @len is used to store the size of the free space that we find.
1131 * But if we don't find suitable free space, it is used to store the size of
1132 * the max free space.
1134 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1135 struct btrfs_device *device, u64 num_bytes,
1136 u64 *start, u64 *len)
1138 struct btrfs_key key;
1139 struct btrfs_root *root = device->dev_root;
1140 struct btrfs_dev_extent *dev_extent;
1141 struct btrfs_path *path;
1147 u64 search_end = device->total_bytes;
1150 struct extent_buffer *l;
1152 /* FIXME use last free of some kind */
1154 /* we don't want to overwrite the superblock on the drive,
1155 * so we make sure to start at an offset of at least 1MB
1157 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1159 path = btrfs_alloc_path();
1163 max_hole_start = search_start;
1167 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1173 path->search_commit_root = 1;
1174 path->skip_locking = 1;
1176 key.objectid = device->devid;
1177 key.offset = search_start;
1178 key.type = BTRFS_DEV_EXTENT_KEY;
1180 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1184 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1191 slot = path->slots[0];
1192 if (slot >= btrfs_header_nritems(l)) {
1193 ret = btrfs_next_leaf(root, path);
1201 btrfs_item_key_to_cpu(l, &key, slot);
1203 if (key.objectid < device->devid)
1206 if (key.objectid > device->devid)
1209 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
1212 if (key.offset > search_start) {
1213 hole_size = key.offset - search_start;
1216 * Have to check before we set max_hole_start, otherwise
1217 * we could end up sending back this offset anyway.
1219 if (contains_pending_extent(trans, device,
1224 if (hole_size > max_hole_size) {
1225 max_hole_start = search_start;
1226 max_hole_size = hole_size;
1230 * If this free space is greater than which we need,
1231 * it must be the max free space that we have found
1232 * until now, so max_hole_start must point to the start
1233 * of this free space and the length of this free space
1234 * is stored in max_hole_size. Thus, we return
1235 * max_hole_start and max_hole_size and go back to the
1238 if (hole_size >= num_bytes) {
1244 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1245 extent_end = key.offset + btrfs_dev_extent_length(l,
1247 if (extent_end > search_start)
1248 search_start = extent_end;
1255 * At this point, search_start should be the end of
1256 * allocated dev extents, and when shrinking the device,
1257 * search_end may be smaller than search_start.
1259 if (search_end > search_start)
1260 hole_size = search_end - search_start;
1262 if (hole_size > max_hole_size) {
1263 max_hole_start = search_start;
1264 max_hole_size = hole_size;
1267 if (contains_pending_extent(trans, device, &search_start, hole_size)) {
1268 btrfs_release_path(path);
1273 if (hole_size < num_bytes)
1279 btrfs_free_path(path);
1280 *start = max_hole_start;
1282 *len = max_hole_size;
1286 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1287 struct btrfs_device *device,
1291 struct btrfs_path *path;
1292 struct btrfs_root *root = device->dev_root;
1293 struct btrfs_key key;
1294 struct btrfs_key found_key;
1295 struct extent_buffer *leaf = NULL;
1296 struct btrfs_dev_extent *extent = NULL;
1298 path = btrfs_alloc_path();
1302 key.objectid = device->devid;
1304 key.type = BTRFS_DEV_EXTENT_KEY;
1306 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1308 ret = btrfs_previous_item(root, path, key.objectid,
1309 BTRFS_DEV_EXTENT_KEY);
1312 leaf = path->nodes[0];
1313 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1314 extent = btrfs_item_ptr(leaf, path->slots[0],
1315 struct btrfs_dev_extent);
1316 BUG_ON(found_key.offset > start || found_key.offset +
1317 btrfs_dev_extent_length(leaf, extent) < start);
1319 btrfs_release_path(path);
1321 } else if (ret == 0) {
1322 leaf = path->nodes[0];
1323 extent = btrfs_item_ptr(leaf, path->slots[0],
1324 struct btrfs_dev_extent);
1326 btrfs_error(root->fs_info, ret, "Slot search failed");
1330 if (device->bytes_used > 0) {
1331 u64 len = btrfs_dev_extent_length(leaf, extent);
1332 device->bytes_used -= len;
1333 spin_lock(&root->fs_info->free_chunk_lock);
1334 root->fs_info->free_chunk_space += len;
1335 spin_unlock(&root->fs_info->free_chunk_lock);
1337 ret = btrfs_del_item(trans, root, path);
1339 btrfs_error(root->fs_info, ret,
1340 "Failed to remove dev extent item");
1343 btrfs_free_path(path);
1347 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1348 struct btrfs_device *device,
1349 u64 chunk_tree, u64 chunk_objectid,
1350 u64 chunk_offset, u64 start, u64 num_bytes)
1353 struct btrfs_path *path;
1354 struct btrfs_root *root = device->dev_root;
1355 struct btrfs_dev_extent *extent;
1356 struct extent_buffer *leaf;
1357 struct btrfs_key key;
1359 WARN_ON(!device->in_fs_metadata);
1360 WARN_ON(device->is_tgtdev_for_dev_replace);
1361 path = btrfs_alloc_path();
1365 key.objectid = device->devid;
1367 key.type = BTRFS_DEV_EXTENT_KEY;
1368 ret = btrfs_insert_empty_item(trans, root, path, &key,
1373 leaf = path->nodes[0];
1374 extent = btrfs_item_ptr(leaf, path->slots[0],
1375 struct btrfs_dev_extent);
1376 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1377 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1378 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1380 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1381 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1383 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1384 btrfs_mark_buffer_dirty(leaf);
1386 btrfs_free_path(path);
1390 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1392 struct extent_map_tree *em_tree;
1393 struct extent_map *em;
1397 em_tree = &fs_info->mapping_tree.map_tree;
1398 read_lock(&em_tree->lock);
1399 n = rb_last(&em_tree->map);
1401 em = rb_entry(n, struct extent_map, rb_node);
1402 ret = em->start + em->len;
1404 read_unlock(&em_tree->lock);
1409 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1413 struct btrfs_key key;
1414 struct btrfs_key found_key;
1415 struct btrfs_path *path;
1417 path = btrfs_alloc_path();
1421 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1422 key.type = BTRFS_DEV_ITEM_KEY;
1423 key.offset = (u64)-1;
1425 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1429 BUG_ON(ret == 0); /* Corruption */
1431 ret = btrfs_previous_item(fs_info->chunk_root, path,
1432 BTRFS_DEV_ITEMS_OBJECTID,
1433 BTRFS_DEV_ITEM_KEY);
1437 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1439 *devid_ret = found_key.offset + 1;
1443 btrfs_free_path(path);
1448 * the device information is stored in the chunk root
1449 * the btrfs_device struct should be fully filled in
1451 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1452 struct btrfs_root *root,
1453 struct btrfs_device *device)
1456 struct btrfs_path *path;
1457 struct btrfs_dev_item *dev_item;
1458 struct extent_buffer *leaf;
1459 struct btrfs_key key;
1462 root = root->fs_info->chunk_root;
1464 path = btrfs_alloc_path();
1468 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1469 key.type = BTRFS_DEV_ITEM_KEY;
1470 key.offset = device->devid;
1472 ret = btrfs_insert_empty_item(trans, root, path, &key,
1477 leaf = path->nodes[0];
1478 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1480 btrfs_set_device_id(leaf, dev_item, device->devid);
1481 btrfs_set_device_generation(leaf, dev_item, 0);
1482 btrfs_set_device_type(leaf, dev_item, device->type);
1483 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1484 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1485 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1486 btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1487 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1488 btrfs_set_device_group(leaf, dev_item, 0);
1489 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1490 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1491 btrfs_set_device_start_offset(leaf, dev_item, 0);
1493 ptr = btrfs_device_uuid(dev_item);
1494 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1495 ptr = btrfs_device_fsid(dev_item);
1496 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1497 btrfs_mark_buffer_dirty(leaf);
1501 btrfs_free_path(path);
1506 * Function to update ctime/mtime for a given device path.
1507 * Mainly used for ctime/mtime based probe like libblkid.
1509 static void update_dev_time(char *path_name)
1513 filp = filp_open(path_name, O_RDWR, 0);
1516 file_update_time(filp);
1517 filp_close(filp, NULL);
1521 static int btrfs_rm_dev_item(struct btrfs_root *root,
1522 struct btrfs_device *device)
1525 struct btrfs_path *path;
1526 struct btrfs_key key;
1527 struct btrfs_trans_handle *trans;
1529 root = root->fs_info->chunk_root;
1531 path = btrfs_alloc_path();
1535 trans = btrfs_start_transaction(root, 0);
1536 if (IS_ERR(trans)) {
1537 btrfs_free_path(path);
1538 return PTR_ERR(trans);
1540 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1541 key.type = BTRFS_DEV_ITEM_KEY;
1542 key.offset = device->devid;
1545 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1554 ret = btrfs_del_item(trans, root, path);
1558 btrfs_free_path(path);
1559 unlock_chunks(root);
1560 btrfs_commit_transaction(trans, root);
1564 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1566 struct btrfs_device *device;
1567 struct btrfs_device *next_device;
1568 struct block_device *bdev;
1569 struct buffer_head *bh = NULL;
1570 struct btrfs_super_block *disk_super;
1571 struct btrfs_fs_devices *cur_devices;
1578 bool clear_super = false;
1580 mutex_lock(&uuid_mutex);
1583 seq = read_seqbegin(&root->fs_info->profiles_lock);
1585 all_avail = root->fs_info->avail_data_alloc_bits |
1586 root->fs_info->avail_system_alloc_bits |
1587 root->fs_info->avail_metadata_alloc_bits;
1588 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
1590 num_devices = root->fs_info->fs_devices->num_devices;
1591 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1592 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1593 WARN_ON(num_devices < 1);
1596 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1598 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1599 ret = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1603 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1604 ret = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1608 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1609 root->fs_info->fs_devices->rw_devices <= 2) {
1610 ret = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1613 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1614 root->fs_info->fs_devices->rw_devices <= 3) {
1615 ret = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1619 if (strcmp(device_path, "missing") == 0) {
1620 struct list_head *devices;
1621 struct btrfs_device *tmp;
1624 devices = &root->fs_info->fs_devices->devices;
1626 * It is safe to read the devices since the volume_mutex
1629 list_for_each_entry(tmp, devices, dev_list) {
1630 if (tmp->in_fs_metadata &&
1631 !tmp->is_tgtdev_for_dev_replace &&
1641 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1645 ret = btrfs_get_bdev_and_sb(device_path,
1646 FMODE_WRITE | FMODE_EXCL,
1647 root->fs_info->bdev_holder, 0,
1651 disk_super = (struct btrfs_super_block *)bh->b_data;
1652 devid = btrfs_stack_device_id(&disk_super->dev_item);
1653 dev_uuid = disk_super->dev_item.uuid;
1654 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1662 if (device->is_tgtdev_for_dev_replace) {
1663 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1667 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1668 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1672 if (device->writeable) {
1674 list_del_init(&device->dev_alloc_list);
1675 unlock_chunks(root);
1676 root->fs_info->fs_devices->rw_devices--;
1680 mutex_unlock(&uuid_mutex);
1681 ret = btrfs_shrink_device(device, 0);
1682 mutex_lock(&uuid_mutex);
1687 * TODO: the superblock still includes this device in its num_devices
1688 * counter although write_all_supers() is not locked out. This
1689 * could give a filesystem state which requires a degraded mount.
1691 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1695 spin_lock(&root->fs_info->free_chunk_lock);
1696 root->fs_info->free_chunk_space = device->total_bytes -
1698 spin_unlock(&root->fs_info->free_chunk_lock);
1700 device->in_fs_metadata = 0;
1701 btrfs_scrub_cancel_dev(root->fs_info, device);
1704 * the device list mutex makes sure that we don't change
1705 * the device list while someone else is writing out all
1706 * the device supers. Whoever is writing all supers, should
1707 * lock the device list mutex before getting the number of
1708 * devices in the super block (super_copy). Conversely,
1709 * whoever updates the number of devices in the super block
1710 * (super_copy) should hold the device list mutex.
1713 cur_devices = device->fs_devices;
1714 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1715 list_del_rcu(&device->dev_list);
1717 device->fs_devices->num_devices--;
1718 device->fs_devices->total_devices--;
1720 if (device->missing)
1721 device->fs_devices->missing_devices--;
1723 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1724 struct btrfs_device, dev_list);
1725 if (device->bdev == root->fs_info->sb->s_bdev)
1726 root->fs_info->sb->s_bdev = next_device->bdev;
1727 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1728 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1731 device->fs_devices->open_devices--;
1732 /* remove sysfs entry */
1733 btrfs_kobj_rm_device(root->fs_info, device);
1736 call_rcu(&device->rcu, free_device);
1738 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1739 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1740 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1742 if (cur_devices->open_devices == 0) {
1743 struct btrfs_fs_devices *fs_devices;
1744 fs_devices = root->fs_info->fs_devices;
1745 while (fs_devices) {
1746 if (fs_devices->seed == cur_devices) {
1747 fs_devices->seed = cur_devices->seed;
1750 fs_devices = fs_devices->seed;
1752 cur_devices->seed = NULL;
1754 __btrfs_close_devices(cur_devices);
1755 unlock_chunks(root);
1756 free_fs_devices(cur_devices);
1759 root->fs_info->num_tolerated_disk_barrier_failures =
1760 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1763 * at this point, the device is zero sized. We want to
1764 * remove it from the devices list and zero out the old super
1766 if (clear_super && disk_super) {
1770 /* make sure this device isn't detected as part of
1773 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1774 set_buffer_dirty(bh);
1775 sync_dirty_buffer(bh);
1777 /* clear the mirror copies of super block on the disk
1778 * being removed, 0th copy is been taken care above and
1779 * the below would take of the rest
1781 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1782 bytenr = btrfs_sb_offset(i);
1783 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
1784 i_size_read(bdev->bd_inode))
1788 bh = __bread(bdev, bytenr / 4096,
1789 BTRFS_SUPER_INFO_SIZE);
1793 disk_super = (struct btrfs_super_block *)bh->b_data;
1795 if (btrfs_super_bytenr(disk_super) != bytenr ||
1796 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1799 memset(&disk_super->magic, 0,
1800 sizeof(disk_super->magic));
1801 set_buffer_dirty(bh);
1802 sync_dirty_buffer(bh);
1809 /* Notify udev that device has changed */
1810 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1812 /* Update ctime/mtime for device path for libblkid */
1813 update_dev_time(device_path);
1819 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1821 mutex_unlock(&uuid_mutex);
1824 if (device->writeable) {
1826 list_add(&device->dev_alloc_list,
1827 &root->fs_info->fs_devices->alloc_list);
1828 unlock_chunks(root);
1829 root->fs_info->fs_devices->rw_devices++;
1834 void btrfs_rm_dev_replace_srcdev(struct btrfs_fs_info *fs_info,
1835 struct btrfs_device *srcdev)
1837 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1839 list_del_rcu(&srcdev->dev_list);
1840 list_del_rcu(&srcdev->dev_alloc_list);
1841 fs_info->fs_devices->num_devices--;
1842 if (srcdev->missing) {
1843 fs_info->fs_devices->missing_devices--;
1844 fs_info->fs_devices->rw_devices++;
1846 if (srcdev->can_discard)
1847 fs_info->fs_devices->num_can_discard--;
1849 fs_info->fs_devices->open_devices--;
1851 /* zero out the old super */
1852 btrfs_scratch_superblock(srcdev);
1855 call_rcu(&srcdev->rcu, free_device);
1858 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1859 struct btrfs_device *tgtdev)
1861 struct btrfs_device *next_device;
1864 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1866 btrfs_scratch_superblock(tgtdev);
1867 fs_info->fs_devices->open_devices--;
1869 fs_info->fs_devices->num_devices--;
1870 if (tgtdev->can_discard)
1871 fs_info->fs_devices->num_can_discard++;
1873 next_device = list_entry(fs_info->fs_devices->devices.next,
1874 struct btrfs_device, dev_list);
1875 if (tgtdev->bdev == fs_info->sb->s_bdev)
1876 fs_info->sb->s_bdev = next_device->bdev;
1877 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1878 fs_info->fs_devices->latest_bdev = next_device->bdev;
1879 list_del_rcu(&tgtdev->dev_list);
1881 call_rcu(&tgtdev->rcu, free_device);
1883 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1886 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1887 struct btrfs_device **device)
1890 struct btrfs_super_block *disk_super;
1893 struct block_device *bdev;
1894 struct buffer_head *bh;
1897 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
1898 root->fs_info->bdev_holder, 0, &bdev, &bh);
1901 disk_super = (struct btrfs_super_block *)bh->b_data;
1902 devid = btrfs_stack_device_id(&disk_super->dev_item);
1903 dev_uuid = disk_super->dev_item.uuid;
1904 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1909 blkdev_put(bdev, FMODE_READ);
1913 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
1915 struct btrfs_device **device)
1918 if (strcmp(device_path, "missing") == 0) {
1919 struct list_head *devices;
1920 struct btrfs_device *tmp;
1922 devices = &root->fs_info->fs_devices->devices;
1924 * It is safe to read the devices since the volume_mutex
1925 * is held by the caller.
1927 list_for_each_entry(tmp, devices, dev_list) {
1928 if (tmp->in_fs_metadata && !tmp->bdev) {
1935 btrfs_err(root->fs_info, "no missing device found");
1941 return btrfs_find_device_by_path(root, device_path, device);
1946 * does all the dirty work required for changing file system's UUID.
1948 static int btrfs_prepare_sprout(struct btrfs_root *root)
1950 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1951 struct btrfs_fs_devices *old_devices;
1952 struct btrfs_fs_devices *seed_devices;
1953 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1954 struct btrfs_device *device;
1957 BUG_ON(!mutex_is_locked(&uuid_mutex));
1958 if (!fs_devices->seeding)
1961 seed_devices = __alloc_fs_devices();
1962 if (IS_ERR(seed_devices))
1963 return PTR_ERR(seed_devices);
1965 old_devices = clone_fs_devices(fs_devices);
1966 if (IS_ERR(old_devices)) {
1967 kfree(seed_devices);
1968 return PTR_ERR(old_devices);
1971 list_add(&old_devices->list, &fs_uuids);
1973 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1974 seed_devices->opened = 1;
1975 INIT_LIST_HEAD(&seed_devices->devices);
1976 INIT_LIST_HEAD(&seed_devices->alloc_list);
1977 mutex_init(&seed_devices->device_list_mutex);
1979 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1980 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1983 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1984 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1985 device->fs_devices = seed_devices;
1988 fs_devices->seeding = 0;
1989 fs_devices->num_devices = 0;
1990 fs_devices->open_devices = 0;
1991 fs_devices->missing_devices = 0;
1992 fs_devices->num_can_discard = 0;
1993 fs_devices->rotating = 0;
1994 fs_devices->seed = seed_devices;
1996 generate_random_uuid(fs_devices->fsid);
1997 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1998 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1999 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2001 super_flags = btrfs_super_flags(disk_super) &
2002 ~BTRFS_SUPER_FLAG_SEEDING;
2003 btrfs_set_super_flags(disk_super, super_flags);
2009 * strore the expected generation for seed devices in device items.
2011 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2012 struct btrfs_root *root)
2014 struct btrfs_path *path;
2015 struct extent_buffer *leaf;
2016 struct btrfs_dev_item *dev_item;
2017 struct btrfs_device *device;
2018 struct btrfs_key key;
2019 u8 fs_uuid[BTRFS_UUID_SIZE];
2020 u8 dev_uuid[BTRFS_UUID_SIZE];
2024 path = btrfs_alloc_path();
2028 root = root->fs_info->chunk_root;
2029 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2031 key.type = BTRFS_DEV_ITEM_KEY;
2034 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2038 leaf = path->nodes[0];
2040 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2041 ret = btrfs_next_leaf(root, path);
2046 leaf = path->nodes[0];
2047 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2048 btrfs_release_path(path);
2052 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2053 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2054 key.type != BTRFS_DEV_ITEM_KEY)
2057 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2058 struct btrfs_dev_item);
2059 devid = btrfs_device_id(leaf, dev_item);
2060 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2062 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2064 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2066 BUG_ON(!device); /* Logic error */
2068 if (device->fs_devices->seeding) {
2069 btrfs_set_device_generation(leaf, dev_item,
2070 device->generation);
2071 btrfs_mark_buffer_dirty(leaf);
2079 btrfs_free_path(path);
2083 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
2085 struct request_queue *q;
2086 struct btrfs_trans_handle *trans;
2087 struct btrfs_device *device;
2088 struct block_device *bdev;
2089 struct list_head *devices;
2090 struct super_block *sb = root->fs_info->sb;
2091 struct rcu_string *name;
2093 int seeding_dev = 0;
2096 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
2099 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2100 root->fs_info->bdev_holder);
2102 return PTR_ERR(bdev);
2104 if (root->fs_info->fs_devices->seeding) {
2106 down_write(&sb->s_umount);
2107 mutex_lock(&uuid_mutex);
2110 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2112 devices = &root->fs_info->fs_devices->devices;
2114 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2115 list_for_each_entry(device, devices, dev_list) {
2116 if (device->bdev == bdev) {
2119 &root->fs_info->fs_devices->device_list_mutex);
2123 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2125 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2126 if (IS_ERR(device)) {
2127 /* we can safely leave the fs_devices entry around */
2128 ret = PTR_ERR(device);
2132 name = rcu_string_strdup(device_path, GFP_NOFS);
2138 rcu_assign_pointer(device->name, name);
2140 trans = btrfs_start_transaction(root, 0);
2141 if (IS_ERR(trans)) {
2142 rcu_string_free(device->name);
2144 ret = PTR_ERR(trans);
2150 q = bdev_get_queue(bdev);
2151 if (blk_queue_discard(q))
2152 device->can_discard = 1;
2153 device->writeable = 1;
2154 device->generation = trans->transid;
2155 device->io_width = root->sectorsize;
2156 device->io_align = root->sectorsize;
2157 device->sector_size = root->sectorsize;
2158 device->total_bytes = i_size_read(bdev->bd_inode);
2159 device->disk_total_bytes = device->total_bytes;
2160 device->dev_root = root->fs_info->dev_root;
2161 device->bdev = bdev;
2162 device->in_fs_metadata = 1;
2163 device->is_tgtdev_for_dev_replace = 0;
2164 device->mode = FMODE_EXCL;
2165 device->dev_stats_valid = 1;
2166 set_blocksize(device->bdev, 4096);
2169 sb->s_flags &= ~MS_RDONLY;
2170 ret = btrfs_prepare_sprout(root);
2171 BUG_ON(ret); /* -ENOMEM */
2174 device->fs_devices = root->fs_info->fs_devices;
2176 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2177 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2178 list_add(&device->dev_alloc_list,
2179 &root->fs_info->fs_devices->alloc_list);
2180 root->fs_info->fs_devices->num_devices++;
2181 root->fs_info->fs_devices->open_devices++;
2182 root->fs_info->fs_devices->rw_devices++;
2183 root->fs_info->fs_devices->total_devices++;
2184 if (device->can_discard)
2185 root->fs_info->fs_devices->num_can_discard++;
2186 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2188 spin_lock(&root->fs_info->free_chunk_lock);
2189 root->fs_info->free_chunk_space += device->total_bytes;
2190 spin_unlock(&root->fs_info->free_chunk_lock);
2192 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2193 root->fs_info->fs_devices->rotating = 1;
2195 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2196 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2197 total_bytes + device->total_bytes);
2199 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
2200 btrfs_set_super_num_devices(root->fs_info->super_copy,
2203 /* add sysfs device entry */
2204 btrfs_kobj_add_device(root->fs_info, device);
2206 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2209 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2210 ret = init_first_rw_device(trans, root, device);
2212 btrfs_abort_transaction(trans, root, ret);
2215 ret = btrfs_finish_sprout(trans, root);
2217 btrfs_abort_transaction(trans, root, ret);
2221 /* Sprouting would change fsid of the mounted root,
2222 * so rename the fsid on the sysfs
2224 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2225 root->fs_info->fsid);
2226 if (kobject_rename(&root->fs_info->super_kobj, fsid_buf))
2229 ret = btrfs_add_device(trans, root, device);
2231 btrfs_abort_transaction(trans, root, ret);
2237 * we've got more storage, clear any full flags on the space
2240 btrfs_clear_space_info_full(root->fs_info);
2242 unlock_chunks(root);
2243 root->fs_info->num_tolerated_disk_barrier_failures =
2244 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2245 ret = btrfs_commit_transaction(trans, root);
2248 mutex_unlock(&uuid_mutex);
2249 up_write(&sb->s_umount);
2251 if (ret) /* transaction commit */
2254 ret = btrfs_relocate_sys_chunks(root);
2256 btrfs_error(root->fs_info, ret,
2257 "Failed to relocate sys chunks after "
2258 "device initialization. This can be fixed "
2259 "using the \"btrfs balance\" command.");
2260 trans = btrfs_attach_transaction(root);
2261 if (IS_ERR(trans)) {
2262 if (PTR_ERR(trans) == -ENOENT)
2264 return PTR_ERR(trans);
2266 ret = btrfs_commit_transaction(trans, root);
2269 /* Update ctime/mtime for libblkid */
2270 update_dev_time(device_path);
2274 unlock_chunks(root);
2275 btrfs_end_transaction(trans, root);
2276 rcu_string_free(device->name);
2277 btrfs_kobj_rm_device(root->fs_info, device);
2280 blkdev_put(bdev, FMODE_EXCL);
2282 mutex_unlock(&uuid_mutex);
2283 up_write(&sb->s_umount);
2288 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2289 struct btrfs_device **device_out)
2291 struct request_queue *q;
2292 struct btrfs_device *device;
2293 struct block_device *bdev;
2294 struct btrfs_fs_info *fs_info = root->fs_info;
2295 struct list_head *devices;
2296 struct rcu_string *name;
2297 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2301 if (fs_info->fs_devices->seeding)
2304 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2305 fs_info->bdev_holder);
2307 return PTR_ERR(bdev);
2309 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2311 devices = &fs_info->fs_devices->devices;
2312 list_for_each_entry(device, devices, dev_list) {
2313 if (device->bdev == bdev) {
2319 device = btrfs_alloc_device(NULL, &devid, NULL);
2320 if (IS_ERR(device)) {
2321 ret = PTR_ERR(device);
2325 name = rcu_string_strdup(device_path, GFP_NOFS);
2331 rcu_assign_pointer(device->name, name);
2333 q = bdev_get_queue(bdev);
2334 if (blk_queue_discard(q))
2335 device->can_discard = 1;
2336 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2337 device->writeable = 1;
2338 device->generation = 0;
2339 device->io_width = root->sectorsize;
2340 device->io_align = root->sectorsize;
2341 device->sector_size = root->sectorsize;
2342 device->total_bytes = i_size_read(bdev->bd_inode);
2343 device->disk_total_bytes = device->total_bytes;
2344 device->dev_root = fs_info->dev_root;
2345 device->bdev = bdev;
2346 device->in_fs_metadata = 1;
2347 device->is_tgtdev_for_dev_replace = 1;
2348 device->mode = FMODE_EXCL;
2349 device->dev_stats_valid = 1;
2350 set_blocksize(device->bdev, 4096);
2351 device->fs_devices = fs_info->fs_devices;
2352 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2353 fs_info->fs_devices->num_devices++;
2354 fs_info->fs_devices->open_devices++;
2355 if (device->can_discard)
2356 fs_info->fs_devices->num_can_discard++;
2357 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2359 *device_out = device;
2363 blkdev_put(bdev, FMODE_EXCL);
2367 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2368 struct btrfs_device *tgtdev)
2370 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2371 tgtdev->io_width = fs_info->dev_root->sectorsize;
2372 tgtdev->io_align = fs_info->dev_root->sectorsize;
2373 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2374 tgtdev->dev_root = fs_info->dev_root;
2375 tgtdev->in_fs_metadata = 1;
2378 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2379 struct btrfs_device *device)
2382 struct btrfs_path *path;
2383 struct btrfs_root *root;
2384 struct btrfs_dev_item *dev_item;
2385 struct extent_buffer *leaf;
2386 struct btrfs_key key;
2388 root = device->dev_root->fs_info->chunk_root;
2390 path = btrfs_alloc_path();
2394 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2395 key.type = BTRFS_DEV_ITEM_KEY;
2396 key.offset = device->devid;
2398 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2407 leaf = path->nodes[0];
2408 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2410 btrfs_set_device_id(leaf, dev_item, device->devid);
2411 btrfs_set_device_type(leaf, dev_item, device->type);
2412 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2413 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2414 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2415 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
2416 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
2417 btrfs_mark_buffer_dirty(leaf);
2420 btrfs_free_path(path);
2424 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
2425 struct btrfs_device *device, u64 new_size)
2427 struct btrfs_super_block *super_copy =
2428 device->dev_root->fs_info->super_copy;
2429 u64 old_total = btrfs_super_total_bytes(super_copy);
2430 u64 diff = new_size - device->total_bytes;
2432 if (!device->writeable)
2434 if (new_size <= device->total_bytes ||
2435 device->is_tgtdev_for_dev_replace)
2438 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2439 device->fs_devices->total_rw_bytes += diff;
2441 device->total_bytes = new_size;
2442 device->disk_total_bytes = new_size;
2443 btrfs_clear_space_info_full(device->dev_root->fs_info);
2445 return btrfs_update_device(trans, device);
2448 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2449 struct btrfs_device *device, u64 new_size)
2452 lock_chunks(device->dev_root);
2453 ret = __btrfs_grow_device(trans, device, new_size);
2454 unlock_chunks(device->dev_root);
2458 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2459 struct btrfs_root *root,
2460 u64 chunk_tree, u64 chunk_objectid,
2464 struct btrfs_path *path;
2465 struct btrfs_key key;
2467 root = root->fs_info->chunk_root;
2468 path = btrfs_alloc_path();
2472 key.objectid = chunk_objectid;
2473 key.offset = chunk_offset;
2474 key.type = BTRFS_CHUNK_ITEM_KEY;
2476 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2479 else if (ret > 0) { /* Logic error or corruption */
2480 btrfs_error(root->fs_info, -ENOENT,
2481 "Failed lookup while freeing chunk.");
2486 ret = btrfs_del_item(trans, root, path);
2488 btrfs_error(root->fs_info, ret,
2489 "Failed to delete chunk item.");
2491 btrfs_free_path(path);
2495 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2498 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2499 struct btrfs_disk_key *disk_key;
2500 struct btrfs_chunk *chunk;
2507 struct btrfs_key key;
2509 array_size = btrfs_super_sys_array_size(super_copy);
2511 ptr = super_copy->sys_chunk_array;
2514 while (cur < array_size) {
2515 disk_key = (struct btrfs_disk_key *)ptr;
2516 btrfs_disk_key_to_cpu(&key, disk_key);
2518 len = sizeof(*disk_key);
2520 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2521 chunk = (struct btrfs_chunk *)(ptr + len);
2522 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2523 len += btrfs_chunk_item_size(num_stripes);
2528 if (key.objectid == chunk_objectid &&
2529 key.offset == chunk_offset) {
2530 memmove(ptr, ptr + len, array_size - (cur + len));
2532 btrfs_set_super_sys_array_size(super_copy, array_size);
2541 static int btrfs_relocate_chunk(struct btrfs_root *root,
2542 u64 chunk_tree, u64 chunk_objectid,
2545 struct extent_map_tree *em_tree;
2546 struct btrfs_root *extent_root;
2547 struct btrfs_trans_handle *trans;
2548 struct extent_map *em;
2549 struct map_lookup *map;
2553 root = root->fs_info->chunk_root;
2554 extent_root = root->fs_info->extent_root;
2555 em_tree = &root->fs_info->mapping_tree.map_tree;
2557 ret = btrfs_can_relocate(extent_root, chunk_offset);
2561 /* step one, relocate all the extents inside this chunk */
2562 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2566 trans = btrfs_start_transaction(root, 0);
2567 if (IS_ERR(trans)) {
2568 ret = PTR_ERR(trans);
2569 btrfs_std_error(root->fs_info, ret);
2576 * step two, delete the device extents and the
2577 * chunk tree entries
2579 read_lock(&em_tree->lock);
2580 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2581 read_unlock(&em_tree->lock);
2583 BUG_ON(!em || em->start > chunk_offset ||
2584 em->start + em->len < chunk_offset);
2585 map = (struct map_lookup *)em->bdev;
2587 for (i = 0; i < map->num_stripes; i++) {
2588 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
2589 map->stripes[i].physical);
2592 if (map->stripes[i].dev) {
2593 ret = btrfs_update_device(trans, map->stripes[i].dev);
2597 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2602 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2604 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2605 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2609 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2612 write_lock(&em_tree->lock);
2613 remove_extent_mapping(em_tree, em);
2614 write_unlock(&em_tree->lock);
2616 /* once for the tree */
2617 free_extent_map(em);
2619 free_extent_map(em);
2621 unlock_chunks(root);
2622 btrfs_end_transaction(trans, root);
2626 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2628 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2629 struct btrfs_path *path;
2630 struct extent_buffer *leaf;
2631 struct btrfs_chunk *chunk;
2632 struct btrfs_key key;
2633 struct btrfs_key found_key;
2634 u64 chunk_tree = chunk_root->root_key.objectid;
2636 bool retried = false;
2640 path = btrfs_alloc_path();
2645 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2646 key.offset = (u64)-1;
2647 key.type = BTRFS_CHUNK_ITEM_KEY;
2650 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2653 BUG_ON(ret == 0); /* Corruption */
2655 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2662 leaf = path->nodes[0];
2663 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2665 chunk = btrfs_item_ptr(leaf, path->slots[0],
2666 struct btrfs_chunk);
2667 chunk_type = btrfs_chunk_type(leaf, chunk);
2668 btrfs_release_path(path);
2670 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2671 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2680 if (found_key.offset == 0)
2682 key.offset = found_key.offset - 1;
2685 if (failed && !retried) {
2689 } else if (WARN_ON(failed && retried)) {
2693 btrfs_free_path(path);
2697 static int insert_balance_item(struct btrfs_root *root,
2698 struct btrfs_balance_control *bctl)
2700 struct btrfs_trans_handle *trans;
2701 struct btrfs_balance_item *item;
2702 struct btrfs_disk_balance_args disk_bargs;
2703 struct btrfs_path *path;
2704 struct extent_buffer *leaf;
2705 struct btrfs_key key;
2708 path = btrfs_alloc_path();
2712 trans = btrfs_start_transaction(root, 0);
2713 if (IS_ERR(trans)) {
2714 btrfs_free_path(path);
2715 return PTR_ERR(trans);
2718 key.objectid = BTRFS_BALANCE_OBJECTID;
2719 key.type = BTRFS_BALANCE_ITEM_KEY;
2722 ret = btrfs_insert_empty_item(trans, root, path, &key,
2727 leaf = path->nodes[0];
2728 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2730 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2732 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2733 btrfs_set_balance_data(leaf, item, &disk_bargs);
2734 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2735 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2736 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2737 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2739 btrfs_set_balance_flags(leaf, item, bctl->flags);
2741 btrfs_mark_buffer_dirty(leaf);
2743 btrfs_free_path(path);
2744 err = btrfs_commit_transaction(trans, root);
2750 static int del_balance_item(struct btrfs_root *root)
2752 struct btrfs_trans_handle *trans;
2753 struct btrfs_path *path;
2754 struct btrfs_key key;
2757 path = btrfs_alloc_path();
2761 trans = btrfs_start_transaction(root, 0);
2762 if (IS_ERR(trans)) {
2763 btrfs_free_path(path);
2764 return PTR_ERR(trans);
2767 key.objectid = BTRFS_BALANCE_OBJECTID;
2768 key.type = BTRFS_BALANCE_ITEM_KEY;
2771 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2779 ret = btrfs_del_item(trans, root, path);
2781 btrfs_free_path(path);
2782 err = btrfs_commit_transaction(trans, root);
2789 * This is a heuristic used to reduce the number of chunks balanced on
2790 * resume after balance was interrupted.
2792 static void update_balance_args(struct btrfs_balance_control *bctl)
2795 * Turn on soft mode for chunk types that were being converted.
2797 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2798 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2799 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2800 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2801 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2802 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2805 * Turn on usage filter if is not already used. The idea is
2806 * that chunks that we have already balanced should be
2807 * reasonably full. Don't do it for chunks that are being
2808 * converted - that will keep us from relocating unconverted
2809 * (albeit full) chunks.
2811 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2812 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2813 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2814 bctl->data.usage = 90;
2816 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2817 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2818 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2819 bctl->sys.usage = 90;
2821 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2822 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2823 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2824 bctl->meta.usage = 90;
2829 * Should be called with both balance and volume mutexes held to
2830 * serialize other volume operations (add_dev/rm_dev/resize) with
2831 * restriper. Same goes for unset_balance_control.
2833 static void set_balance_control(struct btrfs_balance_control *bctl)
2835 struct btrfs_fs_info *fs_info = bctl->fs_info;
2837 BUG_ON(fs_info->balance_ctl);
2839 spin_lock(&fs_info->balance_lock);
2840 fs_info->balance_ctl = bctl;
2841 spin_unlock(&fs_info->balance_lock);
2844 static void unset_balance_control(struct btrfs_fs_info *fs_info)
2846 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2848 BUG_ON(!fs_info->balance_ctl);
2850 spin_lock(&fs_info->balance_lock);
2851 fs_info->balance_ctl = NULL;
2852 spin_unlock(&fs_info->balance_lock);
2858 * Balance filters. Return 1 if chunk should be filtered out
2859 * (should not be balanced).
2861 static int chunk_profiles_filter(u64 chunk_type,
2862 struct btrfs_balance_args *bargs)
2864 chunk_type = chunk_to_extended(chunk_type) &
2865 BTRFS_EXTENDED_PROFILE_MASK;
2867 if (bargs->profiles & chunk_type)
2873 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2874 struct btrfs_balance_args *bargs)
2876 struct btrfs_block_group_cache *cache;
2877 u64 chunk_used, user_thresh;
2880 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2881 chunk_used = btrfs_block_group_used(&cache->item);
2883 if (bargs->usage == 0)
2885 else if (bargs->usage > 100)
2886 user_thresh = cache->key.offset;
2888 user_thresh = div_factor_fine(cache->key.offset,
2891 if (chunk_used < user_thresh)
2894 btrfs_put_block_group(cache);
2898 static int chunk_devid_filter(struct extent_buffer *leaf,
2899 struct btrfs_chunk *chunk,
2900 struct btrfs_balance_args *bargs)
2902 struct btrfs_stripe *stripe;
2903 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2906 for (i = 0; i < num_stripes; i++) {
2907 stripe = btrfs_stripe_nr(chunk, i);
2908 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2915 /* [pstart, pend) */
2916 static int chunk_drange_filter(struct extent_buffer *leaf,
2917 struct btrfs_chunk *chunk,
2919 struct btrfs_balance_args *bargs)
2921 struct btrfs_stripe *stripe;
2922 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2928 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2931 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2932 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
2933 factor = num_stripes / 2;
2934 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
2935 factor = num_stripes - 1;
2936 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
2937 factor = num_stripes - 2;
2939 factor = num_stripes;
2942 for (i = 0; i < num_stripes; i++) {
2943 stripe = btrfs_stripe_nr(chunk, i);
2944 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2947 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2948 stripe_length = btrfs_chunk_length(leaf, chunk);
2949 do_div(stripe_length, factor);
2951 if (stripe_offset < bargs->pend &&
2952 stripe_offset + stripe_length > bargs->pstart)
2959 /* [vstart, vend) */
2960 static int chunk_vrange_filter(struct extent_buffer *leaf,
2961 struct btrfs_chunk *chunk,
2963 struct btrfs_balance_args *bargs)
2965 if (chunk_offset < bargs->vend &&
2966 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2967 /* at least part of the chunk is inside this vrange */
2973 static int chunk_soft_convert_filter(u64 chunk_type,
2974 struct btrfs_balance_args *bargs)
2976 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2979 chunk_type = chunk_to_extended(chunk_type) &
2980 BTRFS_EXTENDED_PROFILE_MASK;
2982 if (bargs->target == chunk_type)
2988 static int should_balance_chunk(struct btrfs_root *root,
2989 struct extent_buffer *leaf,
2990 struct btrfs_chunk *chunk, u64 chunk_offset)
2992 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2993 struct btrfs_balance_args *bargs = NULL;
2994 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2997 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2998 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3002 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3003 bargs = &bctl->data;
3004 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3006 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3007 bargs = &bctl->meta;
3009 /* profiles filter */
3010 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3011 chunk_profiles_filter(chunk_type, bargs)) {
3016 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3017 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
3022 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3023 chunk_devid_filter(leaf, chunk, bargs)) {
3027 /* drange filter, makes sense only with devid filter */
3028 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3029 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
3034 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3035 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3039 /* soft profile changing mode */
3040 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3041 chunk_soft_convert_filter(chunk_type, bargs)) {
3046 * limited by count, must be the last filter
3048 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3049 if (bargs->limit == 0)
3058 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3060 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3061 struct btrfs_root *chunk_root = fs_info->chunk_root;
3062 struct btrfs_root *dev_root = fs_info->dev_root;
3063 struct list_head *devices;
3064 struct btrfs_device *device;
3067 struct btrfs_chunk *chunk;
3068 struct btrfs_path *path;
3069 struct btrfs_key key;
3070 struct btrfs_key found_key;
3071 struct btrfs_trans_handle *trans;
3072 struct extent_buffer *leaf;
3075 int enospc_errors = 0;
3076 bool counting = true;
3077 u64 limit_data = bctl->data.limit;
3078 u64 limit_meta = bctl->meta.limit;
3079 u64 limit_sys = bctl->sys.limit;
3081 /* step one make some room on all the devices */
3082 devices = &fs_info->fs_devices->devices;
3083 list_for_each_entry(device, devices, dev_list) {
3084 old_size = device->total_bytes;
3085 size_to_free = div_factor(old_size, 1);
3086 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
3087 if (!device->writeable ||
3088 device->total_bytes - device->bytes_used > size_to_free ||
3089 device->is_tgtdev_for_dev_replace)
3092 ret = btrfs_shrink_device(device, old_size - size_to_free);
3097 trans = btrfs_start_transaction(dev_root, 0);
3098 BUG_ON(IS_ERR(trans));
3100 ret = btrfs_grow_device(trans, device, old_size);
3103 btrfs_end_transaction(trans, dev_root);
3106 /* step two, relocate all the chunks */
3107 path = btrfs_alloc_path();
3113 /* zero out stat counters */
3114 spin_lock(&fs_info->balance_lock);
3115 memset(&bctl->stat, 0, sizeof(bctl->stat));
3116 spin_unlock(&fs_info->balance_lock);
3119 bctl->data.limit = limit_data;
3120 bctl->meta.limit = limit_meta;
3121 bctl->sys.limit = limit_sys;
3123 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3124 key.offset = (u64)-1;
3125 key.type = BTRFS_CHUNK_ITEM_KEY;
3128 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3129 atomic_read(&fs_info->balance_cancel_req)) {
3134 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3139 * this shouldn't happen, it means the last relocate
3143 BUG(); /* FIXME break ? */
3145 ret = btrfs_previous_item(chunk_root, path, 0,
3146 BTRFS_CHUNK_ITEM_KEY);
3152 leaf = path->nodes[0];
3153 slot = path->slots[0];
3154 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3156 if (found_key.objectid != key.objectid)
3159 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3162 spin_lock(&fs_info->balance_lock);
3163 bctl->stat.considered++;
3164 spin_unlock(&fs_info->balance_lock);
3167 ret = should_balance_chunk(chunk_root, leaf, chunk,
3169 btrfs_release_path(path);
3174 spin_lock(&fs_info->balance_lock);
3175 bctl->stat.expected++;
3176 spin_unlock(&fs_info->balance_lock);
3180 ret = btrfs_relocate_chunk(chunk_root,
3181 chunk_root->root_key.objectid,
3184 if (ret && ret != -ENOSPC)
3186 if (ret == -ENOSPC) {
3189 spin_lock(&fs_info->balance_lock);
3190 bctl->stat.completed++;
3191 spin_unlock(&fs_info->balance_lock);
3194 if (found_key.offset == 0)
3196 key.offset = found_key.offset - 1;
3200 btrfs_release_path(path);
3205 btrfs_free_path(path);
3206 if (enospc_errors) {
3207 btrfs_info(fs_info, "%d enospc errors during balance",
3217 * alloc_profile_is_valid - see if a given profile is valid and reduced
3218 * @flags: profile to validate
3219 * @extended: if true @flags is treated as an extended profile
3221 static int alloc_profile_is_valid(u64 flags, int extended)
3223 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3224 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3226 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3228 /* 1) check that all other bits are zeroed */
3232 /* 2) see if profile is reduced */
3234 return !extended; /* "0" is valid for usual profiles */
3236 /* true if exactly one bit set */
3237 return (flags & (flags - 1)) == 0;
3240 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3242 /* cancel requested || normal exit path */
3243 return atomic_read(&fs_info->balance_cancel_req) ||
3244 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3245 atomic_read(&fs_info->balance_cancel_req) == 0);
3248 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3252 unset_balance_control(fs_info);
3253 ret = del_balance_item(fs_info->tree_root);
3255 btrfs_std_error(fs_info, ret);
3257 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3261 * Should be called with both balance and volume mutexes held
3263 int btrfs_balance(struct btrfs_balance_control *bctl,
3264 struct btrfs_ioctl_balance_args *bargs)
3266 struct btrfs_fs_info *fs_info = bctl->fs_info;
3273 if (btrfs_fs_closing(fs_info) ||
3274 atomic_read(&fs_info->balance_pause_req) ||
3275 atomic_read(&fs_info->balance_cancel_req)) {
3280 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3281 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3285 * In case of mixed groups both data and meta should be picked,
3286 * and identical options should be given for both of them.
3288 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3289 if (mixed && (bctl->flags & allowed)) {
3290 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3291 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3292 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3293 btrfs_err(fs_info, "with mixed groups data and "
3294 "metadata balance options must be the same");
3300 num_devices = fs_info->fs_devices->num_devices;
3301 btrfs_dev_replace_lock(&fs_info->dev_replace);
3302 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3303 BUG_ON(num_devices < 1);
3306 btrfs_dev_replace_unlock(&fs_info->dev_replace);
3307 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3308 if (num_devices == 1)
3309 allowed |= BTRFS_BLOCK_GROUP_DUP;
3310 else if (num_devices > 1)
3311 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3312 if (num_devices > 2)
3313 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3314 if (num_devices > 3)
3315 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3316 BTRFS_BLOCK_GROUP_RAID6);
3317 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3318 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3319 (bctl->data.target & ~allowed))) {
3320 btrfs_err(fs_info, "unable to start balance with target "
3321 "data profile %llu",
3326 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3327 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3328 (bctl->meta.target & ~allowed))) {
3330 "unable to start balance with target metadata profile %llu",
3335 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3336 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3337 (bctl->sys.target & ~allowed))) {
3339 "unable to start balance with target system profile %llu",
3345 /* allow dup'ed data chunks only in mixed mode */
3346 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3347 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
3348 btrfs_err(fs_info, "dup for data is not allowed");
3353 /* allow to reduce meta or sys integrity only if force set */
3354 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3355 BTRFS_BLOCK_GROUP_RAID10 |
3356 BTRFS_BLOCK_GROUP_RAID5 |
3357 BTRFS_BLOCK_GROUP_RAID6;
3359 seq = read_seqbegin(&fs_info->profiles_lock);
3361 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3362 (fs_info->avail_system_alloc_bits & allowed) &&
3363 !(bctl->sys.target & allowed)) ||
3364 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3365 (fs_info->avail_metadata_alloc_bits & allowed) &&
3366 !(bctl->meta.target & allowed))) {
3367 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3368 btrfs_info(fs_info, "force reducing metadata integrity");
3370 btrfs_err(fs_info, "balance will reduce metadata "
3371 "integrity, use force if you want this");
3376 } while (read_seqretry(&fs_info->profiles_lock, seq));
3378 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3379 int num_tolerated_disk_barrier_failures;
3380 u64 target = bctl->sys.target;
3382 num_tolerated_disk_barrier_failures =
3383 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3384 if (num_tolerated_disk_barrier_failures > 0 &&
3386 (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3387 BTRFS_AVAIL_ALLOC_BIT_SINGLE)))
3388 num_tolerated_disk_barrier_failures = 0;
3389 else if (num_tolerated_disk_barrier_failures > 1 &&
3391 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)))
3392 num_tolerated_disk_barrier_failures = 1;
3394 fs_info->num_tolerated_disk_barrier_failures =
3395 num_tolerated_disk_barrier_failures;
3398 ret = insert_balance_item(fs_info->tree_root, bctl);
3399 if (ret && ret != -EEXIST)
3402 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3403 BUG_ON(ret == -EEXIST);
3404 set_balance_control(bctl);
3406 BUG_ON(ret != -EEXIST);
3407 spin_lock(&fs_info->balance_lock);
3408 update_balance_args(bctl);
3409 spin_unlock(&fs_info->balance_lock);
3412 atomic_inc(&fs_info->balance_running);
3413 mutex_unlock(&fs_info->balance_mutex);
3415 ret = __btrfs_balance(fs_info);
3417 mutex_lock(&fs_info->balance_mutex);
3418 atomic_dec(&fs_info->balance_running);
3420 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3421 fs_info->num_tolerated_disk_barrier_failures =
3422 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3426 memset(bargs, 0, sizeof(*bargs));
3427 update_ioctl_balance_args(fs_info, 0, bargs);
3430 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3431 balance_need_close(fs_info)) {
3432 __cancel_balance(fs_info);
3435 wake_up(&fs_info->balance_wait_q);
3439 if (bctl->flags & BTRFS_BALANCE_RESUME)
3440 __cancel_balance(fs_info);
3443 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3448 static int balance_kthread(void *data)
3450 struct btrfs_fs_info *fs_info = data;
3453 mutex_lock(&fs_info->volume_mutex);
3454 mutex_lock(&fs_info->balance_mutex);
3456 if (fs_info->balance_ctl) {
3457 btrfs_info(fs_info, "continuing balance");
3458 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3461 mutex_unlock(&fs_info->balance_mutex);
3462 mutex_unlock(&fs_info->volume_mutex);
3467 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3469 struct task_struct *tsk;
3471 spin_lock(&fs_info->balance_lock);
3472 if (!fs_info->balance_ctl) {
3473 spin_unlock(&fs_info->balance_lock);
3476 spin_unlock(&fs_info->balance_lock);
3478 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3479 btrfs_info(fs_info, "force skipping balance");
3483 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3484 return PTR_ERR_OR_ZERO(tsk);
3487 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3489 struct btrfs_balance_control *bctl;
3490 struct btrfs_balance_item *item;
3491 struct btrfs_disk_balance_args disk_bargs;
3492 struct btrfs_path *path;
3493 struct extent_buffer *leaf;
3494 struct btrfs_key key;
3497 path = btrfs_alloc_path();
3501 key.objectid = BTRFS_BALANCE_OBJECTID;
3502 key.type = BTRFS_BALANCE_ITEM_KEY;
3505 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3508 if (ret > 0) { /* ret = -ENOENT; */
3513 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3519 leaf = path->nodes[0];
3520 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3522 bctl->fs_info = fs_info;
3523 bctl->flags = btrfs_balance_flags(leaf, item);
3524 bctl->flags |= BTRFS_BALANCE_RESUME;
3526 btrfs_balance_data(leaf, item, &disk_bargs);
3527 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3528 btrfs_balance_meta(leaf, item, &disk_bargs);
3529 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3530 btrfs_balance_sys(leaf, item, &disk_bargs);
3531 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3533 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3535 mutex_lock(&fs_info->volume_mutex);
3536 mutex_lock(&fs_info->balance_mutex);
3538 set_balance_control(bctl);
3540 mutex_unlock(&fs_info->balance_mutex);
3541 mutex_unlock(&fs_info->volume_mutex);
3543 btrfs_free_path(path);
3547 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3551 mutex_lock(&fs_info->balance_mutex);
3552 if (!fs_info->balance_ctl) {
3553 mutex_unlock(&fs_info->balance_mutex);
3557 if (atomic_read(&fs_info->balance_running)) {
3558 atomic_inc(&fs_info->balance_pause_req);
3559 mutex_unlock(&fs_info->balance_mutex);
3561 wait_event(fs_info->balance_wait_q,
3562 atomic_read(&fs_info->balance_running) == 0);
3564 mutex_lock(&fs_info->balance_mutex);
3565 /* we are good with balance_ctl ripped off from under us */
3566 BUG_ON(atomic_read(&fs_info->balance_running));
3567 atomic_dec(&fs_info->balance_pause_req);
3572 mutex_unlock(&fs_info->balance_mutex);
3576 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3578 if (fs_info->sb->s_flags & MS_RDONLY)
3581 mutex_lock(&fs_info->balance_mutex);
3582 if (!fs_info->balance_ctl) {
3583 mutex_unlock(&fs_info->balance_mutex);
3587 atomic_inc(&fs_info->balance_cancel_req);
3589 * if we are running just wait and return, balance item is
3590 * deleted in btrfs_balance in this case
3592 if (atomic_read(&fs_info->balance_running)) {
3593 mutex_unlock(&fs_info->balance_mutex);
3594 wait_event(fs_info->balance_wait_q,
3595 atomic_read(&fs_info->balance_running) == 0);
3596 mutex_lock(&fs_info->balance_mutex);
3598 /* __cancel_balance needs volume_mutex */
3599 mutex_unlock(&fs_info->balance_mutex);
3600 mutex_lock(&fs_info->volume_mutex);
3601 mutex_lock(&fs_info->balance_mutex);
3603 if (fs_info->balance_ctl)
3604 __cancel_balance(fs_info);
3606 mutex_unlock(&fs_info->volume_mutex);
3609 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3610 atomic_dec(&fs_info->balance_cancel_req);
3611 mutex_unlock(&fs_info->balance_mutex);
3615 static int btrfs_uuid_scan_kthread(void *data)
3617 struct btrfs_fs_info *fs_info = data;
3618 struct btrfs_root *root = fs_info->tree_root;
3619 struct btrfs_key key;
3620 struct btrfs_key max_key;
3621 struct btrfs_path *path = NULL;
3623 struct extent_buffer *eb;
3625 struct btrfs_root_item root_item;
3627 struct btrfs_trans_handle *trans = NULL;
3629 path = btrfs_alloc_path();
3636 key.type = BTRFS_ROOT_ITEM_KEY;
3639 max_key.objectid = (u64)-1;
3640 max_key.type = BTRFS_ROOT_ITEM_KEY;
3641 max_key.offset = (u64)-1;
3643 path->keep_locks = 1;
3646 ret = btrfs_search_forward(root, &key, path, 0);
3653 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3654 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3655 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3656 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3659 eb = path->nodes[0];
3660 slot = path->slots[0];
3661 item_size = btrfs_item_size_nr(eb, slot);
3662 if (item_size < sizeof(root_item))
3665 read_extent_buffer(eb, &root_item,
3666 btrfs_item_ptr_offset(eb, slot),
3667 (int)sizeof(root_item));
3668 if (btrfs_root_refs(&root_item) == 0)
3671 if (!btrfs_is_empty_uuid(root_item.uuid) ||
3672 !btrfs_is_empty_uuid(root_item.received_uuid)) {
3676 btrfs_release_path(path);
3678 * 1 - subvol uuid item
3679 * 1 - received_subvol uuid item
3681 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
3682 if (IS_ERR(trans)) {
3683 ret = PTR_ERR(trans);
3691 if (!btrfs_is_empty_uuid(root_item.uuid)) {
3692 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3694 BTRFS_UUID_KEY_SUBVOL,
3697 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3703 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
3704 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3705 root_item.received_uuid,
3706 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3709 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3717 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
3723 btrfs_release_path(path);
3724 if (key.offset < (u64)-1) {
3726 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
3728 key.type = BTRFS_ROOT_ITEM_KEY;
3729 } else if (key.objectid < (u64)-1) {
3731 key.type = BTRFS_ROOT_ITEM_KEY;
3740 btrfs_free_path(path);
3741 if (trans && !IS_ERR(trans))
3742 btrfs_end_transaction(trans, fs_info->uuid_root);
3744 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
3746 fs_info->update_uuid_tree_gen = 1;
3747 up(&fs_info->uuid_tree_rescan_sem);
3752 * Callback for btrfs_uuid_tree_iterate().
3754 * 0 check succeeded, the entry is not outdated.
3755 * < 0 if an error occured.
3756 * > 0 if the check failed, which means the caller shall remove the entry.
3758 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
3759 u8 *uuid, u8 type, u64 subid)
3761 struct btrfs_key key;
3763 struct btrfs_root *subvol_root;
3765 if (type != BTRFS_UUID_KEY_SUBVOL &&
3766 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
3769 key.objectid = subid;
3770 key.type = BTRFS_ROOT_ITEM_KEY;
3771 key.offset = (u64)-1;
3772 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
3773 if (IS_ERR(subvol_root)) {
3774 ret = PTR_ERR(subvol_root);
3781 case BTRFS_UUID_KEY_SUBVOL:
3782 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
3785 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
3786 if (memcmp(uuid, subvol_root->root_item.received_uuid,
3796 static int btrfs_uuid_rescan_kthread(void *data)
3798 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
3802 * 1st step is to iterate through the existing UUID tree and
3803 * to delete all entries that contain outdated data.
3804 * 2nd step is to add all missing entries to the UUID tree.
3806 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
3808 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
3809 up(&fs_info->uuid_tree_rescan_sem);
3812 return btrfs_uuid_scan_kthread(data);
3815 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
3817 struct btrfs_trans_handle *trans;
3818 struct btrfs_root *tree_root = fs_info->tree_root;
3819 struct btrfs_root *uuid_root;
3820 struct task_struct *task;
3827 trans = btrfs_start_transaction(tree_root, 2);
3829 return PTR_ERR(trans);
3831 uuid_root = btrfs_create_tree(trans, fs_info,
3832 BTRFS_UUID_TREE_OBJECTID);
3833 if (IS_ERR(uuid_root)) {
3834 btrfs_abort_transaction(trans, tree_root,
3835 PTR_ERR(uuid_root));
3836 return PTR_ERR(uuid_root);
3839 fs_info->uuid_root = uuid_root;
3841 ret = btrfs_commit_transaction(trans, tree_root);
3845 down(&fs_info->uuid_tree_rescan_sem);
3846 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
3848 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3849 btrfs_warn(fs_info, "failed to start uuid_scan task");
3850 up(&fs_info->uuid_tree_rescan_sem);
3851 return PTR_ERR(task);
3857 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
3859 struct task_struct *task;
3861 down(&fs_info->uuid_tree_rescan_sem);
3862 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
3864 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3865 btrfs_warn(fs_info, "failed to start uuid_rescan task");
3866 up(&fs_info->uuid_tree_rescan_sem);
3867 return PTR_ERR(task);
3874 * shrinking a device means finding all of the device extents past
3875 * the new size, and then following the back refs to the chunks.
3876 * The chunk relocation code actually frees the device extent
3878 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3880 struct btrfs_trans_handle *trans;
3881 struct btrfs_root *root = device->dev_root;
3882 struct btrfs_dev_extent *dev_extent = NULL;
3883 struct btrfs_path *path;
3891 bool retried = false;
3892 struct extent_buffer *l;
3893 struct btrfs_key key;
3894 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3895 u64 old_total = btrfs_super_total_bytes(super_copy);
3896 u64 old_size = device->total_bytes;
3897 u64 diff = device->total_bytes - new_size;
3899 if (device->is_tgtdev_for_dev_replace)
3902 path = btrfs_alloc_path();
3910 device->total_bytes = new_size;
3911 if (device->writeable) {
3912 device->fs_devices->total_rw_bytes -= diff;
3913 spin_lock(&root->fs_info->free_chunk_lock);
3914 root->fs_info->free_chunk_space -= diff;
3915 spin_unlock(&root->fs_info->free_chunk_lock);
3917 unlock_chunks(root);
3920 key.objectid = device->devid;
3921 key.offset = (u64)-1;
3922 key.type = BTRFS_DEV_EXTENT_KEY;
3925 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3929 ret = btrfs_previous_item(root, path, 0, key.type);
3934 btrfs_release_path(path);
3939 slot = path->slots[0];
3940 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3942 if (key.objectid != device->devid) {
3943 btrfs_release_path(path);
3947 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3948 length = btrfs_dev_extent_length(l, dev_extent);
3950 if (key.offset + length <= new_size) {
3951 btrfs_release_path(path);
3955 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3956 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3957 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3958 btrfs_release_path(path);
3960 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3962 if (ret && ret != -ENOSPC)
3966 } while (key.offset-- > 0);
3968 if (failed && !retried) {
3972 } else if (failed && retried) {
3976 device->total_bytes = old_size;
3977 if (device->writeable)
3978 device->fs_devices->total_rw_bytes += diff;
3979 spin_lock(&root->fs_info->free_chunk_lock);
3980 root->fs_info->free_chunk_space += diff;
3981 spin_unlock(&root->fs_info->free_chunk_lock);
3982 unlock_chunks(root);
3986 /* Shrinking succeeded, else we would be at "done". */
3987 trans = btrfs_start_transaction(root, 0);
3988 if (IS_ERR(trans)) {
3989 ret = PTR_ERR(trans);
3995 device->disk_total_bytes = new_size;
3996 /* Now btrfs_update_device() will change the on-disk size. */
3997 ret = btrfs_update_device(trans, device);
3999 unlock_chunks(root);
4000 btrfs_end_transaction(trans, root);
4003 WARN_ON(diff > old_total);
4004 btrfs_set_super_total_bytes(super_copy, old_total - diff);
4005 unlock_chunks(root);
4006 btrfs_end_transaction(trans, root);
4008 btrfs_free_path(path);
4012 static int btrfs_add_system_chunk(struct btrfs_root *root,
4013 struct btrfs_key *key,
4014 struct btrfs_chunk *chunk, int item_size)
4016 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4017 struct btrfs_disk_key disk_key;
4021 array_size = btrfs_super_sys_array_size(super_copy);
4022 if (array_size + item_size + sizeof(disk_key)
4023 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
4026 ptr = super_copy->sys_chunk_array + array_size;
4027 btrfs_cpu_key_to_disk(&disk_key, key);
4028 memcpy(ptr, &disk_key, sizeof(disk_key));
4029 ptr += sizeof(disk_key);
4030 memcpy(ptr, chunk, item_size);
4031 item_size += sizeof(disk_key);
4032 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4037 * sort the devices in descending order by max_avail, total_avail
4039 static int btrfs_cmp_device_info(const void *a, const void *b)
4041 const struct btrfs_device_info *di_a = a;
4042 const struct btrfs_device_info *di_b = b;
4044 if (di_a->max_avail > di_b->max_avail)
4046 if (di_a->max_avail < di_b->max_avail)
4048 if (di_a->total_avail > di_b->total_avail)
4050 if (di_a->total_avail < di_b->total_avail)
4055 static struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
4056 [BTRFS_RAID_RAID10] = {
4059 .devs_max = 0, /* 0 == as many as possible */
4061 .devs_increment = 2,
4064 [BTRFS_RAID_RAID1] = {
4069 .devs_increment = 2,
4072 [BTRFS_RAID_DUP] = {
4077 .devs_increment = 1,
4080 [BTRFS_RAID_RAID0] = {
4085 .devs_increment = 1,
4088 [BTRFS_RAID_SINGLE] = {
4093 .devs_increment = 1,
4096 [BTRFS_RAID_RAID5] = {
4101 .devs_increment = 1,
4104 [BTRFS_RAID_RAID6] = {
4109 .devs_increment = 1,
4114 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
4116 /* TODO allow them to set a preferred stripe size */
4120 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4122 if (!(type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)))
4125 btrfs_set_fs_incompat(info, RAID56);
4128 #define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r) \
4129 - sizeof(struct btrfs_item) \
4130 - sizeof(struct btrfs_chunk)) \
4131 / sizeof(struct btrfs_stripe) + 1)
4133 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4134 - 2 * sizeof(struct btrfs_disk_key) \
4135 - 2 * sizeof(struct btrfs_chunk)) \
4136 / sizeof(struct btrfs_stripe) + 1)
4138 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4139 struct btrfs_root *extent_root, u64 start,
4142 struct btrfs_fs_info *info = extent_root->fs_info;
4143 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4144 struct list_head *cur;
4145 struct map_lookup *map = NULL;
4146 struct extent_map_tree *em_tree;
4147 struct extent_map *em;
4148 struct btrfs_device_info *devices_info = NULL;
4150 int num_stripes; /* total number of stripes to allocate */
4151 int data_stripes; /* number of stripes that count for
4153 int sub_stripes; /* sub_stripes info for map */
4154 int dev_stripes; /* stripes per dev */
4155 int devs_max; /* max devs to use */
4156 int devs_min; /* min devs needed */
4157 int devs_increment; /* ndevs has to be a multiple of this */
4158 int ncopies; /* how many copies to data has */
4160 u64 max_stripe_size;
4164 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4170 BUG_ON(!alloc_profile_is_valid(type, 0));
4172 if (list_empty(&fs_devices->alloc_list))
4175 index = __get_raid_index(type);
4177 sub_stripes = btrfs_raid_array[index].sub_stripes;
4178 dev_stripes = btrfs_raid_array[index].dev_stripes;
4179 devs_max = btrfs_raid_array[index].devs_max;
4180 devs_min = btrfs_raid_array[index].devs_min;
4181 devs_increment = btrfs_raid_array[index].devs_increment;
4182 ncopies = btrfs_raid_array[index].ncopies;
4184 if (type & BTRFS_BLOCK_GROUP_DATA) {
4185 max_stripe_size = 1024 * 1024 * 1024;
4186 max_chunk_size = 10 * max_stripe_size;
4188 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4189 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4190 /* for larger filesystems, use larger metadata chunks */
4191 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
4192 max_stripe_size = 1024 * 1024 * 1024;
4194 max_stripe_size = 256 * 1024 * 1024;
4195 max_chunk_size = max_stripe_size;
4197 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4198 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4199 max_stripe_size = 32 * 1024 * 1024;
4200 max_chunk_size = 2 * max_stripe_size;
4202 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4204 btrfs_err(info, "invalid chunk type 0x%llx requested",
4209 /* we don't want a chunk larger than 10% of writeable space */
4210 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4213 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
4218 cur = fs_devices->alloc_list.next;
4221 * in the first pass through the devices list, we gather information
4222 * about the available holes on each device.
4225 while (cur != &fs_devices->alloc_list) {
4226 struct btrfs_device *device;
4230 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4234 if (!device->writeable) {
4236 "BTRFS: read-only device in alloc_list\n");
4240 if (!device->in_fs_metadata ||
4241 device->is_tgtdev_for_dev_replace)
4244 if (device->total_bytes > device->bytes_used)
4245 total_avail = device->total_bytes - device->bytes_used;
4249 /* If there is no space on this device, skip it. */
4250 if (total_avail == 0)
4253 ret = find_free_dev_extent(trans, device,
4254 max_stripe_size * dev_stripes,
4255 &dev_offset, &max_avail);
4256 if (ret && ret != -ENOSPC)
4260 max_avail = max_stripe_size * dev_stripes;
4262 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4265 if (ndevs == fs_devices->rw_devices) {
4266 WARN(1, "%s: found more than %llu devices\n",
4267 __func__, fs_devices->rw_devices);
4270 devices_info[ndevs].dev_offset = dev_offset;
4271 devices_info[ndevs].max_avail = max_avail;
4272 devices_info[ndevs].total_avail = total_avail;
4273 devices_info[ndevs].dev = device;
4278 * now sort the devices by hole size / available space
4280 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4281 btrfs_cmp_device_info, NULL);
4283 /* round down to number of usable stripes */
4284 ndevs -= ndevs % devs_increment;
4286 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4291 if (devs_max && ndevs > devs_max)
4294 * the primary goal is to maximize the number of stripes, so use as many
4295 * devices as possible, even if the stripes are not maximum sized.
4297 stripe_size = devices_info[ndevs-1].max_avail;
4298 num_stripes = ndevs * dev_stripes;
4301 * this will have to be fixed for RAID1 and RAID10 over
4304 data_stripes = num_stripes / ncopies;
4306 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4307 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4308 btrfs_super_stripesize(info->super_copy));
4309 data_stripes = num_stripes - 1;
4311 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4312 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4313 btrfs_super_stripesize(info->super_copy));
4314 data_stripes = num_stripes - 2;
4318 * Use the number of data stripes to figure out how big this chunk
4319 * is really going to be in terms of logical address space,
4320 * and compare that answer with the max chunk size
4322 if (stripe_size * data_stripes > max_chunk_size) {
4323 u64 mask = (1ULL << 24) - 1;
4324 stripe_size = max_chunk_size;
4325 do_div(stripe_size, data_stripes);
4327 /* bump the answer up to a 16MB boundary */
4328 stripe_size = (stripe_size + mask) & ~mask;
4330 /* but don't go higher than the limits we found
4331 * while searching for free extents
4333 if (stripe_size > devices_info[ndevs-1].max_avail)
4334 stripe_size = devices_info[ndevs-1].max_avail;
4337 do_div(stripe_size, dev_stripes);
4339 /* align to BTRFS_STRIPE_LEN */
4340 do_div(stripe_size, raid_stripe_len);
4341 stripe_size *= raid_stripe_len;
4343 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4348 map->num_stripes = num_stripes;
4350 for (i = 0; i < ndevs; ++i) {
4351 for (j = 0; j < dev_stripes; ++j) {
4352 int s = i * dev_stripes + j;
4353 map->stripes[s].dev = devices_info[i].dev;
4354 map->stripes[s].physical = devices_info[i].dev_offset +
4358 map->sector_size = extent_root->sectorsize;
4359 map->stripe_len = raid_stripe_len;
4360 map->io_align = raid_stripe_len;
4361 map->io_width = raid_stripe_len;
4363 map->sub_stripes = sub_stripes;
4365 num_bytes = stripe_size * data_stripes;
4367 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4369 em = alloc_extent_map();
4375 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4376 em->bdev = (struct block_device *)map;
4378 em->len = num_bytes;
4379 em->block_start = 0;
4380 em->block_len = em->len;
4381 em->orig_block_len = stripe_size;
4383 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4384 write_lock(&em_tree->lock);
4385 ret = add_extent_mapping(em_tree, em, 0);
4387 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4388 atomic_inc(&em->refs);
4390 write_unlock(&em_tree->lock);
4392 free_extent_map(em);
4396 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4397 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4400 goto error_del_extent;
4402 free_extent_map(em);
4403 check_raid56_incompat_flag(extent_root->fs_info, type);
4405 kfree(devices_info);
4409 write_lock(&em_tree->lock);
4410 remove_extent_mapping(em_tree, em);
4411 write_unlock(&em_tree->lock);
4413 /* One for our allocation */
4414 free_extent_map(em);
4415 /* One for the tree reference */
4416 free_extent_map(em);
4418 kfree(devices_info);
4422 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4423 struct btrfs_root *extent_root,
4424 u64 chunk_offset, u64 chunk_size)
4426 struct btrfs_key key;
4427 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4428 struct btrfs_device *device;
4429 struct btrfs_chunk *chunk;
4430 struct btrfs_stripe *stripe;
4431 struct extent_map_tree *em_tree;
4432 struct extent_map *em;
4433 struct map_lookup *map;
4440 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4441 read_lock(&em_tree->lock);
4442 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4443 read_unlock(&em_tree->lock);
4446 btrfs_crit(extent_root->fs_info, "unable to find logical "
4447 "%Lu len %Lu", chunk_offset, chunk_size);
4451 if (em->start != chunk_offset || em->len != chunk_size) {
4452 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4453 " %Lu-%Lu, found %Lu-%Lu", chunk_offset,
4454 chunk_size, em->start, em->len);
4455 free_extent_map(em);
4459 map = (struct map_lookup *)em->bdev;
4460 item_size = btrfs_chunk_item_size(map->num_stripes);
4461 stripe_size = em->orig_block_len;
4463 chunk = kzalloc(item_size, GFP_NOFS);
4469 for (i = 0; i < map->num_stripes; i++) {
4470 device = map->stripes[i].dev;
4471 dev_offset = map->stripes[i].physical;
4473 device->bytes_used += stripe_size;
4474 ret = btrfs_update_device(trans, device);
4477 ret = btrfs_alloc_dev_extent(trans, device,
4478 chunk_root->root_key.objectid,
4479 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4480 chunk_offset, dev_offset,
4486 spin_lock(&extent_root->fs_info->free_chunk_lock);
4487 extent_root->fs_info->free_chunk_space -= (stripe_size *
4489 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4491 stripe = &chunk->stripe;
4492 for (i = 0; i < map->num_stripes; i++) {
4493 device = map->stripes[i].dev;
4494 dev_offset = map->stripes[i].physical;
4496 btrfs_set_stack_stripe_devid(stripe, device->devid);
4497 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4498 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4502 btrfs_set_stack_chunk_length(chunk, chunk_size);
4503 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4504 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4505 btrfs_set_stack_chunk_type(chunk, map->type);
4506 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4507 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4508 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4509 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4510 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4512 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4513 key.type = BTRFS_CHUNK_ITEM_KEY;
4514 key.offset = chunk_offset;
4516 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4517 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4519 * TODO: Cleanup of inserted chunk root in case of
4522 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4528 free_extent_map(em);
4533 * Chunk allocation falls into two parts. The first part does works
4534 * that make the new allocated chunk useable, but not do any operation
4535 * that modifies the chunk tree. The second part does the works that
4536 * require modifying the chunk tree. This division is important for the
4537 * bootstrap process of adding storage to a seed btrfs.
4539 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4540 struct btrfs_root *extent_root, u64 type)
4544 chunk_offset = find_next_chunk(extent_root->fs_info);
4545 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4548 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4549 struct btrfs_root *root,
4550 struct btrfs_device *device)
4553 u64 sys_chunk_offset;
4555 struct btrfs_fs_info *fs_info = root->fs_info;
4556 struct btrfs_root *extent_root = fs_info->extent_root;
4559 chunk_offset = find_next_chunk(fs_info);
4560 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4561 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4566 sys_chunk_offset = find_next_chunk(root->fs_info);
4567 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4568 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4571 btrfs_abort_transaction(trans, root, ret);
4575 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
4577 btrfs_abort_transaction(trans, root, ret);
4582 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4584 struct extent_map *em;
4585 struct map_lookup *map;
4586 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4590 read_lock(&map_tree->map_tree.lock);
4591 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4592 read_unlock(&map_tree->map_tree.lock);
4596 if (btrfs_test_opt(root, DEGRADED)) {
4597 free_extent_map(em);
4601 map = (struct map_lookup *)em->bdev;
4602 for (i = 0; i < map->num_stripes; i++) {
4603 if (!map->stripes[i].dev->writeable) {
4608 free_extent_map(em);
4612 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4614 extent_map_tree_init(&tree->map_tree);
4617 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4619 struct extent_map *em;
4622 write_lock(&tree->map_tree.lock);
4623 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4625 remove_extent_mapping(&tree->map_tree, em);
4626 write_unlock(&tree->map_tree.lock);
4630 free_extent_map(em);
4631 /* once for the tree */
4632 free_extent_map(em);
4636 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4638 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4639 struct extent_map *em;
4640 struct map_lookup *map;
4641 struct extent_map_tree *em_tree = &map_tree->map_tree;
4644 read_lock(&em_tree->lock);
4645 em = lookup_extent_mapping(em_tree, logical, len);
4646 read_unlock(&em_tree->lock);
4649 * We could return errors for these cases, but that could get ugly and
4650 * we'd probably do the same thing which is just not do anything else
4651 * and exit, so return 1 so the callers don't try to use other copies.
4654 btrfs_crit(fs_info, "No mapping for %Lu-%Lu", logical,
4659 if (em->start > logical || em->start + em->len < logical) {
4660 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
4661 "%Lu-%Lu", logical, logical+len, em->start,
4662 em->start + em->len);
4663 free_extent_map(em);
4667 map = (struct map_lookup *)em->bdev;
4668 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4669 ret = map->num_stripes;
4670 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4671 ret = map->sub_stripes;
4672 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4674 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4678 free_extent_map(em);
4680 btrfs_dev_replace_lock(&fs_info->dev_replace);
4681 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4683 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4688 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4689 struct btrfs_mapping_tree *map_tree,
4692 struct extent_map *em;
4693 struct map_lookup *map;
4694 struct extent_map_tree *em_tree = &map_tree->map_tree;
4695 unsigned long len = root->sectorsize;
4697 read_lock(&em_tree->lock);
4698 em = lookup_extent_mapping(em_tree, logical, len);
4699 read_unlock(&em_tree->lock);
4702 BUG_ON(em->start > logical || em->start + em->len < logical);
4703 map = (struct map_lookup *)em->bdev;
4704 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4705 BTRFS_BLOCK_GROUP_RAID6)) {
4706 len = map->stripe_len * nr_data_stripes(map);
4708 free_extent_map(em);
4712 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4713 u64 logical, u64 len, int mirror_num)
4715 struct extent_map *em;
4716 struct map_lookup *map;
4717 struct extent_map_tree *em_tree = &map_tree->map_tree;
4720 read_lock(&em_tree->lock);
4721 em = lookup_extent_mapping(em_tree, logical, len);
4722 read_unlock(&em_tree->lock);
4725 BUG_ON(em->start > logical || em->start + em->len < logical);
4726 map = (struct map_lookup *)em->bdev;
4727 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4728 BTRFS_BLOCK_GROUP_RAID6))
4730 free_extent_map(em);
4734 static int find_live_mirror(struct btrfs_fs_info *fs_info,
4735 struct map_lookup *map, int first, int num,
4736 int optimal, int dev_replace_is_ongoing)
4740 struct btrfs_device *srcdev;
4742 if (dev_replace_is_ongoing &&
4743 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
4744 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
4745 srcdev = fs_info->dev_replace.srcdev;
4750 * try to avoid the drive that is the source drive for a
4751 * dev-replace procedure, only choose it if no other non-missing
4752 * mirror is available
4754 for (tolerance = 0; tolerance < 2; tolerance++) {
4755 if (map->stripes[optimal].dev->bdev &&
4756 (tolerance || map->stripes[optimal].dev != srcdev))
4758 for (i = first; i < first + num; i++) {
4759 if (map->stripes[i].dev->bdev &&
4760 (tolerance || map->stripes[i].dev != srcdev))
4765 /* we couldn't find one that doesn't fail. Just return something
4766 * and the io error handling code will clean up eventually
4771 static inline int parity_smaller(u64 a, u64 b)
4776 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
4777 static void sort_parity_stripes(struct btrfs_bio *bbio, u64 *raid_map)
4779 struct btrfs_bio_stripe s;
4786 for (i = 0; i < bbio->num_stripes - 1; i++) {
4787 if (parity_smaller(raid_map[i], raid_map[i+1])) {
4788 s = bbio->stripes[i];
4790 bbio->stripes[i] = bbio->stripes[i+1];
4791 raid_map[i] = raid_map[i+1];
4792 bbio->stripes[i+1] = s;
4800 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
4801 u64 logical, u64 *length,
4802 struct btrfs_bio **bbio_ret,
4803 int mirror_num, u64 **raid_map_ret)
4805 struct extent_map *em;
4806 struct map_lookup *map;
4807 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4808 struct extent_map_tree *em_tree = &map_tree->map_tree;
4811 u64 stripe_end_offset;
4816 u64 *raid_map = NULL;
4822 struct btrfs_bio *bbio = NULL;
4823 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
4824 int dev_replace_is_ongoing = 0;
4825 int num_alloc_stripes;
4826 int patch_the_first_stripe_for_dev_replace = 0;
4827 u64 physical_to_patch_in_first_stripe = 0;
4828 u64 raid56_full_stripe_start = (u64)-1;
4830 read_lock(&em_tree->lock);
4831 em = lookup_extent_mapping(em_tree, logical, *length);
4832 read_unlock(&em_tree->lock);
4835 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
4840 if (em->start > logical || em->start + em->len < logical) {
4841 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
4842 "found %Lu-%Lu", logical, em->start,
4843 em->start + em->len);
4844 free_extent_map(em);
4848 map = (struct map_lookup *)em->bdev;
4849 offset = logical - em->start;
4851 stripe_len = map->stripe_len;
4854 * stripe_nr counts the total number of stripes we have to stride
4855 * to get to this block
4857 do_div(stripe_nr, stripe_len);
4859 stripe_offset = stripe_nr * stripe_len;
4860 BUG_ON(offset < stripe_offset);
4862 /* stripe_offset is the offset of this block in its stripe*/
4863 stripe_offset = offset - stripe_offset;
4865 /* if we're here for raid56, we need to know the stripe aligned start */
4866 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4867 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
4868 raid56_full_stripe_start = offset;
4870 /* allow a write of a full stripe, but make sure we don't
4871 * allow straddling of stripes
4873 do_div(raid56_full_stripe_start, full_stripe_len);
4874 raid56_full_stripe_start *= full_stripe_len;
4877 if (rw & REQ_DISCARD) {
4878 /* we don't discard raid56 yet */
4880 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4884 *length = min_t(u64, em->len - offset, *length);
4885 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
4887 /* For writes to RAID[56], allow a full stripeset across all disks.
4888 For other RAID types and for RAID[56] reads, just allow a single
4889 stripe (on a single disk). */
4890 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6) &&
4892 max_len = stripe_len * nr_data_stripes(map) -
4893 (offset - raid56_full_stripe_start);
4895 /* we limit the length of each bio to what fits in a stripe */
4896 max_len = stripe_len - stripe_offset;
4898 *length = min_t(u64, em->len - offset, max_len);
4900 *length = em->len - offset;
4903 /* This is for when we're called from btrfs_merge_bio_hook() and all
4904 it cares about is the length */
4908 btrfs_dev_replace_lock(dev_replace);
4909 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
4910 if (!dev_replace_is_ongoing)
4911 btrfs_dev_replace_unlock(dev_replace);
4913 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
4914 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
4915 dev_replace->tgtdev != NULL) {
4917 * in dev-replace case, for repair case (that's the only
4918 * case where the mirror is selected explicitly when
4919 * calling btrfs_map_block), blocks left of the left cursor
4920 * can also be read from the target drive.
4921 * For REQ_GET_READ_MIRRORS, the target drive is added as
4922 * the last one to the array of stripes. For READ, it also
4923 * needs to be supported using the same mirror number.
4924 * If the requested block is not left of the left cursor,
4925 * EIO is returned. This can happen because btrfs_num_copies()
4926 * returns one more in the dev-replace case.
4928 u64 tmp_length = *length;
4929 struct btrfs_bio *tmp_bbio = NULL;
4930 int tmp_num_stripes;
4931 u64 srcdev_devid = dev_replace->srcdev->devid;
4932 int index_srcdev = 0;
4934 u64 physical_of_found = 0;
4936 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
4937 logical, &tmp_length, &tmp_bbio, 0, NULL);
4939 WARN_ON(tmp_bbio != NULL);
4943 tmp_num_stripes = tmp_bbio->num_stripes;
4944 if (mirror_num > tmp_num_stripes) {
4946 * REQ_GET_READ_MIRRORS does not contain this
4947 * mirror, that means that the requested area
4948 * is not left of the left cursor
4956 * process the rest of the function using the mirror_num
4957 * of the source drive. Therefore look it up first.
4958 * At the end, patch the device pointer to the one of the
4961 for (i = 0; i < tmp_num_stripes; i++) {
4962 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
4964 * In case of DUP, in order to keep it
4965 * simple, only add the mirror with the
4966 * lowest physical address
4969 physical_of_found <=
4970 tmp_bbio->stripes[i].physical)
4975 tmp_bbio->stripes[i].physical;
4980 mirror_num = index_srcdev + 1;
4981 patch_the_first_stripe_for_dev_replace = 1;
4982 physical_to_patch_in_first_stripe = physical_of_found;
4991 } else if (mirror_num > map->num_stripes) {
4997 stripe_nr_orig = stripe_nr;
4998 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
4999 do_div(stripe_nr_end, map->stripe_len);
5000 stripe_end_offset = stripe_nr_end * map->stripe_len -
5003 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5004 if (rw & REQ_DISCARD)
5005 num_stripes = min_t(u64, map->num_stripes,
5006 stripe_nr_end - stripe_nr_orig);
5007 stripe_index = do_div(stripe_nr, map->num_stripes);
5008 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5009 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
5010 num_stripes = map->num_stripes;
5011 else if (mirror_num)
5012 stripe_index = mirror_num - 1;
5014 stripe_index = find_live_mirror(fs_info, map, 0,
5016 current->pid % map->num_stripes,
5017 dev_replace_is_ongoing);
5018 mirror_num = stripe_index + 1;
5021 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5022 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
5023 num_stripes = map->num_stripes;
5024 } else if (mirror_num) {
5025 stripe_index = mirror_num - 1;
5030 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5031 int factor = map->num_stripes / map->sub_stripes;
5033 stripe_index = do_div(stripe_nr, factor);
5034 stripe_index *= map->sub_stripes;
5036 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5037 num_stripes = map->sub_stripes;
5038 else if (rw & REQ_DISCARD)
5039 num_stripes = min_t(u64, map->sub_stripes *
5040 (stripe_nr_end - stripe_nr_orig),
5042 else if (mirror_num)
5043 stripe_index += mirror_num - 1;
5045 int old_stripe_index = stripe_index;
5046 stripe_index = find_live_mirror(fs_info, map,
5048 map->sub_stripes, stripe_index +
5049 current->pid % map->sub_stripes,
5050 dev_replace_is_ongoing);
5051 mirror_num = stripe_index - old_stripe_index + 1;
5054 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5055 BTRFS_BLOCK_GROUP_RAID6)) {
5058 if (bbio_ret && ((rw & REQ_WRITE) || mirror_num > 1)
5062 /* push stripe_nr back to the start of the full stripe */
5063 stripe_nr = raid56_full_stripe_start;
5064 do_div(stripe_nr, stripe_len);
5066 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
5068 /* RAID[56] write or recovery. Return all stripes */
5069 num_stripes = map->num_stripes;
5070 max_errors = nr_parity_stripes(map);
5072 raid_map = kmalloc_array(num_stripes, sizeof(u64),
5079 /* Work out the disk rotation on this stripe-set */
5081 rot = do_div(tmp, num_stripes);
5083 /* Fill in the logical address of each stripe */
5084 tmp = stripe_nr * nr_data_stripes(map);
5085 for (i = 0; i < nr_data_stripes(map); i++)
5086 raid_map[(i+rot) % num_stripes] =
5087 em->start + (tmp + i) * map->stripe_len;
5089 raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5090 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5091 raid_map[(i+rot+1) % num_stripes] =
5094 *length = map->stripe_len;
5099 * Mirror #0 or #1 means the original data block.
5100 * Mirror #2 is RAID5 parity block.
5101 * Mirror #3 is RAID6 Q block.
5103 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
5105 stripe_index = nr_data_stripes(map) +
5108 /* We distribute the parity blocks across stripes */
5109 tmp = stripe_nr + stripe_index;
5110 stripe_index = do_div(tmp, map->num_stripes);
5114 * after this do_div call, stripe_nr is the number of stripes
5115 * on this device we have to walk to find the data, and
5116 * stripe_index is the number of our device in the stripe array
5118 stripe_index = do_div(stripe_nr, map->num_stripes);
5119 mirror_num = stripe_index + 1;
5121 BUG_ON(stripe_index >= map->num_stripes);
5123 num_alloc_stripes = num_stripes;
5124 if (dev_replace_is_ongoing) {
5125 if (rw & (REQ_WRITE | REQ_DISCARD))
5126 num_alloc_stripes <<= 1;
5127 if (rw & REQ_GET_READ_MIRRORS)
5128 num_alloc_stripes++;
5130 bbio = kzalloc(btrfs_bio_size(num_alloc_stripes), GFP_NOFS);
5136 atomic_set(&bbio->error, 0);
5138 if (rw & REQ_DISCARD) {
5140 int sub_stripes = 0;
5141 u64 stripes_per_dev = 0;
5142 u32 remaining_stripes = 0;
5143 u32 last_stripe = 0;
5146 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5147 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5150 sub_stripes = map->sub_stripes;
5152 factor = map->num_stripes / sub_stripes;
5153 stripes_per_dev = div_u64_rem(stripe_nr_end -
5156 &remaining_stripes);
5157 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5158 last_stripe *= sub_stripes;
5161 for (i = 0; i < num_stripes; i++) {
5162 bbio->stripes[i].physical =
5163 map->stripes[stripe_index].physical +
5164 stripe_offset + stripe_nr * map->stripe_len;
5165 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5167 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5168 BTRFS_BLOCK_GROUP_RAID10)) {
5169 bbio->stripes[i].length = stripes_per_dev *
5172 if (i / sub_stripes < remaining_stripes)
5173 bbio->stripes[i].length +=
5177 * Special for the first stripe and
5180 * |-------|...|-------|
5184 if (i < sub_stripes)
5185 bbio->stripes[i].length -=
5188 if (stripe_index >= last_stripe &&
5189 stripe_index <= (last_stripe +
5191 bbio->stripes[i].length -=
5194 if (i == sub_stripes - 1)
5197 bbio->stripes[i].length = *length;
5200 if (stripe_index == map->num_stripes) {
5201 /* This could only happen for RAID0/10 */
5207 for (i = 0; i < num_stripes; i++) {
5208 bbio->stripes[i].physical =
5209 map->stripes[stripe_index].physical +
5211 stripe_nr * map->stripe_len;
5212 bbio->stripes[i].dev =
5213 map->stripes[stripe_index].dev;
5218 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) {
5219 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5220 BTRFS_BLOCK_GROUP_RAID10 |
5221 BTRFS_BLOCK_GROUP_RAID5 |
5222 BTRFS_BLOCK_GROUP_DUP)) {
5224 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5229 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5230 dev_replace->tgtdev != NULL) {
5231 int index_where_to_add;
5232 u64 srcdev_devid = dev_replace->srcdev->devid;
5235 * duplicate the write operations while the dev replace
5236 * procedure is running. Since the copying of the old disk
5237 * to the new disk takes place at run time while the
5238 * filesystem is mounted writable, the regular write
5239 * operations to the old disk have to be duplicated to go
5240 * to the new disk as well.
5241 * Note that device->missing is handled by the caller, and
5242 * that the write to the old disk is already set up in the
5245 index_where_to_add = num_stripes;
5246 for (i = 0; i < num_stripes; i++) {
5247 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5248 /* write to new disk, too */
5249 struct btrfs_bio_stripe *new =
5250 bbio->stripes + index_where_to_add;
5251 struct btrfs_bio_stripe *old =
5254 new->physical = old->physical;
5255 new->length = old->length;
5256 new->dev = dev_replace->tgtdev;
5257 index_where_to_add++;
5261 num_stripes = index_where_to_add;
5262 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5263 dev_replace->tgtdev != NULL) {
5264 u64 srcdev_devid = dev_replace->srcdev->devid;
5265 int index_srcdev = 0;
5267 u64 physical_of_found = 0;
5270 * During the dev-replace procedure, the target drive can
5271 * also be used to read data in case it is needed to repair
5272 * a corrupt block elsewhere. This is possible if the
5273 * requested area is left of the left cursor. In this area,
5274 * the target drive is a full copy of the source drive.
5276 for (i = 0; i < num_stripes; i++) {
5277 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5279 * In case of DUP, in order to keep it
5280 * simple, only add the mirror with the
5281 * lowest physical address
5284 physical_of_found <=
5285 bbio->stripes[i].physical)
5289 physical_of_found = bbio->stripes[i].physical;
5293 u64 length = map->stripe_len;
5295 if (physical_of_found + length <=
5296 dev_replace->cursor_left) {
5297 struct btrfs_bio_stripe *tgtdev_stripe =
5298 bbio->stripes + num_stripes;
5300 tgtdev_stripe->physical = physical_of_found;
5301 tgtdev_stripe->length =
5302 bbio->stripes[index_srcdev].length;
5303 tgtdev_stripe->dev = dev_replace->tgtdev;
5311 bbio->num_stripes = num_stripes;
5312 bbio->max_errors = max_errors;
5313 bbio->mirror_num = mirror_num;
5316 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5317 * mirror_num == num_stripes + 1 && dev_replace target drive is
5318 * available as a mirror
5320 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5321 WARN_ON(num_stripes > 1);
5322 bbio->stripes[0].dev = dev_replace->tgtdev;
5323 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5324 bbio->mirror_num = map->num_stripes + 1;
5327 sort_parity_stripes(bbio, raid_map);
5328 *raid_map_ret = raid_map;
5331 if (dev_replace_is_ongoing)
5332 btrfs_dev_replace_unlock(dev_replace);
5333 free_extent_map(em);
5337 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5338 u64 logical, u64 *length,
5339 struct btrfs_bio **bbio_ret, int mirror_num)
5341 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5345 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5346 u64 chunk_start, u64 physical, u64 devid,
5347 u64 **logical, int *naddrs, int *stripe_len)
5349 struct extent_map_tree *em_tree = &map_tree->map_tree;
5350 struct extent_map *em;
5351 struct map_lookup *map;
5359 read_lock(&em_tree->lock);
5360 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5361 read_unlock(&em_tree->lock);
5364 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5369 if (em->start != chunk_start) {
5370 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5371 em->start, chunk_start);
5372 free_extent_map(em);
5375 map = (struct map_lookup *)em->bdev;
5378 rmap_len = map->stripe_len;
5380 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5381 do_div(length, map->num_stripes / map->sub_stripes);
5382 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5383 do_div(length, map->num_stripes);
5384 else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5385 BTRFS_BLOCK_GROUP_RAID6)) {
5386 do_div(length, nr_data_stripes(map));
5387 rmap_len = map->stripe_len * nr_data_stripes(map);
5390 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
5391 BUG_ON(!buf); /* -ENOMEM */
5393 for (i = 0; i < map->num_stripes; i++) {
5394 if (devid && map->stripes[i].dev->devid != devid)
5396 if (map->stripes[i].physical > physical ||
5397 map->stripes[i].physical + length <= physical)
5400 stripe_nr = physical - map->stripes[i].physical;
5401 do_div(stripe_nr, map->stripe_len);
5403 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5404 stripe_nr = stripe_nr * map->num_stripes + i;
5405 do_div(stripe_nr, map->sub_stripes);
5406 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5407 stripe_nr = stripe_nr * map->num_stripes + i;
5408 } /* else if RAID[56], multiply by nr_data_stripes().
5409 * Alternatively, just use rmap_len below instead of
5410 * map->stripe_len */
5412 bytenr = chunk_start + stripe_nr * rmap_len;
5413 WARN_ON(nr >= map->num_stripes);
5414 for (j = 0; j < nr; j++) {
5415 if (buf[j] == bytenr)
5419 WARN_ON(nr >= map->num_stripes);
5426 *stripe_len = rmap_len;
5428 free_extent_map(em);
5432 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio, int err)
5434 if (likely(bbio->flags & BTRFS_BIO_ORIG_BIO_SUBMITTED))
5435 bio_endio_nodec(bio, err);
5437 bio_endio(bio, err);
5441 static void btrfs_end_bio(struct bio *bio, int err)
5443 struct btrfs_bio *bbio = bio->bi_private;
5444 struct btrfs_device *dev = bbio->stripes[0].dev;
5445 int is_orig_bio = 0;
5448 atomic_inc(&bbio->error);
5449 if (err == -EIO || err == -EREMOTEIO) {
5450 unsigned int stripe_index =
5451 btrfs_io_bio(bio)->stripe_index;
5453 BUG_ON(stripe_index >= bbio->num_stripes);
5454 dev = bbio->stripes[stripe_index].dev;
5456 if (bio->bi_rw & WRITE)
5457 btrfs_dev_stat_inc(dev,
5458 BTRFS_DEV_STAT_WRITE_ERRS);
5460 btrfs_dev_stat_inc(dev,
5461 BTRFS_DEV_STAT_READ_ERRS);
5462 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5463 btrfs_dev_stat_inc(dev,
5464 BTRFS_DEV_STAT_FLUSH_ERRS);
5465 btrfs_dev_stat_print_on_error(dev);
5470 if (bio == bbio->orig_bio)
5473 btrfs_bio_counter_dec(bbio->fs_info);
5475 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5478 bio = bbio->orig_bio;
5481 bio->bi_private = bbio->private;
5482 bio->bi_end_io = bbio->end_io;
5483 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5484 /* only send an error to the higher layers if it is
5485 * beyond the tolerance of the btrfs bio
5487 if (atomic_read(&bbio->error) > bbio->max_errors) {
5491 * this bio is actually up to date, we didn't
5492 * go over the max number of errors
5494 set_bit(BIO_UPTODATE, &bio->bi_flags);
5498 btrfs_end_bbio(bbio, bio, err);
5499 } else if (!is_orig_bio) {
5505 * see run_scheduled_bios for a description of why bios are collected for
5508 * This will add one bio to the pending list for a device and make sure
5509 * the work struct is scheduled.
5511 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5512 struct btrfs_device *device,
5513 int rw, struct bio *bio)
5515 int should_queue = 1;
5516 struct btrfs_pending_bios *pending_bios;
5518 if (device->missing || !device->bdev) {
5519 bio_endio(bio, -EIO);
5523 /* don't bother with additional async steps for reads, right now */
5524 if (!(rw & REQ_WRITE)) {
5526 btrfsic_submit_bio(rw, bio);
5532 * nr_async_bios allows us to reliably return congestion to the
5533 * higher layers. Otherwise, the async bio makes it appear we have
5534 * made progress against dirty pages when we've really just put it
5535 * on a queue for later
5537 atomic_inc(&root->fs_info->nr_async_bios);
5538 WARN_ON(bio->bi_next);
5539 bio->bi_next = NULL;
5542 spin_lock(&device->io_lock);
5543 if (bio->bi_rw & REQ_SYNC)
5544 pending_bios = &device->pending_sync_bios;
5546 pending_bios = &device->pending_bios;
5548 if (pending_bios->tail)
5549 pending_bios->tail->bi_next = bio;
5551 pending_bios->tail = bio;
5552 if (!pending_bios->head)
5553 pending_bios->head = bio;
5554 if (device->running_pending)
5557 spin_unlock(&device->io_lock);
5560 btrfs_queue_work(root->fs_info->submit_workers,
5564 static int bio_size_ok(struct block_device *bdev, struct bio *bio,
5567 struct bio_vec *prev;
5568 struct request_queue *q = bdev_get_queue(bdev);
5569 unsigned int max_sectors = queue_max_sectors(q);
5570 struct bvec_merge_data bvm = {
5572 .bi_sector = sector,
5573 .bi_rw = bio->bi_rw,
5576 if (WARN_ON(bio->bi_vcnt == 0))
5579 prev = &bio->bi_io_vec[bio->bi_vcnt - 1];
5580 if (bio_sectors(bio) > max_sectors)
5583 if (!q->merge_bvec_fn)
5586 bvm.bi_size = bio->bi_iter.bi_size - prev->bv_len;
5587 if (q->merge_bvec_fn(q, &bvm, prev) < prev->bv_len)
5592 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5593 struct bio *bio, u64 physical, int dev_nr,
5596 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5598 bio->bi_private = bbio;
5599 btrfs_io_bio(bio)->stripe_index = dev_nr;
5600 bio->bi_end_io = btrfs_end_bio;
5601 bio->bi_iter.bi_sector = physical >> 9;
5604 struct rcu_string *name;
5607 name = rcu_dereference(dev->name);
5608 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5609 "(%s id %llu), size=%u\n", rw,
5610 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
5611 name->str, dev->devid, bio->bi_size);
5615 bio->bi_bdev = dev->bdev;
5617 btrfs_bio_counter_inc_noblocked(root->fs_info);
5620 btrfs_schedule_bio(root, dev, rw, bio);
5622 btrfsic_submit_bio(rw, bio);
5625 static int breakup_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5626 struct bio *first_bio, struct btrfs_device *dev,
5627 int dev_nr, int rw, int async)
5629 struct bio_vec *bvec = first_bio->bi_io_vec;
5631 int nr_vecs = bio_get_nr_vecs(dev->bdev);
5632 u64 physical = bbio->stripes[dev_nr].physical;
5635 bio = btrfs_bio_alloc(dev->bdev, physical >> 9, nr_vecs, GFP_NOFS);
5639 while (bvec <= (first_bio->bi_io_vec + first_bio->bi_vcnt - 1)) {
5640 if (bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5641 bvec->bv_offset) < bvec->bv_len) {
5642 u64 len = bio->bi_iter.bi_size;
5644 atomic_inc(&bbio->stripes_pending);
5645 submit_stripe_bio(root, bbio, bio, physical, dev_nr,
5653 submit_stripe_bio(root, bbio, bio, physical, dev_nr, rw, async);
5657 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5659 atomic_inc(&bbio->error);
5660 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5661 /* Shoud be the original bio. */
5662 WARN_ON(bio != bbio->orig_bio);
5664 bio->bi_private = bbio->private;
5665 bio->bi_end_io = bbio->end_io;
5666 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5667 bio->bi_iter.bi_sector = logical >> 9;
5669 btrfs_end_bbio(bbio, bio, -EIO);
5673 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
5674 int mirror_num, int async_submit)
5676 struct btrfs_device *dev;
5677 struct bio *first_bio = bio;
5678 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
5681 u64 *raid_map = NULL;
5685 struct btrfs_bio *bbio = NULL;
5687 length = bio->bi_iter.bi_size;
5688 map_length = length;
5690 btrfs_bio_counter_inc_blocked(root->fs_info);
5691 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5692 mirror_num, &raid_map);
5694 btrfs_bio_counter_dec(root->fs_info);
5698 total_devs = bbio->num_stripes;
5699 bbio->orig_bio = first_bio;
5700 bbio->private = first_bio->bi_private;
5701 bbio->end_io = first_bio->bi_end_io;
5702 bbio->fs_info = root->fs_info;
5703 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5706 /* In this case, map_length has been set to the length of
5707 a single stripe; not the whole write */
5709 ret = raid56_parity_write(root, bio, bbio,
5710 raid_map, map_length);
5712 ret = raid56_parity_recover(root, bio, bbio,
5713 raid_map, map_length,
5717 * FIXME, replace dosen't support raid56 yet, please fix
5720 btrfs_bio_counter_dec(root->fs_info);
5724 if (map_length < length) {
5725 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
5726 logical, length, map_length);
5730 while (dev_nr < total_devs) {
5731 dev = bbio->stripes[dev_nr].dev;
5732 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5733 bbio_error(bbio, first_bio, logical);
5739 * Check and see if we're ok with this bio based on it's size
5740 * and offset with the given device.
5742 if (!bio_size_ok(dev->bdev, first_bio,
5743 bbio->stripes[dev_nr].physical >> 9)) {
5744 ret = breakup_stripe_bio(root, bbio, first_bio, dev,
5745 dev_nr, rw, async_submit);
5751 if (dev_nr < total_devs - 1) {
5752 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
5753 BUG_ON(!bio); /* -ENOMEM */
5756 bbio->flags |= BTRFS_BIO_ORIG_BIO_SUBMITTED;
5759 submit_stripe_bio(root, bbio, bio,
5760 bbio->stripes[dev_nr].physical, dev_nr, rw,
5764 btrfs_bio_counter_dec(root->fs_info);
5768 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
5771 struct btrfs_device *device;
5772 struct btrfs_fs_devices *cur_devices;
5774 cur_devices = fs_info->fs_devices;
5775 while (cur_devices) {
5777 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5778 device = __find_device(&cur_devices->devices,
5783 cur_devices = cur_devices->seed;
5788 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
5789 u64 devid, u8 *dev_uuid)
5791 struct btrfs_device *device;
5792 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5794 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
5798 list_add(&device->dev_list, &fs_devices->devices);
5799 device->fs_devices = fs_devices;
5800 fs_devices->num_devices++;
5802 device->missing = 1;
5803 fs_devices->missing_devices++;
5809 * btrfs_alloc_device - allocate struct btrfs_device
5810 * @fs_info: used only for generating a new devid, can be NULL if
5811 * devid is provided (i.e. @devid != NULL).
5812 * @devid: a pointer to devid for this device. If NULL a new devid
5814 * @uuid: a pointer to UUID for this device. If NULL a new UUID
5817 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
5818 * on error. Returned struct is not linked onto any lists and can be
5819 * destroyed with kfree() right away.
5821 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
5825 struct btrfs_device *dev;
5828 if (WARN_ON(!devid && !fs_info))
5829 return ERR_PTR(-EINVAL);
5831 dev = __alloc_device();
5840 ret = find_next_devid(fs_info, &tmp);
5843 return ERR_PTR(ret);
5849 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
5851 generate_random_uuid(dev->uuid);
5853 btrfs_init_work(&dev->work, pending_bios_fn, NULL, NULL);
5858 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
5859 struct extent_buffer *leaf,
5860 struct btrfs_chunk *chunk)
5862 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5863 struct map_lookup *map;
5864 struct extent_map *em;
5868 u8 uuid[BTRFS_UUID_SIZE];
5873 logical = key->offset;
5874 length = btrfs_chunk_length(leaf, chunk);
5876 read_lock(&map_tree->map_tree.lock);
5877 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
5878 read_unlock(&map_tree->map_tree.lock);
5880 /* already mapped? */
5881 if (em && em->start <= logical && em->start + em->len > logical) {
5882 free_extent_map(em);
5885 free_extent_map(em);
5888 em = alloc_extent_map();
5891 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
5892 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5894 free_extent_map(em);
5898 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5899 em->bdev = (struct block_device *)map;
5900 em->start = logical;
5903 em->block_start = 0;
5904 em->block_len = em->len;
5906 map->num_stripes = num_stripes;
5907 map->io_width = btrfs_chunk_io_width(leaf, chunk);
5908 map->io_align = btrfs_chunk_io_align(leaf, chunk);
5909 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
5910 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
5911 map->type = btrfs_chunk_type(leaf, chunk);
5912 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
5913 for (i = 0; i < num_stripes; i++) {
5914 map->stripes[i].physical =
5915 btrfs_stripe_offset_nr(leaf, chunk, i);
5916 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
5917 read_extent_buffer(leaf, uuid, (unsigned long)
5918 btrfs_stripe_dev_uuid_nr(chunk, i),
5920 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
5922 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
5923 free_extent_map(em);
5926 if (!map->stripes[i].dev) {
5927 map->stripes[i].dev =
5928 add_missing_dev(root, devid, uuid);
5929 if (!map->stripes[i].dev) {
5930 free_extent_map(em);
5934 map->stripes[i].dev->in_fs_metadata = 1;
5937 write_lock(&map_tree->map_tree.lock);
5938 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
5939 write_unlock(&map_tree->map_tree.lock);
5940 BUG_ON(ret); /* Tree corruption */
5941 free_extent_map(em);
5946 static void fill_device_from_item(struct extent_buffer *leaf,
5947 struct btrfs_dev_item *dev_item,
5948 struct btrfs_device *device)
5952 device->devid = btrfs_device_id(leaf, dev_item);
5953 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
5954 device->total_bytes = device->disk_total_bytes;
5955 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
5956 device->type = btrfs_device_type(leaf, dev_item);
5957 device->io_align = btrfs_device_io_align(leaf, dev_item);
5958 device->io_width = btrfs_device_io_width(leaf, dev_item);
5959 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
5960 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
5961 device->is_tgtdev_for_dev_replace = 0;
5963 ptr = btrfs_device_uuid(dev_item);
5964 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
5967 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
5969 struct btrfs_fs_devices *fs_devices;
5972 BUG_ON(!mutex_is_locked(&uuid_mutex));
5974 fs_devices = root->fs_info->fs_devices->seed;
5975 while (fs_devices) {
5976 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5980 fs_devices = fs_devices->seed;
5983 fs_devices = find_fsid(fsid);
5989 fs_devices = clone_fs_devices(fs_devices);
5990 if (IS_ERR(fs_devices)) {
5991 ret = PTR_ERR(fs_devices);
5995 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
5996 root->fs_info->bdev_holder);
5998 free_fs_devices(fs_devices);
6002 if (!fs_devices->seeding) {
6003 __btrfs_close_devices(fs_devices);
6004 free_fs_devices(fs_devices);
6009 fs_devices->seed = root->fs_info->fs_devices->seed;
6010 root->fs_info->fs_devices->seed = fs_devices;
6015 static int read_one_dev(struct btrfs_root *root,
6016 struct extent_buffer *leaf,
6017 struct btrfs_dev_item *dev_item)
6019 struct btrfs_device *device;
6022 u8 fs_uuid[BTRFS_UUID_SIZE];
6023 u8 dev_uuid[BTRFS_UUID_SIZE];
6025 devid = btrfs_device_id(leaf, dev_item);
6026 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6028 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6031 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
6032 ret = open_seed_devices(root, fs_uuid);
6033 if (ret && !btrfs_test_opt(root, DEGRADED))
6037 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
6038 if (!device || !device->bdev) {
6039 if (!btrfs_test_opt(root, DEGRADED))
6043 btrfs_warn(root->fs_info, "devid %llu missing", devid);
6044 device = add_missing_dev(root, devid, dev_uuid);
6047 } else if (!device->missing) {
6049 * this happens when a device that was properly setup
6050 * in the device info lists suddenly goes bad.
6051 * device->bdev is NULL, and so we have to set
6052 * device->missing to one here
6054 root->fs_info->fs_devices->missing_devices++;
6055 device->missing = 1;
6059 if (device->fs_devices != root->fs_info->fs_devices) {
6060 BUG_ON(device->writeable);
6061 if (device->generation !=
6062 btrfs_device_generation(leaf, dev_item))
6066 fill_device_from_item(leaf, dev_item, device);
6067 device->in_fs_metadata = 1;
6068 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6069 device->fs_devices->total_rw_bytes += device->total_bytes;
6070 spin_lock(&root->fs_info->free_chunk_lock);
6071 root->fs_info->free_chunk_space += device->total_bytes -
6073 spin_unlock(&root->fs_info->free_chunk_lock);
6079 int btrfs_read_sys_array(struct btrfs_root *root)
6081 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
6082 struct extent_buffer *sb;
6083 struct btrfs_disk_key *disk_key;
6084 struct btrfs_chunk *chunk;
6086 unsigned long sb_ptr;
6092 struct btrfs_key key;
6094 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
6095 BTRFS_SUPER_INFO_SIZE);
6098 btrfs_set_buffer_uptodate(sb);
6099 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6101 * The sb extent buffer is artifical and just used to read the system array.
6102 * btrfs_set_buffer_uptodate() call does not properly mark all it's
6103 * pages up-to-date when the page is larger: extent does not cover the
6104 * whole page and consequently check_page_uptodate does not find all
6105 * the page's extents up-to-date (the hole beyond sb),
6106 * write_extent_buffer then triggers a WARN_ON.
6108 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6109 * but sb spans only this function. Add an explicit SetPageUptodate call
6110 * to silence the warning eg. on PowerPC 64.
6112 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
6113 SetPageUptodate(sb->pages[0]);
6115 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6116 array_size = btrfs_super_sys_array_size(super_copy);
6118 ptr = super_copy->sys_chunk_array;
6119 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
6122 while (cur < array_size) {
6123 disk_key = (struct btrfs_disk_key *)ptr;
6124 btrfs_disk_key_to_cpu(&key, disk_key);
6126 len = sizeof(*disk_key); ptr += len;
6130 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6131 chunk = (struct btrfs_chunk *)sb_ptr;
6132 ret = read_one_chunk(root, &key, sb, chunk);
6135 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6136 len = btrfs_chunk_item_size(num_stripes);
6145 free_extent_buffer(sb);
6149 int btrfs_read_chunk_tree(struct btrfs_root *root)
6151 struct btrfs_path *path;
6152 struct extent_buffer *leaf;
6153 struct btrfs_key key;
6154 struct btrfs_key found_key;
6158 root = root->fs_info->chunk_root;
6160 path = btrfs_alloc_path();
6164 mutex_lock(&uuid_mutex);
6168 * Read all device items, and then all the chunk items. All
6169 * device items are found before any chunk item (their object id
6170 * is smaller than the lowest possible object id for a chunk
6171 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6173 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6176 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6180 leaf = path->nodes[0];
6181 slot = path->slots[0];
6182 if (slot >= btrfs_header_nritems(leaf)) {
6183 ret = btrfs_next_leaf(root, path);
6190 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6191 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6192 struct btrfs_dev_item *dev_item;
6193 dev_item = btrfs_item_ptr(leaf, slot,
6194 struct btrfs_dev_item);
6195 ret = read_one_dev(root, leaf, dev_item);
6198 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6199 struct btrfs_chunk *chunk;
6200 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6201 ret = read_one_chunk(root, &found_key, leaf, chunk);
6209 unlock_chunks(root);
6210 mutex_unlock(&uuid_mutex);
6212 btrfs_free_path(path);
6216 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6218 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6219 struct btrfs_device *device;
6221 while (fs_devices) {
6222 mutex_lock(&fs_devices->device_list_mutex);
6223 list_for_each_entry(device, &fs_devices->devices, dev_list)
6224 device->dev_root = fs_info->dev_root;
6225 mutex_unlock(&fs_devices->device_list_mutex);
6227 fs_devices = fs_devices->seed;
6231 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6235 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6236 btrfs_dev_stat_reset(dev, i);
6239 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6241 struct btrfs_key key;
6242 struct btrfs_key found_key;
6243 struct btrfs_root *dev_root = fs_info->dev_root;
6244 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6245 struct extent_buffer *eb;
6248 struct btrfs_device *device;
6249 struct btrfs_path *path = NULL;
6252 path = btrfs_alloc_path();
6258 mutex_lock(&fs_devices->device_list_mutex);
6259 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6261 struct btrfs_dev_stats_item *ptr;
6264 key.type = BTRFS_DEV_STATS_KEY;
6265 key.offset = device->devid;
6266 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6268 __btrfs_reset_dev_stats(device);
6269 device->dev_stats_valid = 1;
6270 btrfs_release_path(path);
6273 slot = path->slots[0];
6274 eb = path->nodes[0];
6275 btrfs_item_key_to_cpu(eb, &found_key, slot);
6276 item_size = btrfs_item_size_nr(eb, slot);
6278 ptr = btrfs_item_ptr(eb, slot,
6279 struct btrfs_dev_stats_item);
6281 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6282 if (item_size >= (1 + i) * sizeof(__le64))
6283 btrfs_dev_stat_set(device, i,
6284 btrfs_dev_stats_value(eb, ptr, i));
6286 btrfs_dev_stat_reset(device, i);
6289 device->dev_stats_valid = 1;
6290 btrfs_dev_stat_print_on_load(device);
6291 btrfs_release_path(path);
6293 mutex_unlock(&fs_devices->device_list_mutex);
6296 btrfs_free_path(path);
6297 return ret < 0 ? ret : 0;
6300 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6301 struct btrfs_root *dev_root,
6302 struct btrfs_device *device)
6304 struct btrfs_path *path;
6305 struct btrfs_key key;
6306 struct extent_buffer *eb;
6307 struct btrfs_dev_stats_item *ptr;
6312 key.type = BTRFS_DEV_STATS_KEY;
6313 key.offset = device->devid;
6315 path = btrfs_alloc_path();
6317 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6319 printk_in_rcu(KERN_WARNING "BTRFS: "
6320 "error %d while searching for dev_stats item for device %s!\n",
6321 ret, rcu_str_deref(device->name));
6326 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6327 /* need to delete old one and insert a new one */
6328 ret = btrfs_del_item(trans, dev_root, path);
6330 printk_in_rcu(KERN_WARNING "BTRFS: "
6331 "delete too small dev_stats item for device %s failed %d!\n",
6332 rcu_str_deref(device->name), ret);
6339 /* need to insert a new item */
6340 btrfs_release_path(path);
6341 ret = btrfs_insert_empty_item(trans, dev_root, path,
6342 &key, sizeof(*ptr));
6344 printk_in_rcu(KERN_WARNING "BTRFS: "
6345 "insert dev_stats item for device %s failed %d!\n",
6346 rcu_str_deref(device->name), ret);
6351 eb = path->nodes[0];
6352 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6353 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6354 btrfs_set_dev_stats_value(eb, ptr, i,
6355 btrfs_dev_stat_read(device, i));
6356 btrfs_mark_buffer_dirty(eb);
6359 btrfs_free_path(path);
6364 * called from commit_transaction. Writes all changed device stats to disk.
6366 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6367 struct btrfs_fs_info *fs_info)
6369 struct btrfs_root *dev_root = fs_info->dev_root;
6370 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6371 struct btrfs_device *device;
6374 mutex_lock(&fs_devices->device_list_mutex);
6375 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6376 if (!device->dev_stats_valid || !device->dev_stats_dirty)
6379 ret = update_dev_stat_item(trans, dev_root, device);
6381 device->dev_stats_dirty = 0;
6383 mutex_unlock(&fs_devices->device_list_mutex);
6388 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6390 btrfs_dev_stat_inc(dev, index);
6391 btrfs_dev_stat_print_on_error(dev);
6394 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6396 if (!dev->dev_stats_valid)
6398 printk_ratelimited_in_rcu(KERN_ERR "BTRFS: "
6399 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6400 rcu_str_deref(dev->name),
6401 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6402 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6403 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6404 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6405 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6408 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6412 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6413 if (btrfs_dev_stat_read(dev, i) != 0)
6415 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6416 return; /* all values == 0, suppress message */
6418 printk_in_rcu(KERN_INFO "BTRFS: "
6419 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6420 rcu_str_deref(dev->name),
6421 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6422 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6423 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6424 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6425 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6428 int btrfs_get_dev_stats(struct btrfs_root *root,
6429 struct btrfs_ioctl_get_dev_stats *stats)
6431 struct btrfs_device *dev;
6432 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6435 mutex_lock(&fs_devices->device_list_mutex);
6436 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6437 mutex_unlock(&fs_devices->device_list_mutex);
6440 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6442 } else if (!dev->dev_stats_valid) {
6443 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6445 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6446 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6447 if (stats->nr_items > i)
6449 btrfs_dev_stat_read_and_reset(dev, i);
6451 btrfs_dev_stat_reset(dev, i);
6454 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6455 if (stats->nr_items > i)
6456 stats->values[i] = btrfs_dev_stat_read(dev, i);
6458 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6459 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6463 int btrfs_scratch_superblock(struct btrfs_device *device)
6465 struct buffer_head *bh;
6466 struct btrfs_super_block *disk_super;
6468 bh = btrfs_read_dev_super(device->bdev);
6471 disk_super = (struct btrfs_super_block *)bh->b_data;
6473 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6474 set_buffer_dirty(bh);
6475 sync_dirty_buffer(bh);