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