xref: /freebsd/sys/contrib/openzfs/module/os/linux/zfs/vdev_disk.c (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (C) 2008-2010 Lawrence Livermore National Security, LLC.
24  * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
25  * Rewritten for Linux by Brian Behlendorf <behlendorf1@llnl.gov>.
26  * LLNL-CODE-403049.
27  * Copyright (c) 2012, 2019 by Delphix. All rights reserved.
28  * Copyright (c) 2023, 2024, Klara Inc.
29  */
30 
31 #include <sys/zfs_context.h>
32 #include <sys/spa_impl.h>
33 #include <sys/vdev_disk.h>
34 #include <sys/vdev_impl.h>
35 #include <sys/vdev_trim.h>
36 #include <sys/abd.h>
37 #include <sys/fs/zfs.h>
38 #include <sys/zio.h>
39 #include <linux/blkpg.h>
40 #include <linux/msdos_fs.h>
41 #include <linux/vfs_compat.h>
42 #include <linux/blk-cgroup.h>
43 
44 /*
45  * Linux 6.8.x uses a bdev_handle as an instance/refcount for an underlying
46  * block_device. Since it carries the block_device inside, its convenient to
47  * just use the handle as a proxy.
48  *
49  * Linux 6.9.x uses a file for the same purpose.
50  *
51  * For pre-6.8, we just emulate this with a cast, since we don't need any of
52  * the other fields inside the handle.
53  */
54 #if defined(HAVE_BDEV_OPEN_BY_PATH)
55 typedef struct bdev_handle zfs_bdev_handle_t;
56 #define	BDH_BDEV(bdh)		((bdh)->bdev)
57 #define	BDH_IS_ERR(bdh)		(IS_ERR(bdh))
58 #define	BDH_PTR_ERR(bdh)	(PTR_ERR(bdh))
59 #define	BDH_ERR_PTR(err)	(ERR_PTR(err))
60 #elif defined(HAVE_BDEV_FILE_OPEN_BY_PATH)
61 typedef struct file zfs_bdev_handle_t;
62 #define	BDH_BDEV(bdh)		(file_bdev(bdh))
63 #define	BDH_IS_ERR(bdh)		(IS_ERR(bdh))
64 #define	BDH_PTR_ERR(bdh)	(PTR_ERR(bdh))
65 #define	BDH_ERR_PTR(err)	(ERR_PTR(err))
66 #else
67 typedef void zfs_bdev_handle_t;
68 #define	BDH_BDEV(bdh)		((struct block_device *)bdh)
69 #define	BDH_IS_ERR(bdh)		(IS_ERR(BDH_BDEV(bdh)))
70 #define	BDH_PTR_ERR(bdh)	(PTR_ERR(BDH_BDEV(bdh)))
71 #define	BDH_ERR_PTR(err)	(ERR_PTR(err))
72 #endif
73 
74 typedef struct vdev_disk {
75 	zfs_bdev_handle_t		*vd_bdh;
76 	krwlock_t			vd_lock;
77 } vdev_disk_t;
78 
79 /*
80  * Maximum number of segments to add to a bio (min 4). If this is higher than
81  * the maximum allowed by the device queue or the kernel itself, it will be
82  * clamped. Setting it to zero will cause the kernel's ideal size to be used.
83  */
84 uint_t zfs_vdev_disk_max_segs = 0;
85 
86 /*
87  * Unique identifier for the exclusive vdev holder.
88  */
89 static void *zfs_vdev_holder = VDEV_HOLDER;
90 
91 /*
92  * Wait up to zfs_vdev_open_timeout_ms milliseconds before determining the
93  * device is missing. The missing path may be transient since the links
94  * can be briefly removed and recreated in response to udev events.
95  */
96 static uint_t zfs_vdev_open_timeout_ms = 1000;
97 
98 /*
99  * Size of the "reserved" partition, in blocks.
100  */
101 #define	EFI_MIN_RESV_SIZE	(16 * 1024)
102 
103 /*
104  * BIO request failfast mask.
105  */
106 
107 static unsigned int zfs_vdev_failfast_mask = 1;
108 
109 /*
110  * Convert SPA mode flags into bdev open mode flags.
111  */
112 #ifdef HAVE_BLK_MODE_T
113 typedef blk_mode_t vdev_bdev_mode_t;
114 #define	VDEV_BDEV_MODE_READ	BLK_OPEN_READ
115 #define	VDEV_BDEV_MODE_WRITE	BLK_OPEN_WRITE
116 #define	VDEV_BDEV_MODE_EXCL	BLK_OPEN_EXCL
117 #define	VDEV_BDEV_MODE_MASK	(BLK_OPEN_READ|BLK_OPEN_WRITE|BLK_OPEN_EXCL)
118 #else
119 typedef fmode_t vdev_bdev_mode_t;
120 #define	VDEV_BDEV_MODE_READ	FMODE_READ
121 #define	VDEV_BDEV_MODE_WRITE	FMODE_WRITE
122 #define	VDEV_BDEV_MODE_EXCL	FMODE_EXCL
123 #define	VDEV_BDEV_MODE_MASK	(FMODE_READ|FMODE_WRITE|FMODE_EXCL)
124 #endif
125 
126 static vdev_bdev_mode_t
vdev_bdev_mode(spa_mode_t smode)127 vdev_bdev_mode(spa_mode_t smode)
128 {
129 	ASSERT3U(smode, !=, SPA_MODE_UNINIT);
130 	ASSERT0(smode & ~(SPA_MODE_READ|SPA_MODE_WRITE));
131 
132 	vdev_bdev_mode_t bmode = VDEV_BDEV_MODE_EXCL;
133 
134 	if (smode & SPA_MODE_READ)
135 		bmode |= VDEV_BDEV_MODE_READ;
136 
137 	if (smode & SPA_MODE_WRITE)
138 		bmode |= VDEV_BDEV_MODE_WRITE;
139 
140 	ASSERT(bmode & VDEV_BDEV_MODE_MASK);
141 	ASSERT0(bmode & ~VDEV_BDEV_MODE_MASK);
142 
143 	return (bmode);
144 }
145 
146 /*
147  * Returns the usable capacity (in bytes) for the partition or disk.
148  */
149 static uint64_t
bdev_capacity(struct block_device * bdev)150 bdev_capacity(struct block_device *bdev)
151 {
152 #ifdef HAVE_BDEV_NR_BYTES
153 	return (bdev_nr_bytes(bdev));
154 #else
155 	return (i_size_read(bdev->bd_inode));
156 #endif
157 }
158 
159 #if !defined(HAVE_BDEV_WHOLE)
160 static inline struct block_device *
bdev_whole(struct block_device * bdev)161 bdev_whole(struct block_device *bdev)
162 {
163 	return (bdev->bd_contains);
164 }
165 #endif
166 
167 #if defined(HAVE_BDEVNAME)
168 #define	vdev_bdevname(bdev, name)	bdevname(bdev, name)
169 #else
170 static inline void
vdev_bdevname(struct block_device * bdev,char * name)171 vdev_bdevname(struct block_device *bdev, char *name)
172 {
173 	snprintf(name, BDEVNAME_SIZE, "%pg", bdev);
174 }
175 #endif
176 
177 /*
178  * Returns the maximum expansion capacity of the block device (in bytes).
179  *
180  * It is possible to expand a vdev when it has been created as a wholedisk
181  * and the containing block device has increased in capacity.  Or when the
182  * partition containing the pool has been manually increased in size.
183  *
184  * This function is only responsible for calculating the potential expansion
185  * size so it can be reported by 'zpool list'.  The efi_use_whole_disk() is
186  * responsible for verifying the expected partition layout in the wholedisk
187  * case, and updating the partition table if appropriate.  Once the partition
188  * size has been increased the additional capacity will be visible using
189  * bdev_capacity().
190  *
191  * The returned maximum expansion capacity is always expected to be larger, or
192  * at the very least equal, to its usable capacity to prevent overestimating
193  * the pool expandsize.
194  */
195 static uint64_t
bdev_max_capacity(struct block_device * bdev,uint64_t wholedisk)196 bdev_max_capacity(struct block_device *bdev, uint64_t wholedisk)
197 {
198 	uint64_t psize;
199 	int64_t available;
200 
201 	if (wholedisk && bdev != bdev_whole(bdev)) {
202 		/*
203 		 * When reporting maximum expansion capacity for a wholedisk
204 		 * deduct any capacity which is expected to be lost due to
205 		 * alignment restrictions.  Over reporting this value isn't
206 		 * harmful and would only result in slightly less capacity
207 		 * than expected post expansion.
208 		 * The estimated available space may be slightly smaller than
209 		 * bdev_capacity() for devices where the number of sectors is
210 		 * not a multiple of the alignment size and the partition layout
211 		 * is keeping less than PARTITION_END_ALIGNMENT bytes after the
212 		 * "reserved" EFI partition: in such cases return the device
213 		 * usable capacity.
214 		 */
215 		available = bdev_capacity(bdev_whole(bdev)) -
216 		    ((EFI_MIN_RESV_SIZE + NEW_START_BLOCK +
217 		    PARTITION_END_ALIGNMENT) << SECTOR_BITS);
218 		psize = MAX(available, bdev_capacity(bdev));
219 	} else {
220 		psize = bdev_capacity(bdev);
221 	}
222 
223 	return (psize);
224 }
225 
226 static void
vdev_disk_error(zio_t * zio)227 vdev_disk_error(zio_t *zio)
228 {
229 	/*
230 	 * This function can be called in interrupt context, for instance while
231 	 * handling IRQs coming from a misbehaving disk device; use printk()
232 	 * which is safe from any context.
233 	 */
234 	printk(KERN_WARNING "zio pool=%s vdev=%s error=%d type=%d "
235 	    "offset=%llu size=%llu flags=%llu\n", spa_name(zio->io_spa),
236 	    zio->io_vd->vdev_path, zio->io_error, zio->io_type,
237 	    (u_longlong_t)zio->io_offset, (u_longlong_t)zio->io_size,
238 	    zio->io_flags);
239 }
240 
241 static void
vdev_disk_kobj_evt_post(vdev_t * v)242 vdev_disk_kobj_evt_post(vdev_t *v)
243 {
244 	vdev_disk_t *vd = v->vdev_tsd;
245 	if (vd && vd->vd_bdh) {
246 		spl_signal_kobj_evt(BDH_BDEV(vd->vd_bdh));
247 	} else {
248 		vdev_dbgmsg(v, "vdev_disk_t is NULL for VDEV:%s\n",
249 		    v->vdev_path);
250 	}
251 }
252 
253 static zfs_bdev_handle_t *
vdev_blkdev_get_by_path(const char * path,spa_mode_t smode,void * holder)254 vdev_blkdev_get_by_path(const char *path, spa_mode_t smode, void *holder)
255 {
256 	vdev_bdev_mode_t bmode = vdev_bdev_mode(smode);
257 
258 #if defined(HAVE_BDEV_FILE_OPEN_BY_PATH)
259 	return (bdev_file_open_by_path(path, bmode, holder, NULL));
260 #elif defined(HAVE_BDEV_OPEN_BY_PATH)
261 	return (bdev_open_by_path(path, bmode, holder, NULL));
262 #elif defined(HAVE_BLKDEV_GET_BY_PATH_4ARG)
263 	return (blkdev_get_by_path(path, bmode, holder, NULL));
264 #else
265 	return (blkdev_get_by_path(path, bmode, holder));
266 #endif
267 }
268 
269 static void
vdev_blkdev_put(zfs_bdev_handle_t * bdh,spa_mode_t smode,void * holder)270 vdev_blkdev_put(zfs_bdev_handle_t *bdh, spa_mode_t smode, void *holder)
271 {
272 #if defined(HAVE_BDEV_RELEASE)
273 	return (bdev_release(bdh));
274 #elif defined(HAVE_BLKDEV_PUT_HOLDER)
275 	return (blkdev_put(BDH_BDEV(bdh), holder));
276 #elif defined(HAVE_BLKDEV_PUT)
277 	return (blkdev_put(BDH_BDEV(bdh), vdev_bdev_mode(smode)));
278 #else
279 	fput(bdh);
280 #endif
281 }
282 
283 static int
vdev_disk_open(vdev_t * v,uint64_t * psize,uint64_t * max_psize,uint64_t * logical_ashift,uint64_t * physical_ashift)284 vdev_disk_open(vdev_t *v, uint64_t *psize, uint64_t *max_psize,
285     uint64_t *logical_ashift, uint64_t *physical_ashift)
286 {
287 	zfs_bdev_handle_t *bdh;
288 	spa_mode_t smode = spa_mode(v->vdev_spa);
289 	hrtime_t timeout = MSEC2NSEC(zfs_vdev_open_timeout_ms);
290 	vdev_disk_t *vd;
291 
292 	/* Must have a pathname and it must be absolute. */
293 	if (v->vdev_path == NULL || v->vdev_path[0] != '/') {
294 		v->vdev_stat.vs_aux = VDEV_AUX_BAD_LABEL;
295 		vdev_dbgmsg(v, "invalid vdev_path");
296 		return (SET_ERROR(EINVAL));
297 	}
298 
299 	/*
300 	 * Reopen the device if it is currently open.  When expanding a
301 	 * partition force re-scanning the partition table if userland
302 	 * did not take care of this already. We need to do this while closed
303 	 * in order to get an accurate updated block device size.  Then
304 	 * since udev may need to recreate the device links increase the
305 	 * open retry timeout before reporting the device as unavailable.
306 	 */
307 	vd = v->vdev_tsd;
308 	if (vd) {
309 		char disk_name[BDEVNAME_SIZE + 6] = "/dev/";
310 		boolean_t reread_part = B_FALSE;
311 
312 		rw_enter(&vd->vd_lock, RW_WRITER);
313 		bdh = vd->vd_bdh;
314 		vd->vd_bdh = NULL;
315 
316 		if (bdh) {
317 			struct block_device *bdev = BDH_BDEV(bdh);
318 			if (v->vdev_expanding && bdev != bdev_whole(bdev)) {
319 				vdev_bdevname(bdev_whole(bdev), disk_name + 5);
320 				/*
321 				 * If userland has BLKPG_RESIZE_PARTITION,
322 				 * then it should have updated the partition
323 				 * table already. We can detect this by
324 				 * comparing our current physical size
325 				 * with that of the device. If they are
326 				 * the same, then we must not have
327 				 * BLKPG_RESIZE_PARTITION or it failed to
328 				 * update the partition table online. We
329 				 * fallback to rescanning the partition
330 				 * table from the kernel below. However,
331 				 * if the capacity already reflects the
332 				 * updated partition, then we skip
333 				 * rescanning the partition table here.
334 				 */
335 				if (v->vdev_psize == bdev_capacity(bdev))
336 					reread_part = B_TRUE;
337 			}
338 
339 			vdev_blkdev_put(bdh, smode, zfs_vdev_holder);
340 		}
341 
342 		if (reread_part) {
343 			bdh = vdev_blkdev_get_by_path(disk_name, smode,
344 			    zfs_vdev_holder);
345 			if (!BDH_IS_ERR(bdh)) {
346 				int error =
347 				    vdev_bdev_reread_part(BDH_BDEV(bdh));
348 				vdev_blkdev_put(bdh, smode, zfs_vdev_holder);
349 				if (error == 0) {
350 					timeout = MSEC2NSEC(
351 					    zfs_vdev_open_timeout_ms * 2);
352 				}
353 			}
354 		}
355 	} else {
356 		vd = kmem_zalloc(sizeof (vdev_disk_t), KM_SLEEP);
357 
358 		rw_init(&vd->vd_lock, NULL, RW_DEFAULT, NULL);
359 		rw_enter(&vd->vd_lock, RW_WRITER);
360 	}
361 
362 	/*
363 	 * Devices are always opened by the path provided at configuration
364 	 * time.  This means that if the provided path is a udev by-id path
365 	 * then drives may be re-cabled without an issue.  If the provided
366 	 * path is a udev by-path path, then the physical location information
367 	 * will be preserved.  This can be critical for more complicated
368 	 * configurations where drives are located in specific physical
369 	 * locations to maximize the systems tolerance to component failure.
370 	 *
371 	 * Alternatively, you can provide your own udev rule to flexibly map
372 	 * the drives as you see fit.  It is not advised that you use the
373 	 * /dev/[hd]d devices which may be reordered due to probing order.
374 	 * Devices in the wrong locations will be detected by the higher
375 	 * level vdev validation.
376 	 *
377 	 * The specified paths may be briefly removed and recreated in
378 	 * response to udev events.  This should be exceptionally unlikely
379 	 * because the zpool command makes every effort to verify these paths
380 	 * have already settled prior to reaching this point.  Therefore,
381 	 * a ENOENT failure at this point is highly likely to be transient
382 	 * and it is reasonable to sleep and retry before giving up.  In
383 	 * practice delays have been observed to be on the order of 100ms.
384 	 *
385 	 * When ERESTARTSYS is returned it indicates the block device is
386 	 * a zvol which could not be opened due to the deadlock detection
387 	 * logic in zvol_open().  Extend the timeout and retry the open
388 	 * subsequent attempts are expected to eventually succeed.
389 	 */
390 	hrtime_t start = gethrtime();
391 	bdh = BDH_ERR_PTR(-ENXIO);
392 	while (BDH_IS_ERR(bdh) && ((gethrtime() - start) < timeout)) {
393 		bdh = vdev_blkdev_get_by_path(v->vdev_path, smode,
394 		    zfs_vdev_holder);
395 		if (unlikely(BDH_PTR_ERR(bdh) == -ENOENT)) {
396 			/*
397 			 * There is no point of waiting since device is removed
398 			 * explicitly
399 			 */
400 			if (v->vdev_removed)
401 				break;
402 
403 			schedule_timeout_interruptible(MSEC_TO_TICK(10));
404 		} else if (unlikely(BDH_PTR_ERR(bdh) == -ERESTARTSYS)) {
405 			timeout = MSEC2NSEC(zfs_vdev_open_timeout_ms * 10);
406 			continue;
407 		} else if (BDH_IS_ERR(bdh)) {
408 			break;
409 		}
410 	}
411 
412 	if (BDH_IS_ERR(bdh)) {
413 		int error = -BDH_PTR_ERR(bdh);
414 		vdev_dbgmsg(v, "open error=%d timeout=%llu/%llu", error,
415 		    (u_longlong_t)(gethrtime() - start),
416 		    (u_longlong_t)timeout);
417 		vd->vd_bdh = NULL;
418 		v->vdev_tsd = vd;
419 		rw_exit(&vd->vd_lock);
420 		return (SET_ERROR(error));
421 	} else {
422 		vd->vd_bdh = bdh;
423 		v->vdev_tsd = vd;
424 		rw_exit(&vd->vd_lock);
425 	}
426 
427 	struct block_device *bdev = BDH_BDEV(vd->vd_bdh);
428 
429 	/*  Determine the physical block size */
430 	int physical_block_size = bdev_physical_block_size(bdev);
431 
432 	/*  Determine the logical block size */
433 	int logical_block_size = bdev_logical_block_size(bdev);
434 
435 	/*
436 	 * If the device has a write cache, clear the nowritecache flag,
437 	 * so that we start issuing flush requests again.
438 	 */
439 	v->vdev_nowritecache = !zfs_bdev_has_write_cache(bdev);
440 
441 	/* Set when device reports it supports TRIM. */
442 	v->vdev_has_trim = bdev_discard_supported(bdev);
443 
444 	/* Set when device reports it supports secure TRIM. */
445 	v->vdev_has_securetrim = bdev_secure_discard_supported(bdev);
446 
447 	/* Inform the ZIO pipeline that we are non-rotational */
448 	v->vdev_nonrot = blk_queue_nonrot(bdev_get_queue(bdev));
449 
450 	/* Physical volume size in bytes for the partition */
451 	*psize = bdev_capacity(bdev);
452 
453 	/* Physical volume size in bytes including possible expansion space */
454 	*max_psize = bdev_max_capacity(bdev, v->vdev_wholedisk);
455 
456 	/* Based on the minimum sector size set the block size */
457 	*physical_ashift = highbit64(MAX(physical_block_size,
458 	    SPA_MINBLOCKSIZE)) - 1;
459 
460 	*logical_ashift = highbit64(MAX(logical_block_size,
461 	    SPA_MINBLOCKSIZE)) - 1;
462 
463 	return (0);
464 }
465 
466 static void
vdev_disk_close(vdev_t * v)467 vdev_disk_close(vdev_t *v)
468 {
469 	vdev_disk_t *vd = v->vdev_tsd;
470 
471 	if (v->vdev_reopening || vd == NULL)
472 		return;
473 
474 	if (vd->vd_bdh != NULL)
475 		vdev_blkdev_put(vd->vd_bdh, spa_mode(v->vdev_spa),
476 		    zfs_vdev_holder);
477 
478 	rw_destroy(&vd->vd_lock);
479 	kmem_free(vd, sizeof (vdev_disk_t));
480 	v->vdev_tsd = NULL;
481 }
482 
483 /*
484  * preempt_schedule_notrace is GPL-only which breaks the ZFS build, so
485  * replace it with preempt_schedule under the following condition:
486  */
487 #if defined(CONFIG_ARM64) && \
488     defined(CONFIG_PREEMPTION) && \
489     defined(CONFIG_BLK_CGROUP)
490 #define	preempt_schedule_notrace(x) preempt_schedule(x)
491 #endif
492 
493 /*
494  * As for the Linux 5.18 kernel bio_alloc() expects a block_device struct
495  * as an argument removing the need to set it with bio_set_dev().  This
496  * removes the need for all of the following compatibility code.
497  */
498 #if !defined(HAVE_BIO_ALLOC_4ARG)
499 
500 #if defined(CONFIG_BLK_CGROUP) && defined(HAVE_BIO_SET_DEV_GPL_ONLY)
501 /*
502  * The Linux 5.5 kernel updated percpu_ref_tryget() which is inlined by
503  * blkg_tryget() to use rcu_read_lock() instead of rcu_read_lock_sched().
504  * As a side effect the function was converted to GPL-only.  Define our
505  * own version when needed which uses rcu_read_lock_sched().
506  *
507  * The Linux 5.17 kernel split linux/blk-cgroup.h into a private and a public
508  * part, moving blkg_tryget into the private one. Define our own version.
509  */
510 #if defined(HAVE_BLKG_TRYGET_GPL_ONLY) || !defined(HAVE_BLKG_TRYGET)
511 static inline bool
vdev_blkg_tryget(struct blkcg_gq * blkg)512 vdev_blkg_tryget(struct blkcg_gq *blkg)
513 {
514 	struct percpu_ref *ref = &blkg->refcnt;
515 	unsigned long __percpu *count;
516 	bool rc;
517 
518 	rcu_read_lock_sched();
519 
520 	if (__ref_is_percpu(ref, &count)) {
521 		this_cpu_inc(*count);
522 		rc = true;
523 	} else {
524 #ifdef ZFS_PERCPU_REF_COUNT_IN_DATA
525 		rc = atomic_long_inc_not_zero(&ref->data->count);
526 #else
527 		rc = atomic_long_inc_not_zero(&ref->count);
528 #endif
529 	}
530 
531 	rcu_read_unlock_sched();
532 
533 	return (rc);
534 }
535 #else
536 #define	vdev_blkg_tryget(bg)	blkg_tryget(bg)
537 #endif
538 #ifdef HAVE_BIO_SET_DEV_MACRO
539 /*
540  * The Linux 5.0 kernel updated the bio_set_dev() macro so it calls the
541  * GPL-only bio_associate_blkg() symbol thus inadvertently converting
542  * the entire macro.  Provide a minimal version which always assigns the
543  * request queue's root_blkg to the bio.
544  */
545 static inline void
vdev_bio_associate_blkg(struct bio * bio)546 vdev_bio_associate_blkg(struct bio *bio)
547 {
548 #if defined(HAVE_BIO_BDEV_DISK)
549 	struct request_queue *q = bio->bi_bdev->bd_disk->queue;
550 #else
551 	struct request_queue *q = bio->bi_disk->queue;
552 #endif
553 
554 	ASSERT3P(q, !=, NULL);
555 	ASSERT3P(bio->bi_blkg, ==, NULL);
556 
557 	if (q->root_blkg && vdev_blkg_tryget(q->root_blkg))
558 		bio->bi_blkg = q->root_blkg;
559 }
560 
561 #define	bio_associate_blkg vdev_bio_associate_blkg
562 #else
563 static inline void
vdev_bio_set_dev(struct bio * bio,struct block_device * bdev)564 vdev_bio_set_dev(struct bio *bio, struct block_device *bdev)
565 {
566 #if defined(HAVE_BIO_BDEV_DISK)
567 	struct request_queue *q = bdev->bd_disk->queue;
568 #else
569 	struct request_queue *q = bio->bi_disk->queue;
570 #endif
571 	bio_clear_flag(bio, BIO_REMAPPED);
572 	if (bio->bi_bdev != bdev)
573 		bio_clear_flag(bio, BIO_THROTTLED);
574 	bio->bi_bdev = bdev;
575 
576 	ASSERT3P(q, !=, NULL);
577 	ASSERT3P(bio->bi_blkg, ==, NULL);
578 
579 	if (q->root_blkg && vdev_blkg_tryget(q->root_blkg))
580 		bio->bi_blkg = q->root_blkg;
581 }
582 #define	bio_set_dev		vdev_bio_set_dev
583 #endif
584 #endif
585 #endif /* !HAVE_BIO_ALLOC_4ARG */
586 
587 static inline void
vdev_submit_bio(struct bio * bio)588 vdev_submit_bio(struct bio *bio)
589 {
590 	struct bio_list *bio_list = current->bio_list;
591 	current->bio_list = NULL;
592 	(void) submit_bio(bio);
593 	current->bio_list = bio_list;
594 }
595 
596 static inline struct bio *
vdev_bio_alloc(struct block_device * bdev,gfp_t gfp_mask,unsigned short nr_vecs)597 vdev_bio_alloc(struct block_device *bdev, gfp_t gfp_mask,
598     unsigned short nr_vecs)
599 {
600 	struct bio *bio;
601 
602 #ifdef HAVE_BIO_ALLOC_4ARG
603 	bio = bio_alloc(bdev, nr_vecs, 0, gfp_mask);
604 #else
605 	bio = bio_alloc(gfp_mask, nr_vecs);
606 	if (likely(bio != NULL))
607 		bio_set_dev(bio, bdev);
608 #endif
609 
610 	return (bio);
611 }
612 
613 static inline uint_t
vdev_bio_max_segs(struct block_device * bdev)614 vdev_bio_max_segs(struct block_device *bdev)
615 {
616 	/*
617 	 * Smallest of the device max segs and the tuneable max segs. Minimum
618 	 * 4, so there's room to finish split pages if they come up.
619 	 */
620 	const uint_t dev_max_segs = queue_max_segments(bdev_get_queue(bdev));
621 	const uint_t tune_max_segs = (zfs_vdev_disk_max_segs > 0) ?
622 	    MAX(4, zfs_vdev_disk_max_segs) : dev_max_segs;
623 	const uint_t max_segs = MIN(tune_max_segs, dev_max_segs);
624 
625 #ifdef HAVE_BIO_MAX_SEGS
626 	return (bio_max_segs(max_segs));
627 #else
628 	return (MIN(max_segs, BIO_MAX_PAGES));
629 #endif
630 }
631 
632 static inline uint_t
vdev_bio_max_bytes(struct block_device * bdev)633 vdev_bio_max_bytes(struct block_device *bdev)
634 {
635 	return (queue_max_sectors(bdev_get_queue(bdev)) << 9);
636 }
637 
638 
639 /*
640  * Virtual block IO object (VBIO)
641  *
642  * Linux block IO (BIO) objects have a limit on how many data segments (pages)
643  * they can hold. Depending on how they're allocated and structured, a large
644  * ZIO can require more than one BIO to be submitted to the kernel, which then
645  * all have to complete before we can return the completed ZIO back to ZFS.
646  *
647  * A VBIO is a wrapper around multiple BIOs, carrying everything needed to
648  * translate a ZIO down into the kernel block layer and back again.
649  *
650  * Note that these are only used for data ZIOs (read/write). Meta-operations
651  * (flush/trim) don't need multiple BIOs and so can just make the call
652  * directly.
653  */
654 typedef struct {
655 	zio_t		*vbio_zio;	/* parent zio */
656 
657 	struct block_device *vbio_bdev;	/* blockdev to submit bios to */
658 
659 	abd_t		*vbio_abd;	/* abd carrying borrowed linear buf */
660 
661 	uint_t		vbio_max_segs;	/* max segs per bio */
662 
663 	uint_t		vbio_max_bytes;	/* max bytes per bio */
664 	uint_t		vbio_lbs_mask;	/* logical block size mask */
665 
666 	uint64_t	vbio_offset;	/* start offset of next bio */
667 
668 	struct bio	*vbio_bio;	/* pointer to the current bio */
669 	int		vbio_flags;	/* bio flags */
670 } vbio_t;
671 
672 static vbio_t *
vbio_alloc(zio_t * zio,struct block_device * bdev,int flags)673 vbio_alloc(zio_t *zio, struct block_device *bdev, int flags)
674 {
675 	vbio_t *vbio = kmem_zalloc(sizeof (vbio_t), KM_SLEEP);
676 
677 	vbio->vbio_zio = zio;
678 	vbio->vbio_bdev = bdev;
679 	vbio->vbio_abd = NULL;
680 	vbio->vbio_max_segs = vdev_bio_max_segs(bdev);
681 	vbio->vbio_max_bytes = vdev_bio_max_bytes(bdev);
682 	vbio->vbio_lbs_mask = ~(bdev_logical_block_size(bdev)-1);
683 	vbio->vbio_offset = zio->io_offset;
684 	vbio->vbio_bio = NULL;
685 	vbio->vbio_flags = flags;
686 
687 	return (vbio);
688 }
689 
690 static void vbio_completion(struct bio *bio);
691 
692 static int
vbio_add_page(vbio_t * vbio,struct page * page,uint_t size,uint_t offset)693 vbio_add_page(vbio_t *vbio, struct page *page, uint_t size, uint_t offset)
694 {
695 	struct bio *bio = vbio->vbio_bio;
696 	uint_t ssize;
697 
698 	while (size > 0) {
699 		if (bio == NULL) {
700 			/* New BIO, allocate and set up */
701 			bio = vdev_bio_alloc(vbio->vbio_bdev, GFP_NOIO,
702 			    vbio->vbio_max_segs);
703 			VERIFY(bio);
704 
705 			BIO_BI_SECTOR(bio) = vbio->vbio_offset >> 9;
706 			bio_set_op_attrs(bio,
707 			    vbio->vbio_zio->io_type == ZIO_TYPE_WRITE ?
708 			    WRITE : READ, vbio->vbio_flags);
709 
710 			if (vbio->vbio_bio) {
711 				bio_chain(vbio->vbio_bio, bio);
712 				vdev_submit_bio(vbio->vbio_bio);
713 			}
714 			vbio->vbio_bio = bio;
715 		}
716 
717 		/*
718 		 * Only load as much of the current page data as will fit in
719 		 * the space left in the BIO, respecting lbs alignment. Older
720 		 * kernels will error if we try to overfill the BIO, while
721 		 * newer ones will accept it and split the BIO. This ensures
722 		 * everything works on older kernels, and avoids an additional
723 		 * overhead on the new.
724 		 */
725 		ssize = MIN(size, (vbio->vbio_max_bytes - BIO_BI_SIZE(bio)) &
726 		    vbio->vbio_lbs_mask);
727 		if (ssize > 0 &&
728 		    bio_add_page(bio, page, ssize, offset) == ssize) {
729 			/* Accepted, adjust and load any remaining. */
730 			size -= ssize;
731 			offset += ssize;
732 			continue;
733 		}
734 
735 		/* No room, set up for a new BIO and loop */
736 		vbio->vbio_offset += BIO_BI_SIZE(bio);
737 
738 		/* Signal new BIO allocation wanted */
739 		bio = NULL;
740 	}
741 
742 	return (0);
743 }
744 
745 /* Iterator callback to submit ABD pages to the vbio. */
746 static int
vbio_fill_cb(struct page * page,size_t off,size_t len,void * priv)747 vbio_fill_cb(struct page *page, size_t off, size_t len, void *priv)
748 {
749 	vbio_t *vbio = priv;
750 	return (vbio_add_page(vbio, page, len, off));
751 }
752 
753 /* Create some BIOs, fill them with data and submit them */
754 static void
vbio_submit(vbio_t * vbio,abd_t * abd,uint64_t size)755 vbio_submit(vbio_t *vbio, abd_t *abd, uint64_t size)
756 {
757 	/*
758 	 * We plug so we can submit the BIOs as we go and only unplug them when
759 	 * they are fully created and submitted. This is important; if we don't
760 	 * plug, then the kernel may start executing earlier BIOs while we're
761 	 * still creating and executing later ones, and if the device goes
762 	 * away while that's happening, older kernels can get confused and
763 	 * trample memory.
764 	 */
765 	struct blk_plug plug;
766 	blk_start_plug(&plug);
767 
768 	(void) abd_iterate_page_func(abd, 0, size, vbio_fill_cb, vbio);
769 	ASSERT(vbio->vbio_bio);
770 
771 	vbio->vbio_bio->bi_end_io = vbio_completion;
772 	vbio->vbio_bio->bi_private = vbio;
773 
774 	/*
775 	 * Once submitted, vbio_bio now owns vbio (through bi_private) and we
776 	 * can't touch it again. The bio may complete and vbio_completion() be
777 	 * called and free the vbio before this task is run again, so we must
778 	 * consider it invalid from this point.
779 	 */
780 	vdev_submit_bio(vbio->vbio_bio);
781 
782 	blk_finish_plug(&plug);
783 }
784 
785 /* IO completion callback */
786 static void
vbio_completion(struct bio * bio)787 vbio_completion(struct bio *bio)
788 {
789 	vbio_t *vbio = bio->bi_private;
790 	zio_t *zio = vbio->vbio_zio;
791 
792 	ASSERT(zio);
793 
794 	/* Capture and log any errors */
795 	zio->io_error = bi_status_to_errno(bio->bi_status);
796 	ASSERT3U(zio->io_error, >=, 0);
797 
798 	if (zio->io_error)
799 		vdev_disk_error(zio);
800 
801 	/* Return the BIO to the kernel */
802 	bio_put(bio);
803 
804 	/*
805 	 * We're likely in an interrupt context so we can't do ABD/memory work
806 	 * here; instead we stash vbio on the zio and take care of it in the
807 	 * done callback.
808 	 */
809 	ASSERT3P(zio->io_bio, ==, NULL);
810 	zio->io_bio = vbio;
811 
812 	zio_delay_interrupt(zio);
813 }
814 
815 /*
816  * Iterator callback to count ABD pages and check their size & alignment.
817  *
818  * On Linux, each BIO segment can take a page pointer, and an offset+length of
819  * the data within that page. A page can be arbitrarily large ("compound"
820  * pages) but we still have to ensure the data portion is correctly sized and
821  * aligned to the logical block size, to ensure that if the kernel wants to
822  * split the BIO, the two halves will still be properly aligned.
823  *
824  * NOTE: if you change this function, change the copy in
825  * tests/zfs-tests/tests/functional/vdev_disk/page_alignment.c, and add test
826  * data there to validate the change you're making.
827  */
828 typedef struct {
829 	size_t	blocksize;
830 	int	seen_first;
831 	int	seen_last;
832 } vdev_disk_check_alignment_t;
833 
834 static int
vdev_disk_check_alignment_cb(struct page * page,size_t off,size_t len,void * priv)835 vdev_disk_check_alignment_cb(struct page *page, size_t off, size_t len,
836     void *priv)
837 {
838 	(void) page;
839 	vdev_disk_check_alignment_t *s = priv;
840 
841 	/*
842 	 * The cardinal rule: a single on-disk block must never cross an
843 	 * physical (order-0) page boundary, as the kernel expects to be able
844 	 * to split at both LBS and page boundaries.
845 	 *
846 	 * This implies various alignment rules for the blocks in this
847 	 * (possibly compound) page, which we can check for.
848 	 */
849 
850 	/*
851 	 * If the previous page did not end on a page boundary, then we
852 	 * can't proceed without creating a hole.
853 	 */
854 	if (s->seen_last)
855 		return (1);
856 
857 	/* This page must contain only whole LBS-sized blocks. */
858 	if (!IS_P2ALIGNED(len, s->blocksize))
859 		return (1);
860 
861 	/*
862 	 * If this is not the first page in the ABD, then the data must start
863 	 * on a page-aligned boundary (so the kernel can split on page
864 	 * boundaries without having to deal with a hole). If it is, then
865 	 * it can start on LBS-alignment.
866 	 */
867 	if (s->seen_first) {
868 		if (!IS_P2ALIGNED(off, PAGESIZE))
869 			return (1);
870 	} else {
871 		if (!IS_P2ALIGNED(off, s->blocksize))
872 			return (1);
873 		s->seen_first = 1;
874 	}
875 
876 	/*
877 	 * If this data does not end on a page-aligned boundary, then this
878 	 * must be the last page in the ABD, for the same reason.
879 	 */
880 	s->seen_last = !IS_P2ALIGNED(off+len, PAGESIZE);
881 
882 	return (0);
883 }
884 
885 /*
886  * Check if we can submit the pages in this ABD to the kernel as-is. Returns
887  * the number of pages, or 0 if it can't be submitted like this.
888  */
889 static boolean_t
vdev_disk_check_alignment(abd_t * abd,uint64_t size,struct block_device * bdev)890 vdev_disk_check_alignment(abd_t *abd, uint64_t size, struct block_device *bdev)
891 {
892 	vdev_disk_check_alignment_t s = {
893 	    .blocksize = bdev_logical_block_size(bdev),
894 	};
895 
896 	if (abd_iterate_page_func(abd, 0, size,
897 	    vdev_disk_check_alignment_cb, &s))
898 		return (B_FALSE);
899 
900 	return (B_TRUE);
901 }
902 
903 static int
vdev_disk_io_rw(zio_t * zio)904 vdev_disk_io_rw(zio_t *zio)
905 {
906 	vdev_t *v = zio->io_vd;
907 	vdev_disk_t *vd = v->vdev_tsd;
908 	struct block_device *bdev = BDH_BDEV(vd->vd_bdh);
909 	int flags = 0;
910 
911 	/*
912 	 * Accessing outside the block device is never allowed.
913 	 */
914 	if (zio->io_offset + zio->io_size > bdev_capacity(bdev)) {
915 		vdev_dbgmsg(zio->io_vd,
916 		    "Illegal access %llu size %llu, device size %llu",
917 		    (u_longlong_t)zio->io_offset,
918 		    (u_longlong_t)zio->io_size,
919 		    (u_longlong_t)bdev_capacity(bdev));
920 		return (SET_ERROR(EIO));
921 	}
922 
923 	if (!(zio->io_flags & (ZIO_FLAG_IO_RETRY | ZIO_FLAG_TRYHARD)) &&
924 	    v->vdev_failfast == B_TRUE) {
925 		bio_set_flags_failfast(bdev, &flags, zfs_vdev_failfast_mask & 1,
926 		    zfs_vdev_failfast_mask & 2, zfs_vdev_failfast_mask & 4);
927 	}
928 
929 	/*
930 	 * Check alignment of the incoming ABD. If any part of it would require
931 	 * submitting a page that is not aligned to both the logical block size
932 	 * and the page size, then we take a copy into a new memory region with
933 	 * correct alignment.  This should be impossible on a 512b LBS. On
934 	 * larger blocks, this can happen at least when a small number of
935 	 * blocks (usually 1) are allocated from a shared slab, or when
936 	 * abnormally-small data regions (eg gang headers) are mixed into the
937 	 * same ABD as larger allocations (eg aggregations).
938 	 */
939 	abd_t *abd = zio->io_abd;
940 	if (!vdev_disk_check_alignment(abd, zio->io_size, bdev)) {
941 		/* Allocate a new memory region with guaranteed alignment */
942 		abd = abd_alloc_for_io(zio->io_size,
943 		    zio->io_abd->abd_flags & ABD_FLAG_META);
944 
945 		/* If we're writing copy our data into it */
946 		if (zio->io_type == ZIO_TYPE_WRITE)
947 			abd_copy(abd, zio->io_abd, zio->io_size);
948 
949 		/*
950 		 * False here would mean the new allocation has an invalid
951 		 * alignment too, which would mean that abd_alloc() is not
952 		 * guaranteeing this, or our logic in
953 		 * vdev_disk_check_alignment() is wrong. In either case,
954 		 * something in seriously wrong and its not safe to continue.
955 		 */
956 		VERIFY(vdev_disk_check_alignment(abd, zio->io_size, bdev));
957 	}
958 
959 	/* Allocate vbio, with a pointer to the borrowed ABD if necessary */
960 	vbio_t *vbio = vbio_alloc(zio, bdev, flags);
961 	if (abd != zio->io_abd)
962 		vbio->vbio_abd = abd;
963 
964 	/* Fill it with data pages and submit it to the kernel */
965 	vbio_submit(vbio, abd, zio->io_size);
966 	return (0);
967 }
968 
969 /* ========== */
970 
971 /*
972  * This is the classic, battle-tested BIO submission code. Until we're totally
973  * sure that the new code is safe and correct in all cases, this will remain
974  * available and can be enabled by setting zfs_vdev_disk_classic=1 at module
975  * load time.
976  *
977  * These functions have been renamed to vdev_classic_* to make it clear what
978  * they belong to, but their implementations are unchanged.
979  */
980 
981 /*
982  * Virtual device vector for disks.
983  */
984 typedef struct dio_request {
985 	zio_t			*dr_zio;	/* Parent ZIO */
986 	atomic_t		dr_ref;		/* References */
987 	int			dr_error;	/* Bio error */
988 	int			dr_bio_count;	/* Count of bio's */
989 	struct bio		*dr_bio[];	/* Attached bio's */
990 } dio_request_t;
991 
992 static dio_request_t *
vdev_classic_dio_alloc(int bio_count)993 vdev_classic_dio_alloc(int bio_count)
994 {
995 	dio_request_t *dr = kmem_zalloc(sizeof (dio_request_t) +
996 	    sizeof (struct bio *) * bio_count, KM_SLEEP);
997 	atomic_set(&dr->dr_ref, 0);
998 	dr->dr_bio_count = bio_count;
999 	dr->dr_error = 0;
1000 
1001 	for (int i = 0; i < dr->dr_bio_count; i++)
1002 		dr->dr_bio[i] = NULL;
1003 
1004 	return (dr);
1005 }
1006 
1007 static void
vdev_classic_dio_free(dio_request_t * dr)1008 vdev_classic_dio_free(dio_request_t *dr)
1009 {
1010 	int i;
1011 
1012 	for (i = 0; i < dr->dr_bio_count; i++)
1013 		if (dr->dr_bio[i])
1014 			bio_put(dr->dr_bio[i]);
1015 
1016 	kmem_free(dr, sizeof (dio_request_t) +
1017 	    sizeof (struct bio *) * dr->dr_bio_count);
1018 }
1019 
1020 static void
vdev_classic_dio_get(dio_request_t * dr)1021 vdev_classic_dio_get(dio_request_t *dr)
1022 {
1023 	atomic_inc(&dr->dr_ref);
1024 }
1025 
1026 static void
vdev_classic_dio_put(dio_request_t * dr)1027 vdev_classic_dio_put(dio_request_t *dr)
1028 {
1029 	int rc = atomic_dec_return(&dr->dr_ref);
1030 
1031 	/*
1032 	 * Free the dio_request when the last reference is dropped and
1033 	 * ensure zio_interpret is called only once with the correct zio
1034 	 */
1035 	if (rc == 0) {
1036 		zio_t *zio = dr->dr_zio;
1037 		int error = dr->dr_error;
1038 
1039 		vdev_classic_dio_free(dr);
1040 
1041 		if (zio) {
1042 			zio->io_error = error;
1043 			ASSERT3S(zio->io_error, >=, 0);
1044 			if (zio->io_error)
1045 				vdev_disk_error(zio);
1046 
1047 			zio_delay_interrupt(zio);
1048 		}
1049 	}
1050 }
1051 
1052 static void
vdev_classic_physio_completion(struct bio * bio)1053 vdev_classic_physio_completion(struct bio *bio)
1054 {
1055 	dio_request_t *dr = bio->bi_private;
1056 
1057 	if (dr->dr_error == 0) {
1058 		dr->dr_error = bi_status_to_errno(bio->bi_status);
1059 	}
1060 
1061 	/* Drop reference acquired by vdev_classic_physio */
1062 	vdev_classic_dio_put(dr);
1063 }
1064 
1065 static inline unsigned int
vdev_classic_bio_max_segs(zio_t * zio,int bio_size,uint64_t abd_offset)1066 vdev_classic_bio_max_segs(zio_t *zio, int bio_size, uint64_t abd_offset)
1067 {
1068 	unsigned long nr_segs = abd_nr_pages_off(zio->io_abd,
1069 	    bio_size, abd_offset);
1070 
1071 #ifdef HAVE_BIO_MAX_SEGS
1072 	return (bio_max_segs(nr_segs));
1073 #else
1074 	return (MIN(nr_segs, BIO_MAX_PAGES));
1075 #endif
1076 }
1077 
1078 static int
vdev_classic_physio(zio_t * zio)1079 vdev_classic_physio(zio_t *zio)
1080 {
1081 	vdev_t *v = zio->io_vd;
1082 	vdev_disk_t *vd = v->vdev_tsd;
1083 	struct block_device *bdev = BDH_BDEV(vd->vd_bdh);
1084 	size_t io_size = zio->io_size;
1085 	uint64_t io_offset = zio->io_offset;
1086 	int rw = zio->io_type == ZIO_TYPE_READ ? READ : WRITE;
1087 	int flags = 0;
1088 
1089 	dio_request_t *dr;
1090 	uint64_t abd_offset;
1091 	uint64_t bio_offset;
1092 	int bio_size;
1093 	int bio_count = 16;
1094 	int error = 0;
1095 	struct blk_plug plug;
1096 	unsigned short nr_vecs;
1097 
1098 	/*
1099 	 * Accessing outside the block device is never allowed.
1100 	 */
1101 	if (io_offset + io_size > bdev_capacity(bdev)) {
1102 		vdev_dbgmsg(zio->io_vd,
1103 		    "Illegal access %llu size %llu, device size %llu",
1104 		    (u_longlong_t)io_offset,
1105 		    (u_longlong_t)io_size,
1106 		    (u_longlong_t)bdev_capacity(bdev));
1107 		return (SET_ERROR(EIO));
1108 	}
1109 
1110 retry:
1111 	dr = vdev_classic_dio_alloc(bio_count);
1112 
1113 	if (!(zio->io_flags & (ZIO_FLAG_IO_RETRY | ZIO_FLAG_TRYHARD)) &&
1114 	    zio->io_vd->vdev_failfast == B_TRUE) {
1115 		bio_set_flags_failfast(bdev, &flags, zfs_vdev_failfast_mask & 1,
1116 		    zfs_vdev_failfast_mask & 2, zfs_vdev_failfast_mask & 4);
1117 	}
1118 
1119 	dr->dr_zio = zio;
1120 
1121 	/*
1122 	 * Since bio's can have up to BIO_MAX_PAGES=256 iovec's, each of which
1123 	 * is at least 512 bytes and at most PAGESIZE (typically 4K), one bio
1124 	 * can cover at least 128KB and at most 1MB.  When the required number
1125 	 * of iovec's exceeds this, we are forced to break the IO in multiple
1126 	 * bio's and wait for them all to complete.  This is likely if the
1127 	 * recordsize property is increased beyond 1MB.  The default
1128 	 * bio_count=16 should typically accommodate the maximum-size zio of
1129 	 * 16MB.
1130 	 */
1131 
1132 	abd_offset = 0;
1133 	bio_offset = io_offset;
1134 	bio_size = io_size;
1135 	for (int i = 0; i <= dr->dr_bio_count; i++) {
1136 
1137 		/* Finished constructing bio's for given buffer */
1138 		if (bio_size <= 0)
1139 			break;
1140 
1141 		/*
1142 		 * If additional bio's are required, we have to retry, but
1143 		 * this should be rare - see the comment above.
1144 		 */
1145 		if (dr->dr_bio_count == i) {
1146 			vdev_classic_dio_free(dr);
1147 			bio_count *= 2;
1148 			goto retry;
1149 		}
1150 
1151 		nr_vecs = vdev_classic_bio_max_segs(zio, bio_size, abd_offset);
1152 		dr->dr_bio[i] = vdev_bio_alloc(bdev, GFP_NOIO, nr_vecs);
1153 		if (unlikely(dr->dr_bio[i] == NULL)) {
1154 			vdev_classic_dio_free(dr);
1155 			return (SET_ERROR(ENOMEM));
1156 		}
1157 
1158 		/* Matching put called by vdev_classic_physio_completion */
1159 		vdev_classic_dio_get(dr);
1160 
1161 		BIO_BI_SECTOR(dr->dr_bio[i]) = bio_offset >> 9;
1162 		dr->dr_bio[i]->bi_end_io = vdev_classic_physio_completion;
1163 		dr->dr_bio[i]->bi_private = dr;
1164 		bio_set_op_attrs(dr->dr_bio[i], rw, flags);
1165 
1166 		/* Remaining size is returned to become the new size */
1167 		bio_size = abd_bio_map_off(dr->dr_bio[i], zio->io_abd,
1168 		    bio_size, abd_offset);
1169 
1170 		/* Advance in buffer and construct another bio if needed */
1171 		abd_offset += BIO_BI_SIZE(dr->dr_bio[i]);
1172 		bio_offset += BIO_BI_SIZE(dr->dr_bio[i]);
1173 	}
1174 
1175 	/* Extra reference to protect dio_request during vdev_submit_bio */
1176 	vdev_classic_dio_get(dr);
1177 
1178 	if (dr->dr_bio_count > 1)
1179 		blk_start_plug(&plug);
1180 
1181 	/* Submit all bio's associated with this dio */
1182 	for (int i = 0; i < dr->dr_bio_count; i++) {
1183 		if (dr->dr_bio[i])
1184 			vdev_submit_bio(dr->dr_bio[i]);
1185 	}
1186 
1187 	if (dr->dr_bio_count > 1)
1188 		blk_finish_plug(&plug);
1189 
1190 	vdev_classic_dio_put(dr);
1191 
1192 	return (error);
1193 }
1194 
1195 /* ========== */
1196 
1197 static void
vdev_disk_io_flush_completion(struct bio * bio)1198 vdev_disk_io_flush_completion(struct bio *bio)
1199 {
1200 	zio_t *zio = bio->bi_private;
1201 	zio->io_error = bi_status_to_errno(bio->bi_status);
1202 	if (zio->io_error == EOPNOTSUPP || zio->io_error == ENOTTY)
1203 		zio->io_error = SET_ERROR(ENOTSUP);
1204 
1205 	bio_put(bio);
1206 	ASSERT3S(zio->io_error, >=, 0);
1207 	if (zio->io_error)
1208 		vdev_disk_error(zio);
1209 	zio_interrupt(zio);
1210 }
1211 
1212 static int
vdev_disk_io_flush(struct block_device * bdev,zio_t * zio)1213 vdev_disk_io_flush(struct block_device *bdev, zio_t *zio)
1214 {
1215 	struct request_queue *q;
1216 	struct bio *bio;
1217 
1218 	q = bdev_get_queue(bdev);
1219 	if (!q)
1220 		return (SET_ERROR(ENXIO));
1221 
1222 	bio = vdev_bio_alloc(bdev, GFP_NOIO, 0);
1223 	if (unlikely(bio == NULL))
1224 		return (SET_ERROR(ENOMEM));
1225 
1226 	bio->bi_end_io = vdev_disk_io_flush_completion;
1227 	bio->bi_private = zio;
1228 	bio_set_flush(bio);
1229 	vdev_submit_bio(bio);
1230 	invalidate_bdev(bdev);
1231 
1232 	return (0);
1233 }
1234 
1235 static void
vdev_disk_discard_end_io(struct bio * bio)1236 vdev_disk_discard_end_io(struct bio *bio)
1237 {
1238 	zio_t *zio = bio->bi_private;
1239 	zio->io_error = bi_status_to_errno(bio->bi_status);
1240 
1241 	bio_put(bio);
1242 	if (zio->io_error)
1243 		vdev_disk_error(zio);
1244 	zio_interrupt(zio);
1245 }
1246 
1247 /*
1248  * Wrappers for the different secure erase and discard APIs. We use async
1249  * when available; in this case, *biop is set to the last bio in the chain.
1250  */
1251 static int
vdev_bdev_issue_secure_erase(zfs_bdev_handle_t * bdh,sector_t sector,sector_t nsect,struct bio ** biop)1252 vdev_bdev_issue_secure_erase(zfs_bdev_handle_t *bdh, sector_t sector,
1253     sector_t nsect, struct bio **biop)
1254 {
1255 	*biop = NULL;
1256 	int error;
1257 
1258 #if defined(HAVE_BLKDEV_ISSUE_SECURE_ERASE)
1259 	error = blkdev_issue_secure_erase(BDH_BDEV(bdh),
1260 	    sector, nsect, GFP_NOFS);
1261 #elif defined(HAVE_BLKDEV_ISSUE_DISCARD_ASYNC_FLAGS)
1262 	error = __blkdev_issue_discard(BDH_BDEV(bdh),
1263 	    sector, nsect, GFP_NOFS, BLKDEV_DISCARD_SECURE, biop);
1264 #elif defined(HAVE_BLKDEV_ISSUE_DISCARD_FLAGS)
1265 	error = blkdev_issue_discard(BDH_BDEV(bdh),
1266 	    sector, nsect, GFP_NOFS, BLKDEV_DISCARD_SECURE);
1267 #else
1268 #error "unsupported kernel"
1269 #endif
1270 
1271 	return (error);
1272 }
1273 
1274 static int
vdev_bdev_issue_discard(zfs_bdev_handle_t * bdh,sector_t sector,sector_t nsect,struct bio ** biop)1275 vdev_bdev_issue_discard(zfs_bdev_handle_t *bdh, sector_t sector,
1276     sector_t nsect, struct bio **biop)
1277 {
1278 	*biop = NULL;
1279 	int error;
1280 
1281 #if defined(HAVE_BLKDEV_ISSUE_DISCARD_ASYNC_FLAGS)
1282 	error = __blkdev_issue_discard(BDH_BDEV(bdh),
1283 	    sector, nsect, GFP_NOFS, 0, biop);
1284 #elif defined(HAVE_BLKDEV_ISSUE_DISCARD_ASYNC_NOFLAGS)
1285 	error = __blkdev_issue_discard(BDH_BDEV(bdh),
1286 	    sector, nsect, GFP_NOFS, biop);
1287 #elif defined(HAVE_BLKDEV_ISSUE_DISCARD_FLAGS)
1288 	error = blkdev_issue_discard(BDH_BDEV(bdh),
1289 	    sector, nsect, GFP_NOFS, 0);
1290 #elif defined(HAVE_BLKDEV_ISSUE_DISCARD_NOFLAGS)
1291 	error = blkdev_issue_discard(BDH_BDEV(bdh),
1292 	    sector, nsect, GFP_NOFS);
1293 #else
1294 #error "unsupported kernel"
1295 #endif
1296 
1297 	return (error);
1298 }
1299 
1300 /*
1301  * Entry point for TRIM ops. This calls the right wrapper for secure erase or
1302  * discard, and then does the appropriate finishing work for error vs success
1303  * and async vs sync.
1304  */
1305 static int
vdev_disk_io_trim(zio_t * zio)1306 vdev_disk_io_trim(zio_t *zio)
1307 {
1308 	int error;
1309 	struct bio *bio;
1310 
1311 	zfs_bdev_handle_t *bdh = ((vdev_disk_t *)zio->io_vd->vdev_tsd)->vd_bdh;
1312 	sector_t sector = zio->io_offset >> 9;
1313 	sector_t nsects = zio->io_size >> 9;
1314 
1315 	if (zio->io_trim_flags & ZIO_TRIM_SECURE)
1316 		error = vdev_bdev_issue_secure_erase(bdh, sector, nsects, &bio);
1317 	else
1318 		error = vdev_bdev_issue_discard(bdh, sector, nsects, &bio);
1319 
1320 	if (error != 0)
1321 		return (SET_ERROR(-error));
1322 
1323 	if (bio == NULL) {
1324 		/*
1325 		 * This was a synchronous op that completed successfully, so
1326 		 * return it to ZFS immediately.
1327 		 */
1328 		zio_interrupt(zio);
1329 	} else {
1330 		/*
1331 		 * This was an asynchronous op; set up completion callback and
1332 		 * issue it.
1333 		 */
1334 		bio->bi_private = zio;
1335 		bio->bi_end_io = vdev_disk_discard_end_io;
1336 		vdev_submit_bio(bio);
1337 	}
1338 
1339 	return (0);
1340 }
1341 
1342 int (*vdev_disk_io_rw_fn)(zio_t *zio) = NULL;
1343 
1344 static void
vdev_disk_io_start(zio_t * zio)1345 vdev_disk_io_start(zio_t *zio)
1346 {
1347 	vdev_t *v = zio->io_vd;
1348 	vdev_disk_t *vd = v->vdev_tsd;
1349 	int error;
1350 
1351 	/*
1352 	 * If the vdev is closed, it's likely in the REMOVED or FAULTED state.
1353 	 * Nothing to be done here but return failure.
1354 	 */
1355 	if (vd == NULL) {
1356 		zio->io_error = ENXIO;
1357 		zio_interrupt(zio);
1358 		return;
1359 	}
1360 
1361 	rw_enter(&vd->vd_lock, RW_READER);
1362 
1363 	/*
1364 	 * If the vdev is closed, it's likely due to a failed reopen and is
1365 	 * in the UNAVAIL state.  Nothing to be done here but return failure.
1366 	 */
1367 	if (vd->vd_bdh == NULL) {
1368 		rw_exit(&vd->vd_lock);
1369 		zio->io_error = ENXIO;
1370 		zio_interrupt(zio);
1371 		return;
1372 	}
1373 
1374 	switch (zio->io_type) {
1375 	case ZIO_TYPE_FLUSH:
1376 
1377 		if (!vdev_readable(v)) {
1378 			/* Drive not there, can't flush */
1379 			error = SET_ERROR(ENXIO);
1380 		} else if (zfs_nocacheflush) {
1381 			/* Flushing disabled by operator, declare success */
1382 			error = 0;
1383 		} else if (v->vdev_nowritecache) {
1384 			/* This vdev not capable of flushing */
1385 			error = SET_ERROR(ENOTSUP);
1386 		} else {
1387 			/*
1388 			 * Issue the flush. If successful, the response will
1389 			 * be handled in the completion callback, so we're done.
1390 			 */
1391 			error = vdev_disk_io_flush(BDH_BDEV(vd->vd_bdh), zio);
1392 			if (error == 0) {
1393 				rw_exit(&vd->vd_lock);
1394 				return;
1395 			}
1396 		}
1397 
1398 		/* Couldn't issue the flush, so set the error and return it */
1399 		rw_exit(&vd->vd_lock);
1400 		zio->io_error = error;
1401 		zio_execute(zio);
1402 		return;
1403 
1404 	case ZIO_TYPE_TRIM:
1405 		error = vdev_disk_io_trim(zio);
1406 		rw_exit(&vd->vd_lock);
1407 		if (error) {
1408 			zio->io_error = error;
1409 			zio_execute(zio);
1410 		}
1411 		return;
1412 
1413 	case ZIO_TYPE_READ:
1414 	case ZIO_TYPE_WRITE:
1415 		zio->io_target_timestamp = zio_handle_io_delay(zio);
1416 		error = vdev_disk_io_rw_fn(zio);
1417 		rw_exit(&vd->vd_lock);
1418 		if (error) {
1419 			zio->io_error = error;
1420 			zio_interrupt(zio);
1421 		}
1422 		return;
1423 
1424 	default:
1425 		/*
1426 		 * Getting here means our parent vdev has made a very strange
1427 		 * request of us, and shouldn't happen. Assert here to force a
1428 		 * crash in dev builds, but in production return the IO
1429 		 * unhandled. The pool will likely suspend anyway but that's
1430 		 * nicer than crashing the kernel.
1431 		 */
1432 		ASSERT3S(zio->io_type, ==, -1);
1433 
1434 		rw_exit(&vd->vd_lock);
1435 		zio->io_error = SET_ERROR(ENOTSUP);
1436 		zio_interrupt(zio);
1437 		return;
1438 	}
1439 
1440 	__builtin_unreachable();
1441 }
1442 
1443 static void
vdev_disk_io_done(zio_t * zio)1444 vdev_disk_io_done(zio_t *zio)
1445 {
1446 	/* If this was a read or write, we need to clean up the vbio */
1447 	if (zio->io_bio != NULL) {
1448 		vbio_t *vbio = zio->io_bio;
1449 		zio->io_bio = NULL;
1450 
1451 		/*
1452 		 * If we copied the ABD before issuing it, clean up and return
1453 		 * the copy to the ADB, with changes if appropriate.
1454 		 */
1455 		if (vbio->vbio_abd != NULL) {
1456 			if (zio->io_type == ZIO_TYPE_READ)
1457 				abd_copy(zio->io_abd, vbio->vbio_abd,
1458 				    zio->io_size);
1459 
1460 			abd_free(vbio->vbio_abd);
1461 			vbio->vbio_abd = NULL;
1462 		}
1463 
1464 		/* Final cleanup */
1465 		kmem_free(vbio, sizeof (vbio_t));
1466 	}
1467 
1468 	/*
1469 	 * If the device returned EIO, we revalidate the media.  If it is
1470 	 * determined the media has changed this triggers the asynchronous
1471 	 * removal of the device from the configuration.
1472 	 */
1473 	if (zio->io_error == EIO) {
1474 		vdev_t *v = zio->io_vd;
1475 		vdev_disk_t *vd = v->vdev_tsd;
1476 
1477 		if (!zfs_check_disk_status(BDH_BDEV(vd->vd_bdh))) {
1478 			invalidate_bdev(BDH_BDEV(vd->vd_bdh));
1479 			v->vdev_remove_wanted = B_TRUE;
1480 			spa_async_request(zio->io_spa, SPA_ASYNC_REMOVE);
1481 		}
1482 	}
1483 }
1484 
1485 static void
vdev_disk_hold(vdev_t * vd)1486 vdev_disk_hold(vdev_t *vd)
1487 {
1488 	ASSERT(spa_config_held(vd->vdev_spa, SCL_STATE, RW_WRITER));
1489 
1490 	/* We must have a pathname, and it must be absolute. */
1491 	if (vd->vdev_path == NULL || vd->vdev_path[0] != '/')
1492 		return;
1493 
1494 	/*
1495 	 * Only prefetch path and devid info if the device has
1496 	 * never been opened.
1497 	 */
1498 	if (vd->vdev_tsd != NULL)
1499 		return;
1500 
1501 }
1502 
1503 static void
vdev_disk_rele(vdev_t * vd)1504 vdev_disk_rele(vdev_t *vd)
1505 {
1506 	ASSERT(spa_config_held(vd->vdev_spa, SCL_STATE, RW_WRITER));
1507 
1508 	/* XXX: Implement me as a vnode rele for the device */
1509 }
1510 
1511 /*
1512  * BIO submission method. See comment above about vdev_classic.
1513  * Set zfs_vdev_disk_classic=0 for new, =1 for classic
1514  */
1515 static uint_t zfs_vdev_disk_classic = 0;	/* default new */
1516 
1517 /* Set submission function from module parameter */
1518 static int
vdev_disk_param_set_classic(const char * buf,zfs_kernel_param_t * kp)1519 vdev_disk_param_set_classic(const char *buf, zfs_kernel_param_t *kp)
1520 {
1521 	int err = param_set_uint(buf, kp);
1522 	if (err < 0)
1523 		return (SET_ERROR(err));
1524 
1525 	vdev_disk_io_rw_fn =
1526 	    zfs_vdev_disk_classic ? vdev_classic_physio : vdev_disk_io_rw;
1527 
1528 	printk(KERN_INFO "ZFS: forcing %s BIO submission\n",
1529 	    zfs_vdev_disk_classic ? "classic" : "new");
1530 
1531 	return (0);
1532 }
1533 
1534 /*
1535  * At first use vdev use, set the submission function from the default value if
1536  * it hasn't been set already.
1537  */
1538 static int
vdev_disk_init(spa_t * spa,nvlist_t * nv,void ** tsd)1539 vdev_disk_init(spa_t *spa, nvlist_t *nv, void **tsd)
1540 {
1541 	(void) spa;
1542 	(void) nv;
1543 	(void) tsd;
1544 
1545 	if (vdev_disk_io_rw_fn == NULL)
1546 		vdev_disk_io_rw_fn = zfs_vdev_disk_classic ?
1547 		    vdev_classic_physio : vdev_disk_io_rw;
1548 
1549 	return (0);
1550 }
1551 
1552 vdev_ops_t vdev_disk_ops = {
1553 	.vdev_op_init = vdev_disk_init,
1554 	.vdev_op_fini = NULL,
1555 	.vdev_op_open = vdev_disk_open,
1556 	.vdev_op_close = vdev_disk_close,
1557 	.vdev_op_asize = vdev_default_asize,
1558 	.vdev_op_min_asize = vdev_default_min_asize,
1559 	.vdev_op_min_alloc = NULL,
1560 	.vdev_op_io_start = vdev_disk_io_start,
1561 	.vdev_op_io_done = vdev_disk_io_done,
1562 	.vdev_op_state_change = NULL,
1563 	.vdev_op_need_resilver = NULL,
1564 	.vdev_op_hold = vdev_disk_hold,
1565 	.vdev_op_rele = vdev_disk_rele,
1566 	.vdev_op_remap = NULL,
1567 	.vdev_op_xlate = vdev_default_xlate,
1568 	.vdev_op_rebuild_asize = NULL,
1569 	.vdev_op_metaslab_init = NULL,
1570 	.vdev_op_config_generate = NULL,
1571 	.vdev_op_nparity = NULL,
1572 	.vdev_op_ndisks = NULL,
1573 	.vdev_op_type = VDEV_TYPE_DISK,		/* name of this vdev type */
1574 	.vdev_op_leaf = B_TRUE,			/* leaf vdev */
1575 	.vdev_op_kobj_evt_post = vdev_disk_kobj_evt_post
1576 };
1577 
1578 /*
1579  * The zfs_vdev_scheduler module option has been deprecated. Setting this
1580  * value no longer has any effect.  It has not yet been entirely removed
1581  * to allow the module to be loaded if this option is specified in the
1582  * /etc/modprobe.d/zfs.conf file.  The following warning will be logged.
1583  */
1584 static int
param_set_vdev_scheduler(const char * val,zfs_kernel_param_t * kp)1585 param_set_vdev_scheduler(const char *val, zfs_kernel_param_t *kp)
1586 {
1587 	int error = param_set_charp(val, kp);
1588 	if (error == 0) {
1589 		printk(KERN_INFO "The 'zfs_vdev_scheduler' module option "
1590 		    "is not supported.\n");
1591 	}
1592 
1593 	return (error);
1594 }
1595 
1596 static const char *zfs_vdev_scheduler = "unused";
1597 module_param_call(zfs_vdev_scheduler, param_set_vdev_scheduler,
1598     param_get_charp, &zfs_vdev_scheduler, 0644);
1599 MODULE_PARM_DESC(zfs_vdev_scheduler, "I/O scheduler");
1600 
1601 int
param_set_min_auto_ashift(const char * buf,zfs_kernel_param_t * kp)1602 param_set_min_auto_ashift(const char *buf, zfs_kernel_param_t *kp)
1603 {
1604 	uint_t val;
1605 	int error;
1606 
1607 	error = kstrtouint(buf, 0, &val);
1608 	if (error < 0)
1609 		return (SET_ERROR(error));
1610 
1611 	if (val < ASHIFT_MIN || val > zfs_vdev_max_auto_ashift)
1612 		return (SET_ERROR(-EINVAL));
1613 
1614 	error = param_set_uint(buf, kp);
1615 	if (error < 0)
1616 		return (SET_ERROR(error));
1617 
1618 	return (0);
1619 }
1620 
1621 int
param_set_max_auto_ashift(const char * buf,zfs_kernel_param_t * kp)1622 param_set_max_auto_ashift(const char *buf, zfs_kernel_param_t *kp)
1623 {
1624 	uint_t val;
1625 	int error;
1626 
1627 	error = kstrtouint(buf, 0, &val);
1628 	if (error < 0)
1629 		return (SET_ERROR(error));
1630 
1631 	if (val > ASHIFT_MAX || val < zfs_vdev_min_auto_ashift)
1632 		return (SET_ERROR(-EINVAL));
1633 
1634 	error = param_set_uint(buf, kp);
1635 	if (error < 0)
1636 		return (SET_ERROR(error));
1637 
1638 	return (0);
1639 }
1640 
1641 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, open_timeout_ms, UINT, ZMOD_RW,
1642 	"Timeout before determining that a device is missing");
1643 
1644 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, failfast_mask, UINT, ZMOD_RW,
1645 	"Defines failfast mask: 1 - device, 2 - transport, 4 - driver");
1646 
1647 ZFS_MODULE_PARAM(zfs_vdev_disk, zfs_vdev_disk_, max_segs, UINT, ZMOD_RW,
1648 	"Maximum number of data segments to add to an IO request (min 4)");
1649 
1650 ZFS_MODULE_PARAM_CALL(zfs_vdev_disk, zfs_vdev_disk_, classic,
1651     vdev_disk_param_set_classic, param_get_uint, ZMOD_RD,
1652 	"Use classic BIO submission method");
1653