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