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