xref: /titanic_50/usr/src/uts/common/fs/zfs/vdev_queue.c (revision 4eab410fb63816fe2c0ad0fd18b4c948613f6616)
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 five I/O classes
44  * prioritized in the following order: sync read, sync write, async read,
45  * async write, and scrub/resilver.  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  */
120 uint32_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  */
138 uint32_t zfs_vdev_sync_read_min_active = 10;
139 uint32_t zfs_vdev_sync_read_max_active = 10;
140 uint32_t zfs_vdev_sync_write_min_active = 10;
141 uint32_t zfs_vdev_sync_write_max_active = 10;
142 uint32_t zfs_vdev_async_read_min_active = 1;
143 uint32_t zfs_vdev_async_read_max_active = 3;
144 uint32_t zfs_vdev_async_write_min_active = 1;
145 uint32_t zfs_vdev_async_write_max_active = 10;
146 uint32_t zfs_vdev_scrub_min_active = 1;
147 uint32_t zfs_vdev_scrub_max_active = 2;
148 
149 /*
150  * When the pool has less than zfs_vdev_async_write_active_min_dirty_percent
151  * dirty data, use zfs_vdev_async_write_min_active.  When it has more than
152  * zfs_vdev_async_write_active_max_dirty_percent, use
153  * zfs_vdev_async_write_max_active. The value is linearly interpolated
154  * between min and max.
155  */
156 int zfs_vdev_async_write_active_min_dirty_percent = 30;
157 int zfs_vdev_async_write_active_max_dirty_percent = 60;
158 
159 /*
160  * To reduce IOPs, we aggregate small adjacent I/Os into one large I/O.
161  * For read I/Os, we also aggregate across small adjacency gaps; for writes
162  * we include spans of optional I/Os to aid aggregation at the disk even when
163  * they aren't able to help us aggregate at this level.
164  */
165 int zfs_vdev_aggregation_limit = SPA_OLD_MAXBLOCKSIZE;
166 int zfs_vdev_read_gap_limit = 32 << 10;
167 int zfs_vdev_write_gap_limit = 4 << 10;
168 
169 int
170 vdev_queue_offset_compare(const void *x1, const void *x2)
171 {
172 	const zio_t *z1 = x1;
173 	const zio_t *z2 = x2;
174 
175 	if (z1->io_offset < z2->io_offset)
176 		return (-1);
177 	if (z1->io_offset > z2->io_offset)
178 		return (1);
179 
180 	if (z1 < z2)
181 		return (-1);
182 	if (z1 > z2)
183 		return (1);
184 
185 	return (0);
186 }
187 
188 static inline avl_tree_t *
189 vdev_queue_class_tree(vdev_queue_t *vq, zio_priority_t p)
190 {
191 	return (&vq->vq_class[p].vqc_queued_tree);
192 }
193 
194 static inline avl_tree_t *
195 vdev_queue_type_tree(vdev_queue_t *vq, zio_type_t t)
196 {
197 	ASSERT(t == ZIO_TYPE_READ || t == ZIO_TYPE_WRITE);
198 	if (t == ZIO_TYPE_READ)
199 		return (&vq->vq_read_offset_tree);
200 	else
201 		return (&vq->vq_write_offset_tree);
202 }
203 
204 int
205 vdev_queue_timestamp_compare(const void *x1, const void *x2)
206 {
207 	const zio_t *z1 = x1;
208 	const zio_t *z2 = x2;
209 
210 	if (z1->io_timestamp < z2->io_timestamp)
211 		return (-1);
212 	if (z1->io_timestamp > z2->io_timestamp)
213 		return (1);
214 
215 	if (z1 < z2)
216 		return (-1);
217 	if (z1 > z2)
218 		return (1);
219 
220 	return (0);
221 }
222 
223 void
224 vdev_queue_init(vdev_t *vd)
225 {
226 	vdev_queue_t *vq = &vd->vdev_queue;
227 
228 	mutex_init(&vq->vq_lock, NULL, MUTEX_DEFAULT, NULL);
229 	vq->vq_vdev = vd;
230 
231 	avl_create(&vq->vq_active_tree, vdev_queue_offset_compare,
232 	    sizeof (zio_t), offsetof(struct zio, io_queue_node));
233 	avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_READ),
234 	    vdev_queue_offset_compare, sizeof (zio_t),
235 	    offsetof(struct zio, io_offset_node));
236 	avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_WRITE),
237 	    vdev_queue_offset_compare, sizeof (zio_t),
238 	    offsetof(struct zio, io_offset_node));
239 
240 	for (zio_priority_t p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
241 		int (*compfn) (const void *, const void *);
242 
243 		/*
244 		 * The synchronous i/o queues are dispatched in FIFO rather
245 		 * than LBA order.  This provides more consistent latency for
246 		 * these i/os.
247 		 */
248 		if (p == ZIO_PRIORITY_SYNC_READ || p == ZIO_PRIORITY_SYNC_WRITE)
249 			compfn = vdev_queue_timestamp_compare;
250 		else
251 			compfn = vdev_queue_offset_compare;
252 
253 		avl_create(vdev_queue_class_tree(vq, p), compfn,
254 		    sizeof (zio_t), offsetof(struct zio, io_queue_node));
255 	}
256 }
257 
258 void
259 vdev_queue_fini(vdev_t *vd)
260 {
261 	vdev_queue_t *vq = &vd->vdev_queue;
262 
263 	for (zio_priority_t p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++)
264 		avl_destroy(vdev_queue_class_tree(vq, p));
265 	avl_destroy(&vq->vq_active_tree);
266 	avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_READ));
267 	avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_WRITE));
268 
269 	mutex_destroy(&vq->vq_lock);
270 }
271 
272 static void
273 vdev_queue_io_add(vdev_queue_t *vq, zio_t *zio)
274 {
275 	spa_t *spa = zio->io_spa;
276 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
277 	avl_add(vdev_queue_class_tree(vq, zio->io_priority), zio);
278 	avl_add(vdev_queue_type_tree(vq, zio->io_type), zio);
279 
280 	mutex_enter(&spa->spa_iokstat_lock);
281 	spa->spa_queue_stats[zio->io_priority].spa_queued++;
282 	if (spa->spa_iokstat != NULL)
283 		kstat_waitq_enter(spa->spa_iokstat->ks_data);
284 	mutex_exit(&spa->spa_iokstat_lock);
285 }
286 
287 static void
288 vdev_queue_io_remove(vdev_queue_t *vq, zio_t *zio)
289 {
290 	spa_t *spa = zio->io_spa;
291 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
292 	avl_remove(vdev_queue_class_tree(vq, zio->io_priority), zio);
293 	avl_remove(vdev_queue_type_tree(vq, zio->io_type), zio);
294 
295 	mutex_enter(&spa->spa_iokstat_lock);
296 	ASSERT3U(spa->spa_queue_stats[zio->io_priority].spa_queued, >, 0);
297 	spa->spa_queue_stats[zio->io_priority].spa_queued--;
298 	if (spa->spa_iokstat != NULL)
299 		kstat_waitq_exit(spa->spa_iokstat->ks_data);
300 	mutex_exit(&spa->spa_iokstat_lock);
301 }
302 
303 static void
304 vdev_queue_pending_add(vdev_queue_t *vq, zio_t *zio)
305 {
306 	spa_t *spa = zio->io_spa;
307 	ASSERT(MUTEX_HELD(&vq->vq_lock));
308 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
309 	vq->vq_class[zio->io_priority].vqc_active++;
310 	avl_add(&vq->vq_active_tree, zio);
311 
312 	mutex_enter(&spa->spa_iokstat_lock);
313 	spa->spa_queue_stats[zio->io_priority].spa_active++;
314 	if (spa->spa_iokstat != NULL)
315 		kstat_runq_enter(spa->spa_iokstat->ks_data);
316 	mutex_exit(&spa->spa_iokstat_lock);
317 }
318 
319 static void
320 vdev_queue_pending_remove(vdev_queue_t *vq, zio_t *zio)
321 {
322 	spa_t *spa = zio->io_spa;
323 	ASSERT(MUTEX_HELD(&vq->vq_lock));
324 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
325 	vq->vq_class[zio->io_priority].vqc_active--;
326 	avl_remove(&vq->vq_active_tree, zio);
327 
328 	mutex_enter(&spa->spa_iokstat_lock);
329 	ASSERT3U(spa->spa_queue_stats[zio->io_priority].spa_active, >, 0);
330 	spa->spa_queue_stats[zio->io_priority].spa_active--;
331 	if (spa->spa_iokstat != NULL) {
332 		kstat_io_t *ksio = spa->spa_iokstat->ks_data;
333 
334 		kstat_runq_exit(spa->spa_iokstat->ks_data);
335 		if (zio->io_type == ZIO_TYPE_READ) {
336 			ksio->reads++;
337 			ksio->nread += zio->io_size;
338 		} else if (zio->io_type == ZIO_TYPE_WRITE) {
339 			ksio->writes++;
340 			ksio->nwritten += zio->io_size;
341 		}
342 	}
343 	mutex_exit(&spa->spa_iokstat_lock);
344 }
345 
346 static void
347 vdev_queue_agg_io_done(zio_t *aio)
348 {
349 	if (aio->io_type == ZIO_TYPE_READ) {
350 		zio_t *pio;
351 		while ((pio = zio_walk_parents(aio)) != NULL) {
352 			bcopy((char *)aio->io_data + (pio->io_offset -
353 			    aio->io_offset), pio->io_data, pio->io_size);
354 		}
355 	}
356 
357 	zio_buf_free(aio->io_data, aio->io_size);
358 }
359 
360 static int
361 vdev_queue_class_min_active(zio_priority_t p)
362 {
363 	switch (p) {
364 	case ZIO_PRIORITY_SYNC_READ:
365 		return (zfs_vdev_sync_read_min_active);
366 	case ZIO_PRIORITY_SYNC_WRITE:
367 		return (zfs_vdev_sync_write_min_active);
368 	case ZIO_PRIORITY_ASYNC_READ:
369 		return (zfs_vdev_async_read_min_active);
370 	case ZIO_PRIORITY_ASYNC_WRITE:
371 		return (zfs_vdev_async_write_min_active);
372 	case ZIO_PRIORITY_SCRUB:
373 		return (zfs_vdev_scrub_min_active);
374 	default:
375 		panic("invalid priority %u", p);
376 		return (0);
377 	}
378 }
379 
380 static int
381 vdev_queue_max_async_writes(spa_t *spa)
382 {
383 	int writes;
384 	uint64_t dirty = spa->spa_dsl_pool->dp_dirty_total;
385 	uint64_t min_bytes = zfs_dirty_data_max *
386 	    zfs_vdev_async_write_active_min_dirty_percent / 100;
387 	uint64_t max_bytes = zfs_dirty_data_max *
388 	    zfs_vdev_async_write_active_max_dirty_percent / 100;
389 
390 	/*
391 	 * Sync tasks correspond to interactive user actions. To reduce the
392 	 * execution time of those actions we push data out as fast as possible.
393 	 */
394 	if (spa_has_pending_synctask(spa)) {
395 		return (zfs_vdev_async_write_max_active);
396 	}
397 
398 	if (dirty < min_bytes)
399 		return (zfs_vdev_async_write_min_active);
400 	if (dirty > max_bytes)
401 		return (zfs_vdev_async_write_max_active);
402 
403 	/*
404 	 * linear interpolation:
405 	 * slope = (max_writes - min_writes) / (max_bytes - min_bytes)
406 	 * move right by min_bytes
407 	 * move up by min_writes
408 	 */
409 	writes = (dirty - min_bytes) *
410 	    (zfs_vdev_async_write_max_active -
411 	    zfs_vdev_async_write_min_active) /
412 	    (max_bytes - min_bytes) +
413 	    zfs_vdev_async_write_min_active;
414 	ASSERT3U(writes, >=, zfs_vdev_async_write_min_active);
415 	ASSERT3U(writes, <=, zfs_vdev_async_write_max_active);
416 	return (writes);
417 }
418 
419 static int
420 vdev_queue_class_max_active(spa_t *spa, zio_priority_t p)
421 {
422 	switch (p) {
423 	case ZIO_PRIORITY_SYNC_READ:
424 		return (zfs_vdev_sync_read_max_active);
425 	case ZIO_PRIORITY_SYNC_WRITE:
426 		return (zfs_vdev_sync_write_max_active);
427 	case ZIO_PRIORITY_ASYNC_READ:
428 		return (zfs_vdev_async_read_max_active);
429 	case ZIO_PRIORITY_ASYNC_WRITE:
430 		return (vdev_queue_max_async_writes(spa));
431 	case ZIO_PRIORITY_SCRUB:
432 		return (zfs_vdev_scrub_max_active);
433 	default:
434 		panic("invalid priority %u", p);
435 		return (0);
436 	}
437 }
438 
439 /*
440  * Return the i/o class to issue from, or ZIO_PRIORITY_MAX_QUEUEABLE if
441  * there is no eligible class.
442  */
443 static zio_priority_t
444 vdev_queue_class_to_issue(vdev_queue_t *vq)
445 {
446 	spa_t *spa = vq->vq_vdev->vdev_spa;
447 	zio_priority_t p;
448 
449 	if (avl_numnodes(&vq->vq_active_tree) >= zfs_vdev_max_active)
450 		return (ZIO_PRIORITY_NUM_QUEUEABLE);
451 
452 	/* find a queue that has not reached its minimum # outstanding i/os */
453 	for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
454 		if (avl_numnodes(vdev_queue_class_tree(vq, p)) > 0 &&
455 		    vq->vq_class[p].vqc_active <
456 		    vdev_queue_class_min_active(p))
457 			return (p);
458 	}
459 
460 	/*
461 	 * If we haven't found a queue, look for one that hasn't reached its
462 	 * maximum # outstanding i/os.
463 	 */
464 	for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
465 		if (avl_numnodes(vdev_queue_class_tree(vq, p)) > 0 &&
466 		    vq->vq_class[p].vqc_active <
467 		    vdev_queue_class_max_active(spa, p))
468 			return (p);
469 	}
470 
471 	/* No eligible queued i/os */
472 	return (ZIO_PRIORITY_NUM_QUEUEABLE);
473 }
474 
475 /*
476  * Compute the range spanned by two i/os, which is the endpoint of the last
477  * (lio->io_offset + lio->io_size) minus start of the first (fio->io_offset).
478  * Conveniently, the gap between fio and lio is given by -IO_SPAN(lio, fio);
479  * thus fio and lio are adjacent if and only if IO_SPAN(lio, fio) == 0.
480  */
481 #define	IO_SPAN(fio, lio) ((lio)->io_offset + (lio)->io_size - (fio)->io_offset)
482 #define	IO_GAP(fio, lio) (-IO_SPAN(lio, fio))
483 
484 static zio_t *
485 vdev_queue_aggregate(vdev_queue_t *vq, zio_t *zio)
486 {
487 	zio_t *first, *last, *aio, *dio, *mandatory, *nio;
488 	uint64_t maxgap = 0;
489 	uint64_t size;
490 	boolean_t stretch = B_FALSE;
491 	avl_tree_t *t = vdev_queue_type_tree(vq, zio->io_type);
492 	enum zio_flag flags = zio->io_flags & ZIO_FLAG_AGG_INHERIT;
493 
494 	if (zio->io_flags & ZIO_FLAG_DONT_AGGREGATE)
495 		return (NULL);
496 
497 	first = last = zio;
498 
499 	if (zio->io_type == ZIO_TYPE_READ)
500 		maxgap = zfs_vdev_read_gap_limit;
501 
502 	/*
503 	 * We can aggregate I/Os that are sufficiently adjacent and of
504 	 * the same flavor, as expressed by the AGG_INHERIT flags.
505 	 * The latter requirement is necessary so that certain
506 	 * attributes of the I/O, such as whether it's a normal I/O
507 	 * or a scrub/resilver, can be preserved in the aggregate.
508 	 * We can include optional I/Os, but don't allow them
509 	 * to begin a range as they add no benefit in that situation.
510 	 */
511 
512 	/*
513 	 * We keep track of the last non-optional I/O.
514 	 */
515 	mandatory = (first->io_flags & ZIO_FLAG_OPTIONAL) ? NULL : first;
516 
517 	/*
518 	 * Walk backwards through sufficiently contiguous I/Os
519 	 * recording the last non-option I/O.
520 	 */
521 	while ((dio = AVL_PREV(t, first)) != NULL &&
522 	    (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
523 	    IO_SPAN(dio, last) <= zfs_vdev_aggregation_limit &&
524 	    IO_GAP(dio, first) <= maxgap) {
525 		first = dio;
526 		if (mandatory == NULL && !(first->io_flags & ZIO_FLAG_OPTIONAL))
527 			mandatory = first;
528 	}
529 
530 	/*
531 	 * Skip any initial optional I/Os.
532 	 */
533 	while ((first->io_flags & ZIO_FLAG_OPTIONAL) && first != last) {
534 		first = AVL_NEXT(t, first);
535 		ASSERT(first != NULL);
536 	}
537 
538 	/*
539 	 * Walk forward through sufficiently contiguous I/Os.
540 	 */
541 	while ((dio = AVL_NEXT(t, last)) != NULL &&
542 	    (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
543 	    IO_SPAN(first, dio) <= zfs_vdev_aggregation_limit &&
544 	    IO_GAP(last, dio) <= maxgap) {
545 		last = dio;
546 		if (!(last->io_flags & ZIO_FLAG_OPTIONAL))
547 			mandatory = last;
548 	}
549 
550 	/*
551 	 * Now that we've established the range of the I/O aggregation
552 	 * we must decide what to do with trailing optional I/Os.
553 	 * For reads, there's nothing to do. While we are unable to
554 	 * aggregate further, it's possible that a trailing optional
555 	 * I/O would allow the underlying device to aggregate with
556 	 * subsequent I/Os. We must therefore determine if the next
557 	 * non-optional I/O is close enough to make aggregation
558 	 * worthwhile.
559 	 */
560 	if (zio->io_type == ZIO_TYPE_WRITE && mandatory != NULL) {
561 		zio_t *nio = last;
562 		while ((dio = AVL_NEXT(t, nio)) != NULL &&
563 		    IO_GAP(nio, dio) == 0 &&
564 		    IO_GAP(mandatory, dio) <= zfs_vdev_write_gap_limit) {
565 			nio = dio;
566 			if (!(nio->io_flags & ZIO_FLAG_OPTIONAL)) {
567 				stretch = B_TRUE;
568 				break;
569 			}
570 		}
571 	}
572 
573 	if (stretch) {
574 		/* This may be a no-op. */
575 		dio = AVL_NEXT(t, last);
576 		dio->io_flags &= ~ZIO_FLAG_OPTIONAL;
577 	} else {
578 		while (last != mandatory && last != first) {
579 			ASSERT(last->io_flags & ZIO_FLAG_OPTIONAL);
580 			last = AVL_PREV(t, last);
581 			ASSERT(last != NULL);
582 		}
583 	}
584 
585 	if (first == last)
586 		return (NULL);
587 
588 	size = IO_SPAN(first, last);
589 	ASSERT3U(size, <=, zfs_vdev_aggregation_limit);
590 
591 	aio = zio_vdev_delegated_io(first->io_vd, first->io_offset,
592 	    zio_buf_alloc(size), size, first->io_type, zio->io_priority,
593 	    flags | ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE,
594 	    vdev_queue_agg_io_done, NULL);
595 	aio->io_timestamp = first->io_timestamp;
596 
597 	nio = first;
598 	do {
599 		dio = nio;
600 		nio = AVL_NEXT(t, dio);
601 		ASSERT3U(dio->io_type, ==, aio->io_type);
602 
603 		if (dio->io_flags & ZIO_FLAG_NODATA) {
604 			ASSERT3U(dio->io_type, ==, ZIO_TYPE_WRITE);
605 			bzero((char *)aio->io_data + (dio->io_offset -
606 			    aio->io_offset), dio->io_size);
607 		} else if (dio->io_type == ZIO_TYPE_WRITE) {
608 			bcopy(dio->io_data, (char *)aio->io_data +
609 			    (dio->io_offset - aio->io_offset),
610 			    dio->io_size);
611 		}
612 
613 		zio_add_child(dio, aio);
614 		vdev_queue_io_remove(vq, dio);
615 		zio_vdev_io_bypass(dio);
616 		zio_execute(dio);
617 	} while (dio != last);
618 
619 	return (aio);
620 }
621 
622 static zio_t *
623 vdev_queue_io_to_issue(vdev_queue_t *vq)
624 {
625 	zio_t *zio, *aio;
626 	zio_priority_t p;
627 	avl_index_t idx;
628 	avl_tree_t *tree;
629 	zio_t search;
630 
631 again:
632 	ASSERT(MUTEX_HELD(&vq->vq_lock));
633 
634 	p = vdev_queue_class_to_issue(vq);
635 
636 	if (p == ZIO_PRIORITY_NUM_QUEUEABLE) {
637 		/* No eligible queued i/os */
638 		return (NULL);
639 	}
640 
641 	/*
642 	 * For LBA-ordered queues (async / scrub), issue the i/o which follows
643 	 * the most recently issued i/o in LBA (offset) order.
644 	 *
645 	 * For FIFO queues (sync), issue the i/o with the lowest timestamp.
646 	 */
647 	tree = vdev_queue_class_tree(vq, p);
648 	search.io_timestamp = 0;
649 	search.io_offset = vq->vq_last_offset + 1;
650 	VERIFY3P(avl_find(tree, &search, &idx), ==, NULL);
651 	zio = avl_nearest(tree, idx, AVL_AFTER);
652 	if (zio == NULL)
653 		zio = avl_first(tree);
654 	ASSERT3U(zio->io_priority, ==, p);
655 
656 	aio = vdev_queue_aggregate(vq, zio);
657 	if (aio != NULL)
658 		zio = aio;
659 	else
660 		vdev_queue_io_remove(vq, zio);
661 
662 	/*
663 	 * If the I/O is or was optional and therefore has no data, we need to
664 	 * simply discard it. We need to drop the vdev queue's lock to avoid a
665 	 * deadlock that we could encounter since this I/O will complete
666 	 * immediately.
667 	 */
668 	if (zio->io_flags & ZIO_FLAG_NODATA) {
669 		mutex_exit(&vq->vq_lock);
670 		zio_vdev_io_bypass(zio);
671 		zio_execute(zio);
672 		mutex_enter(&vq->vq_lock);
673 		goto again;
674 	}
675 
676 	vdev_queue_pending_add(vq, zio);
677 	vq->vq_last_offset = zio->io_offset;
678 
679 	return (zio);
680 }
681 
682 zio_t *
683 vdev_queue_io(zio_t *zio)
684 {
685 	vdev_queue_t *vq = &zio->io_vd->vdev_queue;
686 	zio_t *nio;
687 
688 	if (zio->io_flags & ZIO_FLAG_DONT_QUEUE)
689 		return (zio);
690 
691 	/*
692 	 * Children i/os inherent their parent's priority, which might
693 	 * not match the child's i/o type.  Fix it up here.
694 	 */
695 	if (zio->io_type == ZIO_TYPE_READ) {
696 		if (zio->io_priority != ZIO_PRIORITY_SYNC_READ &&
697 		    zio->io_priority != ZIO_PRIORITY_ASYNC_READ &&
698 		    zio->io_priority != ZIO_PRIORITY_SCRUB)
699 			zio->io_priority = ZIO_PRIORITY_ASYNC_READ;
700 	} else {
701 		ASSERT(zio->io_type == ZIO_TYPE_WRITE);
702 		if (zio->io_priority != ZIO_PRIORITY_SYNC_WRITE &&
703 		    zio->io_priority != ZIO_PRIORITY_ASYNC_WRITE)
704 			zio->io_priority = ZIO_PRIORITY_ASYNC_WRITE;
705 	}
706 
707 	zio->io_flags |= ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE;
708 
709 	mutex_enter(&vq->vq_lock);
710 	zio->io_timestamp = gethrtime();
711 	vdev_queue_io_add(vq, zio);
712 	nio = vdev_queue_io_to_issue(vq);
713 	mutex_exit(&vq->vq_lock);
714 
715 	if (nio == NULL)
716 		return (NULL);
717 
718 	if (nio->io_done == vdev_queue_agg_io_done) {
719 		zio_nowait(nio);
720 		return (NULL);
721 	}
722 
723 	return (nio);
724 }
725 
726 void
727 vdev_queue_io_done(zio_t *zio)
728 {
729 	vdev_queue_t *vq = &zio->io_vd->vdev_queue;
730 	zio_t *nio;
731 
732 	if (zio_injection_enabled)
733 		delay(SEC_TO_TICK(zio_handle_io_delay(zio)));
734 
735 	mutex_enter(&vq->vq_lock);
736 
737 	vdev_queue_pending_remove(vq, zio);
738 
739 	vq->vq_io_complete_ts = gethrtime();
740 
741 	while ((nio = vdev_queue_io_to_issue(vq)) != NULL) {
742 		mutex_exit(&vq->vq_lock);
743 		if (nio->io_done == vdev_queue_agg_io_done) {
744 			zio_nowait(nio);
745 		} else {
746 			zio_vdev_io_reissue(nio);
747 			zio_execute(nio);
748 		}
749 		mutex_enter(&vq->vq_lock);
750 	}
751 
752 	mutex_exit(&vq->vq_lock);
753 }
754