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