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