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, 2018 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 #include <sys/metaslab_impl.h>
37 #include <sys/spa.h>
38 #include <sys/spa_impl.h>
39 #include <sys/kstat.h>
40 #include <sys/abd.h>
41 
42 /*
43  * ZFS I/O Scheduler
44  * ---------------
45  *
46  * ZFS issues I/O operations to leaf vdevs to satisfy and complete zios.  The
47  * I/O scheduler determines when and in what order those operations are
48  * issued.  The I/O scheduler divides operations into five I/O classes
49  * prioritized in the following order: sync read, sync write, async read,
50  * async write, and scrub/resilver.  Each queue defines the minimum and
51  * maximum number of concurrent operations that may be issued to the device.
52  * In addition, the device has an aggregate maximum. Note that the sum of the
53  * per-queue minimums must not exceed the aggregate maximum. If the
54  * sum of the per-queue maximums exceeds the aggregate maximum, then the
55  * number of active i/os may reach zfs_vdev_max_active, in which case no
56  * further i/os will be issued regardless of whether all per-queue
57  * minimums have been met.
58  *
59  * For many physical devices, throughput increases with the number of
60  * concurrent operations, but latency typically suffers. Further, physical
61  * devices typically have a limit at which more concurrent operations have no
62  * effect on throughput or can actually cause it to decrease.
63  *
64  * The scheduler selects the next operation to issue by first looking for an
65  * I/O class whose minimum has not been satisfied. Once all are satisfied and
66  * the aggregate maximum has not been hit, the scheduler looks for classes
67  * whose maximum has not been satisfied. Iteration through the I/O classes is
68  * done in the order specified above. No further operations are issued if the
69  * aggregate maximum number of concurrent operations has been hit or if there
70  * are no operations queued for an I/O class that has not hit its maximum.
71  * Every time an i/o is queued or an operation completes, the I/O scheduler
72  * looks for new operations to issue.
73  *
74  * All I/O classes have a fixed maximum number of outstanding operations
75  * except for the async write class. Asynchronous writes represent the data
76  * that is committed to stable storage during the syncing stage for
77  * transaction groups (see txg.c). Transaction groups enter the syncing state
78  * periodically so the number of queued async writes will quickly burst up and
79  * then bleed down to zero. Rather than servicing them as quickly as possible,
80  * the I/O scheduler changes the maximum number of active async write i/os
81  * according to the amount of dirty data in the pool (see dsl_pool.c). Since
82  * both throughput and latency typically increase with the number of
83  * concurrent operations issued to physical devices, reducing the burstiness
84  * in the number of concurrent operations also stabilizes the response time of
85  * operations from other -- and in particular synchronous -- queues. In broad
86  * strokes, the I/O scheduler will issue more concurrent operations from the
87  * async write queue as there's more dirty data in the pool.
88  *
89  * Async Writes
90  *
91  * The number of concurrent operations issued for the async write I/O class
92  * follows a piece-wise linear function defined by a few adjustable points.
93  *
94  *        |                   o---------| <-- zfs_vdev_async_write_max_active
95  *   ^    |                  /^         |
96  *   |    |                 / |         |
97  * active |                /  |         |
98  *  I/O   |               /   |         |
99  * count  |              /    |         |
100  *        |             /     |         |
101  *        |------------o      |         | <-- zfs_vdev_async_write_min_active
102  *       0|____________^______|_________|
103  *        0%           |      |       100% of zfs_dirty_data_max
104  *                     |      |
105  *                     |      `-- zfs_vdev_async_write_active_max_dirty_percent
106  *                     `--------- zfs_vdev_async_write_active_min_dirty_percent
107  *
108  * Until the amount of dirty data exceeds a minimum percentage of the dirty
109  * data allowed in the pool, the I/O scheduler will limit the number of
110  * concurrent operations to the minimum. As that threshold is crossed, the
111  * number of concurrent operations issued increases linearly to the maximum at
112  * the specified maximum percentage of the dirty data allowed in the pool.
113  *
114  * Ideally, the amount of dirty data on a busy pool will stay in the sloped
115  * part of the function between zfs_vdev_async_write_active_min_dirty_percent
116  * and zfs_vdev_async_write_active_max_dirty_percent. If it exceeds the
117  * maximum percentage, this indicates that the rate of incoming data is
118  * greater than the rate that the backend storage can handle. In this case, we
119  * must further throttle incoming writes (see dmu_tx_delay() for details).
120  */
121 
122 /*
123  * The maximum number of i/os active to each device.  Ideally, this will be >=
124  * the sum of each queue's max_active.  It must be at least the sum of each
125  * queue's min_active.
126  */
127 uint32_t zfs_vdev_max_active = 1000;
128 
129 /*
130  * Per-queue limits on the number of i/os active to each device.  If the
131  * number of active i/os is < zfs_vdev_max_active, then the min_active comes
132  * into play. We will send min_active from each queue, and then select from
133  * queues in the order defined by zio_priority_t.
134  *
135  * In general, smaller max_active's will lead to lower latency of synchronous
136  * operations.  Larger max_active's may lead to higher overall throughput,
137  * depending on underlying storage.
138  *
139  * The ratio of the queues' max_actives determines the balance of performance
140  * between reads, writes, and scrubs.  E.g., increasing
141  * zfs_vdev_scrub_max_active will cause the scrub or resilver to complete
142  * more quickly, but reads and writes to have higher latency and lower
143  * throughput.
144  */
145 uint32_t zfs_vdev_sync_read_min_active = 10;
146 uint32_t zfs_vdev_sync_read_max_active = 10;
147 uint32_t zfs_vdev_sync_write_min_active = 10;
148 uint32_t zfs_vdev_sync_write_max_active = 10;
149 uint32_t zfs_vdev_async_read_min_active = 1;
150 uint32_t zfs_vdev_async_read_max_active = 3;
151 uint32_t zfs_vdev_async_write_min_active = 2;
152 uint32_t zfs_vdev_async_write_max_active = 10;
153 uint32_t zfs_vdev_scrub_min_active = 1;
154 uint32_t zfs_vdev_scrub_max_active = 2;
155 uint32_t zfs_vdev_removal_min_active = 1;
156 uint32_t zfs_vdev_removal_max_active = 2;
157 uint32_t zfs_vdev_initializing_min_active = 1;
158 uint32_t zfs_vdev_initializing_max_active = 1;
159 uint32_t zfs_vdev_trim_min_active = 1;
160 uint32_t zfs_vdev_trim_max_active = 2;
161 uint32_t zfs_vdev_rebuild_min_active = 1;
162 uint32_t zfs_vdev_rebuild_max_active = 3;
163 
164 /*
165  * When the pool has less than zfs_vdev_async_write_active_min_dirty_percent
166  * dirty data, use zfs_vdev_async_write_min_active.  When it has more than
167  * zfs_vdev_async_write_active_max_dirty_percent, use
168  * zfs_vdev_async_write_max_active. The value is linearly interpolated
169  * between min and max.
170  */
171 int zfs_vdev_async_write_active_min_dirty_percent = 30;
172 int zfs_vdev_async_write_active_max_dirty_percent = 60;
173 
174 /*
175  * To reduce IOPs, we aggregate small adjacent I/Os into one large I/O.
176  * For read I/Os, we also aggregate across small adjacency gaps; for writes
177  * we include spans of optional I/Os to aid aggregation at the disk even when
178  * they aren't able to help us aggregate at this level.
179  */
180 int zfs_vdev_aggregation_limit = 1 << 20;
181 int zfs_vdev_aggregation_limit_non_rotating = SPA_OLD_MAXBLOCKSIZE;
182 int zfs_vdev_read_gap_limit = 32 << 10;
183 int zfs_vdev_write_gap_limit = 4 << 10;
184 
185 /*
186  * Define the queue depth percentage for each top-level. This percentage is
187  * used in conjunction with zfs_vdev_async_max_active to determine how many
188  * allocations a specific top-level vdev should handle. Once the queue depth
189  * reaches zfs_vdev_queue_depth_pct * zfs_vdev_async_write_max_active / 100
190  * then allocator will stop allocating blocks on that top-level device.
191  * The default kernel setting is 1000% which will yield 100 allocations per
192  * device. For userland testing, the default setting is 300% which equates
193  * to 30 allocations per device.
194  */
195 #ifdef _KERNEL
196 int zfs_vdev_queue_depth_pct = 1000;
197 #else
198 int zfs_vdev_queue_depth_pct = 300;
199 #endif
200 
201 /*
202  * When performing allocations for a given metaslab, we want to make sure that
203  * there are enough IOs to aggregate together to improve throughput. We want to
204  * ensure that there are at least 128k worth of IOs that can be aggregated, and
205  * we assume that the average allocation size is 4k, so we need the queue depth
206  * to be 32 per allocator to get good aggregation of sequential writes.
207  */
208 int zfs_vdev_def_queue_depth = 32;
209 
210 /*
211  * Allow TRIM I/Os to be aggregated.  This should normally not be needed since
212  * TRIM I/O for extents up to zfs_trim_extent_bytes_max (128M) can be submitted
213  * by the TRIM code in zfs_trim.c.
214  */
215 int zfs_vdev_aggregate_trim = 0;
216 
217 static int
218 vdev_queue_offset_compare(const void *x1, const void *x2)
219 {
220 	const zio_t *z1 = (const zio_t *)x1;
221 	const zio_t *z2 = (const zio_t *)x2;
222 
223 	int cmp = TREE_CMP(z1->io_offset, z2->io_offset);
224 
225 	if (likely(cmp))
226 		return (cmp);
227 
228 	return (TREE_PCMP(z1, z2));
229 }
230 
231 static inline avl_tree_t *
232 vdev_queue_class_tree(vdev_queue_t *vq, zio_priority_t p)
233 {
234 	return (&vq->vq_class[p].vqc_queued_tree);
235 }
236 
237 static inline avl_tree_t *
238 vdev_queue_type_tree(vdev_queue_t *vq, zio_type_t t)
239 {
240 	ASSERT(t == ZIO_TYPE_READ || t == ZIO_TYPE_WRITE || t == ZIO_TYPE_TRIM);
241 	if (t == ZIO_TYPE_READ)
242 		return (&vq->vq_read_offset_tree);
243 	else if (t == ZIO_TYPE_WRITE)
244 		return (&vq->vq_write_offset_tree);
245 	else
246 		return (&vq->vq_trim_offset_tree);
247 }
248 
249 static int
250 vdev_queue_timestamp_compare(const void *x1, const void *x2)
251 {
252 	const zio_t *z1 = (const zio_t *)x1;
253 	const zio_t *z2 = (const zio_t *)x2;
254 
255 	int cmp = TREE_CMP(z1->io_timestamp, z2->io_timestamp);
256 
257 	if (likely(cmp))
258 		return (cmp);
259 
260 	return (TREE_PCMP(z1, z2));
261 }
262 
263 static int
264 vdev_queue_class_min_active(zio_priority_t p)
265 {
266 	switch (p) {
267 	case ZIO_PRIORITY_SYNC_READ:
268 		return (zfs_vdev_sync_read_min_active);
269 	case ZIO_PRIORITY_SYNC_WRITE:
270 		return (zfs_vdev_sync_write_min_active);
271 	case ZIO_PRIORITY_ASYNC_READ:
272 		return (zfs_vdev_async_read_min_active);
273 	case ZIO_PRIORITY_ASYNC_WRITE:
274 		return (zfs_vdev_async_write_min_active);
275 	case ZIO_PRIORITY_SCRUB:
276 		return (zfs_vdev_scrub_min_active);
277 	case ZIO_PRIORITY_REMOVAL:
278 		return (zfs_vdev_removal_min_active);
279 	case ZIO_PRIORITY_INITIALIZING:
280 		return (zfs_vdev_initializing_min_active);
281 	case ZIO_PRIORITY_TRIM:
282 		return (zfs_vdev_trim_min_active);
283 	case ZIO_PRIORITY_REBUILD:
284 		return (zfs_vdev_rebuild_min_active);
285 	default:
286 		panic("invalid priority %u", p);
287 		return (0);
288 	}
289 }
290 
291 static int
292 vdev_queue_max_async_writes(spa_t *spa)
293 {
294 	int writes;
295 	uint64_t dirty = 0;
296 	dsl_pool_t *dp = spa_get_dsl(spa);
297 	uint64_t min_bytes = zfs_dirty_data_max *
298 	    zfs_vdev_async_write_active_min_dirty_percent / 100;
299 	uint64_t max_bytes = zfs_dirty_data_max *
300 	    zfs_vdev_async_write_active_max_dirty_percent / 100;
301 
302 	/*
303 	 * Async writes may occur before the assignment of the spa's
304 	 * dsl_pool_t if a self-healing zio is issued prior to the
305 	 * completion of dmu_objset_open_impl().
306 	 */
307 	if (dp == NULL)
308 		return (zfs_vdev_async_write_max_active);
309 
310 	/*
311 	 * Sync tasks correspond to interactive user actions. To reduce the
312 	 * execution time of those actions we push data out as fast as possible.
313 	 */
314 	if (spa_has_pending_synctask(spa))
315 		return (zfs_vdev_async_write_max_active);
316 
317 	dirty = dp->dp_dirty_total;
318 	if (dirty < min_bytes)
319 		return (zfs_vdev_async_write_min_active);
320 	if (dirty > max_bytes)
321 		return (zfs_vdev_async_write_max_active);
322 
323 	/*
324 	 * linear interpolation:
325 	 * slope = (max_writes - min_writes) / (max_bytes - min_bytes)
326 	 * move right by min_bytes
327 	 * move up by min_writes
328 	 */
329 	writes = (dirty - min_bytes) *
330 	    (zfs_vdev_async_write_max_active -
331 	    zfs_vdev_async_write_min_active) /
332 	    (max_bytes - min_bytes) +
333 	    zfs_vdev_async_write_min_active;
334 	ASSERT3U(writes, >=, zfs_vdev_async_write_min_active);
335 	ASSERT3U(writes, <=, zfs_vdev_async_write_max_active);
336 	return (writes);
337 }
338 
339 static int
340 vdev_queue_class_max_active(spa_t *spa, zio_priority_t p)
341 {
342 	switch (p) {
343 	case ZIO_PRIORITY_SYNC_READ:
344 		return (zfs_vdev_sync_read_max_active);
345 	case ZIO_PRIORITY_SYNC_WRITE:
346 		return (zfs_vdev_sync_write_max_active);
347 	case ZIO_PRIORITY_ASYNC_READ:
348 		return (zfs_vdev_async_read_max_active);
349 	case ZIO_PRIORITY_ASYNC_WRITE:
350 		return (vdev_queue_max_async_writes(spa));
351 	case ZIO_PRIORITY_SCRUB:
352 		return (zfs_vdev_scrub_max_active);
353 	case ZIO_PRIORITY_REMOVAL:
354 		return (zfs_vdev_removal_max_active);
355 	case ZIO_PRIORITY_INITIALIZING:
356 		return (zfs_vdev_initializing_max_active);
357 	case ZIO_PRIORITY_TRIM:
358 		return (zfs_vdev_trim_max_active);
359 	case ZIO_PRIORITY_REBUILD:
360 		return (zfs_vdev_rebuild_max_active);
361 	default:
362 		panic("invalid priority %u", p);
363 		return (0);
364 	}
365 }
366 
367 /*
368  * Return the i/o class to issue from, or ZIO_PRIORITY_MAX_QUEUEABLE if
369  * there is no eligible class.
370  */
371 static zio_priority_t
372 vdev_queue_class_to_issue(vdev_queue_t *vq)
373 {
374 	spa_t *spa = vq->vq_vdev->vdev_spa;
375 	zio_priority_t p;
376 
377 	if (avl_numnodes(&vq->vq_active_tree) >= zfs_vdev_max_active)
378 		return (ZIO_PRIORITY_NUM_QUEUEABLE);
379 
380 	/* find a queue that has not reached its minimum # outstanding i/os */
381 	for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
382 		if (avl_numnodes(vdev_queue_class_tree(vq, p)) > 0 &&
383 		    vq->vq_class[p].vqc_active <
384 		    vdev_queue_class_min_active(p))
385 			return (p);
386 	}
387 
388 	/*
389 	 * If we haven't found a queue, look for one that hasn't reached its
390 	 * maximum # outstanding i/os.
391 	 */
392 	for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
393 		if (avl_numnodes(vdev_queue_class_tree(vq, p)) > 0 &&
394 		    vq->vq_class[p].vqc_active <
395 		    vdev_queue_class_max_active(spa, p))
396 			return (p);
397 	}
398 
399 	/* No eligible queued i/os */
400 	return (ZIO_PRIORITY_NUM_QUEUEABLE);
401 }
402 
403 void
404 vdev_queue_init(vdev_t *vd)
405 {
406 	vdev_queue_t *vq = &vd->vdev_queue;
407 	zio_priority_t p;
408 
409 	mutex_init(&vq->vq_lock, NULL, MUTEX_DEFAULT, NULL);
410 	vq->vq_vdev = vd;
411 	taskq_init_ent(&vd->vdev_queue.vq_io_search.io_tqent);
412 
413 	avl_create(&vq->vq_active_tree, vdev_queue_offset_compare,
414 	    sizeof (zio_t), offsetof(struct zio, io_queue_node));
415 	avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_READ),
416 	    vdev_queue_offset_compare, sizeof (zio_t),
417 	    offsetof(struct zio, io_offset_node));
418 	avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_WRITE),
419 	    vdev_queue_offset_compare, sizeof (zio_t),
420 	    offsetof(struct zio, io_offset_node));
421 	avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_TRIM),
422 	    vdev_queue_offset_compare, sizeof (zio_t),
423 	    offsetof(struct zio, io_offset_node));
424 
425 	for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
426 		int (*compfn) (const void *, const void *);
427 
428 		/*
429 		 * The synchronous/trim i/o queues are dispatched in FIFO rather
430 		 * than LBA order. This provides more consistent latency for
431 		 * these i/os.
432 		 */
433 		if (p == ZIO_PRIORITY_SYNC_READ ||
434 		    p == ZIO_PRIORITY_SYNC_WRITE ||
435 		    p == ZIO_PRIORITY_TRIM) {
436 			compfn = vdev_queue_timestamp_compare;
437 		} else {
438 			compfn = vdev_queue_offset_compare;
439 		}
440 		avl_create(vdev_queue_class_tree(vq, p), compfn,
441 		    sizeof (zio_t), offsetof(struct zio, io_queue_node));
442 	}
443 
444 	vq->vq_last_offset = 0;
445 }
446 
447 void
448 vdev_queue_fini(vdev_t *vd)
449 {
450 	vdev_queue_t *vq = &vd->vdev_queue;
451 
452 	for (zio_priority_t p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++)
453 		avl_destroy(vdev_queue_class_tree(vq, p));
454 	avl_destroy(&vq->vq_active_tree);
455 	avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_READ));
456 	avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_WRITE));
457 	avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_TRIM));
458 
459 	mutex_destroy(&vq->vq_lock);
460 }
461 
462 static void
463 vdev_queue_io_add(vdev_queue_t *vq, zio_t *zio)
464 {
465 	spa_t *spa = zio->io_spa;
466 	spa_history_kstat_t *shk = &spa->spa_stats.io_history;
467 
468 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
469 	avl_add(vdev_queue_class_tree(vq, zio->io_priority), zio);
470 	avl_add(vdev_queue_type_tree(vq, zio->io_type), zio);
471 
472 	if (shk->kstat != NULL) {
473 		mutex_enter(&shk->lock);
474 		kstat_waitq_enter(shk->kstat->ks_data);
475 		mutex_exit(&shk->lock);
476 	}
477 }
478 
479 static void
480 vdev_queue_io_remove(vdev_queue_t *vq, zio_t *zio)
481 {
482 	spa_t *spa = zio->io_spa;
483 	spa_history_kstat_t *shk = &spa->spa_stats.io_history;
484 
485 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
486 	avl_remove(vdev_queue_class_tree(vq, zio->io_priority), zio);
487 	avl_remove(vdev_queue_type_tree(vq, zio->io_type), zio);
488 
489 	if (shk->kstat != NULL) {
490 		mutex_enter(&shk->lock);
491 		kstat_waitq_exit(shk->kstat->ks_data);
492 		mutex_exit(&shk->lock);
493 	}
494 }
495 
496 static void
497 vdev_queue_pending_add(vdev_queue_t *vq, zio_t *zio)
498 {
499 	spa_t *spa = zio->io_spa;
500 	spa_history_kstat_t *shk = &spa->spa_stats.io_history;
501 
502 	ASSERT(MUTEX_HELD(&vq->vq_lock));
503 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
504 	vq->vq_class[zio->io_priority].vqc_active++;
505 	avl_add(&vq->vq_active_tree, zio);
506 
507 	if (shk->kstat != NULL) {
508 		mutex_enter(&shk->lock);
509 		kstat_runq_enter(shk->kstat->ks_data);
510 		mutex_exit(&shk->lock);
511 	}
512 }
513 
514 static void
515 vdev_queue_pending_remove(vdev_queue_t *vq, zio_t *zio)
516 {
517 	spa_t *spa = zio->io_spa;
518 	spa_history_kstat_t *shk = &spa->spa_stats.io_history;
519 
520 	ASSERT(MUTEX_HELD(&vq->vq_lock));
521 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
522 	vq->vq_class[zio->io_priority].vqc_active--;
523 	avl_remove(&vq->vq_active_tree, zio);
524 
525 	if (shk->kstat != NULL) {
526 		kstat_io_t *ksio = shk->kstat->ks_data;
527 
528 		mutex_enter(&shk->lock);
529 		kstat_runq_exit(ksio);
530 		if (zio->io_type == ZIO_TYPE_READ) {
531 			ksio->reads++;
532 			ksio->nread += zio->io_size;
533 		} else if (zio->io_type == ZIO_TYPE_WRITE) {
534 			ksio->writes++;
535 			ksio->nwritten += zio->io_size;
536 		}
537 		mutex_exit(&shk->lock);
538 	}
539 }
540 
541 static void
542 vdev_queue_agg_io_done(zio_t *aio)
543 {
544 	abd_free(aio->io_abd);
545 }
546 
547 /*
548  * Compute the range spanned by two i/os, which is the endpoint of the last
549  * (lio->io_offset + lio->io_size) minus start of the first (fio->io_offset).
550  * Conveniently, the gap between fio and lio is given by -IO_SPAN(lio, fio);
551  * thus fio and lio are adjacent if and only if IO_SPAN(lio, fio) == 0.
552  */
553 #define	IO_SPAN(fio, lio) ((lio)->io_offset + (lio)->io_size - (fio)->io_offset)
554 #define	IO_GAP(fio, lio) (-IO_SPAN(lio, fio))
555 
556 /*
557  * Sufficiently adjacent io_offset's in ZIOs will be aggregated. We do this
558  * by creating a gang ABD from the adjacent ZIOs io_abd's. By using
559  * a gang ABD we avoid doing memory copies to and from the parent,
560  * child ZIOs. The gang ABD also accounts for gaps between adjacent
561  * io_offsets by simply getting the zero ABD for writes or allocating
562  * a new ABD for reads and placing them in the gang ABD as well.
563  */
564 static zio_t *
565 vdev_queue_aggregate(vdev_queue_t *vq, zio_t *zio)
566 {
567 	zio_t *first, *last, *aio, *dio, *mandatory, *nio;
568 	zio_link_t *zl = NULL;
569 	uint64_t maxgap = 0;
570 	uint64_t size;
571 	uint64_t limit;
572 	int maxblocksize;
573 	boolean_t stretch = B_FALSE;
574 	avl_tree_t *t = vdev_queue_type_tree(vq, zio->io_type);
575 	enum zio_flag flags = zio->io_flags & ZIO_FLAG_AGG_INHERIT;
576 	uint64_t next_offset;
577 	abd_t *abd;
578 
579 	maxblocksize = spa_maxblocksize(vq->vq_vdev->vdev_spa);
580 	if (vq->vq_vdev->vdev_nonrot)
581 		limit = zfs_vdev_aggregation_limit_non_rotating;
582 	else
583 		limit = zfs_vdev_aggregation_limit;
584 	limit = MAX(MIN(limit, maxblocksize), 0);
585 
586 	if (zio->io_flags & ZIO_FLAG_DONT_AGGREGATE || limit == 0)
587 		return (NULL);
588 
589 	/*
590 	 * While TRIM commands could be aggregated based on offset this
591 	 * behavior is disabled until it's determined to be beneficial.
592 	 */
593 	if (zio->io_type == ZIO_TYPE_TRIM && !zfs_vdev_aggregate_trim)
594 		return (NULL);
595 
596 	first = last = zio;
597 
598 	if (zio->io_type == ZIO_TYPE_READ)
599 		maxgap = zfs_vdev_read_gap_limit;
600 
601 	/*
602 	 * We can aggregate I/Os that are sufficiently adjacent and of
603 	 * the same flavor, as expressed by the AGG_INHERIT flags.
604 	 * The latter requirement is necessary so that certain
605 	 * attributes of the I/O, such as whether it's a normal I/O
606 	 * or a scrub/resilver, can be preserved in the aggregate.
607 	 * We can include optional I/Os, but don't allow them
608 	 * to begin a range as they add no benefit in that situation.
609 	 */
610 
611 	/*
612 	 * We keep track of the last non-optional I/O.
613 	 */
614 	mandatory = (first->io_flags & ZIO_FLAG_OPTIONAL) ? NULL : first;
615 
616 	/*
617 	 * Walk backwards through sufficiently contiguous I/Os
618 	 * recording the last non-optional I/O.
619 	 */
620 	while ((dio = AVL_PREV(t, first)) != NULL &&
621 	    (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
622 	    IO_SPAN(dio, last) <= limit &&
623 	    IO_GAP(dio, first) <= maxgap &&
624 	    dio->io_type == zio->io_type) {
625 		first = dio;
626 		if (mandatory == NULL && !(first->io_flags & ZIO_FLAG_OPTIONAL))
627 			mandatory = first;
628 	}
629 
630 	/*
631 	 * Skip any initial optional I/Os.
632 	 */
633 	while ((first->io_flags & ZIO_FLAG_OPTIONAL) && first != last) {
634 		first = AVL_NEXT(t, first);
635 		ASSERT(first != NULL);
636 	}
637 
638 
639 	/*
640 	 * Walk forward through sufficiently contiguous I/Os.
641 	 * The aggregation limit does not apply to optional i/os, so that
642 	 * we can issue contiguous writes even if they are larger than the
643 	 * aggregation limit.
644 	 */
645 	while ((dio = AVL_NEXT(t, last)) != NULL &&
646 	    (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
647 	    (IO_SPAN(first, dio) <= limit ||
648 	    (dio->io_flags & ZIO_FLAG_OPTIONAL)) &&
649 	    IO_SPAN(first, dio) <= maxblocksize &&
650 	    IO_GAP(last, dio) <= maxgap &&
651 	    dio->io_type == zio->io_type) {
652 		last = dio;
653 		if (!(last->io_flags & ZIO_FLAG_OPTIONAL))
654 			mandatory = last;
655 	}
656 
657 	/*
658 	 * Now that we've established the range of the I/O aggregation
659 	 * we must decide what to do with trailing optional I/Os.
660 	 * For reads, there's nothing to do. While we are unable to
661 	 * aggregate further, it's possible that a trailing optional
662 	 * I/O would allow the underlying device to aggregate with
663 	 * subsequent I/Os. We must therefore determine if the next
664 	 * non-optional I/O is close enough to make aggregation
665 	 * worthwhile.
666 	 */
667 	if (zio->io_type == ZIO_TYPE_WRITE && mandatory != NULL) {
668 		zio_t *nio = last;
669 		while ((dio = AVL_NEXT(t, nio)) != NULL &&
670 		    IO_GAP(nio, dio) == 0 &&
671 		    IO_GAP(mandatory, dio) <= zfs_vdev_write_gap_limit) {
672 			nio = dio;
673 			if (!(nio->io_flags & ZIO_FLAG_OPTIONAL)) {
674 				stretch = B_TRUE;
675 				break;
676 			}
677 		}
678 	}
679 
680 	if (stretch) {
681 		/*
682 		 * We are going to include an optional io in our aggregated
683 		 * span, thus closing the write gap.  Only mandatory i/os can
684 		 * start aggregated spans, so make sure that the next i/o
685 		 * after our span is mandatory.
686 		 */
687 		dio = AVL_NEXT(t, last);
688 		dio->io_flags &= ~ZIO_FLAG_OPTIONAL;
689 	} else {
690 		/* do not include the optional i/o */
691 		while (last != mandatory && last != first) {
692 			ASSERT(last->io_flags & ZIO_FLAG_OPTIONAL);
693 			last = AVL_PREV(t, last);
694 			ASSERT(last != NULL);
695 		}
696 	}
697 
698 	if (first == last)
699 		return (NULL);
700 
701 	size = IO_SPAN(first, last);
702 	ASSERT3U(size, <=, maxblocksize);
703 
704 	abd = abd_alloc_gang_abd();
705 	if (abd == NULL)
706 		return (NULL);
707 
708 	aio = zio_vdev_delegated_io(first->io_vd, first->io_offset,
709 	    abd, size, first->io_type, zio->io_priority,
710 	    flags | ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE,
711 	    vdev_queue_agg_io_done, NULL);
712 	aio->io_timestamp = first->io_timestamp;
713 
714 	nio = first;
715 	next_offset = first->io_offset;
716 	do {
717 		dio = nio;
718 		nio = AVL_NEXT(t, dio);
719 		zio_add_child(dio, aio);
720 		vdev_queue_io_remove(vq, dio);
721 
722 		if (dio->io_offset != next_offset) {
723 			/* allocate a buffer for a read gap */
724 			ASSERT3U(dio->io_type, ==, ZIO_TYPE_READ);
725 			ASSERT3U(dio->io_offset, >, next_offset);
726 			abd = abd_alloc_for_io(
727 			    dio->io_offset - next_offset, B_TRUE);
728 			abd_gang_add(aio->io_abd, abd, B_TRUE);
729 		}
730 		if (dio->io_abd &&
731 		    (dio->io_size != abd_get_size(dio->io_abd))) {
732 			/* abd size not the same as IO size */
733 			ASSERT3U(abd_get_size(dio->io_abd), >, dio->io_size);
734 			abd = abd_get_offset_size(dio->io_abd, 0, dio->io_size);
735 			abd_gang_add(aio->io_abd, abd, B_TRUE);
736 		} else {
737 			if (dio->io_flags & ZIO_FLAG_NODATA) {
738 				/* allocate a buffer for a write gap */
739 				ASSERT3U(dio->io_type, ==, ZIO_TYPE_WRITE);
740 				ASSERT3P(dio->io_abd, ==, NULL);
741 				abd_gang_add(aio->io_abd,
742 				    abd_get_zeros(dio->io_size), B_TRUE);
743 			} else {
744 				/*
745 				 * We pass B_FALSE to abd_gang_add()
746 				 * because we did not allocate a new
747 				 * ABD, so it is assumed the caller
748 				 * will free this ABD.
749 				 */
750 				abd_gang_add(aio->io_abd, dio->io_abd,
751 				    B_FALSE);
752 			}
753 		}
754 		next_offset = dio->io_offset + dio->io_size;
755 	} while (dio != last);
756 	ASSERT3U(abd_get_size(aio->io_abd), ==, aio->io_size);
757 
758 	/*
759 	 * We need to drop the vdev queue's lock during zio_execute() to
760 	 * avoid a deadlock that we could encounter due to lock order
761 	 * reversal between vq_lock and io_lock in zio_change_priority().
762 	 */
763 	mutex_exit(&vq->vq_lock);
764 	while ((dio = zio_walk_parents(aio, &zl)) != NULL) {
765 		ASSERT3U(dio->io_type, ==, aio->io_type);
766 
767 		zio_vdev_io_bypass(dio);
768 		zio_execute(dio);
769 	}
770 	mutex_enter(&vq->vq_lock);
771 
772 	return (aio);
773 }
774 
775 static zio_t *
776 vdev_queue_io_to_issue(vdev_queue_t *vq)
777 {
778 	zio_t *zio, *aio;
779 	zio_priority_t p;
780 	avl_index_t idx;
781 	avl_tree_t *tree;
782 
783 again:
784 	ASSERT(MUTEX_HELD(&vq->vq_lock));
785 
786 	p = vdev_queue_class_to_issue(vq);
787 
788 	if (p == ZIO_PRIORITY_NUM_QUEUEABLE) {
789 		/* No eligible queued i/os */
790 		return (NULL);
791 	}
792 
793 	/*
794 	 * For LBA-ordered queues (async / scrub / initializing), issue the
795 	 * i/o which follows the most recently issued i/o in LBA (offset) order.
796 	 *
797 	 * For FIFO queues (sync/trim), issue the i/o with the lowest timestamp.
798 	 */
799 	tree = vdev_queue_class_tree(vq, p);
800 	vq->vq_io_search.io_timestamp = 0;
801 	vq->vq_io_search.io_offset = vq->vq_last_offset - 1;
802 	VERIFY3P(avl_find(tree, &vq->vq_io_search, &idx), ==, NULL);
803 	zio = avl_nearest(tree, idx, AVL_AFTER);
804 	if (zio == NULL)
805 		zio = avl_first(tree);
806 	ASSERT3U(zio->io_priority, ==, p);
807 
808 	aio = vdev_queue_aggregate(vq, zio);
809 	if (aio != NULL)
810 		zio = aio;
811 	else
812 		vdev_queue_io_remove(vq, zio);
813 
814 	/*
815 	 * If the I/O is or was optional and therefore has no data, we need to
816 	 * simply discard it. We need to drop the vdev queue's lock to avoid a
817 	 * deadlock that we could encounter since this I/O will complete
818 	 * immediately.
819 	 */
820 	if (zio->io_flags & ZIO_FLAG_NODATA) {
821 		mutex_exit(&vq->vq_lock);
822 		zio_vdev_io_bypass(zio);
823 		zio_execute(zio);
824 		mutex_enter(&vq->vq_lock);
825 		goto again;
826 	}
827 
828 	vdev_queue_pending_add(vq, zio);
829 	vq->vq_last_offset = zio->io_offset + zio->io_size;
830 
831 	return (zio);
832 }
833 
834 zio_t *
835 vdev_queue_io(zio_t *zio)
836 {
837 	vdev_queue_t *vq = &zio->io_vd->vdev_queue;
838 	zio_t *nio;
839 
840 	if (zio->io_flags & ZIO_FLAG_DONT_QUEUE)
841 		return (zio);
842 
843 	/*
844 	 * Children i/os inherent their parent's priority, which might
845 	 * not match the child's i/o type.  Fix it up here.
846 	 */
847 	if (zio->io_type == ZIO_TYPE_READ) {
848 		ASSERT(zio->io_priority != ZIO_PRIORITY_TRIM);
849 
850 		if (zio->io_priority != ZIO_PRIORITY_SYNC_READ &&
851 		    zio->io_priority != ZIO_PRIORITY_ASYNC_READ &&
852 		    zio->io_priority != ZIO_PRIORITY_SCRUB &&
853 		    zio->io_priority != ZIO_PRIORITY_REMOVAL &&
854 		    zio->io_priority != ZIO_PRIORITY_INITIALIZING &&
855 		    zio->io_priority != ZIO_PRIORITY_REBUILD) {
856 			zio->io_priority = ZIO_PRIORITY_ASYNC_READ;
857 		}
858 	} else if (zio->io_type == ZIO_TYPE_WRITE) {
859 		ASSERT(zio->io_priority != ZIO_PRIORITY_TRIM);
860 
861 		if (zio->io_priority != ZIO_PRIORITY_SYNC_WRITE &&
862 		    zio->io_priority != ZIO_PRIORITY_ASYNC_WRITE &&
863 		    zio->io_priority != ZIO_PRIORITY_REMOVAL &&
864 		    zio->io_priority != ZIO_PRIORITY_INITIALIZING &&
865 		    zio->io_priority != ZIO_PRIORITY_REBUILD) {
866 			zio->io_priority = ZIO_PRIORITY_ASYNC_WRITE;
867 		}
868 	} else {
869 		ASSERT(zio->io_type == ZIO_TYPE_TRIM);
870 		ASSERT(zio->io_priority == ZIO_PRIORITY_TRIM);
871 	}
872 
873 	zio->io_flags |= ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE;
874 
875 	mutex_enter(&vq->vq_lock);
876 	zio->io_timestamp = gethrtime();
877 	vdev_queue_io_add(vq, zio);
878 	nio = vdev_queue_io_to_issue(vq);
879 	mutex_exit(&vq->vq_lock);
880 
881 	if (nio == NULL)
882 		return (NULL);
883 
884 	if (nio->io_done == vdev_queue_agg_io_done) {
885 		zio_nowait(nio);
886 		return (NULL);
887 	}
888 
889 	return (nio);
890 }
891 
892 void
893 vdev_queue_io_done(zio_t *zio)
894 {
895 	vdev_queue_t *vq = &zio->io_vd->vdev_queue;
896 	zio_t *nio;
897 
898 	mutex_enter(&vq->vq_lock);
899 
900 	vdev_queue_pending_remove(vq, zio);
901 
902 	zio->io_delta = gethrtime() - zio->io_timestamp;
903 	vq->vq_io_complete_ts = gethrtime();
904 	vq->vq_io_delta_ts = vq->vq_io_complete_ts - zio->io_timestamp;
905 
906 	while ((nio = vdev_queue_io_to_issue(vq)) != NULL) {
907 		mutex_exit(&vq->vq_lock);
908 		if (nio->io_done == vdev_queue_agg_io_done) {
909 			zio_nowait(nio);
910 		} else {
911 			zio_vdev_io_reissue(nio);
912 			zio_execute(nio);
913 		}
914 		mutex_enter(&vq->vq_lock);
915 	}
916 
917 	mutex_exit(&vq->vq_lock);
918 }
919 
920 void
921 vdev_queue_change_io_priority(zio_t *zio, zio_priority_t priority)
922 {
923 	vdev_queue_t *vq = &zio->io_vd->vdev_queue;
924 	avl_tree_t *tree;
925 
926 	/*
927 	 * ZIO_PRIORITY_NOW is used by the vdev cache code and the aggregate zio
928 	 * code to issue IOs without adding them to the vdev queue. In this
929 	 * case, the zio is already going to be issued as quickly as possible
930 	 * and so it doesn't need any reprioritization to help.
931 	 */
932 	if (zio->io_priority == ZIO_PRIORITY_NOW)
933 		return;
934 
935 	ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
936 	ASSERT3U(priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
937 
938 	if (zio->io_type == ZIO_TYPE_READ) {
939 		if (priority != ZIO_PRIORITY_SYNC_READ &&
940 		    priority != ZIO_PRIORITY_ASYNC_READ &&
941 		    priority != ZIO_PRIORITY_SCRUB)
942 			priority = ZIO_PRIORITY_ASYNC_READ;
943 	} else {
944 		ASSERT(zio->io_type == ZIO_TYPE_WRITE);
945 		if (priority != ZIO_PRIORITY_SYNC_WRITE &&
946 		    priority != ZIO_PRIORITY_ASYNC_WRITE)
947 			priority = ZIO_PRIORITY_ASYNC_WRITE;
948 	}
949 
950 	mutex_enter(&vq->vq_lock);
951 
952 	/*
953 	 * If the zio is in none of the queues we can simply change
954 	 * the priority. If the zio is waiting to be submitted we must
955 	 * remove it from the queue and re-insert it with the new priority.
956 	 * Otherwise, the zio is currently active and we cannot change its
957 	 * priority.
958 	 */
959 	tree = vdev_queue_class_tree(vq, zio->io_priority);
960 	if (avl_find(tree, zio, NULL) == zio) {
961 		avl_remove(vdev_queue_class_tree(vq, zio->io_priority), zio);
962 		zio->io_priority = priority;
963 		avl_add(vdev_queue_class_tree(vq, zio->io_priority), zio);
964 	} else if (avl_find(&vq->vq_active_tree, zio, NULL) != zio) {
965 		zio->io_priority = priority;
966 	}
967 
968 	mutex_exit(&vq->vq_lock);
969 }
970 
971 /*
972  * As these two methods are only used for load calculations we're not
973  * concerned if we get an incorrect value on 32bit platforms due to lack of
974  * vq_lock mutex use here, instead we prefer to keep it lock free for
975  * performance.
976  */
977 int
978 vdev_queue_length(vdev_t *vd)
979 {
980 	return (avl_numnodes(&vd->vdev_queue.vq_active_tree));
981 }
982 
983 uint64_t
984 vdev_queue_last_offset(vdev_t *vd)
985 {
986 	return (vd->vdev_queue.vq_last_offset);
987 }
988 
989 /* BEGIN CSTYLED */
990 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, aggregation_limit, INT, ZMOD_RW,
991 	"Max vdev I/O aggregation size");
992 
993 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, aggregation_limit_non_rotating, INT, ZMOD_RW,
994 	"Max vdev I/O aggregation size for non-rotating media");
995 
996 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, aggregate_trim, INT, ZMOD_RW,
997 	"Allow TRIM I/O to be aggregated");
998 
999 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, read_gap_limit, INT, ZMOD_RW,
1000 	"Aggregate read I/O over gap");
1001 
1002 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, write_gap_limit, INT, ZMOD_RW,
1003 	"Aggregate write I/O over gap");
1004 
1005 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, max_active, INT, ZMOD_RW,
1006 	"Maximum number of active I/Os per vdev");
1007 
1008 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, async_write_active_max_dirty_percent, INT, ZMOD_RW,
1009 	"Async write concurrency max threshold");
1010 
1011 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, async_write_active_min_dirty_percent, INT, ZMOD_RW,
1012 	"Async write concurrency min threshold");
1013 
1014 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, async_read_max_active, INT, ZMOD_RW,
1015 	"Max active async read I/Os per vdev");
1016 
1017 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, async_read_min_active, INT, ZMOD_RW,
1018 	"Min active async read I/Os per vdev");
1019 
1020 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, async_write_max_active, INT, ZMOD_RW,
1021 	"Max active async write I/Os per vdev");
1022 
1023 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, async_write_min_active, INT, ZMOD_RW,
1024 	"Min active async write I/Os per vdev");
1025 
1026 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, initializing_max_active, INT, ZMOD_RW,
1027 	"Max active initializing I/Os per vdev");
1028 
1029 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, initializing_min_active, INT, ZMOD_RW,
1030 	"Min active initializing I/Os per vdev");
1031 
1032 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, removal_max_active, INT, ZMOD_RW,
1033 	"Max active removal I/Os per vdev");
1034 
1035 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, removal_min_active, INT, ZMOD_RW,
1036 	"Min active removal I/Os per vdev");
1037 
1038 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, scrub_max_active, INT, ZMOD_RW,
1039 	"Max active scrub I/Os per vdev");
1040 
1041 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, scrub_min_active, INT, ZMOD_RW,
1042 	"Min active scrub I/Os per vdev");
1043 
1044 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, sync_read_max_active, INT, ZMOD_RW,
1045 	"Max active sync read I/Os per vdev");
1046 
1047 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, sync_read_min_active, INT, ZMOD_RW,
1048 	"Min active sync read I/Os per vdev");
1049 
1050 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, sync_write_max_active, INT, ZMOD_RW,
1051 	"Max active sync write I/Os per vdev");
1052 
1053 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, sync_write_min_active, INT, ZMOD_RW,
1054 	"Min active sync write I/Os per vdev");
1055 
1056 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, trim_max_active, INT, ZMOD_RW,
1057 	"Max active trim/discard I/Os per vdev");
1058 
1059 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, trim_min_active, INT, ZMOD_RW,
1060 	"Min active trim/discard I/Os per vdev");
1061 
1062 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, rebuild_max_active, INT, ZMOD_RW,
1063 	"Max active rebuild I/Os per vdev");
1064 
1065 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, rebuild_min_active, INT, ZMOD_RW,
1066 	"Min active rebuild I/Os per vdev");
1067 
1068 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, queue_depth_pct, INT, ZMOD_RW,
1069 	"Queue depth percentage for each top-level vdev");
1070 /* END CSTYLED */
1071