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