mm: fix exec activate_mm vs TLB shootdown and lazy tlb switching race
[linux/fpc-iii.git] / fs / btrfs / volumes.c
blob3d92feff249a0a69b555a5fe13ba8bc2025ed277
1 /*
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/sched/mm.h>
20 #include <linux/bio.h>
21 #include <linux/slab.h>
22 #include <linux/buffer_head.h>
23 #include <linux/blkdev.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 <linux/uuid.h>
31 #include <asm/div64.h>
32 #include "ctree.h"
33 #include "extent_map.h"
34 #include "disk-io.h"
35 #include "transaction.h"
36 #include "print-tree.h"
37 #include "volumes.h"
38 #include "raid56.h"
39 #include "async-thread.h"
40 #include "check-integrity.h"
41 #include "rcu-string.h"
42 #include "math.h"
43 #include "dev-replace.h"
44 #include "sysfs.h"
46 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
47 [BTRFS_RAID_RAID10] = {
48 .sub_stripes = 2,
49 .dev_stripes = 1,
50 .devs_max = 0, /* 0 == as many as possible */
51 .devs_min = 4,
52 .tolerated_failures = 1,
53 .devs_increment = 2,
54 .ncopies = 2,
56 [BTRFS_RAID_RAID1] = {
57 .sub_stripes = 1,
58 .dev_stripes = 1,
59 .devs_max = 2,
60 .devs_min = 2,
61 .tolerated_failures = 1,
62 .devs_increment = 2,
63 .ncopies = 2,
65 [BTRFS_RAID_DUP] = {
66 .sub_stripes = 1,
67 .dev_stripes = 2,
68 .devs_max = 1,
69 .devs_min = 1,
70 .tolerated_failures = 0,
71 .devs_increment = 1,
72 .ncopies = 2,
74 [BTRFS_RAID_RAID0] = {
75 .sub_stripes = 1,
76 .dev_stripes = 1,
77 .devs_max = 0,
78 .devs_min = 2,
79 .tolerated_failures = 0,
80 .devs_increment = 1,
81 .ncopies = 1,
83 [BTRFS_RAID_SINGLE] = {
84 .sub_stripes = 1,
85 .dev_stripes = 1,
86 .devs_max = 1,
87 .devs_min = 1,
88 .tolerated_failures = 0,
89 .devs_increment = 1,
90 .ncopies = 1,
92 [BTRFS_RAID_RAID5] = {
93 .sub_stripes = 1,
94 .dev_stripes = 1,
95 .devs_max = 0,
96 .devs_min = 2,
97 .tolerated_failures = 1,
98 .devs_increment = 1,
99 .ncopies = 2,
101 [BTRFS_RAID_RAID6] = {
102 .sub_stripes = 1,
103 .dev_stripes = 1,
104 .devs_max = 0,
105 .devs_min = 3,
106 .tolerated_failures = 2,
107 .devs_increment = 1,
108 .ncopies = 3,
112 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
113 [BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
114 [BTRFS_RAID_RAID1] = BTRFS_BLOCK_GROUP_RAID1,
115 [BTRFS_RAID_DUP] = BTRFS_BLOCK_GROUP_DUP,
116 [BTRFS_RAID_RAID0] = BTRFS_BLOCK_GROUP_RAID0,
117 [BTRFS_RAID_SINGLE] = 0,
118 [BTRFS_RAID_RAID5] = BTRFS_BLOCK_GROUP_RAID5,
119 [BTRFS_RAID_RAID6] = BTRFS_BLOCK_GROUP_RAID6,
123 * Table to convert BTRFS_RAID_* to the error code if minimum number of devices
124 * condition is not met. Zero means there's no corresponding
125 * BTRFS_ERROR_DEV_*_NOT_MET value.
127 const int btrfs_raid_mindev_error[BTRFS_NR_RAID_TYPES] = {
128 [BTRFS_RAID_RAID10] = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
129 [BTRFS_RAID_RAID1] = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
130 [BTRFS_RAID_DUP] = 0,
131 [BTRFS_RAID_RAID0] = 0,
132 [BTRFS_RAID_SINGLE] = 0,
133 [BTRFS_RAID_RAID5] = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
134 [BTRFS_RAID_RAID6] = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
137 static int init_first_rw_device(struct btrfs_trans_handle *trans,
138 struct btrfs_fs_info *fs_info);
139 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
140 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
141 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
142 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
143 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
144 enum btrfs_map_op op,
145 u64 logical, u64 *length,
146 struct btrfs_bio **bbio_ret,
147 int mirror_num, int need_raid_map);
149 DEFINE_MUTEX(uuid_mutex);
150 static LIST_HEAD(fs_uuids);
151 struct list_head *btrfs_get_fs_uuids(void)
153 return &fs_uuids;
157 * alloc_fs_devices - allocate struct btrfs_fs_devices
158 * @fsid: if not NULL, copy the uuid to fs_devices::fsid
160 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
161 * The returned struct is not linked onto any lists and can be destroyed with
162 * kfree() right away.
164 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
166 struct btrfs_fs_devices *fs_devs;
168 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
169 if (!fs_devs)
170 return ERR_PTR(-ENOMEM);
172 mutex_init(&fs_devs->device_list_mutex);
174 INIT_LIST_HEAD(&fs_devs->devices);
175 INIT_LIST_HEAD(&fs_devs->resized_devices);
176 INIT_LIST_HEAD(&fs_devs->alloc_list);
177 INIT_LIST_HEAD(&fs_devs->list);
178 if (fsid)
179 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
181 return fs_devs;
184 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
186 struct btrfs_device *device;
187 WARN_ON(fs_devices->opened);
188 while (!list_empty(&fs_devices->devices)) {
189 device = list_entry(fs_devices->devices.next,
190 struct btrfs_device, dev_list);
191 list_del(&device->dev_list);
192 rcu_string_free(device->name);
193 kfree(device);
195 kfree(fs_devices);
198 static void btrfs_kobject_uevent(struct block_device *bdev,
199 enum kobject_action action)
201 int ret;
203 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
204 if (ret)
205 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
206 action,
207 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
208 &disk_to_dev(bdev->bd_disk)->kobj);
211 void btrfs_cleanup_fs_uuids(void)
213 struct btrfs_fs_devices *fs_devices;
215 while (!list_empty(&fs_uuids)) {
216 fs_devices = list_entry(fs_uuids.next,
217 struct btrfs_fs_devices, list);
218 list_del(&fs_devices->list);
219 free_fs_devices(fs_devices);
223 static struct btrfs_device *__alloc_device(void)
225 struct btrfs_device *dev;
227 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
228 if (!dev)
229 return ERR_PTR(-ENOMEM);
232 * Preallocate a bio that's always going to be used for flushing device
233 * barriers and matches the device lifespan
235 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
236 if (!dev->flush_bio) {
237 kfree(dev);
238 return ERR_PTR(-ENOMEM);
241 INIT_LIST_HEAD(&dev->dev_list);
242 INIT_LIST_HEAD(&dev->dev_alloc_list);
243 INIT_LIST_HEAD(&dev->resized_list);
245 spin_lock_init(&dev->io_lock);
247 spin_lock_init(&dev->reada_lock);
248 atomic_set(&dev->reada_in_flight, 0);
249 atomic_set(&dev->dev_stats_ccnt, 0);
250 btrfs_device_data_ordered_init(dev);
251 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
252 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
254 return dev;
258 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
259 * return NULL.
261 * If devid and uuid are both specified, the match must be exact, otherwise
262 * only devid is used.
264 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
265 u64 devid, const u8 *uuid)
267 struct list_head *head = &fs_devices->devices;
268 struct btrfs_device *dev;
270 list_for_each_entry(dev, head, dev_list) {
271 if (dev->devid == devid &&
272 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
273 return dev;
276 return NULL;
279 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
281 struct btrfs_fs_devices *fs_devices;
283 list_for_each_entry(fs_devices, &fs_uuids, list) {
284 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
285 return fs_devices;
287 return NULL;
290 static int
291 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
292 int flush, struct block_device **bdev,
293 struct buffer_head **bh)
295 int ret;
297 *bdev = blkdev_get_by_path(device_path, flags, holder);
299 if (IS_ERR(*bdev)) {
300 ret = PTR_ERR(*bdev);
301 goto error;
304 if (flush)
305 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
306 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
307 if (ret) {
308 blkdev_put(*bdev, flags);
309 goto error;
311 invalidate_bdev(*bdev);
312 *bh = btrfs_read_dev_super(*bdev);
313 if (IS_ERR(*bh)) {
314 ret = PTR_ERR(*bh);
315 blkdev_put(*bdev, flags);
316 goto error;
319 return 0;
321 error:
322 *bdev = NULL;
323 *bh = NULL;
324 return ret;
327 static void requeue_list(struct btrfs_pending_bios *pending_bios,
328 struct bio *head, struct bio *tail)
331 struct bio *old_head;
333 old_head = pending_bios->head;
334 pending_bios->head = head;
335 if (pending_bios->tail)
336 tail->bi_next = old_head;
337 else
338 pending_bios->tail = tail;
342 * we try to collect pending bios for a device so we don't get a large
343 * number of procs sending bios down to the same device. This greatly
344 * improves the schedulers ability to collect and merge the bios.
346 * But, it also turns into a long list of bios to process and that is sure
347 * to eventually make the worker thread block. The solution here is to
348 * make some progress and then put this work struct back at the end of
349 * the list if the block device is congested. This way, multiple devices
350 * can make progress from a single worker thread.
352 static noinline void run_scheduled_bios(struct btrfs_device *device)
354 struct btrfs_fs_info *fs_info = device->fs_info;
355 struct bio *pending;
356 struct backing_dev_info *bdi;
357 struct btrfs_pending_bios *pending_bios;
358 struct bio *tail;
359 struct bio *cur;
360 int again = 0;
361 unsigned long num_run;
362 unsigned long batch_run = 0;
363 unsigned long limit;
364 unsigned long last_waited = 0;
365 int force_reg = 0;
366 int sync_pending = 0;
367 struct blk_plug plug;
370 * this function runs all the bios we've collected for
371 * a particular device. We don't want to wander off to
372 * another device without first sending all of these down.
373 * So, setup a plug here and finish it off before we return
375 blk_start_plug(&plug);
377 bdi = device->bdev->bd_bdi;
378 limit = btrfs_async_submit_limit(fs_info);
379 limit = limit * 2 / 3;
381 loop:
382 spin_lock(&device->io_lock);
384 loop_lock:
385 num_run = 0;
387 /* take all the bios off the list at once and process them
388 * later on (without the lock held). But, remember the
389 * tail and other pointers so the bios can be properly reinserted
390 * into the list if we hit congestion
392 if (!force_reg && device->pending_sync_bios.head) {
393 pending_bios = &device->pending_sync_bios;
394 force_reg = 1;
395 } else {
396 pending_bios = &device->pending_bios;
397 force_reg = 0;
400 pending = pending_bios->head;
401 tail = pending_bios->tail;
402 WARN_ON(pending && !tail);
405 * if pending was null this time around, no bios need processing
406 * at all and we can stop. Otherwise it'll loop back up again
407 * and do an additional check so no bios are missed.
409 * device->running_pending is used to synchronize with the
410 * schedule_bio code.
412 if (device->pending_sync_bios.head == NULL &&
413 device->pending_bios.head == NULL) {
414 again = 0;
415 device->running_pending = 0;
416 } else {
417 again = 1;
418 device->running_pending = 1;
421 pending_bios->head = NULL;
422 pending_bios->tail = NULL;
424 spin_unlock(&device->io_lock);
426 while (pending) {
428 rmb();
429 /* we want to work on both lists, but do more bios on the
430 * sync list than the regular list
432 if ((num_run > 32 &&
433 pending_bios != &device->pending_sync_bios &&
434 device->pending_sync_bios.head) ||
435 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
436 device->pending_bios.head)) {
437 spin_lock(&device->io_lock);
438 requeue_list(pending_bios, pending, tail);
439 goto loop_lock;
442 cur = pending;
443 pending = pending->bi_next;
444 cur->bi_next = NULL;
447 * atomic_dec_return implies a barrier for waitqueue_active
449 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
450 waitqueue_active(&fs_info->async_submit_wait))
451 wake_up(&fs_info->async_submit_wait);
453 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
456 * if we're doing the sync list, record that our
457 * plug has some sync requests on it
459 * If we're doing the regular list and there are
460 * sync requests sitting around, unplug before
461 * we add more
463 if (pending_bios == &device->pending_sync_bios) {
464 sync_pending = 1;
465 } else if (sync_pending) {
466 blk_finish_plug(&plug);
467 blk_start_plug(&plug);
468 sync_pending = 0;
471 btrfsic_submit_bio(cur);
472 num_run++;
473 batch_run++;
475 cond_resched();
478 * we made progress, there is more work to do and the bdi
479 * is now congested. Back off and let other work structs
480 * run instead
482 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
483 fs_info->fs_devices->open_devices > 1) {
484 struct io_context *ioc;
486 ioc = current->io_context;
489 * the main goal here is that we don't want to
490 * block if we're going to be able to submit
491 * more requests without blocking.
493 * This code does two great things, it pokes into
494 * the elevator code from a filesystem _and_
495 * it makes assumptions about how batching works.
497 if (ioc && ioc->nr_batch_requests > 0 &&
498 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
499 (last_waited == 0 ||
500 ioc->last_waited == last_waited)) {
502 * we want to go through our batch of
503 * requests and stop. So, we copy out
504 * the ioc->last_waited time and test
505 * against it before looping
507 last_waited = ioc->last_waited;
508 cond_resched();
509 continue;
511 spin_lock(&device->io_lock);
512 requeue_list(pending_bios, pending, tail);
513 device->running_pending = 1;
515 spin_unlock(&device->io_lock);
516 btrfs_queue_work(fs_info->submit_workers,
517 &device->work);
518 goto done;
520 /* unplug every 64 requests just for good measure */
521 if (batch_run % 64 == 0) {
522 blk_finish_plug(&plug);
523 blk_start_plug(&plug);
524 sync_pending = 0;
528 cond_resched();
529 if (again)
530 goto loop;
532 spin_lock(&device->io_lock);
533 if (device->pending_bios.head || device->pending_sync_bios.head)
534 goto loop_lock;
535 spin_unlock(&device->io_lock);
537 done:
538 blk_finish_plug(&plug);
541 static void pending_bios_fn(struct btrfs_work *work)
543 struct btrfs_device *device;
545 device = container_of(work, struct btrfs_device, work);
546 run_scheduled_bios(device);
550 void btrfs_free_stale_device(struct btrfs_device *cur_dev)
552 struct btrfs_fs_devices *fs_devs;
553 struct btrfs_device *dev;
555 if (!cur_dev->name)
556 return;
558 list_for_each_entry(fs_devs, &fs_uuids, list) {
559 int del = 1;
561 if (fs_devs->opened)
562 continue;
563 if (fs_devs->seeding)
564 continue;
566 list_for_each_entry(dev, &fs_devs->devices, dev_list) {
568 if (dev == cur_dev)
569 continue;
570 if (!dev->name)
571 continue;
574 * Todo: This won't be enough. What if the same device
575 * comes back (with new uuid and) with its mapper path?
576 * But for now, this does help as mostly an admin will
577 * either use mapper or non mapper path throughout.
579 rcu_read_lock();
580 del = strcmp(rcu_str_deref(dev->name),
581 rcu_str_deref(cur_dev->name));
582 rcu_read_unlock();
583 if (!del)
584 break;
587 if (!del) {
588 /* delete the stale device */
589 if (fs_devs->num_devices == 1) {
590 btrfs_sysfs_remove_fsid(fs_devs);
591 list_del(&fs_devs->list);
592 free_fs_devices(fs_devs);
593 break;
594 } else {
595 fs_devs->num_devices--;
596 list_del(&dev->dev_list);
597 rcu_string_free(dev->name);
598 kfree(dev);
600 break;
606 * Add new device to list of registered devices
608 * Returns:
609 * 1 - first time device is seen
610 * 0 - device already known
611 * < 0 - error
613 static noinline int device_list_add(const char *path,
614 struct btrfs_super_block *disk_super,
615 u64 devid, struct btrfs_fs_devices **fs_devices_ret)
617 struct btrfs_device *device;
618 struct btrfs_fs_devices *fs_devices;
619 struct rcu_string *name;
620 int ret = 0;
621 u64 found_transid = btrfs_super_generation(disk_super);
623 fs_devices = find_fsid(disk_super->fsid);
624 if (!fs_devices) {
625 fs_devices = alloc_fs_devices(disk_super->fsid);
626 if (IS_ERR(fs_devices))
627 return PTR_ERR(fs_devices);
629 list_add(&fs_devices->list, &fs_uuids);
631 device = NULL;
632 } else {
633 device = find_device(fs_devices, devid,
634 disk_super->dev_item.uuid);
637 if (!device) {
638 if (fs_devices->opened)
639 return -EBUSY;
641 device = btrfs_alloc_device(NULL, &devid,
642 disk_super->dev_item.uuid);
643 if (IS_ERR(device)) {
644 /* we can safely leave the fs_devices entry around */
645 return PTR_ERR(device);
648 name = rcu_string_strdup(path, GFP_NOFS);
649 if (!name) {
650 kfree(device);
651 return -ENOMEM;
653 rcu_assign_pointer(device->name, name);
655 mutex_lock(&fs_devices->device_list_mutex);
656 list_add_rcu(&device->dev_list, &fs_devices->devices);
657 fs_devices->num_devices++;
658 mutex_unlock(&fs_devices->device_list_mutex);
660 ret = 1;
661 device->fs_devices = fs_devices;
662 } else if (!device->name || strcmp(device->name->str, path)) {
664 * When FS is already mounted.
665 * 1. If you are here and if the device->name is NULL that
666 * means this device was missing at time of FS mount.
667 * 2. If you are here and if the device->name is different
668 * from 'path' that means either
669 * a. The same device disappeared and reappeared with
670 * different name. or
671 * b. The missing-disk-which-was-replaced, has
672 * reappeared now.
674 * We must allow 1 and 2a above. But 2b would be a spurious
675 * and unintentional.
677 * Further in case of 1 and 2a above, the disk at 'path'
678 * would have missed some transaction when it was away and
679 * in case of 2a the stale bdev has to be updated as well.
680 * 2b must not be allowed at all time.
684 * For now, we do allow update to btrfs_fs_device through the
685 * btrfs dev scan cli after FS has been mounted. We're still
686 * tracking a problem where systems fail mount by subvolume id
687 * when we reject replacement on a mounted FS.
689 if (!fs_devices->opened && found_transid < device->generation) {
691 * That is if the FS is _not_ mounted and if you
692 * are here, that means there is more than one
693 * disk with same uuid and devid.We keep the one
694 * with larger generation number or the last-in if
695 * generation are equal.
697 return -EEXIST;
700 name = rcu_string_strdup(path, GFP_NOFS);
701 if (!name)
702 return -ENOMEM;
703 rcu_string_free(device->name);
704 rcu_assign_pointer(device->name, name);
705 if (device->missing) {
706 fs_devices->missing_devices--;
707 device->missing = 0;
712 * Unmount does not free the btrfs_device struct but would zero
713 * generation along with most of the other members. So just update
714 * it back. We need it to pick the disk with largest generation
715 * (as above).
717 if (!fs_devices->opened)
718 device->generation = found_transid;
721 * if there is new btrfs on an already registered device,
722 * then remove the stale device entry.
724 if (ret > 0)
725 btrfs_free_stale_device(device);
727 *fs_devices_ret = fs_devices;
729 return ret;
732 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
734 struct btrfs_fs_devices *fs_devices;
735 struct btrfs_device *device;
736 struct btrfs_device *orig_dev;
738 fs_devices = alloc_fs_devices(orig->fsid);
739 if (IS_ERR(fs_devices))
740 return fs_devices;
742 mutex_lock(&orig->device_list_mutex);
743 fs_devices->total_devices = orig->total_devices;
745 /* We have held the volume lock, it is safe to get the devices. */
746 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
747 struct rcu_string *name;
749 device = btrfs_alloc_device(NULL, &orig_dev->devid,
750 orig_dev->uuid);
751 if (IS_ERR(device))
752 goto error;
755 * This is ok to do without rcu read locked because we hold the
756 * uuid mutex so nothing we touch in here is going to disappear.
758 if (orig_dev->name) {
759 name = rcu_string_strdup(orig_dev->name->str,
760 GFP_KERNEL);
761 if (!name) {
762 kfree(device);
763 goto error;
765 rcu_assign_pointer(device->name, name);
768 list_add(&device->dev_list, &fs_devices->devices);
769 device->fs_devices = fs_devices;
770 fs_devices->num_devices++;
772 mutex_unlock(&orig->device_list_mutex);
773 return fs_devices;
774 error:
775 mutex_unlock(&orig->device_list_mutex);
776 free_fs_devices(fs_devices);
777 return ERR_PTR(-ENOMEM);
780 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
782 struct btrfs_device *device, *next;
783 struct btrfs_device *latest_dev = NULL;
785 mutex_lock(&uuid_mutex);
786 again:
787 /* This is the initialized path, it is safe to release the devices. */
788 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
789 if (device->in_fs_metadata) {
790 if (!device->is_tgtdev_for_dev_replace &&
791 (!latest_dev ||
792 device->generation > latest_dev->generation)) {
793 latest_dev = device;
795 continue;
798 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
800 * In the first step, keep the device which has
801 * the correct fsid and the devid that is used
802 * for the dev_replace procedure.
803 * In the second step, the dev_replace state is
804 * read from the device tree and it is known
805 * whether the procedure is really active or
806 * not, which means whether this device is
807 * used or whether it should be removed.
809 if (step == 0 || device->is_tgtdev_for_dev_replace) {
810 continue;
813 if (device->bdev) {
814 blkdev_put(device->bdev, device->mode);
815 device->bdev = NULL;
816 fs_devices->open_devices--;
818 if (device->writeable) {
819 list_del_init(&device->dev_alloc_list);
820 device->writeable = 0;
821 if (!device->is_tgtdev_for_dev_replace)
822 fs_devices->rw_devices--;
824 list_del_init(&device->dev_list);
825 fs_devices->num_devices--;
826 rcu_string_free(device->name);
827 kfree(device);
830 if (fs_devices->seed) {
831 fs_devices = fs_devices->seed;
832 goto again;
835 fs_devices->latest_bdev = latest_dev->bdev;
837 mutex_unlock(&uuid_mutex);
840 static void __free_device(struct work_struct *work)
842 struct btrfs_device *device;
844 device = container_of(work, struct btrfs_device, rcu_work);
845 rcu_string_free(device->name);
846 bio_put(device->flush_bio);
847 kfree(device);
850 static void free_device(struct rcu_head *head)
852 struct btrfs_device *device;
854 device = container_of(head, struct btrfs_device, rcu);
856 INIT_WORK(&device->rcu_work, __free_device);
857 schedule_work(&device->rcu_work);
860 static void btrfs_close_bdev(struct btrfs_device *device)
862 if (device->bdev && device->writeable) {
863 sync_blockdev(device->bdev);
864 invalidate_bdev(device->bdev);
867 if (device->bdev)
868 blkdev_put(device->bdev, device->mode);
871 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
873 struct btrfs_fs_devices *fs_devices = device->fs_devices;
874 struct btrfs_device *new_device;
875 struct rcu_string *name;
877 if (device->bdev)
878 fs_devices->open_devices--;
880 if (device->writeable &&
881 device->devid != BTRFS_DEV_REPLACE_DEVID) {
882 list_del_init(&device->dev_alloc_list);
883 fs_devices->rw_devices--;
886 if (device->missing)
887 fs_devices->missing_devices--;
889 new_device = btrfs_alloc_device(NULL, &device->devid,
890 device->uuid);
891 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
893 /* Safe because we are under uuid_mutex */
894 if (device->name) {
895 name = rcu_string_strdup(device->name->str, GFP_NOFS);
896 BUG_ON(!name); /* -ENOMEM */
897 rcu_assign_pointer(new_device->name, name);
900 list_replace_rcu(&device->dev_list, &new_device->dev_list);
901 new_device->fs_devices = device->fs_devices;
904 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
906 struct btrfs_device *device, *tmp;
907 struct list_head pending_put;
909 INIT_LIST_HEAD(&pending_put);
911 if (--fs_devices->opened > 0)
912 return 0;
914 mutex_lock(&fs_devices->device_list_mutex);
915 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
916 btrfs_prepare_close_one_device(device);
917 list_add(&device->dev_list, &pending_put);
919 mutex_unlock(&fs_devices->device_list_mutex);
922 * btrfs_show_devname() is using the device_list_mutex,
923 * sometimes call to blkdev_put() leads vfs calling
924 * into this func. So do put outside of device_list_mutex,
925 * as of now.
927 while (!list_empty(&pending_put)) {
928 device = list_first_entry(&pending_put,
929 struct btrfs_device, dev_list);
930 list_del(&device->dev_list);
931 btrfs_close_bdev(device);
932 call_rcu(&device->rcu, free_device);
935 WARN_ON(fs_devices->open_devices);
936 WARN_ON(fs_devices->rw_devices);
937 fs_devices->opened = 0;
938 fs_devices->seeding = 0;
940 return 0;
943 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
945 struct btrfs_fs_devices *seed_devices = NULL;
946 int ret;
948 mutex_lock(&uuid_mutex);
949 ret = __btrfs_close_devices(fs_devices);
950 if (!fs_devices->opened) {
951 seed_devices = fs_devices->seed;
952 fs_devices->seed = NULL;
954 mutex_unlock(&uuid_mutex);
956 while (seed_devices) {
957 fs_devices = seed_devices;
958 seed_devices = fs_devices->seed;
959 __btrfs_close_devices(fs_devices);
960 free_fs_devices(fs_devices);
963 * Wait for rcu kworkers under __btrfs_close_devices
964 * to finish all blkdev_puts so device is really
965 * free when umount is done.
967 rcu_barrier();
968 return ret;
971 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
972 fmode_t flags, void *holder)
974 struct request_queue *q;
975 struct block_device *bdev;
976 struct list_head *head = &fs_devices->devices;
977 struct btrfs_device *device;
978 struct btrfs_device *latest_dev = NULL;
979 struct buffer_head *bh;
980 struct btrfs_super_block *disk_super;
981 u64 devid;
982 int seeding = 1;
983 int ret = 0;
985 flags |= FMODE_EXCL;
987 list_for_each_entry(device, head, dev_list) {
988 if (device->bdev)
989 continue;
990 if (!device->name)
991 continue;
993 /* Just open everything we can; ignore failures here */
994 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
995 &bdev, &bh))
996 continue;
998 disk_super = (struct btrfs_super_block *)bh->b_data;
999 devid = btrfs_stack_device_id(&disk_super->dev_item);
1000 if (devid != device->devid)
1001 goto error_brelse;
1003 if (memcmp(device->uuid, disk_super->dev_item.uuid,
1004 BTRFS_UUID_SIZE))
1005 goto error_brelse;
1007 device->generation = btrfs_super_generation(disk_super);
1008 if (!latest_dev ||
1009 device->generation > latest_dev->generation)
1010 latest_dev = device;
1012 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
1013 device->writeable = 0;
1014 } else {
1015 device->writeable = !bdev_read_only(bdev);
1016 seeding = 0;
1019 q = bdev_get_queue(bdev);
1020 if (blk_queue_discard(q))
1021 device->can_discard = 1;
1022 if (!blk_queue_nonrot(q))
1023 fs_devices->rotating = 1;
1025 device->bdev = bdev;
1026 device->in_fs_metadata = 0;
1027 device->mode = flags;
1029 fs_devices->open_devices++;
1030 if (device->writeable &&
1031 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1032 fs_devices->rw_devices++;
1033 list_add(&device->dev_alloc_list,
1034 &fs_devices->alloc_list);
1036 brelse(bh);
1037 continue;
1039 error_brelse:
1040 brelse(bh);
1041 blkdev_put(bdev, flags);
1042 continue;
1044 if (fs_devices->open_devices == 0) {
1045 ret = -EINVAL;
1046 goto out;
1048 fs_devices->seeding = seeding;
1049 fs_devices->opened = 1;
1050 fs_devices->latest_bdev = latest_dev->bdev;
1051 fs_devices->total_rw_bytes = 0;
1052 out:
1053 return ret;
1056 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1057 fmode_t flags, void *holder)
1059 int ret;
1061 mutex_lock(&uuid_mutex);
1062 if (fs_devices->opened) {
1063 fs_devices->opened++;
1064 ret = 0;
1065 } else {
1066 ret = __btrfs_open_devices(fs_devices, flags, holder);
1068 mutex_unlock(&uuid_mutex);
1069 return ret;
1072 void btrfs_release_disk_super(struct page *page)
1074 kunmap(page);
1075 put_page(page);
1078 int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1079 struct page **page, struct btrfs_super_block **disk_super)
1081 void *p;
1082 pgoff_t index;
1084 /* make sure our super fits in the device */
1085 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1086 return 1;
1088 /* make sure our super fits in the page */
1089 if (sizeof(**disk_super) > PAGE_SIZE)
1090 return 1;
1092 /* make sure our super doesn't straddle pages on disk */
1093 index = bytenr >> PAGE_SHIFT;
1094 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1095 return 1;
1097 /* pull in the page with our super */
1098 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1099 index, GFP_KERNEL);
1101 if (IS_ERR_OR_NULL(*page))
1102 return 1;
1104 p = kmap(*page);
1106 /* align our pointer to the offset of the super block */
1107 *disk_super = p + (bytenr & ~PAGE_MASK);
1109 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1110 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1111 btrfs_release_disk_super(*page);
1112 return 1;
1115 if ((*disk_super)->label[0] &&
1116 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1117 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1119 return 0;
1123 * Look for a btrfs signature on a device. This may be called out of the mount path
1124 * and we are not allowed to call set_blocksize during the scan. The superblock
1125 * is read via pagecache
1127 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1128 struct btrfs_fs_devices **fs_devices_ret)
1130 struct btrfs_super_block *disk_super;
1131 struct block_device *bdev;
1132 struct page *page;
1133 int ret = -EINVAL;
1134 u64 devid;
1135 u64 transid;
1136 u64 total_devices;
1137 u64 bytenr;
1140 * we would like to check all the supers, but that would make
1141 * a btrfs mount succeed after a mkfs from a different FS.
1142 * So, we need to add a special mount option to scan for
1143 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1145 bytenr = btrfs_sb_offset(0);
1146 flags |= FMODE_EXCL;
1147 mutex_lock(&uuid_mutex);
1149 bdev = blkdev_get_by_path(path, flags, holder);
1150 if (IS_ERR(bdev)) {
1151 ret = PTR_ERR(bdev);
1152 goto error;
1155 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super))
1156 goto error_bdev_put;
1158 devid = btrfs_stack_device_id(&disk_super->dev_item);
1159 transid = btrfs_super_generation(disk_super);
1160 total_devices = btrfs_super_num_devices(disk_super);
1162 ret = device_list_add(path, disk_super, devid, fs_devices_ret);
1163 if (ret > 0) {
1164 if (disk_super->label[0]) {
1165 pr_info("BTRFS: device label %s ", disk_super->label);
1166 } else {
1167 pr_info("BTRFS: device fsid %pU ", disk_super->fsid);
1170 pr_cont("devid %llu transid %llu %s\n", devid, transid, path);
1171 ret = 0;
1173 if (!ret && fs_devices_ret)
1174 (*fs_devices_ret)->total_devices = total_devices;
1176 btrfs_release_disk_super(page);
1178 error_bdev_put:
1179 blkdev_put(bdev, flags);
1180 error:
1181 mutex_unlock(&uuid_mutex);
1182 return ret;
1185 /* helper to account the used device space in the range */
1186 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1187 u64 end, u64 *length)
1189 struct btrfs_key key;
1190 struct btrfs_root *root = device->fs_info->dev_root;
1191 struct btrfs_dev_extent *dev_extent;
1192 struct btrfs_path *path;
1193 u64 extent_end;
1194 int ret;
1195 int slot;
1196 struct extent_buffer *l;
1198 *length = 0;
1200 if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1201 return 0;
1203 path = btrfs_alloc_path();
1204 if (!path)
1205 return -ENOMEM;
1206 path->reada = READA_FORWARD;
1208 key.objectid = device->devid;
1209 key.offset = start;
1210 key.type = BTRFS_DEV_EXTENT_KEY;
1212 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1213 if (ret < 0)
1214 goto out;
1215 if (ret > 0) {
1216 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1217 if (ret < 0)
1218 goto out;
1221 while (1) {
1222 l = path->nodes[0];
1223 slot = path->slots[0];
1224 if (slot >= btrfs_header_nritems(l)) {
1225 ret = btrfs_next_leaf(root, path);
1226 if (ret == 0)
1227 continue;
1228 if (ret < 0)
1229 goto out;
1231 break;
1233 btrfs_item_key_to_cpu(l, &key, slot);
1235 if (key.objectid < device->devid)
1236 goto next;
1238 if (key.objectid > device->devid)
1239 break;
1241 if (key.type != BTRFS_DEV_EXTENT_KEY)
1242 goto next;
1244 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1245 extent_end = key.offset + btrfs_dev_extent_length(l,
1246 dev_extent);
1247 if (key.offset <= start && extent_end > end) {
1248 *length = end - start + 1;
1249 break;
1250 } else if (key.offset <= start && extent_end > start)
1251 *length += extent_end - start;
1252 else if (key.offset > start && extent_end <= end)
1253 *length += extent_end - key.offset;
1254 else if (key.offset > start && key.offset <= end) {
1255 *length += end - key.offset + 1;
1256 break;
1257 } else if (key.offset > end)
1258 break;
1260 next:
1261 path->slots[0]++;
1263 ret = 0;
1264 out:
1265 btrfs_free_path(path);
1266 return ret;
1269 static int contains_pending_extent(struct btrfs_transaction *transaction,
1270 struct btrfs_device *device,
1271 u64 *start, u64 len)
1273 struct btrfs_fs_info *fs_info = device->fs_info;
1274 struct extent_map *em;
1275 struct list_head *search_list = &fs_info->pinned_chunks;
1276 int ret = 0;
1277 u64 physical_start = *start;
1279 if (transaction)
1280 search_list = &transaction->pending_chunks;
1281 again:
1282 list_for_each_entry(em, search_list, list) {
1283 struct map_lookup *map;
1284 int i;
1286 map = em->map_lookup;
1287 for (i = 0; i < map->num_stripes; i++) {
1288 u64 end;
1290 if (map->stripes[i].dev != device)
1291 continue;
1292 if (map->stripes[i].physical >= physical_start + len ||
1293 map->stripes[i].physical + em->orig_block_len <=
1294 physical_start)
1295 continue;
1297 * Make sure that while processing the pinned list we do
1298 * not override our *start with a lower value, because
1299 * we can have pinned chunks that fall within this
1300 * device hole and that have lower physical addresses
1301 * than the pending chunks we processed before. If we
1302 * do not take this special care we can end up getting
1303 * 2 pending chunks that start at the same physical
1304 * device offsets because the end offset of a pinned
1305 * chunk can be equal to the start offset of some
1306 * pending chunk.
1308 end = map->stripes[i].physical + em->orig_block_len;
1309 if (end > *start) {
1310 *start = end;
1311 ret = 1;
1315 if (search_list != &fs_info->pinned_chunks) {
1316 search_list = &fs_info->pinned_chunks;
1317 goto again;
1320 return ret;
1325 * find_free_dev_extent_start - find free space in the specified device
1326 * @device: the device which we search the free space in
1327 * @num_bytes: the size of the free space that we need
1328 * @search_start: the position from which to begin the search
1329 * @start: store the start of the free space.
1330 * @len: the size of the free space. that we find, or the size
1331 * of the max free space if we don't find suitable free space
1333 * this uses a pretty simple search, the expectation is that it is
1334 * called very infrequently and that a given device has a small number
1335 * of extents
1337 * @start is used to store the start of the free space if we find. But if we
1338 * don't find suitable free space, it will be used to store the start position
1339 * of the max free space.
1341 * @len is used to store the size of the free space that we find.
1342 * But if we don't find suitable free space, it is used to store the size of
1343 * the max free space.
1345 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1346 struct btrfs_device *device, u64 num_bytes,
1347 u64 search_start, u64 *start, u64 *len)
1349 struct btrfs_fs_info *fs_info = device->fs_info;
1350 struct btrfs_root *root = fs_info->dev_root;
1351 struct btrfs_key key;
1352 struct btrfs_dev_extent *dev_extent;
1353 struct btrfs_path *path;
1354 u64 hole_size;
1355 u64 max_hole_start;
1356 u64 max_hole_size;
1357 u64 extent_end;
1358 u64 search_end = device->total_bytes;
1359 int ret;
1360 int slot;
1361 struct extent_buffer *l;
1364 * We don't want to overwrite the superblock on the drive nor any area
1365 * used by the boot loader (grub for example), so we make sure to start
1366 * at an offset of at least 1MB.
1368 search_start = max_t(u64, search_start, SZ_1M);
1370 path = btrfs_alloc_path();
1371 if (!path)
1372 return -ENOMEM;
1374 max_hole_start = search_start;
1375 max_hole_size = 0;
1377 again:
1378 if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1379 ret = -ENOSPC;
1380 goto out;
1383 path->reada = READA_FORWARD;
1384 path->search_commit_root = 1;
1385 path->skip_locking = 1;
1387 key.objectid = device->devid;
1388 key.offset = search_start;
1389 key.type = BTRFS_DEV_EXTENT_KEY;
1391 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1392 if (ret < 0)
1393 goto out;
1394 if (ret > 0) {
1395 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1396 if (ret < 0)
1397 goto out;
1400 while (1) {
1401 l = path->nodes[0];
1402 slot = path->slots[0];
1403 if (slot >= btrfs_header_nritems(l)) {
1404 ret = btrfs_next_leaf(root, path);
1405 if (ret == 0)
1406 continue;
1407 if (ret < 0)
1408 goto out;
1410 break;
1412 btrfs_item_key_to_cpu(l, &key, slot);
1414 if (key.objectid < device->devid)
1415 goto next;
1417 if (key.objectid > device->devid)
1418 break;
1420 if (key.type != BTRFS_DEV_EXTENT_KEY)
1421 goto next;
1423 if (key.offset > search_start) {
1424 hole_size = key.offset - search_start;
1427 * Have to check before we set max_hole_start, otherwise
1428 * we could end up sending back this offset anyway.
1430 if (contains_pending_extent(transaction, device,
1431 &search_start,
1432 hole_size)) {
1433 if (key.offset >= search_start) {
1434 hole_size = key.offset - search_start;
1435 } else {
1436 WARN_ON_ONCE(1);
1437 hole_size = 0;
1441 if (hole_size > max_hole_size) {
1442 max_hole_start = search_start;
1443 max_hole_size = hole_size;
1447 * If this free space is greater than which we need,
1448 * it must be the max free space that we have found
1449 * until now, so max_hole_start must point to the start
1450 * of this free space and the length of this free space
1451 * is stored in max_hole_size. Thus, we return
1452 * max_hole_start and max_hole_size and go back to the
1453 * caller.
1455 if (hole_size >= num_bytes) {
1456 ret = 0;
1457 goto out;
1461 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1462 extent_end = key.offset + btrfs_dev_extent_length(l,
1463 dev_extent);
1464 if (extent_end > search_start)
1465 search_start = extent_end;
1466 next:
1467 path->slots[0]++;
1468 cond_resched();
1472 * At this point, search_start should be the end of
1473 * allocated dev extents, and when shrinking the device,
1474 * search_end may be smaller than search_start.
1476 if (search_end > search_start) {
1477 hole_size = search_end - search_start;
1479 if (contains_pending_extent(transaction, device, &search_start,
1480 hole_size)) {
1481 btrfs_release_path(path);
1482 goto again;
1485 if (hole_size > max_hole_size) {
1486 max_hole_start = search_start;
1487 max_hole_size = hole_size;
1491 /* See above. */
1492 if (max_hole_size < num_bytes)
1493 ret = -ENOSPC;
1494 else
1495 ret = 0;
1497 out:
1498 btrfs_free_path(path);
1499 *start = max_hole_start;
1500 if (len)
1501 *len = max_hole_size;
1502 return ret;
1505 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1506 struct btrfs_device *device, u64 num_bytes,
1507 u64 *start, u64 *len)
1509 /* FIXME use last free of some kind */
1510 return find_free_dev_extent_start(trans->transaction, device,
1511 num_bytes, 0, start, len);
1514 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1515 struct btrfs_device *device,
1516 u64 start, u64 *dev_extent_len)
1518 struct btrfs_fs_info *fs_info = device->fs_info;
1519 struct btrfs_root *root = fs_info->dev_root;
1520 int ret;
1521 struct btrfs_path *path;
1522 struct btrfs_key key;
1523 struct btrfs_key found_key;
1524 struct extent_buffer *leaf = NULL;
1525 struct btrfs_dev_extent *extent = NULL;
1527 path = btrfs_alloc_path();
1528 if (!path)
1529 return -ENOMEM;
1531 key.objectid = device->devid;
1532 key.offset = start;
1533 key.type = BTRFS_DEV_EXTENT_KEY;
1534 again:
1535 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1536 if (ret > 0) {
1537 ret = btrfs_previous_item(root, path, key.objectid,
1538 BTRFS_DEV_EXTENT_KEY);
1539 if (ret)
1540 goto out;
1541 leaf = path->nodes[0];
1542 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1543 extent = btrfs_item_ptr(leaf, path->slots[0],
1544 struct btrfs_dev_extent);
1545 BUG_ON(found_key.offset > start || found_key.offset +
1546 btrfs_dev_extent_length(leaf, extent) < start);
1547 key = found_key;
1548 btrfs_release_path(path);
1549 goto again;
1550 } else if (ret == 0) {
1551 leaf = path->nodes[0];
1552 extent = btrfs_item_ptr(leaf, path->slots[0],
1553 struct btrfs_dev_extent);
1554 } else {
1555 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1556 goto out;
1559 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1561 ret = btrfs_del_item(trans, root, path);
1562 if (ret) {
1563 btrfs_handle_fs_error(fs_info, ret,
1564 "Failed to remove dev extent item");
1565 } else {
1566 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1568 out:
1569 btrfs_free_path(path);
1570 return ret;
1573 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1574 struct btrfs_device *device,
1575 u64 chunk_offset, u64 start, u64 num_bytes)
1577 int ret;
1578 struct btrfs_path *path;
1579 struct btrfs_fs_info *fs_info = device->fs_info;
1580 struct btrfs_root *root = fs_info->dev_root;
1581 struct btrfs_dev_extent *extent;
1582 struct extent_buffer *leaf;
1583 struct btrfs_key key;
1585 WARN_ON(!device->in_fs_metadata);
1586 WARN_ON(device->is_tgtdev_for_dev_replace);
1587 path = btrfs_alloc_path();
1588 if (!path)
1589 return -ENOMEM;
1591 key.objectid = device->devid;
1592 key.offset = start;
1593 key.type = BTRFS_DEV_EXTENT_KEY;
1594 ret = btrfs_insert_empty_item(trans, root, path, &key,
1595 sizeof(*extent));
1596 if (ret)
1597 goto out;
1599 leaf = path->nodes[0];
1600 extent = btrfs_item_ptr(leaf, path->slots[0],
1601 struct btrfs_dev_extent);
1602 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1603 BTRFS_CHUNK_TREE_OBJECTID);
1604 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1605 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1606 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1608 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1609 btrfs_mark_buffer_dirty(leaf);
1610 out:
1611 btrfs_free_path(path);
1612 return ret;
1615 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1617 struct extent_map_tree *em_tree;
1618 struct extent_map *em;
1619 struct rb_node *n;
1620 u64 ret = 0;
1622 em_tree = &fs_info->mapping_tree.map_tree;
1623 read_lock(&em_tree->lock);
1624 n = rb_last(&em_tree->map);
1625 if (n) {
1626 em = rb_entry(n, struct extent_map, rb_node);
1627 ret = em->start + em->len;
1629 read_unlock(&em_tree->lock);
1631 return ret;
1634 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1635 u64 *devid_ret)
1637 int ret;
1638 struct btrfs_key key;
1639 struct btrfs_key found_key;
1640 struct btrfs_path *path;
1642 path = btrfs_alloc_path();
1643 if (!path)
1644 return -ENOMEM;
1646 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1647 key.type = BTRFS_DEV_ITEM_KEY;
1648 key.offset = (u64)-1;
1650 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1651 if (ret < 0)
1652 goto error;
1654 BUG_ON(ret == 0); /* Corruption */
1656 ret = btrfs_previous_item(fs_info->chunk_root, path,
1657 BTRFS_DEV_ITEMS_OBJECTID,
1658 BTRFS_DEV_ITEM_KEY);
1659 if (ret) {
1660 *devid_ret = 1;
1661 } else {
1662 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1663 path->slots[0]);
1664 *devid_ret = found_key.offset + 1;
1666 ret = 0;
1667 error:
1668 btrfs_free_path(path);
1669 return ret;
1673 * the device information is stored in the chunk root
1674 * the btrfs_device struct should be fully filled in
1676 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1677 struct btrfs_fs_info *fs_info,
1678 struct btrfs_device *device)
1680 struct btrfs_root *root = fs_info->chunk_root;
1681 int ret;
1682 struct btrfs_path *path;
1683 struct btrfs_dev_item *dev_item;
1684 struct extent_buffer *leaf;
1685 struct btrfs_key key;
1686 unsigned long ptr;
1688 path = btrfs_alloc_path();
1689 if (!path)
1690 return -ENOMEM;
1692 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1693 key.type = BTRFS_DEV_ITEM_KEY;
1694 key.offset = device->devid;
1696 ret = btrfs_insert_empty_item(trans, root, path, &key,
1697 sizeof(*dev_item));
1698 if (ret)
1699 goto out;
1701 leaf = path->nodes[0];
1702 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1704 btrfs_set_device_id(leaf, dev_item, device->devid);
1705 btrfs_set_device_generation(leaf, dev_item, 0);
1706 btrfs_set_device_type(leaf, dev_item, device->type);
1707 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1708 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1709 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1710 btrfs_set_device_total_bytes(leaf, dev_item,
1711 btrfs_device_get_disk_total_bytes(device));
1712 btrfs_set_device_bytes_used(leaf, dev_item,
1713 btrfs_device_get_bytes_used(device));
1714 btrfs_set_device_group(leaf, dev_item, 0);
1715 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1716 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1717 btrfs_set_device_start_offset(leaf, dev_item, 0);
1719 ptr = btrfs_device_uuid(dev_item);
1720 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1721 ptr = btrfs_device_fsid(dev_item);
1722 write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1723 btrfs_mark_buffer_dirty(leaf);
1725 ret = 0;
1726 out:
1727 btrfs_free_path(path);
1728 return ret;
1732 * Function to update ctime/mtime for a given device path.
1733 * Mainly used for ctime/mtime based probe like libblkid.
1735 static void update_dev_time(const char *path_name)
1737 struct file *filp;
1739 filp = filp_open(path_name, O_RDWR, 0);
1740 if (IS_ERR(filp))
1741 return;
1742 file_update_time(filp);
1743 filp_close(filp, NULL);
1746 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1747 struct btrfs_device *device)
1749 struct btrfs_root *root = fs_info->chunk_root;
1750 int ret;
1751 struct btrfs_path *path;
1752 struct btrfs_key key;
1753 struct btrfs_trans_handle *trans;
1755 path = btrfs_alloc_path();
1756 if (!path)
1757 return -ENOMEM;
1759 trans = btrfs_start_transaction(root, 0);
1760 if (IS_ERR(trans)) {
1761 btrfs_free_path(path);
1762 return PTR_ERR(trans);
1764 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1765 key.type = BTRFS_DEV_ITEM_KEY;
1766 key.offset = device->devid;
1768 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1769 if (ret) {
1770 if (ret > 0)
1771 ret = -ENOENT;
1772 btrfs_abort_transaction(trans, ret);
1773 btrfs_end_transaction(trans);
1774 goto out;
1777 ret = btrfs_del_item(trans, root, path);
1778 if (ret) {
1779 btrfs_abort_transaction(trans, ret);
1780 btrfs_end_transaction(trans);
1783 out:
1784 btrfs_free_path(path);
1785 if (!ret)
1786 ret = btrfs_commit_transaction(trans);
1787 return ret;
1791 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1792 * filesystem. It's up to the caller to adjust that number regarding eg. device
1793 * replace.
1795 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1796 u64 num_devices)
1798 u64 all_avail;
1799 unsigned seq;
1800 int i;
1802 do {
1803 seq = read_seqbegin(&fs_info->profiles_lock);
1805 all_avail = fs_info->avail_data_alloc_bits |
1806 fs_info->avail_system_alloc_bits |
1807 fs_info->avail_metadata_alloc_bits;
1808 } while (read_seqretry(&fs_info->profiles_lock, seq));
1810 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1811 if (!(all_avail & btrfs_raid_group[i]))
1812 continue;
1814 if (num_devices < btrfs_raid_array[i].devs_min) {
1815 int ret = btrfs_raid_mindev_error[i];
1817 if (ret)
1818 return ret;
1822 return 0;
1825 struct btrfs_device *btrfs_find_next_active_device(struct btrfs_fs_devices *fs_devs,
1826 struct btrfs_device *device)
1828 struct btrfs_device *next_device;
1830 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1831 if (next_device != device &&
1832 !next_device->missing && next_device->bdev)
1833 return next_device;
1836 return NULL;
1840 * Helper function to check if the given device is part of s_bdev / latest_bdev
1841 * and replace it with the provided or the next active device, in the context
1842 * where this function called, there should be always be another device (or
1843 * this_dev) which is active.
1845 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1846 struct btrfs_device *device, struct btrfs_device *this_dev)
1848 struct btrfs_device *next_device;
1850 if (this_dev)
1851 next_device = this_dev;
1852 else
1853 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1854 device);
1855 ASSERT(next_device);
1857 if (fs_info->sb->s_bdev &&
1858 (fs_info->sb->s_bdev == device->bdev))
1859 fs_info->sb->s_bdev = next_device->bdev;
1861 if (fs_info->fs_devices->latest_bdev == device->bdev)
1862 fs_info->fs_devices->latest_bdev = next_device->bdev;
1865 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1866 u64 devid)
1868 struct btrfs_device *device;
1869 struct btrfs_fs_devices *cur_devices;
1870 u64 num_devices;
1871 int ret = 0;
1873 mutex_lock(&uuid_mutex);
1875 num_devices = fs_info->fs_devices->num_devices;
1876 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
1877 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1878 WARN_ON(num_devices < 1);
1879 num_devices--;
1881 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
1883 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1884 if (ret)
1885 goto out;
1887 ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1888 &device);
1889 if (ret)
1890 goto out;
1892 if (device->is_tgtdev_for_dev_replace) {
1893 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1894 goto out;
1897 if (device->writeable && fs_info->fs_devices->rw_devices == 1) {
1898 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1899 goto out;
1902 if (device->writeable) {
1903 mutex_lock(&fs_info->chunk_mutex);
1904 list_del_init(&device->dev_alloc_list);
1905 device->fs_devices->rw_devices--;
1906 mutex_unlock(&fs_info->chunk_mutex);
1909 mutex_unlock(&uuid_mutex);
1910 ret = btrfs_shrink_device(device, 0);
1911 mutex_lock(&uuid_mutex);
1912 if (ret)
1913 goto error_undo;
1916 * TODO: the superblock still includes this device in its num_devices
1917 * counter although write_all_supers() is not locked out. This
1918 * could give a filesystem state which requires a degraded mount.
1920 ret = btrfs_rm_dev_item(fs_info, device);
1921 if (ret)
1922 goto error_undo;
1924 device->in_fs_metadata = 0;
1925 btrfs_scrub_cancel_dev(fs_info, device);
1928 * the device list mutex makes sure that we don't change
1929 * the device list while someone else is writing out all
1930 * the device supers. Whoever is writing all supers, should
1931 * lock the device list mutex before getting the number of
1932 * devices in the super block (super_copy). Conversely,
1933 * whoever updates the number of devices in the super block
1934 * (super_copy) should hold the device list mutex.
1937 cur_devices = device->fs_devices;
1938 mutex_lock(&fs_info->fs_devices->device_list_mutex);
1939 list_del_rcu(&device->dev_list);
1941 device->fs_devices->num_devices--;
1942 device->fs_devices->total_devices--;
1944 if (device->missing)
1945 device->fs_devices->missing_devices--;
1947 btrfs_assign_next_active_device(fs_info, device, NULL);
1949 if (device->bdev) {
1950 device->fs_devices->open_devices--;
1951 /* remove sysfs entry */
1952 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
1955 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1956 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1957 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1960 * at this point, the device is zero sized and detached from
1961 * the devices list. All that's left is to zero out the old
1962 * supers and free the device.
1964 if (device->writeable)
1965 btrfs_scratch_superblocks(device->bdev, device->name->str);
1967 btrfs_close_bdev(device);
1968 call_rcu(&device->rcu, free_device);
1970 if (cur_devices->open_devices == 0) {
1971 struct btrfs_fs_devices *fs_devices;
1972 fs_devices = fs_info->fs_devices;
1973 while (fs_devices) {
1974 if (fs_devices->seed == cur_devices) {
1975 fs_devices->seed = cur_devices->seed;
1976 break;
1978 fs_devices = fs_devices->seed;
1980 cur_devices->seed = NULL;
1981 __btrfs_close_devices(cur_devices);
1982 free_fs_devices(cur_devices);
1985 out:
1986 mutex_unlock(&uuid_mutex);
1987 return ret;
1989 error_undo:
1990 if (device->writeable) {
1991 mutex_lock(&fs_info->chunk_mutex);
1992 list_add(&device->dev_alloc_list,
1993 &fs_info->fs_devices->alloc_list);
1994 device->fs_devices->rw_devices++;
1995 mutex_unlock(&fs_info->chunk_mutex);
1997 goto out;
2000 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2001 struct btrfs_device *srcdev)
2003 struct btrfs_fs_devices *fs_devices;
2005 WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
2008 * in case of fs with no seed, srcdev->fs_devices will point
2009 * to fs_devices of fs_info. However when the dev being replaced is
2010 * a seed dev it will point to the seed's local fs_devices. In short
2011 * srcdev will have its correct fs_devices in both the cases.
2013 fs_devices = srcdev->fs_devices;
2015 list_del_rcu(&srcdev->dev_list);
2016 list_del_rcu(&srcdev->dev_alloc_list);
2017 fs_devices->num_devices--;
2018 if (srcdev->missing)
2019 fs_devices->missing_devices--;
2021 if (srcdev->writeable)
2022 fs_devices->rw_devices--;
2024 if (srcdev->bdev)
2025 fs_devices->open_devices--;
2028 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2029 struct btrfs_device *srcdev)
2031 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2033 if (srcdev->writeable) {
2034 /* zero out the old super if it is writable */
2035 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2038 btrfs_close_bdev(srcdev);
2040 call_rcu(&srcdev->rcu, free_device);
2043 * unless fs_devices is seed fs, num_devices shouldn't go
2044 * zero
2046 BUG_ON(!fs_devices->num_devices && !fs_devices->seeding);
2048 /* if this is no devs we rather delete the fs_devices */
2049 if (!fs_devices->num_devices) {
2050 struct btrfs_fs_devices *tmp_fs_devices;
2052 tmp_fs_devices = fs_info->fs_devices;
2053 while (tmp_fs_devices) {
2054 if (tmp_fs_devices->seed == fs_devices) {
2055 tmp_fs_devices->seed = fs_devices->seed;
2056 break;
2058 tmp_fs_devices = tmp_fs_devices->seed;
2060 fs_devices->seed = NULL;
2061 __btrfs_close_devices(fs_devices);
2062 free_fs_devices(fs_devices);
2066 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2067 struct btrfs_device *tgtdev)
2069 mutex_lock(&uuid_mutex);
2070 WARN_ON(!tgtdev);
2071 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2073 btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2075 if (tgtdev->bdev)
2076 fs_info->fs_devices->open_devices--;
2078 fs_info->fs_devices->num_devices--;
2080 btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2082 list_del_rcu(&tgtdev->dev_list);
2084 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2085 mutex_unlock(&uuid_mutex);
2088 * The update_dev_time() with in btrfs_scratch_superblocks()
2089 * may lead to a call to btrfs_show_devname() which will try
2090 * to hold device_list_mutex. And here this device
2091 * is already out of device list, so we don't have to hold
2092 * the device_list_mutex lock.
2094 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2096 btrfs_close_bdev(tgtdev);
2097 call_rcu(&tgtdev->rcu, free_device);
2100 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2101 const char *device_path,
2102 struct btrfs_device **device)
2104 int ret = 0;
2105 struct btrfs_super_block *disk_super;
2106 u64 devid;
2107 u8 *dev_uuid;
2108 struct block_device *bdev;
2109 struct buffer_head *bh;
2111 *device = NULL;
2112 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2113 fs_info->bdev_holder, 0, &bdev, &bh);
2114 if (ret)
2115 return ret;
2116 disk_super = (struct btrfs_super_block *)bh->b_data;
2117 devid = btrfs_stack_device_id(&disk_super->dev_item);
2118 dev_uuid = disk_super->dev_item.uuid;
2119 *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2120 brelse(bh);
2121 if (!*device)
2122 ret = -ENOENT;
2123 blkdev_put(bdev, FMODE_READ);
2124 return ret;
2127 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2128 const char *device_path,
2129 struct btrfs_device **device)
2131 *device = NULL;
2132 if (strcmp(device_path, "missing") == 0) {
2133 struct list_head *devices;
2134 struct btrfs_device *tmp;
2136 devices = &fs_info->fs_devices->devices;
2138 * It is safe to read the devices since the volume_mutex
2139 * is held by the caller.
2141 list_for_each_entry(tmp, devices, dev_list) {
2142 if (tmp->in_fs_metadata && !tmp->bdev) {
2143 *device = tmp;
2144 break;
2148 if (!*device)
2149 return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2151 return 0;
2152 } else {
2153 return btrfs_find_device_by_path(fs_info, device_path, device);
2158 * Lookup a device given by device id, or the path if the id is 0.
2160 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2161 const char *devpath,
2162 struct btrfs_device **device)
2164 int ret;
2166 if (devid) {
2167 ret = 0;
2168 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2169 if (!*device)
2170 ret = -ENOENT;
2171 } else {
2172 if (!devpath || !devpath[0])
2173 return -EINVAL;
2175 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2176 device);
2178 return ret;
2182 * does all the dirty work required for changing file system's UUID.
2184 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2186 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2187 struct btrfs_fs_devices *old_devices;
2188 struct btrfs_fs_devices *seed_devices;
2189 struct btrfs_super_block *disk_super = fs_info->super_copy;
2190 struct btrfs_device *device;
2191 u64 super_flags;
2193 BUG_ON(!mutex_is_locked(&uuid_mutex));
2194 if (!fs_devices->seeding)
2195 return -EINVAL;
2197 seed_devices = alloc_fs_devices(NULL);
2198 if (IS_ERR(seed_devices))
2199 return PTR_ERR(seed_devices);
2201 old_devices = clone_fs_devices(fs_devices);
2202 if (IS_ERR(old_devices)) {
2203 kfree(seed_devices);
2204 return PTR_ERR(old_devices);
2207 list_add(&old_devices->list, &fs_uuids);
2209 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2210 seed_devices->opened = 1;
2211 INIT_LIST_HEAD(&seed_devices->devices);
2212 INIT_LIST_HEAD(&seed_devices->alloc_list);
2213 mutex_init(&seed_devices->device_list_mutex);
2215 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2216 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2217 synchronize_rcu);
2218 list_for_each_entry(device, &seed_devices->devices, dev_list)
2219 device->fs_devices = seed_devices;
2221 mutex_lock(&fs_info->chunk_mutex);
2222 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2223 mutex_unlock(&fs_info->chunk_mutex);
2225 fs_devices->seeding = 0;
2226 fs_devices->num_devices = 0;
2227 fs_devices->open_devices = 0;
2228 fs_devices->missing_devices = 0;
2229 fs_devices->rotating = 0;
2230 fs_devices->seed = seed_devices;
2232 generate_random_uuid(fs_devices->fsid);
2233 memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2234 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2235 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2237 super_flags = btrfs_super_flags(disk_super) &
2238 ~BTRFS_SUPER_FLAG_SEEDING;
2239 btrfs_set_super_flags(disk_super, super_flags);
2241 return 0;
2245 * Store the expected generation for seed devices in device items.
2247 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2248 struct btrfs_fs_info *fs_info)
2250 struct btrfs_root *root = fs_info->chunk_root;
2251 struct btrfs_path *path;
2252 struct extent_buffer *leaf;
2253 struct btrfs_dev_item *dev_item;
2254 struct btrfs_device *device;
2255 struct btrfs_key key;
2256 u8 fs_uuid[BTRFS_FSID_SIZE];
2257 u8 dev_uuid[BTRFS_UUID_SIZE];
2258 u64 devid;
2259 int ret;
2261 path = btrfs_alloc_path();
2262 if (!path)
2263 return -ENOMEM;
2265 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2266 key.offset = 0;
2267 key.type = BTRFS_DEV_ITEM_KEY;
2269 while (1) {
2270 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2271 if (ret < 0)
2272 goto error;
2274 leaf = path->nodes[0];
2275 next_slot:
2276 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2277 ret = btrfs_next_leaf(root, path);
2278 if (ret > 0)
2279 break;
2280 if (ret < 0)
2281 goto error;
2282 leaf = path->nodes[0];
2283 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2284 btrfs_release_path(path);
2285 continue;
2288 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2289 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2290 key.type != BTRFS_DEV_ITEM_KEY)
2291 break;
2293 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2294 struct btrfs_dev_item);
2295 devid = btrfs_device_id(leaf, dev_item);
2296 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2297 BTRFS_UUID_SIZE);
2298 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2299 BTRFS_FSID_SIZE);
2300 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2301 BUG_ON(!device); /* Logic error */
2303 if (device->fs_devices->seeding) {
2304 btrfs_set_device_generation(leaf, dev_item,
2305 device->generation);
2306 btrfs_mark_buffer_dirty(leaf);
2309 path->slots[0]++;
2310 goto next_slot;
2312 ret = 0;
2313 error:
2314 btrfs_free_path(path);
2315 return ret;
2318 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2320 struct btrfs_root *root = fs_info->dev_root;
2321 struct request_queue *q;
2322 struct btrfs_trans_handle *trans;
2323 struct btrfs_device *device;
2324 struct block_device *bdev;
2325 struct list_head *devices;
2326 struct super_block *sb = fs_info->sb;
2327 struct rcu_string *name;
2328 u64 tmp;
2329 int seeding_dev = 0;
2330 int ret = 0;
2332 if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2333 return -EROFS;
2335 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2336 fs_info->bdev_holder);
2337 if (IS_ERR(bdev))
2338 return PTR_ERR(bdev);
2340 if (fs_info->fs_devices->seeding) {
2341 seeding_dev = 1;
2342 down_write(&sb->s_umount);
2343 mutex_lock(&uuid_mutex);
2346 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2348 devices = &fs_info->fs_devices->devices;
2350 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2351 list_for_each_entry(device, devices, dev_list) {
2352 if (device->bdev == bdev) {
2353 ret = -EEXIST;
2354 mutex_unlock(
2355 &fs_info->fs_devices->device_list_mutex);
2356 goto error;
2359 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2361 device = btrfs_alloc_device(fs_info, NULL, NULL);
2362 if (IS_ERR(device)) {
2363 /* we can safely leave the fs_devices entry around */
2364 ret = PTR_ERR(device);
2365 goto error;
2368 name = rcu_string_strdup(device_path, GFP_KERNEL);
2369 if (!name) {
2370 kfree(device);
2371 ret = -ENOMEM;
2372 goto error;
2374 rcu_assign_pointer(device->name, name);
2376 trans = btrfs_start_transaction(root, 0);
2377 if (IS_ERR(trans)) {
2378 rcu_string_free(device->name);
2379 kfree(device);
2380 ret = PTR_ERR(trans);
2381 goto error;
2384 q = bdev_get_queue(bdev);
2385 if (blk_queue_discard(q))
2386 device->can_discard = 1;
2387 device->writeable = 1;
2388 device->generation = trans->transid;
2389 device->io_width = fs_info->sectorsize;
2390 device->io_align = fs_info->sectorsize;
2391 device->sector_size = fs_info->sectorsize;
2392 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2393 fs_info->sectorsize);
2394 device->disk_total_bytes = device->total_bytes;
2395 device->commit_total_bytes = device->total_bytes;
2396 device->fs_info = fs_info;
2397 device->bdev = bdev;
2398 device->in_fs_metadata = 1;
2399 device->is_tgtdev_for_dev_replace = 0;
2400 device->mode = FMODE_EXCL;
2401 device->dev_stats_valid = 1;
2402 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2404 if (seeding_dev) {
2405 sb->s_flags &= ~MS_RDONLY;
2406 ret = btrfs_prepare_sprout(fs_info);
2407 BUG_ON(ret); /* -ENOMEM */
2410 device->fs_devices = fs_info->fs_devices;
2412 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2413 mutex_lock(&fs_info->chunk_mutex);
2414 list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2415 list_add(&device->dev_alloc_list,
2416 &fs_info->fs_devices->alloc_list);
2417 fs_info->fs_devices->num_devices++;
2418 fs_info->fs_devices->open_devices++;
2419 fs_info->fs_devices->rw_devices++;
2420 fs_info->fs_devices->total_devices++;
2421 fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2423 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2425 if (!blk_queue_nonrot(q))
2426 fs_info->fs_devices->rotating = 1;
2428 tmp = btrfs_super_total_bytes(fs_info->super_copy);
2429 btrfs_set_super_total_bytes(fs_info->super_copy,
2430 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2432 tmp = btrfs_super_num_devices(fs_info->super_copy);
2433 btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2436 * we've got more storage, clear any full flags on the space
2437 * infos
2439 btrfs_clear_space_info_full(fs_info);
2441 mutex_unlock(&fs_info->chunk_mutex);
2443 /* Add sysfs device entry */
2444 btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2446 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2448 if (seeding_dev) {
2449 mutex_lock(&fs_info->chunk_mutex);
2450 ret = init_first_rw_device(trans, fs_info);
2451 mutex_unlock(&fs_info->chunk_mutex);
2452 if (ret) {
2453 btrfs_abort_transaction(trans, ret);
2454 goto error_trans;
2458 ret = btrfs_add_device(trans, fs_info, device);
2459 if (ret) {
2460 btrfs_abort_transaction(trans, ret);
2461 goto error_trans;
2464 if (seeding_dev) {
2465 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2467 ret = btrfs_finish_sprout(trans, fs_info);
2468 if (ret) {
2469 btrfs_abort_transaction(trans, ret);
2470 goto error_trans;
2473 /* Sprouting would change fsid of the mounted root,
2474 * so rename the fsid on the sysfs
2476 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2477 fs_info->fsid);
2478 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2479 btrfs_warn(fs_info,
2480 "sysfs: failed to create fsid for sprout");
2483 ret = btrfs_commit_transaction(trans);
2485 if (seeding_dev) {
2486 mutex_unlock(&uuid_mutex);
2487 up_write(&sb->s_umount);
2489 if (ret) /* transaction commit */
2490 return ret;
2492 ret = btrfs_relocate_sys_chunks(fs_info);
2493 if (ret < 0)
2494 btrfs_handle_fs_error(fs_info, ret,
2495 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2496 trans = btrfs_attach_transaction(root);
2497 if (IS_ERR(trans)) {
2498 if (PTR_ERR(trans) == -ENOENT)
2499 return 0;
2500 return PTR_ERR(trans);
2502 ret = btrfs_commit_transaction(trans);
2505 /* Update ctime/mtime for libblkid */
2506 update_dev_time(device_path);
2507 return ret;
2509 error_trans:
2510 if (seeding_dev)
2511 sb->s_flags |= MS_RDONLY;
2512 btrfs_end_transaction(trans);
2513 rcu_string_free(device->name);
2514 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2515 kfree(device);
2516 error:
2517 blkdev_put(bdev, FMODE_EXCL);
2518 if (seeding_dev) {
2519 mutex_unlock(&uuid_mutex);
2520 up_write(&sb->s_umount);
2522 return ret;
2525 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2526 const char *device_path,
2527 struct btrfs_device *srcdev,
2528 struct btrfs_device **device_out)
2530 struct request_queue *q;
2531 struct btrfs_device *device;
2532 struct block_device *bdev;
2533 struct list_head *devices;
2534 struct rcu_string *name;
2535 u64 devid = BTRFS_DEV_REPLACE_DEVID;
2536 int ret = 0;
2538 *device_out = NULL;
2539 if (fs_info->fs_devices->seeding) {
2540 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2541 return -EINVAL;
2544 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2545 fs_info->bdev_holder);
2546 if (IS_ERR(bdev)) {
2547 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2548 return PTR_ERR(bdev);
2551 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2553 devices = &fs_info->fs_devices->devices;
2554 list_for_each_entry(device, devices, dev_list) {
2555 if (device->bdev == bdev) {
2556 btrfs_err(fs_info,
2557 "target device is in the filesystem!");
2558 ret = -EEXIST;
2559 goto error;
2564 if (i_size_read(bdev->bd_inode) <
2565 btrfs_device_get_total_bytes(srcdev)) {
2566 btrfs_err(fs_info,
2567 "target device is smaller than source device!");
2568 ret = -EINVAL;
2569 goto error;
2573 device = btrfs_alloc_device(NULL, &devid, NULL);
2574 if (IS_ERR(device)) {
2575 ret = PTR_ERR(device);
2576 goto error;
2579 name = rcu_string_strdup(device_path, GFP_KERNEL);
2580 if (!name) {
2581 kfree(device);
2582 ret = -ENOMEM;
2583 goto error;
2585 rcu_assign_pointer(device->name, name);
2587 q = bdev_get_queue(bdev);
2588 if (blk_queue_discard(q))
2589 device->can_discard = 1;
2590 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2591 device->writeable = 1;
2592 device->generation = 0;
2593 device->io_width = fs_info->sectorsize;
2594 device->io_align = fs_info->sectorsize;
2595 device->sector_size = fs_info->sectorsize;
2596 device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2597 device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2598 device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2599 ASSERT(list_empty(&srcdev->resized_list));
2600 device->commit_total_bytes = srcdev->commit_total_bytes;
2601 device->commit_bytes_used = device->bytes_used;
2602 device->fs_info = fs_info;
2603 device->bdev = bdev;
2604 device->in_fs_metadata = 1;
2605 device->is_tgtdev_for_dev_replace = 1;
2606 device->mode = FMODE_EXCL;
2607 device->dev_stats_valid = 1;
2608 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2609 device->fs_devices = fs_info->fs_devices;
2610 list_add(&device->dev_list, &fs_info->fs_devices->devices);
2611 fs_info->fs_devices->num_devices++;
2612 fs_info->fs_devices->open_devices++;
2613 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2615 *device_out = device;
2616 return ret;
2618 error:
2619 blkdev_put(bdev, FMODE_EXCL);
2620 return ret;
2623 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2624 struct btrfs_device *tgtdev)
2626 u32 sectorsize = fs_info->sectorsize;
2628 WARN_ON(fs_info->fs_devices->rw_devices == 0);
2629 tgtdev->io_width = sectorsize;
2630 tgtdev->io_align = sectorsize;
2631 tgtdev->sector_size = sectorsize;
2632 tgtdev->fs_info = fs_info;
2633 tgtdev->in_fs_metadata = 1;
2636 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2637 struct btrfs_device *device)
2639 int ret;
2640 struct btrfs_path *path;
2641 struct btrfs_root *root = device->fs_info->chunk_root;
2642 struct btrfs_dev_item *dev_item;
2643 struct extent_buffer *leaf;
2644 struct btrfs_key key;
2646 path = btrfs_alloc_path();
2647 if (!path)
2648 return -ENOMEM;
2650 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2651 key.type = BTRFS_DEV_ITEM_KEY;
2652 key.offset = device->devid;
2654 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2655 if (ret < 0)
2656 goto out;
2658 if (ret > 0) {
2659 ret = -ENOENT;
2660 goto out;
2663 leaf = path->nodes[0];
2664 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2666 btrfs_set_device_id(leaf, dev_item, device->devid);
2667 btrfs_set_device_type(leaf, dev_item, device->type);
2668 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2669 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2670 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2671 btrfs_set_device_total_bytes(leaf, dev_item,
2672 btrfs_device_get_disk_total_bytes(device));
2673 btrfs_set_device_bytes_used(leaf, dev_item,
2674 btrfs_device_get_bytes_used(device));
2675 btrfs_mark_buffer_dirty(leaf);
2677 out:
2678 btrfs_free_path(path);
2679 return ret;
2682 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2683 struct btrfs_device *device, u64 new_size)
2685 struct btrfs_fs_info *fs_info = device->fs_info;
2686 struct btrfs_super_block *super_copy = fs_info->super_copy;
2687 struct btrfs_fs_devices *fs_devices;
2688 u64 old_total;
2689 u64 diff;
2691 if (!device->writeable)
2692 return -EACCES;
2694 new_size = round_down(new_size, fs_info->sectorsize);
2696 mutex_lock(&fs_info->chunk_mutex);
2697 old_total = btrfs_super_total_bytes(super_copy);
2698 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2700 if (new_size <= device->total_bytes ||
2701 device->is_tgtdev_for_dev_replace) {
2702 mutex_unlock(&fs_info->chunk_mutex);
2703 return -EINVAL;
2706 fs_devices = fs_info->fs_devices;
2708 btrfs_set_super_total_bytes(super_copy,
2709 round_down(old_total + diff, fs_info->sectorsize));
2710 device->fs_devices->total_rw_bytes += diff;
2712 btrfs_device_set_total_bytes(device, new_size);
2713 btrfs_device_set_disk_total_bytes(device, new_size);
2714 btrfs_clear_space_info_full(device->fs_info);
2715 if (list_empty(&device->resized_list))
2716 list_add_tail(&device->resized_list,
2717 &fs_devices->resized_devices);
2718 mutex_unlock(&fs_info->chunk_mutex);
2720 return btrfs_update_device(trans, device);
2723 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2724 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2726 struct btrfs_root *root = fs_info->chunk_root;
2727 int ret;
2728 struct btrfs_path *path;
2729 struct btrfs_key key;
2731 path = btrfs_alloc_path();
2732 if (!path)
2733 return -ENOMEM;
2735 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2736 key.offset = chunk_offset;
2737 key.type = BTRFS_CHUNK_ITEM_KEY;
2739 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2740 if (ret < 0)
2741 goto out;
2742 else if (ret > 0) { /* Logic error or corruption */
2743 btrfs_handle_fs_error(fs_info, -ENOENT,
2744 "Failed lookup while freeing chunk.");
2745 ret = -ENOENT;
2746 goto out;
2749 ret = btrfs_del_item(trans, root, path);
2750 if (ret < 0)
2751 btrfs_handle_fs_error(fs_info, ret,
2752 "Failed to delete chunk item.");
2753 out:
2754 btrfs_free_path(path);
2755 return ret;
2758 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2760 struct btrfs_super_block *super_copy = fs_info->super_copy;
2761 struct btrfs_disk_key *disk_key;
2762 struct btrfs_chunk *chunk;
2763 u8 *ptr;
2764 int ret = 0;
2765 u32 num_stripes;
2766 u32 array_size;
2767 u32 len = 0;
2768 u32 cur;
2769 struct btrfs_key key;
2771 mutex_lock(&fs_info->chunk_mutex);
2772 array_size = btrfs_super_sys_array_size(super_copy);
2774 ptr = super_copy->sys_chunk_array;
2775 cur = 0;
2777 while (cur < array_size) {
2778 disk_key = (struct btrfs_disk_key *)ptr;
2779 btrfs_disk_key_to_cpu(&key, disk_key);
2781 len = sizeof(*disk_key);
2783 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2784 chunk = (struct btrfs_chunk *)(ptr + len);
2785 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2786 len += btrfs_chunk_item_size(num_stripes);
2787 } else {
2788 ret = -EIO;
2789 break;
2791 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2792 key.offset == chunk_offset) {
2793 memmove(ptr, ptr + len, array_size - (cur + len));
2794 array_size -= len;
2795 btrfs_set_super_sys_array_size(super_copy, array_size);
2796 } else {
2797 ptr += len;
2798 cur += len;
2801 mutex_unlock(&fs_info->chunk_mutex);
2802 return ret;
2805 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2806 u64 logical, u64 length)
2808 struct extent_map_tree *em_tree;
2809 struct extent_map *em;
2811 em_tree = &fs_info->mapping_tree.map_tree;
2812 read_lock(&em_tree->lock);
2813 em = lookup_extent_mapping(em_tree, logical, length);
2814 read_unlock(&em_tree->lock);
2816 if (!em) {
2817 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2818 logical, length);
2819 return ERR_PTR(-EINVAL);
2822 if (em->start > logical || em->start + em->len < logical) {
2823 btrfs_crit(fs_info,
2824 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2825 logical, length, em->start, em->start + em->len);
2826 free_extent_map(em);
2827 return ERR_PTR(-EINVAL);
2830 /* callers are responsible for dropping em's ref. */
2831 return em;
2834 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2835 struct btrfs_fs_info *fs_info, u64 chunk_offset)
2837 struct extent_map *em;
2838 struct map_lookup *map;
2839 u64 dev_extent_len = 0;
2840 int i, ret = 0;
2841 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2843 em = get_chunk_map(fs_info, chunk_offset, 1);
2844 if (IS_ERR(em)) {
2846 * This is a logic error, but we don't want to just rely on the
2847 * user having built with ASSERT enabled, so if ASSERT doesn't
2848 * do anything we still error out.
2850 ASSERT(0);
2851 return PTR_ERR(em);
2853 map = em->map_lookup;
2854 mutex_lock(&fs_info->chunk_mutex);
2855 check_system_chunk(trans, fs_info, map->type);
2856 mutex_unlock(&fs_info->chunk_mutex);
2859 * Take the device list mutex to prevent races with the final phase of
2860 * a device replace operation that replaces the device object associated
2861 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2863 mutex_lock(&fs_devices->device_list_mutex);
2864 for (i = 0; i < map->num_stripes; i++) {
2865 struct btrfs_device *device = map->stripes[i].dev;
2866 ret = btrfs_free_dev_extent(trans, device,
2867 map->stripes[i].physical,
2868 &dev_extent_len);
2869 if (ret) {
2870 mutex_unlock(&fs_devices->device_list_mutex);
2871 btrfs_abort_transaction(trans, ret);
2872 goto out;
2875 if (device->bytes_used > 0) {
2876 mutex_lock(&fs_info->chunk_mutex);
2877 btrfs_device_set_bytes_used(device,
2878 device->bytes_used - dev_extent_len);
2879 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2880 btrfs_clear_space_info_full(fs_info);
2881 mutex_unlock(&fs_info->chunk_mutex);
2884 if (map->stripes[i].dev) {
2885 ret = btrfs_update_device(trans, map->stripes[i].dev);
2886 if (ret) {
2887 mutex_unlock(&fs_devices->device_list_mutex);
2888 btrfs_abort_transaction(trans, ret);
2889 goto out;
2893 mutex_unlock(&fs_devices->device_list_mutex);
2895 ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2896 if (ret) {
2897 btrfs_abort_transaction(trans, ret);
2898 goto out;
2901 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2903 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2904 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2905 if (ret) {
2906 btrfs_abort_transaction(trans, ret);
2907 goto out;
2911 ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2912 if (ret) {
2913 btrfs_abort_transaction(trans, ret);
2914 goto out;
2917 out:
2918 /* once for us */
2919 free_extent_map(em);
2920 return ret;
2923 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2925 struct btrfs_root *root = fs_info->chunk_root;
2926 struct btrfs_trans_handle *trans;
2927 int ret;
2930 * Prevent races with automatic removal of unused block groups.
2931 * After we relocate and before we remove the chunk with offset
2932 * chunk_offset, automatic removal of the block group can kick in,
2933 * resulting in a failure when calling btrfs_remove_chunk() below.
2935 * Make sure to acquire this mutex before doing a tree search (dev
2936 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2937 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2938 * we release the path used to search the chunk/dev tree and before
2939 * the current task acquires this mutex and calls us.
2941 ASSERT(mutex_is_locked(&fs_info->delete_unused_bgs_mutex));
2943 ret = btrfs_can_relocate(fs_info, chunk_offset);
2944 if (ret)
2945 return -ENOSPC;
2947 /* step one, relocate all the extents inside this chunk */
2948 btrfs_scrub_pause(fs_info);
2949 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2950 btrfs_scrub_continue(fs_info);
2951 if (ret)
2952 return ret;
2954 trans = btrfs_start_trans_remove_block_group(root->fs_info,
2955 chunk_offset);
2956 if (IS_ERR(trans)) {
2957 ret = PTR_ERR(trans);
2958 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2959 return ret;
2963 * step two, delete the device extents and the
2964 * chunk tree entries
2966 ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
2967 btrfs_end_transaction(trans);
2968 return ret;
2971 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2973 struct btrfs_root *chunk_root = fs_info->chunk_root;
2974 struct btrfs_path *path;
2975 struct extent_buffer *leaf;
2976 struct btrfs_chunk *chunk;
2977 struct btrfs_key key;
2978 struct btrfs_key found_key;
2979 u64 chunk_type;
2980 bool retried = false;
2981 int failed = 0;
2982 int ret;
2984 path = btrfs_alloc_path();
2985 if (!path)
2986 return -ENOMEM;
2988 again:
2989 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2990 key.offset = (u64)-1;
2991 key.type = BTRFS_CHUNK_ITEM_KEY;
2993 while (1) {
2994 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2995 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2996 if (ret < 0) {
2997 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2998 goto error;
3000 BUG_ON(ret == 0); /* Corruption */
3002 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3003 key.type);
3004 if (ret)
3005 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3006 if (ret < 0)
3007 goto error;
3008 if (ret > 0)
3009 break;
3011 leaf = path->nodes[0];
3012 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3014 chunk = btrfs_item_ptr(leaf, path->slots[0],
3015 struct btrfs_chunk);
3016 chunk_type = btrfs_chunk_type(leaf, chunk);
3017 btrfs_release_path(path);
3019 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3020 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3021 if (ret == -ENOSPC)
3022 failed++;
3023 else
3024 BUG_ON(ret);
3026 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3028 if (found_key.offset == 0)
3029 break;
3030 key.offset = found_key.offset - 1;
3032 ret = 0;
3033 if (failed && !retried) {
3034 failed = 0;
3035 retried = true;
3036 goto again;
3037 } else if (WARN_ON(failed && retried)) {
3038 ret = -ENOSPC;
3040 error:
3041 btrfs_free_path(path);
3042 return ret;
3045 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3046 struct btrfs_balance_control *bctl)
3048 struct btrfs_root *root = fs_info->tree_root;
3049 struct btrfs_trans_handle *trans;
3050 struct btrfs_balance_item *item;
3051 struct btrfs_disk_balance_args disk_bargs;
3052 struct btrfs_path *path;
3053 struct extent_buffer *leaf;
3054 struct btrfs_key key;
3055 int ret, err;
3057 path = btrfs_alloc_path();
3058 if (!path)
3059 return -ENOMEM;
3061 trans = btrfs_start_transaction(root, 0);
3062 if (IS_ERR(trans)) {
3063 btrfs_free_path(path);
3064 return PTR_ERR(trans);
3067 key.objectid = BTRFS_BALANCE_OBJECTID;
3068 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3069 key.offset = 0;
3071 ret = btrfs_insert_empty_item(trans, root, path, &key,
3072 sizeof(*item));
3073 if (ret)
3074 goto out;
3076 leaf = path->nodes[0];
3077 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3079 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3081 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3082 btrfs_set_balance_data(leaf, item, &disk_bargs);
3083 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3084 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3085 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3086 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3088 btrfs_set_balance_flags(leaf, item, bctl->flags);
3090 btrfs_mark_buffer_dirty(leaf);
3091 out:
3092 btrfs_free_path(path);
3093 err = btrfs_commit_transaction(trans);
3094 if (err && !ret)
3095 ret = err;
3096 return ret;
3099 static int del_balance_item(struct btrfs_fs_info *fs_info)
3101 struct btrfs_root *root = fs_info->tree_root;
3102 struct btrfs_trans_handle *trans;
3103 struct btrfs_path *path;
3104 struct btrfs_key key;
3105 int ret, err;
3107 path = btrfs_alloc_path();
3108 if (!path)
3109 return -ENOMEM;
3111 trans = btrfs_start_transaction(root, 0);
3112 if (IS_ERR(trans)) {
3113 btrfs_free_path(path);
3114 return PTR_ERR(trans);
3117 key.objectid = BTRFS_BALANCE_OBJECTID;
3118 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3119 key.offset = 0;
3121 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3122 if (ret < 0)
3123 goto out;
3124 if (ret > 0) {
3125 ret = -ENOENT;
3126 goto out;
3129 ret = btrfs_del_item(trans, root, path);
3130 out:
3131 btrfs_free_path(path);
3132 err = btrfs_commit_transaction(trans);
3133 if (err && !ret)
3134 ret = err;
3135 return ret;
3139 * This is a heuristic used to reduce the number of chunks balanced on
3140 * resume after balance was interrupted.
3142 static void update_balance_args(struct btrfs_balance_control *bctl)
3145 * Turn on soft mode for chunk types that were being converted.
3147 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3148 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3149 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3150 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3151 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3152 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3155 * Turn on usage filter if is not already used. The idea is
3156 * that chunks that we have already balanced should be
3157 * reasonably full. Don't do it for chunks that are being
3158 * converted - that will keep us from relocating unconverted
3159 * (albeit full) chunks.
3161 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3162 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3163 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3164 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3165 bctl->data.usage = 90;
3167 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3168 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3169 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3170 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3171 bctl->sys.usage = 90;
3173 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3174 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3175 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3176 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3177 bctl->meta.usage = 90;
3182 * Should be called with both balance and volume mutexes held to
3183 * serialize other volume operations (add_dev/rm_dev/resize) with
3184 * restriper. Same goes for unset_balance_control.
3186 static void set_balance_control(struct btrfs_balance_control *bctl)
3188 struct btrfs_fs_info *fs_info = bctl->fs_info;
3190 BUG_ON(fs_info->balance_ctl);
3192 spin_lock(&fs_info->balance_lock);
3193 fs_info->balance_ctl = bctl;
3194 spin_unlock(&fs_info->balance_lock);
3197 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3199 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3201 BUG_ON(!fs_info->balance_ctl);
3203 spin_lock(&fs_info->balance_lock);
3204 fs_info->balance_ctl = NULL;
3205 spin_unlock(&fs_info->balance_lock);
3207 kfree(bctl);
3211 * Balance filters. Return 1 if chunk should be filtered out
3212 * (should not be balanced).
3214 static int chunk_profiles_filter(u64 chunk_type,
3215 struct btrfs_balance_args *bargs)
3217 chunk_type = chunk_to_extended(chunk_type) &
3218 BTRFS_EXTENDED_PROFILE_MASK;
3220 if (bargs->profiles & chunk_type)
3221 return 0;
3223 return 1;
3226 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3227 struct btrfs_balance_args *bargs)
3229 struct btrfs_block_group_cache *cache;
3230 u64 chunk_used;
3231 u64 user_thresh_min;
3232 u64 user_thresh_max;
3233 int ret = 1;
3235 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3236 chunk_used = btrfs_block_group_used(&cache->item);
3238 if (bargs->usage_min == 0)
3239 user_thresh_min = 0;
3240 else
3241 user_thresh_min = div_factor_fine(cache->key.offset,
3242 bargs->usage_min);
3244 if (bargs->usage_max == 0)
3245 user_thresh_max = 1;
3246 else if (bargs->usage_max > 100)
3247 user_thresh_max = cache->key.offset;
3248 else
3249 user_thresh_max = div_factor_fine(cache->key.offset,
3250 bargs->usage_max);
3252 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3253 ret = 0;
3255 btrfs_put_block_group(cache);
3256 return ret;
3259 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3260 u64 chunk_offset, struct btrfs_balance_args *bargs)
3262 struct btrfs_block_group_cache *cache;
3263 u64 chunk_used, user_thresh;
3264 int ret = 1;
3266 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3267 chunk_used = btrfs_block_group_used(&cache->item);
3269 if (bargs->usage_min == 0)
3270 user_thresh = 1;
3271 else if (bargs->usage > 100)
3272 user_thresh = cache->key.offset;
3273 else
3274 user_thresh = div_factor_fine(cache->key.offset,
3275 bargs->usage);
3277 if (chunk_used < user_thresh)
3278 ret = 0;
3280 btrfs_put_block_group(cache);
3281 return ret;
3284 static int chunk_devid_filter(struct extent_buffer *leaf,
3285 struct btrfs_chunk *chunk,
3286 struct btrfs_balance_args *bargs)
3288 struct btrfs_stripe *stripe;
3289 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3290 int i;
3292 for (i = 0; i < num_stripes; i++) {
3293 stripe = btrfs_stripe_nr(chunk, i);
3294 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3295 return 0;
3298 return 1;
3301 /* [pstart, pend) */
3302 static int chunk_drange_filter(struct extent_buffer *leaf,
3303 struct btrfs_chunk *chunk,
3304 struct btrfs_balance_args *bargs)
3306 struct btrfs_stripe *stripe;
3307 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3308 u64 stripe_offset;
3309 u64 stripe_length;
3310 int factor;
3311 int i;
3313 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3314 return 0;
3316 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3317 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3318 factor = num_stripes / 2;
3319 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3320 factor = num_stripes - 1;
3321 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3322 factor = num_stripes - 2;
3323 } else {
3324 factor = num_stripes;
3327 for (i = 0; i < num_stripes; i++) {
3328 stripe = btrfs_stripe_nr(chunk, i);
3329 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3330 continue;
3332 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3333 stripe_length = btrfs_chunk_length(leaf, chunk);
3334 stripe_length = div_u64(stripe_length, factor);
3336 if (stripe_offset < bargs->pend &&
3337 stripe_offset + stripe_length > bargs->pstart)
3338 return 0;
3341 return 1;
3344 /* [vstart, vend) */
3345 static int chunk_vrange_filter(struct extent_buffer *leaf,
3346 struct btrfs_chunk *chunk,
3347 u64 chunk_offset,
3348 struct btrfs_balance_args *bargs)
3350 if (chunk_offset < bargs->vend &&
3351 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3352 /* at least part of the chunk is inside this vrange */
3353 return 0;
3355 return 1;
3358 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3359 struct btrfs_chunk *chunk,
3360 struct btrfs_balance_args *bargs)
3362 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3364 if (bargs->stripes_min <= num_stripes
3365 && num_stripes <= bargs->stripes_max)
3366 return 0;
3368 return 1;
3371 static int chunk_soft_convert_filter(u64 chunk_type,
3372 struct btrfs_balance_args *bargs)
3374 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3375 return 0;
3377 chunk_type = chunk_to_extended(chunk_type) &
3378 BTRFS_EXTENDED_PROFILE_MASK;
3380 if (bargs->target == chunk_type)
3381 return 1;
3383 return 0;
3386 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3387 struct extent_buffer *leaf,
3388 struct btrfs_chunk *chunk, u64 chunk_offset)
3390 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3391 struct btrfs_balance_args *bargs = NULL;
3392 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3394 /* type filter */
3395 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3396 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3397 return 0;
3400 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3401 bargs = &bctl->data;
3402 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3403 bargs = &bctl->sys;
3404 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3405 bargs = &bctl->meta;
3407 /* profiles filter */
3408 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3409 chunk_profiles_filter(chunk_type, bargs)) {
3410 return 0;
3413 /* usage filter */
3414 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3415 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3416 return 0;
3417 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3418 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3419 return 0;
3422 /* devid filter */
3423 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3424 chunk_devid_filter(leaf, chunk, bargs)) {
3425 return 0;
3428 /* drange filter, makes sense only with devid filter */
3429 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3430 chunk_drange_filter(leaf, chunk, bargs)) {
3431 return 0;
3434 /* vrange filter */
3435 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3436 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3437 return 0;
3440 /* stripes filter */
3441 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3442 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3443 return 0;
3446 /* soft profile changing mode */
3447 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3448 chunk_soft_convert_filter(chunk_type, bargs)) {
3449 return 0;
3453 * limited by count, must be the last filter
3455 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3456 if (bargs->limit == 0)
3457 return 0;
3458 else
3459 bargs->limit--;
3460 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3462 * Same logic as the 'limit' filter; the minimum cannot be
3463 * determined here because we do not have the global information
3464 * about the count of all chunks that satisfy the filters.
3466 if (bargs->limit_max == 0)
3467 return 0;
3468 else
3469 bargs->limit_max--;
3472 return 1;
3475 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3477 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3478 struct btrfs_root *chunk_root = fs_info->chunk_root;
3479 struct btrfs_root *dev_root = fs_info->dev_root;
3480 struct list_head *devices;
3481 struct btrfs_device *device;
3482 u64 old_size;
3483 u64 size_to_free;
3484 u64 chunk_type;
3485 struct btrfs_chunk *chunk;
3486 struct btrfs_path *path = NULL;
3487 struct btrfs_key key;
3488 struct btrfs_key found_key;
3489 struct btrfs_trans_handle *trans;
3490 struct extent_buffer *leaf;
3491 int slot;
3492 int ret;
3493 int enospc_errors = 0;
3494 bool counting = true;
3495 /* The single value limit and min/max limits use the same bytes in the */
3496 u64 limit_data = bctl->data.limit;
3497 u64 limit_meta = bctl->meta.limit;
3498 u64 limit_sys = bctl->sys.limit;
3499 u32 count_data = 0;
3500 u32 count_meta = 0;
3501 u32 count_sys = 0;
3502 int chunk_reserved = 0;
3503 u64 bytes_used = 0;
3505 /* step one make some room on all the devices */
3506 devices = &fs_info->fs_devices->devices;
3507 list_for_each_entry(device, devices, dev_list) {
3508 old_size = btrfs_device_get_total_bytes(device);
3509 size_to_free = div_factor(old_size, 1);
3510 size_to_free = min_t(u64, size_to_free, SZ_1M);
3511 if (!device->writeable ||
3512 btrfs_device_get_total_bytes(device) -
3513 btrfs_device_get_bytes_used(device) > size_to_free ||
3514 device->is_tgtdev_for_dev_replace)
3515 continue;
3517 ret = btrfs_shrink_device(device, old_size - size_to_free);
3518 if (ret == -ENOSPC)
3519 break;
3520 if (ret) {
3521 /* btrfs_shrink_device never returns ret > 0 */
3522 WARN_ON(ret > 0);
3523 goto error;
3526 trans = btrfs_start_transaction(dev_root, 0);
3527 if (IS_ERR(trans)) {
3528 ret = PTR_ERR(trans);
3529 btrfs_info_in_rcu(fs_info,
3530 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3531 rcu_str_deref(device->name), ret,
3532 old_size, old_size - size_to_free);
3533 goto error;
3536 ret = btrfs_grow_device(trans, device, old_size);
3537 if (ret) {
3538 btrfs_end_transaction(trans);
3539 /* btrfs_grow_device never returns ret > 0 */
3540 WARN_ON(ret > 0);
3541 btrfs_info_in_rcu(fs_info,
3542 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3543 rcu_str_deref(device->name), ret,
3544 old_size, old_size - size_to_free);
3545 goto error;
3548 btrfs_end_transaction(trans);
3551 /* step two, relocate all the chunks */
3552 path = btrfs_alloc_path();
3553 if (!path) {
3554 ret = -ENOMEM;
3555 goto error;
3558 /* zero out stat counters */
3559 spin_lock(&fs_info->balance_lock);
3560 memset(&bctl->stat, 0, sizeof(bctl->stat));
3561 spin_unlock(&fs_info->balance_lock);
3562 again:
3563 if (!counting) {
3565 * The single value limit and min/max limits use the same bytes
3566 * in the
3568 bctl->data.limit = limit_data;
3569 bctl->meta.limit = limit_meta;
3570 bctl->sys.limit = limit_sys;
3572 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3573 key.offset = (u64)-1;
3574 key.type = BTRFS_CHUNK_ITEM_KEY;
3576 while (1) {
3577 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3578 atomic_read(&fs_info->balance_cancel_req)) {
3579 ret = -ECANCELED;
3580 goto error;
3583 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3584 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3585 if (ret < 0) {
3586 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3587 goto error;
3591 * this shouldn't happen, it means the last relocate
3592 * failed
3594 if (ret == 0)
3595 BUG(); /* FIXME break ? */
3597 ret = btrfs_previous_item(chunk_root, path, 0,
3598 BTRFS_CHUNK_ITEM_KEY);
3599 if (ret) {
3600 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3601 ret = 0;
3602 break;
3605 leaf = path->nodes[0];
3606 slot = path->slots[0];
3607 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3609 if (found_key.objectid != key.objectid) {
3610 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3611 break;
3614 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3615 chunk_type = btrfs_chunk_type(leaf, chunk);
3617 if (!counting) {
3618 spin_lock(&fs_info->balance_lock);
3619 bctl->stat.considered++;
3620 spin_unlock(&fs_info->balance_lock);
3623 ret = should_balance_chunk(fs_info, leaf, chunk,
3624 found_key.offset);
3626 btrfs_release_path(path);
3627 if (!ret) {
3628 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3629 goto loop;
3632 if (counting) {
3633 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3634 spin_lock(&fs_info->balance_lock);
3635 bctl->stat.expected++;
3636 spin_unlock(&fs_info->balance_lock);
3638 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3639 count_data++;
3640 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3641 count_sys++;
3642 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3643 count_meta++;
3645 goto loop;
3649 * Apply limit_min filter, no need to check if the LIMITS
3650 * filter is used, limit_min is 0 by default
3652 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3653 count_data < bctl->data.limit_min)
3654 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3655 count_meta < bctl->meta.limit_min)
3656 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3657 count_sys < bctl->sys.limit_min)) {
3658 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3659 goto loop;
3662 ASSERT(fs_info->data_sinfo);
3663 spin_lock(&fs_info->data_sinfo->lock);
3664 bytes_used = fs_info->data_sinfo->bytes_used;
3665 spin_unlock(&fs_info->data_sinfo->lock);
3667 if ((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3668 !chunk_reserved && !bytes_used) {
3669 trans = btrfs_start_transaction(chunk_root, 0);
3670 if (IS_ERR(trans)) {
3671 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3672 ret = PTR_ERR(trans);
3673 goto error;
3676 ret = btrfs_force_chunk_alloc(trans, fs_info,
3677 BTRFS_BLOCK_GROUP_DATA);
3678 btrfs_end_transaction(trans);
3679 if (ret < 0) {
3680 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3681 goto error;
3683 chunk_reserved = 1;
3686 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3687 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3688 if (ret && ret != -ENOSPC)
3689 goto error;
3690 if (ret == -ENOSPC) {
3691 enospc_errors++;
3692 } else {
3693 spin_lock(&fs_info->balance_lock);
3694 bctl->stat.completed++;
3695 spin_unlock(&fs_info->balance_lock);
3697 loop:
3698 if (found_key.offset == 0)
3699 break;
3700 key.offset = found_key.offset - 1;
3703 if (counting) {
3704 btrfs_release_path(path);
3705 counting = false;
3706 goto again;
3708 error:
3709 btrfs_free_path(path);
3710 if (enospc_errors) {
3711 btrfs_info(fs_info, "%d enospc errors during balance",
3712 enospc_errors);
3713 if (!ret)
3714 ret = -ENOSPC;
3717 return ret;
3721 * alloc_profile_is_valid - see if a given profile is valid and reduced
3722 * @flags: profile to validate
3723 * @extended: if true @flags is treated as an extended profile
3725 static int alloc_profile_is_valid(u64 flags, int extended)
3727 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3728 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3730 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3732 /* 1) check that all other bits are zeroed */
3733 if (flags & ~mask)
3734 return 0;
3736 /* 2) see if profile is reduced */
3737 if (flags == 0)
3738 return !extended; /* "0" is valid for usual profiles */
3740 /* true if exactly one bit set */
3741 return (flags & (flags - 1)) == 0;
3744 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3746 /* cancel requested || normal exit path */
3747 return atomic_read(&fs_info->balance_cancel_req) ||
3748 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3749 atomic_read(&fs_info->balance_cancel_req) == 0);
3752 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3754 int ret;
3756 unset_balance_control(fs_info);
3757 ret = del_balance_item(fs_info);
3758 if (ret)
3759 btrfs_handle_fs_error(fs_info, ret, NULL);
3761 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3764 /* Non-zero return value signifies invalidity */
3765 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3766 u64 allowed)
3768 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3769 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3770 (bctl_arg->target & ~allowed)));
3774 * Should be called with both balance and volume mutexes held
3776 int btrfs_balance(struct btrfs_balance_control *bctl,
3777 struct btrfs_ioctl_balance_args *bargs)
3779 struct btrfs_fs_info *fs_info = bctl->fs_info;
3780 u64 meta_target, data_target;
3781 u64 allowed;
3782 int mixed = 0;
3783 int ret;
3784 u64 num_devices;
3785 unsigned seq;
3787 if (btrfs_fs_closing(fs_info) ||
3788 atomic_read(&fs_info->balance_pause_req) ||
3789 atomic_read(&fs_info->balance_cancel_req)) {
3790 ret = -EINVAL;
3791 goto out;
3794 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3795 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3796 mixed = 1;
3799 * In case of mixed groups both data and meta should be picked,
3800 * and identical options should be given for both of them.
3802 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3803 if (mixed && (bctl->flags & allowed)) {
3804 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3805 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3806 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3807 btrfs_err(fs_info,
3808 "with mixed groups data and metadata balance options must be the same");
3809 ret = -EINVAL;
3810 goto out;
3814 num_devices = fs_info->fs_devices->num_devices;
3815 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
3816 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3817 BUG_ON(num_devices < 1);
3818 num_devices--;
3820 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
3821 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3822 if (num_devices > 1)
3823 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3824 if (num_devices > 2)
3825 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3826 if (num_devices > 3)
3827 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3828 BTRFS_BLOCK_GROUP_RAID6);
3829 if (validate_convert_profile(&bctl->data, allowed)) {
3830 btrfs_err(fs_info,
3831 "unable to start balance with target data profile %llu",
3832 bctl->data.target);
3833 ret = -EINVAL;
3834 goto out;
3836 if (validate_convert_profile(&bctl->meta, allowed)) {
3837 btrfs_err(fs_info,
3838 "unable to start balance with target metadata profile %llu",
3839 bctl->meta.target);
3840 ret = -EINVAL;
3841 goto out;
3843 if (validate_convert_profile(&bctl->sys, allowed)) {
3844 btrfs_err(fs_info,
3845 "unable to start balance with target system profile %llu",
3846 bctl->sys.target);
3847 ret = -EINVAL;
3848 goto out;
3851 /* allow to reduce meta or sys integrity only if force set */
3852 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3853 BTRFS_BLOCK_GROUP_RAID10 |
3854 BTRFS_BLOCK_GROUP_RAID5 |
3855 BTRFS_BLOCK_GROUP_RAID6;
3856 do {
3857 seq = read_seqbegin(&fs_info->profiles_lock);
3859 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3860 (fs_info->avail_system_alloc_bits & allowed) &&
3861 !(bctl->sys.target & allowed)) ||
3862 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3863 (fs_info->avail_metadata_alloc_bits & allowed) &&
3864 !(bctl->meta.target & allowed))) {
3865 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3866 btrfs_info(fs_info,
3867 "force reducing metadata integrity");
3868 } else {
3869 btrfs_err(fs_info,
3870 "balance will reduce metadata integrity, use force if you want this");
3871 ret = -EINVAL;
3872 goto out;
3875 } while (read_seqretry(&fs_info->profiles_lock, seq));
3877 /* if we're not converting, the target field is uninitialized */
3878 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3879 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3880 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3881 bctl->data.target : fs_info->avail_data_alloc_bits;
3882 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3883 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3884 btrfs_warn(fs_info,
3885 "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
3886 meta_target, data_target);
3889 ret = insert_balance_item(fs_info, bctl);
3890 if (ret && ret != -EEXIST)
3891 goto out;
3893 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3894 BUG_ON(ret == -EEXIST);
3895 set_balance_control(bctl);
3896 } else {
3897 BUG_ON(ret != -EEXIST);
3898 spin_lock(&fs_info->balance_lock);
3899 update_balance_args(bctl);
3900 spin_unlock(&fs_info->balance_lock);
3903 atomic_inc(&fs_info->balance_running);
3904 mutex_unlock(&fs_info->balance_mutex);
3906 ret = __btrfs_balance(fs_info);
3908 mutex_lock(&fs_info->balance_mutex);
3909 atomic_dec(&fs_info->balance_running);
3911 if (bargs) {
3912 memset(bargs, 0, sizeof(*bargs));
3913 update_ioctl_balance_args(fs_info, 0, bargs);
3916 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3917 balance_need_close(fs_info)) {
3918 __cancel_balance(fs_info);
3921 wake_up(&fs_info->balance_wait_q);
3923 return ret;
3924 out:
3925 if (bctl->flags & BTRFS_BALANCE_RESUME)
3926 __cancel_balance(fs_info);
3927 else {
3928 kfree(bctl);
3929 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3931 return ret;
3934 static int balance_kthread(void *data)
3936 struct btrfs_fs_info *fs_info = data;
3937 int ret = 0;
3939 mutex_lock(&fs_info->volume_mutex);
3940 mutex_lock(&fs_info->balance_mutex);
3942 if (fs_info->balance_ctl) {
3943 btrfs_info(fs_info, "continuing balance");
3944 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3947 mutex_unlock(&fs_info->balance_mutex);
3948 mutex_unlock(&fs_info->volume_mutex);
3950 return ret;
3953 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3955 struct task_struct *tsk;
3957 spin_lock(&fs_info->balance_lock);
3958 if (!fs_info->balance_ctl) {
3959 spin_unlock(&fs_info->balance_lock);
3960 return 0;
3962 spin_unlock(&fs_info->balance_lock);
3964 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3965 btrfs_info(fs_info, "force skipping balance");
3966 return 0;
3970 * A ro->rw remount sequence should continue with the paused balance
3971 * regardless of who pauses it, system or the user as of now, so set
3972 * the resume flag.
3974 spin_lock(&fs_info->balance_lock);
3975 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3976 spin_unlock(&fs_info->balance_lock);
3978 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3979 return PTR_ERR_OR_ZERO(tsk);
3982 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3984 struct btrfs_balance_control *bctl;
3985 struct btrfs_balance_item *item;
3986 struct btrfs_disk_balance_args disk_bargs;
3987 struct btrfs_path *path;
3988 struct extent_buffer *leaf;
3989 struct btrfs_key key;
3990 int ret;
3992 path = btrfs_alloc_path();
3993 if (!path)
3994 return -ENOMEM;
3996 key.objectid = BTRFS_BALANCE_OBJECTID;
3997 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3998 key.offset = 0;
4000 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4001 if (ret < 0)
4002 goto out;
4003 if (ret > 0) { /* ret = -ENOENT; */
4004 ret = 0;
4005 goto out;
4008 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4009 if (!bctl) {
4010 ret = -ENOMEM;
4011 goto out;
4014 leaf = path->nodes[0];
4015 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4017 bctl->fs_info = fs_info;
4018 bctl->flags = btrfs_balance_flags(leaf, item);
4019 bctl->flags |= BTRFS_BALANCE_RESUME;
4021 btrfs_balance_data(leaf, item, &disk_bargs);
4022 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4023 btrfs_balance_meta(leaf, item, &disk_bargs);
4024 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4025 btrfs_balance_sys(leaf, item, &disk_bargs);
4026 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4028 WARN_ON(test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4030 mutex_lock(&fs_info->volume_mutex);
4031 mutex_lock(&fs_info->balance_mutex);
4033 set_balance_control(bctl);
4035 mutex_unlock(&fs_info->balance_mutex);
4036 mutex_unlock(&fs_info->volume_mutex);
4037 out:
4038 btrfs_free_path(path);
4039 return ret;
4042 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4044 int ret = 0;
4046 mutex_lock(&fs_info->balance_mutex);
4047 if (!fs_info->balance_ctl) {
4048 mutex_unlock(&fs_info->balance_mutex);
4049 return -ENOTCONN;
4052 if (atomic_read(&fs_info->balance_running)) {
4053 atomic_inc(&fs_info->balance_pause_req);
4054 mutex_unlock(&fs_info->balance_mutex);
4056 wait_event(fs_info->balance_wait_q,
4057 atomic_read(&fs_info->balance_running) == 0);
4059 mutex_lock(&fs_info->balance_mutex);
4060 /* we are good with balance_ctl ripped off from under us */
4061 BUG_ON(atomic_read(&fs_info->balance_running));
4062 atomic_dec(&fs_info->balance_pause_req);
4063 } else {
4064 ret = -ENOTCONN;
4067 mutex_unlock(&fs_info->balance_mutex);
4068 return ret;
4071 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4073 if (sb_rdonly(fs_info->sb))
4074 return -EROFS;
4076 mutex_lock(&fs_info->balance_mutex);
4077 if (!fs_info->balance_ctl) {
4078 mutex_unlock(&fs_info->balance_mutex);
4079 return -ENOTCONN;
4082 atomic_inc(&fs_info->balance_cancel_req);
4084 * if we are running just wait and return, balance item is
4085 * deleted in btrfs_balance in this case
4087 if (atomic_read(&fs_info->balance_running)) {
4088 mutex_unlock(&fs_info->balance_mutex);
4089 wait_event(fs_info->balance_wait_q,
4090 atomic_read(&fs_info->balance_running) == 0);
4091 mutex_lock(&fs_info->balance_mutex);
4092 } else {
4093 /* __cancel_balance needs volume_mutex */
4094 mutex_unlock(&fs_info->balance_mutex);
4095 mutex_lock(&fs_info->volume_mutex);
4096 mutex_lock(&fs_info->balance_mutex);
4098 if (fs_info->balance_ctl)
4099 __cancel_balance(fs_info);
4101 mutex_unlock(&fs_info->volume_mutex);
4104 BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
4105 atomic_dec(&fs_info->balance_cancel_req);
4106 mutex_unlock(&fs_info->balance_mutex);
4107 return 0;
4110 static int btrfs_uuid_scan_kthread(void *data)
4112 struct btrfs_fs_info *fs_info = data;
4113 struct btrfs_root *root = fs_info->tree_root;
4114 struct btrfs_key key;
4115 struct btrfs_path *path = NULL;
4116 int ret = 0;
4117 struct extent_buffer *eb;
4118 int slot;
4119 struct btrfs_root_item root_item;
4120 u32 item_size;
4121 struct btrfs_trans_handle *trans = NULL;
4123 path = btrfs_alloc_path();
4124 if (!path) {
4125 ret = -ENOMEM;
4126 goto out;
4129 key.objectid = 0;
4130 key.type = BTRFS_ROOT_ITEM_KEY;
4131 key.offset = 0;
4133 while (1) {
4134 ret = btrfs_search_forward(root, &key, path, 0);
4135 if (ret) {
4136 if (ret > 0)
4137 ret = 0;
4138 break;
4141 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4142 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4143 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4144 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4145 goto skip;
4147 eb = path->nodes[0];
4148 slot = path->slots[0];
4149 item_size = btrfs_item_size_nr(eb, slot);
4150 if (item_size < sizeof(root_item))
4151 goto skip;
4153 read_extent_buffer(eb, &root_item,
4154 btrfs_item_ptr_offset(eb, slot),
4155 (int)sizeof(root_item));
4156 if (btrfs_root_refs(&root_item) == 0)
4157 goto skip;
4159 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4160 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4161 if (trans)
4162 goto update_tree;
4164 btrfs_release_path(path);
4166 * 1 - subvol uuid item
4167 * 1 - received_subvol uuid item
4169 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4170 if (IS_ERR(trans)) {
4171 ret = PTR_ERR(trans);
4172 break;
4174 continue;
4175 } else {
4176 goto skip;
4178 update_tree:
4179 btrfs_release_path(path);
4180 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4181 ret = btrfs_uuid_tree_add(trans, fs_info,
4182 root_item.uuid,
4183 BTRFS_UUID_KEY_SUBVOL,
4184 key.objectid);
4185 if (ret < 0) {
4186 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4187 ret);
4188 break;
4192 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4193 ret = btrfs_uuid_tree_add(trans, fs_info,
4194 root_item.received_uuid,
4195 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4196 key.objectid);
4197 if (ret < 0) {
4198 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4199 ret);
4200 break;
4204 skip:
4205 btrfs_release_path(path);
4206 if (trans) {
4207 ret = btrfs_end_transaction(trans);
4208 trans = NULL;
4209 if (ret)
4210 break;
4213 if (key.offset < (u64)-1) {
4214 key.offset++;
4215 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4216 key.offset = 0;
4217 key.type = BTRFS_ROOT_ITEM_KEY;
4218 } else if (key.objectid < (u64)-1) {
4219 key.offset = 0;
4220 key.type = BTRFS_ROOT_ITEM_KEY;
4221 key.objectid++;
4222 } else {
4223 break;
4225 cond_resched();
4228 out:
4229 btrfs_free_path(path);
4230 if (trans && !IS_ERR(trans))
4231 btrfs_end_transaction(trans);
4232 if (ret)
4233 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4234 else
4235 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4236 up(&fs_info->uuid_tree_rescan_sem);
4237 return 0;
4241 * Callback for btrfs_uuid_tree_iterate().
4242 * returns:
4243 * 0 check succeeded, the entry is not outdated.
4244 * < 0 if an error occurred.
4245 * > 0 if the check failed, which means the caller shall remove the entry.
4247 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4248 u8 *uuid, u8 type, u64 subid)
4250 struct btrfs_key key;
4251 int ret = 0;
4252 struct btrfs_root *subvol_root;
4254 if (type != BTRFS_UUID_KEY_SUBVOL &&
4255 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4256 goto out;
4258 key.objectid = subid;
4259 key.type = BTRFS_ROOT_ITEM_KEY;
4260 key.offset = (u64)-1;
4261 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4262 if (IS_ERR(subvol_root)) {
4263 ret = PTR_ERR(subvol_root);
4264 if (ret == -ENOENT)
4265 ret = 1;
4266 goto out;
4269 switch (type) {
4270 case BTRFS_UUID_KEY_SUBVOL:
4271 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4272 ret = 1;
4273 break;
4274 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4275 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4276 BTRFS_UUID_SIZE))
4277 ret = 1;
4278 break;
4281 out:
4282 return ret;
4285 static int btrfs_uuid_rescan_kthread(void *data)
4287 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4288 int ret;
4291 * 1st step is to iterate through the existing UUID tree and
4292 * to delete all entries that contain outdated data.
4293 * 2nd step is to add all missing entries to the UUID tree.
4295 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4296 if (ret < 0) {
4297 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4298 up(&fs_info->uuid_tree_rescan_sem);
4299 return ret;
4301 return btrfs_uuid_scan_kthread(data);
4304 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4306 struct btrfs_trans_handle *trans;
4307 struct btrfs_root *tree_root = fs_info->tree_root;
4308 struct btrfs_root *uuid_root;
4309 struct task_struct *task;
4310 int ret;
4313 * 1 - root node
4314 * 1 - root item
4316 trans = btrfs_start_transaction(tree_root, 2);
4317 if (IS_ERR(trans))
4318 return PTR_ERR(trans);
4320 uuid_root = btrfs_create_tree(trans, fs_info,
4321 BTRFS_UUID_TREE_OBJECTID);
4322 if (IS_ERR(uuid_root)) {
4323 ret = PTR_ERR(uuid_root);
4324 btrfs_abort_transaction(trans, ret);
4325 btrfs_end_transaction(trans);
4326 return ret;
4329 fs_info->uuid_root = uuid_root;
4331 ret = btrfs_commit_transaction(trans);
4332 if (ret)
4333 return ret;
4335 down(&fs_info->uuid_tree_rescan_sem);
4336 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4337 if (IS_ERR(task)) {
4338 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4339 btrfs_warn(fs_info, "failed to start uuid_scan task");
4340 up(&fs_info->uuid_tree_rescan_sem);
4341 return PTR_ERR(task);
4344 return 0;
4347 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4349 struct task_struct *task;
4351 down(&fs_info->uuid_tree_rescan_sem);
4352 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4353 if (IS_ERR(task)) {
4354 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4355 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4356 up(&fs_info->uuid_tree_rescan_sem);
4357 return PTR_ERR(task);
4360 return 0;
4364 * shrinking a device means finding all of the device extents past
4365 * the new size, and then following the back refs to the chunks.
4366 * The chunk relocation code actually frees the device extent
4368 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4370 struct btrfs_fs_info *fs_info = device->fs_info;
4371 struct btrfs_root *root = fs_info->dev_root;
4372 struct btrfs_trans_handle *trans;
4373 struct btrfs_dev_extent *dev_extent = NULL;
4374 struct btrfs_path *path;
4375 u64 length;
4376 u64 chunk_offset;
4377 int ret;
4378 int slot;
4379 int failed = 0;
4380 bool retried = false;
4381 bool checked_pending_chunks = false;
4382 struct extent_buffer *l;
4383 struct btrfs_key key;
4384 struct btrfs_super_block *super_copy = fs_info->super_copy;
4385 u64 old_total = btrfs_super_total_bytes(super_copy);
4386 u64 old_size = btrfs_device_get_total_bytes(device);
4387 u64 diff;
4389 new_size = round_down(new_size, fs_info->sectorsize);
4390 diff = round_down(old_size - new_size, fs_info->sectorsize);
4392 if (device->is_tgtdev_for_dev_replace)
4393 return -EINVAL;
4395 path = btrfs_alloc_path();
4396 if (!path)
4397 return -ENOMEM;
4399 path->reada = READA_FORWARD;
4401 mutex_lock(&fs_info->chunk_mutex);
4403 btrfs_device_set_total_bytes(device, new_size);
4404 if (device->writeable) {
4405 device->fs_devices->total_rw_bytes -= diff;
4406 atomic64_sub(diff, &fs_info->free_chunk_space);
4408 mutex_unlock(&fs_info->chunk_mutex);
4410 again:
4411 key.objectid = device->devid;
4412 key.offset = (u64)-1;
4413 key.type = BTRFS_DEV_EXTENT_KEY;
4415 do {
4416 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4417 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4418 if (ret < 0) {
4419 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4420 goto done;
4423 ret = btrfs_previous_item(root, path, 0, key.type);
4424 if (ret)
4425 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4426 if (ret < 0)
4427 goto done;
4428 if (ret) {
4429 ret = 0;
4430 btrfs_release_path(path);
4431 break;
4434 l = path->nodes[0];
4435 slot = path->slots[0];
4436 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4438 if (key.objectid != device->devid) {
4439 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4440 btrfs_release_path(path);
4441 break;
4444 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4445 length = btrfs_dev_extent_length(l, dev_extent);
4447 if (key.offset + length <= new_size) {
4448 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4449 btrfs_release_path(path);
4450 break;
4453 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4454 btrfs_release_path(path);
4456 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4457 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4458 if (ret && ret != -ENOSPC)
4459 goto done;
4460 if (ret == -ENOSPC)
4461 failed++;
4462 } while (key.offset-- > 0);
4464 if (failed && !retried) {
4465 failed = 0;
4466 retried = true;
4467 goto again;
4468 } else if (failed && retried) {
4469 ret = -ENOSPC;
4470 goto done;
4473 /* Shrinking succeeded, else we would be at "done". */
4474 trans = btrfs_start_transaction(root, 0);
4475 if (IS_ERR(trans)) {
4476 ret = PTR_ERR(trans);
4477 goto done;
4480 mutex_lock(&fs_info->chunk_mutex);
4483 * We checked in the above loop all device extents that were already in
4484 * the device tree. However before we have updated the device's
4485 * total_bytes to the new size, we might have had chunk allocations that
4486 * have not complete yet (new block groups attached to transaction
4487 * handles), and therefore their device extents were not yet in the
4488 * device tree and we missed them in the loop above. So if we have any
4489 * pending chunk using a device extent that overlaps the device range
4490 * that we can not use anymore, commit the current transaction and
4491 * repeat the search on the device tree - this way we guarantee we will
4492 * not have chunks using device extents that end beyond 'new_size'.
4494 if (!checked_pending_chunks) {
4495 u64 start = new_size;
4496 u64 len = old_size - new_size;
4498 if (contains_pending_extent(trans->transaction, device,
4499 &start, len)) {
4500 mutex_unlock(&fs_info->chunk_mutex);
4501 checked_pending_chunks = true;
4502 failed = 0;
4503 retried = false;
4504 ret = btrfs_commit_transaction(trans);
4505 if (ret)
4506 goto done;
4507 goto again;
4511 btrfs_device_set_disk_total_bytes(device, new_size);
4512 if (list_empty(&device->resized_list))
4513 list_add_tail(&device->resized_list,
4514 &fs_info->fs_devices->resized_devices);
4516 WARN_ON(diff > old_total);
4517 btrfs_set_super_total_bytes(super_copy,
4518 round_down(old_total - diff, fs_info->sectorsize));
4519 mutex_unlock(&fs_info->chunk_mutex);
4521 /* Now btrfs_update_device() will change the on-disk size. */
4522 ret = btrfs_update_device(trans, device);
4523 if (ret < 0) {
4524 btrfs_abort_transaction(trans, ret);
4525 btrfs_end_transaction(trans);
4526 } else {
4527 ret = btrfs_commit_transaction(trans);
4529 done:
4530 btrfs_free_path(path);
4531 if (ret) {
4532 mutex_lock(&fs_info->chunk_mutex);
4533 btrfs_device_set_total_bytes(device, old_size);
4534 if (device->writeable)
4535 device->fs_devices->total_rw_bytes += diff;
4536 atomic64_add(diff, &fs_info->free_chunk_space);
4537 mutex_unlock(&fs_info->chunk_mutex);
4539 return ret;
4542 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4543 struct btrfs_key *key,
4544 struct btrfs_chunk *chunk, int item_size)
4546 struct btrfs_super_block *super_copy = fs_info->super_copy;
4547 struct btrfs_disk_key disk_key;
4548 u32 array_size;
4549 u8 *ptr;
4551 mutex_lock(&fs_info->chunk_mutex);
4552 array_size = btrfs_super_sys_array_size(super_copy);
4553 if (array_size + item_size + sizeof(disk_key)
4554 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4555 mutex_unlock(&fs_info->chunk_mutex);
4556 return -EFBIG;
4559 ptr = super_copy->sys_chunk_array + array_size;
4560 btrfs_cpu_key_to_disk(&disk_key, key);
4561 memcpy(ptr, &disk_key, sizeof(disk_key));
4562 ptr += sizeof(disk_key);
4563 memcpy(ptr, chunk, item_size);
4564 item_size += sizeof(disk_key);
4565 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4566 mutex_unlock(&fs_info->chunk_mutex);
4568 return 0;
4572 * sort the devices in descending order by max_avail, total_avail
4574 static int btrfs_cmp_device_info(const void *a, const void *b)
4576 const struct btrfs_device_info *di_a = a;
4577 const struct btrfs_device_info *di_b = b;
4579 if (di_a->max_avail > di_b->max_avail)
4580 return -1;
4581 if (di_a->max_avail < di_b->max_avail)
4582 return 1;
4583 if (di_a->total_avail > di_b->total_avail)
4584 return -1;
4585 if (di_a->total_avail < di_b->total_avail)
4586 return 1;
4587 return 0;
4590 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4592 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4593 return;
4595 btrfs_set_fs_incompat(info, RAID56);
4598 #define BTRFS_MAX_DEVS(r) ((BTRFS_MAX_ITEM_SIZE(r->fs_info) \
4599 - sizeof(struct btrfs_chunk)) \
4600 / sizeof(struct btrfs_stripe) + 1)
4602 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4603 - 2 * sizeof(struct btrfs_disk_key) \
4604 - 2 * sizeof(struct btrfs_chunk)) \
4605 / sizeof(struct btrfs_stripe) + 1)
4607 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4608 u64 start, u64 type)
4610 struct btrfs_fs_info *info = trans->fs_info;
4611 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4612 struct btrfs_device *device;
4613 struct map_lookup *map = NULL;
4614 struct extent_map_tree *em_tree;
4615 struct extent_map *em;
4616 struct btrfs_device_info *devices_info = NULL;
4617 u64 total_avail;
4618 int num_stripes; /* total number of stripes to allocate */
4619 int data_stripes; /* number of stripes that count for
4620 block group size */
4621 int sub_stripes; /* sub_stripes info for map */
4622 int dev_stripes; /* stripes per dev */
4623 int devs_max; /* max devs to use */
4624 int devs_min; /* min devs needed */
4625 int devs_increment; /* ndevs has to be a multiple of this */
4626 int ncopies; /* how many copies to data has */
4627 int ret;
4628 u64 max_stripe_size;
4629 u64 max_chunk_size;
4630 u64 stripe_size;
4631 u64 num_bytes;
4632 int ndevs;
4633 int i;
4634 int j;
4635 int index;
4637 BUG_ON(!alloc_profile_is_valid(type, 0));
4639 if (list_empty(&fs_devices->alloc_list))
4640 return -ENOSPC;
4642 index = __get_raid_index(type);
4644 sub_stripes = btrfs_raid_array[index].sub_stripes;
4645 dev_stripes = btrfs_raid_array[index].dev_stripes;
4646 devs_max = btrfs_raid_array[index].devs_max;
4647 devs_min = btrfs_raid_array[index].devs_min;
4648 devs_increment = btrfs_raid_array[index].devs_increment;
4649 ncopies = btrfs_raid_array[index].ncopies;
4651 if (type & BTRFS_BLOCK_GROUP_DATA) {
4652 max_stripe_size = SZ_1G;
4653 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4654 if (!devs_max)
4655 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4656 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4657 /* for larger filesystems, use larger metadata chunks */
4658 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4659 max_stripe_size = SZ_1G;
4660 else
4661 max_stripe_size = SZ_256M;
4662 max_chunk_size = max_stripe_size;
4663 if (!devs_max)
4664 devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4665 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4666 max_stripe_size = SZ_32M;
4667 max_chunk_size = 2 * max_stripe_size;
4668 if (!devs_max)
4669 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4670 } else {
4671 btrfs_err(info, "invalid chunk type 0x%llx requested",
4672 type);
4673 BUG_ON(1);
4676 /* we don't want a chunk larger than 10% of writeable space */
4677 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4678 max_chunk_size);
4680 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4681 GFP_NOFS);
4682 if (!devices_info)
4683 return -ENOMEM;
4686 * in the first pass through the devices list, we gather information
4687 * about the available holes on each device.
4689 ndevs = 0;
4690 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4691 u64 max_avail;
4692 u64 dev_offset;
4694 if (!device->writeable) {
4695 WARN(1, KERN_ERR
4696 "BTRFS: read-only device in alloc_list\n");
4697 continue;
4700 if (!device->in_fs_metadata ||
4701 device->is_tgtdev_for_dev_replace)
4702 continue;
4704 if (device->total_bytes > device->bytes_used)
4705 total_avail = device->total_bytes - device->bytes_used;
4706 else
4707 total_avail = 0;
4709 /* If there is no space on this device, skip it. */
4710 if (total_avail == 0)
4711 continue;
4713 ret = find_free_dev_extent(trans, device,
4714 max_stripe_size * dev_stripes,
4715 &dev_offset, &max_avail);
4716 if (ret && ret != -ENOSPC)
4717 goto error;
4719 if (ret == 0)
4720 max_avail = max_stripe_size * dev_stripes;
4722 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4723 continue;
4725 if (ndevs == fs_devices->rw_devices) {
4726 WARN(1, "%s: found more than %llu devices\n",
4727 __func__, fs_devices->rw_devices);
4728 break;
4730 devices_info[ndevs].dev_offset = dev_offset;
4731 devices_info[ndevs].max_avail = max_avail;
4732 devices_info[ndevs].total_avail = total_avail;
4733 devices_info[ndevs].dev = device;
4734 ++ndevs;
4738 * now sort the devices by hole size / available space
4740 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4741 btrfs_cmp_device_info, NULL);
4743 /* round down to number of usable stripes */
4744 ndevs = round_down(ndevs, devs_increment);
4746 if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4747 ret = -ENOSPC;
4748 goto error;
4751 ndevs = min(ndevs, devs_max);
4754 * The primary goal is to maximize the number of stripes, so use as
4755 * many devices as possible, even if the stripes are not maximum sized.
4757 * The DUP profile stores more than one stripe per device, the
4758 * max_avail is the total size so we have to adjust.
4760 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4761 num_stripes = ndevs * dev_stripes;
4764 * this will have to be fixed for RAID1 and RAID10 over
4765 * more drives
4767 data_stripes = num_stripes / ncopies;
4769 if (type & BTRFS_BLOCK_GROUP_RAID5)
4770 data_stripes = num_stripes - 1;
4772 if (type & BTRFS_BLOCK_GROUP_RAID6)
4773 data_stripes = num_stripes - 2;
4776 * Use the number of data stripes to figure out how big this chunk
4777 * is really going to be in terms of logical address space,
4778 * and compare that answer with the max chunk size
4780 if (stripe_size * data_stripes > max_chunk_size) {
4781 u64 mask = (1ULL << 24) - 1;
4783 stripe_size = div_u64(max_chunk_size, data_stripes);
4785 /* bump the answer up to a 16MB boundary */
4786 stripe_size = (stripe_size + mask) & ~mask;
4788 /* but don't go higher than the limits we found
4789 * while searching for free extents
4791 if (stripe_size > devices_info[ndevs-1].max_avail)
4792 stripe_size = devices_info[ndevs-1].max_avail;
4795 /* align to BTRFS_STRIPE_LEN */
4796 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4798 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4799 if (!map) {
4800 ret = -ENOMEM;
4801 goto error;
4803 map->num_stripes = num_stripes;
4805 for (i = 0; i < ndevs; ++i) {
4806 for (j = 0; j < dev_stripes; ++j) {
4807 int s = i * dev_stripes + j;
4808 map->stripes[s].dev = devices_info[i].dev;
4809 map->stripes[s].physical = devices_info[i].dev_offset +
4810 j * stripe_size;
4813 map->stripe_len = BTRFS_STRIPE_LEN;
4814 map->io_align = BTRFS_STRIPE_LEN;
4815 map->io_width = BTRFS_STRIPE_LEN;
4816 map->type = type;
4817 map->sub_stripes = sub_stripes;
4819 num_bytes = stripe_size * data_stripes;
4821 trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4823 em = alloc_extent_map();
4824 if (!em) {
4825 kfree(map);
4826 ret = -ENOMEM;
4827 goto error;
4829 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4830 em->map_lookup = map;
4831 em->start = start;
4832 em->len = num_bytes;
4833 em->block_start = 0;
4834 em->block_len = em->len;
4835 em->orig_block_len = stripe_size;
4837 em_tree = &info->mapping_tree.map_tree;
4838 write_lock(&em_tree->lock);
4839 ret = add_extent_mapping(em_tree, em, 0);
4840 if (!ret) {
4841 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4842 refcount_inc(&em->refs);
4844 write_unlock(&em_tree->lock);
4845 if (ret) {
4846 free_extent_map(em);
4847 goto error;
4850 ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4851 if (ret)
4852 goto error_del_extent;
4854 for (i = 0; i < map->num_stripes; i++) {
4855 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4856 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4857 map->stripes[i].dev->has_pending_chunks = true;
4860 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4862 free_extent_map(em);
4863 check_raid56_incompat_flag(info, type);
4865 kfree(devices_info);
4866 return 0;
4868 error_del_extent:
4869 write_lock(&em_tree->lock);
4870 remove_extent_mapping(em_tree, em);
4871 write_unlock(&em_tree->lock);
4873 /* One for our allocation */
4874 free_extent_map(em);
4875 /* One for the tree reference */
4876 free_extent_map(em);
4877 /* One for the pending_chunks list reference */
4878 free_extent_map(em);
4879 error:
4880 kfree(devices_info);
4881 return ret;
4884 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4885 struct btrfs_fs_info *fs_info,
4886 u64 chunk_offset, u64 chunk_size)
4888 struct btrfs_root *extent_root = fs_info->extent_root;
4889 struct btrfs_root *chunk_root = fs_info->chunk_root;
4890 struct btrfs_key key;
4891 struct btrfs_device *device;
4892 struct btrfs_chunk *chunk;
4893 struct btrfs_stripe *stripe;
4894 struct extent_map *em;
4895 struct map_lookup *map;
4896 size_t item_size;
4897 u64 dev_offset;
4898 u64 stripe_size;
4899 int i = 0;
4900 int ret = 0;
4902 em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4903 if (IS_ERR(em))
4904 return PTR_ERR(em);
4906 map = em->map_lookup;
4907 item_size = btrfs_chunk_item_size(map->num_stripes);
4908 stripe_size = em->orig_block_len;
4910 chunk = kzalloc(item_size, GFP_NOFS);
4911 if (!chunk) {
4912 ret = -ENOMEM;
4913 goto out;
4917 * Take the device list mutex to prevent races with the final phase of
4918 * a device replace operation that replaces the device object associated
4919 * with the map's stripes, because the device object's id can change
4920 * at any time during that final phase of the device replace operation
4921 * (dev-replace.c:btrfs_dev_replace_finishing()).
4923 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4924 for (i = 0; i < map->num_stripes; i++) {
4925 device = map->stripes[i].dev;
4926 dev_offset = map->stripes[i].physical;
4928 ret = btrfs_update_device(trans, device);
4929 if (ret)
4930 break;
4931 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4932 dev_offset, stripe_size);
4933 if (ret)
4934 break;
4936 if (ret) {
4937 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4938 goto out;
4941 stripe = &chunk->stripe;
4942 for (i = 0; i < map->num_stripes; i++) {
4943 device = map->stripes[i].dev;
4944 dev_offset = map->stripes[i].physical;
4946 btrfs_set_stack_stripe_devid(stripe, device->devid);
4947 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4948 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4949 stripe++;
4951 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4953 btrfs_set_stack_chunk_length(chunk, chunk_size);
4954 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4955 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4956 btrfs_set_stack_chunk_type(chunk, map->type);
4957 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4958 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4959 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4960 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
4961 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4963 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4964 key.type = BTRFS_CHUNK_ITEM_KEY;
4965 key.offset = chunk_offset;
4967 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4968 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4970 * TODO: Cleanup of inserted chunk root in case of
4971 * failure.
4973 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
4976 out:
4977 kfree(chunk);
4978 free_extent_map(em);
4979 return ret;
4983 * Chunk allocation falls into two parts. The first part does works
4984 * that make the new allocated chunk useable, but not do any operation
4985 * that modifies the chunk tree. The second part does the works that
4986 * require modifying the chunk tree. This division is important for the
4987 * bootstrap process of adding storage to a seed btrfs.
4989 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4990 struct btrfs_fs_info *fs_info, u64 type)
4992 u64 chunk_offset;
4994 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
4995 chunk_offset = find_next_chunk(fs_info);
4996 return __btrfs_alloc_chunk(trans, chunk_offset, type);
4999 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5000 struct btrfs_fs_info *fs_info)
5002 u64 chunk_offset;
5003 u64 sys_chunk_offset;
5004 u64 alloc_profile;
5005 int ret;
5007 chunk_offset = find_next_chunk(fs_info);
5008 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5009 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5010 if (ret)
5011 return ret;
5013 sys_chunk_offset = find_next_chunk(fs_info);
5014 alloc_profile = btrfs_system_alloc_profile(fs_info);
5015 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5016 return ret;
5019 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5021 int max_errors;
5023 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5024 BTRFS_BLOCK_GROUP_RAID10 |
5025 BTRFS_BLOCK_GROUP_RAID5)) {
5026 max_errors = 1;
5027 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5028 max_errors = 2;
5029 } else {
5030 max_errors = 0;
5033 return max_errors;
5036 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5038 struct extent_map *em;
5039 struct map_lookup *map;
5040 int readonly = 0;
5041 int miss_ndevs = 0;
5042 int i;
5044 em = get_chunk_map(fs_info, chunk_offset, 1);
5045 if (IS_ERR(em))
5046 return 1;
5048 map = em->map_lookup;
5049 for (i = 0; i < map->num_stripes; i++) {
5050 if (map->stripes[i].dev->missing) {
5051 miss_ndevs++;
5052 continue;
5055 if (!map->stripes[i].dev->writeable) {
5056 readonly = 1;
5057 goto end;
5062 * If the number of missing devices is larger than max errors,
5063 * we can not write the data into that chunk successfully, so
5064 * set it readonly.
5066 if (miss_ndevs > btrfs_chunk_max_errors(map))
5067 readonly = 1;
5068 end:
5069 free_extent_map(em);
5070 return readonly;
5073 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5075 extent_map_tree_init(&tree->map_tree);
5078 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5080 struct extent_map *em;
5082 while (1) {
5083 write_lock(&tree->map_tree.lock);
5084 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5085 if (em)
5086 remove_extent_mapping(&tree->map_tree, em);
5087 write_unlock(&tree->map_tree.lock);
5088 if (!em)
5089 break;
5090 /* once for us */
5091 free_extent_map(em);
5092 /* once for the tree */
5093 free_extent_map(em);
5097 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5099 struct extent_map *em;
5100 struct map_lookup *map;
5101 int ret;
5103 em = get_chunk_map(fs_info, logical, len);
5104 if (IS_ERR(em))
5106 * We could return errors for these cases, but that could get
5107 * ugly and we'd probably do the same thing which is just not do
5108 * anything else and exit, so return 1 so the callers don't try
5109 * to use other copies.
5111 return 1;
5113 map = em->map_lookup;
5114 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5115 ret = map->num_stripes;
5116 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5117 ret = map->sub_stripes;
5118 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5119 ret = 2;
5120 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5122 * There could be two corrupted data stripes, we need
5123 * to loop retry in order to rebuild the correct data.
5125 * Fail a stripe at a time on every retry except the
5126 * stripe under reconstruction.
5128 ret = map->num_stripes;
5129 else
5130 ret = 1;
5131 free_extent_map(em);
5133 btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
5134 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5135 fs_info->dev_replace.tgtdev)
5136 ret++;
5137 btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
5139 return ret;
5142 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5143 u64 logical)
5145 struct extent_map *em;
5146 struct map_lookup *map;
5147 unsigned long len = fs_info->sectorsize;
5149 em = get_chunk_map(fs_info, logical, len);
5151 if (!WARN_ON(IS_ERR(em))) {
5152 map = em->map_lookup;
5153 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5154 len = map->stripe_len * nr_data_stripes(map);
5155 free_extent_map(em);
5157 return len;
5160 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5162 struct extent_map *em;
5163 struct map_lookup *map;
5164 int ret = 0;
5166 em = get_chunk_map(fs_info, logical, len);
5168 if(!WARN_ON(IS_ERR(em))) {
5169 map = em->map_lookup;
5170 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5171 ret = 1;
5172 free_extent_map(em);
5174 return ret;
5177 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5178 struct map_lookup *map, int first, int num,
5179 int optimal, int dev_replace_is_ongoing)
5181 int i;
5182 int tolerance;
5183 struct btrfs_device *srcdev;
5185 if (dev_replace_is_ongoing &&
5186 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5187 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5188 srcdev = fs_info->dev_replace.srcdev;
5189 else
5190 srcdev = NULL;
5193 * try to avoid the drive that is the source drive for a
5194 * dev-replace procedure, only choose it if no other non-missing
5195 * mirror is available
5197 for (tolerance = 0; tolerance < 2; tolerance++) {
5198 if (map->stripes[optimal].dev->bdev &&
5199 (tolerance || map->stripes[optimal].dev != srcdev))
5200 return optimal;
5201 for (i = first; i < first + num; i++) {
5202 if (map->stripes[i].dev->bdev &&
5203 (tolerance || map->stripes[i].dev != srcdev))
5204 return i;
5208 /* we couldn't find one that doesn't fail. Just return something
5209 * and the io error handling code will clean up eventually
5211 return optimal;
5214 static inline int parity_smaller(u64 a, u64 b)
5216 return a > b;
5219 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5220 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5222 struct btrfs_bio_stripe s;
5223 int i;
5224 u64 l;
5225 int again = 1;
5227 while (again) {
5228 again = 0;
5229 for (i = 0; i < num_stripes - 1; i++) {
5230 if (parity_smaller(bbio->raid_map[i],
5231 bbio->raid_map[i+1])) {
5232 s = bbio->stripes[i];
5233 l = bbio->raid_map[i];
5234 bbio->stripes[i] = bbio->stripes[i+1];
5235 bbio->raid_map[i] = bbio->raid_map[i+1];
5236 bbio->stripes[i+1] = s;
5237 bbio->raid_map[i+1] = l;
5239 again = 1;
5245 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5247 struct btrfs_bio *bbio = kzalloc(
5248 /* the size of the btrfs_bio */
5249 sizeof(struct btrfs_bio) +
5250 /* plus the variable array for the stripes */
5251 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5252 /* plus the variable array for the tgt dev */
5253 sizeof(int) * (real_stripes) +
5255 * plus the raid_map, which includes both the tgt dev
5256 * and the stripes
5258 sizeof(u64) * (total_stripes),
5259 GFP_NOFS|__GFP_NOFAIL);
5261 atomic_set(&bbio->error, 0);
5262 refcount_set(&bbio->refs, 1);
5264 return bbio;
5267 void btrfs_get_bbio(struct btrfs_bio *bbio)
5269 WARN_ON(!refcount_read(&bbio->refs));
5270 refcount_inc(&bbio->refs);
5273 void btrfs_put_bbio(struct btrfs_bio *bbio)
5275 if (!bbio)
5276 return;
5277 if (refcount_dec_and_test(&bbio->refs))
5278 kfree(bbio);
5281 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5283 * Please note that, discard won't be sent to target device of device
5284 * replace.
5286 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5287 u64 logical, u64 length,
5288 struct btrfs_bio **bbio_ret)
5290 struct extent_map *em;
5291 struct map_lookup *map;
5292 struct btrfs_bio *bbio;
5293 u64 offset;
5294 u64 stripe_nr;
5295 u64 stripe_nr_end;
5296 u64 stripe_end_offset;
5297 u64 stripe_cnt;
5298 u64 stripe_len;
5299 u64 stripe_offset;
5300 u64 num_stripes;
5301 u32 stripe_index;
5302 u32 factor = 0;
5303 u32 sub_stripes = 0;
5304 u64 stripes_per_dev = 0;
5305 u32 remaining_stripes = 0;
5306 u32 last_stripe = 0;
5307 int ret = 0;
5308 int i;
5310 /* discard always return a bbio */
5311 ASSERT(bbio_ret);
5313 em = get_chunk_map(fs_info, logical, length);
5314 if (IS_ERR(em))
5315 return PTR_ERR(em);
5317 map = em->map_lookup;
5318 /* we don't discard raid56 yet */
5319 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5320 ret = -EOPNOTSUPP;
5321 goto out;
5324 offset = logical - em->start;
5325 length = min_t(u64, em->len - offset, length);
5327 stripe_len = map->stripe_len;
5329 * stripe_nr counts the total number of stripes we have to stride
5330 * to get to this block
5332 stripe_nr = div64_u64(offset, stripe_len);
5334 /* stripe_offset is the offset of this block in its stripe */
5335 stripe_offset = offset - stripe_nr * stripe_len;
5337 stripe_nr_end = round_up(offset + length, map->stripe_len);
5338 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5339 stripe_cnt = stripe_nr_end - stripe_nr;
5340 stripe_end_offset = stripe_nr_end * map->stripe_len -
5341 (offset + length);
5343 * after this, stripe_nr is the number of stripes on this
5344 * device we have to walk to find the data, and stripe_index is
5345 * the number of our device in the stripe array
5347 num_stripes = 1;
5348 stripe_index = 0;
5349 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5350 BTRFS_BLOCK_GROUP_RAID10)) {
5351 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5352 sub_stripes = 1;
5353 else
5354 sub_stripes = map->sub_stripes;
5356 factor = map->num_stripes / sub_stripes;
5357 num_stripes = min_t(u64, map->num_stripes,
5358 sub_stripes * stripe_cnt);
5359 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5360 stripe_index *= sub_stripes;
5361 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5362 &remaining_stripes);
5363 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5364 last_stripe *= sub_stripes;
5365 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5366 BTRFS_BLOCK_GROUP_DUP)) {
5367 num_stripes = map->num_stripes;
5368 } else {
5369 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5370 &stripe_index);
5373 bbio = alloc_btrfs_bio(num_stripes, 0);
5374 if (!bbio) {
5375 ret = -ENOMEM;
5376 goto out;
5379 for (i = 0; i < num_stripes; i++) {
5380 bbio->stripes[i].physical =
5381 map->stripes[stripe_index].physical +
5382 stripe_offset + stripe_nr * map->stripe_len;
5383 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5385 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5386 BTRFS_BLOCK_GROUP_RAID10)) {
5387 bbio->stripes[i].length = stripes_per_dev *
5388 map->stripe_len;
5390 if (i / sub_stripes < remaining_stripes)
5391 bbio->stripes[i].length +=
5392 map->stripe_len;
5395 * Special for the first stripe and
5396 * the last stripe:
5398 * |-------|...|-------|
5399 * |----------|
5400 * off end_off
5402 if (i < sub_stripes)
5403 bbio->stripes[i].length -=
5404 stripe_offset;
5406 if (stripe_index >= last_stripe &&
5407 stripe_index <= (last_stripe +
5408 sub_stripes - 1))
5409 bbio->stripes[i].length -=
5410 stripe_end_offset;
5412 if (i == sub_stripes - 1)
5413 stripe_offset = 0;
5414 } else {
5415 bbio->stripes[i].length = length;
5418 stripe_index++;
5419 if (stripe_index == map->num_stripes) {
5420 stripe_index = 0;
5421 stripe_nr++;
5425 *bbio_ret = bbio;
5426 bbio->map_type = map->type;
5427 bbio->num_stripes = num_stripes;
5428 out:
5429 free_extent_map(em);
5430 return ret;
5434 * In dev-replace case, for repair case (that's the only case where the mirror
5435 * is selected explicitly when calling btrfs_map_block), blocks left of the
5436 * left cursor can also be read from the target drive.
5438 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5439 * array of stripes.
5440 * For READ, it also needs to be supported using the same mirror number.
5442 * If the requested block is not left of the left cursor, EIO is returned. This
5443 * can happen because btrfs_num_copies() returns one more in the dev-replace
5444 * case.
5446 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5447 u64 logical, u64 length,
5448 u64 srcdev_devid, int *mirror_num,
5449 u64 *physical)
5451 struct btrfs_bio *bbio = NULL;
5452 int num_stripes;
5453 int index_srcdev = 0;
5454 int found = 0;
5455 u64 physical_of_found = 0;
5456 int i;
5457 int ret = 0;
5459 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5460 logical, &length, &bbio, 0, 0);
5461 if (ret) {
5462 ASSERT(bbio == NULL);
5463 return ret;
5466 num_stripes = bbio->num_stripes;
5467 if (*mirror_num > num_stripes) {
5469 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5470 * that means that the requested area is not left of the left
5471 * cursor
5473 btrfs_put_bbio(bbio);
5474 return -EIO;
5478 * process the rest of the function using the mirror_num of the source
5479 * drive. Therefore look it up first. At the end, patch the device
5480 * pointer to the one of the target drive.
5482 for (i = 0; i < num_stripes; i++) {
5483 if (bbio->stripes[i].dev->devid != srcdev_devid)
5484 continue;
5487 * In case of DUP, in order to keep it simple, only add the
5488 * mirror with the lowest physical address
5490 if (found &&
5491 physical_of_found <= bbio->stripes[i].physical)
5492 continue;
5494 index_srcdev = i;
5495 found = 1;
5496 physical_of_found = bbio->stripes[i].physical;
5499 btrfs_put_bbio(bbio);
5501 ASSERT(found);
5502 if (!found)
5503 return -EIO;
5505 *mirror_num = index_srcdev + 1;
5506 *physical = physical_of_found;
5507 return ret;
5510 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5511 struct btrfs_bio **bbio_ret,
5512 struct btrfs_dev_replace *dev_replace,
5513 int *num_stripes_ret, int *max_errors_ret)
5515 struct btrfs_bio *bbio = *bbio_ret;
5516 u64 srcdev_devid = dev_replace->srcdev->devid;
5517 int tgtdev_indexes = 0;
5518 int num_stripes = *num_stripes_ret;
5519 int max_errors = *max_errors_ret;
5520 int i;
5522 if (op == BTRFS_MAP_WRITE) {
5523 int index_where_to_add;
5526 * duplicate the write operations while the dev replace
5527 * procedure is running. Since the copying of the old disk to
5528 * the new disk takes place at run time while the filesystem is
5529 * mounted writable, the regular write operations to the old
5530 * disk have to be duplicated to go to the new disk as well.
5532 * Note that device->missing is handled by the caller, and that
5533 * the write to the old disk is already set up in the stripes
5534 * array.
5536 index_where_to_add = num_stripes;
5537 for (i = 0; i < num_stripes; i++) {
5538 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5539 /* write to new disk, too */
5540 struct btrfs_bio_stripe *new =
5541 bbio->stripes + index_where_to_add;
5542 struct btrfs_bio_stripe *old =
5543 bbio->stripes + i;
5545 new->physical = old->physical;
5546 new->length = old->length;
5547 new->dev = dev_replace->tgtdev;
5548 bbio->tgtdev_map[i] = index_where_to_add;
5549 index_where_to_add++;
5550 max_errors++;
5551 tgtdev_indexes++;
5554 num_stripes = index_where_to_add;
5555 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5556 int index_srcdev = 0;
5557 int found = 0;
5558 u64 physical_of_found = 0;
5561 * During the dev-replace procedure, the target drive can also
5562 * be used to read data in case it is needed to repair a corrupt
5563 * block elsewhere. This is possible if the requested area is
5564 * left of the left cursor. In this area, the target drive is a
5565 * full copy of the source drive.
5567 for (i = 0; i < num_stripes; i++) {
5568 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5570 * In case of DUP, in order to keep it simple,
5571 * only add the mirror with the lowest physical
5572 * address
5574 if (found &&
5575 physical_of_found <=
5576 bbio->stripes[i].physical)
5577 continue;
5578 index_srcdev = i;
5579 found = 1;
5580 physical_of_found = bbio->stripes[i].physical;
5583 if (found) {
5584 struct btrfs_bio_stripe *tgtdev_stripe =
5585 bbio->stripes + num_stripes;
5587 tgtdev_stripe->physical = physical_of_found;
5588 tgtdev_stripe->length =
5589 bbio->stripes[index_srcdev].length;
5590 tgtdev_stripe->dev = dev_replace->tgtdev;
5591 bbio->tgtdev_map[index_srcdev] = num_stripes;
5593 tgtdev_indexes++;
5594 num_stripes++;
5598 *num_stripes_ret = num_stripes;
5599 *max_errors_ret = max_errors;
5600 bbio->num_tgtdevs = tgtdev_indexes;
5601 *bbio_ret = bbio;
5604 static bool need_full_stripe(enum btrfs_map_op op)
5606 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5609 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5610 enum btrfs_map_op op,
5611 u64 logical, u64 *length,
5612 struct btrfs_bio **bbio_ret,
5613 int mirror_num, int need_raid_map)
5615 struct extent_map *em;
5616 struct map_lookup *map;
5617 u64 offset;
5618 u64 stripe_offset;
5619 u64 stripe_nr;
5620 u64 stripe_len;
5621 u32 stripe_index;
5622 int i;
5623 int ret = 0;
5624 int num_stripes;
5625 int max_errors = 0;
5626 int tgtdev_indexes = 0;
5627 struct btrfs_bio *bbio = NULL;
5628 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5629 int dev_replace_is_ongoing = 0;
5630 int num_alloc_stripes;
5631 int patch_the_first_stripe_for_dev_replace = 0;
5632 u64 physical_to_patch_in_first_stripe = 0;
5633 u64 raid56_full_stripe_start = (u64)-1;
5635 if (op == BTRFS_MAP_DISCARD)
5636 return __btrfs_map_block_for_discard(fs_info, logical,
5637 *length, bbio_ret);
5639 em = get_chunk_map(fs_info, logical, *length);
5640 if (IS_ERR(em))
5641 return PTR_ERR(em);
5643 map = em->map_lookup;
5644 offset = logical - em->start;
5646 stripe_len = map->stripe_len;
5647 stripe_nr = offset;
5649 * stripe_nr counts the total number of stripes we have to stride
5650 * to get to this block
5652 stripe_nr = div64_u64(stripe_nr, stripe_len);
5654 stripe_offset = stripe_nr * stripe_len;
5655 if (offset < stripe_offset) {
5656 btrfs_crit(fs_info,
5657 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5658 stripe_offset, offset, em->start, logical,
5659 stripe_len);
5660 free_extent_map(em);
5661 return -EINVAL;
5664 /* stripe_offset is the offset of this block in its stripe*/
5665 stripe_offset = offset - stripe_offset;
5667 /* if we're here for raid56, we need to know the stripe aligned start */
5668 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5669 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5670 raid56_full_stripe_start = offset;
5672 /* allow a write of a full stripe, but make sure we don't
5673 * allow straddling of stripes
5675 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5676 full_stripe_len);
5677 raid56_full_stripe_start *= full_stripe_len;
5680 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5681 u64 max_len;
5682 /* For writes to RAID[56], allow a full stripeset across all disks.
5683 For other RAID types and for RAID[56] reads, just allow a single
5684 stripe (on a single disk). */
5685 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5686 (op == BTRFS_MAP_WRITE)) {
5687 max_len = stripe_len * nr_data_stripes(map) -
5688 (offset - raid56_full_stripe_start);
5689 } else {
5690 /* we limit the length of each bio to what fits in a stripe */
5691 max_len = stripe_len - stripe_offset;
5693 *length = min_t(u64, em->len - offset, max_len);
5694 } else {
5695 *length = em->len - offset;
5698 /* This is for when we're called from btrfs_merge_bio_hook() and all
5699 it cares about is the length */
5700 if (!bbio_ret)
5701 goto out;
5703 btrfs_dev_replace_lock(dev_replace, 0);
5704 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5705 if (!dev_replace_is_ongoing)
5706 btrfs_dev_replace_unlock(dev_replace, 0);
5707 else
5708 btrfs_dev_replace_set_lock_blocking(dev_replace);
5710 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5711 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5712 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5713 dev_replace->srcdev->devid,
5714 &mirror_num,
5715 &physical_to_patch_in_first_stripe);
5716 if (ret)
5717 goto out;
5718 else
5719 patch_the_first_stripe_for_dev_replace = 1;
5720 } else if (mirror_num > map->num_stripes) {
5721 mirror_num = 0;
5724 num_stripes = 1;
5725 stripe_index = 0;
5726 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5727 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5728 &stripe_index);
5729 if (op != BTRFS_MAP_WRITE && op != BTRFS_MAP_GET_READ_MIRRORS)
5730 mirror_num = 1;
5731 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5732 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS)
5733 num_stripes = map->num_stripes;
5734 else if (mirror_num)
5735 stripe_index = mirror_num - 1;
5736 else {
5737 stripe_index = find_live_mirror(fs_info, map, 0,
5738 map->num_stripes,
5739 current->pid % map->num_stripes,
5740 dev_replace_is_ongoing);
5741 mirror_num = stripe_index + 1;
5744 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5745 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS) {
5746 num_stripes = map->num_stripes;
5747 } else if (mirror_num) {
5748 stripe_index = mirror_num - 1;
5749 } else {
5750 mirror_num = 1;
5753 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5754 u32 factor = map->num_stripes / map->sub_stripes;
5756 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5757 stripe_index *= map->sub_stripes;
5759 if (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS)
5760 num_stripes = map->sub_stripes;
5761 else if (mirror_num)
5762 stripe_index += mirror_num - 1;
5763 else {
5764 int old_stripe_index = stripe_index;
5765 stripe_index = find_live_mirror(fs_info, map,
5766 stripe_index,
5767 map->sub_stripes, stripe_index +
5768 current->pid % map->sub_stripes,
5769 dev_replace_is_ongoing);
5770 mirror_num = stripe_index - old_stripe_index + 1;
5773 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5774 if (need_raid_map &&
5775 (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS ||
5776 mirror_num > 1)) {
5777 /* push stripe_nr back to the start of the full stripe */
5778 stripe_nr = div64_u64(raid56_full_stripe_start,
5779 stripe_len * nr_data_stripes(map));
5781 /* RAID[56] write or recovery. Return all stripes */
5782 num_stripes = map->num_stripes;
5783 max_errors = nr_parity_stripes(map);
5785 *length = map->stripe_len;
5786 stripe_index = 0;
5787 stripe_offset = 0;
5788 } else {
5790 * Mirror #0 or #1 means the original data block.
5791 * Mirror #2 is RAID5 parity block.
5792 * Mirror #3 is RAID6 Q block.
5794 stripe_nr = div_u64_rem(stripe_nr,
5795 nr_data_stripes(map), &stripe_index);
5796 if (mirror_num > 1)
5797 stripe_index = nr_data_stripes(map) +
5798 mirror_num - 2;
5800 /* We distribute the parity blocks across stripes */
5801 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5802 &stripe_index);
5803 if ((op != BTRFS_MAP_WRITE &&
5804 op != BTRFS_MAP_GET_READ_MIRRORS) &&
5805 mirror_num <= 1)
5806 mirror_num = 1;
5808 } else {
5810 * after this, stripe_nr is the number of stripes on this
5811 * device we have to walk to find the data, and stripe_index is
5812 * the number of our device in the stripe array
5814 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5815 &stripe_index);
5816 mirror_num = stripe_index + 1;
5818 if (stripe_index >= map->num_stripes) {
5819 btrfs_crit(fs_info,
5820 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5821 stripe_index, map->num_stripes);
5822 ret = -EINVAL;
5823 goto out;
5826 num_alloc_stripes = num_stripes;
5827 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5828 if (op == BTRFS_MAP_WRITE)
5829 num_alloc_stripes <<= 1;
5830 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5831 num_alloc_stripes++;
5832 tgtdev_indexes = num_stripes;
5835 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5836 if (!bbio) {
5837 ret = -ENOMEM;
5838 goto out;
5840 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5841 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5843 /* build raid_map */
5844 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5845 (need_full_stripe(op) || mirror_num > 1)) {
5846 u64 tmp;
5847 unsigned rot;
5849 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5850 sizeof(struct btrfs_bio_stripe) *
5851 num_alloc_stripes +
5852 sizeof(int) * tgtdev_indexes);
5854 /* Work out the disk rotation on this stripe-set */
5855 div_u64_rem(stripe_nr, num_stripes, &rot);
5857 /* Fill in the logical address of each stripe */
5858 tmp = stripe_nr * nr_data_stripes(map);
5859 for (i = 0; i < nr_data_stripes(map); i++)
5860 bbio->raid_map[(i+rot) % num_stripes] =
5861 em->start + (tmp + i) * map->stripe_len;
5863 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5864 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5865 bbio->raid_map[(i+rot+1) % num_stripes] =
5866 RAID6_Q_STRIPE;
5870 for (i = 0; i < num_stripes; i++) {
5871 bbio->stripes[i].physical =
5872 map->stripes[stripe_index].physical +
5873 stripe_offset +
5874 stripe_nr * map->stripe_len;
5875 bbio->stripes[i].dev =
5876 map->stripes[stripe_index].dev;
5877 stripe_index++;
5880 if (need_full_stripe(op))
5881 max_errors = btrfs_chunk_max_errors(map);
5883 if (bbio->raid_map)
5884 sort_parity_stripes(bbio, num_stripes);
5886 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5887 need_full_stripe(op)) {
5888 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5889 &max_errors);
5892 *bbio_ret = bbio;
5893 bbio->map_type = map->type;
5894 bbio->num_stripes = num_stripes;
5895 bbio->max_errors = max_errors;
5896 bbio->mirror_num = mirror_num;
5899 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5900 * mirror_num == num_stripes + 1 && dev_replace target drive is
5901 * available as a mirror
5903 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5904 WARN_ON(num_stripes > 1);
5905 bbio->stripes[0].dev = dev_replace->tgtdev;
5906 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5907 bbio->mirror_num = map->num_stripes + 1;
5909 out:
5910 if (dev_replace_is_ongoing) {
5911 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5912 btrfs_dev_replace_unlock(dev_replace, 0);
5914 free_extent_map(em);
5915 return ret;
5918 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5919 u64 logical, u64 *length,
5920 struct btrfs_bio **bbio_ret, int mirror_num)
5922 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5923 mirror_num, 0);
5926 /* For Scrub/replace */
5927 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5928 u64 logical, u64 *length,
5929 struct btrfs_bio **bbio_ret)
5931 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5934 int btrfs_rmap_block(struct btrfs_fs_info *fs_info,
5935 u64 chunk_start, u64 physical, u64 devid,
5936 u64 **logical, int *naddrs, int *stripe_len)
5938 struct extent_map *em;
5939 struct map_lookup *map;
5940 u64 *buf;
5941 u64 bytenr;
5942 u64 length;
5943 u64 stripe_nr;
5944 u64 rmap_len;
5945 int i, j, nr = 0;
5947 em = get_chunk_map(fs_info, chunk_start, 1);
5948 if (IS_ERR(em))
5949 return -EIO;
5951 map = em->map_lookup;
5952 length = em->len;
5953 rmap_len = map->stripe_len;
5955 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5956 length = div_u64(length, map->num_stripes / map->sub_stripes);
5957 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5958 length = div_u64(length, map->num_stripes);
5959 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5960 length = div_u64(length, nr_data_stripes(map));
5961 rmap_len = map->stripe_len * nr_data_stripes(map);
5964 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5965 BUG_ON(!buf); /* -ENOMEM */
5967 for (i = 0; i < map->num_stripes; i++) {
5968 if (devid && map->stripes[i].dev->devid != devid)
5969 continue;
5970 if (map->stripes[i].physical > physical ||
5971 map->stripes[i].physical + length <= physical)
5972 continue;
5974 stripe_nr = physical - map->stripes[i].physical;
5975 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
5977 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5978 stripe_nr = stripe_nr * map->num_stripes + i;
5979 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5980 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5981 stripe_nr = stripe_nr * map->num_stripes + i;
5982 } /* else if RAID[56], multiply by nr_data_stripes().
5983 * Alternatively, just use rmap_len below instead of
5984 * map->stripe_len */
5986 bytenr = chunk_start + stripe_nr * rmap_len;
5987 WARN_ON(nr >= map->num_stripes);
5988 for (j = 0; j < nr; j++) {
5989 if (buf[j] == bytenr)
5990 break;
5992 if (j == nr) {
5993 WARN_ON(nr >= map->num_stripes);
5994 buf[nr++] = bytenr;
5998 *logical = buf;
5999 *naddrs = nr;
6000 *stripe_len = rmap_len;
6002 free_extent_map(em);
6003 return 0;
6006 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6008 bio->bi_private = bbio->private;
6009 bio->bi_end_io = bbio->end_io;
6010 bio_endio(bio);
6012 btrfs_put_bbio(bbio);
6015 static void btrfs_end_bio(struct bio *bio)
6017 struct btrfs_bio *bbio = bio->bi_private;
6018 int is_orig_bio = 0;
6020 if (bio->bi_status) {
6021 atomic_inc(&bbio->error);
6022 if (bio->bi_status == BLK_STS_IOERR ||
6023 bio->bi_status == BLK_STS_TARGET) {
6024 unsigned int stripe_index =
6025 btrfs_io_bio(bio)->stripe_index;
6026 struct btrfs_device *dev;
6028 BUG_ON(stripe_index >= bbio->num_stripes);
6029 dev = bbio->stripes[stripe_index].dev;
6030 if (dev->bdev) {
6031 if (bio_op(bio) == REQ_OP_WRITE)
6032 btrfs_dev_stat_inc(dev,
6033 BTRFS_DEV_STAT_WRITE_ERRS);
6034 else
6035 btrfs_dev_stat_inc(dev,
6036 BTRFS_DEV_STAT_READ_ERRS);
6037 if (bio->bi_opf & REQ_PREFLUSH)
6038 btrfs_dev_stat_inc(dev,
6039 BTRFS_DEV_STAT_FLUSH_ERRS);
6040 btrfs_dev_stat_print_on_error(dev);
6045 if (bio == bbio->orig_bio)
6046 is_orig_bio = 1;
6048 btrfs_bio_counter_dec(bbio->fs_info);
6050 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6051 if (!is_orig_bio) {
6052 bio_put(bio);
6053 bio = bbio->orig_bio;
6056 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6057 /* only send an error to the higher layers if it is
6058 * beyond the tolerance of the btrfs bio
6060 if (atomic_read(&bbio->error) > bbio->max_errors) {
6061 bio->bi_status = BLK_STS_IOERR;
6062 } else {
6064 * this bio is actually up to date, we didn't
6065 * go over the max number of errors
6067 bio->bi_status = 0;
6070 btrfs_end_bbio(bbio, bio);
6071 } else if (!is_orig_bio) {
6072 bio_put(bio);
6077 * see run_scheduled_bios for a description of why bios are collected for
6078 * async submit.
6080 * This will add one bio to the pending list for a device and make sure
6081 * the work struct is scheduled.
6083 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6084 struct bio *bio)
6086 struct btrfs_fs_info *fs_info = device->fs_info;
6087 int should_queue = 1;
6088 struct btrfs_pending_bios *pending_bios;
6090 if (device->missing || !device->bdev) {
6091 bio_io_error(bio);
6092 return;
6095 /* don't bother with additional async steps for reads, right now */
6096 if (bio_op(bio) == REQ_OP_READ) {
6097 bio_get(bio);
6098 btrfsic_submit_bio(bio);
6099 bio_put(bio);
6100 return;
6104 * nr_async_bios allows us to reliably return congestion to the
6105 * higher layers. Otherwise, the async bio makes it appear we have
6106 * made progress against dirty pages when we've really just put it
6107 * on a queue for later
6109 atomic_inc(&fs_info->nr_async_bios);
6110 WARN_ON(bio->bi_next);
6111 bio->bi_next = NULL;
6113 spin_lock(&device->io_lock);
6114 if (op_is_sync(bio->bi_opf))
6115 pending_bios = &device->pending_sync_bios;
6116 else
6117 pending_bios = &device->pending_bios;
6119 if (pending_bios->tail)
6120 pending_bios->tail->bi_next = bio;
6122 pending_bios->tail = bio;
6123 if (!pending_bios->head)
6124 pending_bios->head = bio;
6125 if (device->running_pending)
6126 should_queue = 0;
6128 spin_unlock(&device->io_lock);
6130 if (should_queue)
6131 btrfs_queue_work(fs_info->submit_workers, &device->work);
6134 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6135 u64 physical, int dev_nr, int async)
6137 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6138 struct btrfs_fs_info *fs_info = bbio->fs_info;
6140 bio->bi_private = bbio;
6141 btrfs_io_bio(bio)->stripe_index = dev_nr;
6142 bio->bi_end_io = btrfs_end_bio;
6143 bio->bi_iter.bi_sector = physical >> 9;
6144 #ifdef DEBUG
6146 struct rcu_string *name;
6148 rcu_read_lock();
6149 name = rcu_dereference(dev->name);
6150 btrfs_debug(fs_info,
6151 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6152 bio_op(bio), bio->bi_opf,
6153 (u64)bio->bi_iter.bi_sector,
6154 (u_long)dev->bdev->bd_dev, name->str, dev->devid,
6155 bio->bi_iter.bi_size);
6156 rcu_read_unlock();
6158 #endif
6159 bio_set_dev(bio, dev->bdev);
6161 btrfs_bio_counter_inc_noblocked(fs_info);
6163 if (async)
6164 btrfs_schedule_bio(dev, bio);
6165 else
6166 btrfsic_submit_bio(bio);
6169 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6171 atomic_inc(&bbio->error);
6172 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6173 /* Should be the original bio. */
6174 WARN_ON(bio != bbio->orig_bio);
6176 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6177 bio->bi_iter.bi_sector = logical >> 9;
6178 if (atomic_read(&bbio->error) > bbio->max_errors)
6179 bio->bi_status = BLK_STS_IOERR;
6180 else
6181 bio->bi_status = BLK_STS_OK;
6182 btrfs_end_bbio(bbio, bio);
6186 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6187 int mirror_num, int async_submit)
6189 struct btrfs_device *dev;
6190 struct bio *first_bio = bio;
6191 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6192 u64 length = 0;
6193 u64 map_length;
6194 int ret;
6195 int dev_nr;
6196 int total_devs;
6197 struct btrfs_bio *bbio = NULL;
6199 length = bio->bi_iter.bi_size;
6200 map_length = length;
6202 btrfs_bio_counter_inc_blocked(fs_info);
6203 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6204 &map_length, &bbio, mirror_num, 1);
6205 if (ret) {
6206 btrfs_bio_counter_dec(fs_info);
6207 return errno_to_blk_status(ret);
6210 total_devs = bbio->num_stripes;
6211 bbio->orig_bio = first_bio;
6212 bbio->private = first_bio->bi_private;
6213 bbio->end_io = first_bio->bi_end_io;
6214 bbio->fs_info = fs_info;
6215 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6217 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6218 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6219 /* In this case, map_length has been set to the length of
6220 a single stripe; not the whole write */
6221 if (bio_op(bio) == REQ_OP_WRITE) {
6222 ret = raid56_parity_write(fs_info, bio, bbio,
6223 map_length);
6224 } else {
6225 ret = raid56_parity_recover(fs_info, bio, bbio,
6226 map_length, mirror_num, 1);
6229 btrfs_bio_counter_dec(fs_info);
6230 return errno_to_blk_status(ret);
6233 if (map_length < length) {
6234 btrfs_crit(fs_info,
6235 "mapping failed logical %llu bio len %llu len %llu",
6236 logical, length, map_length);
6237 BUG();
6240 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6241 dev = bbio->stripes[dev_nr].dev;
6242 if (!dev || !dev->bdev ||
6243 (bio_op(first_bio) == REQ_OP_WRITE && !dev->writeable)) {
6244 bbio_error(bbio, first_bio, logical);
6245 continue;
6248 if (dev_nr < total_devs - 1)
6249 bio = btrfs_bio_clone(first_bio);
6250 else
6251 bio = first_bio;
6253 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6254 dev_nr, async_submit);
6256 btrfs_bio_counter_dec(fs_info);
6257 return BLK_STS_OK;
6260 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6261 u8 *uuid, u8 *fsid)
6263 struct btrfs_device *device;
6264 struct btrfs_fs_devices *cur_devices;
6266 cur_devices = fs_info->fs_devices;
6267 while (cur_devices) {
6268 if (!fsid ||
6269 !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6270 device = find_device(cur_devices, devid, uuid);
6271 if (device)
6272 return device;
6274 cur_devices = cur_devices->seed;
6276 return NULL;
6279 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6280 u64 devid, u8 *dev_uuid)
6282 struct btrfs_device *device;
6283 unsigned int nofs_flag;
6286 * We call this under the chunk_mutex, so we want to use NOFS for this
6287 * allocation, however we don't want to change btrfs_alloc_device() to
6288 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6289 * places.
6291 nofs_flag = memalloc_nofs_save();
6292 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6293 memalloc_nofs_restore(nofs_flag);
6294 if (IS_ERR(device))
6295 return NULL;
6297 list_add(&device->dev_list, &fs_devices->devices);
6298 device->fs_devices = fs_devices;
6299 fs_devices->num_devices++;
6301 device->missing = 1;
6302 fs_devices->missing_devices++;
6304 return device;
6308 * btrfs_alloc_device - allocate struct btrfs_device
6309 * @fs_info: used only for generating a new devid, can be NULL if
6310 * devid is provided (i.e. @devid != NULL).
6311 * @devid: a pointer to devid for this device. If NULL a new devid
6312 * is generated.
6313 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6314 * is generated.
6316 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6317 * on error. Returned struct is not linked onto any lists and can be
6318 * destroyed with kfree() right away.
6320 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6321 const u64 *devid,
6322 const u8 *uuid)
6324 struct btrfs_device *dev;
6325 u64 tmp;
6327 if (WARN_ON(!devid && !fs_info))
6328 return ERR_PTR(-EINVAL);
6330 dev = __alloc_device();
6331 if (IS_ERR(dev))
6332 return dev;
6334 if (devid)
6335 tmp = *devid;
6336 else {
6337 int ret;
6339 ret = find_next_devid(fs_info, &tmp);
6340 if (ret) {
6341 kfree(dev);
6342 return ERR_PTR(ret);
6345 dev->devid = tmp;
6347 if (uuid)
6348 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6349 else
6350 generate_random_uuid(dev->uuid);
6352 btrfs_init_work(&dev->work, btrfs_submit_helper,
6353 pending_bios_fn, NULL, NULL);
6355 return dev;
6358 /* Return -EIO if any error, otherwise return 0. */
6359 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6360 struct extent_buffer *leaf,
6361 struct btrfs_chunk *chunk, u64 logical)
6363 u64 length;
6364 u64 stripe_len;
6365 u16 num_stripes;
6366 u16 sub_stripes;
6367 u64 type;
6368 u64 features;
6369 bool mixed = false;
6371 length = btrfs_chunk_length(leaf, chunk);
6372 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6373 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6374 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6375 type = btrfs_chunk_type(leaf, chunk);
6377 if (!num_stripes) {
6378 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6379 num_stripes);
6380 return -EIO;
6382 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6383 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6384 return -EIO;
6386 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6387 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6388 btrfs_chunk_sector_size(leaf, chunk));
6389 return -EIO;
6391 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6392 btrfs_err(fs_info, "invalid chunk length %llu", length);
6393 return -EIO;
6395 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6396 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6397 stripe_len);
6398 return -EIO;
6400 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6401 type) {
6402 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6403 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6404 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6405 btrfs_chunk_type(leaf, chunk));
6406 return -EIO;
6409 if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0) {
6410 btrfs_err(fs_info, "missing chunk type flag: 0x%llx", type);
6411 return -EIO;
6414 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
6415 (type & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA))) {
6416 btrfs_err(fs_info,
6417 "system chunk with data or metadata type: 0x%llx", type);
6418 return -EIO;
6421 features = btrfs_super_incompat_flags(fs_info->super_copy);
6422 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
6423 mixed = true;
6425 if (!mixed) {
6426 if ((type & BTRFS_BLOCK_GROUP_METADATA) &&
6427 (type & BTRFS_BLOCK_GROUP_DATA)) {
6428 btrfs_err(fs_info,
6429 "mixed chunk type in non-mixed mode: 0x%llx", type);
6430 return -EIO;
6434 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6435 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes != 2) ||
6436 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6437 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6438 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes != 2) ||
6439 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6440 num_stripes != 1)) {
6441 btrfs_err(fs_info,
6442 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6443 num_stripes, sub_stripes,
6444 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6445 return -EIO;
6448 return 0;
6451 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6452 struct extent_buffer *leaf,
6453 struct btrfs_chunk *chunk)
6455 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6456 struct map_lookup *map;
6457 struct extent_map *em;
6458 u64 logical;
6459 u64 length;
6460 u64 devid;
6461 u8 uuid[BTRFS_UUID_SIZE];
6462 int num_stripes;
6463 int ret;
6464 int i;
6466 logical = key->offset;
6467 length = btrfs_chunk_length(leaf, chunk);
6468 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6470 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6471 if (ret)
6472 return ret;
6474 read_lock(&map_tree->map_tree.lock);
6475 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6476 read_unlock(&map_tree->map_tree.lock);
6478 /* already mapped? */
6479 if (em && em->start <= logical && em->start + em->len > logical) {
6480 free_extent_map(em);
6481 return 0;
6482 } else if (em) {
6483 free_extent_map(em);
6486 em = alloc_extent_map();
6487 if (!em)
6488 return -ENOMEM;
6489 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6490 if (!map) {
6491 free_extent_map(em);
6492 return -ENOMEM;
6495 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6496 em->map_lookup = map;
6497 em->start = logical;
6498 em->len = length;
6499 em->orig_start = 0;
6500 em->block_start = 0;
6501 em->block_len = em->len;
6503 map->num_stripes = num_stripes;
6504 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6505 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6506 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6507 map->type = btrfs_chunk_type(leaf, chunk);
6508 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6509 for (i = 0; i < num_stripes; i++) {
6510 map->stripes[i].physical =
6511 btrfs_stripe_offset_nr(leaf, chunk, i);
6512 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6513 read_extent_buffer(leaf, uuid, (unsigned long)
6514 btrfs_stripe_dev_uuid_nr(chunk, i),
6515 BTRFS_UUID_SIZE);
6516 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6517 uuid, NULL);
6518 if (!map->stripes[i].dev &&
6519 !btrfs_test_opt(fs_info, DEGRADED)) {
6520 free_extent_map(em);
6521 btrfs_report_missing_device(fs_info, devid, uuid);
6522 return -EIO;
6524 if (!map->stripes[i].dev) {
6525 map->stripes[i].dev =
6526 add_missing_dev(fs_info->fs_devices, devid,
6527 uuid);
6528 if (!map->stripes[i].dev) {
6529 free_extent_map(em);
6530 return -EIO;
6532 btrfs_report_missing_device(fs_info, devid, uuid);
6534 map->stripes[i].dev->in_fs_metadata = 1;
6537 write_lock(&map_tree->map_tree.lock);
6538 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6539 write_unlock(&map_tree->map_tree.lock);
6540 if (ret < 0) {
6541 btrfs_err(fs_info,
6542 "failed to add chunk map, start=%llu len=%llu: %d",
6543 em->start, em->len, ret);
6545 free_extent_map(em);
6547 return ret;
6550 static void fill_device_from_item(struct extent_buffer *leaf,
6551 struct btrfs_dev_item *dev_item,
6552 struct btrfs_device *device)
6554 unsigned long ptr;
6556 device->devid = btrfs_device_id(leaf, dev_item);
6557 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6558 device->total_bytes = device->disk_total_bytes;
6559 device->commit_total_bytes = device->disk_total_bytes;
6560 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6561 device->commit_bytes_used = device->bytes_used;
6562 device->type = btrfs_device_type(leaf, dev_item);
6563 device->io_align = btrfs_device_io_align(leaf, dev_item);
6564 device->io_width = btrfs_device_io_width(leaf, dev_item);
6565 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6566 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6567 device->is_tgtdev_for_dev_replace = 0;
6569 ptr = btrfs_device_uuid(dev_item);
6570 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6573 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6574 u8 *fsid)
6576 struct btrfs_fs_devices *fs_devices;
6577 int ret;
6579 BUG_ON(!mutex_is_locked(&uuid_mutex));
6580 ASSERT(fsid);
6582 fs_devices = fs_info->fs_devices->seed;
6583 while (fs_devices) {
6584 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6585 return fs_devices;
6587 fs_devices = fs_devices->seed;
6590 fs_devices = find_fsid(fsid);
6591 if (!fs_devices) {
6592 if (!btrfs_test_opt(fs_info, DEGRADED))
6593 return ERR_PTR(-ENOENT);
6595 fs_devices = alloc_fs_devices(fsid);
6596 if (IS_ERR(fs_devices))
6597 return fs_devices;
6599 fs_devices->seeding = 1;
6600 fs_devices->opened = 1;
6601 return fs_devices;
6604 fs_devices = clone_fs_devices(fs_devices);
6605 if (IS_ERR(fs_devices))
6606 return fs_devices;
6608 ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6609 fs_info->bdev_holder);
6610 if (ret) {
6611 free_fs_devices(fs_devices);
6612 fs_devices = ERR_PTR(ret);
6613 goto out;
6616 if (!fs_devices->seeding) {
6617 __btrfs_close_devices(fs_devices);
6618 free_fs_devices(fs_devices);
6619 fs_devices = ERR_PTR(-EINVAL);
6620 goto out;
6623 fs_devices->seed = fs_info->fs_devices->seed;
6624 fs_info->fs_devices->seed = fs_devices;
6625 out:
6626 return fs_devices;
6629 static int read_one_dev(struct btrfs_fs_info *fs_info,
6630 struct extent_buffer *leaf,
6631 struct btrfs_dev_item *dev_item)
6633 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6634 struct btrfs_device *device;
6635 u64 devid;
6636 int ret;
6637 u8 fs_uuid[BTRFS_FSID_SIZE];
6638 u8 dev_uuid[BTRFS_UUID_SIZE];
6640 devid = btrfs_device_id(leaf, dev_item);
6641 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6642 BTRFS_UUID_SIZE);
6643 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6644 BTRFS_FSID_SIZE);
6646 if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6647 fs_devices = open_seed_devices(fs_info, fs_uuid);
6648 if (IS_ERR(fs_devices))
6649 return PTR_ERR(fs_devices);
6652 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6653 if (!device) {
6654 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6655 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6656 return -EIO;
6659 device = add_missing_dev(fs_devices, devid, dev_uuid);
6660 if (!device)
6661 return -ENOMEM;
6662 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6663 } else {
6664 if (!device->bdev) {
6665 btrfs_report_missing_device(fs_info, devid, dev_uuid);
6666 if (!btrfs_test_opt(fs_info, DEGRADED))
6667 return -EIO;
6670 if(!device->bdev && !device->missing) {
6672 * this happens when a device that was properly setup
6673 * in the device info lists suddenly goes bad.
6674 * device->bdev is NULL, and so we have to set
6675 * device->missing to one here
6677 device->fs_devices->missing_devices++;
6678 device->missing = 1;
6681 /* Move the device to its own fs_devices */
6682 if (device->fs_devices != fs_devices) {
6683 ASSERT(device->missing);
6685 list_move(&device->dev_list, &fs_devices->devices);
6686 device->fs_devices->num_devices--;
6687 fs_devices->num_devices++;
6689 device->fs_devices->missing_devices--;
6690 fs_devices->missing_devices++;
6692 device->fs_devices = fs_devices;
6696 if (device->fs_devices != fs_info->fs_devices) {
6697 BUG_ON(device->writeable);
6698 if (device->generation !=
6699 btrfs_device_generation(leaf, dev_item))
6700 return -EINVAL;
6703 fill_device_from_item(leaf, dev_item, device);
6704 device->in_fs_metadata = 1;
6705 if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6706 device->fs_devices->total_rw_bytes += device->total_bytes;
6707 atomic64_add(device->total_bytes - device->bytes_used,
6708 &fs_info->free_chunk_space);
6710 ret = 0;
6711 return ret;
6714 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6716 struct btrfs_root *root = fs_info->tree_root;
6717 struct btrfs_super_block *super_copy = fs_info->super_copy;
6718 struct extent_buffer *sb;
6719 struct btrfs_disk_key *disk_key;
6720 struct btrfs_chunk *chunk;
6721 u8 *array_ptr;
6722 unsigned long sb_array_offset;
6723 int ret = 0;
6724 u32 num_stripes;
6725 u32 array_size;
6726 u32 len = 0;
6727 u32 cur_offset;
6728 u64 type;
6729 struct btrfs_key key;
6731 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6733 * This will create extent buffer of nodesize, superblock size is
6734 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6735 * overallocate but we can keep it as-is, only the first page is used.
6737 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6738 if (IS_ERR(sb))
6739 return PTR_ERR(sb);
6740 set_extent_buffer_uptodate(sb);
6741 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6743 * The sb extent buffer is artificial and just used to read the system array.
6744 * set_extent_buffer_uptodate() call does not properly mark all it's
6745 * pages up-to-date when the page is larger: extent does not cover the
6746 * whole page and consequently check_page_uptodate does not find all
6747 * the page's extents up-to-date (the hole beyond sb),
6748 * write_extent_buffer then triggers a WARN_ON.
6750 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6751 * but sb spans only this function. Add an explicit SetPageUptodate call
6752 * to silence the warning eg. on PowerPC 64.
6754 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6755 SetPageUptodate(sb->pages[0]);
6757 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6758 array_size = btrfs_super_sys_array_size(super_copy);
6760 array_ptr = super_copy->sys_chunk_array;
6761 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6762 cur_offset = 0;
6764 while (cur_offset < array_size) {
6765 disk_key = (struct btrfs_disk_key *)array_ptr;
6766 len = sizeof(*disk_key);
6767 if (cur_offset + len > array_size)
6768 goto out_short_read;
6770 btrfs_disk_key_to_cpu(&key, disk_key);
6772 array_ptr += len;
6773 sb_array_offset += len;
6774 cur_offset += len;
6776 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6777 chunk = (struct btrfs_chunk *)sb_array_offset;
6779 * At least one btrfs_chunk with one stripe must be
6780 * present, exact stripe count check comes afterwards
6782 len = btrfs_chunk_item_size(1);
6783 if (cur_offset + len > array_size)
6784 goto out_short_read;
6786 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6787 if (!num_stripes) {
6788 btrfs_err(fs_info,
6789 "invalid number of stripes %u in sys_array at offset %u",
6790 num_stripes, cur_offset);
6791 ret = -EIO;
6792 break;
6795 type = btrfs_chunk_type(sb, chunk);
6796 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6797 btrfs_err(fs_info,
6798 "invalid chunk type %llu in sys_array at offset %u",
6799 type, cur_offset);
6800 ret = -EIO;
6801 break;
6804 len = btrfs_chunk_item_size(num_stripes);
6805 if (cur_offset + len > array_size)
6806 goto out_short_read;
6808 ret = read_one_chunk(fs_info, &key, sb, chunk);
6809 if (ret)
6810 break;
6811 } else {
6812 btrfs_err(fs_info,
6813 "unexpected item type %u in sys_array at offset %u",
6814 (u32)key.type, cur_offset);
6815 ret = -EIO;
6816 break;
6818 array_ptr += len;
6819 sb_array_offset += len;
6820 cur_offset += len;
6822 clear_extent_buffer_uptodate(sb);
6823 free_extent_buffer_stale(sb);
6824 return ret;
6826 out_short_read:
6827 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6828 len, cur_offset);
6829 clear_extent_buffer_uptodate(sb);
6830 free_extent_buffer_stale(sb);
6831 return -EIO;
6834 void btrfs_report_missing_device(struct btrfs_fs_info *fs_info, u64 devid,
6835 u8 *uuid)
6837 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing", devid, uuid);
6841 * Check if all chunks in the fs are OK for read-write degraded mount
6843 * Return true if all chunks meet the minimal RW mount requirements.
6844 * Return false if any chunk doesn't meet the minimal RW mount requirements.
6846 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info)
6848 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6849 struct extent_map *em;
6850 u64 next_start = 0;
6851 bool ret = true;
6853 read_lock(&map_tree->map_tree.lock);
6854 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6855 read_unlock(&map_tree->map_tree.lock);
6856 /* No chunk at all? Return false anyway */
6857 if (!em) {
6858 ret = false;
6859 goto out;
6861 while (em) {
6862 struct map_lookup *map;
6863 int missing = 0;
6864 int max_tolerated;
6865 int i;
6867 map = em->map_lookup;
6868 max_tolerated =
6869 btrfs_get_num_tolerated_disk_barrier_failures(
6870 map->type);
6871 for (i = 0; i < map->num_stripes; i++) {
6872 struct btrfs_device *dev = map->stripes[i].dev;
6874 if (!dev || !dev->bdev || dev->missing ||
6875 dev->last_flush_error)
6876 missing++;
6878 if (missing > max_tolerated) {
6879 btrfs_warn(fs_info,
6880 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6881 em->start, missing, max_tolerated);
6882 free_extent_map(em);
6883 ret = false;
6884 goto out;
6886 next_start = extent_map_end(em);
6887 free_extent_map(em);
6889 read_lock(&map_tree->map_tree.lock);
6890 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6891 (u64)(-1) - next_start);
6892 read_unlock(&map_tree->map_tree.lock);
6894 out:
6895 return ret;
6898 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6900 struct btrfs_root *root = fs_info->chunk_root;
6901 struct btrfs_path *path;
6902 struct extent_buffer *leaf;
6903 struct btrfs_key key;
6904 struct btrfs_key found_key;
6905 int ret;
6906 int slot;
6907 u64 total_dev = 0;
6909 path = btrfs_alloc_path();
6910 if (!path)
6911 return -ENOMEM;
6913 mutex_lock(&uuid_mutex);
6914 mutex_lock(&fs_info->chunk_mutex);
6917 * It is possible for mount and umount to race in such a way that
6918 * we execute this code path, but open_fs_devices failed to clear
6919 * total_rw_bytes. We certainly want it cleared before reading the
6920 * device items, so clear it here.
6922 fs_info->fs_devices->total_rw_bytes = 0;
6925 * Read all device items, and then all the chunk items. All
6926 * device items are found before any chunk item (their object id
6927 * is smaller than the lowest possible object id for a chunk
6928 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6930 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6931 key.offset = 0;
6932 key.type = 0;
6933 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6934 if (ret < 0)
6935 goto error;
6936 while (1) {
6937 leaf = path->nodes[0];
6938 slot = path->slots[0];
6939 if (slot >= btrfs_header_nritems(leaf)) {
6940 ret = btrfs_next_leaf(root, path);
6941 if (ret == 0)
6942 continue;
6943 if (ret < 0)
6944 goto error;
6945 break;
6947 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6948 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6949 struct btrfs_dev_item *dev_item;
6950 dev_item = btrfs_item_ptr(leaf, slot,
6951 struct btrfs_dev_item);
6952 ret = read_one_dev(fs_info, leaf, dev_item);
6953 if (ret)
6954 goto error;
6955 total_dev++;
6956 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6957 struct btrfs_chunk *chunk;
6958 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6959 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
6960 if (ret)
6961 goto error;
6963 path->slots[0]++;
6967 * After loading chunk tree, we've got all device information,
6968 * do another round of validation checks.
6970 if (total_dev != fs_info->fs_devices->total_devices) {
6971 btrfs_err(fs_info,
6972 "super_num_devices %llu mismatch with num_devices %llu found here",
6973 btrfs_super_num_devices(fs_info->super_copy),
6974 total_dev);
6975 ret = -EINVAL;
6976 goto error;
6978 if (btrfs_super_total_bytes(fs_info->super_copy) <
6979 fs_info->fs_devices->total_rw_bytes) {
6980 btrfs_err(fs_info,
6981 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
6982 btrfs_super_total_bytes(fs_info->super_copy),
6983 fs_info->fs_devices->total_rw_bytes);
6984 ret = -EINVAL;
6985 goto error;
6987 ret = 0;
6988 error:
6989 mutex_unlock(&fs_info->chunk_mutex);
6990 mutex_unlock(&uuid_mutex);
6992 btrfs_free_path(path);
6993 return ret;
6996 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6998 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6999 struct btrfs_device *device;
7001 while (fs_devices) {
7002 mutex_lock(&fs_devices->device_list_mutex);
7003 list_for_each_entry(device, &fs_devices->devices, dev_list)
7004 device->fs_info = fs_info;
7005 mutex_unlock(&fs_devices->device_list_mutex);
7007 fs_devices = fs_devices->seed;
7011 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7013 int i;
7015 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7016 btrfs_dev_stat_reset(dev, i);
7019 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7021 struct btrfs_key key;
7022 struct btrfs_key found_key;
7023 struct btrfs_root *dev_root = fs_info->dev_root;
7024 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7025 struct extent_buffer *eb;
7026 int slot;
7027 int ret = 0;
7028 struct btrfs_device *device;
7029 struct btrfs_path *path = NULL;
7030 int i;
7032 path = btrfs_alloc_path();
7033 if (!path) {
7034 ret = -ENOMEM;
7035 goto out;
7038 mutex_lock(&fs_devices->device_list_mutex);
7039 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7040 int item_size;
7041 struct btrfs_dev_stats_item *ptr;
7043 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7044 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7045 key.offset = device->devid;
7046 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7047 if (ret) {
7048 __btrfs_reset_dev_stats(device);
7049 device->dev_stats_valid = 1;
7050 btrfs_release_path(path);
7051 continue;
7053 slot = path->slots[0];
7054 eb = path->nodes[0];
7055 btrfs_item_key_to_cpu(eb, &found_key, slot);
7056 item_size = btrfs_item_size_nr(eb, slot);
7058 ptr = btrfs_item_ptr(eb, slot,
7059 struct btrfs_dev_stats_item);
7061 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7062 if (item_size >= (1 + i) * sizeof(__le64))
7063 btrfs_dev_stat_set(device, i,
7064 btrfs_dev_stats_value(eb, ptr, i));
7065 else
7066 btrfs_dev_stat_reset(device, i);
7069 device->dev_stats_valid = 1;
7070 btrfs_dev_stat_print_on_load(device);
7071 btrfs_release_path(path);
7073 mutex_unlock(&fs_devices->device_list_mutex);
7075 out:
7076 btrfs_free_path(path);
7077 return ret < 0 ? ret : 0;
7080 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7081 struct btrfs_fs_info *fs_info,
7082 struct btrfs_device *device)
7084 struct btrfs_root *dev_root = fs_info->dev_root;
7085 struct btrfs_path *path;
7086 struct btrfs_key key;
7087 struct extent_buffer *eb;
7088 struct btrfs_dev_stats_item *ptr;
7089 int ret;
7090 int i;
7092 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7093 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7094 key.offset = device->devid;
7096 path = btrfs_alloc_path();
7097 if (!path)
7098 return -ENOMEM;
7099 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7100 if (ret < 0) {
7101 btrfs_warn_in_rcu(fs_info,
7102 "error %d while searching for dev_stats item for device %s",
7103 ret, rcu_str_deref(device->name));
7104 goto out;
7107 if (ret == 0 &&
7108 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7109 /* need to delete old one and insert a new one */
7110 ret = btrfs_del_item(trans, dev_root, path);
7111 if (ret != 0) {
7112 btrfs_warn_in_rcu(fs_info,
7113 "delete too small dev_stats item for device %s failed %d",
7114 rcu_str_deref(device->name), ret);
7115 goto out;
7117 ret = 1;
7120 if (ret == 1) {
7121 /* need to insert a new item */
7122 btrfs_release_path(path);
7123 ret = btrfs_insert_empty_item(trans, dev_root, path,
7124 &key, sizeof(*ptr));
7125 if (ret < 0) {
7126 btrfs_warn_in_rcu(fs_info,
7127 "insert dev_stats item for device %s failed %d",
7128 rcu_str_deref(device->name), ret);
7129 goto out;
7133 eb = path->nodes[0];
7134 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7135 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7136 btrfs_set_dev_stats_value(eb, ptr, i,
7137 btrfs_dev_stat_read(device, i));
7138 btrfs_mark_buffer_dirty(eb);
7140 out:
7141 btrfs_free_path(path);
7142 return ret;
7146 * called from commit_transaction. Writes all changed device stats to disk.
7148 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7149 struct btrfs_fs_info *fs_info)
7151 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7152 struct btrfs_device *device;
7153 int stats_cnt;
7154 int ret = 0;
7156 mutex_lock(&fs_devices->device_list_mutex);
7157 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7158 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7159 if (!device->dev_stats_valid || stats_cnt == 0)
7160 continue;
7164 * There is a LOAD-LOAD control dependency between the value of
7165 * dev_stats_ccnt and updating the on-disk values which requires
7166 * reading the in-memory counters. Such control dependencies
7167 * require explicit read memory barriers.
7169 * This memory barriers pairs with smp_mb__before_atomic in
7170 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7171 * barrier implied by atomic_xchg in
7172 * btrfs_dev_stats_read_and_reset
7174 smp_rmb();
7176 ret = update_dev_stat_item(trans, fs_info, device);
7177 if (!ret)
7178 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7180 mutex_unlock(&fs_devices->device_list_mutex);
7182 return ret;
7185 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7187 btrfs_dev_stat_inc(dev, index);
7188 btrfs_dev_stat_print_on_error(dev);
7191 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7193 if (!dev->dev_stats_valid)
7194 return;
7195 btrfs_err_rl_in_rcu(dev->fs_info,
7196 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7197 rcu_str_deref(dev->name),
7198 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7199 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7200 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7201 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7202 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7205 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7207 int i;
7209 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7210 if (btrfs_dev_stat_read(dev, i) != 0)
7211 break;
7212 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7213 return; /* all values == 0, suppress message */
7215 btrfs_info_in_rcu(dev->fs_info,
7216 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7217 rcu_str_deref(dev->name),
7218 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7219 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7220 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7221 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7222 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7225 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7226 struct btrfs_ioctl_get_dev_stats *stats)
7228 struct btrfs_device *dev;
7229 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7230 int i;
7232 mutex_lock(&fs_devices->device_list_mutex);
7233 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7234 mutex_unlock(&fs_devices->device_list_mutex);
7236 if (!dev) {
7237 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7238 return -ENODEV;
7239 } else if (!dev->dev_stats_valid) {
7240 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7241 return -ENODEV;
7242 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7243 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7244 if (stats->nr_items > i)
7245 stats->values[i] =
7246 btrfs_dev_stat_read_and_reset(dev, i);
7247 else
7248 btrfs_dev_stat_reset(dev, i);
7250 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7251 current->comm, task_pid_nr(current));
7252 } else {
7253 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7254 if (stats->nr_items > i)
7255 stats->values[i] = btrfs_dev_stat_read(dev, i);
7257 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7258 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7259 return 0;
7262 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7264 struct buffer_head *bh;
7265 struct btrfs_super_block *disk_super;
7266 int copy_num;
7268 if (!bdev)
7269 return;
7271 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7272 copy_num++) {
7274 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7275 continue;
7277 disk_super = (struct btrfs_super_block *)bh->b_data;
7279 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7280 set_buffer_dirty(bh);
7281 sync_dirty_buffer(bh);
7282 brelse(bh);
7285 /* Notify udev that device has changed */
7286 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7288 /* Update ctime/mtime for device path for libblkid */
7289 update_dev_time(device_path);
7293 * Update the size of all devices, which is used for writing out the
7294 * super blocks.
7296 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7298 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7299 struct btrfs_device *curr, *next;
7301 if (list_empty(&fs_devices->resized_devices))
7302 return;
7304 mutex_lock(&fs_devices->device_list_mutex);
7305 mutex_lock(&fs_info->chunk_mutex);
7306 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7307 resized_list) {
7308 list_del_init(&curr->resized_list);
7309 curr->commit_total_bytes = curr->disk_total_bytes;
7311 mutex_unlock(&fs_info->chunk_mutex);
7312 mutex_unlock(&fs_devices->device_list_mutex);
7315 /* Must be invoked during the transaction commit */
7316 void btrfs_update_commit_device_bytes_used(struct btrfs_fs_info *fs_info,
7317 struct btrfs_transaction *transaction)
7319 struct extent_map *em;
7320 struct map_lookup *map;
7321 struct btrfs_device *dev;
7322 int i;
7324 if (list_empty(&transaction->pending_chunks))
7325 return;
7327 /* In order to kick the device replace finish process */
7328 mutex_lock(&fs_info->chunk_mutex);
7329 list_for_each_entry(em, &transaction->pending_chunks, list) {
7330 map = em->map_lookup;
7332 for (i = 0; i < map->num_stripes; i++) {
7333 dev = map->stripes[i].dev;
7334 dev->commit_bytes_used = dev->bytes_used;
7335 dev->has_pending_chunks = false;
7338 mutex_unlock(&fs_info->chunk_mutex);
7341 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7343 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7344 while (fs_devices) {
7345 fs_devices->fs_info = fs_info;
7346 fs_devices = fs_devices->seed;
7350 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7352 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7353 while (fs_devices) {
7354 fs_devices->fs_info = NULL;
7355 fs_devices = fs_devices->seed;