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