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