2 * CAM IO Scheduler Interface
4 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
6 * Copyright (c) 2015 Netflix, Inc.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions, and the following disclaimer,
14 * without modification, immediately at the beginning of the file.
15 * 2. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
45 #include <sys/malloc.h>
46 #include <sys/mutex.h>
48 #include <sys/sysctl.h>
51 #include <cam/cam_ccb.h>
52 #include <cam/cam_periph.h>
53 #include <cam/cam_xpt_periph.h>
54 #include <cam/cam_xpt_internal.h>
55 #include <cam/cam_iosched.h>
59 static MALLOC_DEFINE(M_CAMSCHED, "CAM I/O Scheduler",
60 "CAM I/O Scheduler buffers");
63 * Default I/O scheduler for FreeBSD. This implementation is just a thin-vineer
64 * over the bioq_* interface, with notions of separate calls for normal I/O and
67 * When CAM_IOSCHED_DYNAMIC is defined, the scheduler is enhanced to dynamically
68 * steer the rate of one type of traffic to help other types of traffic (eg
69 * limit writes when read latency deteriorates on SSDs).
72 #ifdef CAM_IOSCHED_DYNAMIC
74 static int do_dynamic_iosched = 1;
75 TUNABLE_INT("kern.cam.do_dynamic_iosched", &do_dynamic_iosched);
76 SYSCTL_INT(_kern_cam, OID_AUTO, do_dynamic_iosched, CTLFLAG_RD,
77 &do_dynamic_iosched, 1,
78 "Enable Dynamic I/O scheduler optimizations.");
81 * For an EMA, with an alpha of alpha, we know
85 * where N is the number of samples that 86% of the current
86 * EMA is derived from.
88 * So we invent[*] alpha_bits:
89 * alpha_bits = -log_2(alpha)
90 * alpha = 2^-alpha_bits
92 * N = 1 + 2^(alpha_bits + 1)
94 * The default 9 gives a 1025 lookback for 86% of the data.
95 * For a brief intro: https://en.wikipedia.org/wiki/Moving_average
97 * [*] Steal from the load average code and many other places.
98 * Note: See computation of EMA and EMVAR for acceptable ranges of alpha.
100 static int alpha_bits = 9;
101 TUNABLE_INT("kern.cam.iosched_alpha_bits", &alpha_bits);
102 SYSCTL_INT(_kern_cam, OID_AUTO, iosched_alpha_bits, CTLFLAG_RW,
104 "Bits in EMA's alpha.");
107 struct cam_iosched_softc;
109 int iosched_debug = 0;
112 none = 0, /* No limits */
113 queue_depth, /* Limit how many ops we queue to SIM */
114 iops, /* Limit # of IOPS to the drive */
115 bandwidth, /* Limit bandwidth to the drive */
119 static const char *cam_iosched_limiter_names[] =
120 { "none", "queue_depth", "iops", "bandwidth" };
123 * Called to initialize the bits of the iop_stats structure relevant to the
124 * limiter. Called just after the limiter is set.
126 typedef int l_init_t(struct iop_stats *);
131 typedef int l_tick_t(struct iop_stats *);
134 * Called to see if the limiter thinks this IOP can be allowed to
135 * proceed. If so, the limiter assumes that the IOP proceeded
136 * and makes any accounting of it that's needed.
138 typedef int l_iop_t(struct iop_stats *, struct bio *);
141 * Called when an I/O completes so the limiter can update its
142 * accounting. Pending I/Os may complete in any order (even when
143 * sent to the hardware at the same time), so the limiter may not
144 * make any assumptions other than this I/O has completed. If it
145 * returns 1, then xpt_schedule() needs to be called again.
147 typedef int l_iodone_t(struct iop_stats *, struct bio *);
149 static l_iop_t cam_iosched_qd_iop;
150 static l_iop_t cam_iosched_qd_caniop;
151 static l_iodone_t cam_iosched_qd_iodone;
153 static l_init_t cam_iosched_iops_init;
154 static l_tick_t cam_iosched_iops_tick;
155 static l_iop_t cam_iosched_iops_caniop;
156 static l_iop_t cam_iosched_iops_iop;
158 static l_init_t cam_iosched_bw_init;
159 static l_tick_t cam_iosched_bw_tick;
160 static l_iop_t cam_iosched_bw_caniop;
161 static l_iop_t cam_iosched_bw_iop;
168 l_iodone_t *l_iodone;
180 .l_caniop = cam_iosched_qd_caniop,
181 .l_iop = cam_iosched_qd_iop,
182 .l_iodone= cam_iosched_qd_iodone,
185 .l_init = cam_iosched_iops_init,
186 .l_tick = cam_iosched_iops_tick,
187 .l_caniop = cam_iosched_iops_caniop,
188 .l_iop = cam_iosched_iops_iop,
192 .l_init = cam_iosched_bw_init,
193 .l_tick = cam_iosched_bw_tick,
194 .l_caniop = cam_iosched_bw_caniop,
195 .l_iop = cam_iosched_bw_iop,
202 * sysctl state for this subnode.
204 struct sysctl_ctx_list sysctl_ctx;
205 struct sysctl_oid *sysctl_tree;
208 * Information about the current rate limiters, if any
210 io_limiter limiter; /* How are I/Os being limited */
211 int min; /* Low range of limit */
212 int max; /* High range of limit */
213 int current; /* Current rate limiter */
214 int l_value1; /* per-limiter scratch value 1. */
215 int l_value2; /* per-limiter scratch value 2. */
218 * Debug information about counts of I/Os that have gone through the
221 int pending; /* I/Os pending in the hardware */
222 int queued; /* number currently in the queue */
223 int total; /* Total for all time -- wraps */
224 int in; /* number queued all time -- wraps */
225 int out; /* number completed all time -- wraps */
226 int errs; /* Number of I/Os completed with error -- wraps */
229 * Statistics on different bits of the process.
231 /* Exp Moving Average, see alpha_bits for more details */
234 sbintime_t sd; /* Last computed sd */
236 uint32_t state_flags;
237 #define IOP_RATE_LIMITED 1u
239 #define LAT_BUCKETS 15 /* < 1ms < 2ms ... < 2^(n-1)ms >= 2^(n-1)ms*/
240 uint64_t latencies[LAT_BUCKETS];
242 struct cam_iosched_softc *softc;
247 set_max = 0, /* current = max */
248 read_latency, /* Steer read latency by throttling writes */
249 cl_max /* Keep last */
252 static const char *cam_iosched_control_type_names[] =
253 { "set_max", "read_latency" };
255 struct control_loop {
257 * sysctl state for this subnode.
259 struct sysctl_ctx_list sysctl_ctx;
260 struct sysctl_oid *sysctl_tree;
262 sbintime_t next_steer; /* Time of next steer */
263 sbintime_t steer_interval; /* How often do we steer? */
267 control_type type; /* What type of control? */
268 int last_count; /* Last I/O count */
270 struct cam_iosched_softc *softc;
275 struct cam_iosched_softc {
276 struct bio_queue_head bio_queue;
277 struct bio_queue_head trim_queue;
278 /* scheduler flags < 16, user flags >= 16 */
281 #ifdef CAM_IOSCHED_DYNAMIC
282 int read_bias; /* Read bias setting */
283 int current_read_bias; /* Current read bias state */
285 int load; /* EMA of 'load average' of disk / 2^16 */
287 struct bio_queue_head write_queue;
288 struct iop_stats read_stats, write_stats, trim_stats;
289 struct sysctl_ctx_list sysctl_ctx;
290 struct sysctl_oid *sysctl_tree;
292 int quanta; /* Number of quanta per second */
293 struct callout ticker; /* Callout for our quota system */
294 struct cam_periph *periph; /* cam periph associated with this device */
295 uint32_t this_frac; /* Fraction of a second (1024ths) for this tick */
296 sbintime_t last_time; /* Last time we ticked */
297 struct control_loop cl;
301 #ifdef CAM_IOSCHED_DYNAMIC
303 * helper functions to call the limsw functions.
306 cam_iosched_limiter_init(struct iop_stats *ios)
308 int lim = ios->limiter;
310 /* maybe this should be a kassert */
311 if (lim < none || lim >= limiter_max)
314 if (limsw[lim].l_init)
315 return limsw[lim].l_init(ios);
321 cam_iosched_limiter_tick(struct iop_stats *ios)
323 int lim = ios->limiter;
325 /* maybe this should be a kassert */
326 if (lim < none || lim >= limiter_max)
329 if (limsw[lim].l_tick)
330 return limsw[lim].l_tick(ios);
336 cam_iosched_limiter_iop(struct iop_stats *ios, struct bio *bp)
338 int lim = ios->limiter;
340 /* maybe this should be a kassert */
341 if (lim < none || lim >= limiter_max)
344 if (limsw[lim].l_iop)
345 return limsw[lim].l_iop(ios, bp);
351 cam_iosched_limiter_caniop(struct iop_stats *ios, struct bio *bp)
353 int lim = ios->limiter;
355 /* maybe this should be a kassert */
356 if (lim < none || lim >= limiter_max)
359 if (limsw[lim].l_caniop)
360 return limsw[lim].l_caniop(ios, bp);
366 cam_iosched_limiter_iodone(struct iop_stats *ios, struct bio *bp)
368 int lim = ios->limiter;
370 /* maybe this should be a kassert */
371 if (lim < none || lim >= limiter_max)
374 if (limsw[lim].l_iodone)
375 return limsw[lim].l_iodone(ios, bp);
381 * Functions to implement the different kinds of limiters
385 cam_iosched_qd_iop(struct iop_stats *ios, struct bio *bp)
388 if (ios->current <= 0 || ios->pending < ios->current)
395 cam_iosched_qd_caniop(struct iop_stats *ios, struct bio *bp)
398 if (ios->current <= 0 || ios->pending < ios->current)
405 cam_iosched_qd_iodone(struct iop_stats *ios, struct bio *bp)
408 if (ios->current <= 0 || ios->pending != ios->current)
415 cam_iosched_iops_init(struct iop_stats *ios)
418 ios->l_value1 = ios->current / ios->softc->quanta;
419 if (ios->l_value1 <= 0)
427 cam_iosched_iops_tick(struct iop_stats *ios)
432 * Allow at least one IO per tick until all
433 * the IOs for this interval have been spent.
435 new_ios = (int)((ios->current * (uint64_t)ios->softc->this_frac) >> 16);
436 if (new_ios < 1 && ios->l_value2 < ios->current) {
442 * If this a new accounting interval, discard any "unspent" ios
443 * granted in the previous interval. Otherwise add the new ios to
444 * the previously granted ones that haven't been spent yet.
446 if ((ios->softc->total_ticks % ios->softc->quanta) == 0) {
447 ios->l_value1 = new_ios;
450 ios->l_value1 += new_ios;
458 cam_iosched_iops_caniop(struct iop_stats *ios, struct bio *bp)
462 * So if we have any more IOPs left, allow it,
463 * otherwise wait. If current iops is 0, treat that
464 * as unlimited as a failsafe.
466 if (ios->current > 0 && ios->l_value1 <= 0)
472 cam_iosched_iops_iop(struct iop_stats *ios, struct bio *bp)
476 rv = cam_iosched_limiter_caniop(ios, bp);
484 cam_iosched_bw_init(struct iop_stats *ios)
487 /* ios->current is in kB/s, so scale to bytes */
488 ios->l_value1 = ios->current * 1000 / ios->softc->quanta;
494 cam_iosched_bw_tick(struct iop_stats *ios)
499 * If we're in the hole for available quota from
500 * the last time, then add the quantum for this.
501 * If we have any left over from last quantum,
502 * then too bad, that's lost. Also, ios->current
503 * is in kB/s, so scale.
505 * We also allow up to 4 quanta of credits to
506 * accumulate to deal with burstiness. 4 is extremely
509 bw = (int)((ios->current * 1000ull * (uint64_t)ios->softc->this_frac) >> 16);
510 if (ios->l_value1 < bw * 4)
517 cam_iosched_bw_caniop(struct iop_stats *ios, struct bio *bp)
520 * So if we have any more bw quota left, allow it,
521 * otherwise wait. Note, we'll go negative and that's
522 * OK. We'll just get a little less next quota.
524 * Note on going negative: that allows us to process
525 * requests in order better, since we won't allow
526 * shorter reads to get around the long one that we
527 * don't have the quota to do just yet. It also prevents
528 * starvation by being a little more permissive about
529 * what we let through this quantum (to prevent the
530 * starvation), at the cost of getting a little less
533 * Also note that if the current limit is <= 0,
534 * we treat it as unlimited as a failsafe.
536 if (ios->current > 0 && ios->l_value1 <= 0)
544 cam_iosched_bw_iop(struct iop_stats *ios, struct bio *bp)
548 rv = cam_iosched_limiter_caniop(ios, bp);
550 ios->l_value1 -= bp->bio_length;
555 static void cam_iosched_cl_maybe_steer(struct control_loop *clp);
558 cam_iosched_ticker(void *arg)
560 struct cam_iosched_softc *isc = arg;
561 sbintime_t now, delta;
564 callout_reset(&isc->ticker, hz / isc->quanta, cam_iosched_ticker, isc);
567 delta = now - isc->last_time;
568 isc->this_frac = (uint32_t)delta >> 16; /* Note: discards seconds -- should be 0 harmless if not */
569 isc->last_time = now;
571 cam_iosched_cl_maybe_steer(&isc->cl);
573 cam_iosched_limiter_tick(&isc->read_stats);
574 cam_iosched_limiter_tick(&isc->write_stats);
575 cam_iosched_limiter_tick(&isc->trim_stats);
577 cam_iosched_schedule(isc, isc->periph);
580 * isc->load is an EMA of the pending I/Os at each tick. The number of
581 * pending I/Os is the sum of the I/Os queued to the hardware, and those
582 * in the software queue that could be queued to the hardware if there
585 * ios_stats.pending is a count of requests in the SIM right now for
586 * each of these types of I/O. So the total pending count is the sum of
587 * these I/Os and the sum of the queued I/Os still in the software queue
588 * for those operations that aren't being rate limited at the moment.
590 * The reason for the rate limiting bit is because those I/Os
591 * aren't part of the software queued load (since we could
592 * give them to hardware, but choose not to).
594 * Note: due to a bug in counting pending TRIM in the device, we
595 * don't include them in this count. We count each BIO_DELETE in
596 * the pending count, but the periph drivers collapse them down
597 * into one TRIM command. That one trim command gets the completion
598 * so the counts get off.
600 pending = isc->read_stats.pending + isc->write_stats.pending /* + isc->trim_stats.pending */;
601 pending += !!(isc->read_stats.state_flags & IOP_RATE_LIMITED) * isc->read_stats.queued +
602 !!(isc->write_stats.state_flags & IOP_RATE_LIMITED) * isc->write_stats.queued /* +
603 !!(isc->trim_stats.state_flags & IOP_RATE_LIMITED) * isc->trim_stats.queued */ ;
605 pending /= isc->periph->path->device->ccbq.total_openings;
607 isc->load = (pending + (isc->load << 13) - isc->load) >> 13; /* see above: 13 -> 16139 / 200/s = ~81s ~1 minute */
614 cam_iosched_cl_init(struct control_loop *clp, struct cam_iosched_softc *isc)
617 clp->next_steer = sbinuptime();
619 clp->steer_interval = SBT_1S * 5; /* Let's start out steering every 5s */
620 clp->lolat = 5 * SBT_1MS;
621 clp->hilat = 15 * SBT_1MS;
622 clp->alpha = 20; /* Alpha == gain. 20 = .2 */
627 cam_iosched_cl_maybe_steer(struct control_loop *clp)
629 struct cam_iosched_softc *isc;
634 now = isc->last_time;
635 if (now < clp->next_steer)
638 clp->next_steer = now + clp->steer_interval;
641 if (isc->write_stats.current != isc->write_stats.max)
642 printf("Steering write from %d kBps to %d kBps\n",
643 isc->write_stats.current, isc->write_stats.max);
644 isc->read_stats.current = isc->read_stats.max;
645 isc->write_stats.current = isc->write_stats.max;
646 isc->trim_stats.current = isc->trim_stats.max;
649 old = isc->write_stats.current;
650 lat = isc->read_stats.ema;
652 * Simple PLL-like engine. Since we're steering to a range for
653 * the SP (set point) that makes things a little more
654 * complicated. In addition, we're not directly controlling our
655 * PV (process variable), the read latency, but instead are
656 * manipulating the write bandwidth limit for our MV
657 * (manipulation variable), analysis of this code gets a bit
658 * messy. Also, the MV is a very noisy control surface for read
659 * latency since it is affected by many hidden processes inside
660 * the device which change how responsive read latency will be
661 * in reaction to changes in write bandwidth. Unlike the classic
662 * boiler control PLL. this may result in over-steering while
663 * the SSD takes its time to react to the new, lower load. This
664 * is why we use a relatively low alpha of between .1 and .25 to
665 * compensate for this effect. At .1, it takes ~22 steering
666 * intervals to back off by a factor of 10. At .2 it only takes
667 * ~10. At .25 it only takes ~8. However some preliminary data
668 * from the SSD drives suggests a reasponse time in 10's of
669 * seconds before latency drops regardless of the new write
670 * rate. Careful observation will be required to tune this
673 * Also, when there's no read traffic, we jack up the write
674 * limit too regardless of the last read latency. 10 is
675 * somewhat arbitrary.
677 if (lat < clp->lolat || isc->read_stats.total - clp->last_count < 10)
678 isc->write_stats.current = isc->write_stats.current *
679 (100 + clp->alpha) / 100; /* Scale up */
680 else if (lat > clp->hilat)
681 isc->write_stats.current = isc->write_stats.current *
682 (100 - clp->alpha) / 100; /* Scale down */
683 clp->last_count = isc->read_stats.total;
686 * Even if we don't steer, per se, enforce the min/max limits as
687 * those may have changed.
689 if (isc->write_stats.current < isc->write_stats.min)
690 isc->write_stats.current = isc->write_stats.min;
691 if (isc->write_stats.current > isc->write_stats.max)
692 isc->write_stats.current = isc->write_stats.max;
693 if (old != isc->write_stats.current && iosched_debug)
694 printf("Steering write from %d kBps to %d kBps due to latency of %jdus\n",
695 old, isc->write_stats.current,
696 (uintmax_t)((uint64_t)1000000 * (uint32_t)lat) >> 32);
705 * Trim or similar currently pending completion. Should only be set for
706 * those drivers wishing only one Trim active at a time.
708 #define CAM_IOSCHED_FLAG_TRIM_ACTIVE (1ul << 0)
709 /* Callout active, and needs to be torn down */
710 #define CAM_IOSCHED_FLAG_CALLOUT_ACTIVE (1ul << 1)
712 /* Periph drivers set these flags to indicate work */
713 #define CAM_IOSCHED_FLAG_WORK_FLAGS ((0xffffu) << 16)
715 #ifdef CAM_IOSCHED_DYNAMIC
717 cam_iosched_io_metric_update(struct cam_iosched_softc *isc,
718 sbintime_t sim_latency, int cmd, size_t size);
722 cam_iosched_has_flagged_work(struct cam_iosched_softc *isc)
724 return !!(isc->flags & CAM_IOSCHED_FLAG_WORK_FLAGS);
728 cam_iosched_has_io(struct cam_iosched_softc *isc)
730 #ifdef CAM_IOSCHED_DYNAMIC
731 if (do_dynamic_iosched) {
732 struct bio *rbp = bioq_first(&isc->bio_queue);
733 struct bio *wbp = bioq_first(&isc->write_queue);
734 int can_write = wbp != NULL &&
735 cam_iosched_limiter_caniop(&isc->write_stats, wbp) == 0;
736 int can_read = rbp != NULL &&
737 cam_iosched_limiter_caniop(&isc->read_stats, rbp) == 0;
738 if (iosched_debug > 2) {
739 printf("can write %d: pending_writes %d max_writes %d\n", can_write, isc->write_stats.pending, isc->write_stats.max);
740 printf("can read %d: read_stats.pending %d max_reads %d\n", can_read, isc->read_stats.pending, isc->read_stats.max);
741 printf("Queued reads %d writes %d\n", isc->read_stats.queued, isc->write_stats.queued);
743 return can_read || can_write;
746 return bioq_first(&isc->bio_queue) != NULL;
750 cam_iosched_has_more_trim(struct cam_iosched_softc *isc)
752 return !(isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) &&
753 bioq_first(&isc->trim_queue);
756 #define cam_iosched_sort_queue(isc) ((isc)->sort_io_queue >= 0 ? \
757 (isc)->sort_io_queue : cam_sort_io_queues)
761 cam_iosched_has_work(struct cam_iosched_softc *isc)
763 #ifdef CAM_IOSCHED_DYNAMIC
764 if (iosched_debug > 2)
765 printf("has work: %d %d %d\n", cam_iosched_has_io(isc),
766 cam_iosched_has_more_trim(isc),
767 cam_iosched_has_flagged_work(isc));
770 return cam_iosched_has_io(isc) ||
771 cam_iosched_has_more_trim(isc) ||
772 cam_iosched_has_flagged_work(isc);
775 #ifdef CAM_IOSCHED_DYNAMIC
777 cam_iosched_iop_stats_init(struct cam_iosched_softc *isc, struct iop_stats *ios)
782 ios->max = ios->current = 300000;
792 cam_iosched_limiter_init(ios);
796 cam_iosched_limiter_sysctl(SYSCTL_HANDLER_ARGS)
799 struct iop_stats *ios;
800 struct cam_iosched_softc *isc;
806 value = ios->limiter;
807 if (value < none || value >= limiter_max)
810 p = cam_iosched_limiter_names[value];
812 strlcpy(buf, p, sizeof(buf));
813 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
814 if (error != 0 || req->newptr == NULL)
817 cam_periph_lock(isc->periph);
819 for (i = none; i < limiter_max; i++) {
820 if (strcmp(buf, cam_iosched_limiter_names[i]) != 0)
823 error = cam_iosched_limiter_init(ios);
825 ios->limiter = value;
826 cam_periph_unlock(isc->periph);
829 /* Note: disk load averate requires ticker to be always running */
830 callout_reset(&isc->ticker, hz / isc->quanta, cam_iosched_ticker, isc);
831 isc->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
833 cam_periph_unlock(isc->periph);
837 cam_periph_unlock(isc->periph);
842 cam_iosched_control_type_sysctl(SYSCTL_HANDLER_ARGS)
845 struct control_loop *clp;
846 struct cam_iosched_softc *isc;
853 if (value < none || value >= cl_max)
856 p = cam_iosched_control_type_names[value];
858 strlcpy(buf, p, sizeof(buf));
859 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
860 if (error != 0 || req->newptr == NULL)
863 for (i = set_max; i < cl_max; i++) {
864 if (strcmp(buf, cam_iosched_control_type_names[i]) != 0)
866 cam_periph_lock(isc->periph);
868 cam_periph_unlock(isc->periph);
876 cam_iosched_sbintime_sysctl(SYSCTL_HANDLER_ARGS)
883 value = *(sbintime_t *)arg1;
884 us = (uint64_t)value / SBT_1US;
885 snprintf(buf, sizeof(buf), "%ju", (intmax_t)us);
886 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
887 if (error != 0 || req->newptr == NULL)
889 us = strtoul(buf, NULL, 10);
892 *(sbintime_t *)arg1 = us * SBT_1US;
897 cam_iosched_sysctl_latencies(SYSCTL_HANDLER_ARGS)
904 sbuf_new_for_sysctl(&sb, NULL, LAT_BUCKETS * 16, req);
906 for (i = 0; i < LAT_BUCKETS - 1; i++)
907 sbuf_printf(&sb, "%jd,", (intmax_t)latencies[i]);
908 sbuf_printf(&sb, "%jd", (intmax_t)latencies[LAT_BUCKETS - 1]);
909 error = sbuf_finish(&sb);
916 cam_iosched_quanta_sysctl(SYSCTL_HANDLER_ARGS)
921 quanta = (unsigned *)arg1;
924 error = sysctl_handle_int(oidp, (int *)&value, 0, req);
925 if ((error != 0) || (req->newptr == NULL))
928 if (value < 1 || value > hz)
937 cam_iosched_iop_stats_sysctl_init(struct cam_iosched_softc *isc, struct iop_stats *ios, char *name)
939 struct sysctl_oid_list *n;
940 struct sysctl_ctx_list *ctx;
942 ios->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
943 SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, name,
944 CTLFLAG_RD, 0, name);
945 n = SYSCTL_CHILDREN(ios->sysctl_tree);
946 ctx = &ios->sysctl_ctx;
948 SYSCTL_ADD_UQUAD(ctx, n,
949 OID_AUTO, "ema", CTLFLAG_RD,
951 "Fast Exponentially Weighted Moving Average");
952 SYSCTL_ADD_UQUAD(ctx, n,
953 OID_AUTO, "emvar", CTLFLAG_RD,
955 "Fast Exponentially Weighted Moving Variance");
957 SYSCTL_ADD_INT(ctx, n,
958 OID_AUTO, "pending", CTLFLAG_RD,
960 "Instantaneous # of pending transactions");
961 SYSCTL_ADD_INT(ctx, n,
962 OID_AUTO, "count", CTLFLAG_RD,
964 "# of transactions submitted to hardware");
965 SYSCTL_ADD_INT(ctx, n,
966 OID_AUTO, "queued", CTLFLAG_RD,
968 "# of transactions in the queue");
969 SYSCTL_ADD_INT(ctx, n,
970 OID_AUTO, "in", CTLFLAG_RD,
972 "# of transactions queued to driver");
973 SYSCTL_ADD_INT(ctx, n,
974 OID_AUTO, "out", CTLFLAG_RD,
976 "# of transactions completed (including with error)");
977 SYSCTL_ADD_INT(ctx, n,
978 OID_AUTO, "errs", CTLFLAG_RD,
980 "# of transactions completed with an error");
982 SYSCTL_ADD_PROC(ctx, n,
983 OID_AUTO, "limiter", CTLTYPE_STRING | CTLFLAG_RW,
984 ios, 0, cam_iosched_limiter_sysctl, "A",
985 "Current limiting type.");
986 SYSCTL_ADD_INT(ctx, n,
987 OID_AUTO, "min", CTLFLAG_RW,
990 SYSCTL_ADD_INT(ctx, n,
991 OID_AUTO, "max", CTLFLAG_RW,
994 SYSCTL_ADD_INT(ctx, n,
995 OID_AUTO, "current", CTLFLAG_RW,
999 SYSCTL_ADD_PROC(ctx, n,
1000 OID_AUTO, "latencies", CTLTYPE_STRING | CTLFLAG_RD,
1002 cam_iosched_sysctl_latencies, "A",
1003 "Array of power of 2 latency from 1ms to 1.024s");
1007 cam_iosched_iop_stats_fini(struct iop_stats *ios)
1009 if (ios->sysctl_tree)
1010 if (sysctl_ctx_free(&ios->sysctl_ctx) != 0)
1011 printf("can't remove iosched sysctl stats context\n");
1015 cam_iosched_cl_sysctl_init(struct cam_iosched_softc *isc)
1017 struct sysctl_oid_list *n;
1018 struct sysctl_ctx_list *ctx;
1019 struct control_loop *clp;
1022 clp->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1023 SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, "control",
1024 CTLFLAG_RD, 0, "Control loop info");
1025 n = SYSCTL_CHILDREN(clp->sysctl_tree);
1026 ctx = &clp->sysctl_ctx;
1028 SYSCTL_ADD_PROC(ctx, n,
1029 OID_AUTO, "type", CTLTYPE_STRING | CTLFLAG_RW,
1030 clp, 0, cam_iosched_control_type_sysctl, "A",
1031 "Control loop algorithm");
1032 SYSCTL_ADD_PROC(ctx, n,
1033 OID_AUTO, "steer_interval", CTLTYPE_STRING | CTLFLAG_RW,
1034 &clp->steer_interval, 0, cam_iosched_sbintime_sysctl, "A",
1035 "How often to steer (in us)");
1036 SYSCTL_ADD_PROC(ctx, n,
1037 OID_AUTO, "lolat", CTLTYPE_STRING | CTLFLAG_RW,
1038 &clp->lolat, 0, cam_iosched_sbintime_sysctl, "A",
1039 "Low water mark for Latency (in us)");
1040 SYSCTL_ADD_PROC(ctx, n,
1041 OID_AUTO, "hilat", CTLTYPE_STRING | CTLFLAG_RW,
1042 &clp->hilat, 0, cam_iosched_sbintime_sysctl, "A",
1043 "Hi water mark for Latency (in us)");
1044 SYSCTL_ADD_INT(ctx, n,
1045 OID_AUTO, "alpha", CTLFLAG_RW,
1047 "Alpha for PLL (x100) aka gain");
1051 cam_iosched_cl_sysctl_fini(struct control_loop *clp)
1053 if (clp->sysctl_tree)
1054 if (sysctl_ctx_free(&clp->sysctl_ctx) != 0)
1055 printf("can't remove iosched sysctl control loop context\n");
1060 * Allocate the iosched structure. This also insulates callers from knowing
1061 * sizeof struct cam_iosched_softc.
1064 cam_iosched_init(struct cam_iosched_softc **iscp, struct cam_periph *periph)
1067 *iscp = malloc(sizeof(**iscp), M_CAMSCHED, M_NOWAIT | M_ZERO);
1070 #ifdef CAM_IOSCHED_DYNAMIC
1072 printf("CAM IOSCHEDULER Allocating entry at %p\n", *iscp);
1074 (*iscp)->sort_io_queue = -1;
1075 bioq_init(&(*iscp)->bio_queue);
1076 bioq_init(&(*iscp)->trim_queue);
1077 #ifdef CAM_IOSCHED_DYNAMIC
1078 if (do_dynamic_iosched) {
1079 bioq_init(&(*iscp)->write_queue);
1080 (*iscp)->read_bias = 100;
1081 (*iscp)->current_read_bias = 100;
1082 (*iscp)->quanta = min(hz, 200);
1083 cam_iosched_iop_stats_init(*iscp, &(*iscp)->read_stats);
1084 cam_iosched_iop_stats_init(*iscp, &(*iscp)->write_stats);
1085 cam_iosched_iop_stats_init(*iscp, &(*iscp)->trim_stats);
1086 (*iscp)->trim_stats.max = 1; /* Trims are special: one at a time for now */
1087 (*iscp)->last_time = sbinuptime();
1088 callout_init_mtx(&(*iscp)->ticker, cam_periph_mtx(periph), 0);
1089 (*iscp)->periph = periph;
1090 cam_iosched_cl_init(&(*iscp)->cl, *iscp);
1091 callout_reset(&(*iscp)->ticker, hz / (*iscp)->quanta, cam_iosched_ticker, *iscp);
1092 (*iscp)->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
1100 * Reclaim all used resources. This assumes that other folks have
1101 * drained the requests in the hardware. Maybe an unwise assumption.
1104 cam_iosched_fini(struct cam_iosched_softc *isc)
1107 cam_iosched_flush(isc, NULL, ENXIO);
1108 #ifdef CAM_IOSCHED_DYNAMIC
1109 cam_iosched_iop_stats_fini(&isc->read_stats);
1110 cam_iosched_iop_stats_fini(&isc->write_stats);
1111 cam_iosched_iop_stats_fini(&isc->trim_stats);
1112 cam_iosched_cl_sysctl_fini(&isc->cl);
1113 if (isc->sysctl_tree)
1114 if (sysctl_ctx_free(&isc->sysctl_ctx) != 0)
1115 printf("can't remove iosched sysctl stats context\n");
1116 if (isc->flags & CAM_IOSCHED_FLAG_CALLOUT_ACTIVE) {
1117 callout_drain(&isc->ticker);
1118 isc->flags &= ~ CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
1121 free(isc, M_CAMSCHED);
1126 * After we're sure we're attaching a device, go ahead and add
1127 * hooks for any sysctl we may wish to honor.
1129 void cam_iosched_sysctl_init(struct cam_iosched_softc *isc,
1130 struct sysctl_ctx_list *ctx, struct sysctl_oid *node)
1132 #ifdef CAM_IOSCHED_DYNAMIC
1133 struct sysctl_oid_list *n;
1136 SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(node),
1137 OID_AUTO, "sort_io_queue", CTLFLAG_RW | CTLFLAG_MPSAFE,
1138 &isc->sort_io_queue, 0,
1139 "Sort IO queue to try and optimise disk access patterns");
1141 #ifdef CAM_IOSCHED_DYNAMIC
1142 if (!do_dynamic_iosched)
1145 isc->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1146 SYSCTL_CHILDREN(node), OID_AUTO, "iosched",
1147 CTLFLAG_RD, 0, "I/O scheduler statistics");
1148 n = SYSCTL_CHILDREN(isc->sysctl_tree);
1149 ctx = &isc->sysctl_ctx;
1151 cam_iosched_iop_stats_sysctl_init(isc, &isc->read_stats, "read");
1152 cam_iosched_iop_stats_sysctl_init(isc, &isc->write_stats, "write");
1153 cam_iosched_iop_stats_sysctl_init(isc, &isc->trim_stats, "trim");
1154 cam_iosched_cl_sysctl_init(isc);
1156 SYSCTL_ADD_INT(ctx, n,
1157 OID_AUTO, "read_bias", CTLFLAG_RW,
1158 &isc->read_bias, 100,
1159 "How biased towards read should we be independent of limits");
1161 SYSCTL_ADD_PROC(ctx, n,
1162 OID_AUTO, "quanta", CTLTYPE_UINT | CTLFLAG_RW,
1163 &isc->quanta, 0, cam_iosched_quanta_sysctl, "I",
1164 "How many quanta per second do we slice the I/O up into");
1166 SYSCTL_ADD_INT(ctx, n,
1167 OID_AUTO, "total_ticks", CTLFLAG_RD,
1168 &isc->total_ticks, 0,
1169 "Total number of ticks we've done");
1171 SYSCTL_ADD_INT(ctx, n,
1172 OID_AUTO, "load", CTLFLAG_RD,
1174 "scaled load average / 100");
1179 * Flush outstanding I/O. Consumers of this library don't know all the
1180 * queues we may keep, so this allows all I/O to be flushed in one
1184 cam_iosched_flush(struct cam_iosched_softc *isc, struct devstat *stp, int err)
1186 bioq_flush(&isc->bio_queue, stp, err);
1187 bioq_flush(&isc->trim_queue, stp, err);
1188 #ifdef CAM_IOSCHED_DYNAMIC
1189 if (do_dynamic_iosched)
1190 bioq_flush(&isc->write_queue, stp, err);
1194 #ifdef CAM_IOSCHED_DYNAMIC
1196 cam_iosched_get_write(struct cam_iosched_softc *isc)
1201 * We control the write rate by controlling how many requests we send
1202 * down to the drive at any one time. Fewer requests limits the
1203 * effects of both starvation when the requests take a while and write
1204 * amplification when each request is causing more than one write to
1205 * the NAND media. Limiting the queue depth like this will also limit
1206 * the write throughput and give and reads that want to compete to
1209 bp = bioq_first(&isc->write_queue);
1211 if (iosched_debug > 3)
1212 printf("No writes present in write_queue\n");
1217 * If pending read, prefer that based on current read bias
1220 if (bioq_first(&isc->bio_queue) && isc->current_read_bias) {
1222 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);
1223 isc->current_read_bias--;
1224 /* We're not limiting writes, per se, just doing reads first */
1229 * See if our current limiter allows this I/O.
1231 if (cam_iosched_limiter_iop(&isc->write_stats, bp) != 0) {
1233 printf("Can't write because limiter says no.\n");
1234 isc->write_stats.state_flags |= IOP_RATE_LIMITED;
1239 * Let's do this: We've passed all the gates and we're a go
1240 * to schedule the I/O in the SIM.
1242 isc->current_read_bias = isc->read_bias;
1243 bioq_remove(&isc->write_queue, bp);
1244 if (bp->bio_cmd == BIO_WRITE) {
1245 isc->write_stats.queued--;
1246 isc->write_stats.total++;
1247 isc->write_stats.pending++;
1249 if (iosched_debug > 9)
1250 printf("HWQ : %p %#x\n", bp, bp->bio_cmd);
1251 isc->write_stats.state_flags &= ~IOP_RATE_LIMITED;
1257 * Put back a trim that you weren't able to actually schedule this time.
1260 cam_iosched_put_back_trim(struct cam_iosched_softc *isc, struct bio *bp)
1262 bioq_insert_head(&isc->trim_queue, bp);
1263 #ifdef CAM_IOSCHED_DYNAMIC
1264 isc->trim_stats.queued++;
1265 isc->trim_stats.total--; /* since we put it back, don't double count */
1266 isc->trim_stats.pending--;
1271 * gets the next trim from the trim queue.
1273 * Assumes we're called with the periph lock held. It removes this
1274 * trim from the queue and the device must explicitly reinsert it
1275 * should the need arise.
1278 cam_iosched_next_trim(struct cam_iosched_softc *isc)
1282 bp = bioq_first(&isc->trim_queue);
1285 bioq_remove(&isc->trim_queue, bp);
1286 #ifdef CAM_IOSCHED_DYNAMIC
1287 isc->trim_stats.queued--;
1288 isc->trim_stats.total++;
1289 isc->trim_stats.pending++;
1295 * gets an available trim from the trim queue, if there's no trim
1296 * already pending. It removes this trim from the queue and the device
1297 * must explicitly reinsert it should the need arise.
1299 * Assumes we're called with the periph lock held.
1302 cam_iosched_get_trim(struct cam_iosched_softc *isc)
1305 if (!cam_iosched_has_more_trim(isc))
1308 return cam_iosched_next_trim(isc);
1312 * Determine what the next bit of work to do is for the periph. The
1313 * default implementation looks to see if we have trims to do, but no
1314 * trims outstanding. If so, we do that. Otherwise we see if we have
1315 * other work. If we do, then we do that. Otherwise why were we called?
1318 cam_iosched_next_bio(struct cam_iosched_softc *isc)
1323 * See if we have a trim that can be scheduled. We can only send one
1324 * at a time down, so this takes that into account.
1326 * XXX newer TRIM commands are queueable. Revisit this when we
1329 if ((bp = cam_iosched_get_trim(isc)) != NULL)
1332 #ifdef CAM_IOSCHED_DYNAMIC
1334 * See if we have any pending writes, and room in the queue for them,
1335 * and if so, those are next.
1337 if (do_dynamic_iosched) {
1338 if ((bp = cam_iosched_get_write(isc)) != NULL)
1344 * next, see if there's other, normal I/O waiting. If so return that.
1346 if ((bp = bioq_first(&isc->bio_queue)) == NULL)
1349 #ifdef CAM_IOSCHED_DYNAMIC
1351 * For the dynamic scheduler, bio_queue is only for reads, so enforce
1352 * the limits here. Enforce only for reads.
1354 if (do_dynamic_iosched) {
1355 if (bp->bio_cmd == BIO_READ &&
1356 cam_iosched_limiter_iop(&isc->read_stats, bp) != 0) {
1357 isc->read_stats.state_flags |= IOP_RATE_LIMITED;
1361 isc->read_stats.state_flags &= ~IOP_RATE_LIMITED;
1363 bioq_remove(&isc->bio_queue, bp);
1364 #ifdef CAM_IOSCHED_DYNAMIC
1365 if (do_dynamic_iosched) {
1366 if (bp->bio_cmd == BIO_READ) {
1367 isc->read_stats.queued--;
1368 isc->read_stats.total++;
1369 isc->read_stats.pending++;
1371 printf("Found bio_cmd = %#x\n", bp->bio_cmd);
1373 if (iosched_debug > 9)
1374 printf("HWQ : %p %#x\n", bp, bp->bio_cmd);
1380 * Driver has been given some work to do by the block layer. Tell the
1381 * scheduler about it and have it queue the work up. The scheduler module
1382 * will then return the currently most useful bit of work later, possibly
1383 * deferring work for various reasons.
1386 cam_iosched_queue_work(struct cam_iosched_softc *isc, struct bio *bp)
1390 * Put all trims on the trim queue sorted, since we know
1391 * that the collapsing code requires this. Otherwise put
1392 * the work on the bio queue.
1394 if (bp->bio_cmd == BIO_DELETE) {
1395 bioq_disksort(&isc->trim_queue, bp);
1396 #ifdef CAM_IOSCHED_DYNAMIC
1397 isc->trim_stats.in++;
1398 isc->trim_stats.queued++;
1401 #ifdef CAM_IOSCHED_DYNAMIC
1402 else if (do_dynamic_iosched && (bp->bio_cmd != BIO_READ)) {
1403 if (cam_iosched_sort_queue(isc))
1404 bioq_disksort(&isc->write_queue, bp);
1406 bioq_insert_tail(&isc->write_queue, bp);
1407 if (iosched_debug > 9)
1408 printf("Qw : %p %#x\n", bp, bp->bio_cmd);
1409 if (bp->bio_cmd == BIO_WRITE) {
1410 isc->write_stats.in++;
1411 isc->write_stats.queued++;
1416 if (cam_iosched_sort_queue(isc))
1417 bioq_disksort(&isc->bio_queue, bp);
1419 bioq_insert_tail(&isc->bio_queue, bp);
1420 #ifdef CAM_IOSCHED_DYNAMIC
1421 if (iosched_debug > 9)
1422 printf("Qr : %p %#x\n", bp, bp->bio_cmd);
1423 if (bp->bio_cmd == BIO_READ) {
1424 isc->read_stats.in++;
1425 isc->read_stats.queued++;
1426 } else if (bp->bio_cmd == BIO_WRITE) {
1427 isc->write_stats.in++;
1428 isc->write_stats.queued++;
1435 * If we have work, get it scheduled. Called with the periph lock held.
1438 cam_iosched_schedule(struct cam_iosched_softc *isc, struct cam_periph *periph)
1441 if (cam_iosched_has_work(isc))
1442 xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1446 * Complete a trim request. Mark that we no longer have one in flight.
1449 cam_iosched_trim_done(struct cam_iosched_softc *isc)
1452 isc->flags &= ~CAM_IOSCHED_FLAG_TRIM_ACTIVE;
1456 * Complete a bio. Called before we release the ccb with xpt_release_ccb so we
1457 * might use notes in the ccb for statistics.
1460 cam_iosched_bio_complete(struct cam_iosched_softc *isc, struct bio *bp,
1461 union ccb *done_ccb)
1464 #ifdef CAM_IOSCHED_DYNAMIC
1465 if (!do_dynamic_iosched)
1468 if (iosched_debug > 10)
1469 printf("done: %p %#x\n", bp, bp->bio_cmd);
1470 if (bp->bio_cmd == BIO_WRITE) {
1471 retval = cam_iosched_limiter_iodone(&isc->write_stats, bp);
1472 if (!(bp->bio_flags & BIO_ERROR))
1473 isc->write_stats.errs++;
1474 isc->write_stats.out++;
1475 isc->write_stats.pending--;
1476 } else if (bp->bio_cmd == BIO_READ) {
1477 retval = cam_iosched_limiter_iodone(&isc->read_stats, bp);
1478 if (!(bp->bio_flags & BIO_ERROR))
1479 isc->read_stats.errs++;
1480 isc->read_stats.out++;
1481 isc->read_stats.pending--;
1482 } else if (bp->bio_cmd == BIO_DELETE) {
1483 if (!(bp->bio_flags & BIO_ERROR))
1484 isc->trim_stats.errs++;
1485 isc->trim_stats.out++;
1486 isc->trim_stats.pending--;
1487 } else if (bp->bio_cmd != BIO_FLUSH) {
1489 printf("Completing command with bio_cmd == %#x\n", bp->bio_cmd);
1492 if (!(bp->bio_flags & BIO_ERROR))
1493 cam_iosched_io_metric_update(isc,
1494 cam_iosched_sbintime_t(done_ccb->ccb_h.qos.periph_data),
1495 bp->bio_cmd, bp->bio_bcount);
1501 * Tell the io scheduler that you've pushed a trim down into the sim.
1502 * This also tells the I/O scheduler not to push any more trims down, so
1503 * some periphs do not call it if they can cope with multiple trims in flight.
1506 cam_iosched_submit_trim(struct cam_iosched_softc *isc)
1509 isc->flags |= CAM_IOSCHED_FLAG_TRIM_ACTIVE;
1513 * Change the sorting policy hint for I/O transactions for this device.
1516 cam_iosched_set_sort_queue(struct cam_iosched_softc *isc, int val)
1519 isc->sort_io_queue = val;
1523 cam_iosched_has_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1525 return isc->flags & flags;
1529 cam_iosched_set_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1531 isc->flags |= flags;
1535 cam_iosched_clr_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1537 isc->flags &= ~flags;
1540 #ifdef CAM_IOSCHED_DYNAMIC
1542 * After the method presented in Jack Crenshaw's 1998 article "Integer
1543 * Square Roots," reprinted at
1544 * http://www.embedded.com/electronics-blogs/programmer-s-toolbox/4219659/Integer-Square-Roots
1545 * and well worth the read. Briefly, we find the power of 4 that's the
1546 * largest smaller than val. We then check each smaller power of 4 to
1547 * see if val is still bigger. The right shifts at each step divide
1548 * the result by 2 which after successive application winds up
1549 * accumulating the right answer. It could also have been accumulated
1550 * using a separate root counter, but this code is smaller and faster
1551 * than that method. This method is also integer size invariant.
1552 * It returns floor(sqrt((float)val)), or the largest integer less than
1553 * or equal to the square root.
1556 isqrt64(uint64_t val)
1559 uint64_t bit = 1ULL << (sizeof(uint64_t) * NBBY - 2);
1562 * Find the largest power of 4 smaller than val.
1568 * Accumulate the answer, one bit at a time (we keep moving
1569 * them over since 2 is the square root of 4 and we test
1570 * powers of 4). We accumulate where we find the bit, but
1571 * the successive shifts land the bit in the right place
1575 if (val >= res + bit) {
1577 res = (res >> 1) + bit;
1586 static sbintime_t latencies[LAT_BUCKETS - 1] = {
1600 SBT_1MS << 13 /* 8.192s */
1604 cam_iosched_update(struct iop_stats *iop, sbintime_t sim_latency)
1606 sbintime_t y, deltasq, delta;
1610 * Keep counts for latency. We do it by power of two buckets.
1611 * This helps us spot outlier behavior obscured by averages.
1613 for (i = 0; i < LAT_BUCKETS - 1; i++) {
1614 if (sim_latency < latencies[i]) {
1615 iop->latencies[i]++;
1619 if (i == LAT_BUCKETS - 1)
1620 iop->latencies[i]++; /* Put all > 1024ms values into the last bucket. */
1623 * Classic exponentially decaying average with a tiny alpha
1624 * (2 ^ -alpha_bits). For more info see the NIST statistical
1627 * ema_t = y_t * alpha + ema_t-1 * (1 - alpha) [nist]
1628 * ema_t = y_t * alpha + ema_t-1 - alpha * ema_t-1
1629 * ema_t = alpha * y_t - alpha * ema_t-1 + ema_t-1
1630 * alpha = 1 / (1 << alpha_bits)
1631 * sub e == ema_t-1, b == 1/alpha (== 1 << alpha_bits), d == y_t - ema_t-1
1632 * = y_t/b - e/b + be/b
1633 * = (y_t - e + be) / b
1636 * Since alpha is a power of two, we can compute this w/o any mult or
1639 * Variance can also be computed. Usually, it would be expressed as follows:
1640 * diff_t = y_t - ema_t-1
1641 * emvar_t = (1 - alpha) * (emavar_t-1 + diff_t^2 * alpha)
1642 * = emavar_t-1 - alpha * emavar_t-1 + delta_t^2 * alpha - (delta_t * alpha)^2
1643 * sub b == 1/alpha (== 1 << alpha_bits), e == emavar_t-1, d = delta_t^2
1644 * = e - e/b + dd/b + dd/bb
1645 * = (bbe - be + bdd + dd) / bb
1646 * = (bbe + b(dd-e) + dd) / bb (which is expanded below bb = 1<<(2*alpha_bits))
1649 * XXX possible numeric issues
1650 * o We assume right shifted integers do the right thing, since that's
1651 * implementation defined. You can change the right shifts to / (1LL << alpha).
1652 * o alpha_bits = 9 gives ema ceiling of 23 bits of seconds for ema and 14 bits
1653 * for emvar. This puts a ceiling of 13 bits on alpha since we need a
1654 * few tens of seconds of representation.
1655 * o We mitigate alpha issues by never setting it too high.
1658 delta = (y - iop->ema); /* d */
1659 iop->ema = ((iop->ema << alpha_bits) + delta) >> alpha_bits;
1662 * Were we to naively plow ahead at this point, we wind up with many numerical
1663 * issues making any SD > ~3ms unreliable. So, we shift right by 12. This leaves
1664 * us with microsecond level precision in the input, so the same in the
1665 * output. It means we can't overflow deltasq unless delta > 4k seconds. It
1666 * also means that emvar can be up 46 bits 40 of which are fraction, which
1667 * gives us a way to measure up to ~8s in the SD before the computation goes
1668 * unstable. Even the worst hard disk rarely has > 1s service time in the
1669 * drive. It does mean we have to shift left 12 bits after taking the
1670 * square root to compute the actual standard deviation estimate. This loss of
1671 * precision is preferable to needing int128 types to work. The above numbers
1672 * assume alpha=9. 10 or 11 are ok, but we start to run into issues at 12,
1673 * so 12 or 13 is OK for EMA, EMVAR and SD will be wrong in those cases.
1676 deltasq = delta * delta; /* dd */
1677 iop->emvar = ((iop->emvar << (2 * alpha_bits)) + /* bbe */
1678 ((deltasq - iop->emvar) << alpha_bits) + /* b(dd-e) */
1680 >> (2 * alpha_bits); /* div bb */
1681 iop->sd = (sbintime_t)isqrt64((uint64_t)iop->emvar) << 12;
1685 cam_iosched_io_metric_update(struct cam_iosched_softc *isc,
1686 sbintime_t sim_latency, int cmd, size_t size)
1688 /* xxx Do we need to scale based on the size of the I/O ? */
1691 cam_iosched_update(&isc->read_stats, sim_latency);
1694 cam_iosched_update(&isc->write_stats, sim_latency);
1697 cam_iosched_update(&isc->trim_stats, sim_latency);
1705 static int biolen(struct bio_queue_head *bq)
1710 TAILQ_FOREACH(bp, &bq->queue, bio_queue) {
1717 * Show the internal state of the I/O scheduler.
1719 DB_SHOW_COMMAND(iosched, cam_iosched_db_show)
1721 struct cam_iosched_softc *isc;
1724 db_printf("Need addr\n");
1727 isc = (struct cam_iosched_softc *)addr;
1728 db_printf("pending_reads: %d\n", isc->read_stats.pending);
1729 db_printf("min_reads: %d\n", isc->read_stats.min);
1730 db_printf("max_reads: %d\n", isc->read_stats.max);
1731 db_printf("reads: %d\n", isc->read_stats.total);
1732 db_printf("in_reads: %d\n", isc->read_stats.in);
1733 db_printf("out_reads: %d\n", isc->read_stats.out);
1734 db_printf("queued_reads: %d\n", isc->read_stats.queued);
1735 db_printf("Current Q len %d\n", biolen(&isc->bio_queue));
1736 db_printf("pending_writes: %d\n", isc->write_stats.pending);
1737 db_printf("min_writes: %d\n", isc->write_stats.min);
1738 db_printf("max_writes: %d\n", isc->write_stats.max);
1739 db_printf("writes: %d\n", isc->write_stats.total);
1740 db_printf("in_writes: %d\n", isc->write_stats.in);
1741 db_printf("out_writes: %d\n", isc->write_stats.out);
1742 db_printf("queued_writes: %d\n", isc->write_stats.queued);
1743 db_printf("Current Q len %d\n", biolen(&isc->write_queue));
1744 db_printf("pending_trims: %d\n", isc->trim_stats.pending);
1745 db_printf("min_trims: %d\n", isc->trim_stats.min);
1746 db_printf("max_trims: %d\n", isc->trim_stats.max);
1747 db_printf("trims: %d\n", isc->trim_stats.total);
1748 db_printf("in_trims: %d\n", isc->trim_stats.in);
1749 db_printf("out_trims: %d\n", isc->trim_stats.out);
1750 db_printf("queued_trims: %d\n", isc->trim_stats.queued);
1751 db_printf("Current Q len %d\n", biolen(&isc->trim_queue));
1752 db_printf("read_bias: %d\n", isc->read_bias);
1753 db_printf("current_read_bias: %d\n", isc->current_read_bias);
1754 db_printf("Trim active? %s\n",
1755 (isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) ? "yes" : "no");