Path: blob/main/sys/contrib/openzfs/module/os/linux/zfs/vdev_disk.c
48774 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* Common Development and Distribution License (the "License").6* You may not use this file except in compliance with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or https://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/21/*22* Copyright (C) 2008-2010 Lawrence Livermore National Security, LLC.23* Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).24* Rewritten for Linux by Brian Behlendorf <[email protected]>.25* LLNL-CODE-403049.26* Copyright (c) 2012, 2019 by Delphix. All rights reserved.27* Copyright (c) 2023, 2024, 2025, Klara, Inc.28*/2930#include <sys/zfs_context.h>31#include <sys/spa_impl.h>32#include <sys/vdev_disk.h>33#include <sys/vdev_impl.h>34#include <sys/vdev_trim.h>35#include <sys/abd.h>36#include <sys/fs/zfs.h>37#include <sys/zio.h>38#include <linux/blkpg.h>39#include <linux/msdos_fs.h>40#include <linux/vfs_compat.h>41#include <linux/blk-cgroup.h>4243/*44* Linux 6.8.x uses a bdev_handle as an instance/refcount for an underlying45* block_device. Since it carries the block_device inside, its convenient to46* just use the handle as a proxy.47*48* Linux 6.9.x uses a file for the same purpose.49*50* For pre-6.8, we just emulate this with a cast, since we don't need any of51* the other fields inside the handle.52*/53#if defined(HAVE_BDEV_OPEN_BY_PATH)54typedef struct bdev_handle zfs_bdev_handle_t;55#define BDH_BDEV(bdh) ((bdh)->bdev)56#define BDH_IS_ERR(bdh) (IS_ERR(bdh))57#define BDH_PTR_ERR(bdh) (PTR_ERR(bdh))58#define BDH_ERR_PTR(err) (ERR_PTR(err))59#elif defined(HAVE_BDEV_FILE_OPEN_BY_PATH)60typedef struct file zfs_bdev_handle_t;61#define BDH_BDEV(bdh) (file_bdev(bdh))62#define BDH_IS_ERR(bdh) (IS_ERR(bdh))63#define BDH_PTR_ERR(bdh) (PTR_ERR(bdh))64#define BDH_ERR_PTR(err) (ERR_PTR(err))65#else66typedef void zfs_bdev_handle_t;67#define BDH_BDEV(bdh) ((struct block_device *)bdh)68#define BDH_IS_ERR(bdh) (IS_ERR(BDH_BDEV(bdh)))69#define BDH_PTR_ERR(bdh) (PTR_ERR(BDH_BDEV(bdh)))70#define BDH_ERR_PTR(err) (ERR_PTR(err))71#endif7273typedef struct vdev_disk {74zfs_bdev_handle_t *vd_bdh;75krwlock_t vd_lock;76} vdev_disk_t;7778/*79* Maximum number of segments to add to a bio (min 4). If this is higher than80* the maximum allowed by the device queue or the kernel itself, it will be81* clamped. Setting it to zero will cause the kernel's ideal size to be used.82*/83uint_t zfs_vdev_disk_max_segs = 0;8485/*86* Unique identifier for the exclusive vdev holder.87*/88static void *zfs_vdev_holder = VDEV_HOLDER;8990/*91* Wait up to zfs_vdev_open_timeout_ms milliseconds before determining the92* device is missing. The missing path may be transient since the links93* can be briefly removed and recreated in response to udev events.94*/95static uint_t zfs_vdev_open_timeout_ms = 1000;9697/*98* Size of the "reserved" partition, in blocks.99*/100#define EFI_MIN_RESV_SIZE (16 * 1024)101102/*103* BIO request failfast mask.104*/105106static unsigned int zfs_vdev_failfast_mask = 1;107108/*109* Convert SPA mode flags into bdev open mode flags.110*/111#ifdef HAVE_BLK_MODE_T112typedef blk_mode_t vdev_bdev_mode_t;113#define VDEV_BDEV_MODE_READ BLK_OPEN_READ114#define VDEV_BDEV_MODE_WRITE BLK_OPEN_WRITE115#define VDEV_BDEV_MODE_EXCL BLK_OPEN_EXCL116#define VDEV_BDEV_MODE_MASK (BLK_OPEN_READ|BLK_OPEN_WRITE|BLK_OPEN_EXCL)117#else118typedef fmode_t vdev_bdev_mode_t;119#define VDEV_BDEV_MODE_READ FMODE_READ120#define VDEV_BDEV_MODE_WRITE FMODE_WRITE121#define VDEV_BDEV_MODE_EXCL FMODE_EXCL122#define VDEV_BDEV_MODE_MASK (FMODE_READ|FMODE_WRITE|FMODE_EXCL)123#endif124125static vdev_bdev_mode_t126vdev_bdev_mode(spa_mode_t smode)127{128ASSERT3U(smode, !=, SPA_MODE_UNINIT);129ASSERT0(smode & ~(SPA_MODE_READ|SPA_MODE_WRITE));130131vdev_bdev_mode_t bmode = VDEV_BDEV_MODE_EXCL;132133if (smode & SPA_MODE_READ)134bmode |= VDEV_BDEV_MODE_READ;135136if (smode & SPA_MODE_WRITE)137bmode |= VDEV_BDEV_MODE_WRITE;138139ASSERT(bmode & VDEV_BDEV_MODE_MASK);140ASSERT0(bmode & ~VDEV_BDEV_MODE_MASK);141142return (bmode);143}144145/*146* Returns the usable capacity (in bytes) for the partition or disk.147*/148static uint64_t149bdev_capacity(struct block_device *bdev)150{151#ifdef HAVE_BDEV_NR_BYTES152return (bdev_nr_bytes(bdev));153#else154return (i_size_read(bdev->bd_inode));155#endif156}157158#if !defined(HAVE_BDEV_WHOLE)159static inline struct block_device *160bdev_whole(struct block_device *bdev)161{162return (bdev->bd_contains);163}164#endif165166#if defined(HAVE_BDEVNAME)167#define vdev_bdevname(bdev, name) bdevname(bdev, name)168#else169static inline void170vdev_bdevname(struct block_device *bdev, char *name)171{172snprintf(name, BDEVNAME_SIZE, "%pg", bdev);173}174#endif175176/*177* Returns the maximum expansion capacity of the block device (in bytes).178*179* It is possible to expand a vdev when it has been created as a wholedisk180* and the containing block device has increased in capacity. Or when the181* partition containing the pool has been manually increased in size.182*183* This function is only responsible for calculating the potential expansion184* size so it can be reported by 'zpool list'. The efi_use_whole_disk() is185* responsible for verifying the expected partition layout in the wholedisk186* case, and updating the partition table if appropriate. Once the partition187* size has been increased the additional capacity will be visible using188* bdev_capacity().189*190* The returned maximum expansion capacity is always expected to be larger, or191* at the very least equal, to its usable capacity to prevent overestimating192* the pool expandsize.193*/194static uint64_t195bdev_max_capacity(struct block_device *bdev, uint64_t wholedisk)196{197uint64_t psize;198int64_t available;199200if (wholedisk && bdev != bdev_whole(bdev)) {201/*202* When reporting maximum expansion capacity for a wholedisk203* deduct any capacity which is expected to be lost due to204* alignment restrictions. Over reporting this value isn't205* harmful and would only result in slightly less capacity206* than expected post expansion.207* The estimated available space may be slightly smaller than208* bdev_capacity() for devices where the number of sectors is209* not a multiple of the alignment size and the partition layout210* is keeping less than PARTITION_END_ALIGNMENT bytes after the211* "reserved" EFI partition: in such cases return the device212* usable capacity.213*/214available = bdev_capacity(bdev_whole(bdev)) -215((EFI_MIN_RESV_SIZE + NEW_START_BLOCK +216PARTITION_END_ALIGNMENT) << SECTOR_BITS);217psize = MAX(available, bdev_capacity(bdev));218} else {219psize = bdev_capacity(bdev);220}221222return (psize);223}224225static void226vdev_disk_error(zio_t *zio)227{228/*229* This function can be called in interrupt context, for instance while230* handling IRQs coming from a misbehaving disk device; use printk()231* which is safe from any context.232*/233printk(KERN_WARNING "zio pool=%s vdev=%s error=%d type=%d "234"offset=%llu size=%llu flags=%llu\n", spa_name(zio->io_spa),235zio->io_vd->vdev_path, zio->io_error, zio->io_type,236(u_longlong_t)zio->io_offset, (u_longlong_t)zio->io_size,237zio->io_flags);238}239240static void241vdev_disk_kobj_evt_post(vdev_t *v)242{243vdev_disk_t *vd = v->vdev_tsd;244if (vd && vd->vd_bdh) {245spl_signal_kobj_evt(BDH_BDEV(vd->vd_bdh));246} else {247vdev_dbgmsg(v, "vdev_disk_t is NULL for VDEV:%s\n",248v->vdev_path);249}250}251252static zfs_bdev_handle_t *253vdev_blkdev_get_by_path(const char *path, spa_mode_t smode, void *holder)254{255vdev_bdev_mode_t bmode = vdev_bdev_mode(smode);256257#if defined(HAVE_BDEV_FILE_OPEN_BY_PATH)258return (bdev_file_open_by_path(path, bmode, holder, NULL));259#elif defined(HAVE_BDEV_OPEN_BY_PATH)260return (bdev_open_by_path(path, bmode, holder, NULL));261#elif defined(HAVE_BLKDEV_GET_BY_PATH_4ARG)262return (blkdev_get_by_path(path, bmode, holder, NULL));263#else264return (blkdev_get_by_path(path, bmode, holder));265#endif266}267268static void269vdev_blkdev_put(zfs_bdev_handle_t *bdh, spa_mode_t smode, void *holder)270{271#if defined(HAVE_BDEV_RELEASE)272return (bdev_release(bdh));273#elif defined(HAVE_BLKDEV_PUT_HOLDER)274return (blkdev_put(BDH_BDEV(bdh), holder));275#elif defined(HAVE_BLKDEV_PUT)276return (blkdev_put(BDH_BDEV(bdh), vdev_bdev_mode(smode)));277#else278fput(bdh);279#endif280}281282static int283vdev_disk_open(vdev_t *v, uint64_t *psize, uint64_t *max_psize,284uint64_t *logical_ashift, uint64_t *physical_ashift)285{286zfs_bdev_handle_t *bdh;287spa_mode_t smode = spa_mode(v->vdev_spa);288hrtime_t timeout = MSEC2NSEC(zfs_vdev_open_timeout_ms);289vdev_disk_t *vd;290291/* Must have a pathname and it must be absolute. */292if (v->vdev_path == NULL || v->vdev_path[0] != '/') {293v->vdev_stat.vs_aux = VDEV_AUX_BAD_LABEL;294vdev_dbgmsg(v, "invalid vdev_path");295return (SET_ERROR(EINVAL));296}297298/*299* Reopen the device if it is currently open. When expanding a300* partition force re-scanning the partition table if userland301* did not take care of this already. We need to do this while closed302* in order to get an accurate updated block device size. Then303* since udev may need to recreate the device links increase the304* open retry timeout before reporting the device as unavailable.305*/306vd = v->vdev_tsd;307if (vd) {308char disk_name[BDEVNAME_SIZE + 6] = "/dev/";309boolean_t reread_part = B_FALSE;310311rw_enter(&vd->vd_lock, RW_WRITER);312bdh = vd->vd_bdh;313vd->vd_bdh = NULL;314315if (bdh) {316struct block_device *bdev = BDH_BDEV(bdh);317if (v->vdev_expanding && bdev != bdev_whole(bdev)) {318vdev_bdevname(bdev_whole(bdev), disk_name + 5);319/*320* If userland has BLKPG_RESIZE_PARTITION,321* then it should have updated the partition322* table already. We can detect this by323* comparing our current physical size324* with that of the device. If they are325* the same, then we must not have326* BLKPG_RESIZE_PARTITION or it failed to327* update the partition table online. We328* fallback to rescanning the partition329* table from the kernel below. However,330* if the capacity already reflects the331* updated partition, then we skip332* rescanning the partition table here.333*/334if (v->vdev_psize == bdev_capacity(bdev))335reread_part = B_TRUE;336}337338vdev_blkdev_put(bdh, smode, zfs_vdev_holder);339}340341if (reread_part) {342bdh = vdev_blkdev_get_by_path(disk_name, smode,343zfs_vdev_holder);344if (!BDH_IS_ERR(bdh)) {345int error =346vdev_bdev_reread_part(BDH_BDEV(bdh));347vdev_blkdev_put(bdh, smode, zfs_vdev_holder);348if (error == 0) {349timeout = MSEC2NSEC(350zfs_vdev_open_timeout_ms * 2);351}352}353}354} else {355vd = kmem_zalloc(sizeof (vdev_disk_t), KM_SLEEP);356357rw_init(&vd->vd_lock, NULL, RW_DEFAULT, NULL);358rw_enter(&vd->vd_lock, RW_WRITER);359}360361/*362* Devices are always opened by the path provided at configuration363* time. This means that if the provided path is a udev by-id path364* then drives may be re-cabled without an issue. If the provided365* path is a udev by-path path, then the physical location information366* will be preserved. This can be critical for more complicated367* configurations where drives are located in specific physical368* locations to maximize the systems tolerance to component failure.369*370* Alternatively, you can provide your own udev rule to flexibly map371* the drives as you see fit. It is not advised that you use the372* /dev/[hd]d devices which may be reordered due to probing order.373* Devices in the wrong locations will be detected by the higher374* level vdev validation.375*376* The specified paths may be briefly removed and recreated in377* response to udev events. This should be exceptionally unlikely378* because the zpool command makes every effort to verify these paths379* have already settled prior to reaching this point. Therefore,380* a ENOENT failure at this point is highly likely to be transient381* and it is reasonable to sleep and retry before giving up. In382* practice delays have been observed to be on the order of 100ms.383*384* When ERESTARTSYS is returned it indicates the block device is385* a zvol which could not be opened due to the deadlock detection386* logic in zvol_open(). Extend the timeout and retry the open387* subsequent attempts are expected to eventually succeed.388*/389hrtime_t start = gethrtime();390bdh = BDH_ERR_PTR(-ENXIO);391while (BDH_IS_ERR(bdh) && ((gethrtime() - start) < timeout)) {392bdh = vdev_blkdev_get_by_path(v->vdev_path, smode,393zfs_vdev_holder);394if (unlikely(BDH_PTR_ERR(bdh) == -ENOENT)) {395/*396* There is no point of waiting since device is removed397* explicitly398*/399if (v->vdev_removed)400break;401402schedule_timeout_interruptible(MSEC_TO_TICK(10));403} else if (unlikely(BDH_PTR_ERR(bdh) == -ERESTARTSYS)) {404timeout = MSEC2NSEC(zfs_vdev_open_timeout_ms * 10);405continue;406} else if (BDH_IS_ERR(bdh)) {407break;408}409}410411if (BDH_IS_ERR(bdh)) {412int error = -BDH_PTR_ERR(bdh);413vdev_dbgmsg(v, "open error=%d timeout=%llu/%llu", error,414(u_longlong_t)(gethrtime() - start),415(u_longlong_t)timeout);416vd->vd_bdh = NULL;417v->vdev_tsd = vd;418rw_exit(&vd->vd_lock);419return (SET_ERROR(error));420} else {421vd->vd_bdh = bdh;422v->vdev_tsd = vd;423rw_exit(&vd->vd_lock);424}425426struct block_device *bdev = BDH_BDEV(vd->vd_bdh);427428/* Determine the physical block size */429int physical_block_size = bdev_physical_block_size(bdev);430431/* Determine the logical block size */432int logical_block_size = bdev_logical_block_size(bdev);433434/*435* If the device has a write cache, clear the nowritecache flag,436* so that we start issuing flush requests again.437*/438v->vdev_nowritecache = !zfs_bdev_has_write_cache(bdev);439440/* Set when device reports it supports TRIM. */441v->vdev_has_trim = bdev_discard_supported(bdev);442443/* Set when device reports it supports secure TRIM. */444v->vdev_has_securetrim = bdev_secure_discard_supported(bdev);445446/* Inform the ZIO pipeline that we are non-rotational */447v->vdev_nonrot = blk_queue_nonrot(bdev_get_queue(bdev));448449/* Physical volume size in bytes for the partition */450*psize = bdev_capacity(bdev);451452/* Physical volume size in bytes including possible expansion space */453*max_psize = bdev_max_capacity(bdev, v->vdev_wholedisk);454455/* Based on the minimum sector size set the block size */456*physical_ashift = highbit64(MAX(physical_block_size,457SPA_MINBLOCKSIZE)) - 1;458459*logical_ashift = highbit64(MAX(logical_block_size,460SPA_MINBLOCKSIZE)) - 1;461462return (0);463}464465static void466vdev_disk_close(vdev_t *v)467{468vdev_disk_t *vd = v->vdev_tsd;469470if (v->vdev_reopening || vd == NULL)471return;472473rw_enter(&vd->vd_lock, RW_WRITER);474475if (vd->vd_bdh != NULL)476vdev_blkdev_put(vd->vd_bdh, spa_mode(v->vdev_spa),477zfs_vdev_holder);478479v->vdev_tsd = NULL;480481rw_exit(&vd->vd_lock);482rw_destroy(&vd->vd_lock);483kmem_free(vd, sizeof (vdev_disk_t));484}485486/*487* preempt_schedule_notrace is GPL-only which breaks the ZFS build, so488* replace it with preempt_schedule under the following condition:489*/490#if defined(CONFIG_ARM64) && \491defined(CONFIG_PREEMPTION) && \492defined(CONFIG_BLK_CGROUP)493#define preempt_schedule_notrace(x) preempt_schedule(x)494#endif495496/*497* As for the Linux 5.18 kernel bio_alloc() expects a block_device struct498* as an argument removing the need to set it with bio_set_dev(). This499* removes the need for all of the following compatibility code.500*/501#if !defined(HAVE_BIO_ALLOC_4ARG)502503#if defined(CONFIG_BLK_CGROUP) && defined(HAVE_BIO_SET_DEV_GPL_ONLY)504/*505* The Linux 5.5 kernel updated percpu_ref_tryget() which is inlined by506* blkg_tryget() to use rcu_read_lock() instead of rcu_read_lock_sched().507* As a side effect the function was converted to GPL-only. Define our508* own version when needed which uses rcu_read_lock_sched().509*510* The Linux 5.17 kernel split linux/blk-cgroup.h into a private and a public511* part, moving blkg_tryget into the private one. Define our own version.512*/513#if defined(HAVE_BLKG_TRYGET_GPL_ONLY) || !defined(HAVE_BLKG_TRYGET)514static inline bool515vdev_blkg_tryget(struct blkcg_gq *blkg)516{517struct percpu_ref *ref = &blkg->refcnt;518unsigned long __percpu *count;519bool rc;520521rcu_read_lock_sched();522523if (__ref_is_percpu(ref, &count)) {524this_cpu_inc(*count);525rc = true;526} else {527#ifdef ZFS_PERCPU_REF_COUNT_IN_DATA528rc = atomic_long_inc_not_zero(&ref->data->count);529#else530rc = atomic_long_inc_not_zero(&ref->count);531#endif532}533534rcu_read_unlock_sched();535536return (rc);537}538#else539#define vdev_blkg_tryget(bg) blkg_tryget(bg)540#endif541#ifdef HAVE_BIO_SET_DEV_MACRO542/*543* The Linux 5.0 kernel updated the bio_set_dev() macro so it calls the544* GPL-only bio_associate_blkg() symbol thus inadvertently converting545* the entire macro. Provide a minimal version which always assigns the546* request queue's root_blkg to the bio.547*/548static inline void549vdev_bio_associate_blkg(struct bio *bio)550{551#if defined(HAVE_BIO_BDEV_DISK)552struct request_queue *q = bio->bi_bdev->bd_disk->queue;553#else554struct request_queue *q = bio->bi_disk->queue;555#endif556557ASSERT3P(q, !=, NULL);558ASSERT0P(bio->bi_blkg);559560if (q->root_blkg && vdev_blkg_tryget(q->root_blkg))561bio->bi_blkg = q->root_blkg;562}563564#define bio_associate_blkg vdev_bio_associate_blkg565#else566static inline void567vdev_bio_set_dev(struct bio *bio, struct block_device *bdev)568{569#if defined(HAVE_BIO_BDEV_DISK)570struct request_queue *q = bdev->bd_disk->queue;571#else572struct request_queue *q = bio->bi_disk->queue;573#endif574bio_clear_flag(bio, BIO_REMAPPED);575if (bio->bi_bdev != bdev)576bio_clear_flag(bio, BIO_THROTTLED);577bio->bi_bdev = bdev;578579ASSERT3P(q, !=, NULL);580ASSERT0P(bio->bi_blkg);581582if (q->root_blkg && vdev_blkg_tryget(q->root_blkg))583bio->bi_blkg = q->root_blkg;584}585#define bio_set_dev vdev_bio_set_dev586#endif587#endif588#endif /* !HAVE_BIO_ALLOC_4ARG */589590static inline void591vdev_submit_bio(struct bio *bio)592{593struct bio_list *bio_list = current->bio_list;594current->bio_list = NULL;595(void) submit_bio(bio);596current->bio_list = bio_list;597}598599static inline struct bio *600vdev_bio_alloc(struct block_device *bdev, gfp_t gfp_mask,601unsigned short nr_vecs)602{603struct bio *bio;604605#ifdef HAVE_BIO_ALLOC_4ARG606bio = bio_alloc(bdev, nr_vecs, 0, gfp_mask);607#else608bio = bio_alloc(gfp_mask, nr_vecs);609if (likely(bio != NULL))610bio_set_dev(bio, bdev);611#endif612613return (bio);614}615616static inline uint_t617vdev_bio_max_segs(struct block_device *bdev)618{619/*620* Smallest of the device max segs and the tunable max segs. Minimum621* 4, so there's room to finish split pages if they come up.622*/623const uint_t dev_max_segs = queue_max_segments(bdev_get_queue(bdev));624const uint_t tune_max_segs = (zfs_vdev_disk_max_segs > 0) ?625MAX(4, zfs_vdev_disk_max_segs) : dev_max_segs;626const uint_t max_segs = MIN(tune_max_segs, dev_max_segs);627628#ifdef HAVE_BIO_MAX_SEGS629return (bio_max_segs(max_segs));630#else631return (MIN(max_segs, BIO_MAX_PAGES));632#endif633}634635static inline uint_t636vdev_bio_max_bytes(struct block_device *bdev)637{638return (queue_max_sectors(bdev_get_queue(bdev)) << 9);639}640641642/*643* Virtual block IO object (VBIO)644*645* Linux block IO (BIO) objects have a limit on how many data segments (pages)646* they can hold. Depending on how they're allocated and structured, a large647* ZIO can require more than one BIO to be submitted to the kernel, which then648* all have to complete before we can return the completed ZIO back to ZFS.649*650* A VBIO is a wrapper around multiple BIOs, carrying everything needed to651* translate a ZIO down into the kernel block layer and back again.652*653* Note that these are only used for data ZIOs (read/write). Meta-operations654* (flush/trim) don't need multiple BIOs and so can just make the call655* directly.656*/657typedef struct {658zio_t *vbio_zio; /* parent zio */659660struct block_device *vbio_bdev; /* blockdev to submit bios to */661662abd_t *vbio_abd; /* abd carrying borrowed linear buf */663664uint_t vbio_max_segs; /* max segs per bio */665666uint_t vbio_max_bytes; /* max bytes per bio */667uint_t vbio_lbs_mask; /* logical block size mask */668669uint64_t vbio_offset; /* start offset of next bio */670671struct bio *vbio_bio; /* pointer to the current bio */672int vbio_flags; /* bio flags */673} vbio_t;674675static vbio_t *676vbio_alloc(zio_t *zio, struct block_device *bdev, int flags)677{678vbio_t *vbio = kmem_zalloc(sizeof (vbio_t), KM_SLEEP);679680vbio->vbio_zio = zio;681vbio->vbio_bdev = bdev;682vbio->vbio_abd = NULL;683vbio->vbio_max_segs = vdev_bio_max_segs(bdev);684vbio->vbio_max_bytes = vdev_bio_max_bytes(bdev);685vbio->vbio_lbs_mask = ~(bdev_logical_block_size(bdev)-1);686vbio->vbio_offset = zio->io_offset;687vbio->vbio_bio = NULL;688vbio->vbio_flags = flags;689690return (vbio);691}692693static void vbio_completion(struct bio *bio);694695static int696vbio_add_page(vbio_t *vbio, struct page *page, uint_t size, uint_t offset)697{698struct bio *bio = vbio->vbio_bio;699uint_t ssize;700701while (size > 0) {702if (bio == NULL) {703/* New BIO, allocate and set up */704bio = vdev_bio_alloc(vbio->vbio_bdev, GFP_NOIO,705vbio->vbio_max_segs);706VERIFY(bio);707708BIO_BI_SECTOR(bio) = vbio->vbio_offset >> 9;709bio_set_op_attrs(bio,710vbio->vbio_zio->io_type == ZIO_TYPE_WRITE ?711WRITE : READ, vbio->vbio_flags);712713if (vbio->vbio_bio) {714bio_chain(vbio->vbio_bio, bio);715vdev_submit_bio(vbio->vbio_bio);716}717vbio->vbio_bio = bio;718}719720/*721* Only load as much of the current page data as will fit in722* the space left in the BIO, respecting lbs alignment. Older723* kernels will error if we try to overfill the BIO, while724* newer ones will accept it and split the BIO. This ensures725* everything works on older kernels, and avoids an additional726* overhead on the new.727*/728ssize = MIN(size, (vbio->vbio_max_bytes - BIO_BI_SIZE(bio)) &729vbio->vbio_lbs_mask);730if (ssize > 0 &&731bio_add_page(bio, page, ssize, offset) == ssize) {732/* Accepted, adjust and load any remaining. */733size -= ssize;734offset += ssize;735continue;736}737738/* No room, set up for a new BIO and loop */739vbio->vbio_offset += BIO_BI_SIZE(bio);740741/* Signal new BIO allocation wanted */742bio = NULL;743}744745return (0);746}747748/* Iterator callback to submit ABD pages to the vbio. */749static int750vbio_fill_cb(struct page *page, size_t off, size_t len, void *priv)751{752vbio_t *vbio = priv;753return (vbio_add_page(vbio, page, len, off));754}755756/* Create some BIOs, fill them with data and submit them */757static void758vbio_submit(vbio_t *vbio, abd_t *abd, uint64_t size)759{760/*761* We plug so we can submit the BIOs as we go and only unplug them when762* they are fully created and submitted. This is important; if we don't763* plug, then the kernel may start executing earlier BIOs while we're764* still creating and executing later ones, and if the device goes765* away while that's happening, older kernels can get confused and766* trample memory.767*/768struct blk_plug plug;769blk_start_plug(&plug);770771(void) abd_iterate_page_func(abd, 0, size, vbio_fill_cb, vbio);772ASSERT(vbio->vbio_bio);773774vbio->vbio_bio->bi_end_io = vbio_completion;775vbio->vbio_bio->bi_private = vbio;776777/*778* Once submitted, vbio_bio now owns vbio (through bi_private) and we779* can't touch it again. The bio may complete and vbio_completion() be780* called and free the vbio before this task is run again, so we must781* consider it invalid from this point.782*/783vdev_submit_bio(vbio->vbio_bio);784785blk_finish_plug(&plug);786}787788/* IO completion callback */789static void790vbio_completion(struct bio *bio)791{792vbio_t *vbio = bio->bi_private;793zio_t *zio = vbio->vbio_zio;794795ASSERT(zio);796797/* Capture and log any errors */798zio->io_error = bi_status_to_errno(bio->bi_status);799ASSERT3U(zio->io_error, >=, 0);800801if (zio->io_error)802vdev_disk_error(zio);803804/* Return the BIO to the kernel */805bio_put(bio);806807/*808* We're likely in an interrupt context so we can't do ABD/memory work809* here; instead we stash vbio on the zio and take care of it in the810* done callback.811*/812ASSERT0P(zio->io_bio);813zio->io_bio = vbio;814815zio_delay_interrupt(zio);816}817818/*819* Iterator callback to count ABD pages and check their size & alignment.820*821* On Linux, each BIO segment can take a page pointer, and an offset+length of822* the data within that page. A page can be arbitrarily large ("compound"823* pages) but we still have to ensure the data portion is correctly sized and824* aligned to the logical block size, to ensure that if the kernel wants to825* split the BIO, the two halves will still be properly aligned.826*827* NOTE: if you change this function, change the copy in828* tests/zfs-tests/tests/functional/vdev_disk/page_alignment.c, and add test829* data there to validate the change you're making.830*/831typedef struct {832size_t blocksize;833int seen_first;834int seen_last;835} vdev_disk_check_alignment_t;836837static int838vdev_disk_check_alignment_cb(struct page *page, size_t off, size_t len,839void *priv)840{841(void) page;842vdev_disk_check_alignment_t *s = priv;843844/*845* The cardinal rule: a single on-disk block must never cross an846* physical (order-0) page boundary, as the kernel expects to be able847* to split at both LBS and page boundaries.848*849* This implies various alignment rules for the blocks in this850* (possibly compound) page, which we can check for.851*/852853/*854* If the previous page did not end on a page boundary, then we855* can't proceed without creating a hole.856*/857if (s->seen_last)858return (1);859860/* This page must contain only whole LBS-sized blocks. */861if (!IS_P2ALIGNED(len, s->blocksize))862return (1);863864/*865* If this is not the first page in the ABD, then the data must start866* on a page-aligned boundary (so the kernel can split on page867* boundaries without having to deal with a hole). If it is, then868* it can start on LBS-alignment.869*/870if (s->seen_first) {871if (!IS_P2ALIGNED(off, PAGESIZE))872return (1);873} else {874if (!IS_P2ALIGNED(off, s->blocksize))875return (1);876s->seen_first = 1;877}878879/*880* If this data does not end on a page-aligned boundary, then this881* must be the last page in the ABD, for the same reason.882*/883s->seen_last = !IS_P2ALIGNED(off+len, PAGESIZE);884885return (0);886}887888/*889* Check if we can submit the pages in this ABD to the kernel as-is. Returns890* the number of pages, or 0 if it can't be submitted like this.891*/892static boolean_t893vdev_disk_check_alignment(abd_t *abd, uint64_t size, struct block_device *bdev)894{895vdev_disk_check_alignment_t s = {896.blocksize = bdev_logical_block_size(bdev),897};898899if (abd_iterate_page_func(abd, 0, size,900vdev_disk_check_alignment_cb, &s))901return (B_FALSE);902903return (B_TRUE);904}905906static int907vdev_disk_io_rw(zio_t *zio)908{909vdev_t *v = zio->io_vd;910vdev_disk_t *vd = v->vdev_tsd;911struct block_device *bdev = BDH_BDEV(vd->vd_bdh);912int flags = 0;913914/*915* Accessing outside the block device is never allowed.916*/917if (zio->io_offset + zio->io_size > bdev_capacity(bdev)) {918vdev_dbgmsg(zio->io_vd,919"Illegal access %llu size %llu, device size %llu",920(u_longlong_t)zio->io_offset,921(u_longlong_t)zio->io_size,922(u_longlong_t)bdev_capacity(bdev));923return (SET_ERROR(EIO));924}925926if (!(zio->io_flags & (ZIO_FLAG_IO_RETRY | ZIO_FLAG_TRYHARD)) &&927v->vdev_failfast == B_TRUE) {928bio_set_flags_failfast(bdev, &flags, zfs_vdev_failfast_mask & 1,929zfs_vdev_failfast_mask & 2, zfs_vdev_failfast_mask & 4);930}931932/*933* Check alignment of the incoming ABD. If any part of it would require934* submitting a page that is not aligned to both the logical block size935* and the page size, then we take a copy into a new memory region with936* correct alignment. This should be impossible on a 512b LBS. On937* larger blocks, this can happen at least when a small number of938* blocks (usually 1) are allocated from a shared slab, or when939* abnormally-small data regions (eg gang headers) are mixed into the940* same ABD as larger allocations (eg aggregations).941*/942abd_t *abd = zio->io_abd;943if (!vdev_disk_check_alignment(abd, zio->io_size, bdev)) {944/* Allocate a new memory region with guaranteed alignment */945abd = abd_alloc_for_io(zio->io_size,946zio->io_abd->abd_flags & ABD_FLAG_META);947948/* If we're writing copy our data into it */949if (zio->io_type == ZIO_TYPE_WRITE)950abd_copy(abd, zio->io_abd, zio->io_size);951952/*953* False here would mean the new allocation has an invalid954* alignment too, which would mean that abd_alloc() is not955* guaranteeing this, or our logic in956* vdev_disk_check_alignment() is wrong. In either case,957* something in seriously wrong and its not safe to continue.958*/959VERIFY(vdev_disk_check_alignment(abd, zio->io_size, bdev));960}961962/* Allocate vbio, with a pointer to the borrowed ABD if necessary */963vbio_t *vbio = vbio_alloc(zio, bdev, flags);964if (abd != zio->io_abd)965vbio->vbio_abd = abd;966967/* Fill it with data pages and submit it to the kernel */968vbio_submit(vbio, abd, zio->io_size);969return (0);970}971972static void973vdev_disk_io_flush_completion(struct bio *bio)974{975zio_t *zio = bio->bi_private;976zio->io_error = bi_status_to_errno(bio->bi_status);977if (zio->io_error == EOPNOTSUPP || zio->io_error == ENOTTY)978zio->io_error = SET_ERROR(ENOTSUP);979980bio_put(bio);981ASSERT3S(zio->io_error, >=, 0);982if (zio->io_error)983vdev_disk_error(zio);984zio_interrupt(zio);985}986987static int988vdev_disk_io_flush(struct block_device *bdev, zio_t *zio)989{990struct request_queue *q;991struct bio *bio;992993q = bdev_get_queue(bdev);994if (!q)995return (SET_ERROR(ENXIO));996997bio = vdev_bio_alloc(bdev, GFP_NOIO, 0);998if (unlikely(bio == NULL))999return (SET_ERROR(ENOMEM));10001001bio->bi_end_io = vdev_disk_io_flush_completion;1002bio->bi_private = zio;1003bio_set_flush(bio);1004vdev_submit_bio(bio);1005invalidate_bdev(bdev);10061007return (0);1008}10091010static void1011vdev_disk_discard_end_io(struct bio *bio)1012{1013zio_t *zio = bio->bi_private;1014zio->io_error = bi_status_to_errno(bio->bi_status);10151016bio_put(bio);1017if (zio->io_error)1018vdev_disk_error(zio);1019zio_interrupt(zio);1020}10211022/*1023* Wrappers for the different secure erase and discard APIs. We use async1024* when available; in this case, *biop is set to the last bio in the chain.1025*/1026static int1027vdev_bdev_issue_secure_erase(zfs_bdev_handle_t *bdh, sector_t sector,1028sector_t nsect, struct bio **biop)1029{1030*biop = NULL;1031int error;10321033#if defined(HAVE_BLKDEV_ISSUE_SECURE_ERASE)1034error = blkdev_issue_secure_erase(BDH_BDEV(bdh),1035sector, nsect, GFP_NOFS);1036#elif defined(HAVE_BLKDEV_ISSUE_DISCARD_ASYNC_FLAGS)1037error = __blkdev_issue_discard(BDH_BDEV(bdh),1038sector, nsect, GFP_NOFS, BLKDEV_DISCARD_SECURE, biop);1039#elif defined(HAVE_BLKDEV_ISSUE_DISCARD_FLAGS)1040error = blkdev_issue_discard(BDH_BDEV(bdh),1041sector, nsect, GFP_NOFS, BLKDEV_DISCARD_SECURE);1042#else1043#error "unsupported kernel"1044#endif10451046return (error);1047}10481049static int1050vdev_bdev_issue_discard(zfs_bdev_handle_t *bdh, sector_t sector,1051sector_t nsect, struct bio **biop)1052{1053*biop = NULL;1054int error;10551056#if defined(HAVE_BLKDEV_ISSUE_DISCARD_ASYNC_FLAGS)1057error = __blkdev_issue_discard(BDH_BDEV(bdh),1058sector, nsect, GFP_NOFS, 0, biop);1059#elif defined(HAVE_BLKDEV_ISSUE_DISCARD_ASYNC_NOFLAGS)1060error = __blkdev_issue_discard(BDH_BDEV(bdh),1061sector, nsect, GFP_NOFS, biop);1062#elif defined(HAVE_BLKDEV_ISSUE_DISCARD_FLAGS)1063error = blkdev_issue_discard(BDH_BDEV(bdh),1064sector, nsect, GFP_NOFS, 0);1065#elif defined(HAVE_BLKDEV_ISSUE_DISCARD_NOFLAGS)1066error = blkdev_issue_discard(BDH_BDEV(bdh),1067sector, nsect, GFP_NOFS);1068#else1069#error "unsupported kernel"1070#endif10711072return (error);1073}10741075/*1076* Entry point for TRIM ops. This calls the right wrapper for secure erase or1077* discard, and then does the appropriate finishing work for error vs success1078* and async vs sync.1079*/1080static int1081vdev_disk_io_trim(zio_t *zio)1082{1083int error;1084struct bio *bio;10851086zfs_bdev_handle_t *bdh = ((vdev_disk_t *)zio->io_vd->vdev_tsd)->vd_bdh;1087sector_t sector = zio->io_offset >> 9;1088sector_t nsects = zio->io_size >> 9;10891090if (zio->io_trim_flags & ZIO_TRIM_SECURE)1091error = vdev_bdev_issue_secure_erase(bdh, sector, nsects, &bio);1092else1093error = vdev_bdev_issue_discard(bdh, sector, nsects, &bio);10941095if (error != 0)1096return (SET_ERROR(-error));10971098if (bio == NULL) {1099/*1100* This was a synchronous op that completed successfully, so1101* return it to ZFS immediately.1102*/1103zio_interrupt(zio);1104} else {1105/*1106* This was an asynchronous op; set up completion callback and1107* issue it.1108*/1109bio->bi_private = zio;1110bio->bi_end_io = vdev_disk_discard_end_io;1111vdev_submit_bio(bio);1112}11131114return (0);1115}11161117static void1118vdev_disk_io_start(zio_t *zio)1119{1120vdev_t *v = zio->io_vd;1121vdev_disk_t *vd = v->vdev_tsd;1122int error;11231124/*1125* If the vdev is closed, it's likely in the REMOVED or FAULTED state.1126* Nothing to be done here but return failure.1127*/1128if (vd == NULL) {1129zio->io_error = ENXIO;1130zio_interrupt(zio);1131return;1132}11331134rw_enter(&vd->vd_lock, RW_READER);11351136/*1137* If the vdev is closed, it's likely due to a failed reopen and is1138* in the UNAVAIL state. Nothing to be done here but return failure.1139*/1140if (vd->vd_bdh == NULL) {1141rw_exit(&vd->vd_lock);1142zio->io_error = ENXIO;1143zio_interrupt(zio);1144return;1145}11461147switch (zio->io_type) {1148case ZIO_TYPE_FLUSH:11491150if (!vdev_readable(v)) {1151/* Drive not there, can't flush */1152error = SET_ERROR(ENXIO);1153} else if (zfs_nocacheflush) {1154/* Flushing disabled by operator, declare success */1155error = 0;1156} else if (v->vdev_nowritecache) {1157/* This vdev not capable of flushing */1158error = SET_ERROR(ENOTSUP);1159} else {1160/*1161* Issue the flush. If successful, the response will1162* be handled in the completion callback, so we're done.1163*/1164error = vdev_disk_io_flush(BDH_BDEV(vd->vd_bdh), zio);1165if (error == 0) {1166rw_exit(&vd->vd_lock);1167return;1168}1169}11701171/* Couldn't issue the flush, so set the error and return it */1172rw_exit(&vd->vd_lock);1173zio->io_error = error;1174zio_execute(zio);1175return;11761177case ZIO_TYPE_TRIM:1178error = vdev_disk_io_trim(zio);1179rw_exit(&vd->vd_lock);1180if (error) {1181zio->io_error = error;1182zio_execute(zio);1183}1184return;11851186case ZIO_TYPE_READ:1187case ZIO_TYPE_WRITE:1188zio->io_target_timestamp = zio_handle_io_delay(zio);1189error = vdev_disk_io_rw(zio);1190rw_exit(&vd->vd_lock);1191if (error) {1192zio->io_error = error;1193zio_interrupt(zio);1194}1195return;11961197default:1198/*1199* Getting here means our parent vdev has made a very strange1200* request of us, and shouldn't happen. Assert here to force a1201* crash in dev builds, but in production return the IO1202* unhandled. The pool will likely suspend anyway but that's1203* nicer than crashing the kernel.1204*/1205ASSERT3S(zio->io_type, ==, -1);12061207rw_exit(&vd->vd_lock);1208zio->io_error = SET_ERROR(ENOTSUP);1209zio_interrupt(zio);1210return;1211}12121213__builtin_unreachable();1214}12151216static void1217vdev_disk_io_done(zio_t *zio)1218{1219/* If this was a read or write, we need to clean up the vbio */1220if (zio->io_bio != NULL) {1221vbio_t *vbio = zio->io_bio;1222zio->io_bio = NULL;12231224/*1225* If we copied the ABD before issuing it, clean up and return1226* the copy to the ADB, with changes if appropriate.1227*/1228if (vbio->vbio_abd != NULL) {1229if (zio->io_type == ZIO_TYPE_READ)1230abd_copy(zio->io_abd, vbio->vbio_abd,1231zio->io_size);12321233abd_free(vbio->vbio_abd);1234vbio->vbio_abd = NULL;1235}12361237/* Final cleanup */1238kmem_free(vbio, sizeof (vbio_t));1239}12401241/*1242* If the device returned EIO, we revalidate the media. If it is1243* determined the media has changed this triggers the asynchronous1244* removal of the device from the configuration.1245*/1246if (zio->io_error == EIO) {1247vdev_t *v = zio->io_vd;1248vdev_disk_t *vd = v->vdev_tsd;12491250if (!zfs_check_disk_status(BDH_BDEV(vd->vd_bdh))) {1251invalidate_bdev(BDH_BDEV(vd->vd_bdh));1252v->vdev_remove_wanted = B_TRUE;1253spa_async_request(zio->io_spa, SPA_ASYNC_REMOVE);1254}1255}1256}12571258static void1259vdev_disk_hold(vdev_t *vd)1260{1261ASSERT(spa_config_held(vd->vdev_spa, SCL_STATE, RW_WRITER));12621263/* We must have a pathname, and it must be absolute. */1264if (vd->vdev_path == NULL || vd->vdev_path[0] != '/')1265return;12661267/*1268* Only prefetch path and devid info if the device has1269* never been opened.1270*/1271if (vd->vdev_tsd != NULL)1272return;12731274}12751276static void1277vdev_disk_rele(vdev_t *vd)1278{1279ASSERT(spa_config_held(vd->vdev_spa, SCL_STATE, RW_WRITER));12801281/* XXX: Implement me as a vnode rele for the device */1282}12831284vdev_ops_t vdev_disk_ops = {1285.vdev_op_init = NULL,1286.vdev_op_fini = NULL,1287.vdev_op_open = vdev_disk_open,1288.vdev_op_close = vdev_disk_close,1289.vdev_op_asize_to_psize = vdev_default_psize,1290.vdev_op_psize_to_asize = vdev_default_asize,1291.vdev_op_min_asize = vdev_default_min_asize,1292.vdev_op_min_alloc = NULL,1293.vdev_op_io_start = vdev_disk_io_start,1294.vdev_op_io_done = vdev_disk_io_done,1295.vdev_op_state_change = NULL,1296.vdev_op_need_resilver = NULL,1297.vdev_op_hold = vdev_disk_hold,1298.vdev_op_rele = vdev_disk_rele,1299.vdev_op_remap = NULL,1300.vdev_op_xlate = vdev_default_xlate,1301.vdev_op_rebuild_asize = NULL,1302.vdev_op_metaslab_init = NULL,1303.vdev_op_config_generate = NULL,1304.vdev_op_nparity = NULL,1305.vdev_op_ndisks = NULL,1306.vdev_op_type = VDEV_TYPE_DISK, /* name of this vdev type */1307.vdev_op_leaf = B_TRUE, /* leaf vdev */1308.vdev_op_kobj_evt_post = vdev_disk_kobj_evt_post1309};13101311int1312param_set_min_auto_ashift(const char *buf, zfs_kernel_param_t *kp)1313{1314uint_t val;1315int error;13161317error = kstrtouint(buf, 0, &val);1318if (error < 0)1319return (SET_ERROR(error));13201321if (val < ASHIFT_MIN || val > zfs_vdev_max_auto_ashift)1322return (SET_ERROR(-EINVAL));13231324error = param_set_uint(buf, kp);1325if (error < 0)1326return (SET_ERROR(error));13271328return (0);1329}13301331int1332param_set_max_auto_ashift(const char *buf, zfs_kernel_param_t *kp)1333{1334uint_t val;1335int error;13361337error = kstrtouint(buf, 0, &val);1338if (error < 0)1339return (SET_ERROR(error));13401341if (val > ASHIFT_MAX || val < zfs_vdev_min_auto_ashift)1342return (SET_ERROR(-EINVAL));13431344error = param_set_uint(buf, kp);1345if (error < 0)1346return (SET_ERROR(error));13471348return (0);1349}13501351ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, open_timeout_ms, UINT, ZMOD_RW,1352"Timeout before determining that a device is missing");13531354ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, failfast_mask, UINT, ZMOD_RW,1355"Defines failfast mask: 1 - device, 2 - transport, 4 - driver");13561357ZFS_MODULE_PARAM(zfs_vdev_disk, zfs_vdev_disk_, max_segs, UINT, ZMOD_RW,1358"Maximum number of data segments to add to an IO request (min 4)");135913601361