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 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
46 [BTRFS_RAID_RAID10] = {
49 .devs_max = 0, /* 0 == as many as possible */
51 .tolerated_failures = 1,
55 [BTRFS_RAID_RAID1] = {
60 .tolerated_failures = 1,
69 .tolerated_failures = 0,
73 [BTRFS_RAID_RAID0] = {
78 .tolerated_failures = 0,
82 [BTRFS_RAID_SINGLE] = {
87 .tolerated_failures = 0,
91 [BTRFS_RAID_RAID5] = {
96 .tolerated_failures = 1,
100 [BTRFS_RAID_RAID6] = {
105 .tolerated_failures = 2,
111 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
112 [BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
113 [BTRFS_RAID_RAID1] = BTRFS_BLOCK_GROUP_RAID1,
114 [BTRFS_RAID_DUP] = BTRFS_BLOCK_GROUP_DUP,
115 [BTRFS_RAID_RAID0] = BTRFS_BLOCK_GROUP_RAID0,
116 [BTRFS_RAID_SINGLE] = 0,
117 [BTRFS_RAID_RAID5] = BTRFS_BLOCK_GROUP_RAID5,
118 [BTRFS_RAID_RAID6] = BTRFS_BLOCK_GROUP_RAID6,
121 static int init_first_rw_device(struct btrfs_trans_handle *trans,
122 struct btrfs_root *root,
123 struct btrfs_device *device);
124 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
125 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
126 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
127 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
128 static void btrfs_close_one_device(struct btrfs_device *device);
130 DEFINE_MUTEX(uuid_mutex);
131 static LIST_HEAD(fs_uuids);
132 struct list_head *btrfs_get_fs_uuids(void)
137 static struct btrfs_fs_devices *__alloc_fs_devices(void)
139 struct btrfs_fs_devices *fs_devs;
141 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
143 return ERR_PTR(-ENOMEM);
145 mutex_init(&fs_devs->device_list_mutex);
147 INIT_LIST_HEAD(&fs_devs->devices);
148 INIT_LIST_HEAD(&fs_devs->resized_devices);
149 INIT_LIST_HEAD(&fs_devs->alloc_list);
150 INIT_LIST_HEAD(&fs_devs->list);
156 * alloc_fs_devices - allocate struct btrfs_fs_devices
157 * @fsid: a pointer to UUID for this FS. If NULL a new UUID is
160 * Return: a pointer to a new &struct btrfs_fs_devices on success;
161 * ERR_PTR() on error. Returned struct is not linked onto any lists and
162 * can be destroyed with kfree() right away.
164 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
166 struct btrfs_fs_devices *fs_devs;
168 fs_devs = __alloc_fs_devices();
173 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
175 generate_random_uuid(fs_devs->fsid);
180 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
182 struct btrfs_device *device;
183 WARN_ON(fs_devices->opened);
184 while (!list_empty(&fs_devices->devices)) {
185 device = list_entry(fs_devices->devices.next,
186 struct btrfs_device, dev_list);
187 list_del(&device->dev_list);
188 rcu_string_free(device->name);
194 static void btrfs_kobject_uevent(struct block_device *bdev,
195 enum kobject_action action)
199 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
201 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
203 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
204 &disk_to_dev(bdev->bd_disk)->kobj);
207 void btrfs_cleanup_fs_uuids(void)
209 struct btrfs_fs_devices *fs_devices;
211 while (!list_empty(&fs_uuids)) {
212 fs_devices = list_entry(fs_uuids.next,
213 struct btrfs_fs_devices, list);
214 list_del(&fs_devices->list);
215 free_fs_devices(fs_devices);
219 static struct btrfs_device *__alloc_device(void)
221 struct btrfs_device *dev;
223 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
225 return ERR_PTR(-ENOMEM);
227 INIT_LIST_HEAD(&dev->dev_list);
228 INIT_LIST_HEAD(&dev->dev_alloc_list);
229 INIT_LIST_HEAD(&dev->resized_list);
231 spin_lock_init(&dev->io_lock);
233 spin_lock_init(&dev->reada_lock);
234 atomic_set(&dev->reada_in_flight, 0);
235 atomic_set(&dev->dev_stats_ccnt, 0);
236 btrfs_device_data_ordered_init(dev);
237 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
238 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
243 static noinline struct btrfs_device *__find_device(struct list_head *head,
246 struct btrfs_device *dev;
248 list_for_each_entry(dev, head, dev_list) {
249 if (dev->devid == devid &&
250 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
257 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
259 struct btrfs_fs_devices *fs_devices;
261 list_for_each_entry(fs_devices, &fs_uuids, list) {
262 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
269 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
270 int flush, struct block_device **bdev,
271 struct buffer_head **bh)
275 *bdev = blkdev_get_by_path(device_path, flags, holder);
278 ret = PTR_ERR(*bdev);
283 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
284 ret = set_blocksize(*bdev, 4096);
286 blkdev_put(*bdev, flags);
289 invalidate_bdev(*bdev);
290 *bh = btrfs_read_dev_super(*bdev);
293 blkdev_put(*bdev, flags);
305 static void requeue_list(struct btrfs_pending_bios *pending_bios,
306 struct bio *head, struct bio *tail)
309 struct bio *old_head;
311 old_head = pending_bios->head;
312 pending_bios->head = head;
313 if (pending_bios->tail)
314 tail->bi_next = old_head;
316 pending_bios->tail = tail;
320 * we try to collect pending bios for a device so we don't get a large
321 * number of procs sending bios down to the same device. This greatly
322 * improves the schedulers ability to collect and merge the bios.
324 * But, it also turns into a long list of bios to process and that is sure
325 * to eventually make the worker thread block. The solution here is to
326 * make some progress and then put this work struct back at the end of
327 * the list if the block device is congested. This way, multiple devices
328 * can make progress from a single worker thread.
330 static noinline void run_scheduled_bios(struct btrfs_device *device)
333 struct backing_dev_info *bdi;
334 struct btrfs_fs_info *fs_info;
335 struct btrfs_pending_bios *pending_bios;
339 unsigned long num_run;
340 unsigned long batch_run = 0;
342 unsigned long last_waited = 0;
344 int sync_pending = 0;
345 struct blk_plug plug;
348 * this function runs all the bios we've collected for
349 * a particular device. We don't want to wander off to
350 * another device without first sending all of these down.
351 * So, setup a plug here and finish it off before we return
353 blk_start_plug(&plug);
355 bdi = blk_get_backing_dev_info(device->bdev);
356 fs_info = device->dev_root->fs_info;
357 limit = btrfs_async_submit_limit(fs_info);
358 limit = limit * 2 / 3;
361 spin_lock(&device->io_lock);
366 /* take all the bios off the list at once and process them
367 * later on (without the lock held). But, remember the
368 * tail and other pointers so the bios can be properly reinserted
369 * into the list if we hit congestion
371 if (!force_reg && device->pending_sync_bios.head) {
372 pending_bios = &device->pending_sync_bios;
375 pending_bios = &device->pending_bios;
379 pending = pending_bios->head;
380 tail = pending_bios->tail;
381 WARN_ON(pending && !tail);
384 * if pending was null this time around, no bios need processing
385 * at all and we can stop. Otherwise it'll loop back up again
386 * and do an additional check so no bios are missed.
388 * device->running_pending is used to synchronize with the
391 if (device->pending_sync_bios.head == NULL &&
392 device->pending_bios.head == NULL) {
394 device->running_pending = 0;
397 device->running_pending = 1;
400 pending_bios->head = NULL;
401 pending_bios->tail = NULL;
403 spin_unlock(&device->io_lock);
408 /* we want to work on both lists, but do more bios on the
409 * sync list than the regular list
412 pending_bios != &device->pending_sync_bios &&
413 device->pending_sync_bios.head) ||
414 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
415 device->pending_bios.head)) {
416 spin_lock(&device->io_lock);
417 requeue_list(pending_bios, pending, tail);
422 pending = pending->bi_next;
426 * atomic_dec_return implies a barrier for waitqueue_active
428 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
429 waitqueue_active(&fs_info->async_submit_wait))
430 wake_up(&fs_info->async_submit_wait);
432 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
435 * if we're doing the sync list, record that our
436 * plug has some sync requests on it
438 * If we're doing the regular list and there are
439 * sync requests sitting around, unplug before
442 if (pending_bios == &device->pending_sync_bios) {
444 } else if (sync_pending) {
445 blk_finish_plug(&plug);
446 blk_start_plug(&plug);
450 btrfsic_submit_bio(cur->bi_rw, cur);
457 * we made progress, there is more work to do and the bdi
458 * is now congested. Back off and let other work structs
461 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
462 fs_info->fs_devices->open_devices > 1) {
463 struct io_context *ioc;
465 ioc = current->io_context;
468 * the main goal here is that we don't want to
469 * block if we're going to be able to submit
470 * more requests without blocking.
472 * This code does two great things, it pokes into
473 * the elevator code from a filesystem _and_
474 * it makes assumptions about how batching works.
476 if (ioc && ioc->nr_batch_requests > 0 &&
477 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
479 ioc->last_waited == last_waited)) {
481 * we want to go through our batch of
482 * requests and stop. So, we copy out
483 * the ioc->last_waited time and test
484 * against it before looping
486 last_waited = ioc->last_waited;
490 spin_lock(&device->io_lock);
491 requeue_list(pending_bios, pending, tail);
492 device->running_pending = 1;
494 spin_unlock(&device->io_lock);
495 btrfs_queue_work(fs_info->submit_workers,
499 /* unplug every 64 requests just for good measure */
500 if (batch_run % 64 == 0) {
501 blk_finish_plug(&plug);
502 blk_start_plug(&plug);
511 spin_lock(&device->io_lock);
512 if (device->pending_bios.head || device->pending_sync_bios.head)
514 spin_unlock(&device->io_lock);
517 blk_finish_plug(&plug);
520 static void pending_bios_fn(struct btrfs_work *work)
522 struct btrfs_device *device;
524 device = container_of(work, struct btrfs_device, work);
525 run_scheduled_bios(device);
529 void btrfs_free_stale_device(struct btrfs_device *cur_dev)
531 struct btrfs_fs_devices *fs_devs;
532 struct btrfs_device *dev;
537 list_for_each_entry(fs_devs, &fs_uuids, list) {
542 if (fs_devs->seeding)
545 list_for_each_entry(dev, &fs_devs->devices, dev_list) {
553 * Todo: This won't be enough. What if the same device
554 * comes back (with new uuid and) with its mapper path?
555 * But for now, this does help as mostly an admin will
556 * either use mapper or non mapper path throughout.
559 del = strcmp(rcu_str_deref(dev->name),
560 rcu_str_deref(cur_dev->name));
567 /* delete the stale device */
568 if (fs_devs->num_devices == 1) {
569 btrfs_sysfs_remove_fsid(fs_devs);
570 list_del(&fs_devs->list);
571 free_fs_devices(fs_devs);
573 fs_devs->num_devices--;
574 list_del(&dev->dev_list);
575 rcu_string_free(dev->name);
584 * Add new device to list of registered devices
587 * 1 - first time device is seen
588 * 0 - device already known
591 static noinline int device_list_add(const char *path,
592 struct btrfs_super_block *disk_super,
593 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
595 struct btrfs_device *device;
596 struct btrfs_fs_devices *fs_devices;
597 struct rcu_string *name;
599 u64 found_transid = btrfs_super_generation(disk_super);
601 fs_devices = find_fsid(disk_super->fsid);
603 fs_devices = alloc_fs_devices(disk_super->fsid);
604 if (IS_ERR(fs_devices))
605 return PTR_ERR(fs_devices);
607 list_add(&fs_devices->list, &fs_uuids);
611 device = __find_device(&fs_devices->devices, devid,
612 disk_super->dev_item.uuid);
616 if (fs_devices->opened)
619 device = btrfs_alloc_device(NULL, &devid,
620 disk_super->dev_item.uuid);
621 if (IS_ERR(device)) {
622 /* we can safely leave the fs_devices entry around */
623 return PTR_ERR(device);
626 name = rcu_string_strdup(path, GFP_NOFS);
631 rcu_assign_pointer(device->name, name);
633 mutex_lock(&fs_devices->device_list_mutex);
634 list_add_rcu(&device->dev_list, &fs_devices->devices);
635 fs_devices->num_devices++;
636 mutex_unlock(&fs_devices->device_list_mutex);
639 device->fs_devices = fs_devices;
640 } else if (!device->name || strcmp(device->name->str, path)) {
642 * When FS is already mounted.
643 * 1. If you are here and if the device->name is NULL that
644 * means this device was missing at time of FS mount.
645 * 2. If you are here and if the device->name is different
646 * from 'path' that means either
647 * a. The same device disappeared and reappeared with
649 * b. The missing-disk-which-was-replaced, has
652 * We must allow 1 and 2a above. But 2b would be a spurious
655 * Further in case of 1 and 2a above, the disk at 'path'
656 * would have missed some transaction when it was away and
657 * in case of 2a the stale bdev has to be updated as well.
658 * 2b must not be allowed at all time.
662 * For now, we do allow update to btrfs_fs_device through the
663 * btrfs dev scan cli after FS has been mounted. We're still
664 * tracking a problem where systems fail mount by subvolume id
665 * when we reject replacement on a mounted FS.
667 if (!fs_devices->opened && found_transid < device->generation) {
669 * That is if the FS is _not_ mounted and if you
670 * are here, that means there is more than one
671 * disk with same uuid and devid.We keep the one
672 * with larger generation number or the last-in if
673 * generation are equal.
678 name = rcu_string_strdup(path, GFP_NOFS);
681 rcu_string_free(device->name);
682 rcu_assign_pointer(device->name, name);
683 if (device->missing) {
684 fs_devices->missing_devices--;
690 * Unmount does not free the btrfs_device struct but would zero
691 * generation along with most of the other members. So just update
692 * it back. We need it to pick the disk with largest generation
695 if (!fs_devices->opened)
696 device->generation = found_transid;
699 * if there is new btrfs on an already registered device,
700 * then remove the stale device entry.
703 btrfs_free_stale_device(device);
705 *fs_devices_ret = fs_devices;
710 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
712 struct btrfs_fs_devices *fs_devices;
713 struct btrfs_device *device;
714 struct btrfs_device *orig_dev;
716 fs_devices = alloc_fs_devices(orig->fsid);
717 if (IS_ERR(fs_devices))
720 mutex_lock(&orig->device_list_mutex);
721 fs_devices->total_devices = orig->total_devices;
723 /* We have held the volume lock, it is safe to get the devices. */
724 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
725 struct rcu_string *name;
727 device = btrfs_alloc_device(NULL, &orig_dev->devid,
733 * This is ok to do without rcu read locked because we hold the
734 * uuid mutex so nothing we touch in here is going to disappear.
736 if (orig_dev->name) {
737 name = rcu_string_strdup(orig_dev->name->str,
743 rcu_assign_pointer(device->name, name);
746 list_add(&device->dev_list, &fs_devices->devices);
747 device->fs_devices = fs_devices;
748 fs_devices->num_devices++;
750 mutex_unlock(&orig->device_list_mutex);
753 mutex_unlock(&orig->device_list_mutex);
754 free_fs_devices(fs_devices);
755 return ERR_PTR(-ENOMEM);
758 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
760 struct btrfs_device *device, *next;
761 struct btrfs_device *latest_dev = NULL;
763 mutex_lock(&uuid_mutex);
765 /* This is the initialized path, it is safe to release the devices. */
766 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
767 if (device->in_fs_metadata) {
768 if (!device->is_tgtdev_for_dev_replace &&
770 device->generation > latest_dev->generation)) {
776 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
778 * In the first step, keep the device which has
779 * the correct fsid and the devid that is used
780 * for the dev_replace procedure.
781 * In the second step, the dev_replace state is
782 * read from the device tree and it is known
783 * whether the procedure is really active or
784 * not, which means whether this device is
785 * used or whether it should be removed.
787 if (step == 0 || device->is_tgtdev_for_dev_replace) {
792 blkdev_put(device->bdev, device->mode);
794 fs_devices->open_devices--;
796 if (device->writeable) {
797 list_del_init(&device->dev_alloc_list);
798 device->writeable = 0;
799 if (!device->is_tgtdev_for_dev_replace)
800 fs_devices->rw_devices--;
802 list_del_init(&device->dev_list);
803 fs_devices->num_devices--;
804 rcu_string_free(device->name);
808 if (fs_devices->seed) {
809 fs_devices = fs_devices->seed;
813 fs_devices->latest_bdev = latest_dev->bdev;
815 mutex_unlock(&uuid_mutex);
818 static void __free_device(struct work_struct *work)
820 struct btrfs_device *device;
822 device = container_of(work, struct btrfs_device, rcu_work);
825 blkdev_put(device->bdev, device->mode);
827 rcu_string_free(device->name);
831 static void free_device(struct rcu_head *head)
833 struct btrfs_device *device;
835 device = container_of(head, struct btrfs_device, rcu);
837 INIT_WORK(&device->rcu_work, __free_device);
838 schedule_work(&device->rcu_work);
841 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
843 struct btrfs_device *device, *tmp;
845 if (--fs_devices->opened > 0)
848 mutex_lock(&fs_devices->device_list_mutex);
849 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
850 btrfs_close_one_device(device);
852 mutex_unlock(&fs_devices->device_list_mutex);
854 WARN_ON(fs_devices->open_devices);
855 WARN_ON(fs_devices->rw_devices);
856 fs_devices->opened = 0;
857 fs_devices->seeding = 0;
862 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
864 struct btrfs_fs_devices *seed_devices = NULL;
867 mutex_lock(&uuid_mutex);
868 ret = __btrfs_close_devices(fs_devices);
869 if (!fs_devices->opened) {
870 seed_devices = fs_devices->seed;
871 fs_devices->seed = NULL;
873 mutex_unlock(&uuid_mutex);
875 while (seed_devices) {
876 fs_devices = seed_devices;
877 seed_devices = fs_devices->seed;
878 __btrfs_close_devices(fs_devices);
879 free_fs_devices(fs_devices);
882 * Wait for rcu kworkers under __btrfs_close_devices
883 * to finish all blkdev_puts so device is really
884 * free when umount is done.
890 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
891 fmode_t flags, void *holder)
893 struct request_queue *q;
894 struct block_device *bdev;
895 struct list_head *head = &fs_devices->devices;
896 struct btrfs_device *device;
897 struct btrfs_device *latest_dev = NULL;
898 struct buffer_head *bh;
899 struct btrfs_super_block *disk_super;
906 list_for_each_entry(device, head, dev_list) {
912 /* Just open everything we can; ignore failures here */
913 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
917 disk_super = (struct btrfs_super_block *)bh->b_data;
918 devid = btrfs_stack_device_id(&disk_super->dev_item);
919 if (devid != device->devid)
922 if (memcmp(device->uuid, disk_super->dev_item.uuid,
926 device->generation = btrfs_super_generation(disk_super);
928 device->generation > latest_dev->generation)
931 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
932 device->writeable = 0;
934 device->writeable = !bdev_read_only(bdev);
938 q = bdev_get_queue(bdev);
939 if (blk_queue_discard(q))
940 device->can_discard = 1;
943 device->in_fs_metadata = 0;
944 device->mode = flags;
946 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
947 fs_devices->rotating = 1;
949 fs_devices->open_devices++;
950 if (device->writeable &&
951 device->devid != BTRFS_DEV_REPLACE_DEVID) {
952 fs_devices->rw_devices++;
953 list_add(&device->dev_alloc_list,
954 &fs_devices->alloc_list);
961 blkdev_put(bdev, flags);
964 if (fs_devices->open_devices == 0) {
968 fs_devices->seeding = seeding;
969 fs_devices->opened = 1;
970 fs_devices->latest_bdev = latest_dev->bdev;
971 fs_devices->total_rw_bytes = 0;
976 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
977 fmode_t flags, void *holder)
981 mutex_lock(&uuid_mutex);
982 if (fs_devices->opened) {
983 fs_devices->opened++;
986 ret = __btrfs_open_devices(fs_devices, flags, holder);
988 mutex_unlock(&uuid_mutex);
992 void btrfs_release_disk_super(struct page *page)
998 int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
999 struct page **page, struct btrfs_super_block **disk_super)
1004 /* make sure our super fits in the device */
1005 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1008 /* make sure our super fits in the page */
1009 if (sizeof(**disk_super) > PAGE_SIZE)
1012 /* make sure our super doesn't straddle pages on disk */
1013 index = bytenr >> PAGE_SHIFT;
1014 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1017 /* pull in the page with our super */
1018 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1021 if (IS_ERR_OR_NULL(*page))
1026 /* align our pointer to the offset of the super block */
1027 *disk_super = p + (bytenr & ~PAGE_MASK);
1029 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1030 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1031 btrfs_release_disk_super(*page);
1035 if ((*disk_super)->label[0] &&
1036 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1037 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1043 * Look for a btrfs signature on a device. This may be called out of the mount path
1044 * and we are not allowed to call set_blocksize during the scan. The superblock
1045 * is read via pagecache
1047 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1048 struct btrfs_fs_devices **fs_devices_ret)
1050 struct btrfs_super_block *disk_super;
1051 struct block_device *bdev;
1060 * we would like to check all the supers, but that would make
1061 * a btrfs mount succeed after a mkfs from a different FS.
1062 * So, we need to add a special mount option to scan for
1063 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1065 bytenr = btrfs_sb_offset(0);
1066 flags |= FMODE_EXCL;
1067 mutex_lock(&uuid_mutex);
1069 bdev = blkdev_get_by_path(path, flags, holder);
1071 ret = PTR_ERR(bdev);
1075 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super))
1076 goto error_bdev_put;
1078 devid = btrfs_stack_device_id(&disk_super->dev_item);
1079 transid = btrfs_super_generation(disk_super);
1080 total_devices = btrfs_super_num_devices(disk_super);
1082 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
1084 if (disk_super->label[0]) {
1085 printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
1087 printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
1090 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
1093 if (!ret && fs_devices_ret)
1094 (*fs_devices_ret)->total_devices = total_devices;
1096 btrfs_release_disk_super(page);
1099 blkdev_put(bdev, flags);
1101 mutex_unlock(&uuid_mutex);
1105 /* helper to account the used device space in the range */
1106 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1107 u64 end, u64 *length)
1109 struct btrfs_key key;
1110 struct btrfs_root *root = device->dev_root;
1111 struct btrfs_dev_extent *dev_extent;
1112 struct btrfs_path *path;
1116 struct extent_buffer *l;
1120 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1123 path = btrfs_alloc_path();
1126 path->reada = READA_FORWARD;
1128 key.objectid = device->devid;
1130 key.type = BTRFS_DEV_EXTENT_KEY;
1132 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1136 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1143 slot = path->slots[0];
1144 if (slot >= btrfs_header_nritems(l)) {
1145 ret = btrfs_next_leaf(root, path);
1153 btrfs_item_key_to_cpu(l, &key, slot);
1155 if (key.objectid < device->devid)
1158 if (key.objectid > device->devid)
1161 if (key.type != BTRFS_DEV_EXTENT_KEY)
1164 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1165 extent_end = key.offset + btrfs_dev_extent_length(l,
1167 if (key.offset <= start && extent_end > end) {
1168 *length = end - start + 1;
1170 } else if (key.offset <= start && extent_end > start)
1171 *length += extent_end - start;
1172 else if (key.offset > start && extent_end <= end)
1173 *length += extent_end - key.offset;
1174 else if (key.offset > start && key.offset <= end) {
1175 *length += end - key.offset + 1;
1177 } else if (key.offset > end)
1185 btrfs_free_path(path);
1189 static int contains_pending_extent(struct btrfs_transaction *transaction,
1190 struct btrfs_device *device,
1191 u64 *start, u64 len)
1193 struct btrfs_fs_info *fs_info = device->dev_root->fs_info;
1194 struct extent_map *em;
1195 struct list_head *search_list = &fs_info->pinned_chunks;
1197 u64 physical_start = *start;
1200 search_list = &transaction->pending_chunks;
1202 list_for_each_entry(em, search_list, list) {
1203 struct map_lookup *map;
1206 map = em->map_lookup;
1207 for (i = 0; i < map->num_stripes; i++) {
1210 if (map->stripes[i].dev != device)
1212 if (map->stripes[i].physical >= physical_start + len ||
1213 map->stripes[i].physical + em->orig_block_len <=
1217 * Make sure that while processing the pinned list we do
1218 * not override our *start with a lower value, because
1219 * we can have pinned chunks that fall within this
1220 * device hole and that have lower physical addresses
1221 * than the pending chunks we processed before. If we
1222 * do not take this special care we can end up getting
1223 * 2 pending chunks that start at the same physical
1224 * device offsets because the end offset of a pinned
1225 * chunk can be equal to the start offset of some
1228 end = map->stripes[i].physical + em->orig_block_len;
1235 if (search_list != &fs_info->pinned_chunks) {
1236 search_list = &fs_info->pinned_chunks;
1245 * find_free_dev_extent_start - find free space in the specified device
1246 * @device: the device which we search the free space in
1247 * @num_bytes: the size of the free space that we need
1248 * @search_start: the position from which to begin the search
1249 * @start: store the start of the free space.
1250 * @len: the size of the free space. that we find, or the size
1251 * of the max free space if we don't find suitable free space
1253 * this uses a pretty simple search, the expectation is that it is
1254 * called very infrequently and that a given device has a small number
1257 * @start is used to store the start of the free space if we find. But if we
1258 * don't find suitable free space, it will be used to store the start position
1259 * of the max free space.
1261 * @len is used to store the size of the free space that we find.
1262 * But if we don't find suitable free space, it is used to store the size of
1263 * the max free space.
1265 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1266 struct btrfs_device *device, u64 num_bytes,
1267 u64 search_start, u64 *start, u64 *len)
1269 struct btrfs_key key;
1270 struct btrfs_root *root = device->dev_root;
1271 struct btrfs_dev_extent *dev_extent;
1272 struct btrfs_path *path;
1277 u64 search_end = device->total_bytes;
1280 struct extent_buffer *l;
1281 u64 min_search_start;
1284 * We don't want to overwrite the superblock on the drive nor any area
1285 * used by the boot loader (grub for example), so we make sure to start
1286 * at an offset of at least 1MB.
1288 min_search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1289 search_start = max(search_start, min_search_start);
1291 path = btrfs_alloc_path();
1295 max_hole_start = search_start;
1299 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1304 path->reada = READA_FORWARD;
1305 path->search_commit_root = 1;
1306 path->skip_locking = 1;
1308 key.objectid = device->devid;
1309 key.offset = search_start;
1310 key.type = BTRFS_DEV_EXTENT_KEY;
1312 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1316 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1323 slot = path->slots[0];
1324 if (slot >= btrfs_header_nritems(l)) {
1325 ret = btrfs_next_leaf(root, path);
1333 btrfs_item_key_to_cpu(l, &key, slot);
1335 if (key.objectid < device->devid)
1338 if (key.objectid > device->devid)
1341 if (key.type != BTRFS_DEV_EXTENT_KEY)
1344 if (key.offset > search_start) {
1345 hole_size = key.offset - search_start;
1348 * Have to check before we set max_hole_start, otherwise
1349 * we could end up sending back this offset anyway.
1351 if (contains_pending_extent(transaction, device,
1354 if (key.offset >= search_start) {
1355 hole_size = key.offset - search_start;
1362 if (hole_size > max_hole_size) {
1363 max_hole_start = search_start;
1364 max_hole_size = hole_size;
1368 * If this free space is greater than which we need,
1369 * it must be the max free space that we have found
1370 * until now, so max_hole_start must point to the start
1371 * of this free space and the length of this free space
1372 * is stored in max_hole_size. Thus, we return
1373 * max_hole_start and max_hole_size and go back to the
1376 if (hole_size >= num_bytes) {
1382 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1383 extent_end = key.offset + btrfs_dev_extent_length(l,
1385 if (extent_end > search_start)
1386 search_start = extent_end;
1393 * At this point, search_start should be the end of
1394 * allocated dev extents, and when shrinking the device,
1395 * search_end may be smaller than search_start.
1397 if (search_end > search_start) {
1398 hole_size = search_end - search_start;
1400 if (contains_pending_extent(transaction, device, &search_start,
1402 btrfs_release_path(path);
1406 if (hole_size > max_hole_size) {
1407 max_hole_start = search_start;
1408 max_hole_size = hole_size;
1413 if (max_hole_size < num_bytes)
1419 btrfs_free_path(path);
1420 *start = max_hole_start;
1422 *len = max_hole_size;
1426 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1427 struct btrfs_device *device, u64 num_bytes,
1428 u64 *start, u64 *len)
1430 /* FIXME use last free of some kind */
1431 return find_free_dev_extent_start(trans->transaction, device,
1432 num_bytes, 0, start, len);
1435 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1436 struct btrfs_device *device,
1437 u64 start, u64 *dev_extent_len)
1440 struct btrfs_path *path;
1441 struct btrfs_root *root = device->dev_root;
1442 struct btrfs_key key;
1443 struct btrfs_key found_key;
1444 struct extent_buffer *leaf = NULL;
1445 struct btrfs_dev_extent *extent = NULL;
1447 path = btrfs_alloc_path();
1451 key.objectid = device->devid;
1453 key.type = BTRFS_DEV_EXTENT_KEY;
1455 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1457 ret = btrfs_previous_item(root, path, key.objectid,
1458 BTRFS_DEV_EXTENT_KEY);
1461 leaf = path->nodes[0];
1462 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1463 extent = btrfs_item_ptr(leaf, path->slots[0],
1464 struct btrfs_dev_extent);
1465 BUG_ON(found_key.offset > start || found_key.offset +
1466 btrfs_dev_extent_length(leaf, extent) < start);
1468 btrfs_release_path(path);
1470 } else if (ret == 0) {
1471 leaf = path->nodes[0];
1472 extent = btrfs_item_ptr(leaf, path->slots[0],
1473 struct btrfs_dev_extent);
1475 btrfs_std_error(root->fs_info, ret, "Slot search failed");
1479 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1481 ret = btrfs_del_item(trans, root, path);
1483 btrfs_std_error(root->fs_info, ret,
1484 "Failed to remove dev extent item");
1486 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1489 btrfs_free_path(path);
1493 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1494 struct btrfs_device *device,
1495 u64 chunk_tree, u64 chunk_objectid,
1496 u64 chunk_offset, u64 start, u64 num_bytes)
1499 struct btrfs_path *path;
1500 struct btrfs_root *root = device->dev_root;
1501 struct btrfs_dev_extent *extent;
1502 struct extent_buffer *leaf;
1503 struct btrfs_key key;
1505 WARN_ON(!device->in_fs_metadata);
1506 WARN_ON(device->is_tgtdev_for_dev_replace);
1507 path = btrfs_alloc_path();
1511 key.objectid = device->devid;
1513 key.type = BTRFS_DEV_EXTENT_KEY;
1514 ret = btrfs_insert_empty_item(trans, root, path, &key,
1519 leaf = path->nodes[0];
1520 extent = btrfs_item_ptr(leaf, path->slots[0],
1521 struct btrfs_dev_extent);
1522 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1523 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1524 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1526 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1527 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1529 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1530 btrfs_mark_buffer_dirty(leaf);
1532 btrfs_free_path(path);
1536 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1538 struct extent_map_tree *em_tree;
1539 struct extent_map *em;
1543 em_tree = &fs_info->mapping_tree.map_tree;
1544 read_lock(&em_tree->lock);
1545 n = rb_last(&em_tree->map);
1547 em = rb_entry(n, struct extent_map, rb_node);
1548 ret = em->start + em->len;
1550 read_unlock(&em_tree->lock);
1555 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1559 struct btrfs_key key;
1560 struct btrfs_key found_key;
1561 struct btrfs_path *path;
1563 path = btrfs_alloc_path();
1567 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1568 key.type = BTRFS_DEV_ITEM_KEY;
1569 key.offset = (u64)-1;
1571 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1575 BUG_ON(ret == 0); /* Corruption */
1577 ret = btrfs_previous_item(fs_info->chunk_root, path,
1578 BTRFS_DEV_ITEMS_OBJECTID,
1579 BTRFS_DEV_ITEM_KEY);
1583 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1585 *devid_ret = found_key.offset + 1;
1589 btrfs_free_path(path);
1594 * the device information is stored in the chunk root
1595 * the btrfs_device struct should be fully filled in
1597 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1598 struct btrfs_root *root,
1599 struct btrfs_device *device)
1602 struct btrfs_path *path;
1603 struct btrfs_dev_item *dev_item;
1604 struct extent_buffer *leaf;
1605 struct btrfs_key key;
1608 root = root->fs_info->chunk_root;
1610 path = btrfs_alloc_path();
1614 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1615 key.type = BTRFS_DEV_ITEM_KEY;
1616 key.offset = device->devid;
1618 ret = btrfs_insert_empty_item(trans, root, path, &key,
1623 leaf = path->nodes[0];
1624 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1626 btrfs_set_device_id(leaf, dev_item, device->devid);
1627 btrfs_set_device_generation(leaf, dev_item, 0);
1628 btrfs_set_device_type(leaf, dev_item, device->type);
1629 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1630 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1631 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1632 btrfs_set_device_total_bytes(leaf, dev_item,
1633 btrfs_device_get_disk_total_bytes(device));
1634 btrfs_set_device_bytes_used(leaf, dev_item,
1635 btrfs_device_get_bytes_used(device));
1636 btrfs_set_device_group(leaf, dev_item, 0);
1637 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1638 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1639 btrfs_set_device_start_offset(leaf, dev_item, 0);
1641 ptr = btrfs_device_uuid(dev_item);
1642 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1643 ptr = btrfs_device_fsid(dev_item);
1644 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1645 btrfs_mark_buffer_dirty(leaf);
1649 btrfs_free_path(path);
1654 * Function to update ctime/mtime for a given device path.
1655 * Mainly used for ctime/mtime based probe like libblkid.
1657 static void update_dev_time(char *path_name)
1661 filp = filp_open(path_name, O_RDWR, 0);
1664 file_update_time(filp);
1665 filp_close(filp, NULL);
1668 static int btrfs_rm_dev_item(struct btrfs_root *root,
1669 struct btrfs_device *device)
1672 struct btrfs_path *path;
1673 struct btrfs_key key;
1674 struct btrfs_trans_handle *trans;
1676 root = root->fs_info->chunk_root;
1678 path = btrfs_alloc_path();
1682 trans = btrfs_start_transaction(root, 0);
1683 if (IS_ERR(trans)) {
1684 btrfs_free_path(path);
1685 return PTR_ERR(trans);
1687 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1688 key.type = BTRFS_DEV_ITEM_KEY;
1689 key.offset = device->devid;
1691 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1700 ret = btrfs_del_item(trans, root, path);
1704 btrfs_free_path(path);
1705 btrfs_commit_transaction(trans, root);
1709 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info)
1715 num_devices = fs_info->fs_devices->num_devices;
1716 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
1717 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1718 WARN_ON(num_devices < 1);
1721 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
1724 seq = read_seqbegin(&fs_info->profiles_lock);
1726 all_avail = fs_info->avail_data_alloc_bits |
1727 fs_info->avail_system_alloc_bits |
1728 fs_info->avail_metadata_alloc_bits;
1729 } while (read_seqretry(&fs_info->profiles_lock, seq));
1731 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1732 return BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1735 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1736 return BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1739 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1740 fs_info->fs_devices->rw_devices <= 2) {
1741 return BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1744 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1745 fs_info->fs_devices->rw_devices <= 3) {
1746 return BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1752 int btrfs_rm_device(struct btrfs_root *root, char *device_path, u64 devid)
1754 struct btrfs_device *device;
1755 struct btrfs_device *next_device;
1756 struct btrfs_fs_devices *cur_devices;
1759 bool clear_super = false;
1760 char *dev_name = NULL;
1762 mutex_lock(&uuid_mutex);
1764 ret = btrfs_check_raid_min_devices(root->fs_info);
1768 ret = btrfs_find_device_by_user_input(root, devid, device_path,
1773 if (device->is_tgtdev_for_dev_replace) {
1774 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1778 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1779 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1783 if (device->writeable) {
1785 list_del_init(&device->dev_alloc_list);
1786 device->fs_devices->rw_devices--;
1787 unlock_chunks(root);
1788 dev_name = kstrdup(device->name->str, GFP_KERNEL);
1796 mutex_unlock(&uuid_mutex);
1797 ret = btrfs_shrink_device(device, 0);
1798 mutex_lock(&uuid_mutex);
1803 * TODO: the superblock still includes this device in its num_devices
1804 * counter although write_all_supers() is not locked out. This
1805 * could give a filesystem state which requires a degraded mount.
1807 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1811 device->in_fs_metadata = 0;
1812 btrfs_scrub_cancel_dev(root->fs_info, device);
1815 * the device list mutex makes sure that we don't change
1816 * the device list while someone else is writing out all
1817 * the device supers. Whoever is writing all supers, should
1818 * lock the device list mutex before getting the number of
1819 * devices in the super block (super_copy). Conversely,
1820 * whoever updates the number of devices in the super block
1821 * (super_copy) should hold the device list mutex.
1824 cur_devices = device->fs_devices;
1825 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1826 list_del_rcu(&device->dev_list);
1828 device->fs_devices->num_devices--;
1829 device->fs_devices->total_devices--;
1831 if (device->missing)
1832 device->fs_devices->missing_devices--;
1834 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1835 struct btrfs_device, dev_list);
1836 if (device->bdev == root->fs_info->sb->s_bdev)
1837 root->fs_info->sb->s_bdev = next_device->bdev;
1838 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1839 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1842 device->fs_devices->open_devices--;
1843 /* remove sysfs entry */
1844 btrfs_sysfs_rm_device_link(root->fs_info->fs_devices, device);
1847 call_rcu(&device->rcu, free_device);
1849 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1850 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1851 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1853 if (cur_devices->open_devices == 0) {
1854 struct btrfs_fs_devices *fs_devices;
1855 fs_devices = root->fs_info->fs_devices;
1856 while (fs_devices) {
1857 if (fs_devices->seed == cur_devices) {
1858 fs_devices->seed = cur_devices->seed;
1861 fs_devices = fs_devices->seed;
1863 cur_devices->seed = NULL;
1864 __btrfs_close_devices(cur_devices);
1865 free_fs_devices(cur_devices);
1868 root->fs_info->num_tolerated_disk_barrier_failures =
1869 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1872 * at this point, the device is zero sized. We want to
1873 * remove it from the devices list and zero out the old super
1876 struct block_device *bdev;
1878 bdev = blkdev_get_by_path(dev_name, FMODE_READ | FMODE_EXCL,
1879 root->fs_info->bdev_holder);
1880 if (!IS_ERR(bdev)) {
1881 btrfs_scratch_superblocks(bdev, dev_name);
1882 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1889 mutex_unlock(&uuid_mutex);
1893 if (device->writeable) {
1895 list_add(&device->dev_alloc_list,
1896 &root->fs_info->fs_devices->alloc_list);
1897 device->fs_devices->rw_devices++;
1898 unlock_chunks(root);
1903 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
1904 struct btrfs_device *srcdev)
1906 struct btrfs_fs_devices *fs_devices;
1908 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1911 * in case of fs with no seed, srcdev->fs_devices will point
1912 * to fs_devices of fs_info. However when the dev being replaced is
1913 * a seed dev it will point to the seed's local fs_devices. In short
1914 * srcdev will have its correct fs_devices in both the cases.
1916 fs_devices = srcdev->fs_devices;
1918 list_del_rcu(&srcdev->dev_list);
1919 list_del_rcu(&srcdev->dev_alloc_list);
1920 fs_devices->num_devices--;
1921 if (srcdev->missing)
1922 fs_devices->missing_devices--;
1924 if (srcdev->writeable) {
1925 fs_devices->rw_devices--;
1926 /* zero out the old super if it is writable */
1927 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
1931 fs_devices->open_devices--;
1934 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
1935 struct btrfs_device *srcdev)
1937 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
1939 call_rcu(&srcdev->rcu, free_device);
1942 * unless fs_devices is seed fs, num_devices shouldn't go
1945 BUG_ON(!fs_devices->num_devices && !fs_devices->seeding);
1947 /* if this is no devs we rather delete the fs_devices */
1948 if (!fs_devices->num_devices) {
1949 struct btrfs_fs_devices *tmp_fs_devices;
1951 tmp_fs_devices = fs_info->fs_devices;
1952 while (tmp_fs_devices) {
1953 if (tmp_fs_devices->seed == fs_devices) {
1954 tmp_fs_devices->seed = fs_devices->seed;
1957 tmp_fs_devices = tmp_fs_devices->seed;
1959 fs_devices->seed = NULL;
1960 __btrfs_close_devices(fs_devices);
1961 free_fs_devices(fs_devices);
1965 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1966 struct btrfs_device *tgtdev)
1968 struct btrfs_device *next_device;
1970 mutex_lock(&uuid_mutex);
1972 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1974 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
1977 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
1978 fs_info->fs_devices->open_devices--;
1980 fs_info->fs_devices->num_devices--;
1982 next_device = list_entry(fs_info->fs_devices->devices.next,
1983 struct btrfs_device, dev_list);
1984 if (tgtdev->bdev == fs_info->sb->s_bdev)
1985 fs_info->sb->s_bdev = next_device->bdev;
1986 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1987 fs_info->fs_devices->latest_bdev = next_device->bdev;
1988 list_del_rcu(&tgtdev->dev_list);
1990 call_rcu(&tgtdev->rcu, free_device);
1992 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1993 mutex_unlock(&uuid_mutex);
1996 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1997 struct btrfs_device **device)
2000 struct btrfs_super_block *disk_super;
2003 struct block_device *bdev;
2004 struct buffer_head *bh;
2007 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2008 root->fs_info->bdev_holder, 0, &bdev, &bh);
2011 disk_super = (struct btrfs_super_block *)bh->b_data;
2012 devid = btrfs_stack_device_id(&disk_super->dev_item);
2013 dev_uuid = disk_super->dev_item.uuid;
2014 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2019 blkdev_put(bdev, FMODE_READ);
2023 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
2025 struct btrfs_device **device)
2028 if (strcmp(device_path, "missing") == 0) {
2029 struct list_head *devices;
2030 struct btrfs_device *tmp;
2032 devices = &root->fs_info->fs_devices->devices;
2034 * It is safe to read the devices since the volume_mutex
2035 * is held by the caller.
2037 list_for_each_entry(tmp, devices, dev_list) {
2038 if (tmp->in_fs_metadata && !tmp->bdev) {
2045 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2049 return btrfs_find_device_by_path(root, device_path, device);
2053 int btrfs_find_device_by_user_input(struct btrfs_root *root, u64 srcdevid,
2055 struct btrfs_device **device)
2061 *device = btrfs_find_device(root->fs_info, srcdevid, NULL,
2066 if (!srcdev_name || !srcdev_name[0])
2069 ret = btrfs_find_device_missing_or_by_path(root, srcdev_name,
2076 * does all the dirty work required for changing file system's UUID.
2078 static int btrfs_prepare_sprout(struct btrfs_root *root)
2080 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2081 struct btrfs_fs_devices *old_devices;
2082 struct btrfs_fs_devices *seed_devices;
2083 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
2084 struct btrfs_device *device;
2087 BUG_ON(!mutex_is_locked(&uuid_mutex));
2088 if (!fs_devices->seeding)
2091 seed_devices = __alloc_fs_devices();
2092 if (IS_ERR(seed_devices))
2093 return PTR_ERR(seed_devices);
2095 old_devices = clone_fs_devices(fs_devices);
2096 if (IS_ERR(old_devices)) {
2097 kfree(seed_devices);
2098 return PTR_ERR(old_devices);
2101 list_add(&old_devices->list, &fs_uuids);
2103 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2104 seed_devices->opened = 1;
2105 INIT_LIST_HEAD(&seed_devices->devices);
2106 INIT_LIST_HEAD(&seed_devices->alloc_list);
2107 mutex_init(&seed_devices->device_list_mutex);
2109 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2110 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2112 list_for_each_entry(device, &seed_devices->devices, dev_list)
2113 device->fs_devices = seed_devices;
2116 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2117 unlock_chunks(root);
2119 fs_devices->seeding = 0;
2120 fs_devices->num_devices = 0;
2121 fs_devices->open_devices = 0;
2122 fs_devices->missing_devices = 0;
2123 fs_devices->rotating = 0;
2124 fs_devices->seed = seed_devices;
2126 generate_random_uuid(fs_devices->fsid);
2127 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2128 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2129 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2131 super_flags = btrfs_super_flags(disk_super) &
2132 ~BTRFS_SUPER_FLAG_SEEDING;
2133 btrfs_set_super_flags(disk_super, super_flags);
2139 * strore the expected generation for seed devices in device items.
2141 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2142 struct btrfs_root *root)
2144 struct btrfs_path *path;
2145 struct extent_buffer *leaf;
2146 struct btrfs_dev_item *dev_item;
2147 struct btrfs_device *device;
2148 struct btrfs_key key;
2149 u8 fs_uuid[BTRFS_UUID_SIZE];
2150 u8 dev_uuid[BTRFS_UUID_SIZE];
2154 path = btrfs_alloc_path();
2158 root = root->fs_info->chunk_root;
2159 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2161 key.type = BTRFS_DEV_ITEM_KEY;
2164 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2168 leaf = path->nodes[0];
2170 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2171 ret = btrfs_next_leaf(root, path);
2176 leaf = path->nodes[0];
2177 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2178 btrfs_release_path(path);
2182 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2183 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2184 key.type != BTRFS_DEV_ITEM_KEY)
2187 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2188 struct btrfs_dev_item);
2189 devid = btrfs_device_id(leaf, dev_item);
2190 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2192 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2194 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2196 BUG_ON(!device); /* Logic error */
2198 if (device->fs_devices->seeding) {
2199 btrfs_set_device_generation(leaf, dev_item,
2200 device->generation);
2201 btrfs_mark_buffer_dirty(leaf);
2209 btrfs_free_path(path);
2213 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
2215 struct request_queue *q;
2216 struct btrfs_trans_handle *trans;
2217 struct btrfs_device *device;
2218 struct block_device *bdev;
2219 struct list_head *devices;
2220 struct super_block *sb = root->fs_info->sb;
2221 struct rcu_string *name;
2223 int seeding_dev = 0;
2226 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
2229 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2230 root->fs_info->bdev_holder);
2232 return PTR_ERR(bdev);
2234 if (root->fs_info->fs_devices->seeding) {
2236 down_write(&sb->s_umount);
2237 mutex_lock(&uuid_mutex);
2240 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2242 devices = &root->fs_info->fs_devices->devices;
2244 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2245 list_for_each_entry(device, devices, dev_list) {
2246 if (device->bdev == bdev) {
2249 &root->fs_info->fs_devices->device_list_mutex);
2253 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2255 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2256 if (IS_ERR(device)) {
2257 /* we can safely leave the fs_devices entry around */
2258 ret = PTR_ERR(device);
2262 name = rcu_string_strdup(device_path, GFP_KERNEL);
2268 rcu_assign_pointer(device->name, name);
2270 trans = btrfs_start_transaction(root, 0);
2271 if (IS_ERR(trans)) {
2272 rcu_string_free(device->name);
2274 ret = PTR_ERR(trans);
2278 q = bdev_get_queue(bdev);
2279 if (blk_queue_discard(q))
2280 device->can_discard = 1;
2281 device->writeable = 1;
2282 device->generation = trans->transid;
2283 device->io_width = root->sectorsize;
2284 device->io_align = root->sectorsize;
2285 device->sector_size = root->sectorsize;
2286 device->total_bytes = i_size_read(bdev->bd_inode);
2287 device->disk_total_bytes = device->total_bytes;
2288 device->commit_total_bytes = device->total_bytes;
2289 device->dev_root = root->fs_info->dev_root;
2290 device->bdev = bdev;
2291 device->in_fs_metadata = 1;
2292 device->is_tgtdev_for_dev_replace = 0;
2293 device->mode = FMODE_EXCL;
2294 device->dev_stats_valid = 1;
2295 set_blocksize(device->bdev, 4096);
2298 sb->s_flags &= ~MS_RDONLY;
2299 ret = btrfs_prepare_sprout(root);
2300 BUG_ON(ret); /* -ENOMEM */
2303 device->fs_devices = root->fs_info->fs_devices;
2305 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2307 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2308 list_add(&device->dev_alloc_list,
2309 &root->fs_info->fs_devices->alloc_list);
2310 root->fs_info->fs_devices->num_devices++;
2311 root->fs_info->fs_devices->open_devices++;
2312 root->fs_info->fs_devices->rw_devices++;
2313 root->fs_info->fs_devices->total_devices++;
2314 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2316 spin_lock(&root->fs_info->free_chunk_lock);
2317 root->fs_info->free_chunk_space += device->total_bytes;
2318 spin_unlock(&root->fs_info->free_chunk_lock);
2320 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2321 root->fs_info->fs_devices->rotating = 1;
2323 tmp = btrfs_super_total_bytes(root->fs_info->super_copy);
2324 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2325 tmp + device->total_bytes);
2327 tmp = btrfs_super_num_devices(root->fs_info->super_copy);
2328 btrfs_set_super_num_devices(root->fs_info->super_copy,
2331 /* add sysfs device entry */
2332 btrfs_sysfs_add_device_link(root->fs_info->fs_devices, device);
2335 * we've got more storage, clear any full flags on the space
2338 btrfs_clear_space_info_full(root->fs_info);
2340 unlock_chunks(root);
2341 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2345 ret = init_first_rw_device(trans, root, device);
2346 unlock_chunks(root);
2348 btrfs_abort_transaction(trans, root, ret);
2353 ret = btrfs_add_device(trans, root, device);
2355 btrfs_abort_transaction(trans, root, ret);
2360 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2362 ret = btrfs_finish_sprout(trans, root);
2364 btrfs_abort_transaction(trans, root, ret);
2368 /* Sprouting would change fsid of the mounted root,
2369 * so rename the fsid on the sysfs
2371 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2372 root->fs_info->fsid);
2373 if (kobject_rename(&root->fs_info->fs_devices->fsid_kobj,
2375 btrfs_warn(root->fs_info,
2376 "sysfs: failed to create fsid for sprout");
2379 root->fs_info->num_tolerated_disk_barrier_failures =
2380 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2381 ret = btrfs_commit_transaction(trans, root);
2384 mutex_unlock(&uuid_mutex);
2385 up_write(&sb->s_umount);
2387 if (ret) /* transaction commit */
2390 ret = btrfs_relocate_sys_chunks(root);
2392 btrfs_std_error(root->fs_info, ret,
2393 "Failed to relocate sys chunks after "
2394 "device initialization. This can be fixed "
2395 "using the \"btrfs balance\" command.");
2396 trans = btrfs_attach_transaction(root);
2397 if (IS_ERR(trans)) {
2398 if (PTR_ERR(trans) == -ENOENT)
2400 return PTR_ERR(trans);
2402 ret = btrfs_commit_transaction(trans, root);
2405 /* Update ctime/mtime for libblkid */
2406 update_dev_time(device_path);
2410 btrfs_end_transaction(trans, root);
2411 rcu_string_free(device->name);
2412 btrfs_sysfs_rm_device_link(root->fs_info->fs_devices, device);
2415 blkdev_put(bdev, FMODE_EXCL);
2417 mutex_unlock(&uuid_mutex);
2418 up_write(&sb->s_umount);
2423 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2424 struct btrfs_device *srcdev,
2425 struct btrfs_device **device_out)
2427 struct request_queue *q;
2428 struct btrfs_device *device;
2429 struct block_device *bdev;
2430 struct btrfs_fs_info *fs_info = root->fs_info;
2431 struct list_head *devices;
2432 struct rcu_string *name;
2433 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2437 if (fs_info->fs_devices->seeding) {
2438 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2442 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2443 fs_info->bdev_holder);
2445 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2446 return PTR_ERR(bdev);
2449 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2451 devices = &fs_info->fs_devices->devices;
2452 list_for_each_entry(device, devices, dev_list) {
2453 if (device->bdev == bdev) {
2454 btrfs_err(fs_info, "target device is in the filesystem!");
2461 if (i_size_read(bdev->bd_inode) <
2462 btrfs_device_get_total_bytes(srcdev)) {
2463 btrfs_err(fs_info, "target device is smaller than source device!");
2469 device = btrfs_alloc_device(NULL, &devid, NULL);
2470 if (IS_ERR(device)) {
2471 ret = PTR_ERR(device);
2475 name = rcu_string_strdup(device_path, GFP_NOFS);
2481 rcu_assign_pointer(device->name, name);
2483 q = bdev_get_queue(bdev);
2484 if (blk_queue_discard(q))
2485 device->can_discard = 1;
2486 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2487 device->writeable = 1;
2488 device->generation = 0;
2489 device->io_width = root->sectorsize;
2490 device->io_align = root->sectorsize;
2491 device->sector_size = root->sectorsize;
2492 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2493 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2494 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2495 ASSERT(list_empty(&srcdev->resized_list));
2496 device->commit_total_bytes = srcdev->commit_total_bytes;
2497 device->commit_bytes_used = device->bytes_used;
2498 device->dev_root = fs_info->dev_root;
2499 device->bdev = bdev;
2500 device->in_fs_metadata = 1;
2501 device->is_tgtdev_for_dev_replace = 1;
2502 device->mode = FMODE_EXCL;
2503 device->dev_stats_valid = 1;
2504 set_blocksize(device->bdev, 4096);
2505 device->fs_devices = fs_info->fs_devices;
2506 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2507 fs_info->fs_devices->num_devices++;
2508 fs_info->fs_devices->open_devices++;
2509 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2511 *device_out = device;
2515 blkdev_put(bdev, FMODE_EXCL);
2519 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2520 struct btrfs_device *tgtdev)
2522 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2523 tgtdev->io_width = fs_info->dev_root->sectorsize;
2524 tgtdev->io_align = fs_info->dev_root->sectorsize;
2525 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2526 tgtdev->dev_root = fs_info->dev_root;
2527 tgtdev->in_fs_metadata = 1;
2530 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2531 struct btrfs_device *device)
2534 struct btrfs_path *path;
2535 struct btrfs_root *root;
2536 struct btrfs_dev_item *dev_item;
2537 struct extent_buffer *leaf;
2538 struct btrfs_key key;
2540 root = device->dev_root->fs_info->chunk_root;
2542 path = btrfs_alloc_path();
2546 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2547 key.type = BTRFS_DEV_ITEM_KEY;
2548 key.offset = device->devid;
2550 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2559 leaf = path->nodes[0];
2560 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2562 btrfs_set_device_id(leaf, dev_item, device->devid);
2563 btrfs_set_device_type(leaf, dev_item, device->type);
2564 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2565 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2566 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2567 btrfs_set_device_total_bytes(leaf, dev_item,
2568 btrfs_device_get_disk_total_bytes(device));
2569 btrfs_set_device_bytes_used(leaf, dev_item,
2570 btrfs_device_get_bytes_used(device));
2571 btrfs_mark_buffer_dirty(leaf);
2574 btrfs_free_path(path);
2578 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2579 struct btrfs_device *device, u64 new_size)
2581 struct btrfs_super_block *super_copy =
2582 device->dev_root->fs_info->super_copy;
2583 struct btrfs_fs_devices *fs_devices;
2587 if (!device->writeable)
2590 lock_chunks(device->dev_root);
2591 old_total = btrfs_super_total_bytes(super_copy);
2592 diff = new_size - device->total_bytes;
2594 if (new_size <= device->total_bytes ||
2595 device->is_tgtdev_for_dev_replace) {
2596 unlock_chunks(device->dev_root);
2600 fs_devices = device->dev_root->fs_info->fs_devices;
2602 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2603 device->fs_devices->total_rw_bytes += diff;
2605 btrfs_device_set_total_bytes(device, new_size);
2606 btrfs_device_set_disk_total_bytes(device, new_size);
2607 btrfs_clear_space_info_full(device->dev_root->fs_info);
2608 if (list_empty(&device->resized_list))
2609 list_add_tail(&device->resized_list,
2610 &fs_devices->resized_devices);
2611 unlock_chunks(device->dev_root);
2613 return btrfs_update_device(trans, device);
2616 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2617 struct btrfs_root *root, u64 chunk_objectid,
2621 struct btrfs_path *path;
2622 struct btrfs_key key;
2624 root = root->fs_info->chunk_root;
2625 path = btrfs_alloc_path();
2629 key.objectid = chunk_objectid;
2630 key.offset = chunk_offset;
2631 key.type = BTRFS_CHUNK_ITEM_KEY;
2633 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2636 else if (ret > 0) { /* Logic error or corruption */
2637 btrfs_std_error(root->fs_info, -ENOENT,
2638 "Failed lookup while freeing chunk.");
2643 ret = btrfs_del_item(trans, root, path);
2645 btrfs_std_error(root->fs_info, ret,
2646 "Failed to delete chunk item.");
2648 btrfs_free_path(path);
2652 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2655 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2656 struct btrfs_disk_key *disk_key;
2657 struct btrfs_chunk *chunk;
2664 struct btrfs_key key;
2667 array_size = btrfs_super_sys_array_size(super_copy);
2669 ptr = super_copy->sys_chunk_array;
2672 while (cur < array_size) {
2673 disk_key = (struct btrfs_disk_key *)ptr;
2674 btrfs_disk_key_to_cpu(&key, disk_key);
2676 len = sizeof(*disk_key);
2678 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2679 chunk = (struct btrfs_chunk *)(ptr + len);
2680 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2681 len += btrfs_chunk_item_size(num_stripes);
2686 if (key.objectid == chunk_objectid &&
2687 key.offset == chunk_offset) {
2688 memmove(ptr, ptr + len, array_size - (cur + len));
2690 btrfs_set_super_sys_array_size(super_copy, array_size);
2696 unlock_chunks(root);
2700 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2701 struct btrfs_root *root, u64 chunk_offset)
2703 struct extent_map_tree *em_tree;
2704 struct extent_map *em;
2705 struct btrfs_root *extent_root = root->fs_info->extent_root;
2706 struct map_lookup *map;
2707 u64 dev_extent_len = 0;
2708 u64 chunk_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2712 root = root->fs_info->chunk_root;
2713 em_tree = &root->fs_info->mapping_tree.map_tree;
2715 read_lock(&em_tree->lock);
2716 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2717 read_unlock(&em_tree->lock);
2719 if (!em || em->start > chunk_offset ||
2720 em->start + em->len < chunk_offset) {
2722 * This is a logic error, but we don't want to just rely on the
2723 * user having built with ASSERT enabled, so if ASSERT doesn't
2724 * do anything we still error out.
2728 free_extent_map(em);
2731 map = em->map_lookup;
2732 lock_chunks(root->fs_info->chunk_root);
2733 check_system_chunk(trans, extent_root, map->type);
2734 unlock_chunks(root->fs_info->chunk_root);
2736 for (i = 0; i < map->num_stripes; i++) {
2737 struct btrfs_device *device = map->stripes[i].dev;
2738 ret = btrfs_free_dev_extent(trans, device,
2739 map->stripes[i].physical,
2742 btrfs_abort_transaction(trans, root, ret);
2746 if (device->bytes_used > 0) {
2748 btrfs_device_set_bytes_used(device,
2749 device->bytes_used - dev_extent_len);
2750 spin_lock(&root->fs_info->free_chunk_lock);
2751 root->fs_info->free_chunk_space += dev_extent_len;
2752 spin_unlock(&root->fs_info->free_chunk_lock);
2753 btrfs_clear_space_info_full(root->fs_info);
2754 unlock_chunks(root);
2757 if (map->stripes[i].dev) {
2758 ret = btrfs_update_device(trans, map->stripes[i].dev);
2760 btrfs_abort_transaction(trans, root, ret);
2765 ret = btrfs_free_chunk(trans, root, chunk_objectid, chunk_offset);
2767 btrfs_abort_transaction(trans, root, ret);
2771 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2773 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2774 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2776 btrfs_abort_transaction(trans, root, ret);
2781 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset, em);
2783 btrfs_abort_transaction(trans, extent_root, ret);
2789 free_extent_map(em);
2793 static int btrfs_relocate_chunk(struct btrfs_root *root, u64 chunk_offset)
2795 struct btrfs_root *extent_root;
2796 struct btrfs_trans_handle *trans;
2799 root = root->fs_info->chunk_root;
2800 extent_root = root->fs_info->extent_root;
2803 * Prevent races with automatic removal of unused block groups.
2804 * After we relocate and before we remove the chunk with offset
2805 * chunk_offset, automatic removal of the block group can kick in,
2806 * resulting in a failure when calling btrfs_remove_chunk() below.
2808 * Make sure to acquire this mutex before doing a tree search (dev
2809 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2810 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2811 * we release the path used to search the chunk/dev tree and before
2812 * the current task acquires this mutex and calls us.
2814 ASSERT(mutex_is_locked(&root->fs_info->delete_unused_bgs_mutex));
2816 ret = btrfs_can_relocate(extent_root, chunk_offset);
2820 /* step one, relocate all the extents inside this chunk */
2821 btrfs_scrub_pause(root);
2822 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2823 btrfs_scrub_continue(root);
2827 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2829 if (IS_ERR(trans)) {
2830 ret = PTR_ERR(trans);
2831 btrfs_std_error(root->fs_info, ret, NULL);
2836 * step two, delete the device extents and the
2837 * chunk tree entries
2839 ret = btrfs_remove_chunk(trans, root, chunk_offset);
2840 btrfs_end_transaction(trans, root);
2844 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2846 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2847 struct btrfs_path *path;
2848 struct extent_buffer *leaf;
2849 struct btrfs_chunk *chunk;
2850 struct btrfs_key key;
2851 struct btrfs_key found_key;
2853 bool retried = false;
2857 path = btrfs_alloc_path();
2862 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2863 key.offset = (u64)-1;
2864 key.type = BTRFS_CHUNK_ITEM_KEY;
2867 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
2868 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2870 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2873 BUG_ON(ret == 0); /* Corruption */
2875 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2878 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2884 leaf = path->nodes[0];
2885 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2887 chunk = btrfs_item_ptr(leaf, path->slots[0],
2888 struct btrfs_chunk);
2889 chunk_type = btrfs_chunk_type(leaf, chunk);
2890 btrfs_release_path(path);
2892 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2893 ret = btrfs_relocate_chunk(chunk_root,
2900 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2902 if (found_key.offset == 0)
2904 key.offset = found_key.offset - 1;
2907 if (failed && !retried) {
2911 } else if (WARN_ON(failed && retried)) {
2915 btrfs_free_path(path);
2919 static int insert_balance_item(struct btrfs_root *root,
2920 struct btrfs_balance_control *bctl)
2922 struct btrfs_trans_handle *trans;
2923 struct btrfs_balance_item *item;
2924 struct btrfs_disk_balance_args disk_bargs;
2925 struct btrfs_path *path;
2926 struct extent_buffer *leaf;
2927 struct btrfs_key key;
2930 path = btrfs_alloc_path();
2934 trans = btrfs_start_transaction(root, 0);
2935 if (IS_ERR(trans)) {
2936 btrfs_free_path(path);
2937 return PTR_ERR(trans);
2940 key.objectid = BTRFS_BALANCE_OBJECTID;
2941 key.type = BTRFS_TEMPORARY_ITEM_KEY;
2944 ret = btrfs_insert_empty_item(trans, root, path, &key,
2949 leaf = path->nodes[0];
2950 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2952 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2954 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2955 btrfs_set_balance_data(leaf, item, &disk_bargs);
2956 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2957 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2958 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2959 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2961 btrfs_set_balance_flags(leaf, item, bctl->flags);
2963 btrfs_mark_buffer_dirty(leaf);
2965 btrfs_free_path(path);
2966 err = btrfs_commit_transaction(trans, root);
2972 static int del_balance_item(struct btrfs_root *root)
2974 struct btrfs_trans_handle *trans;
2975 struct btrfs_path *path;
2976 struct btrfs_key key;
2979 path = btrfs_alloc_path();
2983 trans = btrfs_start_transaction(root, 0);
2984 if (IS_ERR(trans)) {
2985 btrfs_free_path(path);
2986 return PTR_ERR(trans);
2989 key.objectid = BTRFS_BALANCE_OBJECTID;
2990 key.type = BTRFS_TEMPORARY_ITEM_KEY;
2993 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3001 ret = btrfs_del_item(trans, root, path);
3003 btrfs_free_path(path);
3004 err = btrfs_commit_transaction(trans, root);
3011 * This is a heuristic used to reduce the number of chunks balanced on
3012 * resume after balance was interrupted.
3014 static void update_balance_args(struct btrfs_balance_control *bctl)
3017 * Turn on soft mode for chunk types that were being converted.
3019 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3020 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3021 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3022 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3023 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3024 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3027 * Turn on usage filter if is not already used. The idea is
3028 * that chunks that we have already balanced should be
3029 * reasonably full. Don't do it for chunks that are being
3030 * converted - that will keep us from relocating unconverted
3031 * (albeit full) chunks.
3033 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3034 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3035 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3036 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3037 bctl->data.usage = 90;
3039 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3040 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3041 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3042 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3043 bctl->sys.usage = 90;
3045 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3046 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3047 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3048 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3049 bctl->meta.usage = 90;
3054 * Should be called with both balance and volume mutexes held to
3055 * serialize other volume operations (add_dev/rm_dev/resize) with
3056 * restriper. Same goes for unset_balance_control.
3058 static void set_balance_control(struct btrfs_balance_control *bctl)
3060 struct btrfs_fs_info *fs_info = bctl->fs_info;
3062 BUG_ON(fs_info->balance_ctl);
3064 spin_lock(&fs_info->balance_lock);
3065 fs_info->balance_ctl = bctl;
3066 spin_unlock(&fs_info->balance_lock);
3069 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3071 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3073 BUG_ON(!fs_info->balance_ctl);
3075 spin_lock(&fs_info->balance_lock);
3076 fs_info->balance_ctl = NULL;
3077 spin_unlock(&fs_info->balance_lock);
3083 * Balance filters. Return 1 if chunk should be filtered out
3084 * (should not be balanced).
3086 static int chunk_profiles_filter(u64 chunk_type,
3087 struct btrfs_balance_args *bargs)
3089 chunk_type = chunk_to_extended(chunk_type) &
3090 BTRFS_EXTENDED_PROFILE_MASK;
3092 if (bargs->profiles & chunk_type)
3098 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3099 struct btrfs_balance_args *bargs)
3101 struct btrfs_block_group_cache *cache;
3103 u64 user_thresh_min;
3104 u64 user_thresh_max;
3107 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3108 chunk_used = btrfs_block_group_used(&cache->item);
3110 if (bargs->usage_min == 0)
3111 user_thresh_min = 0;
3113 user_thresh_min = div_factor_fine(cache->key.offset,
3116 if (bargs->usage_max == 0)
3117 user_thresh_max = 1;
3118 else if (bargs->usage_max > 100)
3119 user_thresh_max = cache->key.offset;
3121 user_thresh_max = div_factor_fine(cache->key.offset,
3124 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3127 btrfs_put_block_group(cache);
3131 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3132 u64 chunk_offset, struct btrfs_balance_args *bargs)
3134 struct btrfs_block_group_cache *cache;
3135 u64 chunk_used, user_thresh;
3138 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3139 chunk_used = btrfs_block_group_used(&cache->item);
3141 if (bargs->usage_min == 0)
3143 else if (bargs->usage > 100)
3144 user_thresh = cache->key.offset;
3146 user_thresh = div_factor_fine(cache->key.offset,
3149 if (chunk_used < user_thresh)
3152 btrfs_put_block_group(cache);
3156 static int chunk_devid_filter(struct extent_buffer *leaf,
3157 struct btrfs_chunk *chunk,
3158 struct btrfs_balance_args *bargs)
3160 struct btrfs_stripe *stripe;
3161 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3164 for (i = 0; i < num_stripes; i++) {
3165 stripe = btrfs_stripe_nr(chunk, i);
3166 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3173 /* [pstart, pend) */
3174 static int chunk_drange_filter(struct extent_buffer *leaf,
3175 struct btrfs_chunk *chunk,
3177 struct btrfs_balance_args *bargs)
3179 struct btrfs_stripe *stripe;
3180 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3186 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3189 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3190 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3191 factor = num_stripes / 2;
3192 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3193 factor = num_stripes - 1;
3194 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3195 factor = num_stripes - 2;
3197 factor = num_stripes;
3200 for (i = 0; i < num_stripes; i++) {
3201 stripe = btrfs_stripe_nr(chunk, i);
3202 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3205 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3206 stripe_length = btrfs_chunk_length(leaf, chunk);
3207 stripe_length = div_u64(stripe_length, factor);
3209 if (stripe_offset < bargs->pend &&
3210 stripe_offset + stripe_length > bargs->pstart)
3217 /* [vstart, vend) */
3218 static int chunk_vrange_filter(struct extent_buffer *leaf,
3219 struct btrfs_chunk *chunk,
3221 struct btrfs_balance_args *bargs)
3223 if (chunk_offset < bargs->vend &&
3224 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3225 /* at least part of the chunk is inside this vrange */
3231 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3232 struct btrfs_chunk *chunk,
3233 struct btrfs_balance_args *bargs)
3235 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3237 if (bargs->stripes_min <= num_stripes
3238 && num_stripes <= bargs->stripes_max)
3244 static int chunk_soft_convert_filter(u64 chunk_type,
3245 struct btrfs_balance_args *bargs)
3247 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3250 chunk_type = chunk_to_extended(chunk_type) &
3251 BTRFS_EXTENDED_PROFILE_MASK;
3253 if (bargs->target == chunk_type)
3259 static int should_balance_chunk(struct btrfs_root *root,
3260 struct extent_buffer *leaf,
3261 struct btrfs_chunk *chunk, u64 chunk_offset)
3263 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
3264 struct btrfs_balance_args *bargs = NULL;
3265 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3268 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3269 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3273 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3274 bargs = &bctl->data;
3275 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3277 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3278 bargs = &bctl->meta;
3280 /* profiles filter */
3281 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3282 chunk_profiles_filter(chunk_type, bargs)) {
3287 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3288 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
3290 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3291 chunk_usage_range_filter(bctl->fs_info, chunk_offset, bargs)) {
3296 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3297 chunk_devid_filter(leaf, chunk, bargs)) {
3301 /* drange filter, makes sense only with devid filter */
3302 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3303 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
3308 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3309 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3313 /* stripes filter */
3314 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3315 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3319 /* soft profile changing mode */
3320 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3321 chunk_soft_convert_filter(chunk_type, bargs)) {
3326 * limited by count, must be the last filter
3328 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3329 if (bargs->limit == 0)
3333 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3335 * Same logic as the 'limit' filter; the minimum cannot be
3336 * determined here because we do not have the global informatoin
3337 * about the count of all chunks that satisfy the filters.
3339 if (bargs->limit_max == 0)
3348 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3350 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3351 struct btrfs_root *chunk_root = fs_info->chunk_root;
3352 struct btrfs_root *dev_root = fs_info->dev_root;
3353 struct list_head *devices;
3354 struct btrfs_device *device;
3358 struct btrfs_chunk *chunk;
3359 struct btrfs_path *path;
3360 struct btrfs_key key;
3361 struct btrfs_key found_key;
3362 struct btrfs_trans_handle *trans;
3363 struct extent_buffer *leaf;
3366 int enospc_errors = 0;
3367 bool counting = true;
3368 /* The single value limit and min/max limits use the same bytes in the */
3369 u64 limit_data = bctl->data.limit;
3370 u64 limit_meta = bctl->meta.limit;
3371 u64 limit_sys = bctl->sys.limit;
3375 int chunk_reserved = 0;
3377 /* step one make some room on all the devices */
3378 devices = &fs_info->fs_devices->devices;
3379 list_for_each_entry(device, devices, dev_list) {
3380 old_size = btrfs_device_get_total_bytes(device);
3381 size_to_free = div_factor(old_size, 1);
3382 size_to_free = min_t(u64, size_to_free, SZ_1M);
3383 if (!device->writeable ||
3384 btrfs_device_get_total_bytes(device) -
3385 btrfs_device_get_bytes_used(device) > size_to_free ||
3386 device->is_tgtdev_for_dev_replace)
3389 ret = btrfs_shrink_device(device, old_size - size_to_free);
3394 trans = btrfs_start_transaction(dev_root, 0);
3395 BUG_ON(IS_ERR(trans));
3397 ret = btrfs_grow_device(trans, device, old_size);
3400 btrfs_end_transaction(trans, dev_root);
3403 /* step two, relocate all the chunks */
3404 path = btrfs_alloc_path();
3410 /* zero out stat counters */
3411 spin_lock(&fs_info->balance_lock);
3412 memset(&bctl->stat, 0, sizeof(bctl->stat));
3413 spin_unlock(&fs_info->balance_lock);
3417 * The single value limit and min/max limits use the same bytes
3420 bctl->data.limit = limit_data;
3421 bctl->meta.limit = limit_meta;
3422 bctl->sys.limit = limit_sys;
3424 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3425 key.offset = (u64)-1;
3426 key.type = BTRFS_CHUNK_ITEM_KEY;
3429 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3430 atomic_read(&fs_info->balance_cancel_req)) {
3435 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3436 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3438 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3443 * this shouldn't happen, it means the last relocate
3447 BUG(); /* FIXME break ? */
3449 ret = btrfs_previous_item(chunk_root, path, 0,
3450 BTRFS_CHUNK_ITEM_KEY);
3452 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3457 leaf = path->nodes[0];
3458 slot = path->slots[0];
3459 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3461 if (found_key.objectid != key.objectid) {
3462 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3466 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3467 chunk_type = btrfs_chunk_type(leaf, chunk);
3470 spin_lock(&fs_info->balance_lock);
3471 bctl->stat.considered++;
3472 spin_unlock(&fs_info->balance_lock);
3475 ret = should_balance_chunk(chunk_root, leaf, chunk,
3478 btrfs_release_path(path);
3480 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3485 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3486 spin_lock(&fs_info->balance_lock);
3487 bctl->stat.expected++;
3488 spin_unlock(&fs_info->balance_lock);
3490 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3492 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3494 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3501 * Apply limit_min filter, no need to check if the LIMITS
3502 * filter is used, limit_min is 0 by default
3504 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3505 count_data < bctl->data.limit_min)
3506 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3507 count_meta < bctl->meta.limit_min)
3508 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3509 count_sys < bctl->sys.limit_min)) {
3510 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3514 if ((chunk_type & BTRFS_BLOCK_GROUP_DATA) && !chunk_reserved) {
3515 trans = btrfs_start_transaction(chunk_root, 0);
3516 if (IS_ERR(trans)) {
3517 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3518 ret = PTR_ERR(trans);
3522 ret = btrfs_force_chunk_alloc(trans, chunk_root,
3523 BTRFS_BLOCK_GROUP_DATA);
3524 btrfs_end_transaction(trans, chunk_root);
3526 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3532 ret = btrfs_relocate_chunk(chunk_root,
3534 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3535 if (ret && ret != -ENOSPC)
3537 if (ret == -ENOSPC) {
3540 spin_lock(&fs_info->balance_lock);
3541 bctl->stat.completed++;
3542 spin_unlock(&fs_info->balance_lock);
3545 if (found_key.offset == 0)
3547 key.offset = found_key.offset - 1;
3551 btrfs_release_path(path);
3556 btrfs_free_path(path);
3557 if (enospc_errors) {
3558 btrfs_info(fs_info, "%d enospc errors during balance",
3568 * alloc_profile_is_valid - see if a given profile is valid and reduced
3569 * @flags: profile to validate
3570 * @extended: if true @flags is treated as an extended profile
3572 static int alloc_profile_is_valid(u64 flags, int extended)
3574 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3575 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3577 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3579 /* 1) check that all other bits are zeroed */
3583 /* 2) see if profile is reduced */
3585 return !extended; /* "0" is valid for usual profiles */
3587 /* true if exactly one bit set */
3588 return (flags & (flags - 1)) == 0;
3591 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3593 /* cancel requested || normal exit path */
3594 return atomic_read(&fs_info->balance_cancel_req) ||
3595 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3596 atomic_read(&fs_info->balance_cancel_req) == 0);
3599 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3603 unset_balance_control(fs_info);
3604 ret = del_balance_item(fs_info->tree_root);
3606 btrfs_std_error(fs_info, ret, NULL);
3608 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3611 /* Non-zero return value signifies invalidity */
3612 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3615 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3616 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3617 (bctl_arg->target & ~allowed)));
3621 * Should be called with both balance and volume mutexes held
3623 int btrfs_balance(struct btrfs_balance_control *bctl,
3624 struct btrfs_ioctl_balance_args *bargs)
3626 struct btrfs_fs_info *fs_info = bctl->fs_info;
3633 if (btrfs_fs_closing(fs_info) ||
3634 atomic_read(&fs_info->balance_pause_req) ||
3635 atomic_read(&fs_info->balance_cancel_req)) {
3640 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3641 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3645 * In case of mixed groups both data and meta should be picked,
3646 * and identical options should be given for both of them.
3648 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3649 if (mixed && (bctl->flags & allowed)) {
3650 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3651 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3652 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3653 btrfs_err(fs_info, "with mixed groups data and "
3654 "metadata balance options must be the same");
3660 num_devices = fs_info->fs_devices->num_devices;
3661 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
3662 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3663 BUG_ON(num_devices < 1);
3666 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
3667 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3668 if (num_devices == 1)
3669 allowed |= BTRFS_BLOCK_GROUP_DUP;
3670 else if (num_devices > 1)
3671 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3672 if (num_devices > 2)
3673 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3674 if (num_devices > 3)
3675 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3676 BTRFS_BLOCK_GROUP_RAID6);
3677 if (validate_convert_profile(&bctl->data, allowed)) {
3678 btrfs_err(fs_info, "unable to start balance with target "
3679 "data profile %llu",
3684 if (validate_convert_profile(&bctl->meta, allowed)) {
3686 "unable to start balance with target metadata profile %llu",
3691 if (validate_convert_profile(&bctl->sys, allowed)) {
3693 "unable to start balance with target system profile %llu",
3699 /* allow to reduce meta or sys integrity only if force set */
3700 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3701 BTRFS_BLOCK_GROUP_RAID10 |
3702 BTRFS_BLOCK_GROUP_RAID5 |
3703 BTRFS_BLOCK_GROUP_RAID6;
3705 seq = read_seqbegin(&fs_info->profiles_lock);
3707 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3708 (fs_info->avail_system_alloc_bits & allowed) &&
3709 !(bctl->sys.target & allowed)) ||
3710 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3711 (fs_info->avail_metadata_alloc_bits & allowed) &&
3712 !(bctl->meta.target & allowed))) {
3713 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3714 btrfs_info(fs_info, "force reducing metadata integrity");
3716 btrfs_err(fs_info, "balance will reduce metadata "
3717 "integrity, use force if you want this");
3722 } while (read_seqretry(&fs_info->profiles_lock, seq));
3724 if (btrfs_get_num_tolerated_disk_barrier_failures(bctl->meta.target) <
3725 btrfs_get_num_tolerated_disk_barrier_failures(bctl->data.target)) {
3727 "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
3728 bctl->meta.target, bctl->data.target);
3731 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3732 fs_info->num_tolerated_disk_barrier_failures = min(
3733 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info),
3734 btrfs_get_num_tolerated_disk_barrier_failures(
3738 ret = insert_balance_item(fs_info->tree_root, bctl);
3739 if (ret && ret != -EEXIST)
3742 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3743 BUG_ON(ret == -EEXIST);
3744 set_balance_control(bctl);
3746 BUG_ON(ret != -EEXIST);
3747 spin_lock(&fs_info->balance_lock);
3748 update_balance_args(bctl);
3749 spin_unlock(&fs_info->balance_lock);
3752 atomic_inc(&fs_info->balance_running);
3753 mutex_unlock(&fs_info->balance_mutex);
3755 ret = __btrfs_balance(fs_info);
3757 mutex_lock(&fs_info->balance_mutex);
3758 atomic_dec(&fs_info->balance_running);
3760 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3761 fs_info->num_tolerated_disk_barrier_failures =
3762 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3766 memset(bargs, 0, sizeof(*bargs));
3767 update_ioctl_balance_args(fs_info, 0, bargs);
3770 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3771 balance_need_close(fs_info)) {
3772 __cancel_balance(fs_info);
3775 wake_up(&fs_info->balance_wait_q);
3779 if (bctl->flags & BTRFS_BALANCE_RESUME)
3780 __cancel_balance(fs_info);
3783 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3788 static int balance_kthread(void *data)
3790 struct btrfs_fs_info *fs_info = data;
3793 mutex_lock(&fs_info->volume_mutex);
3794 mutex_lock(&fs_info->balance_mutex);
3796 if (fs_info->balance_ctl) {
3797 btrfs_info(fs_info, "continuing balance");
3798 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3801 mutex_unlock(&fs_info->balance_mutex);
3802 mutex_unlock(&fs_info->volume_mutex);
3807 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3809 struct task_struct *tsk;
3811 spin_lock(&fs_info->balance_lock);
3812 if (!fs_info->balance_ctl) {
3813 spin_unlock(&fs_info->balance_lock);
3816 spin_unlock(&fs_info->balance_lock);
3818 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3819 btrfs_info(fs_info, "force skipping balance");
3823 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3824 return PTR_ERR_OR_ZERO(tsk);
3827 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3829 struct btrfs_balance_control *bctl;
3830 struct btrfs_balance_item *item;
3831 struct btrfs_disk_balance_args disk_bargs;
3832 struct btrfs_path *path;
3833 struct extent_buffer *leaf;
3834 struct btrfs_key key;
3837 path = btrfs_alloc_path();
3841 key.objectid = BTRFS_BALANCE_OBJECTID;
3842 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3845 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3848 if (ret > 0) { /* ret = -ENOENT; */
3853 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3859 leaf = path->nodes[0];
3860 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3862 bctl->fs_info = fs_info;
3863 bctl->flags = btrfs_balance_flags(leaf, item);
3864 bctl->flags |= BTRFS_BALANCE_RESUME;
3866 btrfs_balance_data(leaf, item, &disk_bargs);
3867 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3868 btrfs_balance_meta(leaf, item, &disk_bargs);
3869 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3870 btrfs_balance_sys(leaf, item, &disk_bargs);
3871 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3873 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3875 mutex_lock(&fs_info->volume_mutex);
3876 mutex_lock(&fs_info->balance_mutex);
3878 set_balance_control(bctl);
3880 mutex_unlock(&fs_info->balance_mutex);
3881 mutex_unlock(&fs_info->volume_mutex);
3883 btrfs_free_path(path);
3887 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3891 mutex_lock(&fs_info->balance_mutex);
3892 if (!fs_info->balance_ctl) {
3893 mutex_unlock(&fs_info->balance_mutex);
3897 if (atomic_read(&fs_info->balance_running)) {
3898 atomic_inc(&fs_info->balance_pause_req);
3899 mutex_unlock(&fs_info->balance_mutex);
3901 wait_event(fs_info->balance_wait_q,
3902 atomic_read(&fs_info->balance_running) == 0);
3904 mutex_lock(&fs_info->balance_mutex);
3905 /* we are good with balance_ctl ripped off from under us */
3906 BUG_ON(atomic_read(&fs_info->balance_running));
3907 atomic_dec(&fs_info->balance_pause_req);
3912 mutex_unlock(&fs_info->balance_mutex);
3916 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3918 if (fs_info->sb->s_flags & MS_RDONLY)
3921 mutex_lock(&fs_info->balance_mutex);
3922 if (!fs_info->balance_ctl) {
3923 mutex_unlock(&fs_info->balance_mutex);
3927 atomic_inc(&fs_info->balance_cancel_req);
3929 * if we are running just wait and return, balance item is
3930 * deleted in btrfs_balance in this case
3932 if (atomic_read(&fs_info->balance_running)) {
3933 mutex_unlock(&fs_info->balance_mutex);
3934 wait_event(fs_info->balance_wait_q,
3935 atomic_read(&fs_info->balance_running) == 0);
3936 mutex_lock(&fs_info->balance_mutex);
3938 /* __cancel_balance needs volume_mutex */
3939 mutex_unlock(&fs_info->balance_mutex);
3940 mutex_lock(&fs_info->volume_mutex);
3941 mutex_lock(&fs_info->balance_mutex);
3943 if (fs_info->balance_ctl)
3944 __cancel_balance(fs_info);
3946 mutex_unlock(&fs_info->volume_mutex);
3949 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3950 atomic_dec(&fs_info->balance_cancel_req);
3951 mutex_unlock(&fs_info->balance_mutex);
3955 static int btrfs_uuid_scan_kthread(void *data)
3957 struct btrfs_fs_info *fs_info = data;
3958 struct btrfs_root *root = fs_info->tree_root;
3959 struct btrfs_key key;
3960 struct btrfs_key max_key;
3961 struct btrfs_path *path = NULL;
3963 struct extent_buffer *eb;
3965 struct btrfs_root_item root_item;
3967 struct btrfs_trans_handle *trans = NULL;
3969 path = btrfs_alloc_path();
3976 key.type = BTRFS_ROOT_ITEM_KEY;
3979 max_key.objectid = (u64)-1;
3980 max_key.type = BTRFS_ROOT_ITEM_KEY;
3981 max_key.offset = (u64)-1;
3984 ret = btrfs_search_forward(root, &key, path, 0);
3991 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3992 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3993 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3994 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3997 eb = path->nodes[0];
3998 slot = path->slots[0];
3999 item_size = btrfs_item_size_nr(eb, slot);
4000 if (item_size < sizeof(root_item))
4003 read_extent_buffer(eb, &root_item,
4004 btrfs_item_ptr_offset(eb, slot),
4005 (int)sizeof(root_item));
4006 if (btrfs_root_refs(&root_item) == 0)
4009 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4010 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4014 btrfs_release_path(path);
4016 * 1 - subvol uuid item
4017 * 1 - received_subvol uuid item
4019 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4020 if (IS_ERR(trans)) {
4021 ret = PTR_ERR(trans);
4029 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4030 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
4032 BTRFS_UUID_KEY_SUBVOL,
4035 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4041 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4042 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
4043 root_item.received_uuid,
4044 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4047 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4055 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
4061 btrfs_release_path(path);
4062 if (key.offset < (u64)-1) {
4064 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4066 key.type = BTRFS_ROOT_ITEM_KEY;
4067 } else if (key.objectid < (u64)-1) {
4069 key.type = BTRFS_ROOT_ITEM_KEY;
4078 btrfs_free_path(path);
4079 if (trans && !IS_ERR(trans))
4080 btrfs_end_transaction(trans, fs_info->uuid_root);
4082 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4084 fs_info->update_uuid_tree_gen = 1;
4085 up(&fs_info->uuid_tree_rescan_sem);
4090 * Callback for btrfs_uuid_tree_iterate().
4092 * 0 check succeeded, the entry is not outdated.
4093 * < 0 if an error occurred.
4094 * > 0 if the check failed, which means the caller shall remove the entry.
4096 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4097 u8 *uuid, u8 type, u64 subid)
4099 struct btrfs_key key;
4101 struct btrfs_root *subvol_root;
4103 if (type != BTRFS_UUID_KEY_SUBVOL &&
4104 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4107 key.objectid = subid;
4108 key.type = BTRFS_ROOT_ITEM_KEY;
4109 key.offset = (u64)-1;
4110 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4111 if (IS_ERR(subvol_root)) {
4112 ret = PTR_ERR(subvol_root);
4119 case BTRFS_UUID_KEY_SUBVOL:
4120 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4123 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4124 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4134 static int btrfs_uuid_rescan_kthread(void *data)
4136 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4140 * 1st step is to iterate through the existing UUID tree and
4141 * to delete all entries that contain outdated data.
4142 * 2nd step is to add all missing entries to the UUID tree.
4144 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4146 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4147 up(&fs_info->uuid_tree_rescan_sem);
4150 return btrfs_uuid_scan_kthread(data);
4153 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4155 struct btrfs_trans_handle *trans;
4156 struct btrfs_root *tree_root = fs_info->tree_root;
4157 struct btrfs_root *uuid_root;
4158 struct task_struct *task;
4165 trans = btrfs_start_transaction(tree_root, 2);
4167 return PTR_ERR(trans);
4169 uuid_root = btrfs_create_tree(trans, fs_info,
4170 BTRFS_UUID_TREE_OBJECTID);
4171 if (IS_ERR(uuid_root)) {
4172 ret = PTR_ERR(uuid_root);
4173 btrfs_abort_transaction(trans, tree_root, ret);
4177 fs_info->uuid_root = uuid_root;
4179 ret = btrfs_commit_transaction(trans, tree_root);
4183 down(&fs_info->uuid_tree_rescan_sem);
4184 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4186 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4187 btrfs_warn(fs_info, "failed to start uuid_scan task");
4188 up(&fs_info->uuid_tree_rescan_sem);
4189 return PTR_ERR(task);
4195 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4197 struct task_struct *task;
4199 down(&fs_info->uuid_tree_rescan_sem);
4200 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4202 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4203 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4204 up(&fs_info->uuid_tree_rescan_sem);
4205 return PTR_ERR(task);
4212 * shrinking a device means finding all of the device extents past
4213 * the new size, and then following the back refs to the chunks.
4214 * The chunk relocation code actually frees the device extent
4216 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4218 struct btrfs_trans_handle *trans;
4219 struct btrfs_root *root = device->dev_root;
4220 struct btrfs_dev_extent *dev_extent = NULL;
4221 struct btrfs_path *path;
4227 bool retried = false;
4228 bool checked_pending_chunks = false;
4229 struct extent_buffer *l;
4230 struct btrfs_key key;
4231 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4232 u64 old_total = btrfs_super_total_bytes(super_copy);
4233 u64 old_size = btrfs_device_get_total_bytes(device);
4234 u64 diff = old_size - new_size;
4236 if (device->is_tgtdev_for_dev_replace)
4239 path = btrfs_alloc_path();
4243 path->reada = READA_FORWARD;
4247 btrfs_device_set_total_bytes(device, new_size);
4248 if (device->writeable) {
4249 device->fs_devices->total_rw_bytes -= diff;
4250 spin_lock(&root->fs_info->free_chunk_lock);
4251 root->fs_info->free_chunk_space -= diff;
4252 spin_unlock(&root->fs_info->free_chunk_lock);
4254 unlock_chunks(root);
4257 key.objectid = device->devid;
4258 key.offset = (u64)-1;
4259 key.type = BTRFS_DEV_EXTENT_KEY;
4262 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
4263 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4265 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4269 ret = btrfs_previous_item(root, path, 0, key.type);
4271 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4276 btrfs_release_path(path);
4281 slot = path->slots[0];
4282 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4284 if (key.objectid != device->devid) {
4285 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4286 btrfs_release_path(path);
4290 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4291 length = btrfs_dev_extent_length(l, dev_extent);
4293 if (key.offset + length <= new_size) {
4294 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4295 btrfs_release_path(path);
4299 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4300 btrfs_release_path(path);
4302 ret = btrfs_relocate_chunk(root, chunk_offset);
4303 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4304 if (ret && ret != -ENOSPC)
4308 } while (key.offset-- > 0);
4310 if (failed && !retried) {
4314 } else if (failed && retried) {
4319 /* Shrinking succeeded, else we would be at "done". */
4320 trans = btrfs_start_transaction(root, 0);
4321 if (IS_ERR(trans)) {
4322 ret = PTR_ERR(trans);
4329 * We checked in the above loop all device extents that were already in
4330 * the device tree. However before we have updated the device's
4331 * total_bytes to the new size, we might have had chunk allocations that
4332 * have not complete yet (new block groups attached to transaction
4333 * handles), and therefore their device extents were not yet in the
4334 * device tree and we missed them in the loop above. So if we have any
4335 * pending chunk using a device extent that overlaps the device range
4336 * that we can not use anymore, commit the current transaction and
4337 * repeat the search on the device tree - this way we guarantee we will
4338 * not have chunks using device extents that end beyond 'new_size'.
4340 if (!checked_pending_chunks) {
4341 u64 start = new_size;
4342 u64 len = old_size - new_size;
4344 if (contains_pending_extent(trans->transaction, device,
4346 unlock_chunks(root);
4347 checked_pending_chunks = true;
4350 ret = btrfs_commit_transaction(trans, root);
4357 btrfs_device_set_disk_total_bytes(device, new_size);
4358 if (list_empty(&device->resized_list))
4359 list_add_tail(&device->resized_list,
4360 &root->fs_info->fs_devices->resized_devices);
4362 WARN_ON(diff > old_total);
4363 btrfs_set_super_total_bytes(super_copy, old_total - diff);
4364 unlock_chunks(root);
4366 /* Now btrfs_update_device() will change the on-disk size. */
4367 ret = btrfs_update_device(trans, device);
4368 btrfs_end_transaction(trans, root);
4370 btrfs_free_path(path);
4373 btrfs_device_set_total_bytes(device, old_size);
4374 if (device->writeable)
4375 device->fs_devices->total_rw_bytes += diff;
4376 spin_lock(&root->fs_info->free_chunk_lock);
4377 root->fs_info->free_chunk_space += diff;
4378 spin_unlock(&root->fs_info->free_chunk_lock);
4379 unlock_chunks(root);
4384 static int btrfs_add_system_chunk(struct btrfs_root *root,
4385 struct btrfs_key *key,
4386 struct btrfs_chunk *chunk, int item_size)
4388 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4389 struct btrfs_disk_key disk_key;
4394 array_size = btrfs_super_sys_array_size(super_copy);
4395 if (array_size + item_size + sizeof(disk_key)
4396 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4397 unlock_chunks(root);
4401 ptr = super_copy->sys_chunk_array + array_size;
4402 btrfs_cpu_key_to_disk(&disk_key, key);
4403 memcpy(ptr, &disk_key, sizeof(disk_key));
4404 ptr += sizeof(disk_key);
4405 memcpy(ptr, chunk, item_size);
4406 item_size += sizeof(disk_key);
4407 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4408 unlock_chunks(root);
4414 * sort the devices in descending order by max_avail, total_avail
4416 static int btrfs_cmp_device_info(const void *a, const void *b)
4418 const struct btrfs_device_info *di_a = a;
4419 const struct btrfs_device_info *di_b = b;
4421 if (di_a->max_avail > di_b->max_avail)
4423 if (di_a->max_avail < di_b->max_avail)
4425 if (di_a->total_avail > di_b->total_avail)
4427 if (di_a->total_avail < di_b->total_avail)
4432 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
4434 /* TODO allow them to set a preferred stripe size */
4438 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4440 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4443 btrfs_set_fs_incompat(info, RAID56);
4446 #define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r) \
4447 - sizeof(struct btrfs_item) \
4448 - sizeof(struct btrfs_chunk)) \
4449 / sizeof(struct btrfs_stripe) + 1)
4451 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4452 - 2 * sizeof(struct btrfs_disk_key) \
4453 - 2 * sizeof(struct btrfs_chunk)) \
4454 / sizeof(struct btrfs_stripe) + 1)
4456 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4457 struct btrfs_root *extent_root, u64 start,
4460 struct btrfs_fs_info *info = extent_root->fs_info;
4461 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4462 struct list_head *cur;
4463 struct map_lookup *map = NULL;
4464 struct extent_map_tree *em_tree;
4465 struct extent_map *em;
4466 struct btrfs_device_info *devices_info = NULL;
4468 int num_stripes; /* total number of stripes to allocate */
4469 int data_stripes; /* number of stripes that count for
4471 int sub_stripes; /* sub_stripes info for map */
4472 int dev_stripes; /* stripes per dev */
4473 int devs_max; /* max devs to use */
4474 int devs_min; /* min devs needed */
4475 int devs_increment; /* ndevs has to be a multiple of this */
4476 int ncopies; /* how many copies to data has */
4478 u64 max_stripe_size;
4482 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4488 BUG_ON(!alloc_profile_is_valid(type, 0));
4490 if (list_empty(&fs_devices->alloc_list))
4493 index = __get_raid_index(type);
4495 sub_stripes = btrfs_raid_array[index].sub_stripes;
4496 dev_stripes = btrfs_raid_array[index].dev_stripes;
4497 devs_max = btrfs_raid_array[index].devs_max;
4498 devs_min = btrfs_raid_array[index].devs_min;
4499 devs_increment = btrfs_raid_array[index].devs_increment;
4500 ncopies = btrfs_raid_array[index].ncopies;
4502 if (type & BTRFS_BLOCK_GROUP_DATA) {
4503 max_stripe_size = SZ_1G;
4504 max_chunk_size = 10 * max_stripe_size;
4506 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4507 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4508 /* for larger filesystems, use larger metadata chunks */
4509 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4510 max_stripe_size = SZ_1G;
4512 max_stripe_size = SZ_256M;
4513 max_chunk_size = max_stripe_size;
4515 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4516 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4517 max_stripe_size = SZ_32M;
4518 max_chunk_size = 2 * max_stripe_size;
4520 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4522 btrfs_err(info, "invalid chunk type 0x%llx requested",
4527 /* we don't want a chunk larger than 10% of writeable space */
4528 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4531 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4536 cur = fs_devices->alloc_list.next;
4539 * in the first pass through the devices list, we gather information
4540 * about the available holes on each device.
4543 while (cur != &fs_devices->alloc_list) {
4544 struct btrfs_device *device;
4548 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4552 if (!device->writeable) {
4554 "BTRFS: read-only device in alloc_list\n");
4558 if (!device->in_fs_metadata ||
4559 device->is_tgtdev_for_dev_replace)
4562 if (device->total_bytes > device->bytes_used)
4563 total_avail = device->total_bytes - device->bytes_used;
4567 /* If there is no space on this device, skip it. */
4568 if (total_avail == 0)
4571 ret = find_free_dev_extent(trans, device,
4572 max_stripe_size * dev_stripes,
4573 &dev_offset, &max_avail);
4574 if (ret && ret != -ENOSPC)
4578 max_avail = max_stripe_size * dev_stripes;
4580 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4583 if (ndevs == fs_devices->rw_devices) {
4584 WARN(1, "%s: found more than %llu devices\n",
4585 __func__, fs_devices->rw_devices);
4588 devices_info[ndevs].dev_offset = dev_offset;
4589 devices_info[ndevs].max_avail = max_avail;
4590 devices_info[ndevs].total_avail = total_avail;
4591 devices_info[ndevs].dev = device;
4596 * now sort the devices by hole size / available space
4598 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4599 btrfs_cmp_device_info, NULL);
4601 /* round down to number of usable stripes */
4602 ndevs -= ndevs % devs_increment;
4604 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4609 if (devs_max && ndevs > devs_max)
4612 * the primary goal is to maximize the number of stripes, so use as many
4613 * devices as possible, even if the stripes are not maximum sized.
4615 stripe_size = devices_info[ndevs-1].max_avail;
4616 num_stripes = ndevs * dev_stripes;
4619 * this will have to be fixed for RAID1 and RAID10 over
4622 data_stripes = num_stripes / ncopies;
4624 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4625 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4626 btrfs_super_stripesize(info->super_copy));
4627 data_stripes = num_stripes - 1;
4629 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4630 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4631 btrfs_super_stripesize(info->super_copy));
4632 data_stripes = num_stripes - 2;
4636 * Use the number of data stripes to figure out how big this chunk
4637 * is really going to be in terms of logical address space,
4638 * and compare that answer with the max chunk size
4640 if (stripe_size * data_stripes > max_chunk_size) {
4641 u64 mask = (1ULL << 24) - 1;
4643 stripe_size = div_u64(max_chunk_size, data_stripes);
4645 /* bump the answer up to a 16MB boundary */
4646 stripe_size = (stripe_size + mask) & ~mask;
4648 /* but don't go higher than the limits we found
4649 * while searching for free extents
4651 if (stripe_size > devices_info[ndevs-1].max_avail)
4652 stripe_size = devices_info[ndevs-1].max_avail;
4655 stripe_size = div_u64(stripe_size, dev_stripes);
4657 /* align to BTRFS_STRIPE_LEN */
4658 stripe_size = div_u64(stripe_size, raid_stripe_len);
4659 stripe_size *= raid_stripe_len;
4661 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4666 map->num_stripes = num_stripes;
4668 for (i = 0; i < ndevs; ++i) {
4669 for (j = 0; j < dev_stripes; ++j) {
4670 int s = i * dev_stripes + j;
4671 map->stripes[s].dev = devices_info[i].dev;
4672 map->stripes[s].physical = devices_info[i].dev_offset +
4676 map->sector_size = extent_root->sectorsize;
4677 map->stripe_len = raid_stripe_len;
4678 map->io_align = raid_stripe_len;
4679 map->io_width = raid_stripe_len;
4681 map->sub_stripes = sub_stripes;
4683 num_bytes = stripe_size * data_stripes;
4685 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4687 em = alloc_extent_map();
4693 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4694 em->map_lookup = map;
4696 em->len = num_bytes;
4697 em->block_start = 0;
4698 em->block_len = em->len;
4699 em->orig_block_len = stripe_size;
4701 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4702 write_lock(&em_tree->lock);
4703 ret = add_extent_mapping(em_tree, em, 0);
4705 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4706 atomic_inc(&em->refs);
4708 write_unlock(&em_tree->lock);
4710 free_extent_map(em);
4714 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4715 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4718 goto error_del_extent;
4720 for (i = 0; i < map->num_stripes; i++) {
4721 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4722 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4725 spin_lock(&extent_root->fs_info->free_chunk_lock);
4726 extent_root->fs_info->free_chunk_space -= (stripe_size *
4728 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4730 free_extent_map(em);
4731 check_raid56_incompat_flag(extent_root->fs_info, type);
4733 kfree(devices_info);
4737 write_lock(&em_tree->lock);
4738 remove_extent_mapping(em_tree, em);
4739 write_unlock(&em_tree->lock);
4741 /* One for our allocation */
4742 free_extent_map(em);
4743 /* One for the tree reference */
4744 free_extent_map(em);
4745 /* One for the pending_chunks list reference */
4746 free_extent_map(em);
4748 kfree(devices_info);
4752 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4753 struct btrfs_root *extent_root,
4754 u64 chunk_offset, u64 chunk_size)
4756 struct btrfs_key key;
4757 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4758 struct btrfs_device *device;
4759 struct btrfs_chunk *chunk;
4760 struct btrfs_stripe *stripe;
4761 struct extent_map_tree *em_tree;
4762 struct extent_map *em;
4763 struct map_lookup *map;
4770 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4771 read_lock(&em_tree->lock);
4772 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4773 read_unlock(&em_tree->lock);
4776 btrfs_crit(extent_root->fs_info, "unable to find logical "
4777 "%Lu len %Lu", chunk_offset, chunk_size);
4781 if (em->start != chunk_offset || em->len != chunk_size) {
4782 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4783 " %Lu-%Lu, found %Lu-%Lu", chunk_offset,
4784 chunk_size, em->start, em->len);
4785 free_extent_map(em);
4789 map = em->map_lookup;
4790 item_size = btrfs_chunk_item_size(map->num_stripes);
4791 stripe_size = em->orig_block_len;
4793 chunk = kzalloc(item_size, GFP_NOFS);
4800 * Take the device list mutex to prevent races with the final phase of
4801 * a device replace operation that replaces the device object associated
4802 * with the map's stripes, because the device object's id can change
4803 * at any time during that final phase of the device replace operation
4804 * (dev-replace.c:btrfs_dev_replace_finishing()).
4806 mutex_lock(&chunk_root->fs_info->fs_devices->device_list_mutex);
4807 for (i = 0; i < map->num_stripes; i++) {
4808 device = map->stripes[i].dev;
4809 dev_offset = map->stripes[i].physical;
4811 ret = btrfs_update_device(trans, device);
4814 ret = btrfs_alloc_dev_extent(trans, device,
4815 chunk_root->root_key.objectid,
4816 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4817 chunk_offset, dev_offset,
4823 mutex_unlock(&chunk_root->fs_info->fs_devices->device_list_mutex);
4827 stripe = &chunk->stripe;
4828 for (i = 0; i < map->num_stripes; i++) {
4829 device = map->stripes[i].dev;
4830 dev_offset = map->stripes[i].physical;
4832 btrfs_set_stack_stripe_devid(stripe, device->devid);
4833 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4834 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4837 mutex_unlock(&chunk_root->fs_info->fs_devices->device_list_mutex);
4839 btrfs_set_stack_chunk_length(chunk, chunk_size);
4840 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4841 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4842 btrfs_set_stack_chunk_type(chunk, map->type);
4843 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4844 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4845 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4846 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4847 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4849 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4850 key.type = BTRFS_CHUNK_ITEM_KEY;
4851 key.offset = chunk_offset;
4853 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4854 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4856 * TODO: Cleanup of inserted chunk root in case of
4859 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4865 free_extent_map(em);
4870 * Chunk allocation falls into two parts. The first part does works
4871 * that make the new allocated chunk useable, but not do any operation
4872 * that modifies the chunk tree. The second part does the works that
4873 * require modifying the chunk tree. This division is important for the
4874 * bootstrap process of adding storage to a seed btrfs.
4876 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4877 struct btrfs_root *extent_root, u64 type)
4881 ASSERT(mutex_is_locked(&extent_root->fs_info->chunk_mutex));
4882 chunk_offset = find_next_chunk(extent_root->fs_info);
4883 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4886 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4887 struct btrfs_root *root,
4888 struct btrfs_device *device)
4891 u64 sys_chunk_offset;
4893 struct btrfs_fs_info *fs_info = root->fs_info;
4894 struct btrfs_root *extent_root = fs_info->extent_root;
4897 chunk_offset = find_next_chunk(fs_info);
4898 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4899 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4904 sys_chunk_offset = find_next_chunk(root->fs_info);
4905 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4906 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4911 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
4915 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4916 BTRFS_BLOCK_GROUP_RAID10 |
4917 BTRFS_BLOCK_GROUP_RAID5 |
4918 BTRFS_BLOCK_GROUP_DUP)) {
4920 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
4929 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4931 struct extent_map *em;
4932 struct map_lookup *map;
4933 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4938 read_lock(&map_tree->map_tree.lock);
4939 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4940 read_unlock(&map_tree->map_tree.lock);
4944 map = em->map_lookup;
4945 for (i = 0; i < map->num_stripes; i++) {
4946 if (map->stripes[i].dev->missing) {
4951 if (!map->stripes[i].dev->writeable) {
4958 * If the number of missing devices is larger than max errors,
4959 * we can not write the data into that chunk successfully, so
4962 if (miss_ndevs > btrfs_chunk_max_errors(map))
4965 free_extent_map(em);
4969 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4971 extent_map_tree_init(&tree->map_tree);
4974 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4976 struct extent_map *em;
4979 write_lock(&tree->map_tree.lock);
4980 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4982 remove_extent_mapping(&tree->map_tree, em);
4983 write_unlock(&tree->map_tree.lock);
4987 free_extent_map(em);
4988 /* once for the tree */
4989 free_extent_map(em);
4993 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4995 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4996 struct extent_map *em;
4997 struct map_lookup *map;
4998 struct extent_map_tree *em_tree = &map_tree->map_tree;
5001 read_lock(&em_tree->lock);
5002 em = lookup_extent_mapping(em_tree, logical, len);
5003 read_unlock(&em_tree->lock);
5006 * We could return errors for these cases, but that could get ugly and
5007 * we'd probably do the same thing which is just not do anything else
5008 * and exit, so return 1 so the callers don't try to use other copies.
5011 btrfs_crit(fs_info, "No mapping for %Lu-%Lu", logical,
5016 if (em->start > logical || em->start + em->len < logical) {
5017 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
5018 "%Lu-%Lu", logical, logical+len, em->start,
5019 em->start + em->len);
5020 free_extent_map(em);
5024 map = em->map_lookup;
5025 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5026 ret = map->num_stripes;
5027 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5028 ret = map->sub_stripes;
5029 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5031 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5035 free_extent_map(em);
5037 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
5038 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
5040 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
5045 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
5046 struct btrfs_mapping_tree *map_tree,
5049 struct extent_map *em;
5050 struct map_lookup *map;
5051 struct extent_map_tree *em_tree = &map_tree->map_tree;
5052 unsigned long len = root->sectorsize;
5054 read_lock(&em_tree->lock);
5055 em = lookup_extent_mapping(em_tree, logical, len);
5056 read_unlock(&em_tree->lock);
5059 BUG_ON(em->start > logical || em->start + em->len < logical);
5060 map = em->map_lookup;
5061 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5062 len = map->stripe_len * nr_data_stripes(map);
5063 free_extent_map(em);
5067 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
5068 u64 logical, u64 len, int mirror_num)
5070 struct extent_map *em;
5071 struct map_lookup *map;
5072 struct extent_map_tree *em_tree = &map_tree->map_tree;
5075 read_lock(&em_tree->lock);
5076 em = lookup_extent_mapping(em_tree, logical, len);
5077 read_unlock(&em_tree->lock);
5080 BUG_ON(em->start > logical || em->start + em->len < logical);
5081 map = em->map_lookup;
5082 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5084 free_extent_map(em);
5088 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5089 struct map_lookup *map, int first, int num,
5090 int optimal, int dev_replace_is_ongoing)
5094 struct btrfs_device *srcdev;
5096 if (dev_replace_is_ongoing &&
5097 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5098 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5099 srcdev = fs_info->dev_replace.srcdev;
5104 * try to avoid the drive that is the source drive for a
5105 * dev-replace procedure, only choose it if no other non-missing
5106 * mirror is available
5108 for (tolerance = 0; tolerance < 2; tolerance++) {
5109 if (map->stripes[optimal].dev->bdev &&
5110 (tolerance || map->stripes[optimal].dev != srcdev))
5112 for (i = first; i < first + num; i++) {
5113 if (map->stripes[i].dev->bdev &&
5114 (tolerance || map->stripes[i].dev != srcdev))
5119 /* we couldn't find one that doesn't fail. Just return something
5120 * and the io error handling code will clean up eventually
5125 static inline int parity_smaller(u64 a, u64 b)
5130 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5131 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5133 struct btrfs_bio_stripe s;
5140 for (i = 0; i < num_stripes - 1; i++) {
5141 if (parity_smaller(bbio->raid_map[i],
5142 bbio->raid_map[i+1])) {
5143 s = bbio->stripes[i];
5144 l = bbio->raid_map[i];
5145 bbio->stripes[i] = bbio->stripes[i+1];
5146 bbio->raid_map[i] = bbio->raid_map[i+1];
5147 bbio->stripes[i+1] = s;
5148 bbio->raid_map[i+1] = l;
5156 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5158 struct btrfs_bio *bbio = kzalloc(
5159 /* the size of the btrfs_bio */
5160 sizeof(struct btrfs_bio) +
5161 /* plus the variable array for the stripes */
5162 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5163 /* plus the variable array for the tgt dev */
5164 sizeof(int) * (real_stripes) +
5166 * plus the raid_map, which includes both the tgt dev
5169 sizeof(u64) * (total_stripes),
5170 GFP_NOFS|__GFP_NOFAIL);
5172 atomic_set(&bbio->error, 0);
5173 atomic_set(&bbio->refs, 1);
5178 void btrfs_get_bbio(struct btrfs_bio *bbio)
5180 WARN_ON(!atomic_read(&bbio->refs));
5181 atomic_inc(&bbio->refs);
5184 void btrfs_put_bbio(struct btrfs_bio *bbio)
5188 if (atomic_dec_and_test(&bbio->refs))
5192 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5193 u64 logical, u64 *length,
5194 struct btrfs_bio **bbio_ret,
5195 int mirror_num, int need_raid_map)
5197 struct extent_map *em;
5198 struct map_lookup *map;
5199 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
5200 struct extent_map_tree *em_tree = &map_tree->map_tree;
5203 u64 stripe_end_offset;
5213 int tgtdev_indexes = 0;
5214 struct btrfs_bio *bbio = NULL;
5215 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5216 int dev_replace_is_ongoing = 0;
5217 int num_alloc_stripes;
5218 int patch_the_first_stripe_for_dev_replace = 0;
5219 u64 physical_to_patch_in_first_stripe = 0;
5220 u64 raid56_full_stripe_start = (u64)-1;
5222 read_lock(&em_tree->lock);
5223 em = lookup_extent_mapping(em_tree, logical, *length);
5224 read_unlock(&em_tree->lock);
5227 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
5232 if (em->start > logical || em->start + em->len < logical) {
5233 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
5234 "found %Lu-%Lu", logical, em->start,
5235 em->start + em->len);
5236 free_extent_map(em);
5240 map = em->map_lookup;
5241 offset = logical - em->start;
5243 stripe_len = map->stripe_len;
5246 * stripe_nr counts the total number of stripes we have to stride
5247 * to get to this block
5249 stripe_nr = div64_u64(stripe_nr, stripe_len);
5251 stripe_offset = stripe_nr * stripe_len;
5252 BUG_ON(offset < stripe_offset);
5254 /* stripe_offset is the offset of this block in its stripe*/
5255 stripe_offset = offset - stripe_offset;
5257 /* if we're here for raid56, we need to know the stripe aligned start */
5258 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5259 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5260 raid56_full_stripe_start = offset;
5262 /* allow a write of a full stripe, but make sure we don't
5263 * allow straddling of stripes
5265 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5267 raid56_full_stripe_start *= full_stripe_len;
5270 if (rw & REQ_DISCARD) {
5271 /* we don't discard raid56 yet */
5272 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5276 *length = min_t(u64, em->len - offset, *length);
5277 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5279 /* For writes to RAID[56], allow a full stripeset across all disks.
5280 For other RAID types and for RAID[56] reads, just allow a single
5281 stripe (on a single disk). */
5282 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5284 max_len = stripe_len * nr_data_stripes(map) -
5285 (offset - raid56_full_stripe_start);
5287 /* we limit the length of each bio to what fits in a stripe */
5288 max_len = stripe_len - stripe_offset;
5290 *length = min_t(u64, em->len - offset, max_len);
5292 *length = em->len - offset;
5295 /* This is for when we're called from btrfs_merge_bio_hook() and all
5296 it cares about is the length */
5300 btrfs_dev_replace_lock(dev_replace, 0);
5301 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5302 if (!dev_replace_is_ongoing)
5303 btrfs_dev_replace_unlock(dev_replace, 0);
5305 btrfs_dev_replace_set_lock_blocking(dev_replace);
5307 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5308 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
5309 dev_replace->tgtdev != NULL) {
5311 * in dev-replace case, for repair case (that's the only
5312 * case where the mirror is selected explicitly when
5313 * calling btrfs_map_block), blocks left of the left cursor
5314 * can also be read from the target drive.
5315 * For REQ_GET_READ_MIRRORS, the target drive is added as
5316 * the last one to the array of stripes. For READ, it also
5317 * needs to be supported using the same mirror number.
5318 * If the requested block is not left of the left cursor,
5319 * EIO is returned. This can happen because btrfs_num_copies()
5320 * returns one more in the dev-replace case.
5322 u64 tmp_length = *length;
5323 struct btrfs_bio *tmp_bbio = NULL;
5324 int tmp_num_stripes;
5325 u64 srcdev_devid = dev_replace->srcdev->devid;
5326 int index_srcdev = 0;
5328 u64 physical_of_found = 0;
5330 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
5331 logical, &tmp_length, &tmp_bbio, 0, 0);
5333 WARN_ON(tmp_bbio != NULL);
5337 tmp_num_stripes = tmp_bbio->num_stripes;
5338 if (mirror_num > tmp_num_stripes) {
5340 * REQ_GET_READ_MIRRORS does not contain this
5341 * mirror, that means that the requested area
5342 * is not left of the left cursor
5345 btrfs_put_bbio(tmp_bbio);
5350 * process the rest of the function using the mirror_num
5351 * of the source drive. Therefore look it up first.
5352 * At the end, patch the device pointer to the one of the
5355 for (i = 0; i < tmp_num_stripes; i++) {
5356 if (tmp_bbio->stripes[i].dev->devid != srcdev_devid)
5360 * In case of DUP, in order to keep it simple, only add
5361 * the mirror with the lowest physical address
5364 physical_of_found <= tmp_bbio->stripes[i].physical)
5369 physical_of_found = tmp_bbio->stripes[i].physical;
5372 btrfs_put_bbio(tmp_bbio);
5380 mirror_num = index_srcdev + 1;
5381 patch_the_first_stripe_for_dev_replace = 1;
5382 physical_to_patch_in_first_stripe = physical_of_found;
5383 } else if (mirror_num > map->num_stripes) {
5389 stripe_nr_orig = stripe_nr;
5390 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
5391 stripe_nr_end = div_u64(stripe_nr_end, map->stripe_len);
5392 stripe_end_offset = stripe_nr_end * map->stripe_len -
5395 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5396 if (rw & REQ_DISCARD)
5397 num_stripes = min_t(u64, map->num_stripes,
5398 stripe_nr_end - stripe_nr_orig);
5399 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5401 if (!(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)))
5403 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5404 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
5405 num_stripes = map->num_stripes;
5406 else if (mirror_num)
5407 stripe_index = mirror_num - 1;
5409 stripe_index = find_live_mirror(fs_info, map, 0,
5411 current->pid % map->num_stripes,
5412 dev_replace_is_ongoing);
5413 mirror_num = stripe_index + 1;
5416 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5417 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
5418 num_stripes = map->num_stripes;
5419 } else if (mirror_num) {
5420 stripe_index = mirror_num - 1;
5425 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5426 u32 factor = map->num_stripes / map->sub_stripes;
5428 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5429 stripe_index *= map->sub_stripes;
5431 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5432 num_stripes = map->sub_stripes;
5433 else if (rw & REQ_DISCARD)
5434 num_stripes = min_t(u64, map->sub_stripes *
5435 (stripe_nr_end - stripe_nr_orig),
5437 else if (mirror_num)
5438 stripe_index += mirror_num - 1;
5440 int old_stripe_index = stripe_index;
5441 stripe_index = find_live_mirror(fs_info, map,
5443 map->sub_stripes, stripe_index +
5444 current->pid % map->sub_stripes,
5445 dev_replace_is_ongoing);
5446 mirror_num = stripe_index - old_stripe_index + 1;
5449 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5450 if (need_raid_map &&
5451 ((rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) ||
5453 /* push stripe_nr back to the start of the full stripe */
5454 stripe_nr = div_u64(raid56_full_stripe_start,
5455 stripe_len * nr_data_stripes(map));
5457 /* RAID[56] write or recovery. Return all stripes */
5458 num_stripes = map->num_stripes;
5459 max_errors = nr_parity_stripes(map);
5461 *length = map->stripe_len;
5466 * Mirror #0 or #1 means the original data block.
5467 * Mirror #2 is RAID5 parity block.
5468 * Mirror #3 is RAID6 Q block.
5470 stripe_nr = div_u64_rem(stripe_nr,
5471 nr_data_stripes(map), &stripe_index);
5473 stripe_index = nr_data_stripes(map) +
5476 /* We distribute the parity blocks across stripes */
5477 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5479 if (!(rw & (REQ_WRITE | REQ_DISCARD |
5480 REQ_GET_READ_MIRRORS)) && mirror_num <= 1)
5485 * after this, stripe_nr is the number of stripes on this
5486 * device we have to walk to find the data, and stripe_index is
5487 * the number of our device in the stripe array
5489 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5491 mirror_num = stripe_index + 1;
5493 BUG_ON(stripe_index >= map->num_stripes);
5495 num_alloc_stripes = num_stripes;
5496 if (dev_replace_is_ongoing) {
5497 if (rw & (REQ_WRITE | REQ_DISCARD))
5498 num_alloc_stripes <<= 1;
5499 if (rw & REQ_GET_READ_MIRRORS)
5500 num_alloc_stripes++;
5501 tgtdev_indexes = num_stripes;
5504 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5509 if (dev_replace_is_ongoing)
5510 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5512 /* build raid_map */
5513 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
5514 need_raid_map && ((rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) ||
5519 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5520 sizeof(struct btrfs_bio_stripe) *
5522 sizeof(int) * tgtdev_indexes);
5524 /* Work out the disk rotation on this stripe-set */
5525 div_u64_rem(stripe_nr, num_stripes, &rot);
5527 /* Fill in the logical address of each stripe */
5528 tmp = stripe_nr * nr_data_stripes(map);
5529 for (i = 0; i < nr_data_stripes(map); i++)
5530 bbio->raid_map[(i+rot) % num_stripes] =
5531 em->start + (tmp + i) * map->stripe_len;
5533 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5534 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5535 bbio->raid_map[(i+rot+1) % num_stripes] =
5539 if (rw & REQ_DISCARD) {
5541 u32 sub_stripes = 0;
5542 u64 stripes_per_dev = 0;
5543 u32 remaining_stripes = 0;
5544 u32 last_stripe = 0;
5547 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5548 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5551 sub_stripes = map->sub_stripes;
5553 factor = map->num_stripes / sub_stripes;
5554 stripes_per_dev = div_u64_rem(stripe_nr_end -
5557 &remaining_stripes);
5558 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5559 last_stripe *= sub_stripes;
5562 for (i = 0; i < num_stripes; i++) {
5563 bbio->stripes[i].physical =
5564 map->stripes[stripe_index].physical +
5565 stripe_offset + stripe_nr * map->stripe_len;
5566 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5568 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5569 BTRFS_BLOCK_GROUP_RAID10)) {
5570 bbio->stripes[i].length = stripes_per_dev *
5573 if (i / sub_stripes < remaining_stripes)
5574 bbio->stripes[i].length +=
5578 * Special for the first stripe and
5581 * |-------|...|-------|
5585 if (i < sub_stripes)
5586 bbio->stripes[i].length -=
5589 if (stripe_index >= last_stripe &&
5590 stripe_index <= (last_stripe +
5592 bbio->stripes[i].length -=
5595 if (i == sub_stripes - 1)
5598 bbio->stripes[i].length = *length;
5601 if (stripe_index == map->num_stripes) {
5602 /* This could only happen for RAID0/10 */
5608 for (i = 0; i < num_stripes; i++) {
5609 bbio->stripes[i].physical =
5610 map->stripes[stripe_index].physical +
5612 stripe_nr * map->stripe_len;
5613 bbio->stripes[i].dev =
5614 map->stripes[stripe_index].dev;
5619 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5620 max_errors = btrfs_chunk_max_errors(map);
5623 sort_parity_stripes(bbio, num_stripes);
5626 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5627 dev_replace->tgtdev != NULL) {
5628 int index_where_to_add;
5629 u64 srcdev_devid = dev_replace->srcdev->devid;
5632 * duplicate the write operations while the dev replace
5633 * procedure is running. Since the copying of the old disk
5634 * to the new disk takes place at run time while the
5635 * filesystem is mounted writable, the regular write
5636 * operations to the old disk have to be duplicated to go
5637 * to the new disk as well.
5638 * Note that device->missing is handled by the caller, and
5639 * that the write to the old disk is already set up in the
5642 index_where_to_add = num_stripes;
5643 for (i = 0; i < num_stripes; i++) {
5644 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5645 /* write to new disk, too */
5646 struct btrfs_bio_stripe *new =
5647 bbio->stripes + index_where_to_add;
5648 struct btrfs_bio_stripe *old =
5651 new->physical = old->physical;
5652 new->length = old->length;
5653 new->dev = dev_replace->tgtdev;
5654 bbio->tgtdev_map[i] = index_where_to_add;
5655 index_where_to_add++;
5660 num_stripes = index_where_to_add;
5661 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5662 dev_replace->tgtdev != NULL) {
5663 u64 srcdev_devid = dev_replace->srcdev->devid;
5664 int index_srcdev = 0;
5666 u64 physical_of_found = 0;
5669 * During the dev-replace procedure, the target drive can
5670 * also be used to read data in case it is needed to repair
5671 * a corrupt block elsewhere. This is possible if the
5672 * requested area is left of the left cursor. In this area,
5673 * the target drive is a full copy of the source drive.
5675 for (i = 0; i < num_stripes; i++) {
5676 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5678 * In case of DUP, in order to keep it
5679 * simple, only add the mirror with the
5680 * lowest physical address
5683 physical_of_found <=
5684 bbio->stripes[i].physical)
5688 physical_of_found = bbio->stripes[i].physical;
5692 if (physical_of_found + map->stripe_len <=
5693 dev_replace->cursor_left) {
5694 struct btrfs_bio_stripe *tgtdev_stripe =
5695 bbio->stripes + num_stripes;
5697 tgtdev_stripe->physical = physical_of_found;
5698 tgtdev_stripe->length =
5699 bbio->stripes[index_srcdev].length;
5700 tgtdev_stripe->dev = dev_replace->tgtdev;
5701 bbio->tgtdev_map[index_srcdev] = num_stripes;
5710 bbio->map_type = map->type;
5711 bbio->num_stripes = num_stripes;
5712 bbio->max_errors = max_errors;
5713 bbio->mirror_num = mirror_num;
5714 bbio->num_tgtdevs = tgtdev_indexes;
5717 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5718 * mirror_num == num_stripes + 1 && dev_replace target drive is
5719 * available as a mirror
5721 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5722 WARN_ON(num_stripes > 1);
5723 bbio->stripes[0].dev = dev_replace->tgtdev;
5724 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5725 bbio->mirror_num = map->num_stripes + 1;
5728 if (dev_replace_is_ongoing) {
5729 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5730 btrfs_dev_replace_unlock(dev_replace, 0);
5732 free_extent_map(em);
5736 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5737 u64 logical, u64 *length,
5738 struct btrfs_bio **bbio_ret, int mirror_num)
5740 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5744 /* For Scrub/replace */
5745 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, int rw,
5746 u64 logical, u64 *length,
5747 struct btrfs_bio **bbio_ret, int mirror_num,
5750 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5751 mirror_num, need_raid_map);
5754 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5755 u64 chunk_start, u64 physical, u64 devid,
5756 u64 **logical, int *naddrs, int *stripe_len)
5758 struct extent_map_tree *em_tree = &map_tree->map_tree;
5759 struct extent_map *em;
5760 struct map_lookup *map;
5768 read_lock(&em_tree->lock);
5769 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5770 read_unlock(&em_tree->lock);
5773 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5778 if (em->start != chunk_start) {
5779 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5780 em->start, chunk_start);
5781 free_extent_map(em);
5784 map = em->map_lookup;
5787 rmap_len = map->stripe_len;
5789 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5790 length = div_u64(length, map->num_stripes / map->sub_stripes);
5791 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5792 length = div_u64(length, map->num_stripes);
5793 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5794 length = div_u64(length, nr_data_stripes(map));
5795 rmap_len = map->stripe_len * nr_data_stripes(map);
5798 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5799 BUG_ON(!buf); /* -ENOMEM */
5801 for (i = 0; i < map->num_stripes; i++) {
5802 if (devid && map->stripes[i].dev->devid != devid)
5804 if (map->stripes[i].physical > physical ||
5805 map->stripes[i].physical + length <= physical)
5808 stripe_nr = physical - map->stripes[i].physical;
5809 stripe_nr = div_u64(stripe_nr, map->stripe_len);
5811 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5812 stripe_nr = stripe_nr * map->num_stripes + i;
5813 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5814 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5815 stripe_nr = stripe_nr * map->num_stripes + i;
5816 } /* else if RAID[56], multiply by nr_data_stripes().
5817 * Alternatively, just use rmap_len below instead of
5818 * map->stripe_len */
5820 bytenr = chunk_start + stripe_nr * rmap_len;
5821 WARN_ON(nr >= map->num_stripes);
5822 for (j = 0; j < nr; j++) {
5823 if (buf[j] == bytenr)
5827 WARN_ON(nr >= map->num_stripes);
5834 *stripe_len = rmap_len;
5836 free_extent_map(em);
5840 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
5842 bio->bi_private = bbio->private;
5843 bio->bi_end_io = bbio->end_io;
5846 btrfs_put_bbio(bbio);
5849 static void btrfs_end_bio(struct bio *bio)
5851 struct btrfs_bio *bbio = bio->bi_private;
5852 int is_orig_bio = 0;
5854 if (bio->bi_error) {
5855 atomic_inc(&bbio->error);
5856 if (bio->bi_error == -EIO || bio->bi_error == -EREMOTEIO) {
5857 unsigned int stripe_index =
5858 btrfs_io_bio(bio)->stripe_index;
5859 struct btrfs_device *dev;
5861 BUG_ON(stripe_index >= bbio->num_stripes);
5862 dev = bbio->stripes[stripe_index].dev;
5864 if (bio->bi_rw & WRITE)
5865 btrfs_dev_stat_inc(dev,
5866 BTRFS_DEV_STAT_WRITE_ERRS);
5868 btrfs_dev_stat_inc(dev,
5869 BTRFS_DEV_STAT_READ_ERRS);
5870 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5871 btrfs_dev_stat_inc(dev,
5872 BTRFS_DEV_STAT_FLUSH_ERRS);
5873 btrfs_dev_stat_print_on_error(dev);
5878 if (bio == bbio->orig_bio)
5881 btrfs_bio_counter_dec(bbio->fs_info);
5883 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5886 bio = bbio->orig_bio;
5889 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5890 /* only send an error to the higher layers if it is
5891 * beyond the tolerance of the btrfs bio
5893 if (atomic_read(&bbio->error) > bbio->max_errors) {
5894 bio->bi_error = -EIO;
5897 * this bio is actually up to date, we didn't
5898 * go over the max number of errors
5903 btrfs_end_bbio(bbio, bio);
5904 } else if (!is_orig_bio) {
5910 * see run_scheduled_bios for a description of why bios are collected for
5913 * This will add one bio to the pending list for a device and make sure
5914 * the work struct is scheduled.
5916 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5917 struct btrfs_device *device,
5918 int rw, struct bio *bio)
5920 int should_queue = 1;
5921 struct btrfs_pending_bios *pending_bios;
5923 if (device->missing || !device->bdev) {
5928 /* don't bother with additional async steps for reads, right now */
5929 if (!(rw & REQ_WRITE)) {
5931 btrfsic_submit_bio(rw, bio);
5937 * nr_async_bios allows us to reliably return congestion to the
5938 * higher layers. Otherwise, the async bio makes it appear we have
5939 * made progress against dirty pages when we've really just put it
5940 * on a queue for later
5942 atomic_inc(&root->fs_info->nr_async_bios);
5943 WARN_ON(bio->bi_next);
5944 bio->bi_next = NULL;
5947 spin_lock(&device->io_lock);
5948 if (bio->bi_rw & REQ_SYNC)
5949 pending_bios = &device->pending_sync_bios;
5951 pending_bios = &device->pending_bios;
5953 if (pending_bios->tail)
5954 pending_bios->tail->bi_next = bio;
5956 pending_bios->tail = bio;
5957 if (!pending_bios->head)
5958 pending_bios->head = bio;
5959 if (device->running_pending)
5962 spin_unlock(&device->io_lock);
5965 btrfs_queue_work(root->fs_info->submit_workers,
5969 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5970 struct bio *bio, u64 physical, int dev_nr,
5973 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5975 bio->bi_private = bbio;
5976 btrfs_io_bio(bio)->stripe_index = dev_nr;
5977 bio->bi_end_io = btrfs_end_bio;
5978 bio->bi_iter.bi_sector = physical >> 9;
5981 struct rcu_string *name;
5984 name = rcu_dereference(dev->name);
5985 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5986 "(%s id %llu), size=%u\n", rw,
5987 (u64)bio->bi_iter.bi_sector, (u_long)dev->bdev->bd_dev,
5988 name->str, dev->devid, bio->bi_iter.bi_size);
5992 bio->bi_bdev = dev->bdev;
5994 btrfs_bio_counter_inc_noblocked(root->fs_info);
5997 btrfs_schedule_bio(root, dev, rw, bio);
5999 btrfsic_submit_bio(rw, bio);
6002 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6004 atomic_inc(&bbio->error);
6005 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6006 /* Shoud be the original bio. */
6007 WARN_ON(bio != bbio->orig_bio);
6009 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6010 bio->bi_iter.bi_sector = logical >> 9;
6011 bio->bi_error = -EIO;
6012 btrfs_end_bbio(bbio, bio);
6016 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
6017 int mirror_num, int async_submit)
6019 struct btrfs_device *dev;
6020 struct bio *first_bio = bio;
6021 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6027 struct btrfs_bio *bbio = NULL;
6029 length = bio->bi_iter.bi_size;
6030 map_length = length;
6032 btrfs_bio_counter_inc_blocked(root->fs_info);
6033 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
6036 btrfs_bio_counter_dec(root->fs_info);
6040 total_devs = bbio->num_stripes;
6041 bbio->orig_bio = first_bio;
6042 bbio->private = first_bio->bi_private;
6043 bbio->end_io = first_bio->bi_end_io;
6044 bbio->fs_info = root->fs_info;
6045 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6047 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6048 ((rw & WRITE) || (mirror_num > 1))) {
6049 /* In this case, map_length has been set to the length of
6050 a single stripe; not the whole write */
6052 ret = raid56_parity_write(root, bio, bbio, map_length);
6054 ret = raid56_parity_recover(root, bio, bbio, map_length,
6058 btrfs_bio_counter_dec(root->fs_info);
6062 if (map_length < length) {
6063 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
6064 logical, length, map_length);
6068 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6069 dev = bbio->stripes[dev_nr].dev;
6070 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
6071 bbio_error(bbio, first_bio, logical);
6075 if (dev_nr < total_devs - 1) {
6076 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
6077 BUG_ON(!bio); /* -ENOMEM */
6081 submit_stripe_bio(root, bbio, bio,
6082 bbio->stripes[dev_nr].physical, dev_nr, rw,
6085 btrfs_bio_counter_dec(root->fs_info);
6089 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6092 struct btrfs_device *device;
6093 struct btrfs_fs_devices *cur_devices;
6095 cur_devices = fs_info->fs_devices;
6096 while (cur_devices) {
6098 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
6099 device = __find_device(&cur_devices->devices,
6104 cur_devices = cur_devices->seed;
6109 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
6110 struct btrfs_fs_devices *fs_devices,
6111 u64 devid, u8 *dev_uuid)
6113 struct btrfs_device *device;
6115 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6119 list_add(&device->dev_list, &fs_devices->devices);
6120 device->fs_devices = fs_devices;
6121 fs_devices->num_devices++;
6123 device->missing = 1;
6124 fs_devices->missing_devices++;
6130 * btrfs_alloc_device - allocate struct btrfs_device
6131 * @fs_info: used only for generating a new devid, can be NULL if
6132 * devid is provided (i.e. @devid != NULL).
6133 * @devid: a pointer to devid for this device. If NULL a new devid
6135 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6138 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6139 * on error. Returned struct is not linked onto any lists and can be
6140 * destroyed with kfree() right away.
6142 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6146 struct btrfs_device *dev;
6149 if (WARN_ON(!devid && !fs_info))
6150 return ERR_PTR(-EINVAL);
6152 dev = __alloc_device();
6161 ret = find_next_devid(fs_info, &tmp);
6164 return ERR_PTR(ret);
6170 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6172 generate_random_uuid(dev->uuid);
6174 btrfs_init_work(&dev->work, btrfs_submit_helper,
6175 pending_bios_fn, NULL, NULL);
6180 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
6181 struct extent_buffer *leaf,
6182 struct btrfs_chunk *chunk)
6184 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
6185 struct map_lookup *map;
6186 struct extent_map *em;
6191 u8 uuid[BTRFS_UUID_SIZE];
6196 logical = key->offset;
6197 length = btrfs_chunk_length(leaf, chunk);
6198 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6199 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6200 /* Validation check */
6202 btrfs_err(root->fs_info, "invalid chunk num_stripes: %u",
6206 if (!IS_ALIGNED(logical, root->sectorsize)) {
6207 btrfs_err(root->fs_info,
6208 "invalid chunk logical %llu", logical);
6211 if (!length || !IS_ALIGNED(length, root->sectorsize)) {
6212 btrfs_err(root->fs_info,
6213 "invalid chunk length %llu", length);
6216 if (!is_power_of_2(stripe_len)) {
6217 btrfs_err(root->fs_info, "invalid chunk stripe length: %llu",
6221 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6222 btrfs_chunk_type(leaf, chunk)) {
6223 btrfs_err(root->fs_info, "unrecognized chunk type: %llu",
6224 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6225 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6226 btrfs_chunk_type(leaf, chunk));
6230 read_lock(&map_tree->map_tree.lock);
6231 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6232 read_unlock(&map_tree->map_tree.lock);
6234 /* already mapped? */
6235 if (em && em->start <= logical && em->start + em->len > logical) {
6236 free_extent_map(em);
6239 free_extent_map(em);
6242 em = alloc_extent_map();
6245 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6247 free_extent_map(em);
6251 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6252 em->map_lookup = map;
6253 em->start = logical;
6256 em->block_start = 0;
6257 em->block_len = em->len;
6259 map->num_stripes = num_stripes;
6260 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6261 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6262 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
6263 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6264 map->type = btrfs_chunk_type(leaf, chunk);
6265 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6266 for (i = 0; i < num_stripes; i++) {
6267 map->stripes[i].physical =
6268 btrfs_stripe_offset_nr(leaf, chunk, i);
6269 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6270 read_extent_buffer(leaf, uuid, (unsigned long)
6271 btrfs_stripe_dev_uuid_nr(chunk, i),
6273 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
6275 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
6276 free_extent_map(em);
6279 if (!map->stripes[i].dev) {
6280 map->stripes[i].dev =
6281 add_missing_dev(root, root->fs_info->fs_devices,
6283 if (!map->stripes[i].dev) {
6284 free_extent_map(em);
6287 btrfs_warn(root->fs_info, "devid %llu uuid %pU is missing",
6290 map->stripes[i].dev->in_fs_metadata = 1;
6293 write_lock(&map_tree->map_tree.lock);
6294 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6295 write_unlock(&map_tree->map_tree.lock);
6296 BUG_ON(ret); /* Tree corruption */
6297 free_extent_map(em);
6302 static void fill_device_from_item(struct extent_buffer *leaf,
6303 struct btrfs_dev_item *dev_item,
6304 struct btrfs_device *device)
6308 device->devid = btrfs_device_id(leaf, dev_item);
6309 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6310 device->total_bytes = device->disk_total_bytes;
6311 device->commit_total_bytes = device->disk_total_bytes;
6312 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6313 device->commit_bytes_used = device->bytes_used;
6314 device->type = btrfs_device_type(leaf, dev_item);
6315 device->io_align = btrfs_device_io_align(leaf, dev_item);
6316 device->io_width = btrfs_device_io_width(leaf, dev_item);
6317 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6318 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6319 device->is_tgtdev_for_dev_replace = 0;
6321 ptr = btrfs_device_uuid(dev_item);
6322 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6325 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_root *root,
6328 struct btrfs_fs_devices *fs_devices;
6331 BUG_ON(!mutex_is_locked(&uuid_mutex));
6333 fs_devices = root->fs_info->fs_devices->seed;
6334 while (fs_devices) {
6335 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE))
6338 fs_devices = fs_devices->seed;
6341 fs_devices = find_fsid(fsid);
6343 if (!btrfs_test_opt(root, DEGRADED))
6344 return ERR_PTR(-ENOENT);
6346 fs_devices = alloc_fs_devices(fsid);
6347 if (IS_ERR(fs_devices))
6350 fs_devices->seeding = 1;
6351 fs_devices->opened = 1;
6355 fs_devices = clone_fs_devices(fs_devices);
6356 if (IS_ERR(fs_devices))
6359 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6360 root->fs_info->bdev_holder);
6362 free_fs_devices(fs_devices);
6363 fs_devices = ERR_PTR(ret);
6367 if (!fs_devices->seeding) {
6368 __btrfs_close_devices(fs_devices);
6369 free_fs_devices(fs_devices);
6370 fs_devices = ERR_PTR(-EINVAL);
6374 fs_devices->seed = root->fs_info->fs_devices->seed;
6375 root->fs_info->fs_devices->seed = fs_devices;
6380 static int read_one_dev(struct btrfs_root *root,
6381 struct extent_buffer *leaf,
6382 struct btrfs_dev_item *dev_item)
6384 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6385 struct btrfs_device *device;
6388 u8 fs_uuid[BTRFS_UUID_SIZE];
6389 u8 dev_uuid[BTRFS_UUID_SIZE];
6391 devid = btrfs_device_id(leaf, dev_item);
6392 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6394 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6397 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
6398 fs_devices = open_seed_devices(root, fs_uuid);
6399 if (IS_ERR(fs_devices))
6400 return PTR_ERR(fs_devices);
6403 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
6405 if (!btrfs_test_opt(root, DEGRADED))
6408 device = add_missing_dev(root, fs_devices, devid, dev_uuid);
6411 btrfs_warn(root->fs_info, "devid %llu uuid %pU missing",
6414 if (!device->bdev && !btrfs_test_opt(root, DEGRADED))
6417 if(!device->bdev && !device->missing) {
6419 * this happens when a device that was properly setup
6420 * in the device info lists suddenly goes bad.
6421 * device->bdev is NULL, and so we have to set
6422 * device->missing to one here
6424 device->fs_devices->missing_devices++;
6425 device->missing = 1;
6428 /* Move the device to its own fs_devices */
6429 if (device->fs_devices != fs_devices) {
6430 ASSERT(device->missing);
6432 list_move(&device->dev_list, &fs_devices->devices);
6433 device->fs_devices->num_devices--;
6434 fs_devices->num_devices++;
6436 device->fs_devices->missing_devices--;
6437 fs_devices->missing_devices++;
6439 device->fs_devices = fs_devices;
6443 if (device->fs_devices != root->fs_info->fs_devices) {
6444 BUG_ON(device->writeable);
6445 if (device->generation !=
6446 btrfs_device_generation(leaf, dev_item))
6450 fill_device_from_item(leaf, dev_item, device);
6451 device->in_fs_metadata = 1;
6452 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6453 device->fs_devices->total_rw_bytes += device->total_bytes;
6454 spin_lock(&root->fs_info->free_chunk_lock);
6455 root->fs_info->free_chunk_space += device->total_bytes -
6457 spin_unlock(&root->fs_info->free_chunk_lock);
6463 int btrfs_read_sys_array(struct btrfs_root *root)
6465 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
6466 struct extent_buffer *sb;
6467 struct btrfs_disk_key *disk_key;
6468 struct btrfs_chunk *chunk;
6470 unsigned long sb_array_offset;
6476 struct btrfs_key key;
6478 ASSERT(BTRFS_SUPER_INFO_SIZE <= root->nodesize);
6480 * This will create extent buffer of nodesize, superblock size is
6481 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6482 * overallocate but we can keep it as-is, only the first page is used.
6484 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET);
6487 set_extent_buffer_uptodate(sb);
6488 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6490 * The sb extent buffer is artifical and just used to read the system array.
6491 * set_extent_buffer_uptodate() call does not properly mark all it's
6492 * pages up-to-date when the page is larger: extent does not cover the
6493 * whole page and consequently check_page_uptodate does not find all
6494 * the page's extents up-to-date (the hole beyond sb),
6495 * write_extent_buffer then triggers a WARN_ON.
6497 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6498 * but sb spans only this function. Add an explicit SetPageUptodate call
6499 * to silence the warning eg. on PowerPC 64.
6501 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6502 SetPageUptodate(sb->pages[0]);
6504 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6505 array_size = btrfs_super_sys_array_size(super_copy);
6507 array_ptr = super_copy->sys_chunk_array;
6508 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6511 while (cur_offset < array_size) {
6512 disk_key = (struct btrfs_disk_key *)array_ptr;
6513 len = sizeof(*disk_key);
6514 if (cur_offset + len > array_size)
6515 goto out_short_read;
6517 btrfs_disk_key_to_cpu(&key, disk_key);
6520 sb_array_offset += len;
6523 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6524 chunk = (struct btrfs_chunk *)sb_array_offset;
6526 * At least one btrfs_chunk with one stripe must be
6527 * present, exact stripe count check comes afterwards
6529 len = btrfs_chunk_item_size(1);
6530 if (cur_offset + len > array_size)
6531 goto out_short_read;
6533 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6536 "BTRFS: invalid number of stripes %u in sys_array at offset %u\n",
6537 num_stripes, cur_offset);
6542 len = btrfs_chunk_item_size(num_stripes);
6543 if (cur_offset + len > array_size)
6544 goto out_short_read;
6546 ret = read_one_chunk(root, &key, sb, chunk);
6551 "BTRFS: unexpected item type %u in sys_array at offset %u\n",
6552 (u32)key.type, cur_offset);
6557 sb_array_offset += len;
6560 free_extent_buffer(sb);
6564 printk(KERN_ERR "BTRFS: sys_array too short to read %u bytes at offset %u\n",
6566 free_extent_buffer(sb);
6570 int btrfs_read_chunk_tree(struct btrfs_root *root)
6572 struct btrfs_path *path;
6573 struct extent_buffer *leaf;
6574 struct btrfs_key key;
6575 struct btrfs_key found_key;
6579 root = root->fs_info->chunk_root;
6581 path = btrfs_alloc_path();
6585 mutex_lock(&uuid_mutex);
6589 * Read all device items, and then all the chunk items. All
6590 * device items are found before any chunk item (their object id
6591 * is smaller than the lowest possible object id for a chunk
6592 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6594 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6597 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6601 leaf = path->nodes[0];
6602 slot = path->slots[0];
6603 if (slot >= btrfs_header_nritems(leaf)) {
6604 ret = btrfs_next_leaf(root, path);
6611 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6612 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6613 struct btrfs_dev_item *dev_item;
6614 dev_item = btrfs_item_ptr(leaf, slot,
6615 struct btrfs_dev_item);
6616 ret = read_one_dev(root, leaf, dev_item);
6619 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6620 struct btrfs_chunk *chunk;
6621 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6622 ret = read_one_chunk(root, &found_key, leaf, chunk);
6630 unlock_chunks(root);
6631 mutex_unlock(&uuid_mutex);
6633 btrfs_free_path(path);
6637 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6639 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6640 struct btrfs_device *device;
6642 while (fs_devices) {
6643 mutex_lock(&fs_devices->device_list_mutex);
6644 list_for_each_entry(device, &fs_devices->devices, dev_list)
6645 device->dev_root = fs_info->dev_root;
6646 mutex_unlock(&fs_devices->device_list_mutex);
6648 fs_devices = fs_devices->seed;
6652 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6656 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6657 btrfs_dev_stat_reset(dev, i);
6660 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6662 struct btrfs_key key;
6663 struct btrfs_key found_key;
6664 struct btrfs_root *dev_root = fs_info->dev_root;
6665 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6666 struct extent_buffer *eb;
6669 struct btrfs_device *device;
6670 struct btrfs_path *path = NULL;
6673 path = btrfs_alloc_path();
6679 mutex_lock(&fs_devices->device_list_mutex);
6680 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6682 struct btrfs_dev_stats_item *ptr;
6684 key.objectid = BTRFS_DEV_STATS_OBJECTID;
6685 key.type = BTRFS_PERSISTENT_ITEM_KEY;
6686 key.offset = device->devid;
6687 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6689 __btrfs_reset_dev_stats(device);
6690 device->dev_stats_valid = 1;
6691 btrfs_release_path(path);
6694 slot = path->slots[0];
6695 eb = path->nodes[0];
6696 btrfs_item_key_to_cpu(eb, &found_key, slot);
6697 item_size = btrfs_item_size_nr(eb, slot);
6699 ptr = btrfs_item_ptr(eb, slot,
6700 struct btrfs_dev_stats_item);
6702 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6703 if (item_size >= (1 + i) * sizeof(__le64))
6704 btrfs_dev_stat_set(device, i,
6705 btrfs_dev_stats_value(eb, ptr, i));
6707 btrfs_dev_stat_reset(device, i);
6710 device->dev_stats_valid = 1;
6711 btrfs_dev_stat_print_on_load(device);
6712 btrfs_release_path(path);
6714 mutex_unlock(&fs_devices->device_list_mutex);
6717 btrfs_free_path(path);
6718 return ret < 0 ? ret : 0;
6721 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6722 struct btrfs_root *dev_root,
6723 struct btrfs_device *device)
6725 struct btrfs_path *path;
6726 struct btrfs_key key;
6727 struct extent_buffer *eb;
6728 struct btrfs_dev_stats_item *ptr;
6732 key.objectid = BTRFS_DEV_STATS_OBJECTID;
6733 key.type = BTRFS_PERSISTENT_ITEM_KEY;
6734 key.offset = device->devid;
6736 path = btrfs_alloc_path();
6738 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6740 btrfs_warn_in_rcu(dev_root->fs_info,
6741 "error %d while searching for dev_stats item for device %s",
6742 ret, rcu_str_deref(device->name));
6747 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6748 /* need to delete old one and insert a new one */
6749 ret = btrfs_del_item(trans, dev_root, path);
6751 btrfs_warn_in_rcu(dev_root->fs_info,
6752 "delete too small dev_stats item for device %s failed %d",
6753 rcu_str_deref(device->name), ret);
6760 /* need to insert a new item */
6761 btrfs_release_path(path);
6762 ret = btrfs_insert_empty_item(trans, dev_root, path,
6763 &key, sizeof(*ptr));
6765 btrfs_warn_in_rcu(dev_root->fs_info,
6766 "insert dev_stats item for device %s failed %d",
6767 rcu_str_deref(device->name), ret);
6772 eb = path->nodes[0];
6773 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6774 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6775 btrfs_set_dev_stats_value(eb, ptr, i,
6776 btrfs_dev_stat_read(device, i));
6777 btrfs_mark_buffer_dirty(eb);
6780 btrfs_free_path(path);
6785 * called from commit_transaction. Writes all changed device stats to disk.
6787 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6788 struct btrfs_fs_info *fs_info)
6790 struct btrfs_root *dev_root = fs_info->dev_root;
6791 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6792 struct btrfs_device *device;
6796 mutex_lock(&fs_devices->device_list_mutex);
6797 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6798 if (!device->dev_stats_valid || !btrfs_dev_stats_dirty(device))
6801 stats_cnt = atomic_read(&device->dev_stats_ccnt);
6802 ret = update_dev_stat_item(trans, dev_root, device);
6804 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
6806 mutex_unlock(&fs_devices->device_list_mutex);
6811 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6813 btrfs_dev_stat_inc(dev, index);
6814 btrfs_dev_stat_print_on_error(dev);
6817 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6819 if (!dev->dev_stats_valid)
6821 btrfs_err_rl_in_rcu(dev->dev_root->fs_info,
6822 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
6823 rcu_str_deref(dev->name),
6824 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6825 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6826 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6827 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6828 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6831 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6835 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6836 if (btrfs_dev_stat_read(dev, i) != 0)
6838 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6839 return; /* all values == 0, suppress message */
6841 btrfs_info_in_rcu(dev->dev_root->fs_info,
6842 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
6843 rcu_str_deref(dev->name),
6844 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6845 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6846 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6847 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6848 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6851 int btrfs_get_dev_stats(struct btrfs_root *root,
6852 struct btrfs_ioctl_get_dev_stats *stats)
6854 struct btrfs_device *dev;
6855 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6858 mutex_lock(&fs_devices->device_list_mutex);
6859 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6860 mutex_unlock(&fs_devices->device_list_mutex);
6863 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6865 } else if (!dev->dev_stats_valid) {
6866 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6868 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6869 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6870 if (stats->nr_items > i)
6872 btrfs_dev_stat_read_and_reset(dev, i);
6874 btrfs_dev_stat_reset(dev, i);
6877 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6878 if (stats->nr_items > i)
6879 stats->values[i] = btrfs_dev_stat_read(dev, i);
6881 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6882 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6886 void btrfs_scratch_superblocks(struct block_device *bdev, char *device_path)
6888 struct buffer_head *bh;
6889 struct btrfs_super_block *disk_super;
6895 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
6898 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
6901 disk_super = (struct btrfs_super_block *)bh->b_data;
6903 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6904 set_buffer_dirty(bh);
6905 sync_dirty_buffer(bh);
6909 /* Notify udev that device has changed */
6910 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
6912 /* Update ctime/mtime for device path for libblkid */
6913 update_dev_time(device_path);
6917 * Update the size of all devices, which is used for writing out the
6920 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
6922 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6923 struct btrfs_device *curr, *next;
6925 if (list_empty(&fs_devices->resized_devices))
6928 mutex_lock(&fs_devices->device_list_mutex);
6929 lock_chunks(fs_info->dev_root);
6930 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
6932 list_del_init(&curr->resized_list);
6933 curr->commit_total_bytes = curr->disk_total_bytes;
6935 unlock_chunks(fs_info->dev_root);
6936 mutex_unlock(&fs_devices->device_list_mutex);
6939 /* Must be invoked during the transaction commit */
6940 void btrfs_update_commit_device_bytes_used(struct btrfs_root *root,
6941 struct btrfs_transaction *transaction)
6943 struct extent_map *em;
6944 struct map_lookup *map;
6945 struct btrfs_device *dev;
6948 if (list_empty(&transaction->pending_chunks))
6951 /* In order to kick the device replace finish process */
6953 list_for_each_entry(em, &transaction->pending_chunks, list) {
6954 map = em->map_lookup;
6956 for (i = 0; i < map->num_stripes; i++) {
6957 dev = map->stripes[i].dev;
6958 dev->commit_bytes_used = dev->bytes_used;
6961 unlock_chunks(root);
6964 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
6966 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6967 while (fs_devices) {
6968 fs_devices->fs_info = fs_info;
6969 fs_devices = fs_devices->seed;
6973 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
6975 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6976 while (fs_devices) {
6977 fs_devices->fs_info = NULL;
6978 fs_devices = fs_devices->seed;
6982 static void btrfs_close_one_device(struct btrfs_device *device)
6984 struct btrfs_fs_devices *fs_devices = device->fs_devices;
6985 struct btrfs_device *new_device;
6986 struct rcu_string *name;
6989 fs_devices->open_devices--;
6991 if (device->writeable &&
6992 device->devid != BTRFS_DEV_REPLACE_DEVID) {
6993 list_del_init(&device->dev_alloc_list);
6994 fs_devices->rw_devices--;
6997 if (device->missing)
6998 fs_devices->missing_devices--;
7000 new_device = btrfs_alloc_device(NULL, &device->devid,
7002 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
7004 /* Safe because we are under uuid_mutex */
7006 name = rcu_string_strdup(device->name->str, GFP_NOFS);
7007 BUG_ON(!name); /* -ENOMEM */
7008 rcu_assign_pointer(new_device->name, name);
7011 list_replace_rcu(&device->dev_list, &new_device->dev_list);
7012 new_device->fs_devices = device->fs_devices;
7014 call_rcu(&device->rcu, free_device);