2 * CAM IO Scheduler Interface
4 * Copyright (c) 2015 Netflix, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions, and the following disclaimer,
12 * without modification, immediately at the beginning of the file.
13 * 2. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
43 #include <sys/malloc.h>
44 #include <sys/mutex.h>
46 #include <sys/sysctl.h>
49 #include <cam/cam_ccb.h>
50 #include <cam/cam_periph.h>
51 #include <cam/cam_xpt_periph.h>
52 #include <cam/cam_xpt_internal.h>
53 #include <cam/cam_iosched.h>
57 static MALLOC_DEFINE(M_CAMSCHED, "CAM I/O Scheduler",
58 "CAM I/O Scheduler buffers");
61 * Default I/O scheduler for FreeBSD. This implementation is just a thin-vineer
62 * over the bioq_* interface, with notions of separate calls for normal I/O and
65 * When CAM_IOSCHED_DYNAMIC is defined, the scheduler is enhanced to dynamically
66 * steer the rate of one type of traffic to help other types of traffic (eg
67 * limit writes when read latency deteriorates on SSDs).
70 #ifdef CAM_IOSCHED_DYNAMIC
72 static int do_dynamic_iosched = 1;
73 TUNABLE_INT("kern.cam.do_dynamic_iosched", &do_dynamic_iosched);
74 SYSCTL_INT(_kern_cam, OID_AUTO, do_dynamic_iosched, CTLFLAG_RD,
75 &do_dynamic_iosched, 1,
76 "Enable Dynamic I/O scheduler optimizations.");
79 * For an EMA, with an alpha of alpha, we know
83 * where N is the number of samples that 86% of the current
84 * EMA is derived from.
86 * So we invent[*] alpha_bits:
87 * alpha_bits = -log_2(alpha)
88 * alpha = 2^-alpha_bits
90 * N = 1 + 2^(alpha_bits + 1)
92 * The default 9 gives a 1025 lookback for 86% of the data.
93 * For a brief intro: https://en.wikipedia.org/wiki/Moving_average
95 * [*] Steal from the load average code and many other places.
96 * Note: See computation of EMA and EMVAR for acceptable ranges of alpha.
98 static int alpha_bits = 9;
99 TUNABLE_INT("kern.cam.iosched_alpha_bits", &alpha_bits);
100 SYSCTL_INT(_kern_cam, OID_AUTO, iosched_alpha_bits, CTLFLAG_RW,
102 "Bits in EMA's alpha.");
105 struct cam_iosched_softc;
107 int iosched_debug = 0;
110 none = 0, /* No limits */
111 queue_depth, /* Limit how many ops we queue to SIM */
112 iops, /* Limit # of IOPS to the drive */
113 bandwidth, /* Limit bandwidth to the drive */
117 static const char *cam_iosched_limiter_names[] =
118 { "none", "queue_depth", "iops", "bandwidth" };
121 * Called to initialize the bits of the iop_stats structure relevant to the
122 * limiter. Called just after the limiter is set.
124 typedef int l_init_t(struct iop_stats *);
129 typedef int l_tick_t(struct iop_stats *);
132 * Called to see if the limiter thinks this IOP can be allowed to
133 * proceed. If so, the limiter assumes that the IOP proceeded
134 * and makes any accounting of it that's needed.
136 typedef int l_iop_t(struct iop_stats *, struct bio *);
139 * Called when an I/O completes so the limiter can update its
140 * accounting. Pending I/Os may complete in any order (even when
141 * sent to the hardware at the same time), so the limiter may not
142 * make any assumptions other than this I/O has completed. If it
143 * returns 1, then xpt_schedule() needs to be called again.
145 typedef int l_iodone_t(struct iop_stats *, struct bio *);
147 static l_iop_t cam_iosched_qd_iop;
148 static l_iop_t cam_iosched_qd_caniop;
149 static l_iodone_t cam_iosched_qd_iodone;
151 static l_init_t cam_iosched_iops_init;
152 static l_tick_t cam_iosched_iops_tick;
153 static l_iop_t cam_iosched_iops_caniop;
154 static l_iop_t cam_iosched_iops_iop;
156 static l_init_t cam_iosched_bw_init;
157 static l_tick_t cam_iosched_bw_tick;
158 static l_iop_t cam_iosched_bw_caniop;
159 static l_iop_t cam_iosched_bw_iop;
166 l_iodone_t *l_iodone;
178 .l_caniop = cam_iosched_qd_caniop,
179 .l_iop = cam_iosched_qd_iop,
180 .l_iodone= cam_iosched_qd_iodone,
183 .l_init = cam_iosched_iops_init,
184 .l_tick = cam_iosched_iops_tick,
185 .l_caniop = cam_iosched_iops_caniop,
186 .l_iop = cam_iosched_iops_iop,
190 .l_init = cam_iosched_bw_init,
191 .l_tick = cam_iosched_bw_tick,
192 .l_caniop = cam_iosched_bw_caniop,
193 .l_iop = cam_iosched_bw_iop,
200 * sysctl state for this subnode.
202 struct sysctl_ctx_list sysctl_ctx;
203 struct sysctl_oid *sysctl_tree;
206 * Information about the current rate limiters, if any
208 io_limiter limiter; /* How are I/Os being limited */
209 int min; /* Low range of limit */
210 int max; /* High range of limit */
211 int current; /* Current rate limiter */
212 int l_value1; /* per-limiter scratch value 1. */
213 int l_value2; /* per-limiter scratch value 2. */
216 * Debug information about counts of I/Os that have gone through the
219 int pending; /* I/Os pending in the hardware */
220 int queued; /* number currently in the queue */
221 int total; /* Total for all time -- wraps */
222 int in; /* number queued all time -- wraps */
223 int out; /* number completed all time -- wraps */
226 * Statistics on different bits of the process.
228 /* Exp Moving Average, see alpha_bits for more details */
231 sbintime_t sd; /* Last computed sd */
233 uint32_t state_flags;
234 #define IOP_RATE_LIMITED 1u
236 #define LAT_BUCKETS 15 /* < 1ms < 2ms ... < 2^(n-1)ms >= 2^(n-1)ms*/
237 uint64_t latencies[LAT_BUCKETS];
239 struct cam_iosched_softc *softc;
244 set_max = 0, /* current = max */
245 read_latency, /* Steer read latency by throttling writes */
246 cl_max /* Keep last */
249 static const char *cam_iosched_control_type_names[] =
250 { "set_max", "read_latency" };
252 struct control_loop {
254 * sysctl state for this subnode.
256 struct sysctl_ctx_list sysctl_ctx;
257 struct sysctl_oid *sysctl_tree;
259 sbintime_t next_steer; /* Time of next steer */
260 sbintime_t steer_interval; /* How often do we steer? */
264 control_type type; /* What type of control? */
265 int last_count; /* Last I/O count */
267 struct cam_iosched_softc *softc;
272 struct cam_iosched_softc {
273 struct bio_queue_head bio_queue;
274 struct bio_queue_head trim_queue;
275 /* scheduler flags < 16, user flags >= 16 */
278 #ifdef CAM_IOSCHED_DYNAMIC
279 int read_bias; /* Read bias setting */
280 int current_read_bias; /* Current read bias state */
282 int load; /* EMA of 'load average' of disk / 2^16 */
284 struct bio_queue_head write_queue;
285 struct iop_stats read_stats, write_stats, trim_stats;
286 struct sysctl_ctx_list sysctl_ctx;
287 struct sysctl_oid *sysctl_tree;
289 int quanta; /* Number of quanta per second */
290 struct callout ticker; /* Callout for our quota system */
291 struct cam_periph *periph; /* cam periph associated with this device */
292 uint32_t this_frac; /* Fraction of a second (1024ths) for this tick */
293 sbintime_t last_time; /* Last time we ticked */
294 struct control_loop cl;
298 #ifdef CAM_IOSCHED_DYNAMIC
300 * helper functions to call the limsw functions.
303 cam_iosched_limiter_init(struct iop_stats *ios)
305 int lim = ios->limiter;
307 /* maybe this should be a kassert */
308 if (lim < none || lim >= limiter_max)
311 if (limsw[lim].l_init)
312 return limsw[lim].l_init(ios);
318 cam_iosched_limiter_tick(struct iop_stats *ios)
320 int lim = ios->limiter;
322 /* maybe this should be a kassert */
323 if (lim < none || lim >= limiter_max)
326 if (limsw[lim].l_tick)
327 return limsw[lim].l_tick(ios);
333 cam_iosched_limiter_iop(struct iop_stats *ios, struct bio *bp)
335 int lim = ios->limiter;
337 /* maybe this should be a kassert */
338 if (lim < none || lim >= limiter_max)
341 if (limsw[lim].l_iop)
342 return limsw[lim].l_iop(ios, bp);
348 cam_iosched_limiter_caniop(struct iop_stats *ios, struct bio *bp)
350 int lim = ios->limiter;
352 /* maybe this should be a kassert */
353 if (lim < none || lim >= limiter_max)
356 if (limsw[lim].l_caniop)
357 return limsw[lim].l_caniop(ios, bp);
363 cam_iosched_limiter_iodone(struct iop_stats *ios, struct bio *bp)
365 int lim = ios->limiter;
367 /* maybe this should be a kassert */
368 if (lim < none || lim >= limiter_max)
371 if (limsw[lim].l_iodone)
372 return limsw[lim].l_iodone(ios, bp);
378 * Functions to implement the different kinds of limiters
382 cam_iosched_qd_iop(struct iop_stats *ios, struct bio *bp)
385 if (ios->current <= 0 || ios->pending < ios->current)
392 cam_iosched_qd_caniop(struct iop_stats *ios, struct bio *bp)
395 if (ios->current <= 0 || ios->pending < ios->current)
402 cam_iosched_qd_iodone(struct iop_stats *ios, struct bio *bp)
405 if (ios->current <= 0 || ios->pending != ios->current)
412 cam_iosched_iops_init(struct iop_stats *ios)
415 ios->l_value1 = ios->current / ios->softc->quanta;
416 if (ios->l_value1 <= 0)
424 cam_iosched_iops_tick(struct iop_stats *ios)
429 * Allow at least one IO per tick until all
430 * the IOs for this interval have been spent.
432 new_ios = (int)((ios->current * (uint64_t)ios->softc->this_frac) >> 16);
433 if (new_ios < 1 && ios->l_value2 < ios->current) {
439 * If this a new accounting interval, discard any "unspent" ios
440 * granted in the previous interval. Otherwise add the new ios to
441 * the previously granted ones that haven't been spent yet.
443 if ((ios->softc->total_ticks % ios->softc->quanta) == 0) {
444 ios->l_value1 = new_ios;
447 ios->l_value1 += new_ios;
455 cam_iosched_iops_caniop(struct iop_stats *ios, struct bio *bp)
459 * So if we have any more IOPs left, allow it,
460 * otherwise wait. If current iops is 0, treat that
461 * as unlimited as a failsafe.
463 if (ios->current > 0 && ios->l_value1 <= 0)
469 cam_iosched_iops_iop(struct iop_stats *ios, struct bio *bp)
473 rv = cam_iosched_limiter_caniop(ios, bp);
481 cam_iosched_bw_init(struct iop_stats *ios)
484 /* ios->current is in kB/s, so scale to bytes */
485 ios->l_value1 = ios->current * 1000 / ios->softc->quanta;
491 cam_iosched_bw_tick(struct iop_stats *ios)
496 * If we're in the hole for available quota from
497 * the last time, then add the quantum for this.
498 * If we have any left over from last quantum,
499 * then too bad, that's lost. Also, ios->current
500 * is in kB/s, so scale.
502 * We also allow up to 4 quanta of credits to
503 * accumulate to deal with burstiness. 4 is extremely
506 bw = (int)((ios->current * 1000ull * (uint64_t)ios->softc->this_frac) >> 16);
507 if (ios->l_value1 < bw * 4)
514 cam_iosched_bw_caniop(struct iop_stats *ios, struct bio *bp)
517 * So if we have any more bw quota left, allow it,
518 * otherwise wait. Note, we'll go negative and that's
519 * OK. We'll just get a little less next quota.
521 * Note on going negative: that allows us to process
522 * requests in order better, since we won't allow
523 * shorter reads to get around the long one that we
524 * don't have the quota to do just yet. It also prevents
525 * starvation by being a little more permissive about
526 * what we let through this quantum (to prevent the
527 * starvation), at the cost of getting a little less
530 * Also note that if the current limit is <= 0,
531 * we treat it as unlimited as a failsafe.
533 if (ios->current > 0 && ios->l_value1 <= 0)
541 cam_iosched_bw_iop(struct iop_stats *ios, struct bio *bp)
545 rv = cam_iosched_limiter_caniop(ios, bp);
547 ios->l_value1 -= bp->bio_length;
552 static void cam_iosched_cl_maybe_steer(struct control_loop *clp);
555 cam_iosched_ticker(void *arg)
557 struct cam_iosched_softc *isc = arg;
558 sbintime_t now, delta;
561 callout_reset(&isc->ticker, hz / isc->quanta, cam_iosched_ticker, isc);
564 delta = now - isc->last_time;
565 isc->this_frac = (uint32_t)delta >> 16; /* Note: discards seconds -- should be 0 harmless if not */
566 isc->last_time = now;
568 cam_iosched_cl_maybe_steer(&isc->cl);
570 cam_iosched_limiter_tick(&isc->read_stats);
571 cam_iosched_limiter_tick(&isc->write_stats);
572 cam_iosched_limiter_tick(&isc->trim_stats);
574 cam_iosched_schedule(isc, isc->periph);
577 * isc->load is an EMA of the pending I/Os at each tick. The number of
578 * pending I/Os is the sum of the I/Os queued to the hardware, and those
579 * in the software queue that could be queued to the hardware if there
582 * ios_stats.pending is a count of requests in the SIM right now for
583 * each of these types of I/O. So the total pending count is the sum of
584 * these I/Os and the sum of the queued I/Os still in the software queue
585 * for those operations that aren't being rate limited at the moment.
587 * The reason for the rate limiting bit is because those I/Os
588 * aren't part of the software queued load (since we could
589 * give them to hardware, but choose not to).
591 * Note: due to a bug in counting pending TRIM in the device, we
592 * don't include them in this count. We count each BIO_DELETE in
593 * the pending count, but the periph drivers collapse them down
594 * into one TRIM command. That one trim command gets the completion
595 * so the counts get off.
597 pending = isc->read_stats.pending + isc->write_stats.pending /* + isc->trim_stats.pending */;
598 pending += !!(isc->read_stats.state_flags & IOP_RATE_LIMITED) * isc->read_stats.queued +
599 !!(isc->write_stats.state_flags & IOP_RATE_LIMITED) * isc->write_stats.queued /* +
600 !!(isc->trim_stats.state_flags & IOP_RATE_LIMITED) * isc->trim_stats.queued */ ;
602 pending /= isc->periph->path->device->ccbq.total_openings;
604 isc->load = (pending + (isc->load << 13) - isc->load) >> 13; /* see above: 13 -> 16139 / 200/s = ~81s ~1 minute */
611 cam_iosched_cl_init(struct control_loop *clp, struct cam_iosched_softc *isc)
614 clp->next_steer = sbinuptime();
616 clp->steer_interval = SBT_1S * 5; /* Let's start out steering every 5s */
617 clp->lolat = 5 * SBT_1MS;
618 clp->hilat = 15 * SBT_1MS;
619 clp->alpha = 20; /* Alpha == gain. 20 = .2 */
624 cam_iosched_cl_maybe_steer(struct control_loop *clp)
626 struct cam_iosched_softc *isc;
631 now = isc->last_time;
632 if (now < clp->next_steer)
635 clp->next_steer = now + clp->steer_interval;
638 if (isc->write_stats.current != isc->write_stats.max)
639 printf("Steering write from %d kBps to %d kBps\n",
640 isc->write_stats.current, isc->write_stats.max);
641 isc->read_stats.current = isc->read_stats.max;
642 isc->write_stats.current = isc->write_stats.max;
643 isc->trim_stats.current = isc->trim_stats.max;
646 old = isc->write_stats.current;
647 lat = isc->read_stats.ema;
649 * Simple PLL-like engine. Since we're steering to a range for
650 * the SP (set point) that makes things a little more
651 * complicated. In addition, we're not directly controlling our
652 * PV (process variable), the read latency, but instead are
653 * manipulating the write bandwidth limit for our MV
654 * (manipulation variable), analysis of this code gets a bit
655 * messy. Also, the MV is a very noisy control surface for read
656 * latency since it is affected by many hidden processes inside
657 * the device which change how responsive read latency will be
658 * in reaction to changes in write bandwidth. Unlike the classic
659 * boiler control PLL. this may result in over-steering while
660 * the SSD takes its time to react to the new, lower load. This
661 * is why we use a relatively low alpha of between .1 and .25 to
662 * compensate for this effect. At .1, it takes ~22 steering
663 * intervals to back off by a factor of 10. At .2 it only takes
664 * ~10. At .25 it only takes ~8. However some preliminary data
665 * from the SSD drives suggests a reasponse time in 10's of
666 * seconds before latency drops regardless of the new write
667 * rate. Careful observation will be required to tune this
670 * Also, when there's no read traffic, we jack up the write
671 * limit too regardless of the last read latency. 10 is
672 * somewhat arbitrary.
674 if (lat < clp->lolat || isc->read_stats.total - clp->last_count < 10)
675 isc->write_stats.current = isc->write_stats.current *
676 (100 + clp->alpha) / 100; /* Scale up */
677 else if (lat > clp->hilat)
678 isc->write_stats.current = isc->write_stats.current *
679 (100 - clp->alpha) / 100; /* Scale down */
680 clp->last_count = isc->read_stats.total;
683 * Even if we don't steer, per se, enforce the min/max limits as
684 * those may have changed.
686 if (isc->write_stats.current < isc->write_stats.min)
687 isc->write_stats.current = isc->write_stats.min;
688 if (isc->write_stats.current > isc->write_stats.max)
689 isc->write_stats.current = isc->write_stats.max;
690 if (old != isc->write_stats.current && iosched_debug)
691 printf("Steering write from %d kBps to %d kBps due to latency of %jdus\n",
692 old, isc->write_stats.current,
693 (uintmax_t)((uint64_t)1000000 * (uint32_t)lat) >> 32);
702 * Trim or similar currently pending completion. Should only be set for
703 * those drivers wishing only one Trim active at a time.
705 #define CAM_IOSCHED_FLAG_TRIM_ACTIVE (1ul << 0)
706 /* Callout active, and needs to be torn down */
707 #define CAM_IOSCHED_FLAG_CALLOUT_ACTIVE (1ul << 1)
709 /* Periph drivers set these flags to indicate work */
710 #define CAM_IOSCHED_FLAG_WORK_FLAGS ((0xffffu) << 16)
712 #ifdef CAM_IOSCHED_DYNAMIC
714 cam_iosched_io_metric_update(struct cam_iosched_softc *isc,
715 sbintime_t sim_latency, int cmd, size_t size);
719 cam_iosched_has_flagged_work(struct cam_iosched_softc *isc)
721 return !!(isc->flags & CAM_IOSCHED_FLAG_WORK_FLAGS);
725 cam_iosched_has_io(struct cam_iosched_softc *isc)
727 #ifdef CAM_IOSCHED_DYNAMIC
728 if (do_dynamic_iosched) {
729 struct bio *rbp = bioq_first(&isc->bio_queue);
730 struct bio *wbp = bioq_first(&isc->write_queue);
731 int can_write = wbp != NULL &&
732 cam_iosched_limiter_caniop(&isc->write_stats, wbp) == 0;
733 int can_read = rbp != NULL &&
734 cam_iosched_limiter_caniop(&isc->read_stats, rbp) == 0;
735 if (iosched_debug > 2) {
736 printf("can write %d: pending_writes %d max_writes %d\n", can_write, isc->write_stats.pending, isc->write_stats.max);
737 printf("can read %d: read_stats.pending %d max_reads %d\n", can_read, isc->read_stats.pending, isc->read_stats.max);
738 printf("Queued reads %d writes %d\n", isc->read_stats.queued, isc->write_stats.queued);
740 return can_read || can_write;
743 return bioq_first(&isc->bio_queue) != NULL;
747 cam_iosched_has_more_trim(struct cam_iosched_softc *isc)
749 return !(isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) &&
750 bioq_first(&isc->trim_queue);
753 #define cam_iosched_sort_queue(isc) ((isc)->sort_io_queue >= 0 ? \
754 (isc)->sort_io_queue : cam_sort_io_queues)
758 cam_iosched_has_work(struct cam_iosched_softc *isc)
760 #ifdef CAM_IOSCHED_DYNAMIC
761 if (iosched_debug > 2)
762 printf("has work: %d %d %d\n", cam_iosched_has_io(isc),
763 cam_iosched_has_more_trim(isc),
764 cam_iosched_has_flagged_work(isc));
767 return cam_iosched_has_io(isc) ||
768 cam_iosched_has_more_trim(isc) ||
769 cam_iosched_has_flagged_work(isc);
772 #ifdef CAM_IOSCHED_DYNAMIC
774 cam_iosched_iop_stats_init(struct cam_iosched_softc *isc, struct iop_stats *ios)
779 ios->max = ios->current = 300000;
788 cam_iosched_limiter_init(ios);
792 cam_iosched_limiter_sysctl(SYSCTL_HANDLER_ARGS)
795 struct iop_stats *ios;
796 struct cam_iosched_softc *isc;
802 value = ios->limiter;
803 if (value < none || value >= limiter_max)
806 p = cam_iosched_limiter_names[value];
808 strlcpy(buf, p, sizeof(buf));
809 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
810 if (error != 0 || req->newptr == NULL)
813 cam_periph_lock(isc->periph);
815 for (i = none; i < limiter_max; i++) {
816 if (strcmp(buf, cam_iosched_limiter_names[i]) != 0)
819 error = cam_iosched_limiter_init(ios);
821 ios->limiter = value;
822 cam_periph_unlock(isc->periph);
825 /* Note: disk load averate requires ticker to be always running */
826 callout_reset(&isc->ticker, hz / isc->quanta, cam_iosched_ticker, isc);
827 isc->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
829 cam_periph_unlock(isc->periph);
833 cam_periph_unlock(isc->periph);
838 cam_iosched_control_type_sysctl(SYSCTL_HANDLER_ARGS)
841 struct control_loop *clp;
842 struct cam_iosched_softc *isc;
849 if (value < none || value >= cl_max)
852 p = cam_iosched_control_type_names[value];
854 strlcpy(buf, p, sizeof(buf));
855 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
856 if (error != 0 || req->newptr == NULL)
859 for (i = set_max; i < cl_max; i++) {
860 if (strcmp(buf, cam_iosched_control_type_names[i]) != 0)
862 cam_periph_lock(isc->periph);
864 cam_periph_unlock(isc->periph);
872 cam_iosched_sbintime_sysctl(SYSCTL_HANDLER_ARGS)
879 value = *(sbintime_t *)arg1;
880 us = (uint64_t)value / SBT_1US;
881 snprintf(buf, sizeof(buf), "%ju", (intmax_t)us);
882 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
883 if (error != 0 || req->newptr == NULL)
885 us = strtoul(buf, NULL, 10);
888 *(sbintime_t *)arg1 = us * SBT_1US;
893 cam_iosched_sysctl_latencies(SYSCTL_HANDLER_ARGS)
900 sbuf_new_for_sysctl(&sb, NULL, LAT_BUCKETS * 16, req);
902 for (i = 0; i < LAT_BUCKETS - 1; i++)
903 sbuf_printf(&sb, "%jd,", (intmax_t)latencies[i]);
904 sbuf_printf(&sb, "%jd", (intmax_t)latencies[LAT_BUCKETS - 1]);
905 error = sbuf_finish(&sb);
912 cam_iosched_quanta_sysctl(SYSCTL_HANDLER_ARGS)
917 quanta = (unsigned *)arg1;
920 error = sysctl_handle_int(oidp, (int *)&value, 0, req);
921 if ((error != 0) || (req->newptr == NULL))
924 if (value < 1 || value > hz)
933 cam_iosched_iop_stats_sysctl_init(struct cam_iosched_softc *isc, struct iop_stats *ios, char *name)
935 struct sysctl_oid_list *n;
936 struct sysctl_ctx_list *ctx;
938 ios->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
939 SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, name,
940 CTLFLAG_RD, 0, name);
941 n = SYSCTL_CHILDREN(ios->sysctl_tree);
942 ctx = &ios->sysctl_ctx;
944 SYSCTL_ADD_UQUAD(ctx, n,
945 OID_AUTO, "ema", CTLFLAG_RD,
947 "Fast Exponentially Weighted Moving Average");
948 SYSCTL_ADD_UQUAD(ctx, n,
949 OID_AUTO, "emvar", CTLFLAG_RD,
951 "Fast Exponentially Weighted Moving Variance");
953 SYSCTL_ADD_INT(ctx, n,
954 OID_AUTO, "pending", CTLFLAG_RD,
956 "Instantaneous # of pending transactions");
957 SYSCTL_ADD_INT(ctx, n,
958 OID_AUTO, "count", CTLFLAG_RD,
960 "# of transactions submitted to hardware");
961 SYSCTL_ADD_INT(ctx, n,
962 OID_AUTO, "queued", CTLFLAG_RD,
964 "# of transactions in the queue");
965 SYSCTL_ADD_INT(ctx, n,
966 OID_AUTO, "in", CTLFLAG_RD,
968 "# of transactions queued to driver");
969 SYSCTL_ADD_INT(ctx, n,
970 OID_AUTO, "out", CTLFLAG_RD,
972 "# of transactions completed");
974 SYSCTL_ADD_PROC(ctx, n,
975 OID_AUTO, "limiter", CTLTYPE_STRING | CTLFLAG_RW,
976 ios, 0, cam_iosched_limiter_sysctl, "A",
977 "Current limiting type.");
978 SYSCTL_ADD_INT(ctx, n,
979 OID_AUTO, "min", CTLFLAG_RW,
982 SYSCTL_ADD_INT(ctx, n,
983 OID_AUTO, "max", CTLFLAG_RW,
986 SYSCTL_ADD_INT(ctx, n,
987 OID_AUTO, "current", CTLFLAG_RW,
991 SYSCTL_ADD_PROC(ctx, n,
992 OID_AUTO, "latencies", CTLTYPE_STRING | CTLFLAG_RD,
994 cam_iosched_sysctl_latencies, "A",
995 "Array of power of 2 latency from 1ms to 1.024s");
999 cam_iosched_iop_stats_fini(struct iop_stats *ios)
1001 if (ios->sysctl_tree)
1002 if (sysctl_ctx_free(&ios->sysctl_ctx) != 0)
1003 printf("can't remove iosched sysctl stats context\n");
1007 cam_iosched_cl_sysctl_init(struct cam_iosched_softc *isc)
1009 struct sysctl_oid_list *n;
1010 struct sysctl_ctx_list *ctx;
1011 struct control_loop *clp;
1014 clp->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1015 SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, "control",
1016 CTLFLAG_RD, 0, "Control loop info");
1017 n = SYSCTL_CHILDREN(clp->sysctl_tree);
1018 ctx = &clp->sysctl_ctx;
1020 SYSCTL_ADD_PROC(ctx, n,
1021 OID_AUTO, "type", CTLTYPE_STRING | CTLFLAG_RW,
1022 clp, 0, cam_iosched_control_type_sysctl, "A",
1023 "Control loop algorithm");
1024 SYSCTL_ADD_PROC(ctx, n,
1025 OID_AUTO, "steer_interval", CTLTYPE_STRING | CTLFLAG_RW,
1026 &clp->steer_interval, 0, cam_iosched_sbintime_sysctl, "A",
1027 "How often to steer (in us)");
1028 SYSCTL_ADD_PROC(ctx, n,
1029 OID_AUTO, "lolat", CTLTYPE_STRING | CTLFLAG_RW,
1030 &clp->lolat, 0, cam_iosched_sbintime_sysctl, "A",
1031 "Low water mark for Latency (in us)");
1032 SYSCTL_ADD_PROC(ctx, n,
1033 OID_AUTO, "hilat", CTLTYPE_STRING | CTLFLAG_RW,
1034 &clp->hilat, 0, cam_iosched_sbintime_sysctl, "A",
1035 "Hi water mark for Latency (in us)");
1036 SYSCTL_ADD_INT(ctx, n,
1037 OID_AUTO, "alpha", CTLFLAG_RW,
1039 "Alpha for PLL (x100) aka gain");
1043 cam_iosched_cl_sysctl_fini(struct control_loop *clp)
1045 if (clp->sysctl_tree)
1046 if (sysctl_ctx_free(&clp->sysctl_ctx) != 0)
1047 printf("can't remove iosched sysctl control loop context\n");
1052 * Allocate the iosched structure. This also insulates callers from knowing
1053 * sizeof struct cam_iosched_softc.
1056 cam_iosched_init(struct cam_iosched_softc **iscp, struct cam_periph *periph)
1059 *iscp = malloc(sizeof(**iscp), M_CAMSCHED, M_NOWAIT | M_ZERO);
1062 #ifdef CAM_IOSCHED_DYNAMIC
1064 printf("CAM IOSCHEDULER Allocating entry at %p\n", *iscp);
1066 (*iscp)->sort_io_queue = -1;
1067 bioq_init(&(*iscp)->bio_queue);
1068 bioq_init(&(*iscp)->trim_queue);
1069 #ifdef CAM_IOSCHED_DYNAMIC
1070 if (do_dynamic_iosched) {
1071 bioq_init(&(*iscp)->write_queue);
1072 (*iscp)->read_bias = 100;
1073 (*iscp)->current_read_bias = 100;
1074 (*iscp)->quanta = min(hz, 200);
1075 cam_iosched_iop_stats_init(*iscp, &(*iscp)->read_stats);
1076 cam_iosched_iop_stats_init(*iscp, &(*iscp)->write_stats);
1077 cam_iosched_iop_stats_init(*iscp, &(*iscp)->trim_stats);
1078 (*iscp)->trim_stats.max = 1; /* Trims are special: one at a time for now */
1079 (*iscp)->last_time = sbinuptime();
1080 callout_init_mtx(&(*iscp)->ticker, cam_periph_mtx(periph), 0);
1081 (*iscp)->periph = periph;
1082 cam_iosched_cl_init(&(*iscp)->cl, *iscp);
1083 callout_reset(&(*iscp)->ticker, hz / (*iscp)->quanta, cam_iosched_ticker, *iscp);
1084 (*iscp)->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
1092 * Reclaim all used resources. This assumes that other folks have
1093 * drained the requests in the hardware. Maybe an unwise assumption.
1096 cam_iosched_fini(struct cam_iosched_softc *isc)
1099 cam_iosched_flush(isc, NULL, ENXIO);
1100 #ifdef CAM_IOSCHED_DYNAMIC
1101 cam_iosched_iop_stats_fini(&isc->read_stats);
1102 cam_iosched_iop_stats_fini(&isc->write_stats);
1103 cam_iosched_iop_stats_fini(&isc->trim_stats);
1104 cam_iosched_cl_sysctl_fini(&isc->cl);
1105 if (isc->sysctl_tree)
1106 if (sysctl_ctx_free(&isc->sysctl_ctx) != 0)
1107 printf("can't remove iosched sysctl stats context\n");
1108 if (isc->flags & CAM_IOSCHED_FLAG_CALLOUT_ACTIVE) {
1109 callout_drain(&isc->ticker);
1110 isc->flags &= ~ CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
1113 free(isc, M_CAMSCHED);
1118 * After we're sure we're attaching a device, go ahead and add
1119 * hooks for any sysctl we may wish to honor.
1121 void cam_iosched_sysctl_init(struct cam_iosched_softc *isc,
1122 struct sysctl_ctx_list *ctx, struct sysctl_oid *node)
1124 #ifdef CAM_IOSCHED_DYNAMIC
1125 struct sysctl_oid_list *n;
1128 SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(node),
1129 OID_AUTO, "sort_io_queue", CTLFLAG_RW | CTLFLAG_MPSAFE,
1130 &isc->sort_io_queue, 0,
1131 "Sort IO queue to try and optimise disk access patterns");
1133 #ifdef CAM_IOSCHED_DYNAMIC
1134 if (!do_dynamic_iosched)
1137 isc->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1138 SYSCTL_CHILDREN(node), OID_AUTO, "iosched",
1139 CTLFLAG_RD, 0, "I/O scheduler statistics");
1140 n = SYSCTL_CHILDREN(isc->sysctl_tree);
1141 ctx = &isc->sysctl_ctx;
1143 cam_iosched_iop_stats_sysctl_init(isc, &isc->read_stats, "read");
1144 cam_iosched_iop_stats_sysctl_init(isc, &isc->write_stats, "write");
1145 cam_iosched_iop_stats_sysctl_init(isc, &isc->trim_stats, "trim");
1146 cam_iosched_cl_sysctl_init(isc);
1148 SYSCTL_ADD_INT(ctx, n,
1149 OID_AUTO, "read_bias", CTLFLAG_RW,
1150 &isc->read_bias, 100,
1151 "How biased towards read should we be independent of limits");
1153 SYSCTL_ADD_PROC(ctx, n,
1154 OID_AUTO, "quanta", CTLTYPE_UINT | CTLFLAG_RW,
1155 &isc->quanta, 0, cam_iosched_quanta_sysctl, "I",
1156 "How many quanta per second do we slice the I/O up into");
1158 SYSCTL_ADD_INT(ctx, n,
1159 OID_AUTO, "total_ticks", CTLFLAG_RD,
1160 &isc->total_ticks, 0,
1161 "Total number of ticks we've done");
1163 SYSCTL_ADD_INT(ctx, n,
1164 OID_AUTO, "load", CTLFLAG_RD,
1166 "scaled load average / 100");
1171 * Flush outstanding I/O. Consumers of this library don't know all the
1172 * queues we may keep, so this allows all I/O to be flushed in one
1176 cam_iosched_flush(struct cam_iosched_softc *isc, struct devstat *stp, int err)
1178 bioq_flush(&isc->bio_queue, stp, err);
1179 bioq_flush(&isc->trim_queue, stp, err);
1180 #ifdef CAM_IOSCHED_DYNAMIC
1181 if (do_dynamic_iosched)
1182 bioq_flush(&isc->write_queue, stp, err);
1186 #ifdef CAM_IOSCHED_DYNAMIC
1188 cam_iosched_get_write(struct cam_iosched_softc *isc)
1193 * We control the write rate by controlling how many requests we send
1194 * down to the drive at any one time. Fewer requests limits the
1195 * effects of both starvation when the requests take a while and write
1196 * amplification when each request is causing more than one write to
1197 * the NAND media. Limiting the queue depth like this will also limit
1198 * the write throughput and give and reads that want to compete to
1201 bp = bioq_first(&isc->write_queue);
1203 if (iosched_debug > 3)
1204 printf("No writes present in write_queue\n");
1209 * If pending read, prefer that based on current read bias
1212 if (bioq_first(&isc->bio_queue) && isc->current_read_bias) {
1214 printf("Reads present and current_read_bias is %d queued writes %d queued reads %d\n", isc->current_read_bias, isc->write_stats.queued, isc->read_stats.queued);
1215 isc->current_read_bias--;
1216 /* We're not limiting writes, per se, just doing reads first */
1221 * See if our current limiter allows this I/O.
1223 if (cam_iosched_limiter_iop(&isc->write_stats, bp) != 0) {
1225 printf("Can't write because limiter says no.\n");
1226 isc->write_stats.state_flags |= IOP_RATE_LIMITED;
1231 * Let's do this: We've passed all the gates and we're a go
1232 * to schedule the I/O in the SIM.
1234 isc->current_read_bias = isc->read_bias;
1235 bioq_remove(&isc->write_queue, bp);
1236 if (bp->bio_cmd == BIO_WRITE) {
1237 isc->write_stats.queued--;
1238 isc->write_stats.total++;
1239 isc->write_stats.pending++;
1241 if (iosched_debug > 9)
1242 printf("HWQ : %p %#x\n", bp, bp->bio_cmd);
1243 isc->write_stats.state_flags &= ~IOP_RATE_LIMITED;
1249 * Put back a trim that you weren't able to actually schedule this time.
1252 cam_iosched_put_back_trim(struct cam_iosched_softc *isc, struct bio *bp)
1254 bioq_insert_head(&isc->trim_queue, bp);
1255 #ifdef CAM_IOSCHED_DYNAMIC
1256 isc->trim_stats.queued++;
1257 isc->trim_stats.total--; /* since we put it back, don't double count */
1258 isc->trim_stats.pending--;
1263 * gets the next trim from the trim queue.
1265 * Assumes we're called with the periph lock held. It removes this
1266 * trim from the queue and the device must explicitly reinsert it
1267 * should the need arise.
1270 cam_iosched_next_trim(struct cam_iosched_softc *isc)
1274 bp = bioq_first(&isc->trim_queue);
1277 bioq_remove(&isc->trim_queue, bp);
1278 #ifdef CAM_IOSCHED_DYNAMIC
1279 isc->trim_stats.queued--;
1280 isc->trim_stats.total++;
1281 isc->trim_stats.pending++;
1287 * gets an available trim from the trim queue, if there's no trim
1288 * already pending. It removes this trim from the queue and the device
1289 * must explicitly reinsert it should the need arise.
1291 * Assumes we're called with the periph lock held.
1294 cam_iosched_get_trim(struct cam_iosched_softc *isc)
1297 if (!cam_iosched_has_more_trim(isc))
1300 return cam_iosched_next_trim(isc);
1304 * Determine what the next bit of work to do is for the periph. The
1305 * default implementation looks to see if we have trims to do, but no
1306 * trims outstanding. If so, we do that. Otherwise we see if we have
1307 * other work. If we do, then we do that. Otherwise why were we called?
1310 cam_iosched_next_bio(struct cam_iosched_softc *isc)
1315 * See if we have a trim that can be scheduled. We can only send one
1316 * at a time down, so this takes that into account.
1318 * XXX newer TRIM commands are queueable. Revisit this when we
1321 if ((bp = cam_iosched_get_trim(isc)) != NULL)
1324 #ifdef CAM_IOSCHED_DYNAMIC
1326 * See if we have any pending writes, and room in the queue for them,
1327 * and if so, those are next.
1329 if (do_dynamic_iosched) {
1330 if ((bp = cam_iosched_get_write(isc)) != NULL)
1336 * next, see if there's other, normal I/O waiting. If so return that.
1338 if ((bp = bioq_first(&isc->bio_queue)) == NULL)
1341 #ifdef CAM_IOSCHED_DYNAMIC
1343 * For the dynamic scheduler, bio_queue is only for reads, so enforce
1344 * the limits here. Enforce only for reads.
1346 if (do_dynamic_iosched) {
1347 if (bp->bio_cmd == BIO_READ &&
1348 cam_iosched_limiter_iop(&isc->read_stats, bp) != 0) {
1349 isc->read_stats.state_flags |= IOP_RATE_LIMITED;
1353 isc->read_stats.state_flags &= ~IOP_RATE_LIMITED;
1355 bioq_remove(&isc->bio_queue, bp);
1356 #ifdef CAM_IOSCHED_DYNAMIC
1357 if (do_dynamic_iosched) {
1358 if (bp->bio_cmd == BIO_READ) {
1359 isc->read_stats.queued--;
1360 isc->read_stats.total++;
1361 isc->read_stats.pending++;
1363 printf("Found bio_cmd = %#x\n", bp->bio_cmd);
1365 if (iosched_debug > 9)
1366 printf("HWQ : %p %#x\n", bp, bp->bio_cmd);
1372 * Driver has been given some work to do by the block layer. Tell the
1373 * scheduler about it and have it queue the work up. The scheduler module
1374 * will then return the currently most useful bit of work later, possibly
1375 * deferring work for various reasons.
1378 cam_iosched_queue_work(struct cam_iosched_softc *isc, struct bio *bp)
1382 * Put all trims on the trim queue sorted, since we know
1383 * that the collapsing code requires this. Otherwise put
1384 * the work on the bio queue.
1386 if (bp->bio_cmd == BIO_DELETE) {
1387 bioq_disksort(&isc->trim_queue, bp);
1388 #ifdef CAM_IOSCHED_DYNAMIC
1389 isc->trim_stats.in++;
1390 isc->trim_stats.queued++;
1393 #ifdef CAM_IOSCHED_DYNAMIC
1394 else if (do_dynamic_iosched && (bp->bio_cmd != BIO_READ)) {
1395 if (cam_iosched_sort_queue(isc))
1396 bioq_disksort(&isc->write_queue, bp);
1398 bioq_insert_tail(&isc->write_queue, bp);
1399 if (iosched_debug > 9)
1400 printf("Qw : %p %#x\n", bp, bp->bio_cmd);
1401 if (bp->bio_cmd == BIO_WRITE) {
1402 isc->write_stats.in++;
1403 isc->write_stats.queued++;
1408 if (cam_iosched_sort_queue(isc))
1409 bioq_disksort(&isc->bio_queue, bp);
1411 bioq_insert_tail(&isc->bio_queue, bp);
1412 #ifdef CAM_IOSCHED_DYNAMIC
1413 if (iosched_debug > 9)
1414 printf("Qr : %p %#x\n", bp, bp->bio_cmd);
1415 if (bp->bio_cmd == BIO_READ) {
1416 isc->read_stats.in++;
1417 isc->read_stats.queued++;
1418 } else if (bp->bio_cmd == BIO_WRITE) {
1419 isc->write_stats.in++;
1420 isc->write_stats.queued++;
1427 * If we have work, get it scheduled. Called with the periph lock held.
1430 cam_iosched_schedule(struct cam_iosched_softc *isc, struct cam_periph *periph)
1433 if (cam_iosched_has_work(isc))
1434 xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1438 * Complete a trim request. Mark that we no longer have one in flight.
1441 cam_iosched_trim_done(struct cam_iosched_softc *isc)
1444 isc->flags &= ~CAM_IOSCHED_FLAG_TRIM_ACTIVE;
1448 * Complete a bio. Called before we release the ccb with xpt_release_ccb so we
1449 * might use notes in the ccb for statistics.
1452 cam_iosched_bio_complete(struct cam_iosched_softc *isc, struct bio *bp,
1453 union ccb *done_ccb)
1456 #ifdef CAM_IOSCHED_DYNAMIC
1457 if (!do_dynamic_iosched)
1460 if (iosched_debug > 10)
1461 printf("done: %p %#x\n", bp, bp->bio_cmd);
1462 if (bp->bio_cmd == BIO_WRITE) {
1463 retval = cam_iosched_limiter_iodone(&isc->write_stats, bp);
1464 isc->write_stats.out++;
1465 isc->write_stats.pending--;
1466 } else if (bp->bio_cmd == BIO_READ) {
1467 retval = cam_iosched_limiter_iodone(&isc->read_stats, bp);
1468 isc->read_stats.out++;
1469 isc->read_stats.pending--;
1470 } else if (bp->bio_cmd == BIO_DELETE) {
1471 isc->trim_stats.out++;
1472 isc->trim_stats.pending--;
1473 } else if (bp->bio_cmd != BIO_FLUSH) {
1475 printf("Completing command with bio_cmd == %#x\n", bp->bio_cmd);
1478 if (!(bp->bio_flags & BIO_ERROR))
1479 cam_iosched_io_metric_update(isc,
1480 cam_iosched_sbintime_t(done_ccb->ccb_h.qos.periph_data),
1481 bp->bio_cmd, bp->bio_bcount);
1487 * Tell the io scheduler that you've pushed a trim down into the sim.
1488 * This also tells the I/O scheduler not to push any more trims down, so
1489 * some periphs do not call it if they can cope with multiple trims in flight.
1492 cam_iosched_submit_trim(struct cam_iosched_softc *isc)
1495 isc->flags |= CAM_IOSCHED_FLAG_TRIM_ACTIVE;
1499 * Change the sorting policy hint for I/O transactions for this device.
1502 cam_iosched_set_sort_queue(struct cam_iosched_softc *isc, int val)
1505 isc->sort_io_queue = val;
1509 cam_iosched_has_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1511 return isc->flags & flags;
1515 cam_iosched_set_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1517 isc->flags |= flags;
1521 cam_iosched_clr_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1523 isc->flags &= ~flags;
1526 #ifdef CAM_IOSCHED_DYNAMIC
1528 * After the method presented in Jack Crenshaw's 1998 article "Integer
1529 * Square Roots," reprinted at
1530 * http://www.embedded.com/electronics-blogs/programmer-s-toolbox/4219659/Integer-Square-Roots
1531 * and well worth the read. Briefly, we find the power of 4 that's the
1532 * largest smaller than val. We then check each smaller power of 4 to
1533 * see if val is still bigger. The right shifts at each step divide
1534 * the result by 2 which after successive application winds up
1535 * accumulating the right answer. It could also have been accumulated
1536 * using a separate root counter, but this code is smaller and faster
1537 * than that method. This method is also integer size invariant.
1538 * It returns floor(sqrt((float)val)), or the largest integer less than
1539 * or equal to the square root.
1542 isqrt64(uint64_t val)
1545 uint64_t bit = 1ULL << (sizeof(uint64_t) * NBBY - 2);
1548 * Find the largest power of 4 smaller than val.
1554 * Accumulate the answer, one bit at a time (we keep moving
1555 * them over since 2 is the square root of 4 and we test
1556 * powers of 4). We accumulate where we find the bit, but
1557 * the successive shifts land the bit in the right place
1561 if (val >= res + bit) {
1563 res = (res >> 1) + bit;
1572 static sbintime_t latencies[LAT_BUCKETS - 1] = {
1586 SBT_1MS << 13 /* 8.192s */
1590 cam_iosched_update(struct iop_stats *iop, sbintime_t sim_latency)
1592 sbintime_t y, deltasq, delta;
1596 * Keep counts for latency. We do it by power of two buckets.
1597 * This helps us spot outlier behavior obscured by averages.
1599 for (i = 0; i < LAT_BUCKETS - 1; i++) {
1600 if (sim_latency < latencies[i]) {
1601 iop->latencies[i]++;
1605 if (i == LAT_BUCKETS - 1)
1606 iop->latencies[i]++; /* Put all > 1024ms values into the last bucket. */
1609 * Classic exponentially decaying average with a tiny alpha
1610 * (2 ^ -alpha_bits). For more info see the NIST statistical
1613 * ema_t = y_t * alpha + ema_t-1 * (1 - alpha) [nist]
1614 * ema_t = y_t * alpha + ema_t-1 - alpha * ema_t-1
1615 * ema_t = alpha * y_t - alpha * ema_t-1 + ema_t-1
1616 * alpha = 1 / (1 << alpha_bits)
1617 * sub e == ema_t-1, b == 1/alpha (== 1 << alpha_bits), d == y_t - ema_t-1
1618 * = y_t/b - e/b + be/b
1619 * = (y_t - e + be) / b
1622 * Since alpha is a power of two, we can compute this w/o any mult or
1625 * Variance can also be computed. Usually, it would be expressed as follows:
1626 * diff_t = y_t - ema_t-1
1627 * emvar_t = (1 - alpha) * (emavar_t-1 + diff_t^2 * alpha)
1628 * = emavar_t-1 - alpha * emavar_t-1 + delta_t^2 * alpha - (delta_t * alpha)^2
1629 * sub b == 1/alpha (== 1 << alpha_bits), e == emavar_t-1, d = delta_t^2
1630 * = e - e/b + dd/b + dd/bb
1631 * = (bbe - be + bdd + dd) / bb
1632 * = (bbe + b(dd-e) + dd) / bb (which is expanded below bb = 1<<(2*alpha_bits))
1635 * XXX possible numeric issues
1636 * o We assume right shifted integers do the right thing, since that's
1637 * implementation defined. You can change the right shifts to / (1LL << alpha).
1638 * o alpha_bits = 9 gives ema ceiling of 23 bits of seconds for ema and 14 bits
1639 * for emvar. This puts a ceiling of 13 bits on alpha since we need a
1640 * few tens of seconds of representation.
1641 * o We mitigate alpha issues by never setting it too high.
1644 delta = (y - iop->ema); /* d */
1645 iop->ema = ((iop->ema << alpha_bits) + delta) >> alpha_bits;
1648 * Were we to naively plow ahead at this point, we wind up with many numerical
1649 * issues making any SD > ~3ms unreliable. So, we shift right by 12. This leaves
1650 * us with microsecond level precision in the input, so the same in the
1651 * output. It means we can't overflow deltasq unless delta > 4k seconds. It
1652 * also means that emvar can be up 46 bits 40 of which are fraction, which
1653 * gives us a way to measure up to ~8s in the SD before the computation goes
1654 * unstable. Even the worst hard disk rarely has > 1s service time in the
1655 * drive. It does mean we have to shift left 12 bits after taking the
1656 * square root to compute the actual standard deviation estimate. This loss of
1657 * precision is preferable to needing int128 types to work. The above numbers
1658 * assume alpha=9. 10 or 11 are ok, but we start to run into issues at 12,
1659 * so 12 or 13 is OK for EMA, EMVAR and SD will be wrong in those cases.
1662 deltasq = delta * delta; /* dd */
1663 iop->emvar = ((iop->emvar << (2 * alpha_bits)) + /* bbe */
1664 ((deltasq - iop->emvar) << alpha_bits) + /* b(dd-e) */
1666 >> (2 * alpha_bits); /* div bb */
1667 iop->sd = (sbintime_t)isqrt64((uint64_t)iop->emvar) << 12;
1671 cam_iosched_io_metric_update(struct cam_iosched_softc *isc,
1672 sbintime_t sim_latency, int cmd, size_t size)
1674 /* xxx Do we need to scale based on the size of the I/O ? */
1677 cam_iosched_update(&isc->read_stats, sim_latency);
1680 cam_iosched_update(&isc->write_stats, sim_latency);
1683 cam_iosched_update(&isc->trim_stats, sim_latency);
1691 static int biolen(struct bio_queue_head *bq)
1696 TAILQ_FOREACH(bp, &bq->queue, bio_queue) {
1703 * Show the internal state of the I/O scheduler.
1705 DB_SHOW_COMMAND(iosched, cam_iosched_db_show)
1707 struct cam_iosched_softc *isc;
1710 db_printf("Need addr\n");
1713 isc = (struct cam_iosched_softc *)addr;
1714 db_printf("pending_reads: %d\n", isc->read_stats.pending);
1715 db_printf("min_reads: %d\n", isc->read_stats.min);
1716 db_printf("max_reads: %d\n", isc->read_stats.max);
1717 db_printf("reads: %d\n", isc->read_stats.total);
1718 db_printf("in_reads: %d\n", isc->read_stats.in);
1719 db_printf("out_reads: %d\n", isc->read_stats.out);
1720 db_printf("queued_reads: %d\n", isc->read_stats.queued);
1721 db_printf("Current Q len %d\n", biolen(&isc->bio_queue));
1722 db_printf("pending_writes: %d\n", isc->write_stats.pending);
1723 db_printf("min_writes: %d\n", isc->write_stats.min);
1724 db_printf("max_writes: %d\n", isc->write_stats.max);
1725 db_printf("writes: %d\n", isc->write_stats.total);
1726 db_printf("in_writes: %d\n", isc->write_stats.in);
1727 db_printf("out_writes: %d\n", isc->write_stats.out);
1728 db_printf("queued_writes: %d\n", isc->write_stats.queued);
1729 db_printf("Current Q len %d\n", biolen(&isc->write_queue));
1730 db_printf("pending_trims: %d\n", isc->trim_stats.pending);
1731 db_printf("min_trims: %d\n", isc->trim_stats.min);
1732 db_printf("max_trims: %d\n", isc->trim_stats.max);
1733 db_printf("trims: %d\n", isc->trim_stats.total);
1734 db_printf("in_trims: %d\n", isc->trim_stats.in);
1735 db_printf("out_trims: %d\n", isc->trim_stats.out);
1736 db_printf("queued_trims: %d\n", isc->trim_stats.queued);
1737 db_printf("Current Q len %d\n", biolen(&isc->trim_queue));
1738 db_printf("read_bias: %d\n", isc->read_bias);
1739 db_printf("current_read_bias: %d\n", isc->current_read_bias);
1740 db_printf("Trim active? %s\n",
1741 (isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) ? "yes" : "no");