vdev_queue.c revision 270312
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * 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.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
22 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23 * Use is subject to license terms.
24 */
25
26/*
27 * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
28 */
29
30#include <sys/zfs_context.h>
31#include <sys/vdev_impl.h>
32#include <sys/spa_impl.h>
33#include <sys/zio.h>
34#include <sys/avl.h>
35#include <sys/dsl_pool.h>
36
37/*
38 * ZFS I/O Scheduler
39 * ---------------
40 *
41 * ZFS issues I/O operations to leaf vdevs to satisfy and complete zios.  The
42 * I/O scheduler determines when and in what order those operations are
43 * issued.  The I/O scheduler divides operations into six I/O classes
44 * prioritized in the following order: sync read, sync write, async read,
45 * async write, scrub/resilver and trim.  Each queue defines the minimum and
46 * maximum number of concurrent operations that may be issued to the device.
47 * In addition, the device has an aggregate maximum. Note that the sum of the
48 * per-queue minimums must not exceed the aggregate maximum, and if the
49 * aggregate maximum is equal to or greater than the sum of the per-queue
50 * maximums, the per-queue minimum has no effect.
51 *
52 * For many physical devices, throughput increases with the number of
53 * concurrent operations, but latency typically suffers. Further, physical
54 * devices typically have a limit at which more concurrent operations have no
55 * effect on throughput or can actually cause it to decrease.
56 *
57 * The scheduler selects the next operation to issue by first looking for an
58 * I/O class whose minimum has not been satisfied. Once all are satisfied and
59 * the aggregate maximum has not been hit, the scheduler looks for classes
60 * whose maximum has not been satisfied. Iteration through the I/O classes is
61 * done in the order specified above. No further operations are issued if the
62 * aggregate maximum number of concurrent operations has been hit or if there
63 * are no operations queued for an I/O class that has not hit its maximum.
64 * Every time an I/O is queued or an operation completes, the I/O scheduler
65 * looks for new operations to issue.
66 *
67 * All I/O classes have a fixed maximum number of outstanding operations
68 * except for the async write class. Asynchronous writes represent the data
69 * that is committed to stable storage during the syncing stage for
70 * transaction groups (see txg.c). Transaction groups enter the syncing state
71 * periodically so the number of queued async writes will quickly burst up and
72 * then bleed down to zero. Rather than servicing them as quickly as possible,
73 * the I/O scheduler changes the maximum number of active async write I/Os
74 * according to the amount of dirty data in the pool (see dsl_pool.c). Since
75 * both throughput and latency typically increase with the number of
76 * concurrent operations issued to physical devices, reducing the burstiness
77 * in the number of concurrent operations also stabilizes the response time of
78 * operations from other -- and in particular synchronous -- queues. In broad
79 * strokes, the I/O scheduler will issue more concurrent operations from the
80 * async write queue as there's more dirty data in the pool.
81 *
82 * Async Writes
83 *
84 * The number of concurrent operations issued for the async write I/O class
85 * follows a piece-wise linear function defined by a few adjustable points.
86 *
87 *        |                   o---------| <-- zfs_vdev_async_write_max_active
88 *   ^    |                  /^         |
89 *   |    |                 / |         |
90 * active |                /  |         |
91 *  I/O   |               /   |         |
92 * count  |              /    |         |
93 *        |             /     |         |
94 *        |------------o      |         | <-- zfs_vdev_async_write_min_active
95 *       0|____________^______|_________|
96 *        0%           |      |       100% of zfs_dirty_data_max
97 *                     |      |
98 *                     |      `-- zfs_vdev_async_write_active_max_dirty_percent
99 *                     `--------- zfs_vdev_async_write_active_min_dirty_percent
100 *
101 * Until the amount of dirty data exceeds a minimum percentage of the dirty
102 * data allowed in the pool, the I/O scheduler will limit the number of
103 * concurrent operations to the minimum. As that threshold is crossed, the
104 * number of concurrent operations issued increases linearly to the maximum at
105 * the specified maximum percentage of the dirty data allowed in the pool.
106 *
107 * Ideally, the amount of dirty data on a busy pool will stay in the sloped
108 * part of the function between zfs_vdev_async_write_active_min_dirty_percent
109 * and zfs_vdev_async_write_active_max_dirty_percent. If it exceeds the
110 * maximum percentage, this indicates that the rate of incoming data is
111 * greater than the rate that the backend storage can handle. In this case, we
112 * must further throttle incoming writes (see dmu_tx_delay() for details).
113 */
114
115/*
116 * The maximum number of I/Os active to each device.  Ideally, this will be >=
117 * the sum of each queue's max_active.  It must be at least the sum of each
118 * queue's min_active.
119 */
120uint32_t zfs_vdev_max_active = 1000;
121
122/*
123 * Per-queue limits on the number of I/Os active to each device.  If the
124 * sum of the queue's max_active is < zfs_vdev_max_active, then the
125 * min_active comes into play.  We will send min_active from each queue,
126 * and then select from queues in the order defined by zio_priority_t.
127 *
128 * In general, smaller max_active's will lead to lower latency of synchronous
129 * operations.  Larger max_active's may lead to higher overall throughput,
130 * depending on underlying storage.
131 *
132 * The ratio of the queues' max_actives determines the balance of performance
133 * between reads, writes, and scrubs.  E.g., increasing
134 * zfs_vdev_scrub_max_active will cause the scrub or resilver to complete
135 * more quickly, but reads and writes to have higher latency and lower
136 * throughput.
137 */
138uint32_t zfs_vdev_sync_read_min_active = 10;
139uint32_t zfs_vdev_sync_read_max_active = 10;
140uint32_t zfs_vdev_sync_write_min_active = 10;
141uint32_t zfs_vdev_sync_write_max_active = 10;
142uint32_t zfs_vdev_async_read_min_active = 1;
143uint32_t zfs_vdev_async_read_max_active = 3;
144uint32_t zfs_vdev_async_write_min_active = 1;
145uint32_t zfs_vdev_async_write_max_active = 10;
146uint32_t zfs_vdev_scrub_min_active = 1;
147uint32_t zfs_vdev_scrub_max_active = 2;
148uint32_t zfs_vdev_trim_min_active = 1;
149/*
150 * TRIM max active is large in comparison to the other values due to the fact
151 * that TRIM IOs are coalesced at the device layer. This value is set such
152 * that a typical SSD can process the queued IOs in a single request.
153 */
154uint32_t zfs_vdev_trim_max_active = 64;
155
156
157/*
158 * When the pool has less than zfs_vdev_async_write_active_min_dirty_percent
159 * dirty data, use zfs_vdev_async_write_min_active.  When it has more than
160 * zfs_vdev_async_write_active_max_dirty_percent, use
161 * zfs_vdev_async_write_max_active. The value is linearly interpolated
162 * between min and max.
163 */
164int zfs_vdev_async_write_active_min_dirty_percent = 30;
165int zfs_vdev_async_write_active_max_dirty_percent = 60;
166
167/*
168 * To reduce IOPs, we aggregate small adjacent I/Os into one large I/O.
169 * For read I/Os, we also aggregate across small adjacency gaps; for writes
170 * we include spans of optional I/Os to aid aggregation at the disk even when
171 * they aren't able to help us aggregate at this level.
172 */
173int zfs_vdev_aggregation_limit = SPA_MAXBLOCKSIZE;
174int zfs_vdev_read_gap_limit = 32 << 10;
175int zfs_vdev_write_gap_limit = 4 << 10;
176
177#ifdef __FreeBSD__
178SYSCTL_DECL(_vfs_zfs_vdev);
179TUNABLE_INT("vfs.zfs.vdev.max_active", &zfs_vdev_max_active);
180SYSCTL_UINT(_vfs_zfs_vdev, OID_AUTO, max_active, CTLFLAG_RW,
181    &zfs_vdev_max_active, 0,
182    "The maximum number of I/Os of all types active for each device.");
183
184#define ZFS_VDEV_QUEUE_KNOB_MIN(name)					\
185TUNABLE_INT("vfs.zfs.vdev." #name "_min_active",			\
186    &zfs_vdev_ ## name ## _min_active);					\
187SYSCTL_UINT(_vfs_zfs_vdev, OID_AUTO, name ## _min_active, CTLFLAG_RW,	\
188    &zfs_vdev_ ## name ## _min_active, 0,				\
189    "Initial number of I/O requests of type " #name			\
190    " active for each device");
191
192#define ZFS_VDEV_QUEUE_KNOB_MAX(name)					\
193TUNABLE_INT("vfs.zfs.vdev." #name "_max_active",			\
194    &zfs_vdev_ ## name ## _max_active);					\
195SYSCTL_UINT(_vfs_zfs_vdev, OID_AUTO, name ## _max_active, CTLFLAG_RW,	\
196    &zfs_vdev_ ## name ## _max_active, 0,				\
197    "Maximum number of I/O requests of type " #name			\
198    " active for each device");
199
200ZFS_VDEV_QUEUE_KNOB_MIN(sync_read);
201ZFS_VDEV_QUEUE_KNOB_MAX(sync_read);
202ZFS_VDEV_QUEUE_KNOB_MIN(sync_write);
203ZFS_VDEV_QUEUE_KNOB_MAX(sync_write);
204ZFS_VDEV_QUEUE_KNOB_MIN(async_read);
205ZFS_VDEV_QUEUE_KNOB_MAX(async_read);
206ZFS_VDEV_QUEUE_KNOB_MIN(async_write);
207ZFS_VDEV_QUEUE_KNOB_MAX(async_write);
208ZFS_VDEV_QUEUE_KNOB_MIN(scrub);
209ZFS_VDEV_QUEUE_KNOB_MAX(scrub);
210ZFS_VDEV_QUEUE_KNOB_MIN(trim);
211ZFS_VDEV_QUEUE_KNOB_MAX(trim);
212
213#undef ZFS_VDEV_QUEUE_KNOB
214
215TUNABLE_INT("vfs.zfs.vdev.aggregation_limit", &zfs_vdev_aggregation_limit);
216SYSCTL_INT(_vfs_zfs_vdev, OID_AUTO, aggregation_limit, CTLFLAG_RW,
217    &zfs_vdev_aggregation_limit, 0,
218    "I/O requests are aggregated up to this size");
219TUNABLE_INT("vfs.zfs.vdev.read_gap_limit", &zfs_vdev_read_gap_limit);
220SYSCTL_INT(_vfs_zfs_vdev, OID_AUTO, read_gap_limit, CTLFLAG_RW,
221    &zfs_vdev_read_gap_limit, 0,
222    "Acceptable gap between two reads being aggregated");
223TUNABLE_INT("vfs.zfs.vdev.write_gap_limit", &zfs_vdev_write_gap_limit);
224SYSCTL_INT(_vfs_zfs_vdev, OID_AUTO, write_gap_limit, CTLFLAG_RW,
225    &zfs_vdev_write_gap_limit, 0,
226    "Acceptable gap between two writes being aggregated");
227#endif
228
229int
230vdev_queue_offset_compare(const void *x1, const void *x2)
231{
232	const zio_t *z1 = x1;
233	const zio_t *z2 = x2;
234
235	if (z1->io_offset < z2->io_offset)
236		return (-1);
237	if (z1->io_offset > z2->io_offset)
238		return (1);
239
240	if (z1 < z2)
241		return (-1);
242	if (z1 > z2)
243		return (1);
244
245	return (0);
246}
247
248int
249vdev_queue_timestamp_compare(const void *x1, const void *x2)
250{
251	const zio_t *z1 = x1;
252	const zio_t *z2 = x2;
253
254	if (z1->io_timestamp < z2->io_timestamp)
255		return (-1);
256	if (z1->io_timestamp > z2->io_timestamp)
257		return (1);
258
259	if (z1 < z2)
260		return (-1);
261	if (z1 > z2)
262		return (1);
263
264	return (0);
265}
266
267void
268vdev_queue_init(vdev_t *vd)
269{
270	vdev_queue_t *vq = &vd->vdev_queue;
271
272	mutex_init(&vq->vq_lock, NULL, MUTEX_DEFAULT, NULL);
273	vq->vq_vdev = vd;
274
275	avl_create(&vq->vq_active_tree, vdev_queue_offset_compare,
276	    sizeof (zio_t), offsetof(struct zio, io_queue_node));
277
278	for (zio_priority_t p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
279		/*
280		 * The synchronous i/o queues are FIFO rather than LBA ordered.
281		 * This provides more consistent latency for these i/os, and
282		 * they tend to not be tightly clustered anyway so there is
283		 * little to no throughput loss.
284		 */
285		boolean_t fifo = (p == ZIO_PRIORITY_SYNC_READ ||
286		    p == ZIO_PRIORITY_SYNC_WRITE);
287		avl_create(&vq->vq_class[p].vqc_queued_tree,
288		    fifo ? vdev_queue_timestamp_compare :
289		    vdev_queue_offset_compare,
290		    sizeof (zio_t), offsetof(struct zio, io_queue_node));
291	}
292}
293
294void
295vdev_queue_fini(vdev_t *vd)
296{
297	vdev_queue_t *vq = &vd->vdev_queue;
298
299	for (zio_priority_t p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++)
300		avl_destroy(&vq->vq_class[p].vqc_queued_tree);
301	avl_destroy(&vq->vq_active_tree);
302
303	mutex_destroy(&vq->vq_lock);
304}
305
306static void
307vdev_queue_io_add(vdev_queue_t *vq, zio_t *zio)
308{
309	spa_t *spa = zio->io_spa;
310	ASSERT(MUTEX_HELD(&vq->vq_lock));
311	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
312	avl_add(&vq->vq_class[zio->io_priority].vqc_queued_tree, zio);
313
314#ifdef illumos
315	mutex_enter(&spa->spa_iokstat_lock);
316	spa->spa_queue_stats[zio->io_priority].spa_queued++;
317	if (spa->spa_iokstat != NULL)
318		kstat_waitq_enter(spa->spa_iokstat->ks_data);
319	mutex_exit(&spa->spa_iokstat_lock);
320#endif
321}
322
323static void
324vdev_queue_io_remove(vdev_queue_t *vq, zio_t *zio)
325{
326	spa_t *spa = zio->io_spa;
327	ASSERT(MUTEX_HELD(&vq->vq_lock));
328	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
329	avl_remove(&vq->vq_class[zio->io_priority].vqc_queued_tree, zio);
330
331#ifdef illumos
332	mutex_enter(&spa->spa_iokstat_lock);
333	ASSERT3U(spa->spa_queue_stats[zio->io_priority].spa_queued, >, 0);
334	spa->spa_queue_stats[zio->io_priority].spa_queued--;
335	if (spa->spa_iokstat != NULL)
336		kstat_waitq_exit(spa->spa_iokstat->ks_data);
337	mutex_exit(&spa->spa_iokstat_lock);
338#endif
339}
340
341static void
342vdev_queue_pending_add(vdev_queue_t *vq, zio_t *zio)
343{
344	spa_t *spa = zio->io_spa;
345	ASSERT(MUTEX_HELD(&vq->vq_lock));
346	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
347	vq->vq_class[zio->io_priority].vqc_active++;
348	avl_add(&vq->vq_active_tree, zio);
349
350#ifdef illumos
351	mutex_enter(&spa->spa_iokstat_lock);
352	spa->spa_queue_stats[zio->io_priority].spa_active++;
353	if (spa->spa_iokstat != NULL)
354		kstat_runq_enter(spa->spa_iokstat->ks_data);
355	mutex_exit(&spa->spa_iokstat_lock);
356#endif
357}
358
359static void
360vdev_queue_pending_remove(vdev_queue_t *vq, zio_t *zio)
361{
362	spa_t *spa = zio->io_spa;
363	ASSERT(MUTEX_HELD(&vq->vq_lock));
364	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
365	vq->vq_class[zio->io_priority].vqc_active--;
366	avl_remove(&vq->vq_active_tree, zio);
367
368#ifdef illumos
369	mutex_enter(&spa->spa_iokstat_lock);
370	ASSERT3U(spa->spa_queue_stats[zio->io_priority].spa_active, >, 0);
371	spa->spa_queue_stats[zio->io_priority].spa_active--;
372	if (spa->spa_iokstat != NULL) {
373		kstat_io_t *ksio = spa->spa_iokstat->ks_data;
374
375		kstat_runq_exit(spa->spa_iokstat->ks_data);
376		if (zio->io_type == ZIO_TYPE_READ) {
377			ksio->reads++;
378			ksio->nread += zio->io_size;
379		} else if (zio->io_type == ZIO_TYPE_WRITE) {
380			ksio->writes++;
381			ksio->nwritten += zio->io_size;
382		}
383	}
384	mutex_exit(&spa->spa_iokstat_lock);
385#endif
386}
387
388static void
389vdev_queue_agg_io_done(zio_t *aio)
390{
391	if (aio->io_type == ZIO_TYPE_READ) {
392		zio_t *pio;
393		while ((pio = zio_walk_parents(aio)) != NULL) {
394			bcopy((char *)aio->io_data + (pio->io_offset -
395			    aio->io_offset), pio->io_data, pio->io_size);
396		}
397	}
398
399	zio_buf_free(aio->io_data, aio->io_size);
400}
401
402static int
403vdev_queue_class_min_active(zio_priority_t p)
404{
405	switch (p) {
406	case ZIO_PRIORITY_SYNC_READ:
407		return (zfs_vdev_sync_read_min_active);
408	case ZIO_PRIORITY_SYNC_WRITE:
409		return (zfs_vdev_sync_write_min_active);
410	case ZIO_PRIORITY_ASYNC_READ:
411		return (zfs_vdev_async_read_min_active);
412	case ZIO_PRIORITY_ASYNC_WRITE:
413		return (zfs_vdev_async_write_min_active);
414	case ZIO_PRIORITY_SCRUB:
415		return (zfs_vdev_scrub_min_active);
416	case ZIO_PRIORITY_TRIM:
417		return (zfs_vdev_trim_min_active);
418	default:
419		panic("invalid priority %u", p);
420		return (0);
421	}
422}
423
424static int
425vdev_queue_max_async_writes(spa_t *spa)
426{
427	int writes;
428	uint64_t dirty = spa->spa_dsl_pool->dp_dirty_total;
429	uint64_t min_bytes = zfs_dirty_data_max *
430	    zfs_vdev_async_write_active_min_dirty_percent / 100;
431	uint64_t max_bytes = zfs_dirty_data_max *
432	    zfs_vdev_async_write_active_max_dirty_percent / 100;
433
434	/*
435	 * Sync tasks correspond to interactive user actions. To reduce the
436	 * execution time of those actions we push data out as fast as possible.
437	 */
438	if (spa_has_pending_synctask(spa)) {
439		return (zfs_vdev_async_write_max_active);
440	}
441
442	if (dirty < min_bytes)
443		return (zfs_vdev_async_write_min_active);
444	if (dirty > max_bytes)
445		return (zfs_vdev_async_write_max_active);
446
447	/*
448	 * linear interpolation:
449	 * slope = (max_writes - min_writes) / (max_bytes - min_bytes)
450	 * move right by min_bytes
451	 * move up by min_writes
452	 */
453	writes = (dirty - min_bytes) *
454	    (zfs_vdev_async_write_max_active -
455	    zfs_vdev_async_write_min_active) /
456	    (max_bytes - min_bytes) +
457	    zfs_vdev_async_write_min_active;
458	ASSERT3U(writes, >=, zfs_vdev_async_write_min_active);
459	ASSERT3U(writes, <=, zfs_vdev_async_write_max_active);
460	return (writes);
461}
462
463static int
464vdev_queue_class_max_active(spa_t *spa, zio_priority_t p)
465{
466	switch (p) {
467	case ZIO_PRIORITY_SYNC_READ:
468		return (zfs_vdev_sync_read_max_active);
469	case ZIO_PRIORITY_SYNC_WRITE:
470		return (zfs_vdev_sync_write_max_active);
471	case ZIO_PRIORITY_ASYNC_READ:
472		return (zfs_vdev_async_read_max_active);
473	case ZIO_PRIORITY_ASYNC_WRITE:
474		return (vdev_queue_max_async_writes(spa));
475	case ZIO_PRIORITY_SCRUB:
476		return (zfs_vdev_scrub_max_active);
477	case ZIO_PRIORITY_TRIM:
478		return (zfs_vdev_trim_max_active);
479	default:
480		panic("invalid priority %u", p);
481		return (0);
482	}
483}
484
485/*
486 * Return the i/o class to issue from, or ZIO_PRIORITY_MAX_QUEUEABLE if
487 * there is no eligible class.
488 */
489static zio_priority_t
490vdev_queue_class_to_issue(vdev_queue_t *vq)
491{
492	spa_t *spa = vq->vq_vdev->vdev_spa;
493	zio_priority_t p;
494
495	ASSERT(MUTEX_HELD(&vq->vq_lock));
496
497	if (avl_numnodes(&vq->vq_active_tree) >= zfs_vdev_max_active)
498		return (ZIO_PRIORITY_NUM_QUEUEABLE);
499
500	/* find a queue that has not reached its minimum # outstanding i/os */
501	for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
502		if (avl_numnodes(&vq->vq_class[p].vqc_queued_tree) > 0 &&
503		    vq->vq_class[p].vqc_active <
504		    vdev_queue_class_min_active(p))
505			return (p);
506	}
507
508	/*
509	 * If we haven't found a queue, look for one that hasn't reached its
510	 * maximum # outstanding i/os.
511	 */
512	for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
513		if (avl_numnodes(&vq->vq_class[p].vqc_queued_tree) > 0 &&
514		    vq->vq_class[p].vqc_active <
515		    vdev_queue_class_max_active(spa, p))
516			return (p);
517	}
518
519	/* No eligible queued i/os */
520	return (ZIO_PRIORITY_NUM_QUEUEABLE);
521}
522
523/*
524 * Compute the range spanned by two i/os, which is the endpoint of the last
525 * (lio->io_offset + lio->io_size) minus start of the first (fio->io_offset).
526 * Conveniently, the gap between fio and lio is given by -IO_SPAN(lio, fio);
527 * thus fio and lio are adjacent if and only if IO_SPAN(lio, fio) == 0.
528 */
529#define	IO_SPAN(fio, lio) ((lio)->io_offset + (lio)->io_size - (fio)->io_offset)
530#define	IO_GAP(fio, lio) (-IO_SPAN(lio, fio))
531
532static zio_t *
533vdev_queue_aggregate(vdev_queue_t *vq, zio_t *zio)
534{
535	zio_t *first, *last, *aio, *dio, *mandatory, *nio;
536	uint64_t maxgap = 0;
537	uint64_t size;
538	boolean_t stretch;
539	avl_tree_t *t;
540	enum zio_flag flags;
541
542	ASSERT(MUTEX_HELD(&vq->vq_lock));
543
544	if (zio->io_flags & ZIO_FLAG_DONT_AGGREGATE)
545		return (NULL);
546
547	/*
548	 * The synchronous i/o queues are not sorted by LBA, so we can't
549	 * find adjacent i/os.  These i/os tend to not be tightly clustered,
550	 * or too large to aggregate, so this has little impact on performance.
551	 */
552	if (zio->io_priority == ZIO_PRIORITY_SYNC_READ ||
553	    zio->io_priority == ZIO_PRIORITY_SYNC_WRITE)
554		return (NULL);
555
556	first = last = zio;
557
558	if (zio->io_type == ZIO_TYPE_READ)
559		maxgap = zfs_vdev_read_gap_limit;
560
561	/*
562	 * We can aggregate I/Os that are sufficiently adjacent and of
563	 * the same flavor, as expressed by the AGG_INHERIT flags.
564	 * The latter requirement is necessary so that certain
565	 * attributes of the I/O, such as whether it's a normal I/O
566	 * or a scrub/resilver, can be preserved in the aggregate.
567	 * We can include optional I/Os, but don't allow them
568	 * to begin a range as they add no benefit in that situation.
569	 */
570
571	/*
572	 * We keep track of the last non-optional I/O.
573	 */
574	mandatory = (first->io_flags & ZIO_FLAG_OPTIONAL) ? NULL : first;
575
576	/*
577	 * Walk backwards through sufficiently contiguous I/Os
578	 * recording the last non-option I/O.
579	 */
580	flags = zio->io_flags & ZIO_FLAG_AGG_INHERIT;
581	t = &vq->vq_class[zio->io_priority].vqc_queued_tree;
582	while ((dio = AVL_PREV(t, first)) != NULL &&
583	    (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
584	    IO_SPAN(dio, last) <= zfs_vdev_aggregation_limit &&
585	    IO_GAP(dio, first) <= maxgap) {
586		first = dio;
587		if (mandatory == NULL && !(first->io_flags & ZIO_FLAG_OPTIONAL))
588			mandatory = first;
589	}
590
591	/*
592	 * Skip any initial optional I/Os.
593	 */
594	while ((first->io_flags & ZIO_FLAG_OPTIONAL) && first != last) {
595		first = AVL_NEXT(t, first);
596		ASSERT(first != NULL);
597	}
598
599	/*
600	 * Walk forward through sufficiently contiguous I/Os.
601	 */
602	while ((dio = AVL_NEXT(t, last)) != NULL &&
603	    (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
604	    IO_SPAN(first, dio) <= zfs_vdev_aggregation_limit &&
605	    IO_GAP(last, dio) <= maxgap) {
606		last = dio;
607		if (!(last->io_flags & ZIO_FLAG_OPTIONAL))
608			mandatory = last;
609	}
610
611	/*
612	 * Now that we've established the range of the I/O aggregation
613	 * we must decide what to do with trailing optional I/Os.
614	 * For reads, there's nothing to do. While we are unable to
615	 * aggregate further, it's possible that a trailing optional
616	 * I/O would allow the underlying device to aggregate with
617	 * subsequent I/Os. We must therefore determine if the next
618	 * non-optional I/O is close enough to make aggregation
619	 * worthwhile.
620	 */
621	stretch = B_FALSE;
622	if (zio->io_type == ZIO_TYPE_WRITE && mandatory != NULL) {
623		zio_t *nio = last;
624		while ((dio = AVL_NEXT(t, nio)) != NULL &&
625		    IO_GAP(nio, dio) == 0 &&
626		    IO_GAP(mandatory, dio) <= zfs_vdev_write_gap_limit) {
627			nio = dio;
628			if (!(nio->io_flags & ZIO_FLAG_OPTIONAL)) {
629				stretch = B_TRUE;
630				break;
631			}
632		}
633	}
634
635	if (stretch) {
636		/* This may be a no-op. */
637		dio = AVL_NEXT(t, last);
638		dio->io_flags &= ~ZIO_FLAG_OPTIONAL;
639	} else {
640		while (last != mandatory && last != first) {
641			ASSERT(last->io_flags & ZIO_FLAG_OPTIONAL);
642			last = AVL_PREV(t, last);
643			ASSERT(last != NULL);
644		}
645	}
646
647	if (first == last)
648		return (NULL);
649
650	size = IO_SPAN(first, last);
651	ASSERT3U(size, <=, zfs_vdev_aggregation_limit);
652
653	aio = zio_vdev_delegated_io(first->io_vd, first->io_offset,
654	    zio_buf_alloc(size), size, first->io_type, zio->io_priority,
655	    flags | ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE,
656	    vdev_queue_agg_io_done, NULL);
657	aio->io_timestamp = first->io_timestamp;
658
659	nio = first;
660	do {
661		dio = nio;
662		nio = AVL_NEXT(t, dio);
663		ASSERT3U(dio->io_type, ==, aio->io_type);
664
665		if (dio->io_flags & ZIO_FLAG_NODATA) {
666			ASSERT3U(dio->io_type, ==, ZIO_TYPE_WRITE);
667			bzero((char *)aio->io_data + (dio->io_offset -
668			    aio->io_offset), dio->io_size);
669		} else if (dio->io_type == ZIO_TYPE_WRITE) {
670			bcopy(dio->io_data, (char *)aio->io_data +
671			    (dio->io_offset - aio->io_offset),
672			    dio->io_size);
673		}
674
675		zio_add_child(dio, aio);
676		vdev_queue_io_remove(vq, dio);
677		zio_vdev_io_bypass(dio);
678		zio_execute(dio);
679	} while (dio != last);
680
681	return (aio);
682}
683
684static zio_t *
685vdev_queue_io_to_issue(vdev_queue_t *vq)
686{
687	zio_t *zio, *aio;
688	zio_priority_t p;
689	avl_index_t idx;
690	vdev_queue_class_t *vqc;
691	zio_t search;
692
693again:
694	ASSERT(MUTEX_HELD(&vq->vq_lock));
695
696	p = vdev_queue_class_to_issue(vq);
697
698	if (p == ZIO_PRIORITY_NUM_QUEUEABLE) {
699		/* No eligible queued i/os */
700		return (NULL);
701	}
702
703	/*
704	 * For LBA-ordered queues (async / scrub), issue the i/o which follows
705	 * the most recently issued i/o in LBA (offset) order.
706	 *
707	 * For FIFO queues (sync), issue the i/o with the lowest timestamp.
708	 */
709	vqc = &vq->vq_class[p];
710	search.io_timestamp = 0;
711	search.io_offset = vq->vq_last_offset + 1;
712	VERIFY3P(avl_find(&vqc->vqc_queued_tree, &search, &idx), ==, NULL);
713	zio = avl_nearest(&vqc->vqc_queued_tree, idx, AVL_AFTER);
714	if (zio == NULL)
715		zio = avl_first(&vqc->vqc_queued_tree);
716	ASSERT3U(zio->io_priority, ==, p);
717
718	aio = vdev_queue_aggregate(vq, zio);
719	if (aio != NULL)
720		zio = aio;
721	else
722		vdev_queue_io_remove(vq, zio);
723
724	/*
725	 * If the I/O is or was optional and therefore has no data, we need to
726	 * simply discard it. We need to drop the vdev queue's lock to avoid a
727	 * deadlock that we could encounter since this I/O will complete
728	 * immediately.
729	 */
730	if (zio->io_flags & ZIO_FLAG_NODATA) {
731		mutex_exit(&vq->vq_lock);
732		zio_vdev_io_bypass(zio);
733		zio_execute(zio);
734		mutex_enter(&vq->vq_lock);
735		goto again;
736	}
737
738	vdev_queue_pending_add(vq, zio);
739	vq->vq_last_offset = zio->io_offset;
740
741	return (zio);
742}
743
744zio_t *
745vdev_queue_io(zio_t *zio)
746{
747	vdev_queue_t *vq = &zio->io_vd->vdev_queue;
748	zio_t *nio;
749
750	if (zio->io_flags & ZIO_FLAG_DONT_QUEUE)
751		return (zio);
752
753	/*
754	 * Children i/os inherent their parent's priority, which might
755	 * not match the child's i/o type.  Fix it up here.
756	 */
757	if (zio->io_type == ZIO_TYPE_READ) {
758		if (zio->io_priority != ZIO_PRIORITY_SYNC_READ &&
759		    zio->io_priority != ZIO_PRIORITY_ASYNC_READ &&
760		    zio->io_priority != ZIO_PRIORITY_SCRUB)
761			zio->io_priority = ZIO_PRIORITY_ASYNC_READ;
762	} else if (zio->io_type == ZIO_TYPE_WRITE) {
763		if (zio->io_priority != ZIO_PRIORITY_SYNC_WRITE &&
764		    zio->io_priority != ZIO_PRIORITY_ASYNC_WRITE)
765			zio->io_priority = ZIO_PRIORITY_ASYNC_WRITE;
766	} else {
767		ASSERT(zio->io_type == ZIO_TYPE_FREE);
768		zio->io_priority = ZIO_PRIORITY_TRIM;
769	}
770
771	zio->io_flags |= ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE;
772
773	mutex_enter(&vq->vq_lock);
774	zio->io_timestamp = gethrtime();
775	vdev_queue_io_add(vq, zio);
776	nio = vdev_queue_io_to_issue(vq);
777	mutex_exit(&vq->vq_lock);
778
779	if (nio == NULL)
780		return (NULL);
781
782	if (nio->io_done == vdev_queue_agg_io_done) {
783		zio_nowait(nio);
784		return (NULL);
785	}
786
787	return (nio);
788}
789
790void
791vdev_queue_io_done(zio_t *zio)
792{
793	vdev_queue_t *vq = &zio->io_vd->vdev_queue;
794	zio_t *nio;
795
796	if (zio_injection_enabled)
797		delay(SEC_TO_TICK(zio_handle_io_delay(zio)));
798
799	mutex_enter(&vq->vq_lock);
800
801	vdev_queue_pending_remove(vq, zio);
802
803	vq->vq_io_complete_ts = gethrtime();
804
805	while ((nio = vdev_queue_io_to_issue(vq)) != NULL) {
806		mutex_exit(&vq->vq_lock);
807		if (nio->io_done == vdev_queue_agg_io_done) {
808			zio_nowait(nio);
809		} else {
810			zio_vdev_io_reissue(nio);
811			zio_execute(nio);
812		}
813		mutex_enter(&vq->vq_lock);
814	}
815
816	mutex_exit(&vq->vq_lock);
817}
818