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