]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/vdev_queue.c
Don't directly cast unsigned long to void*
[FreeBSD/FreeBSD.git] / module / 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, 2018 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 #include <sys/metaslab_impl.h>
37 #include <sys/spa.h>
38 #include <sys/spa_impl.h>
39 #include <sys/kstat.h>
40 #include <sys/abd.h>
41
42 /*
43  * ZFS I/O Scheduler
44  * ---------------
45  *
46  * ZFS issues I/O operations to leaf vdevs to satisfy and complete zios.  The
47  * I/O scheduler determines when and in what order those operations are
48  * issued.  The I/O scheduler divides operations into five I/O classes
49  * prioritized in the following order: sync read, sync write, async read,
50  * async write, and scrub/resilver.  Each queue defines the minimum and
51  * maximum number of concurrent operations that may be issued to the device.
52  * In addition, the device has an aggregate maximum. Note that the sum of the
53  * per-queue minimums must not exceed the aggregate maximum. If the
54  * sum of the per-queue maximums exceeds the aggregate maximum, then the
55  * number of active i/os may reach zfs_vdev_max_active, in which case no
56  * further i/os will be issued regardless of whether all per-queue
57  * minimums have been met.
58  *
59  * For many physical devices, throughput increases with the number of
60  * concurrent operations, but latency typically suffers. Further, physical
61  * devices typically have a limit at which more concurrent operations have no
62  * effect on throughput or can actually cause it to decrease.
63  *
64  * The scheduler selects the next operation to issue by first looking for an
65  * I/O class whose minimum has not been satisfied. Once all are satisfied and
66  * the aggregate maximum has not been hit, the scheduler looks for classes
67  * whose maximum has not been satisfied. Iteration through the I/O classes is
68  * done in the order specified above. No further operations are issued if the
69  * aggregate maximum number of concurrent operations has been hit or if there
70  * are no operations queued for an I/O class that has not hit its maximum.
71  * Every time an i/o is queued or an operation completes, the I/O scheduler
72  * looks for new operations to issue.
73  *
74  * All I/O classes have a fixed maximum number of outstanding operations
75  * except for the async write class. Asynchronous writes represent the data
76  * that is committed to stable storage during the syncing stage for
77  * transaction groups (see txg.c). Transaction groups enter the syncing state
78  * periodically so the number of queued async writes will quickly burst up and
79  * then bleed down to zero. Rather than servicing them as quickly as possible,
80  * the I/O scheduler changes the maximum number of active async write i/os
81  * according to the amount of dirty data in the pool (see dsl_pool.c). Since
82  * both throughput and latency typically increase with the number of
83  * concurrent operations issued to physical devices, reducing the burstiness
84  * in the number of concurrent operations also stabilizes the response time of
85  * operations from other -- and in particular synchronous -- queues. In broad
86  * strokes, the I/O scheduler will issue more concurrent operations from the
87  * async write queue as there's more dirty data in the pool.
88  *
89  * Async Writes
90  *
91  * The number of concurrent operations issued for the async write I/O class
92  * follows a piece-wise linear function defined by a few adjustable points.
93  *
94  *        |                   o---------| <-- zfs_vdev_async_write_max_active
95  *   ^    |                  /^         |
96  *   |    |                 / |         |
97  * active |                /  |         |
98  *  I/O   |               /   |         |
99  * count  |              /    |         |
100  *        |             /     |         |
101  *        |------------o      |         | <-- zfs_vdev_async_write_min_active
102  *       0|____________^______|_________|
103  *        0%           |      |       100% of zfs_dirty_data_max
104  *                     |      |
105  *                     |      `-- zfs_vdev_async_write_active_max_dirty_percent
106  *                     `--------- zfs_vdev_async_write_active_min_dirty_percent
107  *
108  * Until the amount of dirty data exceeds a minimum percentage of the dirty
109  * data allowed in the pool, the I/O scheduler will limit the number of
110  * concurrent operations to the minimum. As that threshold is crossed, the
111  * number of concurrent operations issued increases linearly to the maximum at
112  * the specified maximum percentage of the dirty data allowed in the pool.
113  *
114  * Ideally, the amount of dirty data on a busy pool will stay in the sloped
115  * part of the function between zfs_vdev_async_write_active_min_dirty_percent
116  * and zfs_vdev_async_write_active_max_dirty_percent. If it exceeds the
117  * maximum percentage, this indicates that the rate of incoming data is
118  * greater than the rate that the backend storage can handle. In this case, we
119  * must further throttle incoming writes (see dmu_tx_delay() for details).
120  */
121
122 /*
123  * The maximum number of i/os active to each device.  Ideally, this will be >=
124  * the sum of each queue's max_active.  It must be at least the sum of each
125  * queue's min_active.
126  */
127 uint32_t zfs_vdev_max_active = 1000;
128
129 /*
130  * Per-queue limits on the number of i/os active to each device.  If the
131  * number of active i/os is < zfs_vdev_max_active, then the min_active comes
132  * into play. We will send min_active from each queue, and then select from
133  * queues in the order defined by zio_priority_t.
134  *
135  * In general, smaller max_active's will lead to lower latency of synchronous
136  * operations.  Larger max_active's may lead to higher overall throughput,
137  * depending on underlying storage.
138  *
139  * The ratio of the queues' max_actives determines the balance of performance
140  * between reads, writes, and scrubs.  E.g., increasing
141  * zfs_vdev_scrub_max_active will cause the scrub or resilver to complete
142  * more quickly, but reads and writes to have higher latency and lower
143  * throughput.
144  */
145 uint32_t zfs_vdev_sync_read_min_active = 10;
146 uint32_t zfs_vdev_sync_read_max_active = 10;
147 uint32_t zfs_vdev_sync_write_min_active = 10;
148 uint32_t zfs_vdev_sync_write_max_active = 10;
149 uint32_t zfs_vdev_async_read_min_active = 1;
150 uint32_t zfs_vdev_async_read_max_active = 3;
151 uint32_t zfs_vdev_async_write_min_active = 2;
152 uint32_t zfs_vdev_async_write_max_active = 10;
153 uint32_t zfs_vdev_scrub_min_active = 1;
154 uint32_t zfs_vdev_scrub_max_active = 2;
155 uint32_t zfs_vdev_removal_min_active = 1;
156 uint32_t zfs_vdev_removal_max_active = 2;
157 uint32_t zfs_vdev_initializing_min_active = 1;
158 uint32_t zfs_vdev_initializing_max_active = 1;
159 uint32_t zfs_vdev_trim_min_active = 1;
160 uint32_t zfs_vdev_trim_max_active = 2;
161
162 /*
163  * When the pool has less than zfs_vdev_async_write_active_min_dirty_percent
164  * dirty data, use zfs_vdev_async_write_min_active.  When it has more than
165  * zfs_vdev_async_write_active_max_dirty_percent, use
166  * zfs_vdev_async_write_max_active. The value is linearly interpolated
167  * between min and max.
168  */
169 int zfs_vdev_async_write_active_min_dirty_percent = 30;
170 int zfs_vdev_async_write_active_max_dirty_percent = 60;
171
172 /*
173  * To reduce IOPs, we aggregate small adjacent I/Os into one large I/O.
174  * For read I/Os, we also aggregate across small adjacency gaps; for writes
175  * we include spans of optional I/Os to aid aggregation at the disk even when
176  * they aren't able to help us aggregate at this level.
177  */
178 int zfs_vdev_aggregation_limit = 1 << 20;
179 int zfs_vdev_aggregation_limit_non_rotating = SPA_OLD_MAXBLOCKSIZE;
180 int zfs_vdev_read_gap_limit = 32 << 10;
181 int zfs_vdev_write_gap_limit = 4 << 10;
182
183 /*
184  * Define the queue depth percentage for each top-level. This percentage is
185  * used in conjunction with zfs_vdev_async_max_active to determine how many
186  * allocations a specific top-level vdev should handle. Once the queue depth
187  * reaches zfs_vdev_queue_depth_pct * zfs_vdev_async_write_max_active / 100
188  * then allocator will stop allocating blocks on that top-level device.
189  * The default kernel setting is 1000% which will yield 100 allocations per
190  * device. For userland testing, the default setting is 300% which equates
191  * to 30 allocations per device.
192  */
193 #ifdef _KERNEL
194 int zfs_vdev_queue_depth_pct = 1000;
195 #else
196 int zfs_vdev_queue_depth_pct = 300;
197 #endif
198
199 /*
200  * When performing allocations for a given metaslab, we want to make sure that
201  * there are enough IOs to aggregate together to improve throughput. We want to
202  * ensure that there are at least 128k worth of IOs that can be aggregated, and
203  * we assume that the average allocation size is 4k, so we need the queue depth
204  * to be 32 per allocator to get good aggregation of sequential writes.
205  */
206 int zfs_vdev_def_queue_depth = 32;
207
208 /*
209  * Allow TRIM I/Os to be aggregated.  This should normally not be needed since
210  * TRIM I/O for extents up to zfs_trim_extent_bytes_max (128M) can be submitted
211  * by the TRIM code in zfs_trim.c.
212  */
213 int zfs_vdev_aggregate_trim = 0;
214
215 int
216 vdev_queue_offset_compare(const void *x1, const void *x2)
217 {
218         const zio_t *z1 = (const zio_t *)x1;
219         const zio_t *z2 = (const zio_t *)x2;
220
221         int cmp = AVL_CMP(z1->io_offset, z2->io_offset);
222
223         if (likely(cmp))
224                 return (cmp);
225
226         return (AVL_PCMP(z1, z2));
227 }
228
229 static inline avl_tree_t *
230 vdev_queue_class_tree(vdev_queue_t *vq, zio_priority_t p)
231 {
232         return (&vq->vq_class[p].vqc_queued_tree);
233 }
234
235 static inline avl_tree_t *
236 vdev_queue_type_tree(vdev_queue_t *vq, zio_type_t t)
237 {
238         ASSERT(t == ZIO_TYPE_READ || t == ZIO_TYPE_WRITE || t == ZIO_TYPE_TRIM);
239         if (t == ZIO_TYPE_READ)
240                 return (&vq->vq_read_offset_tree);
241         else if (t == ZIO_TYPE_WRITE)
242                 return (&vq->vq_write_offset_tree);
243         else
244                 return (&vq->vq_trim_offset_tree);
245 }
246
247 int
248 vdev_queue_timestamp_compare(const void *x1, const void *x2)
249 {
250         const zio_t *z1 = (const zio_t *)x1;
251         const zio_t *z2 = (const zio_t *)x2;
252
253         int cmp = AVL_CMP(z1->io_timestamp, z2->io_timestamp);
254
255         if (likely(cmp))
256                 return (cmp);
257
258         return (AVL_PCMP(z1, z2));
259 }
260
261 static int
262 vdev_queue_class_min_active(zio_priority_t p)
263 {
264         switch (p) {
265         case ZIO_PRIORITY_SYNC_READ:
266                 return (zfs_vdev_sync_read_min_active);
267         case ZIO_PRIORITY_SYNC_WRITE:
268                 return (zfs_vdev_sync_write_min_active);
269         case ZIO_PRIORITY_ASYNC_READ:
270                 return (zfs_vdev_async_read_min_active);
271         case ZIO_PRIORITY_ASYNC_WRITE:
272                 return (zfs_vdev_async_write_min_active);
273         case ZIO_PRIORITY_SCRUB:
274                 return (zfs_vdev_scrub_min_active);
275         case ZIO_PRIORITY_REMOVAL:
276                 return (zfs_vdev_removal_min_active);
277         case ZIO_PRIORITY_INITIALIZING:
278                 return (zfs_vdev_initializing_min_active);
279         case ZIO_PRIORITY_TRIM:
280                 return (zfs_vdev_trim_min_active);
281         default:
282                 panic("invalid priority %u", p);
283                 return (0);
284         }
285 }
286
287 static int
288 vdev_queue_max_async_writes(spa_t *spa)
289 {
290         int writes;
291         uint64_t dirty = 0;
292         dsl_pool_t *dp = spa_get_dsl(spa);
293         uint64_t min_bytes = zfs_dirty_data_max *
294             zfs_vdev_async_write_active_min_dirty_percent / 100;
295         uint64_t max_bytes = zfs_dirty_data_max *
296             zfs_vdev_async_write_active_max_dirty_percent / 100;
297
298         /*
299          * Async writes may occur before the assignment of the spa's
300          * dsl_pool_t if a self-healing zio is issued prior to the
301          * completion of dmu_objset_open_impl().
302          */
303         if (dp == NULL)
304                 return (zfs_vdev_async_write_max_active);
305
306         /*
307          * Sync tasks correspond to interactive user actions. To reduce the
308          * execution time of those actions we push data out as fast as possible.
309          */
310         if (spa_has_pending_synctask(spa))
311                 return (zfs_vdev_async_write_max_active);
312
313         dirty = dp->dp_dirty_total;
314         if (dirty < min_bytes)
315                 return (zfs_vdev_async_write_min_active);
316         if (dirty > max_bytes)
317                 return (zfs_vdev_async_write_max_active);
318
319         /*
320          * linear interpolation:
321          * slope = (max_writes - min_writes) / (max_bytes - min_bytes)
322          * move right by min_bytes
323          * move up by min_writes
324          */
325         writes = (dirty - min_bytes) *
326             (zfs_vdev_async_write_max_active -
327             zfs_vdev_async_write_min_active) /
328             (max_bytes - min_bytes) +
329             zfs_vdev_async_write_min_active;
330         ASSERT3U(writes, >=, zfs_vdev_async_write_min_active);
331         ASSERT3U(writes, <=, zfs_vdev_async_write_max_active);
332         return (writes);
333 }
334
335 static int
336 vdev_queue_class_max_active(spa_t *spa, zio_priority_t p)
337 {
338         switch (p) {
339         case ZIO_PRIORITY_SYNC_READ:
340                 return (zfs_vdev_sync_read_max_active);
341         case ZIO_PRIORITY_SYNC_WRITE:
342                 return (zfs_vdev_sync_write_max_active);
343         case ZIO_PRIORITY_ASYNC_READ:
344                 return (zfs_vdev_async_read_max_active);
345         case ZIO_PRIORITY_ASYNC_WRITE:
346                 return (vdev_queue_max_async_writes(spa));
347         case ZIO_PRIORITY_SCRUB:
348                 return (zfs_vdev_scrub_max_active);
349         case ZIO_PRIORITY_REMOVAL:
350                 return (zfs_vdev_removal_max_active);
351         case ZIO_PRIORITY_INITIALIZING:
352                 return (zfs_vdev_initializing_max_active);
353         case ZIO_PRIORITY_TRIM:
354                 return (zfs_vdev_trim_max_active);
355         default:
356                 panic("invalid priority %u", p);
357                 return (0);
358         }
359 }
360
361 /*
362  * Return the i/o class to issue from, or ZIO_PRIORITY_MAX_QUEUEABLE if
363  * there is no eligible class.
364  */
365 static zio_priority_t
366 vdev_queue_class_to_issue(vdev_queue_t *vq)
367 {
368         spa_t *spa = vq->vq_vdev->vdev_spa;
369         zio_priority_t p;
370
371         if (avl_numnodes(&vq->vq_active_tree) >= zfs_vdev_max_active)
372                 return (ZIO_PRIORITY_NUM_QUEUEABLE);
373
374         /* find a queue that has not reached its minimum # outstanding i/os */
375         for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
376                 if (avl_numnodes(vdev_queue_class_tree(vq, p)) > 0 &&
377                     vq->vq_class[p].vqc_active <
378                     vdev_queue_class_min_active(p))
379                         return (p);
380         }
381
382         /*
383          * If we haven't found a queue, look for one that hasn't reached its
384          * maximum # outstanding i/os.
385          */
386         for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
387                 if (avl_numnodes(vdev_queue_class_tree(vq, p)) > 0 &&
388                     vq->vq_class[p].vqc_active <
389                     vdev_queue_class_max_active(spa, p))
390                         return (p);
391         }
392
393         /* No eligible queued i/os */
394         return (ZIO_PRIORITY_NUM_QUEUEABLE);
395 }
396
397 void
398 vdev_queue_init(vdev_t *vd)
399 {
400         vdev_queue_t *vq = &vd->vdev_queue;
401         zio_priority_t p;
402
403         mutex_init(&vq->vq_lock, NULL, MUTEX_DEFAULT, NULL);
404         vq->vq_vdev = vd;
405         taskq_init_ent(&vd->vdev_queue.vq_io_search.io_tqent);
406
407         avl_create(&vq->vq_active_tree, vdev_queue_offset_compare,
408             sizeof (zio_t), offsetof(struct zio, io_queue_node));
409         avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_READ),
410             vdev_queue_offset_compare, sizeof (zio_t),
411             offsetof(struct zio, io_offset_node));
412         avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_WRITE),
413             vdev_queue_offset_compare, sizeof (zio_t),
414             offsetof(struct zio, io_offset_node));
415         avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_TRIM),
416             vdev_queue_offset_compare, sizeof (zio_t),
417             offsetof(struct zio, io_offset_node));
418
419         for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
420                 int (*compfn) (const void *, const void *);
421
422                 /*
423                  * The synchronous/trim i/o queues are dispatched in FIFO rather
424                  * than LBA order. This provides more consistent latency for
425                  * these i/os.
426                  */
427                 if (p == ZIO_PRIORITY_SYNC_READ ||
428                     p == ZIO_PRIORITY_SYNC_WRITE ||
429                     p == ZIO_PRIORITY_TRIM) {
430                         compfn = vdev_queue_timestamp_compare;
431                 } else {
432                         compfn = vdev_queue_offset_compare;
433                 }
434                 avl_create(vdev_queue_class_tree(vq, p), compfn,
435                     sizeof (zio_t), offsetof(struct zio, io_queue_node));
436         }
437
438         vq->vq_last_offset = 0;
439 }
440
441 void
442 vdev_queue_fini(vdev_t *vd)
443 {
444         vdev_queue_t *vq = &vd->vdev_queue;
445
446         for (zio_priority_t p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++)
447                 avl_destroy(vdev_queue_class_tree(vq, p));
448         avl_destroy(&vq->vq_active_tree);
449         avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_READ));
450         avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_WRITE));
451         avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_TRIM));
452
453         mutex_destroy(&vq->vq_lock);
454 }
455
456 static void
457 vdev_queue_io_add(vdev_queue_t *vq, zio_t *zio)
458 {
459         spa_t *spa = zio->io_spa;
460         spa_history_kstat_t *shk = &spa->spa_stats.io_history;
461
462         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
463         avl_add(vdev_queue_class_tree(vq, zio->io_priority), zio);
464         avl_add(vdev_queue_type_tree(vq, zio->io_type), zio);
465
466         if (shk->kstat != NULL) {
467                 mutex_enter(&shk->lock);
468                 kstat_waitq_enter(shk->kstat->ks_data);
469                 mutex_exit(&shk->lock);
470         }
471 }
472
473 static void
474 vdev_queue_io_remove(vdev_queue_t *vq, zio_t *zio)
475 {
476         spa_t *spa = zio->io_spa;
477         spa_history_kstat_t *shk = &spa->spa_stats.io_history;
478
479         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
480         avl_remove(vdev_queue_class_tree(vq, zio->io_priority), zio);
481         avl_remove(vdev_queue_type_tree(vq, zio->io_type), zio);
482
483         if (shk->kstat != NULL) {
484                 mutex_enter(&shk->lock);
485                 kstat_waitq_exit(shk->kstat->ks_data);
486                 mutex_exit(&shk->lock);
487         }
488 }
489
490 static void
491 vdev_queue_pending_add(vdev_queue_t *vq, zio_t *zio)
492 {
493         spa_t *spa = zio->io_spa;
494         spa_history_kstat_t *shk = &spa->spa_stats.io_history;
495
496         ASSERT(MUTEX_HELD(&vq->vq_lock));
497         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
498         vq->vq_class[zio->io_priority].vqc_active++;
499         avl_add(&vq->vq_active_tree, zio);
500
501         if (shk->kstat != NULL) {
502                 mutex_enter(&shk->lock);
503                 kstat_runq_enter(shk->kstat->ks_data);
504                 mutex_exit(&shk->lock);
505         }
506 }
507
508 static void
509 vdev_queue_pending_remove(vdev_queue_t *vq, zio_t *zio)
510 {
511         spa_t *spa = zio->io_spa;
512         spa_history_kstat_t *shk = &spa->spa_stats.io_history;
513
514         ASSERT(MUTEX_HELD(&vq->vq_lock));
515         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
516         vq->vq_class[zio->io_priority].vqc_active--;
517         avl_remove(&vq->vq_active_tree, zio);
518
519         if (shk->kstat != NULL) {
520                 kstat_io_t *ksio = shk->kstat->ks_data;
521
522                 mutex_enter(&shk->lock);
523                 kstat_runq_exit(ksio);
524                 if (zio->io_type == ZIO_TYPE_READ) {
525                         ksio->reads++;
526                         ksio->nread += zio->io_size;
527                 } else if (zio->io_type == ZIO_TYPE_WRITE) {
528                         ksio->writes++;
529                         ksio->nwritten += zio->io_size;
530                 }
531                 mutex_exit(&shk->lock);
532         }
533 }
534
535 static void
536 vdev_queue_agg_io_done(zio_t *aio)
537 {
538         if (aio->io_type == ZIO_TYPE_READ) {
539                 zio_t *pio;
540                 zio_link_t *zl = NULL;
541                 while ((pio = zio_walk_parents(aio, &zl)) != NULL) {
542                         abd_copy_off(pio->io_abd, aio->io_abd,
543                             0, pio->io_offset - aio->io_offset, pio->io_size);
544                 }
545         }
546
547         abd_free(aio->io_abd);
548 }
549
550 /*
551  * Compute the range spanned by two i/os, which is the endpoint of the last
552  * (lio->io_offset + lio->io_size) minus start of the first (fio->io_offset).
553  * Conveniently, the gap between fio and lio is given by -IO_SPAN(lio, fio);
554  * thus fio and lio are adjacent if and only if IO_SPAN(lio, fio) == 0.
555  */
556 #define IO_SPAN(fio, lio) ((lio)->io_offset + (lio)->io_size - (fio)->io_offset)
557 #define IO_GAP(fio, lio) (-IO_SPAN(lio, fio))
558
559 static zio_t *
560 vdev_queue_aggregate(vdev_queue_t *vq, zio_t *zio)
561 {
562         zio_t *first, *last, *aio, *dio, *mandatory, *nio;
563         zio_link_t *zl = NULL;
564         uint64_t maxgap = 0;
565         uint64_t size;
566         uint64_t limit;
567         int maxblocksize;
568         boolean_t stretch = B_FALSE;
569         avl_tree_t *t = vdev_queue_type_tree(vq, zio->io_type);
570         enum zio_flag flags = zio->io_flags & ZIO_FLAG_AGG_INHERIT;
571         abd_t *abd;
572
573         maxblocksize = spa_maxblocksize(vq->vq_vdev->vdev_spa);
574         if (vq->vq_vdev->vdev_nonrot)
575                 limit = zfs_vdev_aggregation_limit_non_rotating;
576         else
577                 limit = zfs_vdev_aggregation_limit;
578         limit = MAX(MIN(limit, maxblocksize), 0);
579
580         if (zio->io_flags & ZIO_FLAG_DONT_AGGREGATE || limit == 0)
581                 return (NULL);
582
583         /*
584          * While TRIM commands could be aggregated based on offset this
585          * behavior is disabled until it's determined to be beneficial.
586          */
587         if (zio->io_type == ZIO_TYPE_TRIM && !zfs_vdev_aggregate_trim)
588                 return (NULL);
589
590         first = last = zio;
591
592         if (zio->io_type == ZIO_TYPE_READ)
593                 maxgap = zfs_vdev_read_gap_limit;
594
595         /*
596          * We can aggregate I/Os that are sufficiently adjacent and of
597          * the same flavor, as expressed by the AGG_INHERIT flags.
598          * The latter requirement is necessary so that certain
599          * attributes of the I/O, such as whether it's a normal I/O
600          * or a scrub/resilver, can be preserved in the aggregate.
601          * We can include optional I/Os, but don't allow them
602          * to begin a range as they add no benefit in that situation.
603          */
604
605         /*
606          * We keep track of the last non-optional I/O.
607          */
608         mandatory = (first->io_flags & ZIO_FLAG_OPTIONAL) ? NULL : first;
609
610         /*
611          * Walk backwards through sufficiently contiguous I/Os
612          * recording the last non-optional I/O.
613          */
614         while ((dio = AVL_PREV(t, first)) != NULL &&
615             (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
616             IO_SPAN(dio, last) <= limit &&
617             IO_GAP(dio, first) <= maxgap &&
618             dio->io_type == zio->io_type) {
619                 first = dio;
620                 if (mandatory == NULL && !(first->io_flags & ZIO_FLAG_OPTIONAL))
621                         mandatory = first;
622         }
623
624         /*
625          * Skip any initial optional I/Os.
626          */
627         while ((first->io_flags & ZIO_FLAG_OPTIONAL) && first != last) {
628                 first = AVL_NEXT(t, first);
629                 ASSERT(first != NULL);
630         }
631
632
633         /*
634          * Walk forward through sufficiently contiguous I/Os.
635          * The aggregation limit does not apply to optional i/os, so that
636          * we can issue contiguous writes even if they are larger than the
637          * aggregation limit.
638          */
639         while ((dio = AVL_NEXT(t, last)) != NULL &&
640             (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
641             (IO_SPAN(first, dio) <= limit ||
642             (dio->io_flags & ZIO_FLAG_OPTIONAL)) &&
643             IO_SPAN(first, dio) <= maxblocksize &&
644             IO_GAP(last, dio) <= maxgap &&
645             dio->io_type == zio->io_type) {
646                 last = dio;
647                 if (!(last->io_flags & ZIO_FLAG_OPTIONAL))
648                         mandatory = last;
649         }
650
651         /*
652          * Now that we've established the range of the I/O aggregation
653          * we must decide what to do with trailing optional I/Os.
654          * For reads, there's nothing to do. While we are unable to
655          * aggregate further, it's possible that a trailing optional
656          * I/O would allow the underlying device to aggregate with
657          * subsequent I/Os. We must therefore determine if the next
658          * non-optional I/O is close enough to make aggregation
659          * worthwhile.
660          */
661         if (zio->io_type == ZIO_TYPE_WRITE && mandatory != NULL) {
662                 zio_t *nio = last;
663                 while ((dio = AVL_NEXT(t, nio)) != NULL &&
664                     IO_GAP(nio, dio) == 0 &&
665                     IO_GAP(mandatory, dio) <= zfs_vdev_write_gap_limit) {
666                         nio = dio;
667                         if (!(nio->io_flags & ZIO_FLAG_OPTIONAL)) {
668                                 stretch = B_TRUE;
669                                 break;
670                         }
671                 }
672         }
673
674         if (stretch) {
675                 /*
676                  * We are going to include an optional io in our aggregated
677                  * span, thus closing the write gap.  Only mandatory i/os can
678                  * start aggregated spans, so make sure that the next i/o
679                  * after our span is mandatory.
680                  */
681                 dio = AVL_NEXT(t, last);
682                 dio->io_flags &= ~ZIO_FLAG_OPTIONAL;
683         } else {
684                 /* do not include the optional i/o */
685                 while (last != mandatory && last != first) {
686                         ASSERT(last->io_flags & ZIO_FLAG_OPTIONAL);
687                         last = AVL_PREV(t, last);
688                         ASSERT(last != NULL);
689                 }
690         }
691
692         if (first == last)
693                 return (NULL);
694
695         size = IO_SPAN(first, last);
696         ASSERT3U(size, <=, maxblocksize);
697
698         abd = abd_alloc_for_io(size, B_TRUE);
699         if (abd == NULL)
700                 return (NULL);
701
702         aio = zio_vdev_delegated_io(first->io_vd, first->io_offset,
703             abd, size, first->io_type, zio->io_priority,
704             flags | ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE,
705             vdev_queue_agg_io_done, NULL);
706         aio->io_timestamp = first->io_timestamp;
707
708         nio = first;
709         do {
710                 dio = nio;
711                 nio = AVL_NEXT(t, dio);
712                 zio_add_child(dio, aio);
713                 vdev_queue_io_remove(vq, dio);
714         } while (dio != last);
715
716         /*
717          * We need to drop the vdev queue's lock during zio_execute() to
718          * avoid a deadlock that we could encounter due to lock order
719          * reversal between vq_lock and io_lock in zio_change_priority().
720          * Use the dropped lock to do memory copy without congestion.
721          */
722         mutex_exit(&vq->vq_lock);
723         while ((dio = zio_walk_parents(aio, &zl)) != NULL) {
724                 ASSERT3U(dio->io_type, ==, aio->io_type);
725
726                 if (dio->io_flags & ZIO_FLAG_NODATA) {
727                         ASSERT3U(dio->io_type, ==, ZIO_TYPE_WRITE);
728                         abd_zero_off(aio->io_abd,
729                             dio->io_offset - aio->io_offset, dio->io_size);
730                 } else if (dio->io_type == ZIO_TYPE_WRITE) {
731                         abd_copy_off(aio->io_abd, dio->io_abd,
732                             dio->io_offset - aio->io_offset, 0, dio->io_size);
733                 }
734
735                 zio_vdev_io_bypass(dio);
736                 zio_execute(dio);
737         }
738         mutex_enter(&vq->vq_lock);
739
740         return (aio);
741 }
742
743 static zio_t *
744 vdev_queue_io_to_issue(vdev_queue_t *vq)
745 {
746         zio_t *zio, *aio;
747         zio_priority_t p;
748         avl_index_t idx;
749         avl_tree_t *tree;
750
751 again:
752         ASSERT(MUTEX_HELD(&vq->vq_lock));
753
754         p = vdev_queue_class_to_issue(vq);
755
756         if (p == ZIO_PRIORITY_NUM_QUEUEABLE) {
757                 /* No eligible queued i/os */
758                 return (NULL);
759         }
760
761         /*
762          * For LBA-ordered queues (async / scrub / initializing), issue the
763          * i/o which follows the most recently issued i/o in LBA (offset) order.
764          *
765          * For FIFO queues (sync/trim), issue the i/o with the lowest timestamp.
766          */
767         tree = vdev_queue_class_tree(vq, p);
768         vq->vq_io_search.io_timestamp = 0;
769         vq->vq_io_search.io_offset = vq->vq_last_offset - 1;
770         VERIFY3P(avl_find(tree, &vq->vq_io_search, &idx), ==, NULL);
771         zio = avl_nearest(tree, idx, AVL_AFTER);
772         if (zio == NULL)
773                 zio = avl_first(tree);
774         ASSERT3U(zio->io_priority, ==, p);
775
776         aio = vdev_queue_aggregate(vq, zio);
777         if (aio != NULL)
778                 zio = aio;
779         else
780                 vdev_queue_io_remove(vq, zio);
781
782         /*
783          * If the I/O is or was optional and therefore has no data, we need to
784          * simply discard it. We need to drop the vdev queue's lock to avoid a
785          * deadlock that we could encounter since this I/O will complete
786          * immediately.
787          */
788         if (zio->io_flags & ZIO_FLAG_NODATA) {
789                 mutex_exit(&vq->vq_lock);
790                 zio_vdev_io_bypass(zio);
791                 zio_execute(zio);
792                 mutex_enter(&vq->vq_lock);
793                 goto again;
794         }
795
796         vdev_queue_pending_add(vq, zio);
797         vq->vq_last_offset = zio->io_offset + zio->io_size;
798
799         return (zio);
800 }
801
802 zio_t *
803 vdev_queue_io(zio_t *zio)
804 {
805         vdev_queue_t *vq = &zio->io_vd->vdev_queue;
806         zio_t *nio;
807
808         if (zio->io_flags & ZIO_FLAG_DONT_QUEUE)
809                 return (zio);
810
811         /*
812          * Children i/os inherent their parent's priority, which might
813          * not match the child's i/o type.  Fix it up here.
814          */
815         if (zio->io_type == ZIO_TYPE_READ) {
816                 ASSERT(zio->io_priority != ZIO_PRIORITY_TRIM);
817
818                 if (zio->io_priority != ZIO_PRIORITY_SYNC_READ &&
819                     zio->io_priority != ZIO_PRIORITY_ASYNC_READ &&
820                     zio->io_priority != ZIO_PRIORITY_SCRUB &&
821                     zio->io_priority != ZIO_PRIORITY_REMOVAL &&
822                     zio->io_priority != ZIO_PRIORITY_INITIALIZING) {
823                         zio->io_priority = ZIO_PRIORITY_ASYNC_READ;
824                 }
825         } else if (zio->io_type == ZIO_TYPE_WRITE) {
826                 ASSERT(zio->io_priority != ZIO_PRIORITY_TRIM);
827
828                 if (zio->io_priority != ZIO_PRIORITY_SYNC_WRITE &&
829                     zio->io_priority != ZIO_PRIORITY_ASYNC_WRITE &&
830                     zio->io_priority != ZIO_PRIORITY_REMOVAL &&
831                     zio->io_priority != ZIO_PRIORITY_INITIALIZING) {
832                         zio->io_priority = ZIO_PRIORITY_ASYNC_WRITE;
833                 }
834         } else {
835                 ASSERT(zio->io_type == ZIO_TYPE_TRIM);
836                 ASSERT(zio->io_priority == ZIO_PRIORITY_TRIM);
837         }
838
839         zio->io_flags |= ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE;
840
841         mutex_enter(&vq->vq_lock);
842         zio->io_timestamp = gethrtime();
843         vdev_queue_io_add(vq, zio);
844         nio = vdev_queue_io_to_issue(vq);
845         mutex_exit(&vq->vq_lock);
846
847         if (nio == NULL)
848                 return (NULL);
849
850         if (nio->io_done == vdev_queue_agg_io_done) {
851                 zio_nowait(nio);
852                 return (NULL);
853         }
854
855         return (nio);
856 }
857
858 void
859 vdev_queue_io_done(zio_t *zio)
860 {
861         vdev_queue_t *vq = &zio->io_vd->vdev_queue;
862         zio_t *nio;
863
864         mutex_enter(&vq->vq_lock);
865
866         vdev_queue_pending_remove(vq, zio);
867
868         zio->io_delta = gethrtime() - zio->io_timestamp;
869         vq->vq_io_complete_ts = gethrtime();
870         vq->vq_io_delta_ts = vq->vq_io_complete_ts - zio->io_timestamp;
871
872         while ((nio = vdev_queue_io_to_issue(vq)) != NULL) {
873                 mutex_exit(&vq->vq_lock);
874                 if (nio->io_done == vdev_queue_agg_io_done) {
875                         zio_nowait(nio);
876                 } else {
877                         zio_vdev_io_reissue(nio);
878                         zio_execute(nio);
879                 }
880                 mutex_enter(&vq->vq_lock);
881         }
882
883         mutex_exit(&vq->vq_lock);
884 }
885
886 void
887 vdev_queue_change_io_priority(zio_t *zio, zio_priority_t priority)
888 {
889         vdev_queue_t *vq = &zio->io_vd->vdev_queue;
890         avl_tree_t *tree;
891
892         /*
893          * ZIO_PRIORITY_NOW is used by the vdev cache code and the aggregate zio
894          * code to issue IOs without adding them to the vdev queue. In this
895          * case, the zio is already going to be issued as quickly as possible
896          * and so it doesn't need any reprioitization to help.
897          */
898         if (zio->io_priority == ZIO_PRIORITY_NOW)
899                 return;
900
901         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
902         ASSERT3U(priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
903
904         if (zio->io_type == ZIO_TYPE_READ) {
905                 if (priority != ZIO_PRIORITY_SYNC_READ &&
906                     priority != ZIO_PRIORITY_ASYNC_READ &&
907                     priority != ZIO_PRIORITY_SCRUB)
908                         priority = ZIO_PRIORITY_ASYNC_READ;
909         } else {
910                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
911                 if (priority != ZIO_PRIORITY_SYNC_WRITE &&
912                     priority != ZIO_PRIORITY_ASYNC_WRITE)
913                         priority = ZIO_PRIORITY_ASYNC_WRITE;
914         }
915
916         mutex_enter(&vq->vq_lock);
917
918         /*
919          * If the zio is in none of the queues we can simply change
920          * the priority. If the zio is waiting to be submitted we must
921          * remove it from the queue and re-insert it with the new priority.
922          * Otherwise, the zio is currently active and we cannot change its
923          * priority.
924          */
925         tree = vdev_queue_class_tree(vq, zio->io_priority);
926         if (avl_find(tree, zio, NULL) == zio) {
927                 avl_remove(vdev_queue_class_tree(vq, zio->io_priority), zio);
928                 zio->io_priority = priority;
929                 avl_add(vdev_queue_class_tree(vq, zio->io_priority), zio);
930         } else if (avl_find(&vq->vq_active_tree, zio, NULL) != zio) {
931                 zio->io_priority = priority;
932         }
933
934         mutex_exit(&vq->vq_lock);
935 }
936
937 /*
938  * As these two methods are only used for load calculations we're not
939  * concerned if we get an incorrect value on 32bit platforms due to lack of
940  * vq_lock mutex use here, instead we prefer to keep it lock free for
941  * performance.
942  */
943 int
944 vdev_queue_length(vdev_t *vd)
945 {
946         return (avl_numnodes(&vd->vdev_queue.vq_active_tree));
947 }
948
949 uint64_t
950 vdev_queue_last_offset(vdev_t *vd)
951 {
952         return (vd->vdev_queue.vq_last_offset);
953 }
954
955 #if defined(_KERNEL)
956 module_param(zfs_vdev_aggregation_limit, int, 0644);
957 MODULE_PARM_DESC(zfs_vdev_aggregation_limit, "Max vdev I/O aggregation size");
958
959 module_param(zfs_vdev_aggregation_limit_non_rotating, int, 0644);
960 MODULE_PARM_DESC(zfs_vdev_aggregation_limit_non_rotating,
961         "Max vdev I/O aggregation size for non-rotating media");
962
963 module_param(zfs_vdev_aggregate_trim, int, 0644);
964 MODULE_PARM_DESC(zfs_vdev_aggregate_trim, "Allow TRIM I/O to be aggregated");
965
966 module_param(zfs_vdev_read_gap_limit, int, 0644);
967 MODULE_PARM_DESC(zfs_vdev_read_gap_limit, "Aggregate read I/O over gap");
968
969 module_param(zfs_vdev_write_gap_limit, int, 0644);
970 MODULE_PARM_DESC(zfs_vdev_write_gap_limit, "Aggregate write I/O over gap");
971
972 module_param(zfs_vdev_max_active, int, 0644);
973 MODULE_PARM_DESC(zfs_vdev_max_active, "Maximum number of active I/Os per vdev");
974
975 module_param(zfs_vdev_async_write_active_max_dirty_percent, int, 0644);
976 MODULE_PARM_DESC(zfs_vdev_async_write_active_max_dirty_percent,
977         "Async write concurrency max threshold");
978
979 module_param(zfs_vdev_async_write_active_min_dirty_percent, int, 0644);
980 MODULE_PARM_DESC(zfs_vdev_async_write_active_min_dirty_percent,
981         "Async write concurrency min threshold");
982
983 module_param(zfs_vdev_async_read_max_active, int, 0644);
984 MODULE_PARM_DESC(zfs_vdev_async_read_max_active,
985         "Max active async read I/Os per vdev");
986
987 module_param(zfs_vdev_async_read_min_active, int, 0644);
988 MODULE_PARM_DESC(zfs_vdev_async_read_min_active,
989         "Min active async read I/Os per vdev");
990
991 module_param(zfs_vdev_async_write_max_active, int, 0644);
992 MODULE_PARM_DESC(zfs_vdev_async_write_max_active,
993         "Max active async write I/Os per vdev");
994
995 module_param(zfs_vdev_async_write_min_active, int, 0644);
996 MODULE_PARM_DESC(zfs_vdev_async_write_min_active,
997         "Min active async write I/Os per vdev");
998
999 module_param(zfs_vdev_initializing_max_active, int, 0644);
1000 MODULE_PARM_DESC(zfs_vdev_initializing_max_active,
1001         "Max active initializing I/Os per vdev");
1002
1003 module_param(zfs_vdev_initializing_min_active, int, 0644);
1004 MODULE_PARM_DESC(zfs_vdev_initializing_min_active,
1005         "Min active initializing I/Os per vdev");
1006
1007 module_param(zfs_vdev_removal_max_active, int, 0644);
1008 MODULE_PARM_DESC(zfs_vdev_removal_max_active,
1009         "Max active removal I/Os per vdev");
1010
1011 module_param(zfs_vdev_removal_min_active, int, 0644);
1012 MODULE_PARM_DESC(zfs_vdev_removal_min_active,
1013         "Min active removal I/Os per vdev");
1014
1015 module_param(zfs_vdev_scrub_max_active, int, 0644);
1016 MODULE_PARM_DESC(zfs_vdev_scrub_max_active,
1017         "Max active scrub I/Os per vdev");
1018
1019 module_param(zfs_vdev_scrub_min_active, int, 0644);
1020 MODULE_PARM_DESC(zfs_vdev_scrub_min_active,
1021         "Min active scrub I/Os per vdev");
1022
1023 module_param(zfs_vdev_sync_read_max_active, int, 0644);
1024 MODULE_PARM_DESC(zfs_vdev_sync_read_max_active,
1025         "Max active sync read I/Os per vdev");
1026
1027 module_param(zfs_vdev_sync_read_min_active, int, 0644);
1028 MODULE_PARM_DESC(zfs_vdev_sync_read_min_active,
1029         "Min active sync read I/Os per vdev");
1030
1031 module_param(zfs_vdev_sync_write_max_active, int, 0644);
1032 MODULE_PARM_DESC(zfs_vdev_sync_write_max_active,
1033         "Max active sync write I/Os per vdev");
1034
1035 module_param(zfs_vdev_sync_write_min_active, int, 0644);
1036 MODULE_PARM_DESC(zfs_vdev_sync_write_min_active,
1037         "Min active sync write I/Os per vdev");
1038
1039 module_param(zfs_vdev_trim_max_active, int, 0644);
1040 MODULE_PARM_DESC(zfs_vdev_trim_max_active,
1041         "Max active trim/discard I/Os per vdev");
1042
1043 module_param(zfs_vdev_trim_min_active, int, 0644);
1044 MODULE_PARM_DESC(zfs_vdev_trim_min_active,
1045         "Min active trim/discard I/Os per vdev");
1046
1047 module_param(zfs_vdev_queue_depth_pct, int, 0644);
1048 MODULE_PARM_DESC(zfs_vdev_queue_depth_pct,
1049         "Queue depth percentage for each top-level vdev");
1050 #endif