]> granicus.if.org Git - zfs/blob - module/zfs/vdev_queue.c
Fix 0 byte memory leak in zfs receive
[zfs] / 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
160 /*
161  * When the pool has less than zfs_vdev_async_write_active_min_dirty_percent
162  * dirty data, use zfs_vdev_async_write_min_active.  When it has more than
163  * zfs_vdev_async_write_active_max_dirty_percent, use
164  * zfs_vdev_async_write_max_active. The value is linearly interpolated
165  * between min and max.
166  */
167 int zfs_vdev_async_write_active_min_dirty_percent = 30;
168 int zfs_vdev_async_write_active_max_dirty_percent = 60;
169
170 /*
171  * To reduce IOPs, we aggregate small adjacent I/Os into one large I/O.
172  * For read I/Os, we also aggregate across small adjacency gaps; for writes
173  * we include spans of optional I/Os to aid aggregation at the disk even when
174  * they aren't able to help us aggregate at this level.
175  */
176 int zfs_vdev_aggregation_limit = 1 << 20;
177 int zfs_vdev_read_gap_limit = 32 << 10;
178 int zfs_vdev_write_gap_limit = 4 << 10;
179
180 /*
181  * Define the queue depth percentage for each top-level. This percentage is
182  * used in conjunction with zfs_vdev_async_max_active to determine how many
183  * allocations a specific top-level vdev should handle. Once the queue depth
184  * reaches zfs_vdev_queue_depth_pct * zfs_vdev_async_write_max_active / 100
185  * then allocator will stop allocating blocks on that top-level device.
186  * The default kernel setting is 1000% which will yield 100 allocations per
187  * device. For userland testing, the default setting is 300% which equates
188  * to 30 allocations per device.
189  */
190 #ifdef _KERNEL
191 int zfs_vdev_queue_depth_pct = 1000;
192 #else
193 int zfs_vdev_queue_depth_pct = 300;
194 #endif
195
196 /*
197  * When performing allocations for a given metaslab, we want to make sure that
198  * there are enough IOs to aggregate together to improve throughput. We want to
199  * ensure that there are at least 128k worth of IOs that can be aggregated, and
200  * we assume that the average allocation size is 4k, so we need the queue depth
201  * to be 32 per allocator to get good aggregation of sequential writes.
202  */
203 int zfs_vdev_def_queue_depth = 32;
204
205
206 int
207 vdev_queue_offset_compare(const void *x1, const void *x2)
208 {
209         const zio_t *z1 = (const zio_t *)x1;
210         const zio_t *z2 = (const zio_t *)x2;
211
212         int cmp = AVL_CMP(z1->io_offset, z2->io_offset);
213
214         if (likely(cmp))
215                 return (cmp);
216
217         return (AVL_PCMP(z1, z2));
218 }
219
220 static inline avl_tree_t *
221 vdev_queue_class_tree(vdev_queue_t *vq, zio_priority_t p)
222 {
223         return (&vq->vq_class[p].vqc_queued_tree);
224 }
225
226 static inline avl_tree_t *
227 vdev_queue_type_tree(vdev_queue_t *vq, zio_type_t t)
228 {
229         ASSERT(t == ZIO_TYPE_READ || t == ZIO_TYPE_WRITE);
230         if (t == ZIO_TYPE_READ)
231                 return (&vq->vq_read_offset_tree);
232         else
233                 return (&vq->vq_write_offset_tree);
234 }
235
236 int
237 vdev_queue_timestamp_compare(const void *x1, const void *x2)
238 {
239         const zio_t *z1 = (const zio_t *)x1;
240         const zio_t *z2 = (const zio_t *)x2;
241
242         int cmp = AVL_CMP(z1->io_timestamp, z2->io_timestamp);
243
244         if (likely(cmp))
245                 return (cmp);
246
247         return (AVL_PCMP(z1, z2));
248 }
249
250 static int
251 vdev_queue_class_min_active(zio_priority_t p)
252 {
253         switch (p) {
254         case ZIO_PRIORITY_SYNC_READ:
255                 return (zfs_vdev_sync_read_min_active);
256         case ZIO_PRIORITY_SYNC_WRITE:
257                 return (zfs_vdev_sync_write_min_active);
258         case ZIO_PRIORITY_ASYNC_READ:
259                 return (zfs_vdev_async_read_min_active);
260         case ZIO_PRIORITY_ASYNC_WRITE:
261                 return (zfs_vdev_async_write_min_active);
262         case ZIO_PRIORITY_SCRUB:
263                 return (zfs_vdev_scrub_min_active);
264         case ZIO_PRIORITY_REMOVAL:
265                 return (zfs_vdev_removal_min_active);
266         case ZIO_PRIORITY_INITIALIZING:
267                 return (zfs_vdev_initializing_min_active);
268         default:
269                 panic("invalid priority %u", p);
270                 return (0);
271         }
272 }
273
274 static int
275 vdev_queue_max_async_writes(spa_t *spa)
276 {
277         int writes;
278         uint64_t dirty = 0;
279         dsl_pool_t *dp = spa_get_dsl(spa);
280         uint64_t min_bytes = zfs_dirty_data_max *
281             zfs_vdev_async_write_active_min_dirty_percent / 100;
282         uint64_t max_bytes = zfs_dirty_data_max *
283             zfs_vdev_async_write_active_max_dirty_percent / 100;
284
285         /*
286          * Async writes may occur before the assignment of the spa's
287          * dsl_pool_t if a self-healing zio is issued prior to the
288          * completion of dmu_objset_open_impl().
289          */
290         if (dp == NULL)
291                 return (zfs_vdev_async_write_max_active);
292
293         /*
294          * Sync tasks correspond to interactive user actions. To reduce the
295          * execution time of those actions we push data out as fast as possible.
296          */
297         if (spa_has_pending_synctask(spa))
298                 return (zfs_vdev_async_write_max_active);
299
300         dirty = dp->dp_dirty_total;
301         if (dirty < min_bytes)
302                 return (zfs_vdev_async_write_min_active);
303         if (dirty > max_bytes)
304                 return (zfs_vdev_async_write_max_active);
305
306         /*
307          * linear interpolation:
308          * slope = (max_writes - min_writes) / (max_bytes - min_bytes)
309          * move right by min_bytes
310          * move up by min_writes
311          */
312         writes = (dirty - min_bytes) *
313             (zfs_vdev_async_write_max_active -
314             zfs_vdev_async_write_min_active) /
315             (max_bytes - min_bytes) +
316             zfs_vdev_async_write_min_active;
317         ASSERT3U(writes, >=, zfs_vdev_async_write_min_active);
318         ASSERT3U(writes, <=, zfs_vdev_async_write_max_active);
319         return (writes);
320 }
321
322 static int
323 vdev_queue_class_max_active(spa_t *spa, zio_priority_t p)
324 {
325         switch (p) {
326         case ZIO_PRIORITY_SYNC_READ:
327                 return (zfs_vdev_sync_read_max_active);
328         case ZIO_PRIORITY_SYNC_WRITE:
329                 return (zfs_vdev_sync_write_max_active);
330         case ZIO_PRIORITY_ASYNC_READ:
331                 return (zfs_vdev_async_read_max_active);
332         case ZIO_PRIORITY_ASYNC_WRITE:
333                 return (vdev_queue_max_async_writes(spa));
334         case ZIO_PRIORITY_SCRUB:
335                 return (zfs_vdev_scrub_max_active);
336         case ZIO_PRIORITY_REMOVAL:
337                 return (zfs_vdev_removal_max_active);
338         case ZIO_PRIORITY_INITIALIZING:
339                 return (zfs_vdev_initializing_max_active);
340         default:
341                 panic("invalid priority %u", p);
342                 return (0);
343         }
344 }
345
346 /*
347  * Return the i/o class to issue from, or ZIO_PRIORITY_MAX_QUEUEABLE if
348  * there is no eligible class.
349  */
350 static zio_priority_t
351 vdev_queue_class_to_issue(vdev_queue_t *vq)
352 {
353         spa_t *spa = vq->vq_vdev->vdev_spa;
354         zio_priority_t p;
355
356         if (avl_numnodes(&vq->vq_active_tree) >= zfs_vdev_max_active)
357                 return (ZIO_PRIORITY_NUM_QUEUEABLE);
358
359         /* find a queue that has not reached its minimum # outstanding i/os */
360         for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
361                 if (avl_numnodes(vdev_queue_class_tree(vq, p)) > 0 &&
362                     vq->vq_class[p].vqc_active <
363                     vdev_queue_class_min_active(p))
364                         return (p);
365         }
366
367         /*
368          * If we haven't found a queue, look for one that hasn't reached its
369          * maximum # outstanding i/os.
370          */
371         for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
372                 if (avl_numnodes(vdev_queue_class_tree(vq, p)) > 0 &&
373                     vq->vq_class[p].vqc_active <
374                     vdev_queue_class_max_active(spa, p))
375                         return (p);
376         }
377
378         /* No eligible queued i/os */
379         return (ZIO_PRIORITY_NUM_QUEUEABLE);
380 }
381
382 void
383 vdev_queue_init(vdev_t *vd)
384 {
385         vdev_queue_t *vq = &vd->vdev_queue;
386         zio_priority_t p;
387
388         mutex_init(&vq->vq_lock, NULL, MUTEX_DEFAULT, NULL);
389         vq->vq_vdev = vd;
390         taskq_init_ent(&vd->vdev_queue.vq_io_search.io_tqent);
391
392         avl_create(&vq->vq_active_tree, vdev_queue_offset_compare,
393             sizeof (zio_t), offsetof(struct zio, io_queue_node));
394         avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_READ),
395             vdev_queue_offset_compare, sizeof (zio_t),
396             offsetof(struct zio, io_offset_node));
397         avl_create(vdev_queue_type_tree(vq, ZIO_TYPE_WRITE),
398             vdev_queue_offset_compare, sizeof (zio_t),
399             offsetof(struct zio, io_offset_node));
400
401         for (p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++) {
402                 int (*compfn) (const void *, const void *);
403
404                 /*
405                  * The synchronous i/o queues are dispatched in FIFO rather
406                  * than LBA order. This provides more consistent latency for
407                  * these i/os.
408                  */
409                 if (p == ZIO_PRIORITY_SYNC_READ || p == ZIO_PRIORITY_SYNC_WRITE)
410                         compfn = vdev_queue_timestamp_compare;
411                 else
412                         compfn = vdev_queue_offset_compare;
413                 avl_create(vdev_queue_class_tree(vq, p), compfn,
414                     sizeof (zio_t), offsetof(struct zio, io_queue_node));
415         }
416
417         vq->vq_last_offset = 0;
418 }
419
420 void
421 vdev_queue_fini(vdev_t *vd)
422 {
423         vdev_queue_t *vq = &vd->vdev_queue;
424
425         for (zio_priority_t p = 0; p < ZIO_PRIORITY_NUM_QUEUEABLE; p++)
426                 avl_destroy(vdev_queue_class_tree(vq, p));
427         avl_destroy(&vq->vq_active_tree);
428         avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_READ));
429         avl_destroy(vdev_queue_type_tree(vq, ZIO_TYPE_WRITE));
430
431         mutex_destroy(&vq->vq_lock);
432 }
433
434 static void
435 vdev_queue_io_add(vdev_queue_t *vq, zio_t *zio)
436 {
437         spa_t *spa = zio->io_spa;
438         spa_history_kstat_t *shk = &spa->spa_stats.io_history;
439
440         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
441         avl_add(vdev_queue_class_tree(vq, zio->io_priority), zio);
442         avl_add(vdev_queue_type_tree(vq, zio->io_type), zio);
443
444         if (shk->kstat != NULL) {
445                 mutex_enter(&shk->lock);
446                 kstat_waitq_enter(shk->kstat->ks_data);
447                 mutex_exit(&shk->lock);
448         }
449 }
450
451 static void
452 vdev_queue_io_remove(vdev_queue_t *vq, zio_t *zio)
453 {
454         spa_t *spa = zio->io_spa;
455         spa_history_kstat_t *shk = &spa->spa_stats.io_history;
456
457         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
458         avl_remove(vdev_queue_class_tree(vq, zio->io_priority), zio);
459         avl_remove(vdev_queue_type_tree(vq, zio->io_type), zio);
460
461         if (shk->kstat != NULL) {
462                 mutex_enter(&shk->lock);
463                 kstat_waitq_exit(shk->kstat->ks_data);
464                 mutex_exit(&shk->lock);
465         }
466 }
467
468 static void
469 vdev_queue_pending_add(vdev_queue_t *vq, zio_t *zio)
470 {
471         spa_t *spa = zio->io_spa;
472         spa_history_kstat_t *shk = &spa->spa_stats.io_history;
473
474         ASSERT(MUTEX_HELD(&vq->vq_lock));
475         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
476         vq->vq_class[zio->io_priority].vqc_active++;
477         avl_add(&vq->vq_active_tree, zio);
478
479         if (shk->kstat != NULL) {
480                 mutex_enter(&shk->lock);
481                 kstat_runq_enter(shk->kstat->ks_data);
482                 mutex_exit(&shk->lock);
483         }
484 }
485
486 static void
487 vdev_queue_pending_remove(vdev_queue_t *vq, zio_t *zio)
488 {
489         spa_t *spa = zio->io_spa;
490         spa_history_kstat_t *shk = &spa->spa_stats.io_history;
491
492         ASSERT(MUTEX_HELD(&vq->vq_lock));
493         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
494         vq->vq_class[zio->io_priority].vqc_active--;
495         avl_remove(&vq->vq_active_tree, zio);
496
497         if (shk->kstat != NULL) {
498                 kstat_io_t *ksio = shk->kstat->ks_data;
499
500                 mutex_enter(&shk->lock);
501                 kstat_runq_exit(ksio);
502                 if (zio->io_type == ZIO_TYPE_READ) {
503                         ksio->reads++;
504                         ksio->nread += zio->io_size;
505                 } else if (zio->io_type == ZIO_TYPE_WRITE) {
506                         ksio->writes++;
507                         ksio->nwritten += zio->io_size;
508                 }
509                 mutex_exit(&shk->lock);
510         }
511 }
512
513 static void
514 vdev_queue_agg_io_done(zio_t *aio)
515 {
516         if (aio->io_type == ZIO_TYPE_READ) {
517                 zio_t *pio;
518                 zio_link_t *zl = NULL;
519                 while ((pio = zio_walk_parents(aio, &zl)) != NULL) {
520                         abd_copy_off(pio->io_abd, aio->io_abd,
521                             0, pio->io_offset - aio->io_offset, pio->io_size);
522                 }
523         }
524
525         abd_free(aio->io_abd);
526 }
527
528 /*
529  * Compute the range spanned by two i/os, which is the endpoint of the last
530  * (lio->io_offset + lio->io_size) minus start of the first (fio->io_offset).
531  * Conveniently, the gap between fio and lio is given by -IO_SPAN(lio, fio);
532  * thus fio and lio are adjacent if and only if IO_SPAN(lio, fio) == 0.
533  */
534 #define IO_SPAN(fio, lio) ((lio)->io_offset + (lio)->io_size - (fio)->io_offset)
535 #define IO_GAP(fio, lio) (-IO_SPAN(lio, fio))
536
537 static zio_t *
538 vdev_queue_aggregate(vdev_queue_t *vq, zio_t *zio)
539 {
540         zio_t *first, *last, *aio, *dio, *mandatory, *nio;
541         zio_link_t *zl = NULL;
542         uint64_t maxgap = 0;
543         uint64_t size;
544         uint64_t limit;
545         int maxblocksize;
546         boolean_t stretch = B_FALSE;
547         avl_tree_t *t = vdev_queue_type_tree(vq, zio->io_type);
548         enum zio_flag flags = zio->io_flags & ZIO_FLAG_AGG_INHERIT;
549         abd_t *abd;
550
551         maxblocksize = spa_maxblocksize(vq->vq_vdev->vdev_spa);
552         limit = MAX(MIN(zfs_vdev_aggregation_limit, maxblocksize), 0);
553
554         if (zio->io_flags & ZIO_FLAG_DONT_AGGREGATE || limit == 0)
555                 return (NULL);
556
557         first = last = zio;
558
559         if (zio->io_type == ZIO_TYPE_READ)
560                 maxgap = zfs_vdev_read_gap_limit;
561
562         /*
563          * We can aggregate I/Os that are sufficiently adjacent and of
564          * the same flavor, as expressed by the AGG_INHERIT flags.
565          * The latter requirement is necessary so that certain
566          * attributes of the I/O, such as whether it's a normal I/O
567          * or a scrub/resilver, can be preserved in the aggregate.
568          * We can include optional I/Os, but don't allow them
569          * to begin a range as they add no benefit in that situation.
570          */
571
572         /*
573          * We keep track of the last non-optional I/O.
574          */
575         mandatory = (first->io_flags & ZIO_FLAG_OPTIONAL) ? NULL : first;
576
577         /*
578          * Walk backwards through sufficiently contiguous I/Os
579          * recording the last non-optional I/O.
580          */
581         while ((dio = AVL_PREV(t, first)) != NULL &&
582             (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
583             IO_SPAN(dio, last) <= limit &&
584             IO_GAP(dio, first) <= maxgap &&
585             dio->io_type == zio->io_type) {
586                 first = dio;
587                 if (mandatory == NULL && !(first->io_flags & ZIO_FLAG_OPTIONAL))
588                         mandatory = first;
589         }
590
591         /*
592          * Skip any initial optional I/Os.
593          */
594         while ((first->io_flags & ZIO_FLAG_OPTIONAL) && first != last) {
595                 first = AVL_NEXT(t, first);
596                 ASSERT(first != NULL);
597         }
598
599
600         /*
601          * Walk forward through sufficiently contiguous I/Os.
602          * The aggregation limit does not apply to optional i/os, so that
603          * we can issue contiguous writes even if they are larger than the
604          * aggregation limit.
605          */
606         while ((dio = AVL_NEXT(t, last)) != NULL &&
607             (dio->io_flags & ZIO_FLAG_AGG_INHERIT) == flags &&
608             (IO_SPAN(first, dio) <= limit ||
609             (dio->io_flags & ZIO_FLAG_OPTIONAL)) &&
610             IO_SPAN(first, dio) <= maxblocksize &&
611             IO_GAP(last, dio) <= maxgap &&
612             dio->io_type == zio->io_type) {
613                 last = dio;
614                 if (!(last->io_flags & ZIO_FLAG_OPTIONAL))
615                         mandatory = last;
616         }
617
618         /*
619          * Now that we've established the range of the I/O aggregation
620          * we must decide what to do with trailing optional I/Os.
621          * For reads, there's nothing to do. While we are unable to
622          * aggregate further, it's possible that a trailing optional
623          * I/O would allow the underlying device to aggregate with
624          * subsequent I/Os. We must therefore determine if the next
625          * non-optional I/O is close enough to make aggregation
626          * worthwhile.
627          */
628         if (zio->io_type == ZIO_TYPE_WRITE && mandatory != NULL) {
629                 zio_t *nio = last;
630                 while ((dio = AVL_NEXT(t, nio)) != NULL &&
631                     IO_GAP(nio, dio) == 0 &&
632                     IO_GAP(mandatory, dio) <= zfs_vdev_write_gap_limit) {
633                         nio = dio;
634                         if (!(nio->io_flags & ZIO_FLAG_OPTIONAL)) {
635                                 stretch = B_TRUE;
636                                 break;
637                         }
638                 }
639         }
640
641         if (stretch) {
642                 /*
643                  * We are going to include an optional io in our aggregated
644                  * span, thus closing the write gap.  Only mandatory i/os can
645                  * start aggregated spans, so make sure that the next i/o
646                  * after our span is mandatory.
647                  */
648                 dio = AVL_NEXT(t, last);
649                 dio->io_flags &= ~ZIO_FLAG_OPTIONAL;
650         } else {
651                 /* do not include the optional i/o */
652                 while (last != mandatory && last != first) {
653                         ASSERT(last->io_flags & ZIO_FLAG_OPTIONAL);
654                         last = AVL_PREV(t, last);
655                         ASSERT(last != NULL);
656                 }
657         }
658
659         if (first == last)
660                 return (NULL);
661
662         size = IO_SPAN(first, last);
663         ASSERT3U(size, <=, maxblocksize);
664
665         abd = abd_alloc_for_io(size, B_TRUE);
666         if (abd == NULL)
667                 return (NULL);
668
669         aio = zio_vdev_delegated_io(first->io_vd, first->io_offset,
670             abd, size, first->io_type, zio->io_priority,
671             flags | ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE,
672             vdev_queue_agg_io_done, NULL);
673         aio->io_timestamp = first->io_timestamp;
674
675         nio = first;
676         do {
677                 dio = nio;
678                 nio = AVL_NEXT(t, dio);
679                 ASSERT3U(dio->io_type, ==, aio->io_type);
680
681                 if (dio->io_flags & ZIO_FLAG_NODATA) {
682                         ASSERT3U(dio->io_type, ==, ZIO_TYPE_WRITE);
683                         abd_zero_off(aio->io_abd,
684                             dio->io_offset - aio->io_offset, dio->io_size);
685                 } else if (dio->io_type == ZIO_TYPE_WRITE) {
686                         abd_copy_off(aio->io_abd, dio->io_abd,
687                             dio->io_offset - aio->io_offset, 0, dio->io_size);
688                 }
689
690                 zio_add_child(dio, aio);
691                 vdev_queue_io_remove(vq, dio);
692         } while (dio != last);
693
694         /*
695          * We need to drop the vdev queue's lock to avoid a deadlock that we
696          * could encounter since this I/O will complete immediately.
697          */
698         mutex_exit(&vq->vq_lock);
699         while ((dio = zio_walk_parents(aio, &zl)) != NULL) {
700                 zio_vdev_io_bypass(dio);
701                 zio_execute(dio);
702         }
703         mutex_enter(&vq->vq_lock);
704
705         return (aio);
706 }
707
708 static zio_t *
709 vdev_queue_io_to_issue(vdev_queue_t *vq)
710 {
711         zio_t *zio, *aio;
712         zio_priority_t p;
713         avl_index_t idx;
714         avl_tree_t *tree;
715
716 again:
717         ASSERT(MUTEX_HELD(&vq->vq_lock));
718
719         p = vdev_queue_class_to_issue(vq);
720
721         if (p == ZIO_PRIORITY_NUM_QUEUEABLE) {
722                 /* No eligible queued i/os */
723                 return (NULL);
724         }
725
726         /*
727          * For LBA-ordered queues (async / scrub / initializing), issue the
728          * i/o which follows the most recently issued i/o in LBA (offset) order.
729          *
730          * For FIFO queues (sync), issue the i/o with the lowest timestamp.
731          */
732         tree = vdev_queue_class_tree(vq, p);
733         vq->vq_io_search.io_timestamp = 0;
734         vq->vq_io_search.io_offset = vq->vq_last_offset - 1;
735         VERIFY3P(avl_find(tree, &vq->vq_io_search, &idx), ==, NULL);
736         zio = avl_nearest(tree, idx, AVL_AFTER);
737         if (zio == NULL)
738                 zio = avl_first(tree);
739         ASSERT3U(zio->io_priority, ==, p);
740
741         aio = vdev_queue_aggregate(vq, zio);
742         if (aio != NULL)
743                 zio = aio;
744         else
745                 vdev_queue_io_remove(vq, zio);
746
747         /*
748          * If the I/O is or was optional and therefore has no data, we need to
749          * simply discard it. We need to drop the vdev queue's lock to avoid a
750          * deadlock that we could encounter since this I/O will complete
751          * immediately.
752          */
753         if (zio->io_flags & ZIO_FLAG_NODATA) {
754                 mutex_exit(&vq->vq_lock);
755                 zio_vdev_io_bypass(zio);
756                 zio_execute(zio);
757                 mutex_enter(&vq->vq_lock);
758                 goto again;
759         }
760
761         vdev_queue_pending_add(vq, zio);
762         vq->vq_last_offset = zio->io_offset + zio->io_size;
763
764         return (zio);
765 }
766
767 zio_t *
768 vdev_queue_io(zio_t *zio)
769 {
770         vdev_queue_t *vq = &zio->io_vd->vdev_queue;
771         zio_t *nio;
772
773         if (zio->io_flags & ZIO_FLAG_DONT_QUEUE)
774                 return (zio);
775
776         /*
777          * Children i/os inherent their parent's priority, which might
778          * not match the child's i/o type.  Fix it up here.
779          */
780         if (zio->io_type == ZIO_TYPE_READ) {
781                 if (zio->io_priority != ZIO_PRIORITY_SYNC_READ &&
782                     zio->io_priority != ZIO_PRIORITY_ASYNC_READ &&
783                     zio->io_priority != ZIO_PRIORITY_SCRUB &&
784                     zio->io_priority != ZIO_PRIORITY_REMOVAL &&
785                     zio->io_priority != ZIO_PRIORITY_INITIALIZING)
786                         zio->io_priority = ZIO_PRIORITY_ASYNC_READ;
787         } else {
788                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
789                 if (zio->io_priority != ZIO_PRIORITY_SYNC_WRITE &&
790                     zio->io_priority != ZIO_PRIORITY_ASYNC_WRITE &&
791                     zio->io_priority != ZIO_PRIORITY_REMOVAL &&
792                     zio->io_priority != ZIO_PRIORITY_INITIALIZING)
793                         zio->io_priority = ZIO_PRIORITY_ASYNC_WRITE;
794         }
795
796         zio->io_flags |= ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE;
797
798         mutex_enter(&vq->vq_lock);
799         zio->io_timestamp = gethrtime();
800         vdev_queue_io_add(vq, zio);
801         nio = vdev_queue_io_to_issue(vq);
802         mutex_exit(&vq->vq_lock);
803
804         if (nio == NULL)
805                 return (NULL);
806
807         if (nio->io_done == vdev_queue_agg_io_done) {
808                 zio_nowait(nio);
809                 return (NULL);
810         }
811
812         return (nio);
813 }
814
815 void
816 vdev_queue_io_done(zio_t *zio)
817 {
818         vdev_queue_t *vq = &zio->io_vd->vdev_queue;
819         zio_t *nio;
820
821         mutex_enter(&vq->vq_lock);
822
823         vdev_queue_pending_remove(vq, zio);
824
825         zio->io_delta = gethrtime() - zio->io_timestamp;
826         vq->vq_io_complete_ts = gethrtime();
827         vq->vq_io_delta_ts = vq->vq_io_complete_ts - zio->io_timestamp;
828
829         while ((nio = vdev_queue_io_to_issue(vq)) != NULL) {
830                 mutex_exit(&vq->vq_lock);
831                 if (nio->io_done == vdev_queue_agg_io_done) {
832                         zio_nowait(nio);
833                 } else {
834                         zio_vdev_io_reissue(nio);
835                         zio_execute(nio);
836                 }
837                 mutex_enter(&vq->vq_lock);
838         }
839
840         mutex_exit(&vq->vq_lock);
841 }
842
843 void
844 vdev_queue_change_io_priority(zio_t *zio, zio_priority_t priority)
845 {
846         vdev_queue_t *vq = &zio->io_vd->vdev_queue;
847         avl_tree_t *tree;
848
849         /*
850          * ZIO_PRIORITY_NOW is used by the vdev cache code and the aggregate zio
851          * code to issue IOs without adding them to the vdev queue. In this
852          * case, the zio is already going to be issued as quickly as possible
853          * and so it doesn't need any reprioitization to help.
854          */
855         if (zio->io_priority == ZIO_PRIORITY_NOW)
856                 return;
857
858         ASSERT3U(zio->io_priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
859         ASSERT3U(priority, <, ZIO_PRIORITY_NUM_QUEUEABLE);
860
861         if (zio->io_type == ZIO_TYPE_READ) {
862                 if (priority != ZIO_PRIORITY_SYNC_READ &&
863                     priority != ZIO_PRIORITY_ASYNC_READ &&
864                     priority != ZIO_PRIORITY_SCRUB)
865                         priority = ZIO_PRIORITY_ASYNC_READ;
866         } else {
867                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
868                 if (priority != ZIO_PRIORITY_SYNC_WRITE &&
869                     priority != ZIO_PRIORITY_ASYNC_WRITE)
870                         priority = ZIO_PRIORITY_ASYNC_WRITE;
871         }
872
873         mutex_enter(&vq->vq_lock);
874
875         /*
876          * If the zio is in none of the queues we can simply change
877          * the priority. If the zio is waiting to be submitted we must
878          * remove it from the queue and re-insert it with the new priority.
879          * Otherwise, the zio is currently active and we cannot change its
880          * priority.
881          */
882         tree = vdev_queue_class_tree(vq, zio->io_priority);
883         if (avl_find(tree, zio, NULL) == zio) {
884                 avl_remove(vdev_queue_class_tree(vq, zio->io_priority), zio);
885                 zio->io_priority = priority;
886                 avl_add(vdev_queue_class_tree(vq, zio->io_priority), zio);
887         } else if (avl_find(&vq->vq_active_tree, zio, NULL) != zio) {
888                 zio->io_priority = priority;
889         }
890
891         mutex_exit(&vq->vq_lock);
892 }
893
894 /*
895  * As these two methods are only used for load calculations we're not
896  * concerned if we get an incorrect value on 32bit platforms due to lack of
897  * vq_lock mutex use here, instead we prefer to keep it lock free for
898  * 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_last_offset(vdev_t *vd)
908 {
909         return (vd->vdev_queue.vq_last_offset);
910 }
911
912 #if defined(_KERNEL)
913 module_param(zfs_vdev_aggregation_limit, int, 0644);
914 MODULE_PARM_DESC(zfs_vdev_aggregation_limit, "Max vdev I/O aggregation size");
915
916 module_param(zfs_vdev_read_gap_limit, int, 0644);
917 MODULE_PARM_DESC(zfs_vdev_read_gap_limit, "Aggregate read I/O over gap");
918
919 module_param(zfs_vdev_write_gap_limit, int, 0644);
920 MODULE_PARM_DESC(zfs_vdev_write_gap_limit, "Aggregate write I/O over gap");
921
922 module_param(zfs_vdev_max_active, int, 0644);
923 MODULE_PARM_DESC(zfs_vdev_max_active, "Maximum number of active I/Os per vdev");
924
925 module_param(zfs_vdev_async_write_active_max_dirty_percent, int, 0644);
926 MODULE_PARM_DESC(zfs_vdev_async_write_active_max_dirty_percent,
927         "Async write concurrency max threshold");
928
929 module_param(zfs_vdev_async_write_active_min_dirty_percent, int, 0644);
930 MODULE_PARM_DESC(zfs_vdev_async_write_active_min_dirty_percent,
931         "Async write concurrency min threshold");
932
933 module_param(zfs_vdev_async_read_max_active, int, 0644);
934 MODULE_PARM_DESC(zfs_vdev_async_read_max_active,
935         "Max active async read I/Os per vdev");
936
937 module_param(zfs_vdev_async_read_min_active, int, 0644);
938 MODULE_PARM_DESC(zfs_vdev_async_read_min_active,
939         "Min active async read I/Os per vdev");
940
941 module_param(zfs_vdev_async_write_max_active, int, 0644);
942 MODULE_PARM_DESC(zfs_vdev_async_write_max_active,
943         "Max active async write I/Os per vdev");
944
945 module_param(zfs_vdev_async_write_min_active, int, 0644);
946 MODULE_PARM_DESC(zfs_vdev_async_write_min_active,
947         "Min active async write I/Os per vdev");
948
949 module_param(zfs_vdev_initializing_max_active, int, 0644);
950 MODULE_PARM_DESC(zfs_vdev_initializing_max_active,
951         "Max active initializing I/Os per vdev");
952
953 module_param(zfs_vdev_initializing_min_active, int, 0644);
954 MODULE_PARM_DESC(zfs_vdev_initializing_min_active,
955         "Min active initializing I/Os per vdev");
956
957 module_param(zfs_vdev_removal_max_active, int, 0644);
958 MODULE_PARM_DESC(zfs_vdev_removal_max_active,
959         "Max active removal I/Os per vdev");
960
961 module_param(zfs_vdev_removal_min_active, int, 0644);
962 MODULE_PARM_DESC(zfs_vdev_removal_min_active,
963         "Min active removal I/Os per vdev");
964
965 module_param(zfs_vdev_scrub_max_active, int, 0644);
966 MODULE_PARM_DESC(zfs_vdev_scrub_max_active,
967         "Max active scrub I/Os per vdev");
968
969 module_param(zfs_vdev_scrub_min_active, int, 0644);
970 MODULE_PARM_DESC(zfs_vdev_scrub_min_active,
971         "Min active scrub I/Os per vdev");
972
973 module_param(zfs_vdev_sync_read_max_active, int, 0644);
974 MODULE_PARM_DESC(zfs_vdev_sync_read_max_active,
975         "Max active sync read I/Os per vdev");
976
977 module_param(zfs_vdev_sync_read_min_active, int, 0644);
978 MODULE_PARM_DESC(zfs_vdev_sync_read_min_active,
979         "Min active sync read I/Os per vdev");
980
981 module_param(zfs_vdev_sync_write_max_active, int, 0644);
982 MODULE_PARM_DESC(zfs_vdev_sync_write_max_active,
983         "Max active sync write I/Os per vdev");
984
985 module_param(zfs_vdev_sync_write_min_active, int, 0644);
986 MODULE_PARM_DESC(zfs_vdev_sync_write_min_active,
987         "Min active sync write I/Os per vdev");
988
989 module_param(zfs_vdev_queue_depth_pct, int, 0644);
990 MODULE_PARM_DESC(zfs_vdev_queue_depth_pct,
991         "Queue depth percentage for each top-level vdev");
992 #endif