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