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"
44 static int init_first_rw_device(struct btrfs_trans_handle *trans,
45 struct btrfs_root *root,
46 struct btrfs_device *device);
47 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
48 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
49 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
50 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
52 static DEFINE_MUTEX(uuid_mutex);
53 static LIST_HEAD(fs_uuids);
55 static void lock_chunks(struct btrfs_root *root)
57 mutex_lock(&root->fs_info->chunk_mutex);
60 static void unlock_chunks(struct btrfs_root *root)
62 mutex_unlock(&root->fs_info->chunk_mutex);
65 static struct btrfs_fs_devices *__alloc_fs_devices(void)
67 struct btrfs_fs_devices *fs_devs;
69 fs_devs = kzalloc(sizeof(*fs_devs), GFP_NOFS);
71 return ERR_PTR(-ENOMEM);
73 mutex_init(&fs_devs->device_list_mutex);
75 INIT_LIST_HEAD(&fs_devs->devices);
76 INIT_LIST_HEAD(&fs_devs->alloc_list);
77 INIT_LIST_HEAD(&fs_devs->list);
83 * alloc_fs_devices - allocate struct btrfs_fs_devices
84 * @fsid: a pointer to UUID for this FS. If NULL a new UUID is
87 * Return: a pointer to a new &struct btrfs_fs_devices on success;
88 * ERR_PTR() on error. Returned struct is not linked onto any lists and
89 * can be destroyed with kfree() right away.
91 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
93 struct btrfs_fs_devices *fs_devs;
95 fs_devs = __alloc_fs_devices();
100 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
102 generate_random_uuid(fs_devs->fsid);
107 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
109 struct btrfs_device *device;
110 WARN_ON(fs_devices->opened);
111 while (!list_empty(&fs_devices->devices)) {
112 device = list_entry(fs_devices->devices.next,
113 struct btrfs_device, dev_list);
114 list_del(&device->dev_list);
115 rcu_string_free(device->name);
121 static void btrfs_kobject_uevent(struct block_device *bdev,
122 enum kobject_action action)
126 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
128 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
130 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
131 &disk_to_dev(bdev->bd_disk)->kobj);
134 void btrfs_cleanup_fs_uuids(void)
136 struct btrfs_fs_devices *fs_devices;
138 while (!list_empty(&fs_uuids)) {
139 fs_devices = list_entry(fs_uuids.next,
140 struct btrfs_fs_devices, list);
141 list_del(&fs_devices->list);
142 free_fs_devices(fs_devices);
146 static struct btrfs_device *__alloc_device(void)
148 struct btrfs_device *dev;
150 dev = kzalloc(sizeof(*dev), GFP_NOFS);
152 return ERR_PTR(-ENOMEM);
154 INIT_LIST_HEAD(&dev->dev_list);
155 INIT_LIST_HEAD(&dev->dev_alloc_list);
157 spin_lock_init(&dev->io_lock);
159 spin_lock_init(&dev->reada_lock);
160 atomic_set(&dev->reada_in_flight, 0);
161 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_WAIT);
162 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_WAIT);
167 static noinline struct btrfs_device *__find_device(struct list_head *head,
170 struct btrfs_device *dev;
172 list_for_each_entry(dev, head, dev_list) {
173 if (dev->devid == devid &&
174 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
181 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
183 struct btrfs_fs_devices *fs_devices;
185 list_for_each_entry(fs_devices, &fs_uuids, list) {
186 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
193 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
194 int flush, struct block_device **bdev,
195 struct buffer_head **bh)
199 *bdev = blkdev_get_by_path(device_path, flags, holder);
202 ret = PTR_ERR(*bdev);
203 printk(KERN_INFO "BTRFS: open %s failed\n", device_path);
208 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
209 ret = set_blocksize(*bdev, 4096);
211 blkdev_put(*bdev, flags);
214 invalidate_bdev(*bdev);
215 *bh = btrfs_read_dev_super(*bdev);
218 blkdev_put(*bdev, flags);
230 static void requeue_list(struct btrfs_pending_bios *pending_bios,
231 struct bio *head, struct bio *tail)
234 struct bio *old_head;
236 old_head = pending_bios->head;
237 pending_bios->head = head;
238 if (pending_bios->tail)
239 tail->bi_next = old_head;
241 pending_bios->tail = tail;
245 * we try to collect pending bios for a device so we don't get a large
246 * number of procs sending bios down to the same device. This greatly
247 * improves the schedulers ability to collect and merge the bios.
249 * But, it also turns into a long list of bios to process and that is sure
250 * to eventually make the worker thread block. The solution here is to
251 * make some progress and then put this work struct back at the end of
252 * the list if the block device is congested. This way, multiple devices
253 * can make progress from a single worker thread.
255 static noinline void run_scheduled_bios(struct btrfs_device *device)
258 struct backing_dev_info *bdi;
259 struct btrfs_fs_info *fs_info;
260 struct btrfs_pending_bios *pending_bios;
264 unsigned long num_run;
265 unsigned long batch_run = 0;
267 unsigned long last_waited = 0;
269 int sync_pending = 0;
270 struct blk_plug plug;
273 * this function runs all the bios we've collected for
274 * a particular device. We don't want to wander off to
275 * another device without first sending all of these down.
276 * So, setup a plug here and finish it off before we return
278 blk_start_plug(&plug);
280 bdi = blk_get_backing_dev_info(device->bdev);
281 fs_info = device->dev_root->fs_info;
282 limit = btrfs_async_submit_limit(fs_info);
283 limit = limit * 2 / 3;
286 spin_lock(&device->io_lock);
291 /* take all the bios off the list at once and process them
292 * later on (without the lock held). But, remember the
293 * tail and other pointers so the bios can be properly reinserted
294 * into the list if we hit congestion
296 if (!force_reg && device->pending_sync_bios.head) {
297 pending_bios = &device->pending_sync_bios;
300 pending_bios = &device->pending_bios;
304 pending = pending_bios->head;
305 tail = pending_bios->tail;
306 WARN_ON(pending && !tail);
309 * if pending was null this time around, no bios need processing
310 * at all and we can stop. Otherwise it'll loop back up again
311 * and do an additional check so no bios are missed.
313 * device->running_pending is used to synchronize with the
316 if (device->pending_sync_bios.head == NULL &&
317 device->pending_bios.head == NULL) {
319 device->running_pending = 0;
322 device->running_pending = 1;
325 pending_bios->head = NULL;
326 pending_bios->tail = NULL;
328 spin_unlock(&device->io_lock);
333 /* we want to work on both lists, but do more bios on the
334 * sync list than the regular list
337 pending_bios != &device->pending_sync_bios &&
338 device->pending_sync_bios.head) ||
339 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
340 device->pending_bios.head)) {
341 spin_lock(&device->io_lock);
342 requeue_list(pending_bios, pending, tail);
347 pending = pending->bi_next;
350 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
351 waitqueue_active(&fs_info->async_submit_wait))
352 wake_up(&fs_info->async_submit_wait);
354 BUG_ON(atomic_read(&cur->bi_cnt) == 0);
357 * if we're doing the sync list, record that our
358 * plug has some sync requests on it
360 * If we're doing the regular list and there are
361 * sync requests sitting around, unplug before
364 if (pending_bios == &device->pending_sync_bios) {
366 } else if (sync_pending) {
367 blk_finish_plug(&plug);
368 blk_start_plug(&plug);
372 btrfsic_submit_bio(cur->bi_rw, cur);
379 * we made progress, there is more work to do and the bdi
380 * is now congested. Back off and let other work structs
383 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
384 fs_info->fs_devices->open_devices > 1) {
385 struct io_context *ioc;
387 ioc = current->io_context;
390 * the main goal here is that we don't want to
391 * block if we're going to be able to submit
392 * more requests without blocking.
394 * This code does two great things, it pokes into
395 * the elevator code from a filesystem _and_
396 * it makes assumptions about how batching works.
398 if (ioc && ioc->nr_batch_requests > 0 &&
399 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
401 ioc->last_waited == last_waited)) {
403 * we want to go through our batch of
404 * requests and stop. So, we copy out
405 * the ioc->last_waited time and test
406 * against it before looping
408 last_waited = ioc->last_waited;
413 spin_lock(&device->io_lock);
414 requeue_list(pending_bios, pending, tail);
415 device->running_pending = 1;
417 spin_unlock(&device->io_lock);
418 btrfs_requeue_work(&device->work);
421 /* unplug every 64 requests just for good measure */
422 if (batch_run % 64 == 0) {
423 blk_finish_plug(&plug);
424 blk_start_plug(&plug);
433 spin_lock(&device->io_lock);
434 if (device->pending_bios.head || device->pending_sync_bios.head)
436 spin_unlock(&device->io_lock);
439 blk_finish_plug(&plug);
442 static void pending_bios_fn(struct btrfs_work *work)
444 struct btrfs_device *device;
446 device = container_of(work, struct btrfs_device, work);
447 run_scheduled_bios(device);
450 static noinline int device_list_add(const char *path,
451 struct btrfs_super_block *disk_super,
452 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
454 struct btrfs_device *device;
455 struct btrfs_fs_devices *fs_devices;
456 struct rcu_string *name;
457 u64 found_transid = btrfs_super_generation(disk_super);
459 fs_devices = find_fsid(disk_super->fsid);
461 fs_devices = alloc_fs_devices(disk_super->fsid);
462 if (IS_ERR(fs_devices))
463 return PTR_ERR(fs_devices);
465 list_add(&fs_devices->list, &fs_uuids);
466 fs_devices->latest_devid = devid;
467 fs_devices->latest_trans = found_transid;
471 device = __find_device(&fs_devices->devices, devid,
472 disk_super->dev_item.uuid);
475 if (fs_devices->opened)
478 device = btrfs_alloc_device(NULL, &devid,
479 disk_super->dev_item.uuid);
480 if (IS_ERR(device)) {
481 /* we can safely leave the fs_devices entry around */
482 return PTR_ERR(device);
485 name = rcu_string_strdup(path, GFP_NOFS);
490 rcu_assign_pointer(device->name, name);
492 mutex_lock(&fs_devices->device_list_mutex);
493 list_add_rcu(&device->dev_list, &fs_devices->devices);
494 fs_devices->num_devices++;
495 mutex_unlock(&fs_devices->device_list_mutex);
497 device->fs_devices = fs_devices;
498 } else if (!device->name || strcmp(device->name->str, path)) {
499 name = rcu_string_strdup(path, GFP_NOFS);
502 rcu_string_free(device->name);
503 rcu_assign_pointer(device->name, name);
504 if (device->missing) {
505 fs_devices->missing_devices--;
510 if (found_transid > fs_devices->latest_trans) {
511 fs_devices->latest_devid = devid;
512 fs_devices->latest_trans = found_transid;
514 *fs_devices_ret = fs_devices;
518 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
520 struct btrfs_fs_devices *fs_devices;
521 struct btrfs_device *device;
522 struct btrfs_device *orig_dev;
524 fs_devices = alloc_fs_devices(orig->fsid);
525 if (IS_ERR(fs_devices))
528 fs_devices->latest_devid = orig->latest_devid;
529 fs_devices->latest_trans = orig->latest_trans;
530 fs_devices->total_devices = orig->total_devices;
532 /* We have held the volume lock, it is safe to get the devices. */
533 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
534 struct rcu_string *name;
536 device = btrfs_alloc_device(NULL, &orig_dev->devid,
542 * This is ok to do without rcu read locked because we hold the
543 * uuid mutex so nothing we touch in here is going to disappear.
545 name = rcu_string_strdup(orig_dev->name->str, GFP_NOFS);
550 rcu_assign_pointer(device->name, name);
552 list_add(&device->dev_list, &fs_devices->devices);
553 device->fs_devices = fs_devices;
554 fs_devices->num_devices++;
558 free_fs_devices(fs_devices);
559 return ERR_PTR(-ENOMEM);
562 void btrfs_close_extra_devices(struct btrfs_fs_info *fs_info,
563 struct btrfs_fs_devices *fs_devices, int step)
565 struct btrfs_device *device, *next;
567 struct block_device *latest_bdev = NULL;
568 u64 latest_devid = 0;
569 u64 latest_transid = 0;
571 mutex_lock(&uuid_mutex);
573 /* This is the initialized path, it is safe to release the devices. */
574 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
575 if (device->in_fs_metadata) {
576 if (!device->is_tgtdev_for_dev_replace &&
578 device->generation > latest_transid)) {
579 latest_devid = device->devid;
580 latest_transid = device->generation;
581 latest_bdev = device->bdev;
586 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
588 * In the first step, keep the device which has
589 * the correct fsid and the devid that is used
590 * for the dev_replace procedure.
591 * In the second step, the dev_replace state is
592 * read from the device tree and it is known
593 * whether the procedure is really active or
594 * not, which means whether this device is
595 * used or whether it should be removed.
597 if (step == 0 || device->is_tgtdev_for_dev_replace) {
602 blkdev_put(device->bdev, device->mode);
604 fs_devices->open_devices--;
606 if (device->writeable) {
607 list_del_init(&device->dev_alloc_list);
608 device->writeable = 0;
609 if (!device->is_tgtdev_for_dev_replace)
610 fs_devices->rw_devices--;
612 list_del_init(&device->dev_list);
613 fs_devices->num_devices--;
614 rcu_string_free(device->name);
618 if (fs_devices->seed) {
619 fs_devices = fs_devices->seed;
623 fs_devices->latest_bdev = latest_bdev;
624 fs_devices->latest_devid = latest_devid;
625 fs_devices->latest_trans = latest_transid;
627 mutex_unlock(&uuid_mutex);
630 static void __free_device(struct work_struct *work)
632 struct btrfs_device *device;
634 device = container_of(work, struct btrfs_device, rcu_work);
637 blkdev_put(device->bdev, device->mode);
639 rcu_string_free(device->name);
643 static void free_device(struct rcu_head *head)
645 struct btrfs_device *device;
647 device = container_of(head, struct btrfs_device, rcu);
649 INIT_WORK(&device->rcu_work, __free_device);
650 schedule_work(&device->rcu_work);
653 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
655 struct btrfs_device *device;
657 if (--fs_devices->opened > 0)
660 mutex_lock(&fs_devices->device_list_mutex);
661 list_for_each_entry(device, &fs_devices->devices, dev_list) {
662 struct btrfs_device *new_device;
663 struct rcu_string *name;
666 fs_devices->open_devices--;
668 if (device->writeable &&
669 device->devid != BTRFS_DEV_REPLACE_DEVID) {
670 list_del_init(&device->dev_alloc_list);
671 fs_devices->rw_devices--;
674 if (device->can_discard)
675 fs_devices->num_can_discard--;
677 fs_devices->missing_devices--;
679 new_device = btrfs_alloc_device(NULL, &device->devid,
681 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
683 /* Safe because we are under uuid_mutex */
685 name = rcu_string_strdup(device->name->str, GFP_NOFS);
686 BUG_ON(!name); /* -ENOMEM */
687 rcu_assign_pointer(new_device->name, name);
690 list_replace_rcu(&device->dev_list, &new_device->dev_list);
691 new_device->fs_devices = device->fs_devices;
693 call_rcu(&device->rcu, free_device);
695 mutex_unlock(&fs_devices->device_list_mutex);
697 WARN_ON(fs_devices->open_devices);
698 WARN_ON(fs_devices->rw_devices);
699 fs_devices->opened = 0;
700 fs_devices->seeding = 0;
705 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
707 struct btrfs_fs_devices *seed_devices = NULL;
710 mutex_lock(&uuid_mutex);
711 ret = __btrfs_close_devices(fs_devices);
712 if (!fs_devices->opened) {
713 seed_devices = fs_devices->seed;
714 fs_devices->seed = NULL;
716 mutex_unlock(&uuid_mutex);
718 while (seed_devices) {
719 fs_devices = seed_devices;
720 seed_devices = fs_devices->seed;
721 __btrfs_close_devices(fs_devices);
722 free_fs_devices(fs_devices);
725 * Wait for rcu kworkers under __btrfs_close_devices
726 * to finish all blkdev_puts so device is really
727 * free when umount is done.
733 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
734 fmode_t flags, void *holder)
736 struct request_queue *q;
737 struct block_device *bdev;
738 struct list_head *head = &fs_devices->devices;
739 struct btrfs_device *device;
740 struct block_device *latest_bdev = NULL;
741 struct buffer_head *bh;
742 struct btrfs_super_block *disk_super;
743 u64 latest_devid = 0;
744 u64 latest_transid = 0;
751 list_for_each_entry(device, head, dev_list) {
757 /* Just open everything we can; ignore failures here */
758 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
762 disk_super = (struct btrfs_super_block *)bh->b_data;
763 devid = btrfs_stack_device_id(&disk_super->dev_item);
764 if (devid != device->devid)
767 if (memcmp(device->uuid, disk_super->dev_item.uuid,
771 device->generation = btrfs_super_generation(disk_super);
772 if (!latest_transid || device->generation > latest_transid) {
773 latest_devid = devid;
774 latest_transid = device->generation;
778 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
779 device->writeable = 0;
781 device->writeable = !bdev_read_only(bdev);
785 q = bdev_get_queue(bdev);
786 if (blk_queue_discard(q)) {
787 device->can_discard = 1;
788 fs_devices->num_can_discard++;
792 device->in_fs_metadata = 0;
793 device->mode = flags;
795 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
796 fs_devices->rotating = 1;
798 fs_devices->open_devices++;
799 if (device->writeable &&
800 device->devid != BTRFS_DEV_REPLACE_DEVID) {
801 fs_devices->rw_devices++;
802 list_add(&device->dev_alloc_list,
803 &fs_devices->alloc_list);
810 blkdev_put(bdev, flags);
813 if (fs_devices->open_devices == 0) {
817 fs_devices->seeding = seeding;
818 fs_devices->opened = 1;
819 fs_devices->latest_bdev = latest_bdev;
820 fs_devices->latest_devid = latest_devid;
821 fs_devices->latest_trans = latest_transid;
822 fs_devices->total_rw_bytes = 0;
827 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
828 fmode_t flags, void *holder)
832 mutex_lock(&uuid_mutex);
833 if (fs_devices->opened) {
834 fs_devices->opened++;
837 ret = __btrfs_open_devices(fs_devices, flags, holder);
839 mutex_unlock(&uuid_mutex);
844 * Look for a btrfs signature on a device. This may be called out of the mount path
845 * and we are not allowed to call set_blocksize during the scan. The superblock
846 * is read via pagecache
848 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
849 struct btrfs_fs_devices **fs_devices_ret)
851 struct btrfs_super_block *disk_super;
852 struct block_device *bdev;
863 * we would like to check all the supers, but that would make
864 * a btrfs mount succeed after a mkfs from a different FS.
865 * So, we need to add a special mount option to scan for
866 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
868 bytenr = btrfs_sb_offset(0);
870 mutex_lock(&uuid_mutex);
872 bdev = blkdev_get_by_path(path, flags, holder);
879 /* make sure our super fits in the device */
880 if (bytenr + PAGE_CACHE_SIZE >= i_size_read(bdev->bd_inode))
883 /* make sure our super fits in the page */
884 if (sizeof(*disk_super) > PAGE_CACHE_SIZE)
887 /* make sure our super doesn't straddle pages on disk */
888 index = bytenr >> PAGE_CACHE_SHIFT;
889 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_CACHE_SHIFT != index)
892 /* pull in the page with our super */
893 page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
896 if (IS_ERR_OR_NULL(page))
901 /* align our pointer to the offset of the super block */
902 disk_super = p + (bytenr & ~PAGE_CACHE_MASK);
904 if (btrfs_super_bytenr(disk_super) != bytenr ||
905 btrfs_super_magic(disk_super) != BTRFS_MAGIC)
908 devid = btrfs_stack_device_id(&disk_super->dev_item);
909 transid = btrfs_super_generation(disk_super);
910 total_devices = btrfs_super_num_devices(disk_super);
912 if (disk_super->label[0]) {
913 if (disk_super->label[BTRFS_LABEL_SIZE - 1])
914 disk_super->label[BTRFS_LABEL_SIZE - 1] = '\0';
915 printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
917 printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
920 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
922 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
923 if (!ret && fs_devices_ret)
924 (*fs_devices_ret)->total_devices = total_devices;
928 page_cache_release(page);
931 blkdev_put(bdev, flags);
933 mutex_unlock(&uuid_mutex);
937 /* helper to account the used device space in the range */
938 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
939 u64 end, u64 *length)
941 struct btrfs_key key;
942 struct btrfs_root *root = device->dev_root;
943 struct btrfs_dev_extent *dev_extent;
944 struct btrfs_path *path;
948 struct extent_buffer *l;
952 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
955 path = btrfs_alloc_path();
960 key.objectid = device->devid;
962 key.type = BTRFS_DEV_EXTENT_KEY;
964 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
968 ret = btrfs_previous_item(root, path, key.objectid, key.type);
975 slot = path->slots[0];
976 if (slot >= btrfs_header_nritems(l)) {
977 ret = btrfs_next_leaf(root, path);
985 btrfs_item_key_to_cpu(l, &key, slot);
987 if (key.objectid < device->devid)
990 if (key.objectid > device->devid)
993 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
996 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
997 extent_end = key.offset + btrfs_dev_extent_length(l,
999 if (key.offset <= start && extent_end > end) {
1000 *length = end - start + 1;
1002 } else if (key.offset <= start && extent_end > start)
1003 *length += extent_end - start;
1004 else if (key.offset > start && extent_end <= end)
1005 *length += extent_end - key.offset;
1006 else if (key.offset > start && key.offset <= end) {
1007 *length += end - key.offset + 1;
1009 } else if (key.offset > end)
1017 btrfs_free_path(path);
1021 static int contains_pending_extent(struct btrfs_trans_handle *trans,
1022 struct btrfs_device *device,
1023 u64 *start, u64 len)
1025 struct extent_map *em;
1028 list_for_each_entry(em, &trans->transaction->pending_chunks, list) {
1029 struct map_lookup *map;
1032 map = (struct map_lookup *)em->bdev;
1033 for (i = 0; i < map->num_stripes; i++) {
1034 if (map->stripes[i].dev != device)
1036 if (map->stripes[i].physical >= *start + len ||
1037 map->stripes[i].physical + em->orig_block_len <=
1040 *start = map->stripes[i].physical +
1051 * find_free_dev_extent - find free space in the specified device
1052 * @device: the device which we search the free space in
1053 * @num_bytes: the size of the free space that we need
1054 * @start: store the start of the free space.
1055 * @len: the size of the free space. that we find, or the size of the max
1056 * free space if we don't find suitable free space
1058 * this uses a pretty simple search, the expectation is that it is
1059 * called very infrequently and that a given device has a small number
1062 * @start is used to store the start of the free space if we find. But if we
1063 * don't find suitable free space, it will be used to store the start position
1064 * of the max free space.
1066 * @len is used to store the size of the free space that we find.
1067 * But if we don't find suitable free space, it is used to store the size of
1068 * the max free space.
1070 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1071 struct btrfs_device *device, u64 num_bytes,
1072 u64 *start, u64 *len)
1074 struct btrfs_key key;
1075 struct btrfs_root *root = device->dev_root;
1076 struct btrfs_dev_extent *dev_extent;
1077 struct btrfs_path *path;
1083 u64 search_end = device->total_bytes;
1086 struct extent_buffer *l;
1088 /* FIXME use last free of some kind */
1090 /* we don't want to overwrite the superblock on the drive,
1091 * so we make sure to start at an offset of at least 1MB
1093 search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1095 path = btrfs_alloc_path();
1099 max_hole_start = search_start;
1103 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1109 path->search_commit_root = 1;
1110 path->skip_locking = 1;
1112 key.objectid = device->devid;
1113 key.offset = search_start;
1114 key.type = BTRFS_DEV_EXTENT_KEY;
1116 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1120 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1127 slot = path->slots[0];
1128 if (slot >= btrfs_header_nritems(l)) {
1129 ret = btrfs_next_leaf(root, path);
1137 btrfs_item_key_to_cpu(l, &key, slot);
1139 if (key.objectid < device->devid)
1142 if (key.objectid > device->devid)
1145 if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
1148 if (key.offset > search_start) {
1149 hole_size = key.offset - search_start;
1152 * Have to check before we set max_hole_start, otherwise
1153 * we could end up sending back this offset anyway.
1155 if (contains_pending_extent(trans, device,
1160 if (hole_size > max_hole_size) {
1161 max_hole_start = search_start;
1162 max_hole_size = hole_size;
1166 * If this free space is greater than which we need,
1167 * it must be the max free space that we have found
1168 * until now, so max_hole_start must point to the start
1169 * of this free space and the length of this free space
1170 * is stored in max_hole_size. Thus, we return
1171 * max_hole_start and max_hole_size and go back to the
1174 if (hole_size >= num_bytes) {
1180 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1181 extent_end = key.offset + btrfs_dev_extent_length(l,
1183 if (extent_end > search_start)
1184 search_start = extent_end;
1191 * At this point, search_start should be the end of
1192 * allocated dev extents, and when shrinking the device,
1193 * search_end may be smaller than search_start.
1195 if (search_end > search_start)
1196 hole_size = search_end - search_start;
1198 if (hole_size > max_hole_size) {
1199 max_hole_start = search_start;
1200 max_hole_size = hole_size;
1203 if (contains_pending_extent(trans, device, &search_start, hole_size)) {
1204 btrfs_release_path(path);
1209 if (hole_size < num_bytes)
1215 btrfs_free_path(path);
1216 *start = max_hole_start;
1218 *len = max_hole_size;
1222 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1223 struct btrfs_device *device,
1227 struct btrfs_path *path;
1228 struct btrfs_root *root = device->dev_root;
1229 struct btrfs_key key;
1230 struct btrfs_key found_key;
1231 struct extent_buffer *leaf = NULL;
1232 struct btrfs_dev_extent *extent = NULL;
1234 path = btrfs_alloc_path();
1238 key.objectid = device->devid;
1240 key.type = BTRFS_DEV_EXTENT_KEY;
1242 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1244 ret = btrfs_previous_item(root, path, key.objectid,
1245 BTRFS_DEV_EXTENT_KEY);
1248 leaf = path->nodes[0];
1249 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1250 extent = btrfs_item_ptr(leaf, path->slots[0],
1251 struct btrfs_dev_extent);
1252 BUG_ON(found_key.offset > start || found_key.offset +
1253 btrfs_dev_extent_length(leaf, extent) < start);
1255 btrfs_release_path(path);
1257 } else if (ret == 0) {
1258 leaf = path->nodes[0];
1259 extent = btrfs_item_ptr(leaf, path->slots[0],
1260 struct btrfs_dev_extent);
1262 btrfs_error(root->fs_info, ret, "Slot search failed");
1266 if (device->bytes_used > 0) {
1267 u64 len = btrfs_dev_extent_length(leaf, extent);
1268 device->bytes_used -= len;
1269 spin_lock(&root->fs_info->free_chunk_lock);
1270 root->fs_info->free_chunk_space += len;
1271 spin_unlock(&root->fs_info->free_chunk_lock);
1273 ret = btrfs_del_item(trans, root, path);
1275 btrfs_error(root->fs_info, ret,
1276 "Failed to remove dev extent item");
1279 btrfs_free_path(path);
1283 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1284 struct btrfs_device *device,
1285 u64 chunk_tree, u64 chunk_objectid,
1286 u64 chunk_offset, u64 start, u64 num_bytes)
1289 struct btrfs_path *path;
1290 struct btrfs_root *root = device->dev_root;
1291 struct btrfs_dev_extent *extent;
1292 struct extent_buffer *leaf;
1293 struct btrfs_key key;
1295 WARN_ON(!device->in_fs_metadata);
1296 WARN_ON(device->is_tgtdev_for_dev_replace);
1297 path = btrfs_alloc_path();
1301 key.objectid = device->devid;
1303 key.type = BTRFS_DEV_EXTENT_KEY;
1304 ret = btrfs_insert_empty_item(trans, root, path, &key,
1309 leaf = path->nodes[0];
1310 extent = btrfs_item_ptr(leaf, path->slots[0],
1311 struct btrfs_dev_extent);
1312 btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1313 btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1314 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1316 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1317 btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1319 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1320 btrfs_mark_buffer_dirty(leaf);
1322 btrfs_free_path(path);
1326 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1328 struct extent_map_tree *em_tree;
1329 struct extent_map *em;
1333 em_tree = &fs_info->mapping_tree.map_tree;
1334 read_lock(&em_tree->lock);
1335 n = rb_last(&em_tree->map);
1337 em = rb_entry(n, struct extent_map, rb_node);
1338 ret = em->start + em->len;
1340 read_unlock(&em_tree->lock);
1345 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1349 struct btrfs_key key;
1350 struct btrfs_key found_key;
1351 struct btrfs_path *path;
1353 path = btrfs_alloc_path();
1357 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1358 key.type = BTRFS_DEV_ITEM_KEY;
1359 key.offset = (u64)-1;
1361 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1365 BUG_ON(ret == 0); /* Corruption */
1367 ret = btrfs_previous_item(fs_info->chunk_root, path,
1368 BTRFS_DEV_ITEMS_OBJECTID,
1369 BTRFS_DEV_ITEM_KEY);
1373 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1375 *devid_ret = found_key.offset + 1;
1379 btrfs_free_path(path);
1384 * the device information is stored in the chunk root
1385 * the btrfs_device struct should be fully filled in
1387 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1388 struct btrfs_root *root,
1389 struct btrfs_device *device)
1392 struct btrfs_path *path;
1393 struct btrfs_dev_item *dev_item;
1394 struct extent_buffer *leaf;
1395 struct btrfs_key key;
1398 root = root->fs_info->chunk_root;
1400 path = btrfs_alloc_path();
1404 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1405 key.type = BTRFS_DEV_ITEM_KEY;
1406 key.offset = device->devid;
1408 ret = btrfs_insert_empty_item(trans, root, path, &key,
1413 leaf = path->nodes[0];
1414 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1416 btrfs_set_device_id(leaf, dev_item, device->devid);
1417 btrfs_set_device_generation(leaf, dev_item, 0);
1418 btrfs_set_device_type(leaf, dev_item, device->type);
1419 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1420 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1421 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1422 btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
1423 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
1424 btrfs_set_device_group(leaf, dev_item, 0);
1425 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1426 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1427 btrfs_set_device_start_offset(leaf, dev_item, 0);
1429 ptr = btrfs_device_uuid(dev_item);
1430 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1431 ptr = btrfs_device_fsid(dev_item);
1432 write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1433 btrfs_mark_buffer_dirty(leaf);
1437 btrfs_free_path(path);
1442 * Function to update ctime/mtime for a given device path.
1443 * Mainly used for ctime/mtime based probe like libblkid.
1445 static void update_dev_time(char *path_name)
1449 filp = filp_open(path_name, O_RDWR, 0);
1452 file_update_time(filp);
1453 filp_close(filp, NULL);
1457 static int btrfs_rm_dev_item(struct btrfs_root *root,
1458 struct btrfs_device *device)
1461 struct btrfs_path *path;
1462 struct btrfs_key key;
1463 struct btrfs_trans_handle *trans;
1465 root = root->fs_info->chunk_root;
1467 path = btrfs_alloc_path();
1471 trans = btrfs_start_transaction(root, 0);
1472 if (IS_ERR(trans)) {
1473 btrfs_free_path(path);
1474 return PTR_ERR(trans);
1476 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1477 key.type = BTRFS_DEV_ITEM_KEY;
1478 key.offset = device->devid;
1481 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1490 ret = btrfs_del_item(trans, root, path);
1494 btrfs_free_path(path);
1495 unlock_chunks(root);
1496 btrfs_commit_transaction(trans, root);
1500 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1502 struct btrfs_device *device;
1503 struct btrfs_device *next_device;
1504 struct block_device *bdev;
1505 struct buffer_head *bh = NULL;
1506 struct btrfs_super_block *disk_super;
1507 struct btrfs_fs_devices *cur_devices;
1514 bool clear_super = false;
1516 mutex_lock(&uuid_mutex);
1519 seq = read_seqbegin(&root->fs_info->profiles_lock);
1521 all_avail = root->fs_info->avail_data_alloc_bits |
1522 root->fs_info->avail_system_alloc_bits |
1523 root->fs_info->avail_metadata_alloc_bits;
1524 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
1526 num_devices = root->fs_info->fs_devices->num_devices;
1527 btrfs_dev_replace_lock(&root->fs_info->dev_replace);
1528 if (btrfs_dev_replace_is_ongoing(&root->fs_info->dev_replace)) {
1529 WARN_ON(num_devices < 1);
1532 btrfs_dev_replace_unlock(&root->fs_info->dev_replace);
1534 if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1535 ret = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1539 if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1540 ret = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1544 if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1545 root->fs_info->fs_devices->rw_devices <= 2) {
1546 ret = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1549 if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1550 root->fs_info->fs_devices->rw_devices <= 3) {
1551 ret = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1555 if (strcmp(device_path, "missing") == 0) {
1556 struct list_head *devices;
1557 struct btrfs_device *tmp;
1560 devices = &root->fs_info->fs_devices->devices;
1562 * It is safe to read the devices since the volume_mutex
1565 list_for_each_entry(tmp, devices, dev_list) {
1566 if (tmp->in_fs_metadata &&
1567 !tmp->is_tgtdev_for_dev_replace &&
1577 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1581 ret = btrfs_get_bdev_and_sb(device_path,
1582 FMODE_WRITE | FMODE_EXCL,
1583 root->fs_info->bdev_holder, 0,
1587 disk_super = (struct btrfs_super_block *)bh->b_data;
1588 devid = btrfs_stack_device_id(&disk_super->dev_item);
1589 dev_uuid = disk_super->dev_item.uuid;
1590 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1598 if (device->is_tgtdev_for_dev_replace) {
1599 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1603 if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1604 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1608 if (device->writeable) {
1610 list_del_init(&device->dev_alloc_list);
1611 unlock_chunks(root);
1612 root->fs_info->fs_devices->rw_devices--;
1616 mutex_unlock(&uuid_mutex);
1617 ret = btrfs_shrink_device(device, 0);
1618 mutex_lock(&uuid_mutex);
1623 * TODO: the superblock still includes this device in its num_devices
1624 * counter although write_all_supers() is not locked out. This
1625 * could give a filesystem state which requires a degraded mount.
1627 ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1631 spin_lock(&root->fs_info->free_chunk_lock);
1632 root->fs_info->free_chunk_space = device->total_bytes -
1634 spin_unlock(&root->fs_info->free_chunk_lock);
1636 device->in_fs_metadata = 0;
1637 btrfs_scrub_cancel_dev(root->fs_info, device);
1640 * the device list mutex makes sure that we don't change
1641 * the device list while someone else is writing out all
1642 * the device supers. Whoever is writing all supers, should
1643 * lock the device list mutex before getting the number of
1644 * devices in the super block (super_copy). Conversely,
1645 * whoever updates the number of devices in the super block
1646 * (super_copy) should hold the device list mutex.
1649 cur_devices = device->fs_devices;
1650 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1651 list_del_rcu(&device->dev_list);
1653 device->fs_devices->num_devices--;
1654 device->fs_devices->total_devices--;
1656 if (device->missing)
1657 root->fs_info->fs_devices->missing_devices--;
1659 next_device = list_entry(root->fs_info->fs_devices->devices.next,
1660 struct btrfs_device, dev_list);
1661 if (device->bdev == root->fs_info->sb->s_bdev)
1662 root->fs_info->sb->s_bdev = next_device->bdev;
1663 if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1664 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1667 device->fs_devices->open_devices--;
1669 call_rcu(&device->rcu, free_device);
1671 num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1672 btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1673 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1675 if (cur_devices->open_devices == 0) {
1676 struct btrfs_fs_devices *fs_devices;
1677 fs_devices = root->fs_info->fs_devices;
1678 while (fs_devices) {
1679 if (fs_devices->seed == cur_devices) {
1680 fs_devices->seed = cur_devices->seed;
1683 fs_devices = fs_devices->seed;
1685 cur_devices->seed = NULL;
1687 __btrfs_close_devices(cur_devices);
1688 unlock_chunks(root);
1689 free_fs_devices(cur_devices);
1692 root->fs_info->num_tolerated_disk_barrier_failures =
1693 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1696 * at this point, the device is zero sized. We want to
1697 * remove it from the devices list and zero out the old super
1699 if (clear_super && disk_super) {
1700 /* make sure this device isn't detected as part of
1703 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1704 set_buffer_dirty(bh);
1705 sync_dirty_buffer(bh);
1711 /* Notify udev that device has changed */
1712 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1714 /* Update ctime/mtime for device path for libblkid */
1715 update_dev_time(device_path);
1721 blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1723 mutex_unlock(&uuid_mutex);
1726 if (device->writeable) {
1728 list_add(&device->dev_alloc_list,
1729 &root->fs_info->fs_devices->alloc_list);
1730 unlock_chunks(root);
1731 root->fs_info->fs_devices->rw_devices++;
1736 void btrfs_rm_dev_replace_srcdev(struct btrfs_fs_info *fs_info,
1737 struct btrfs_device *srcdev)
1739 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1741 list_del_rcu(&srcdev->dev_list);
1742 list_del_rcu(&srcdev->dev_alloc_list);
1743 fs_info->fs_devices->num_devices--;
1744 if (srcdev->missing) {
1745 fs_info->fs_devices->missing_devices--;
1746 fs_info->fs_devices->rw_devices++;
1748 if (srcdev->can_discard)
1749 fs_info->fs_devices->num_can_discard--;
1751 fs_info->fs_devices->open_devices--;
1753 /* zero out the old super */
1754 btrfs_scratch_superblock(srcdev);
1757 call_rcu(&srcdev->rcu, free_device);
1760 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
1761 struct btrfs_device *tgtdev)
1763 struct btrfs_device *next_device;
1766 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1768 btrfs_scratch_superblock(tgtdev);
1769 fs_info->fs_devices->open_devices--;
1771 fs_info->fs_devices->num_devices--;
1772 if (tgtdev->can_discard)
1773 fs_info->fs_devices->num_can_discard++;
1775 next_device = list_entry(fs_info->fs_devices->devices.next,
1776 struct btrfs_device, dev_list);
1777 if (tgtdev->bdev == fs_info->sb->s_bdev)
1778 fs_info->sb->s_bdev = next_device->bdev;
1779 if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
1780 fs_info->fs_devices->latest_bdev = next_device->bdev;
1781 list_del_rcu(&tgtdev->dev_list);
1783 call_rcu(&tgtdev->rcu, free_device);
1785 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1788 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
1789 struct btrfs_device **device)
1792 struct btrfs_super_block *disk_super;
1795 struct block_device *bdev;
1796 struct buffer_head *bh;
1799 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
1800 root->fs_info->bdev_holder, 0, &bdev, &bh);
1803 disk_super = (struct btrfs_super_block *)bh->b_data;
1804 devid = btrfs_stack_device_id(&disk_super->dev_item);
1805 dev_uuid = disk_super->dev_item.uuid;
1806 *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1811 blkdev_put(bdev, FMODE_READ);
1815 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
1817 struct btrfs_device **device)
1820 if (strcmp(device_path, "missing") == 0) {
1821 struct list_head *devices;
1822 struct btrfs_device *tmp;
1824 devices = &root->fs_info->fs_devices->devices;
1826 * It is safe to read the devices since the volume_mutex
1827 * is held by the caller.
1829 list_for_each_entry(tmp, devices, dev_list) {
1830 if (tmp->in_fs_metadata && !tmp->bdev) {
1837 btrfs_err(root->fs_info, "no missing device found");
1843 return btrfs_find_device_by_path(root, device_path, device);
1848 * does all the dirty work required for changing file system's UUID.
1850 static int btrfs_prepare_sprout(struct btrfs_root *root)
1852 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
1853 struct btrfs_fs_devices *old_devices;
1854 struct btrfs_fs_devices *seed_devices;
1855 struct btrfs_super_block *disk_super = root->fs_info->super_copy;
1856 struct btrfs_device *device;
1859 BUG_ON(!mutex_is_locked(&uuid_mutex));
1860 if (!fs_devices->seeding)
1863 seed_devices = __alloc_fs_devices();
1864 if (IS_ERR(seed_devices))
1865 return PTR_ERR(seed_devices);
1867 old_devices = clone_fs_devices(fs_devices);
1868 if (IS_ERR(old_devices)) {
1869 kfree(seed_devices);
1870 return PTR_ERR(old_devices);
1873 list_add(&old_devices->list, &fs_uuids);
1875 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
1876 seed_devices->opened = 1;
1877 INIT_LIST_HEAD(&seed_devices->devices);
1878 INIT_LIST_HEAD(&seed_devices->alloc_list);
1879 mutex_init(&seed_devices->device_list_mutex);
1881 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1882 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
1885 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
1886 list_for_each_entry(device, &seed_devices->devices, dev_list) {
1887 device->fs_devices = seed_devices;
1890 fs_devices->seeding = 0;
1891 fs_devices->num_devices = 0;
1892 fs_devices->open_devices = 0;
1893 fs_devices->seed = seed_devices;
1895 generate_random_uuid(fs_devices->fsid);
1896 memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1897 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
1898 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1900 super_flags = btrfs_super_flags(disk_super) &
1901 ~BTRFS_SUPER_FLAG_SEEDING;
1902 btrfs_set_super_flags(disk_super, super_flags);
1908 * strore the expected generation for seed devices in device items.
1910 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
1911 struct btrfs_root *root)
1913 struct btrfs_path *path;
1914 struct extent_buffer *leaf;
1915 struct btrfs_dev_item *dev_item;
1916 struct btrfs_device *device;
1917 struct btrfs_key key;
1918 u8 fs_uuid[BTRFS_UUID_SIZE];
1919 u8 dev_uuid[BTRFS_UUID_SIZE];
1923 path = btrfs_alloc_path();
1927 root = root->fs_info->chunk_root;
1928 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1930 key.type = BTRFS_DEV_ITEM_KEY;
1933 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1937 leaf = path->nodes[0];
1939 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1940 ret = btrfs_next_leaf(root, path);
1945 leaf = path->nodes[0];
1946 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1947 btrfs_release_path(path);
1951 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1952 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
1953 key.type != BTRFS_DEV_ITEM_KEY)
1956 dev_item = btrfs_item_ptr(leaf, path->slots[0],
1957 struct btrfs_dev_item);
1958 devid = btrfs_device_id(leaf, dev_item);
1959 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
1961 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
1963 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
1965 BUG_ON(!device); /* Logic error */
1967 if (device->fs_devices->seeding) {
1968 btrfs_set_device_generation(leaf, dev_item,
1969 device->generation);
1970 btrfs_mark_buffer_dirty(leaf);
1978 btrfs_free_path(path);
1982 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
1984 struct request_queue *q;
1985 struct btrfs_trans_handle *trans;
1986 struct btrfs_device *device;
1987 struct block_device *bdev;
1988 struct list_head *devices;
1989 struct super_block *sb = root->fs_info->sb;
1990 struct rcu_string *name;
1992 int seeding_dev = 0;
1995 if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
1998 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
1999 root->fs_info->bdev_holder);
2001 return PTR_ERR(bdev);
2003 if (root->fs_info->fs_devices->seeding) {
2005 down_write(&sb->s_umount);
2006 mutex_lock(&uuid_mutex);
2009 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2011 devices = &root->fs_info->fs_devices->devices;
2013 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2014 list_for_each_entry(device, devices, dev_list) {
2015 if (device->bdev == bdev) {
2018 &root->fs_info->fs_devices->device_list_mutex);
2022 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2024 device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2025 if (IS_ERR(device)) {
2026 /* we can safely leave the fs_devices entry around */
2027 ret = PTR_ERR(device);
2031 name = rcu_string_strdup(device_path, GFP_NOFS);
2037 rcu_assign_pointer(device->name, name);
2039 trans = btrfs_start_transaction(root, 0);
2040 if (IS_ERR(trans)) {
2041 rcu_string_free(device->name);
2043 ret = PTR_ERR(trans);
2049 q = bdev_get_queue(bdev);
2050 if (blk_queue_discard(q))
2051 device->can_discard = 1;
2052 device->writeable = 1;
2053 device->generation = trans->transid;
2054 device->io_width = root->sectorsize;
2055 device->io_align = root->sectorsize;
2056 device->sector_size = root->sectorsize;
2057 device->total_bytes = i_size_read(bdev->bd_inode);
2058 device->disk_total_bytes = device->total_bytes;
2059 device->dev_root = root->fs_info->dev_root;
2060 device->bdev = bdev;
2061 device->in_fs_metadata = 1;
2062 device->is_tgtdev_for_dev_replace = 0;
2063 device->mode = FMODE_EXCL;
2064 device->dev_stats_valid = 1;
2065 set_blocksize(device->bdev, 4096);
2068 sb->s_flags &= ~MS_RDONLY;
2069 ret = btrfs_prepare_sprout(root);
2070 BUG_ON(ret); /* -ENOMEM */
2073 device->fs_devices = root->fs_info->fs_devices;
2075 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2076 list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2077 list_add(&device->dev_alloc_list,
2078 &root->fs_info->fs_devices->alloc_list);
2079 root->fs_info->fs_devices->num_devices++;
2080 root->fs_info->fs_devices->open_devices++;
2081 root->fs_info->fs_devices->rw_devices++;
2082 root->fs_info->fs_devices->total_devices++;
2083 if (device->can_discard)
2084 root->fs_info->fs_devices->num_can_discard++;
2085 root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2087 spin_lock(&root->fs_info->free_chunk_lock);
2088 root->fs_info->free_chunk_space += device->total_bytes;
2089 spin_unlock(&root->fs_info->free_chunk_lock);
2091 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2092 root->fs_info->fs_devices->rotating = 1;
2094 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2095 btrfs_set_super_total_bytes(root->fs_info->super_copy,
2096 total_bytes + device->total_bytes);
2098 total_bytes = btrfs_super_num_devices(root->fs_info->super_copy);
2099 btrfs_set_super_num_devices(root->fs_info->super_copy,
2101 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2104 ret = init_first_rw_device(trans, root, device);
2106 btrfs_abort_transaction(trans, root, ret);
2109 ret = btrfs_finish_sprout(trans, root);
2111 btrfs_abort_transaction(trans, root, ret);
2115 ret = btrfs_add_device(trans, root, device);
2117 btrfs_abort_transaction(trans, root, ret);
2123 * we've got more storage, clear any full flags on the space
2126 btrfs_clear_space_info_full(root->fs_info);
2128 unlock_chunks(root);
2129 root->fs_info->num_tolerated_disk_barrier_failures =
2130 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2131 ret = btrfs_commit_transaction(trans, root);
2134 mutex_unlock(&uuid_mutex);
2135 up_write(&sb->s_umount);
2137 if (ret) /* transaction commit */
2140 ret = btrfs_relocate_sys_chunks(root);
2142 btrfs_error(root->fs_info, ret,
2143 "Failed to relocate sys chunks after "
2144 "device initialization. This can be fixed "
2145 "using the \"btrfs balance\" command.");
2146 trans = btrfs_attach_transaction(root);
2147 if (IS_ERR(trans)) {
2148 if (PTR_ERR(trans) == -ENOENT)
2150 return PTR_ERR(trans);
2152 ret = btrfs_commit_transaction(trans, root);
2155 /* Update ctime/mtime for libblkid */
2156 update_dev_time(device_path);
2160 unlock_chunks(root);
2161 btrfs_end_transaction(trans, root);
2162 rcu_string_free(device->name);
2165 blkdev_put(bdev, FMODE_EXCL);
2167 mutex_unlock(&uuid_mutex);
2168 up_write(&sb->s_umount);
2173 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2174 struct btrfs_device **device_out)
2176 struct request_queue *q;
2177 struct btrfs_device *device;
2178 struct block_device *bdev;
2179 struct btrfs_fs_info *fs_info = root->fs_info;
2180 struct list_head *devices;
2181 struct rcu_string *name;
2182 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2186 if (fs_info->fs_devices->seeding)
2189 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2190 fs_info->bdev_holder);
2192 return PTR_ERR(bdev);
2194 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2196 devices = &fs_info->fs_devices->devices;
2197 list_for_each_entry(device, devices, dev_list) {
2198 if (device->bdev == bdev) {
2204 device = btrfs_alloc_device(NULL, &devid, NULL);
2205 if (IS_ERR(device)) {
2206 ret = PTR_ERR(device);
2210 name = rcu_string_strdup(device_path, GFP_NOFS);
2216 rcu_assign_pointer(device->name, name);
2218 q = bdev_get_queue(bdev);
2219 if (blk_queue_discard(q))
2220 device->can_discard = 1;
2221 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2222 device->writeable = 1;
2223 device->generation = 0;
2224 device->io_width = root->sectorsize;
2225 device->io_align = root->sectorsize;
2226 device->sector_size = root->sectorsize;
2227 device->total_bytes = i_size_read(bdev->bd_inode);
2228 device->disk_total_bytes = device->total_bytes;
2229 device->dev_root = fs_info->dev_root;
2230 device->bdev = bdev;
2231 device->in_fs_metadata = 1;
2232 device->is_tgtdev_for_dev_replace = 1;
2233 device->mode = FMODE_EXCL;
2234 device->dev_stats_valid = 1;
2235 set_blocksize(device->bdev, 4096);
2236 device->fs_devices = fs_info->fs_devices;
2237 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2238 fs_info->fs_devices->num_devices++;
2239 fs_info->fs_devices->open_devices++;
2240 if (device->can_discard)
2241 fs_info->fs_devices->num_can_discard++;
2242 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2244 *device_out = device;
2248 blkdev_put(bdev, FMODE_EXCL);
2252 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2253 struct btrfs_device *tgtdev)
2255 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2256 tgtdev->io_width = fs_info->dev_root->sectorsize;
2257 tgtdev->io_align = fs_info->dev_root->sectorsize;
2258 tgtdev->sector_size = fs_info->dev_root->sectorsize;
2259 tgtdev->dev_root = fs_info->dev_root;
2260 tgtdev->in_fs_metadata = 1;
2263 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2264 struct btrfs_device *device)
2267 struct btrfs_path *path;
2268 struct btrfs_root *root;
2269 struct btrfs_dev_item *dev_item;
2270 struct extent_buffer *leaf;
2271 struct btrfs_key key;
2273 root = device->dev_root->fs_info->chunk_root;
2275 path = btrfs_alloc_path();
2279 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2280 key.type = BTRFS_DEV_ITEM_KEY;
2281 key.offset = device->devid;
2283 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2292 leaf = path->nodes[0];
2293 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2295 btrfs_set_device_id(leaf, dev_item, device->devid);
2296 btrfs_set_device_type(leaf, dev_item, device->type);
2297 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2298 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2299 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2300 btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
2301 btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
2302 btrfs_mark_buffer_dirty(leaf);
2305 btrfs_free_path(path);
2309 static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
2310 struct btrfs_device *device, u64 new_size)
2312 struct btrfs_super_block *super_copy =
2313 device->dev_root->fs_info->super_copy;
2314 u64 old_total = btrfs_super_total_bytes(super_copy);
2315 u64 diff = new_size - device->total_bytes;
2317 if (!device->writeable)
2319 if (new_size <= device->total_bytes ||
2320 device->is_tgtdev_for_dev_replace)
2323 btrfs_set_super_total_bytes(super_copy, old_total + diff);
2324 device->fs_devices->total_rw_bytes += diff;
2326 device->total_bytes = new_size;
2327 device->disk_total_bytes = new_size;
2328 btrfs_clear_space_info_full(device->dev_root->fs_info);
2330 return btrfs_update_device(trans, device);
2333 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2334 struct btrfs_device *device, u64 new_size)
2337 lock_chunks(device->dev_root);
2338 ret = __btrfs_grow_device(trans, device, new_size);
2339 unlock_chunks(device->dev_root);
2343 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2344 struct btrfs_root *root,
2345 u64 chunk_tree, u64 chunk_objectid,
2349 struct btrfs_path *path;
2350 struct btrfs_key key;
2352 root = root->fs_info->chunk_root;
2353 path = btrfs_alloc_path();
2357 key.objectid = chunk_objectid;
2358 key.offset = chunk_offset;
2359 key.type = BTRFS_CHUNK_ITEM_KEY;
2361 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2364 else if (ret > 0) { /* Logic error or corruption */
2365 btrfs_error(root->fs_info, -ENOENT,
2366 "Failed lookup while freeing chunk.");
2371 ret = btrfs_del_item(trans, root, path);
2373 btrfs_error(root->fs_info, ret,
2374 "Failed to delete chunk item.");
2376 btrfs_free_path(path);
2380 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2383 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2384 struct btrfs_disk_key *disk_key;
2385 struct btrfs_chunk *chunk;
2392 struct btrfs_key key;
2394 array_size = btrfs_super_sys_array_size(super_copy);
2396 ptr = super_copy->sys_chunk_array;
2399 while (cur < array_size) {
2400 disk_key = (struct btrfs_disk_key *)ptr;
2401 btrfs_disk_key_to_cpu(&key, disk_key);
2403 len = sizeof(*disk_key);
2405 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2406 chunk = (struct btrfs_chunk *)(ptr + len);
2407 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2408 len += btrfs_chunk_item_size(num_stripes);
2413 if (key.objectid == chunk_objectid &&
2414 key.offset == chunk_offset) {
2415 memmove(ptr, ptr + len, array_size - (cur + len));
2417 btrfs_set_super_sys_array_size(super_copy, array_size);
2426 static int btrfs_relocate_chunk(struct btrfs_root *root,
2427 u64 chunk_tree, u64 chunk_objectid,
2430 struct extent_map_tree *em_tree;
2431 struct btrfs_root *extent_root;
2432 struct btrfs_trans_handle *trans;
2433 struct extent_map *em;
2434 struct map_lookup *map;
2438 root = root->fs_info->chunk_root;
2439 extent_root = root->fs_info->extent_root;
2440 em_tree = &root->fs_info->mapping_tree.map_tree;
2442 ret = btrfs_can_relocate(extent_root, chunk_offset);
2446 /* step one, relocate all the extents inside this chunk */
2447 ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2451 trans = btrfs_start_transaction(root, 0);
2452 if (IS_ERR(trans)) {
2453 ret = PTR_ERR(trans);
2454 btrfs_std_error(root->fs_info, ret);
2461 * step two, delete the device extents and the
2462 * chunk tree entries
2464 read_lock(&em_tree->lock);
2465 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2466 read_unlock(&em_tree->lock);
2468 BUG_ON(!em || em->start > chunk_offset ||
2469 em->start + em->len < chunk_offset);
2470 map = (struct map_lookup *)em->bdev;
2472 for (i = 0; i < map->num_stripes; i++) {
2473 ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
2474 map->stripes[i].physical);
2477 if (map->stripes[i].dev) {
2478 ret = btrfs_update_device(trans, map->stripes[i].dev);
2482 ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
2487 trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2489 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2490 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2494 ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
2497 write_lock(&em_tree->lock);
2498 remove_extent_mapping(em_tree, em);
2499 write_unlock(&em_tree->lock);
2504 /* once for the tree */
2505 free_extent_map(em);
2507 free_extent_map(em);
2509 unlock_chunks(root);
2510 btrfs_end_transaction(trans, root);
2514 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2516 struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2517 struct btrfs_path *path;
2518 struct extent_buffer *leaf;
2519 struct btrfs_chunk *chunk;
2520 struct btrfs_key key;
2521 struct btrfs_key found_key;
2522 u64 chunk_tree = chunk_root->root_key.objectid;
2524 bool retried = false;
2528 path = btrfs_alloc_path();
2533 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2534 key.offset = (u64)-1;
2535 key.type = BTRFS_CHUNK_ITEM_KEY;
2538 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2541 BUG_ON(ret == 0); /* Corruption */
2543 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2550 leaf = path->nodes[0];
2551 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2553 chunk = btrfs_item_ptr(leaf, path->slots[0],
2554 struct btrfs_chunk);
2555 chunk_type = btrfs_chunk_type(leaf, chunk);
2556 btrfs_release_path(path);
2558 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2559 ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
2568 if (found_key.offset == 0)
2570 key.offset = found_key.offset - 1;
2573 if (failed && !retried) {
2577 } else if (WARN_ON(failed && retried)) {
2581 btrfs_free_path(path);
2585 static int insert_balance_item(struct btrfs_root *root,
2586 struct btrfs_balance_control *bctl)
2588 struct btrfs_trans_handle *trans;
2589 struct btrfs_balance_item *item;
2590 struct btrfs_disk_balance_args disk_bargs;
2591 struct btrfs_path *path;
2592 struct extent_buffer *leaf;
2593 struct btrfs_key key;
2596 path = btrfs_alloc_path();
2600 trans = btrfs_start_transaction(root, 0);
2601 if (IS_ERR(trans)) {
2602 btrfs_free_path(path);
2603 return PTR_ERR(trans);
2606 key.objectid = BTRFS_BALANCE_OBJECTID;
2607 key.type = BTRFS_BALANCE_ITEM_KEY;
2610 ret = btrfs_insert_empty_item(trans, root, path, &key,
2615 leaf = path->nodes[0];
2616 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
2618 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
2620 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
2621 btrfs_set_balance_data(leaf, item, &disk_bargs);
2622 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
2623 btrfs_set_balance_meta(leaf, item, &disk_bargs);
2624 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
2625 btrfs_set_balance_sys(leaf, item, &disk_bargs);
2627 btrfs_set_balance_flags(leaf, item, bctl->flags);
2629 btrfs_mark_buffer_dirty(leaf);
2631 btrfs_free_path(path);
2632 err = btrfs_commit_transaction(trans, root);
2638 static int del_balance_item(struct btrfs_root *root)
2640 struct btrfs_trans_handle *trans;
2641 struct btrfs_path *path;
2642 struct btrfs_key key;
2645 path = btrfs_alloc_path();
2649 trans = btrfs_start_transaction(root, 0);
2650 if (IS_ERR(trans)) {
2651 btrfs_free_path(path);
2652 return PTR_ERR(trans);
2655 key.objectid = BTRFS_BALANCE_OBJECTID;
2656 key.type = BTRFS_BALANCE_ITEM_KEY;
2659 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2667 ret = btrfs_del_item(trans, root, path);
2669 btrfs_free_path(path);
2670 err = btrfs_commit_transaction(trans, root);
2677 * This is a heuristic used to reduce the number of chunks balanced on
2678 * resume after balance was interrupted.
2680 static void update_balance_args(struct btrfs_balance_control *bctl)
2683 * Turn on soft mode for chunk types that were being converted.
2685 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
2686 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
2687 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
2688 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
2689 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
2690 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
2693 * Turn on usage filter if is not already used. The idea is
2694 * that chunks that we have already balanced should be
2695 * reasonably full. Don't do it for chunks that are being
2696 * converted - that will keep us from relocating unconverted
2697 * (albeit full) chunks.
2699 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2700 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2701 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
2702 bctl->data.usage = 90;
2704 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2705 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2706 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
2707 bctl->sys.usage = 90;
2709 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
2710 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
2711 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
2712 bctl->meta.usage = 90;
2717 * Should be called with both balance and volume mutexes held to
2718 * serialize other volume operations (add_dev/rm_dev/resize) with
2719 * restriper. Same goes for unset_balance_control.
2721 static void set_balance_control(struct btrfs_balance_control *bctl)
2723 struct btrfs_fs_info *fs_info = bctl->fs_info;
2725 BUG_ON(fs_info->balance_ctl);
2727 spin_lock(&fs_info->balance_lock);
2728 fs_info->balance_ctl = bctl;
2729 spin_unlock(&fs_info->balance_lock);
2732 static void unset_balance_control(struct btrfs_fs_info *fs_info)
2734 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2736 BUG_ON(!fs_info->balance_ctl);
2738 spin_lock(&fs_info->balance_lock);
2739 fs_info->balance_ctl = NULL;
2740 spin_unlock(&fs_info->balance_lock);
2746 * Balance filters. Return 1 if chunk should be filtered out
2747 * (should not be balanced).
2749 static int chunk_profiles_filter(u64 chunk_type,
2750 struct btrfs_balance_args *bargs)
2752 chunk_type = chunk_to_extended(chunk_type) &
2753 BTRFS_EXTENDED_PROFILE_MASK;
2755 if (bargs->profiles & chunk_type)
2761 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
2762 struct btrfs_balance_args *bargs)
2764 struct btrfs_block_group_cache *cache;
2765 u64 chunk_used, user_thresh;
2768 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2769 chunk_used = btrfs_block_group_used(&cache->item);
2771 if (bargs->usage == 0)
2773 else if (bargs->usage > 100)
2774 user_thresh = cache->key.offset;
2776 user_thresh = div_factor_fine(cache->key.offset,
2779 if (chunk_used < user_thresh)
2782 btrfs_put_block_group(cache);
2786 static int chunk_devid_filter(struct extent_buffer *leaf,
2787 struct btrfs_chunk *chunk,
2788 struct btrfs_balance_args *bargs)
2790 struct btrfs_stripe *stripe;
2791 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2794 for (i = 0; i < num_stripes; i++) {
2795 stripe = btrfs_stripe_nr(chunk, i);
2796 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
2803 /* [pstart, pend) */
2804 static int chunk_drange_filter(struct extent_buffer *leaf,
2805 struct btrfs_chunk *chunk,
2807 struct btrfs_balance_args *bargs)
2809 struct btrfs_stripe *stripe;
2810 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
2816 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
2819 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
2820 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
2821 factor = num_stripes / 2;
2822 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
2823 factor = num_stripes - 1;
2824 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
2825 factor = num_stripes - 2;
2827 factor = num_stripes;
2830 for (i = 0; i < num_stripes; i++) {
2831 stripe = btrfs_stripe_nr(chunk, i);
2832 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
2835 stripe_offset = btrfs_stripe_offset(leaf, stripe);
2836 stripe_length = btrfs_chunk_length(leaf, chunk);
2837 do_div(stripe_length, factor);
2839 if (stripe_offset < bargs->pend &&
2840 stripe_offset + stripe_length > bargs->pstart)
2847 /* [vstart, vend) */
2848 static int chunk_vrange_filter(struct extent_buffer *leaf,
2849 struct btrfs_chunk *chunk,
2851 struct btrfs_balance_args *bargs)
2853 if (chunk_offset < bargs->vend &&
2854 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
2855 /* at least part of the chunk is inside this vrange */
2861 static int chunk_soft_convert_filter(u64 chunk_type,
2862 struct btrfs_balance_args *bargs)
2864 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
2867 chunk_type = chunk_to_extended(chunk_type) &
2868 BTRFS_EXTENDED_PROFILE_MASK;
2870 if (bargs->target == chunk_type)
2876 static int should_balance_chunk(struct btrfs_root *root,
2877 struct extent_buffer *leaf,
2878 struct btrfs_chunk *chunk, u64 chunk_offset)
2880 struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
2881 struct btrfs_balance_args *bargs = NULL;
2882 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
2885 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
2886 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
2890 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
2891 bargs = &bctl->data;
2892 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
2894 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
2895 bargs = &bctl->meta;
2897 /* profiles filter */
2898 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
2899 chunk_profiles_filter(chunk_type, bargs)) {
2904 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
2905 chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
2910 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
2911 chunk_devid_filter(leaf, chunk, bargs)) {
2915 /* drange filter, makes sense only with devid filter */
2916 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
2917 chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
2922 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
2923 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
2927 /* soft profile changing mode */
2928 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
2929 chunk_soft_convert_filter(chunk_type, bargs)) {
2936 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
2938 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
2939 struct btrfs_root *chunk_root = fs_info->chunk_root;
2940 struct btrfs_root *dev_root = fs_info->dev_root;
2941 struct list_head *devices;
2942 struct btrfs_device *device;
2945 struct btrfs_chunk *chunk;
2946 struct btrfs_path *path;
2947 struct btrfs_key key;
2948 struct btrfs_key found_key;
2949 struct btrfs_trans_handle *trans;
2950 struct extent_buffer *leaf;
2953 int enospc_errors = 0;
2954 bool counting = true;
2956 /* step one make some room on all the devices */
2957 devices = &fs_info->fs_devices->devices;
2958 list_for_each_entry(device, devices, dev_list) {
2959 old_size = device->total_bytes;
2960 size_to_free = div_factor(old_size, 1);
2961 size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
2962 if (!device->writeable ||
2963 device->total_bytes - device->bytes_used > size_to_free ||
2964 device->is_tgtdev_for_dev_replace)
2967 ret = btrfs_shrink_device(device, old_size - size_to_free);
2972 trans = btrfs_start_transaction(dev_root, 0);
2973 BUG_ON(IS_ERR(trans));
2975 ret = btrfs_grow_device(trans, device, old_size);
2978 btrfs_end_transaction(trans, dev_root);
2981 /* step two, relocate all the chunks */
2982 path = btrfs_alloc_path();
2988 /* zero out stat counters */
2989 spin_lock(&fs_info->balance_lock);
2990 memset(&bctl->stat, 0, sizeof(bctl->stat));
2991 spin_unlock(&fs_info->balance_lock);
2993 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2994 key.offset = (u64)-1;
2995 key.type = BTRFS_CHUNK_ITEM_KEY;
2998 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
2999 atomic_read(&fs_info->balance_cancel_req)) {
3004 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3009 * this shouldn't happen, it means the last relocate
3013 BUG(); /* FIXME break ? */
3015 ret = btrfs_previous_item(chunk_root, path, 0,
3016 BTRFS_CHUNK_ITEM_KEY);
3022 leaf = path->nodes[0];
3023 slot = path->slots[0];
3024 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3026 if (found_key.objectid != key.objectid)
3029 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3032 spin_lock(&fs_info->balance_lock);
3033 bctl->stat.considered++;
3034 spin_unlock(&fs_info->balance_lock);
3037 ret = should_balance_chunk(chunk_root, leaf, chunk,
3039 btrfs_release_path(path);
3044 spin_lock(&fs_info->balance_lock);
3045 bctl->stat.expected++;
3046 spin_unlock(&fs_info->balance_lock);
3050 ret = btrfs_relocate_chunk(chunk_root,
3051 chunk_root->root_key.objectid,
3054 if (ret && ret != -ENOSPC)
3056 if (ret == -ENOSPC) {
3059 spin_lock(&fs_info->balance_lock);
3060 bctl->stat.completed++;
3061 spin_unlock(&fs_info->balance_lock);
3064 if (found_key.offset == 0)
3066 key.offset = found_key.offset - 1;
3070 btrfs_release_path(path);
3075 btrfs_free_path(path);
3076 if (enospc_errors) {
3077 btrfs_info(fs_info, "%d enospc errors during balance",
3087 * alloc_profile_is_valid - see if a given profile is valid and reduced
3088 * @flags: profile to validate
3089 * @extended: if true @flags is treated as an extended profile
3091 static int alloc_profile_is_valid(u64 flags, int extended)
3093 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3094 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3096 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3098 /* 1) check that all other bits are zeroed */
3102 /* 2) see if profile is reduced */
3104 return !extended; /* "0" is valid for usual profiles */
3106 /* true if exactly one bit set */
3107 return (flags & (flags - 1)) == 0;
3110 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3112 /* cancel requested || normal exit path */
3113 return atomic_read(&fs_info->balance_cancel_req) ||
3114 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3115 atomic_read(&fs_info->balance_cancel_req) == 0);
3118 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3122 unset_balance_control(fs_info);
3123 ret = del_balance_item(fs_info->tree_root);
3125 btrfs_std_error(fs_info, ret);
3127 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3131 * Should be called with both balance and volume mutexes held
3133 int btrfs_balance(struct btrfs_balance_control *bctl,
3134 struct btrfs_ioctl_balance_args *bargs)
3136 struct btrfs_fs_info *fs_info = bctl->fs_info;
3143 if (btrfs_fs_closing(fs_info) ||
3144 atomic_read(&fs_info->balance_pause_req) ||
3145 atomic_read(&fs_info->balance_cancel_req)) {
3150 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3151 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3155 * In case of mixed groups both data and meta should be picked,
3156 * and identical options should be given for both of them.
3158 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3159 if (mixed && (bctl->flags & allowed)) {
3160 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3161 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3162 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3163 btrfs_err(fs_info, "with mixed groups data and "
3164 "metadata balance options must be the same");
3170 num_devices = fs_info->fs_devices->num_devices;
3171 btrfs_dev_replace_lock(&fs_info->dev_replace);
3172 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3173 BUG_ON(num_devices < 1);
3176 btrfs_dev_replace_unlock(&fs_info->dev_replace);
3177 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3178 if (num_devices == 1)
3179 allowed |= BTRFS_BLOCK_GROUP_DUP;
3180 else if (num_devices > 1)
3181 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3182 if (num_devices > 2)
3183 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3184 if (num_devices > 3)
3185 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3186 BTRFS_BLOCK_GROUP_RAID6);
3187 if ((bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3188 (!alloc_profile_is_valid(bctl->data.target, 1) ||
3189 (bctl->data.target & ~allowed))) {
3190 btrfs_err(fs_info, "unable to start balance with target "
3191 "data profile %llu",
3196 if ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3197 (!alloc_profile_is_valid(bctl->meta.target, 1) ||
3198 (bctl->meta.target & ~allowed))) {
3200 "unable to start balance with target metadata profile %llu",
3205 if ((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3206 (!alloc_profile_is_valid(bctl->sys.target, 1) ||
3207 (bctl->sys.target & ~allowed))) {
3209 "unable to start balance with target system profile %llu",
3215 /* allow dup'ed data chunks only in mixed mode */
3216 if (!mixed && (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3217 (bctl->data.target & BTRFS_BLOCK_GROUP_DUP)) {
3218 btrfs_err(fs_info, "dup for data is not allowed");
3223 /* allow to reduce meta or sys integrity only if force set */
3224 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3225 BTRFS_BLOCK_GROUP_RAID10 |
3226 BTRFS_BLOCK_GROUP_RAID5 |
3227 BTRFS_BLOCK_GROUP_RAID6;
3229 seq = read_seqbegin(&fs_info->profiles_lock);
3231 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3232 (fs_info->avail_system_alloc_bits & allowed) &&
3233 !(bctl->sys.target & allowed)) ||
3234 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3235 (fs_info->avail_metadata_alloc_bits & allowed) &&
3236 !(bctl->meta.target & allowed))) {
3237 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3238 btrfs_info(fs_info, "force reducing metadata integrity");
3240 btrfs_err(fs_info, "balance will reduce metadata "
3241 "integrity, use force if you want this");
3246 } while (read_seqretry(&fs_info->profiles_lock, seq));
3248 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3249 int num_tolerated_disk_barrier_failures;
3250 u64 target = bctl->sys.target;
3252 num_tolerated_disk_barrier_failures =
3253 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3254 if (num_tolerated_disk_barrier_failures > 0 &&
3256 (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3257 BTRFS_AVAIL_ALLOC_BIT_SINGLE)))
3258 num_tolerated_disk_barrier_failures = 0;
3259 else if (num_tolerated_disk_barrier_failures > 1 &&
3261 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)))
3262 num_tolerated_disk_barrier_failures = 1;
3264 fs_info->num_tolerated_disk_barrier_failures =
3265 num_tolerated_disk_barrier_failures;
3268 ret = insert_balance_item(fs_info->tree_root, bctl);
3269 if (ret && ret != -EEXIST)
3272 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3273 BUG_ON(ret == -EEXIST);
3274 set_balance_control(bctl);
3276 BUG_ON(ret != -EEXIST);
3277 spin_lock(&fs_info->balance_lock);
3278 update_balance_args(bctl);
3279 spin_unlock(&fs_info->balance_lock);
3282 atomic_inc(&fs_info->balance_running);
3283 mutex_unlock(&fs_info->balance_mutex);
3285 ret = __btrfs_balance(fs_info);
3287 mutex_lock(&fs_info->balance_mutex);
3288 atomic_dec(&fs_info->balance_running);
3290 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3291 fs_info->num_tolerated_disk_barrier_failures =
3292 btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3296 memset(bargs, 0, sizeof(*bargs));
3297 update_ioctl_balance_args(fs_info, 0, bargs);
3300 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3301 balance_need_close(fs_info)) {
3302 __cancel_balance(fs_info);
3305 wake_up(&fs_info->balance_wait_q);
3309 if (bctl->flags & BTRFS_BALANCE_RESUME)
3310 __cancel_balance(fs_info);
3313 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3318 static int balance_kthread(void *data)
3320 struct btrfs_fs_info *fs_info = data;
3323 mutex_lock(&fs_info->volume_mutex);
3324 mutex_lock(&fs_info->balance_mutex);
3326 if (fs_info->balance_ctl) {
3327 btrfs_info(fs_info, "continuing balance");
3328 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3331 mutex_unlock(&fs_info->balance_mutex);
3332 mutex_unlock(&fs_info->volume_mutex);
3337 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3339 struct task_struct *tsk;
3341 spin_lock(&fs_info->balance_lock);
3342 if (!fs_info->balance_ctl) {
3343 spin_unlock(&fs_info->balance_lock);
3346 spin_unlock(&fs_info->balance_lock);
3348 if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3349 btrfs_info(fs_info, "force skipping balance");
3353 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3354 return PTR_ERR_OR_ZERO(tsk);
3357 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3359 struct btrfs_balance_control *bctl;
3360 struct btrfs_balance_item *item;
3361 struct btrfs_disk_balance_args disk_bargs;
3362 struct btrfs_path *path;
3363 struct extent_buffer *leaf;
3364 struct btrfs_key key;
3367 path = btrfs_alloc_path();
3371 key.objectid = BTRFS_BALANCE_OBJECTID;
3372 key.type = BTRFS_BALANCE_ITEM_KEY;
3375 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3378 if (ret > 0) { /* ret = -ENOENT; */
3383 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3389 leaf = path->nodes[0];
3390 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3392 bctl->fs_info = fs_info;
3393 bctl->flags = btrfs_balance_flags(leaf, item);
3394 bctl->flags |= BTRFS_BALANCE_RESUME;
3396 btrfs_balance_data(leaf, item, &disk_bargs);
3397 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3398 btrfs_balance_meta(leaf, item, &disk_bargs);
3399 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3400 btrfs_balance_sys(leaf, item, &disk_bargs);
3401 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3403 WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3405 mutex_lock(&fs_info->volume_mutex);
3406 mutex_lock(&fs_info->balance_mutex);
3408 set_balance_control(bctl);
3410 mutex_unlock(&fs_info->balance_mutex);
3411 mutex_unlock(&fs_info->volume_mutex);
3413 btrfs_free_path(path);
3417 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3421 mutex_lock(&fs_info->balance_mutex);
3422 if (!fs_info->balance_ctl) {
3423 mutex_unlock(&fs_info->balance_mutex);
3427 if (atomic_read(&fs_info->balance_running)) {
3428 atomic_inc(&fs_info->balance_pause_req);
3429 mutex_unlock(&fs_info->balance_mutex);
3431 wait_event(fs_info->balance_wait_q,
3432 atomic_read(&fs_info->balance_running) == 0);
3434 mutex_lock(&fs_info->balance_mutex);
3435 /* we are good with balance_ctl ripped off from under us */
3436 BUG_ON(atomic_read(&fs_info->balance_running));
3437 atomic_dec(&fs_info->balance_pause_req);
3442 mutex_unlock(&fs_info->balance_mutex);
3446 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3448 if (fs_info->sb->s_flags & MS_RDONLY)
3451 mutex_lock(&fs_info->balance_mutex);
3452 if (!fs_info->balance_ctl) {
3453 mutex_unlock(&fs_info->balance_mutex);
3457 atomic_inc(&fs_info->balance_cancel_req);
3459 * if we are running just wait and return, balance item is
3460 * deleted in btrfs_balance in this case
3462 if (atomic_read(&fs_info->balance_running)) {
3463 mutex_unlock(&fs_info->balance_mutex);
3464 wait_event(fs_info->balance_wait_q,
3465 atomic_read(&fs_info->balance_running) == 0);
3466 mutex_lock(&fs_info->balance_mutex);
3468 /* __cancel_balance needs volume_mutex */
3469 mutex_unlock(&fs_info->balance_mutex);
3470 mutex_lock(&fs_info->volume_mutex);
3471 mutex_lock(&fs_info->balance_mutex);
3473 if (fs_info->balance_ctl)
3474 __cancel_balance(fs_info);
3476 mutex_unlock(&fs_info->volume_mutex);
3479 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
3480 atomic_dec(&fs_info->balance_cancel_req);
3481 mutex_unlock(&fs_info->balance_mutex);
3485 static int btrfs_uuid_scan_kthread(void *data)
3487 struct btrfs_fs_info *fs_info = data;
3488 struct btrfs_root *root = fs_info->tree_root;
3489 struct btrfs_key key;
3490 struct btrfs_key max_key;
3491 struct btrfs_path *path = NULL;
3493 struct extent_buffer *eb;
3495 struct btrfs_root_item root_item;
3497 struct btrfs_trans_handle *trans = NULL;
3499 path = btrfs_alloc_path();
3506 key.type = BTRFS_ROOT_ITEM_KEY;
3509 max_key.objectid = (u64)-1;
3510 max_key.type = BTRFS_ROOT_ITEM_KEY;
3511 max_key.offset = (u64)-1;
3513 path->keep_locks = 1;
3516 ret = btrfs_search_forward(root, &key, path, 0);
3523 if (key.type != BTRFS_ROOT_ITEM_KEY ||
3524 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
3525 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
3526 key.objectid > BTRFS_LAST_FREE_OBJECTID)
3529 eb = path->nodes[0];
3530 slot = path->slots[0];
3531 item_size = btrfs_item_size_nr(eb, slot);
3532 if (item_size < sizeof(root_item))
3535 read_extent_buffer(eb, &root_item,
3536 btrfs_item_ptr_offset(eb, slot),
3537 (int)sizeof(root_item));
3538 if (btrfs_root_refs(&root_item) == 0)
3541 if (!btrfs_is_empty_uuid(root_item.uuid) ||
3542 !btrfs_is_empty_uuid(root_item.received_uuid)) {
3546 btrfs_release_path(path);
3548 * 1 - subvol uuid item
3549 * 1 - received_subvol uuid item
3551 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
3552 if (IS_ERR(trans)) {
3553 ret = PTR_ERR(trans);
3561 if (!btrfs_is_empty_uuid(root_item.uuid)) {
3562 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3564 BTRFS_UUID_KEY_SUBVOL,
3567 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3573 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
3574 ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
3575 root_item.received_uuid,
3576 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3579 btrfs_warn(fs_info, "uuid_tree_add failed %d",
3587 ret = btrfs_end_transaction(trans, fs_info->uuid_root);
3593 btrfs_release_path(path);
3594 if (key.offset < (u64)-1) {
3596 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
3598 key.type = BTRFS_ROOT_ITEM_KEY;
3599 } else if (key.objectid < (u64)-1) {
3601 key.type = BTRFS_ROOT_ITEM_KEY;
3610 btrfs_free_path(path);
3611 if (trans && !IS_ERR(trans))
3612 btrfs_end_transaction(trans, fs_info->uuid_root);
3614 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
3616 fs_info->update_uuid_tree_gen = 1;
3617 up(&fs_info->uuid_tree_rescan_sem);
3622 * Callback for btrfs_uuid_tree_iterate().
3624 * 0 check succeeded, the entry is not outdated.
3625 * < 0 if an error occured.
3626 * > 0 if the check failed, which means the caller shall remove the entry.
3628 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
3629 u8 *uuid, u8 type, u64 subid)
3631 struct btrfs_key key;
3633 struct btrfs_root *subvol_root;
3635 if (type != BTRFS_UUID_KEY_SUBVOL &&
3636 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
3639 key.objectid = subid;
3640 key.type = BTRFS_ROOT_ITEM_KEY;
3641 key.offset = (u64)-1;
3642 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
3643 if (IS_ERR(subvol_root)) {
3644 ret = PTR_ERR(subvol_root);
3651 case BTRFS_UUID_KEY_SUBVOL:
3652 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
3655 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
3656 if (memcmp(uuid, subvol_root->root_item.received_uuid,
3666 static int btrfs_uuid_rescan_kthread(void *data)
3668 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
3672 * 1st step is to iterate through the existing UUID tree and
3673 * to delete all entries that contain outdated data.
3674 * 2nd step is to add all missing entries to the UUID tree.
3676 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
3678 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
3679 up(&fs_info->uuid_tree_rescan_sem);
3682 return btrfs_uuid_scan_kthread(data);
3685 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
3687 struct btrfs_trans_handle *trans;
3688 struct btrfs_root *tree_root = fs_info->tree_root;
3689 struct btrfs_root *uuid_root;
3690 struct task_struct *task;
3697 trans = btrfs_start_transaction(tree_root, 2);
3699 return PTR_ERR(trans);
3701 uuid_root = btrfs_create_tree(trans, fs_info,
3702 BTRFS_UUID_TREE_OBJECTID);
3703 if (IS_ERR(uuid_root)) {
3704 btrfs_abort_transaction(trans, tree_root,
3705 PTR_ERR(uuid_root));
3706 return PTR_ERR(uuid_root);
3709 fs_info->uuid_root = uuid_root;
3711 ret = btrfs_commit_transaction(trans, tree_root);
3715 down(&fs_info->uuid_tree_rescan_sem);
3716 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
3718 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3719 btrfs_warn(fs_info, "failed to start uuid_scan task");
3720 up(&fs_info->uuid_tree_rescan_sem);
3721 return PTR_ERR(task);
3727 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
3729 struct task_struct *task;
3731 down(&fs_info->uuid_tree_rescan_sem);
3732 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
3734 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
3735 btrfs_warn(fs_info, "failed to start uuid_rescan task");
3736 up(&fs_info->uuid_tree_rescan_sem);
3737 return PTR_ERR(task);
3744 * shrinking a device means finding all of the device extents past
3745 * the new size, and then following the back refs to the chunks.
3746 * The chunk relocation code actually frees the device extent
3748 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
3750 struct btrfs_trans_handle *trans;
3751 struct btrfs_root *root = device->dev_root;
3752 struct btrfs_dev_extent *dev_extent = NULL;
3753 struct btrfs_path *path;
3761 bool retried = false;
3762 struct extent_buffer *l;
3763 struct btrfs_key key;
3764 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3765 u64 old_total = btrfs_super_total_bytes(super_copy);
3766 u64 old_size = device->total_bytes;
3767 u64 diff = device->total_bytes - new_size;
3769 if (device->is_tgtdev_for_dev_replace)
3772 path = btrfs_alloc_path();
3780 device->total_bytes = new_size;
3781 if (device->writeable) {
3782 device->fs_devices->total_rw_bytes -= diff;
3783 spin_lock(&root->fs_info->free_chunk_lock);
3784 root->fs_info->free_chunk_space -= diff;
3785 spin_unlock(&root->fs_info->free_chunk_lock);
3787 unlock_chunks(root);
3790 key.objectid = device->devid;
3791 key.offset = (u64)-1;
3792 key.type = BTRFS_DEV_EXTENT_KEY;
3795 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3799 ret = btrfs_previous_item(root, path, 0, key.type);
3804 btrfs_release_path(path);
3809 slot = path->slots[0];
3810 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
3812 if (key.objectid != device->devid) {
3813 btrfs_release_path(path);
3817 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
3818 length = btrfs_dev_extent_length(l, dev_extent);
3820 if (key.offset + length <= new_size) {
3821 btrfs_release_path(path);
3825 chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
3826 chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
3827 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
3828 btrfs_release_path(path);
3830 ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
3832 if (ret && ret != -ENOSPC)
3836 } while (key.offset-- > 0);
3838 if (failed && !retried) {
3842 } else if (failed && retried) {
3846 device->total_bytes = old_size;
3847 if (device->writeable)
3848 device->fs_devices->total_rw_bytes += diff;
3849 spin_lock(&root->fs_info->free_chunk_lock);
3850 root->fs_info->free_chunk_space += diff;
3851 spin_unlock(&root->fs_info->free_chunk_lock);
3852 unlock_chunks(root);
3856 /* Shrinking succeeded, else we would be at "done". */
3857 trans = btrfs_start_transaction(root, 0);
3858 if (IS_ERR(trans)) {
3859 ret = PTR_ERR(trans);
3865 device->disk_total_bytes = new_size;
3866 /* Now btrfs_update_device() will change the on-disk size. */
3867 ret = btrfs_update_device(trans, device);
3869 unlock_chunks(root);
3870 btrfs_end_transaction(trans, root);
3873 WARN_ON(diff > old_total);
3874 btrfs_set_super_total_bytes(super_copy, old_total - diff);
3875 unlock_chunks(root);
3876 btrfs_end_transaction(trans, root);
3878 btrfs_free_path(path);
3882 static int btrfs_add_system_chunk(struct btrfs_root *root,
3883 struct btrfs_key *key,
3884 struct btrfs_chunk *chunk, int item_size)
3886 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
3887 struct btrfs_disk_key disk_key;
3891 array_size = btrfs_super_sys_array_size(super_copy);
3892 if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
3895 ptr = super_copy->sys_chunk_array + array_size;
3896 btrfs_cpu_key_to_disk(&disk_key, key);
3897 memcpy(ptr, &disk_key, sizeof(disk_key));
3898 ptr += sizeof(disk_key);
3899 memcpy(ptr, chunk, item_size);
3900 item_size += sizeof(disk_key);
3901 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
3906 * sort the devices in descending order by max_avail, total_avail
3908 static int btrfs_cmp_device_info(const void *a, const void *b)
3910 const struct btrfs_device_info *di_a = a;
3911 const struct btrfs_device_info *di_b = b;
3913 if (di_a->max_avail > di_b->max_avail)
3915 if (di_a->max_avail < di_b->max_avail)
3917 if (di_a->total_avail > di_b->total_avail)
3919 if (di_a->total_avail < di_b->total_avail)
3924 static struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
3925 [BTRFS_RAID_RAID10] = {
3928 .devs_max = 0, /* 0 == as many as possible */
3930 .devs_increment = 2,
3933 [BTRFS_RAID_RAID1] = {
3938 .devs_increment = 2,
3941 [BTRFS_RAID_DUP] = {
3946 .devs_increment = 1,
3949 [BTRFS_RAID_RAID0] = {
3954 .devs_increment = 1,
3957 [BTRFS_RAID_SINGLE] = {
3962 .devs_increment = 1,
3965 [BTRFS_RAID_RAID5] = {
3970 .devs_increment = 1,
3973 [BTRFS_RAID_RAID6] = {
3978 .devs_increment = 1,
3983 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
3985 /* TODO allow them to set a preferred stripe size */
3989 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
3991 if (!(type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)))
3994 btrfs_set_fs_incompat(info, RAID56);
3997 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
3998 struct btrfs_root *extent_root, u64 start,
4001 struct btrfs_fs_info *info = extent_root->fs_info;
4002 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4003 struct list_head *cur;
4004 struct map_lookup *map = NULL;
4005 struct extent_map_tree *em_tree;
4006 struct extent_map *em;
4007 struct btrfs_device_info *devices_info = NULL;
4009 int num_stripes; /* total number of stripes to allocate */
4010 int data_stripes; /* number of stripes that count for
4012 int sub_stripes; /* sub_stripes info for map */
4013 int dev_stripes; /* stripes per dev */
4014 int devs_max; /* max devs to use */
4015 int devs_min; /* min devs needed */
4016 int devs_increment; /* ndevs has to be a multiple of this */
4017 int ncopies; /* how many copies to data has */
4019 u64 max_stripe_size;
4023 u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4029 BUG_ON(!alloc_profile_is_valid(type, 0));
4031 if (list_empty(&fs_devices->alloc_list))
4034 index = __get_raid_index(type);
4036 sub_stripes = btrfs_raid_array[index].sub_stripes;
4037 dev_stripes = btrfs_raid_array[index].dev_stripes;
4038 devs_max = btrfs_raid_array[index].devs_max;
4039 devs_min = btrfs_raid_array[index].devs_min;
4040 devs_increment = btrfs_raid_array[index].devs_increment;
4041 ncopies = btrfs_raid_array[index].ncopies;
4043 if (type & BTRFS_BLOCK_GROUP_DATA) {
4044 max_stripe_size = 1024 * 1024 * 1024;
4045 max_chunk_size = 10 * max_stripe_size;
4046 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4047 /* for larger filesystems, use larger metadata chunks */
4048 if (fs_devices->total_rw_bytes > 50ULL * 1024 * 1024 * 1024)
4049 max_stripe_size = 1024 * 1024 * 1024;
4051 max_stripe_size = 256 * 1024 * 1024;
4052 max_chunk_size = max_stripe_size;
4053 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4054 max_stripe_size = 32 * 1024 * 1024;
4055 max_chunk_size = 2 * max_stripe_size;
4057 btrfs_err(info, "invalid chunk type 0x%llx requested\n",
4062 /* we don't want a chunk larger than 10% of writeable space */
4063 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4066 devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
4071 cur = fs_devices->alloc_list.next;
4074 * in the first pass through the devices list, we gather information
4075 * about the available holes on each device.
4078 while (cur != &fs_devices->alloc_list) {
4079 struct btrfs_device *device;
4083 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4087 if (!device->writeable) {
4089 "BTRFS: read-only device in alloc_list\n");
4093 if (!device->in_fs_metadata ||
4094 device->is_tgtdev_for_dev_replace)
4097 if (device->total_bytes > device->bytes_used)
4098 total_avail = device->total_bytes - device->bytes_used;
4102 /* If there is no space on this device, skip it. */
4103 if (total_avail == 0)
4106 ret = find_free_dev_extent(trans, device,
4107 max_stripe_size * dev_stripes,
4108 &dev_offset, &max_avail);
4109 if (ret && ret != -ENOSPC)
4113 max_avail = max_stripe_size * dev_stripes;
4115 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4118 if (ndevs == fs_devices->rw_devices) {
4119 WARN(1, "%s: found more than %llu devices\n",
4120 __func__, fs_devices->rw_devices);
4123 devices_info[ndevs].dev_offset = dev_offset;
4124 devices_info[ndevs].max_avail = max_avail;
4125 devices_info[ndevs].total_avail = total_avail;
4126 devices_info[ndevs].dev = device;
4131 * now sort the devices by hole size / available space
4133 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4134 btrfs_cmp_device_info, NULL);
4136 /* round down to number of usable stripes */
4137 ndevs -= ndevs % devs_increment;
4139 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4144 if (devs_max && ndevs > devs_max)
4147 * the primary goal is to maximize the number of stripes, so use as many
4148 * devices as possible, even if the stripes are not maximum sized.
4150 stripe_size = devices_info[ndevs-1].max_avail;
4151 num_stripes = ndevs * dev_stripes;
4154 * this will have to be fixed for RAID1 and RAID10 over
4157 data_stripes = num_stripes / ncopies;
4159 if (type & BTRFS_BLOCK_GROUP_RAID5) {
4160 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4161 btrfs_super_stripesize(info->super_copy));
4162 data_stripes = num_stripes - 1;
4164 if (type & BTRFS_BLOCK_GROUP_RAID6) {
4165 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4166 btrfs_super_stripesize(info->super_copy));
4167 data_stripes = num_stripes - 2;
4171 * Use the number of data stripes to figure out how big this chunk
4172 * is really going to be in terms of logical address space,
4173 * and compare that answer with the max chunk size
4175 if (stripe_size * data_stripes > max_chunk_size) {
4176 u64 mask = (1ULL << 24) - 1;
4177 stripe_size = max_chunk_size;
4178 do_div(stripe_size, data_stripes);
4180 /* bump the answer up to a 16MB boundary */
4181 stripe_size = (stripe_size + mask) & ~mask;
4183 /* but don't go higher than the limits we found
4184 * while searching for free extents
4186 if (stripe_size > devices_info[ndevs-1].max_avail)
4187 stripe_size = devices_info[ndevs-1].max_avail;
4190 do_div(stripe_size, dev_stripes);
4192 /* align to BTRFS_STRIPE_LEN */
4193 do_div(stripe_size, raid_stripe_len);
4194 stripe_size *= raid_stripe_len;
4196 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4201 map->num_stripes = num_stripes;
4203 for (i = 0; i < ndevs; ++i) {
4204 for (j = 0; j < dev_stripes; ++j) {
4205 int s = i * dev_stripes + j;
4206 map->stripes[s].dev = devices_info[i].dev;
4207 map->stripes[s].physical = devices_info[i].dev_offset +
4211 map->sector_size = extent_root->sectorsize;
4212 map->stripe_len = raid_stripe_len;
4213 map->io_align = raid_stripe_len;
4214 map->io_width = raid_stripe_len;
4216 map->sub_stripes = sub_stripes;
4218 num_bytes = stripe_size * data_stripes;
4220 trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4222 em = alloc_extent_map();
4227 em->bdev = (struct block_device *)map;
4229 em->len = num_bytes;
4230 em->block_start = 0;
4231 em->block_len = em->len;
4232 em->orig_block_len = stripe_size;
4234 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4235 write_lock(&em_tree->lock);
4236 ret = add_extent_mapping(em_tree, em, 0);
4238 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4239 atomic_inc(&em->refs);
4241 write_unlock(&em_tree->lock);
4243 free_extent_map(em);
4247 ret = btrfs_make_block_group(trans, extent_root, 0, type,
4248 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4251 goto error_del_extent;
4253 free_extent_map(em);
4254 check_raid56_incompat_flag(extent_root->fs_info, type);
4256 kfree(devices_info);
4260 write_lock(&em_tree->lock);
4261 remove_extent_mapping(em_tree, em);
4262 write_unlock(&em_tree->lock);
4264 /* One for our allocation */
4265 free_extent_map(em);
4266 /* One for the tree reference */
4267 free_extent_map(em);
4270 kfree(devices_info);
4274 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4275 struct btrfs_root *extent_root,
4276 u64 chunk_offset, u64 chunk_size)
4278 struct btrfs_key key;
4279 struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4280 struct btrfs_device *device;
4281 struct btrfs_chunk *chunk;
4282 struct btrfs_stripe *stripe;
4283 struct extent_map_tree *em_tree;
4284 struct extent_map *em;
4285 struct map_lookup *map;
4292 em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4293 read_lock(&em_tree->lock);
4294 em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4295 read_unlock(&em_tree->lock);
4298 btrfs_crit(extent_root->fs_info, "unable to find logical "
4299 "%Lu len %Lu", chunk_offset, chunk_size);
4303 if (em->start != chunk_offset || em->len != chunk_size) {
4304 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4305 " %Lu-%Lu, found %Lu-%Lu\n", chunk_offset,
4306 chunk_size, em->start, em->len);
4307 free_extent_map(em);
4311 map = (struct map_lookup *)em->bdev;
4312 item_size = btrfs_chunk_item_size(map->num_stripes);
4313 stripe_size = em->orig_block_len;
4315 chunk = kzalloc(item_size, GFP_NOFS);
4321 for (i = 0; i < map->num_stripes; i++) {
4322 device = map->stripes[i].dev;
4323 dev_offset = map->stripes[i].physical;
4325 device->bytes_used += stripe_size;
4326 ret = btrfs_update_device(trans, device);
4329 ret = btrfs_alloc_dev_extent(trans, device,
4330 chunk_root->root_key.objectid,
4331 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4332 chunk_offset, dev_offset,
4338 spin_lock(&extent_root->fs_info->free_chunk_lock);
4339 extent_root->fs_info->free_chunk_space -= (stripe_size *
4341 spin_unlock(&extent_root->fs_info->free_chunk_lock);
4343 stripe = &chunk->stripe;
4344 for (i = 0; i < map->num_stripes; i++) {
4345 device = map->stripes[i].dev;
4346 dev_offset = map->stripes[i].physical;
4348 btrfs_set_stack_stripe_devid(stripe, device->devid);
4349 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4350 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4354 btrfs_set_stack_chunk_length(chunk, chunk_size);
4355 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4356 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4357 btrfs_set_stack_chunk_type(chunk, map->type);
4358 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4359 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4360 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4361 btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4362 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4364 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4365 key.type = BTRFS_CHUNK_ITEM_KEY;
4366 key.offset = chunk_offset;
4368 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4369 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4371 * TODO: Cleanup of inserted chunk root in case of
4374 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4380 free_extent_map(em);
4385 * Chunk allocation falls into two parts. The first part does works
4386 * that make the new allocated chunk useable, but not do any operation
4387 * that modifies the chunk tree. The second part does the works that
4388 * require modifying the chunk tree. This division is important for the
4389 * bootstrap process of adding storage to a seed btrfs.
4391 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4392 struct btrfs_root *extent_root, u64 type)
4396 chunk_offset = find_next_chunk(extent_root->fs_info);
4397 return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4400 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4401 struct btrfs_root *root,
4402 struct btrfs_device *device)
4405 u64 sys_chunk_offset;
4407 struct btrfs_fs_info *fs_info = root->fs_info;
4408 struct btrfs_root *extent_root = fs_info->extent_root;
4411 chunk_offset = find_next_chunk(fs_info);
4412 alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4413 ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4418 sys_chunk_offset = find_next_chunk(root->fs_info);
4419 alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4420 ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4423 btrfs_abort_transaction(trans, root, ret);
4427 ret = btrfs_add_device(trans, fs_info->chunk_root, device);
4429 btrfs_abort_transaction(trans, root, ret);
4434 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4436 struct extent_map *em;
4437 struct map_lookup *map;
4438 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4442 read_lock(&map_tree->map_tree.lock);
4443 em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4444 read_unlock(&map_tree->map_tree.lock);
4448 if (btrfs_test_opt(root, DEGRADED)) {
4449 free_extent_map(em);
4453 map = (struct map_lookup *)em->bdev;
4454 for (i = 0; i < map->num_stripes; i++) {
4455 if (!map->stripes[i].dev->writeable) {
4460 free_extent_map(em);
4464 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
4466 extent_map_tree_init(&tree->map_tree);
4469 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
4471 struct extent_map *em;
4474 write_lock(&tree->map_tree.lock);
4475 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
4477 remove_extent_mapping(&tree->map_tree, em);
4478 write_unlock(&tree->map_tree.lock);
4483 free_extent_map(em);
4484 /* once for the tree */
4485 free_extent_map(em);
4489 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
4491 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4492 struct extent_map *em;
4493 struct map_lookup *map;
4494 struct extent_map_tree *em_tree = &map_tree->map_tree;
4497 read_lock(&em_tree->lock);
4498 em = lookup_extent_mapping(em_tree, logical, len);
4499 read_unlock(&em_tree->lock);
4502 * We could return errors for these cases, but that could get ugly and
4503 * we'd probably do the same thing which is just not do anything else
4504 * and exit, so return 1 so the callers don't try to use other copies.
4507 btrfs_crit(fs_info, "No mapping for %Lu-%Lu\n", logical,
4512 if (em->start > logical || em->start + em->len < logical) {
4513 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
4514 "%Lu-%Lu\n", logical, logical+len, em->start,
4515 em->start + em->len);
4516 free_extent_map(em);
4520 map = (struct map_lookup *)em->bdev;
4521 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
4522 ret = map->num_stripes;
4523 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
4524 ret = map->sub_stripes;
4525 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
4527 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4531 free_extent_map(em);
4533 btrfs_dev_replace_lock(&fs_info->dev_replace);
4534 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
4536 btrfs_dev_replace_unlock(&fs_info->dev_replace);
4541 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
4542 struct btrfs_mapping_tree *map_tree,
4545 struct extent_map *em;
4546 struct map_lookup *map;
4547 struct extent_map_tree *em_tree = &map_tree->map_tree;
4548 unsigned long len = root->sectorsize;
4550 read_lock(&em_tree->lock);
4551 em = lookup_extent_mapping(em_tree, logical, len);
4552 read_unlock(&em_tree->lock);
4555 BUG_ON(em->start > logical || em->start + em->len < logical);
4556 map = (struct map_lookup *)em->bdev;
4557 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4558 BTRFS_BLOCK_GROUP_RAID6)) {
4559 len = map->stripe_len * nr_data_stripes(map);
4561 free_extent_map(em);
4565 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
4566 u64 logical, u64 len, int mirror_num)
4568 struct extent_map *em;
4569 struct map_lookup *map;
4570 struct extent_map_tree *em_tree = &map_tree->map_tree;
4573 read_lock(&em_tree->lock);
4574 em = lookup_extent_mapping(em_tree, logical, len);
4575 read_unlock(&em_tree->lock);
4578 BUG_ON(em->start > logical || em->start + em->len < logical);
4579 map = (struct map_lookup *)em->bdev;
4580 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4581 BTRFS_BLOCK_GROUP_RAID6))
4583 free_extent_map(em);
4587 static int find_live_mirror(struct btrfs_fs_info *fs_info,
4588 struct map_lookup *map, int first, int num,
4589 int optimal, int dev_replace_is_ongoing)
4593 struct btrfs_device *srcdev;
4595 if (dev_replace_is_ongoing &&
4596 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
4597 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
4598 srcdev = fs_info->dev_replace.srcdev;
4603 * try to avoid the drive that is the source drive for a
4604 * dev-replace procedure, only choose it if no other non-missing
4605 * mirror is available
4607 for (tolerance = 0; tolerance < 2; tolerance++) {
4608 if (map->stripes[optimal].dev->bdev &&
4609 (tolerance || map->stripes[optimal].dev != srcdev))
4611 for (i = first; i < first + num; i++) {
4612 if (map->stripes[i].dev->bdev &&
4613 (tolerance || map->stripes[i].dev != srcdev))
4618 /* we couldn't find one that doesn't fail. Just return something
4619 * and the io error handling code will clean up eventually
4624 static inline int parity_smaller(u64 a, u64 b)
4629 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
4630 static void sort_parity_stripes(struct btrfs_bio *bbio, u64 *raid_map)
4632 struct btrfs_bio_stripe s;
4639 for (i = 0; i < bbio->num_stripes - 1; i++) {
4640 if (parity_smaller(raid_map[i], raid_map[i+1])) {
4641 s = bbio->stripes[i];
4643 bbio->stripes[i] = bbio->stripes[i+1];
4644 raid_map[i] = raid_map[i+1];
4645 bbio->stripes[i+1] = s;
4653 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
4654 u64 logical, u64 *length,
4655 struct btrfs_bio **bbio_ret,
4656 int mirror_num, u64 **raid_map_ret)
4658 struct extent_map *em;
4659 struct map_lookup *map;
4660 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
4661 struct extent_map_tree *em_tree = &map_tree->map_tree;
4664 u64 stripe_end_offset;
4669 u64 *raid_map = NULL;
4675 struct btrfs_bio *bbio = NULL;
4676 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
4677 int dev_replace_is_ongoing = 0;
4678 int num_alloc_stripes;
4679 int patch_the_first_stripe_for_dev_replace = 0;
4680 u64 physical_to_patch_in_first_stripe = 0;
4681 u64 raid56_full_stripe_start = (u64)-1;
4683 read_lock(&em_tree->lock);
4684 em = lookup_extent_mapping(em_tree, logical, *length);
4685 read_unlock(&em_tree->lock);
4688 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
4693 if (em->start > logical || em->start + em->len < logical) {
4694 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
4695 "found %Lu-%Lu\n", logical, em->start,
4696 em->start + em->len);
4697 free_extent_map(em);
4701 map = (struct map_lookup *)em->bdev;
4702 offset = logical - em->start;
4704 stripe_len = map->stripe_len;
4707 * stripe_nr counts the total number of stripes we have to stride
4708 * to get to this block
4710 do_div(stripe_nr, stripe_len);
4712 stripe_offset = stripe_nr * stripe_len;
4713 BUG_ON(offset < stripe_offset);
4715 /* stripe_offset is the offset of this block in its stripe*/
4716 stripe_offset = offset - stripe_offset;
4718 /* if we're here for raid56, we need to know the stripe aligned start */
4719 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4720 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
4721 raid56_full_stripe_start = offset;
4723 /* allow a write of a full stripe, but make sure we don't
4724 * allow straddling of stripes
4726 do_div(raid56_full_stripe_start, full_stripe_len);
4727 raid56_full_stripe_start *= full_stripe_len;
4730 if (rw & REQ_DISCARD) {
4731 /* we don't discard raid56 yet */
4733 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6)) {
4737 *length = min_t(u64, em->len - offset, *length);
4738 } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
4740 /* For writes to RAID[56], allow a full stripeset across all disks.
4741 For other RAID types and for RAID[56] reads, just allow a single
4742 stripe (on a single disk). */
4743 if (map->type & (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6) &&
4745 max_len = stripe_len * nr_data_stripes(map) -
4746 (offset - raid56_full_stripe_start);
4748 /* we limit the length of each bio to what fits in a stripe */
4749 max_len = stripe_len - stripe_offset;
4751 *length = min_t(u64, em->len - offset, max_len);
4753 *length = em->len - offset;
4756 /* This is for when we're called from btrfs_merge_bio_hook() and all
4757 it cares about is the length */
4761 btrfs_dev_replace_lock(dev_replace);
4762 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
4763 if (!dev_replace_is_ongoing)
4764 btrfs_dev_replace_unlock(dev_replace);
4766 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
4767 !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
4768 dev_replace->tgtdev != NULL) {
4770 * in dev-replace case, for repair case (that's the only
4771 * case where the mirror is selected explicitly when
4772 * calling btrfs_map_block), blocks left of the left cursor
4773 * can also be read from the target drive.
4774 * For REQ_GET_READ_MIRRORS, the target drive is added as
4775 * the last one to the array of stripes. For READ, it also
4776 * needs to be supported using the same mirror number.
4777 * If the requested block is not left of the left cursor,
4778 * EIO is returned. This can happen because btrfs_num_copies()
4779 * returns one more in the dev-replace case.
4781 u64 tmp_length = *length;
4782 struct btrfs_bio *tmp_bbio = NULL;
4783 int tmp_num_stripes;
4784 u64 srcdev_devid = dev_replace->srcdev->devid;
4785 int index_srcdev = 0;
4787 u64 physical_of_found = 0;
4789 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
4790 logical, &tmp_length, &tmp_bbio, 0, NULL);
4792 WARN_ON(tmp_bbio != NULL);
4796 tmp_num_stripes = tmp_bbio->num_stripes;
4797 if (mirror_num > tmp_num_stripes) {
4799 * REQ_GET_READ_MIRRORS does not contain this
4800 * mirror, that means that the requested area
4801 * is not left of the left cursor
4809 * process the rest of the function using the mirror_num
4810 * of the source drive. Therefore look it up first.
4811 * At the end, patch the device pointer to the one of the
4814 for (i = 0; i < tmp_num_stripes; i++) {
4815 if (tmp_bbio->stripes[i].dev->devid == srcdev_devid) {
4817 * In case of DUP, in order to keep it
4818 * simple, only add the mirror with the
4819 * lowest physical address
4822 physical_of_found <=
4823 tmp_bbio->stripes[i].physical)
4828 tmp_bbio->stripes[i].physical;
4833 mirror_num = index_srcdev + 1;
4834 patch_the_first_stripe_for_dev_replace = 1;
4835 physical_to_patch_in_first_stripe = physical_of_found;
4844 } else if (mirror_num > map->num_stripes) {
4850 stripe_nr_orig = stripe_nr;
4851 stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
4852 do_div(stripe_nr_end, map->stripe_len);
4853 stripe_end_offset = stripe_nr_end * map->stripe_len -
4856 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
4857 if (rw & REQ_DISCARD)
4858 num_stripes = min_t(u64, map->num_stripes,
4859 stripe_nr_end - stripe_nr_orig);
4860 stripe_index = do_div(stripe_nr, map->num_stripes);
4861 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
4862 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
4863 num_stripes = map->num_stripes;
4864 else if (mirror_num)
4865 stripe_index = mirror_num - 1;
4867 stripe_index = find_live_mirror(fs_info, map, 0,
4869 current->pid % map->num_stripes,
4870 dev_replace_is_ongoing);
4871 mirror_num = stripe_index + 1;
4874 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
4875 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
4876 num_stripes = map->num_stripes;
4877 } else if (mirror_num) {
4878 stripe_index = mirror_num - 1;
4883 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
4884 int factor = map->num_stripes / map->sub_stripes;
4886 stripe_index = do_div(stripe_nr, factor);
4887 stripe_index *= map->sub_stripes;
4889 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
4890 num_stripes = map->sub_stripes;
4891 else if (rw & REQ_DISCARD)
4892 num_stripes = min_t(u64, map->sub_stripes *
4893 (stripe_nr_end - stripe_nr_orig),
4895 else if (mirror_num)
4896 stripe_index += mirror_num - 1;
4898 int old_stripe_index = stripe_index;
4899 stripe_index = find_live_mirror(fs_info, map,
4901 map->sub_stripes, stripe_index +
4902 current->pid % map->sub_stripes,
4903 dev_replace_is_ongoing);
4904 mirror_num = stripe_index - old_stripe_index + 1;
4907 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
4908 BTRFS_BLOCK_GROUP_RAID6)) {
4911 if (bbio_ret && ((rw & REQ_WRITE) || mirror_num > 1)
4915 /* push stripe_nr back to the start of the full stripe */
4916 stripe_nr = raid56_full_stripe_start;
4917 do_div(stripe_nr, stripe_len);
4919 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
4921 /* RAID[56] write or recovery. Return all stripes */
4922 num_stripes = map->num_stripes;
4923 max_errors = nr_parity_stripes(map);
4925 raid_map = kmalloc_array(num_stripes, sizeof(u64),
4932 /* Work out the disk rotation on this stripe-set */
4934 rot = do_div(tmp, num_stripes);
4936 /* Fill in the logical address of each stripe */
4937 tmp = stripe_nr * nr_data_stripes(map);
4938 for (i = 0; i < nr_data_stripes(map); i++)
4939 raid_map[(i+rot) % num_stripes] =
4940 em->start + (tmp + i) * map->stripe_len;
4942 raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
4943 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
4944 raid_map[(i+rot+1) % num_stripes] =
4947 *length = map->stripe_len;
4952 * Mirror #0 or #1 means the original data block.
4953 * Mirror #2 is RAID5 parity block.
4954 * Mirror #3 is RAID6 Q block.
4956 stripe_index = do_div(stripe_nr, nr_data_stripes(map));
4958 stripe_index = nr_data_stripes(map) +
4961 /* We distribute the parity blocks across stripes */
4962 tmp = stripe_nr + stripe_index;
4963 stripe_index = do_div(tmp, map->num_stripes);
4967 * after this do_div call, stripe_nr is the number of stripes
4968 * on this device we have to walk to find the data, and
4969 * stripe_index is the number of our device in the stripe array
4971 stripe_index = do_div(stripe_nr, map->num_stripes);
4972 mirror_num = stripe_index + 1;
4974 BUG_ON(stripe_index >= map->num_stripes);
4976 num_alloc_stripes = num_stripes;
4977 if (dev_replace_is_ongoing) {
4978 if (rw & (REQ_WRITE | REQ_DISCARD))
4979 num_alloc_stripes <<= 1;
4980 if (rw & REQ_GET_READ_MIRRORS)
4981 num_alloc_stripes++;
4983 bbio = kzalloc(btrfs_bio_size(num_alloc_stripes), GFP_NOFS);
4989 atomic_set(&bbio->error, 0);
4991 if (rw & REQ_DISCARD) {
4993 int sub_stripes = 0;
4994 u64 stripes_per_dev = 0;
4995 u32 remaining_stripes = 0;
4996 u32 last_stripe = 0;
4999 (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5000 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5003 sub_stripes = map->sub_stripes;
5005 factor = map->num_stripes / sub_stripes;
5006 stripes_per_dev = div_u64_rem(stripe_nr_end -
5009 &remaining_stripes);
5010 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5011 last_stripe *= sub_stripes;
5014 for (i = 0; i < num_stripes; i++) {
5015 bbio->stripes[i].physical =
5016 map->stripes[stripe_index].physical +
5017 stripe_offset + stripe_nr * map->stripe_len;
5018 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5020 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5021 BTRFS_BLOCK_GROUP_RAID10)) {
5022 bbio->stripes[i].length = stripes_per_dev *
5025 if (i / sub_stripes < remaining_stripes)
5026 bbio->stripes[i].length +=
5030 * Special for the first stripe and
5033 * |-------|...|-------|
5037 if (i < sub_stripes)
5038 bbio->stripes[i].length -=
5041 if (stripe_index >= last_stripe &&
5042 stripe_index <= (last_stripe +
5044 bbio->stripes[i].length -=
5047 if (i == sub_stripes - 1)
5050 bbio->stripes[i].length = *length;
5053 if (stripe_index == map->num_stripes) {
5054 /* This could only happen for RAID0/10 */
5060 for (i = 0; i < num_stripes; i++) {
5061 bbio->stripes[i].physical =
5062 map->stripes[stripe_index].physical +
5064 stripe_nr * map->stripe_len;
5065 bbio->stripes[i].dev =
5066 map->stripes[stripe_index].dev;
5071 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) {
5072 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5073 BTRFS_BLOCK_GROUP_RAID10 |
5074 BTRFS_BLOCK_GROUP_RAID5 |
5075 BTRFS_BLOCK_GROUP_DUP)) {
5077 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5082 if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5083 dev_replace->tgtdev != NULL) {
5084 int index_where_to_add;
5085 u64 srcdev_devid = dev_replace->srcdev->devid;
5088 * duplicate the write operations while the dev replace
5089 * procedure is running. Since the copying of the old disk
5090 * to the new disk takes place at run time while the
5091 * filesystem is mounted writable, the regular write
5092 * operations to the old disk have to be duplicated to go
5093 * to the new disk as well.
5094 * Note that device->missing is handled by the caller, and
5095 * that the write to the old disk is already set up in the
5098 index_where_to_add = num_stripes;
5099 for (i = 0; i < num_stripes; i++) {
5100 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5101 /* write to new disk, too */
5102 struct btrfs_bio_stripe *new =
5103 bbio->stripes + index_where_to_add;
5104 struct btrfs_bio_stripe *old =
5107 new->physical = old->physical;
5108 new->length = old->length;
5109 new->dev = dev_replace->tgtdev;
5110 index_where_to_add++;
5114 num_stripes = index_where_to_add;
5115 } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5116 dev_replace->tgtdev != NULL) {
5117 u64 srcdev_devid = dev_replace->srcdev->devid;
5118 int index_srcdev = 0;
5120 u64 physical_of_found = 0;
5123 * During the dev-replace procedure, the target drive can
5124 * also be used to read data in case it is needed to repair
5125 * a corrupt block elsewhere. This is possible if the
5126 * requested area is left of the left cursor. In this area,
5127 * the target drive is a full copy of the source drive.
5129 for (i = 0; i < num_stripes; i++) {
5130 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5132 * In case of DUP, in order to keep it
5133 * simple, only add the mirror with the
5134 * lowest physical address
5137 physical_of_found <=
5138 bbio->stripes[i].physical)
5142 physical_of_found = bbio->stripes[i].physical;
5146 u64 length = map->stripe_len;
5148 if (physical_of_found + length <=
5149 dev_replace->cursor_left) {
5150 struct btrfs_bio_stripe *tgtdev_stripe =
5151 bbio->stripes + num_stripes;
5153 tgtdev_stripe->physical = physical_of_found;
5154 tgtdev_stripe->length =
5155 bbio->stripes[index_srcdev].length;
5156 tgtdev_stripe->dev = dev_replace->tgtdev;
5164 bbio->num_stripes = num_stripes;
5165 bbio->max_errors = max_errors;
5166 bbio->mirror_num = mirror_num;
5169 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5170 * mirror_num == num_stripes + 1 && dev_replace target drive is
5171 * available as a mirror
5173 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5174 WARN_ON(num_stripes > 1);
5175 bbio->stripes[0].dev = dev_replace->tgtdev;
5176 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5177 bbio->mirror_num = map->num_stripes + 1;
5180 sort_parity_stripes(bbio, raid_map);
5181 *raid_map_ret = raid_map;
5184 if (dev_replace_is_ongoing)
5185 btrfs_dev_replace_unlock(dev_replace);
5186 free_extent_map(em);
5190 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5191 u64 logical, u64 *length,
5192 struct btrfs_bio **bbio_ret, int mirror_num)
5194 return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5198 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5199 u64 chunk_start, u64 physical, u64 devid,
5200 u64 **logical, int *naddrs, int *stripe_len)
5202 struct extent_map_tree *em_tree = &map_tree->map_tree;
5203 struct extent_map *em;
5204 struct map_lookup *map;
5212 read_lock(&em_tree->lock);
5213 em = lookup_extent_mapping(em_tree, chunk_start, 1);
5214 read_unlock(&em_tree->lock);
5217 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5222 if (em->start != chunk_start) {
5223 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5224 em->start, chunk_start);
5225 free_extent_map(em);
5228 map = (struct map_lookup *)em->bdev;
5231 rmap_len = map->stripe_len;
5233 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5234 do_div(length, map->num_stripes / map->sub_stripes);
5235 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5236 do_div(length, map->num_stripes);
5237 else if (map->type & (BTRFS_BLOCK_GROUP_RAID5 |
5238 BTRFS_BLOCK_GROUP_RAID6)) {
5239 do_div(length, nr_data_stripes(map));
5240 rmap_len = map->stripe_len * nr_data_stripes(map);
5243 buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
5244 BUG_ON(!buf); /* -ENOMEM */
5246 for (i = 0; i < map->num_stripes; i++) {
5247 if (devid && map->stripes[i].dev->devid != devid)
5249 if (map->stripes[i].physical > physical ||
5250 map->stripes[i].physical + length <= physical)
5253 stripe_nr = physical - map->stripes[i].physical;
5254 do_div(stripe_nr, map->stripe_len);
5256 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5257 stripe_nr = stripe_nr * map->num_stripes + i;
5258 do_div(stripe_nr, map->sub_stripes);
5259 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5260 stripe_nr = stripe_nr * map->num_stripes + i;
5261 } /* else if RAID[56], multiply by nr_data_stripes().
5262 * Alternatively, just use rmap_len below instead of
5263 * map->stripe_len */
5265 bytenr = chunk_start + stripe_nr * rmap_len;
5266 WARN_ON(nr >= map->num_stripes);
5267 for (j = 0; j < nr; j++) {
5268 if (buf[j] == bytenr)
5272 WARN_ON(nr >= map->num_stripes);
5279 *stripe_len = rmap_len;
5281 free_extent_map(em);
5285 static void btrfs_end_bio(struct bio *bio, int err)
5287 struct btrfs_bio *bbio = bio->bi_private;
5288 int is_orig_bio = 0;
5291 atomic_inc(&bbio->error);
5292 if (err == -EIO || err == -EREMOTEIO) {
5293 unsigned int stripe_index =
5294 btrfs_io_bio(bio)->stripe_index;
5295 struct btrfs_device *dev;
5297 BUG_ON(stripe_index >= bbio->num_stripes);
5298 dev = bbio->stripes[stripe_index].dev;
5300 if (bio->bi_rw & WRITE)
5301 btrfs_dev_stat_inc(dev,
5302 BTRFS_DEV_STAT_WRITE_ERRS);
5304 btrfs_dev_stat_inc(dev,
5305 BTRFS_DEV_STAT_READ_ERRS);
5306 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5307 btrfs_dev_stat_inc(dev,
5308 BTRFS_DEV_STAT_FLUSH_ERRS);
5309 btrfs_dev_stat_print_on_error(dev);
5314 if (bio == bbio->orig_bio)
5317 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5320 bio = bbio->orig_bio;
5324 * We have original bio now. So increment bi_remaining to
5325 * account for it in endio
5327 atomic_inc(&bio->bi_remaining);
5329 bio->bi_private = bbio->private;
5330 bio->bi_end_io = bbio->end_io;
5331 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5332 /* only send an error to the higher layers if it is
5333 * beyond the tolerance of the btrfs bio
5335 if (atomic_read(&bbio->error) > bbio->max_errors) {
5339 * this bio is actually up to date, we didn't
5340 * go over the max number of errors
5342 set_bit(BIO_UPTODATE, &bio->bi_flags);
5347 bio_endio(bio, err);
5348 } else if (!is_orig_bio) {
5353 struct async_sched {
5356 struct btrfs_fs_info *info;
5357 struct btrfs_work work;
5361 * see run_scheduled_bios for a description of why bios are collected for
5364 * This will add one bio to the pending list for a device and make sure
5365 * the work struct is scheduled.
5367 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5368 struct btrfs_device *device,
5369 int rw, struct bio *bio)
5371 int should_queue = 1;
5372 struct btrfs_pending_bios *pending_bios;
5374 if (device->missing || !device->bdev) {
5375 bio_endio(bio, -EIO);
5379 /* don't bother with additional async steps for reads, right now */
5380 if (!(rw & REQ_WRITE)) {
5382 btrfsic_submit_bio(rw, bio);
5388 * nr_async_bios allows us to reliably return congestion to the
5389 * higher layers. Otherwise, the async bio makes it appear we have
5390 * made progress against dirty pages when we've really just put it
5391 * on a queue for later
5393 atomic_inc(&root->fs_info->nr_async_bios);
5394 WARN_ON(bio->bi_next);
5395 bio->bi_next = NULL;
5398 spin_lock(&device->io_lock);
5399 if (bio->bi_rw & REQ_SYNC)
5400 pending_bios = &device->pending_sync_bios;
5402 pending_bios = &device->pending_bios;
5404 if (pending_bios->tail)
5405 pending_bios->tail->bi_next = bio;
5407 pending_bios->tail = bio;
5408 if (!pending_bios->head)
5409 pending_bios->head = bio;
5410 if (device->running_pending)
5413 spin_unlock(&device->io_lock);
5416 btrfs_queue_worker(&root->fs_info->submit_workers,
5420 static int bio_size_ok(struct block_device *bdev, struct bio *bio,
5423 struct bio_vec *prev;
5424 struct request_queue *q = bdev_get_queue(bdev);
5425 unsigned int max_sectors = queue_max_sectors(q);
5426 struct bvec_merge_data bvm = {
5428 .bi_sector = sector,
5429 .bi_rw = bio->bi_rw,
5432 if (WARN_ON(bio->bi_vcnt == 0))
5435 prev = &bio->bi_io_vec[bio->bi_vcnt - 1];
5436 if (bio_sectors(bio) > max_sectors)
5439 if (!q->merge_bvec_fn)
5442 bvm.bi_size = bio->bi_iter.bi_size - prev->bv_len;
5443 if (q->merge_bvec_fn(q, &bvm, prev) < prev->bv_len)
5448 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5449 struct bio *bio, u64 physical, int dev_nr,
5452 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
5454 bio->bi_private = bbio;
5455 btrfs_io_bio(bio)->stripe_index = dev_nr;
5456 bio->bi_end_io = btrfs_end_bio;
5457 bio->bi_iter.bi_sector = physical >> 9;
5460 struct rcu_string *name;
5463 name = rcu_dereference(dev->name);
5464 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
5465 "(%s id %llu), size=%u\n", rw,
5466 (u64)bio->bi_sector, (u_long)dev->bdev->bd_dev,
5467 name->str, dev->devid, bio->bi_size);
5471 bio->bi_bdev = dev->bdev;
5473 btrfs_schedule_bio(root, dev, rw, bio);
5475 btrfsic_submit_bio(rw, bio);
5478 static int breakup_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
5479 struct bio *first_bio, struct btrfs_device *dev,
5480 int dev_nr, int rw, int async)
5482 struct bio_vec *bvec = first_bio->bi_io_vec;
5484 int nr_vecs = bio_get_nr_vecs(dev->bdev);
5485 u64 physical = bbio->stripes[dev_nr].physical;
5488 bio = btrfs_bio_alloc(dev->bdev, physical >> 9, nr_vecs, GFP_NOFS);
5492 while (bvec <= (first_bio->bi_io_vec + first_bio->bi_vcnt - 1)) {
5493 if (bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5494 bvec->bv_offset) < bvec->bv_len) {
5495 u64 len = bio->bi_iter.bi_size;
5497 atomic_inc(&bbio->stripes_pending);
5498 submit_stripe_bio(root, bbio, bio, physical, dev_nr,
5506 submit_stripe_bio(root, bbio, bio, physical, dev_nr, rw, async);
5510 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
5512 atomic_inc(&bbio->error);
5513 if (atomic_dec_and_test(&bbio->stripes_pending)) {
5514 bio->bi_private = bbio->private;
5515 bio->bi_end_io = bbio->end_io;
5516 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5517 bio->bi_iter.bi_sector = logical >> 9;
5519 bio_endio(bio, -EIO);
5523 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
5524 int mirror_num, int async_submit)
5526 struct btrfs_device *dev;
5527 struct bio *first_bio = bio;
5528 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
5531 u64 *raid_map = NULL;
5535 struct btrfs_bio *bbio = NULL;
5537 length = bio->bi_iter.bi_size;
5538 map_length = length;
5540 ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
5541 mirror_num, &raid_map);
5542 if (ret) /* -ENOMEM */
5545 total_devs = bbio->num_stripes;
5546 bbio->orig_bio = first_bio;
5547 bbio->private = first_bio->bi_private;
5548 bbio->end_io = first_bio->bi_end_io;
5549 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
5552 /* In this case, map_length has been set to the length of
5553 a single stripe; not the whole write */
5555 return raid56_parity_write(root, bio, bbio,
5556 raid_map, map_length);
5558 return raid56_parity_recover(root, bio, bbio,
5559 raid_map, map_length,
5564 if (map_length < length) {
5565 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
5566 logical, length, map_length);
5570 while (dev_nr < total_devs) {
5571 dev = bbio->stripes[dev_nr].dev;
5572 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
5573 bbio_error(bbio, first_bio, logical);
5579 * Check and see if we're ok with this bio based on it's size
5580 * and offset with the given device.
5582 if (!bio_size_ok(dev->bdev, first_bio,
5583 bbio->stripes[dev_nr].physical >> 9)) {
5584 ret = breakup_stripe_bio(root, bbio, first_bio, dev,
5585 dev_nr, rw, async_submit);
5591 if (dev_nr < total_devs - 1) {
5592 bio = btrfs_bio_clone(first_bio, GFP_NOFS);
5593 BUG_ON(!bio); /* -ENOMEM */
5598 submit_stripe_bio(root, bbio, bio,
5599 bbio->stripes[dev_nr].physical, dev_nr, rw,
5606 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
5609 struct btrfs_device *device;
5610 struct btrfs_fs_devices *cur_devices;
5612 cur_devices = fs_info->fs_devices;
5613 while (cur_devices) {
5615 !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5616 device = __find_device(&cur_devices->devices,
5621 cur_devices = cur_devices->seed;
5626 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
5627 u64 devid, u8 *dev_uuid)
5629 struct btrfs_device *device;
5630 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5632 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
5636 list_add(&device->dev_list, &fs_devices->devices);
5637 device->fs_devices = fs_devices;
5638 fs_devices->num_devices++;
5640 device->missing = 1;
5641 fs_devices->missing_devices++;
5647 * btrfs_alloc_device - allocate struct btrfs_device
5648 * @fs_info: used only for generating a new devid, can be NULL if
5649 * devid is provided (i.e. @devid != NULL).
5650 * @devid: a pointer to devid for this device. If NULL a new devid
5652 * @uuid: a pointer to UUID for this device. If NULL a new UUID
5655 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
5656 * on error. Returned struct is not linked onto any lists and can be
5657 * destroyed with kfree() right away.
5659 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
5663 struct btrfs_device *dev;
5666 if (WARN_ON(!devid && !fs_info))
5667 return ERR_PTR(-EINVAL);
5669 dev = __alloc_device();
5678 ret = find_next_devid(fs_info, &tmp);
5681 return ERR_PTR(ret);
5687 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
5689 generate_random_uuid(dev->uuid);
5691 dev->work.func = pending_bios_fn;
5696 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
5697 struct extent_buffer *leaf,
5698 struct btrfs_chunk *chunk)
5700 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5701 struct map_lookup *map;
5702 struct extent_map *em;
5706 u8 uuid[BTRFS_UUID_SIZE];
5711 logical = key->offset;
5712 length = btrfs_chunk_length(leaf, chunk);
5714 read_lock(&map_tree->map_tree.lock);
5715 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
5716 read_unlock(&map_tree->map_tree.lock);
5718 /* already mapped? */
5719 if (em && em->start <= logical && em->start + em->len > logical) {
5720 free_extent_map(em);
5723 free_extent_map(em);
5726 em = alloc_extent_map();
5729 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
5730 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5732 free_extent_map(em);
5736 em->bdev = (struct block_device *)map;
5737 em->start = logical;
5740 em->block_start = 0;
5741 em->block_len = em->len;
5743 map->num_stripes = num_stripes;
5744 map->io_width = btrfs_chunk_io_width(leaf, chunk);
5745 map->io_align = btrfs_chunk_io_align(leaf, chunk);
5746 map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
5747 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
5748 map->type = btrfs_chunk_type(leaf, chunk);
5749 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
5750 for (i = 0; i < num_stripes; i++) {
5751 map->stripes[i].physical =
5752 btrfs_stripe_offset_nr(leaf, chunk, i);
5753 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
5754 read_extent_buffer(leaf, uuid, (unsigned long)
5755 btrfs_stripe_dev_uuid_nr(chunk, i),
5757 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
5759 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
5761 free_extent_map(em);
5764 if (!map->stripes[i].dev) {
5765 map->stripes[i].dev =
5766 add_missing_dev(root, devid, uuid);
5767 if (!map->stripes[i].dev) {
5769 free_extent_map(em);
5773 map->stripes[i].dev->in_fs_metadata = 1;
5776 write_lock(&map_tree->map_tree.lock);
5777 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
5778 write_unlock(&map_tree->map_tree.lock);
5779 BUG_ON(ret); /* Tree corruption */
5780 free_extent_map(em);
5785 static void fill_device_from_item(struct extent_buffer *leaf,
5786 struct btrfs_dev_item *dev_item,
5787 struct btrfs_device *device)
5791 device->devid = btrfs_device_id(leaf, dev_item);
5792 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
5793 device->total_bytes = device->disk_total_bytes;
5794 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
5795 device->type = btrfs_device_type(leaf, dev_item);
5796 device->io_align = btrfs_device_io_align(leaf, dev_item);
5797 device->io_width = btrfs_device_io_width(leaf, dev_item);
5798 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
5799 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
5800 device->is_tgtdev_for_dev_replace = 0;
5802 ptr = btrfs_device_uuid(dev_item);
5803 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
5806 static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
5808 struct btrfs_fs_devices *fs_devices;
5811 BUG_ON(!mutex_is_locked(&uuid_mutex));
5813 fs_devices = root->fs_info->fs_devices->seed;
5814 while (fs_devices) {
5815 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
5819 fs_devices = fs_devices->seed;
5822 fs_devices = find_fsid(fsid);
5828 fs_devices = clone_fs_devices(fs_devices);
5829 if (IS_ERR(fs_devices)) {
5830 ret = PTR_ERR(fs_devices);
5834 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
5835 root->fs_info->bdev_holder);
5837 free_fs_devices(fs_devices);
5841 if (!fs_devices->seeding) {
5842 __btrfs_close_devices(fs_devices);
5843 free_fs_devices(fs_devices);
5848 fs_devices->seed = root->fs_info->fs_devices->seed;
5849 root->fs_info->fs_devices->seed = fs_devices;
5854 static int read_one_dev(struct btrfs_root *root,
5855 struct extent_buffer *leaf,
5856 struct btrfs_dev_item *dev_item)
5858 struct btrfs_device *device;
5861 u8 fs_uuid[BTRFS_UUID_SIZE];
5862 u8 dev_uuid[BTRFS_UUID_SIZE];
5864 devid = btrfs_device_id(leaf, dev_item);
5865 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
5867 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
5870 if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
5871 ret = open_seed_devices(root, fs_uuid);
5872 if (ret && !btrfs_test_opt(root, DEGRADED))
5876 device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
5877 if (!device || !device->bdev) {
5878 if (!btrfs_test_opt(root, DEGRADED))
5882 btrfs_warn(root->fs_info, "devid %llu missing", devid);
5883 device = add_missing_dev(root, devid, dev_uuid);
5886 } else if (!device->missing) {
5888 * this happens when a device that was properly setup
5889 * in the device info lists suddenly goes bad.
5890 * device->bdev is NULL, and so we have to set
5891 * device->missing to one here
5893 root->fs_info->fs_devices->missing_devices++;
5894 device->missing = 1;
5898 if (device->fs_devices != root->fs_info->fs_devices) {
5899 BUG_ON(device->writeable);
5900 if (device->generation !=
5901 btrfs_device_generation(leaf, dev_item))
5905 fill_device_from_item(leaf, dev_item, device);
5906 device->in_fs_metadata = 1;
5907 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
5908 device->fs_devices->total_rw_bytes += device->total_bytes;
5909 spin_lock(&root->fs_info->free_chunk_lock);
5910 root->fs_info->free_chunk_space += device->total_bytes -
5912 spin_unlock(&root->fs_info->free_chunk_lock);
5918 int btrfs_read_sys_array(struct btrfs_root *root)
5920 struct btrfs_super_block *super_copy = root->fs_info->super_copy;
5921 struct extent_buffer *sb;
5922 struct btrfs_disk_key *disk_key;
5923 struct btrfs_chunk *chunk;
5925 unsigned long sb_ptr;
5931 struct btrfs_key key;
5933 sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
5934 BTRFS_SUPER_INFO_SIZE);
5937 btrfs_set_buffer_uptodate(sb);
5938 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
5940 * The sb extent buffer is artifical and just used to read the system array.
5941 * btrfs_set_buffer_uptodate() call does not properly mark all it's
5942 * pages up-to-date when the page is larger: extent does not cover the
5943 * whole page and consequently check_page_uptodate does not find all
5944 * the page's extents up-to-date (the hole beyond sb),
5945 * write_extent_buffer then triggers a WARN_ON.
5947 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
5948 * but sb spans only this function. Add an explicit SetPageUptodate call
5949 * to silence the warning eg. on PowerPC 64.
5951 if (PAGE_CACHE_SIZE > BTRFS_SUPER_INFO_SIZE)
5952 SetPageUptodate(sb->pages[0]);
5954 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
5955 array_size = btrfs_super_sys_array_size(super_copy);
5957 ptr = super_copy->sys_chunk_array;
5958 sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
5961 while (cur < array_size) {
5962 disk_key = (struct btrfs_disk_key *)ptr;
5963 btrfs_disk_key_to_cpu(&key, disk_key);
5965 len = sizeof(*disk_key); ptr += len;
5969 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5970 chunk = (struct btrfs_chunk *)sb_ptr;
5971 ret = read_one_chunk(root, &key, sb, chunk);
5974 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
5975 len = btrfs_chunk_item_size(num_stripes);
5984 free_extent_buffer(sb);
5988 int btrfs_read_chunk_tree(struct btrfs_root *root)
5990 struct btrfs_path *path;
5991 struct extent_buffer *leaf;
5992 struct btrfs_key key;
5993 struct btrfs_key found_key;
5997 root = root->fs_info->chunk_root;
5999 path = btrfs_alloc_path();
6003 mutex_lock(&uuid_mutex);
6007 * Read all device items, and then all the chunk items. All
6008 * device items are found before any chunk item (their object id
6009 * is smaller than the lowest possible object id for a chunk
6010 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6012 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6015 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6019 leaf = path->nodes[0];
6020 slot = path->slots[0];
6021 if (slot >= btrfs_header_nritems(leaf)) {
6022 ret = btrfs_next_leaf(root, path);
6029 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6030 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6031 struct btrfs_dev_item *dev_item;
6032 dev_item = btrfs_item_ptr(leaf, slot,
6033 struct btrfs_dev_item);
6034 ret = read_one_dev(root, leaf, dev_item);
6037 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6038 struct btrfs_chunk *chunk;
6039 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6040 ret = read_one_chunk(root, &found_key, leaf, chunk);
6048 unlock_chunks(root);
6049 mutex_unlock(&uuid_mutex);
6051 btrfs_free_path(path);
6055 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6057 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6058 struct btrfs_device *device;
6060 while (fs_devices) {
6061 mutex_lock(&fs_devices->device_list_mutex);
6062 list_for_each_entry(device, &fs_devices->devices, dev_list)
6063 device->dev_root = fs_info->dev_root;
6064 mutex_unlock(&fs_devices->device_list_mutex);
6066 fs_devices = fs_devices->seed;
6070 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6074 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6075 btrfs_dev_stat_reset(dev, i);
6078 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6080 struct btrfs_key key;
6081 struct btrfs_key found_key;
6082 struct btrfs_root *dev_root = fs_info->dev_root;
6083 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6084 struct extent_buffer *eb;
6087 struct btrfs_device *device;
6088 struct btrfs_path *path = NULL;
6091 path = btrfs_alloc_path();
6097 mutex_lock(&fs_devices->device_list_mutex);
6098 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6100 struct btrfs_dev_stats_item *ptr;
6103 key.type = BTRFS_DEV_STATS_KEY;
6104 key.offset = device->devid;
6105 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6107 __btrfs_reset_dev_stats(device);
6108 device->dev_stats_valid = 1;
6109 btrfs_release_path(path);
6112 slot = path->slots[0];
6113 eb = path->nodes[0];
6114 btrfs_item_key_to_cpu(eb, &found_key, slot);
6115 item_size = btrfs_item_size_nr(eb, slot);
6117 ptr = btrfs_item_ptr(eb, slot,
6118 struct btrfs_dev_stats_item);
6120 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6121 if (item_size >= (1 + i) * sizeof(__le64))
6122 btrfs_dev_stat_set(device, i,
6123 btrfs_dev_stats_value(eb, ptr, i));
6125 btrfs_dev_stat_reset(device, i);
6128 device->dev_stats_valid = 1;
6129 btrfs_dev_stat_print_on_load(device);
6130 btrfs_release_path(path);
6132 mutex_unlock(&fs_devices->device_list_mutex);
6135 btrfs_free_path(path);
6136 return ret < 0 ? ret : 0;
6139 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6140 struct btrfs_root *dev_root,
6141 struct btrfs_device *device)
6143 struct btrfs_path *path;
6144 struct btrfs_key key;
6145 struct extent_buffer *eb;
6146 struct btrfs_dev_stats_item *ptr;
6151 key.type = BTRFS_DEV_STATS_KEY;
6152 key.offset = device->devid;
6154 path = btrfs_alloc_path();
6156 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6158 printk_in_rcu(KERN_WARNING "BTRFS: "
6159 "error %d while searching for dev_stats item for device %s!\n",
6160 ret, rcu_str_deref(device->name));
6165 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6166 /* need to delete old one and insert a new one */
6167 ret = btrfs_del_item(trans, dev_root, path);
6169 printk_in_rcu(KERN_WARNING "BTRFS: "
6170 "delete too small dev_stats item for device %s failed %d!\n",
6171 rcu_str_deref(device->name), ret);
6178 /* need to insert a new item */
6179 btrfs_release_path(path);
6180 ret = btrfs_insert_empty_item(trans, dev_root, path,
6181 &key, sizeof(*ptr));
6183 printk_in_rcu(KERN_WARNING "BTRFS: "
6184 "insert dev_stats item for device %s failed %d!\n",
6185 rcu_str_deref(device->name), ret);
6190 eb = path->nodes[0];
6191 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6192 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6193 btrfs_set_dev_stats_value(eb, ptr, i,
6194 btrfs_dev_stat_read(device, i));
6195 btrfs_mark_buffer_dirty(eb);
6198 btrfs_free_path(path);
6203 * called from commit_transaction. Writes all changed device stats to disk.
6205 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6206 struct btrfs_fs_info *fs_info)
6208 struct btrfs_root *dev_root = fs_info->dev_root;
6209 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6210 struct btrfs_device *device;
6213 mutex_lock(&fs_devices->device_list_mutex);
6214 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6215 if (!device->dev_stats_valid || !device->dev_stats_dirty)
6218 ret = update_dev_stat_item(trans, dev_root, device);
6220 device->dev_stats_dirty = 0;
6222 mutex_unlock(&fs_devices->device_list_mutex);
6227 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6229 btrfs_dev_stat_inc(dev, index);
6230 btrfs_dev_stat_print_on_error(dev);
6233 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6235 if (!dev->dev_stats_valid)
6237 printk_ratelimited_in_rcu(KERN_ERR "BTRFS: "
6238 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6239 rcu_str_deref(dev->name),
6240 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6241 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6242 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6243 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6244 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6247 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6251 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6252 if (btrfs_dev_stat_read(dev, i) != 0)
6254 if (i == BTRFS_DEV_STAT_VALUES_MAX)
6255 return; /* all values == 0, suppress message */
6257 printk_in_rcu(KERN_INFO "BTRFS: "
6258 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u\n",
6259 rcu_str_deref(dev->name),
6260 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6261 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6262 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6263 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6264 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6267 int btrfs_get_dev_stats(struct btrfs_root *root,
6268 struct btrfs_ioctl_get_dev_stats *stats)
6270 struct btrfs_device *dev;
6271 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6274 mutex_lock(&fs_devices->device_list_mutex);
6275 dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6276 mutex_unlock(&fs_devices->device_list_mutex);
6279 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6281 } else if (!dev->dev_stats_valid) {
6282 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6284 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6285 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6286 if (stats->nr_items > i)
6288 btrfs_dev_stat_read_and_reset(dev, i);
6290 btrfs_dev_stat_reset(dev, i);
6293 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6294 if (stats->nr_items > i)
6295 stats->values[i] = btrfs_dev_stat_read(dev, i);
6297 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6298 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6302 int btrfs_scratch_superblock(struct btrfs_device *device)
6304 struct buffer_head *bh;
6305 struct btrfs_super_block *disk_super;
6307 bh = btrfs_read_dev_super(device->bdev);
6310 disk_super = (struct btrfs_super_block *)bh->b_data;
6312 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6313 set_buffer_dirty(bh);
6314 sync_dirty_buffer(bh);