2 * CAM IO Scheduler Interface
4 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
6 * Copyright (c) 2015 Netflix, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions, and the following disclaimer,
13 * without modification, immediately at the beginning of the file.
14 * 2. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
38 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/mutex.h>
47 #include <sys/sysctl.h>
50 #include <cam/cam_ccb.h>
51 #include <cam/cam_periph.h>
52 #include <cam/cam_xpt_periph.h>
53 #include <cam/cam_xpt_internal.h>
54 #include <cam/cam_iosched.h>
58 static MALLOC_DEFINE(M_CAMSCHED, "CAM I/O Scheduler",
59 "CAM I/O Scheduler buffers");
61 static SYSCTL_NODE(_kern_cam, OID_AUTO, iosched, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
62 "CAM I/O Scheduler parameters");
65 * Default I/O scheduler for FreeBSD. This implementation is just a thin-vineer
66 * over the bioq_* interface, with notions of separate calls for normal I/O and
69 * When CAM_IOSCHED_DYNAMIC is defined, the scheduler is enhanced to dynamically
70 * steer the rate of one type of traffic to help other types of traffic (eg
71 * limit writes when read latency deteriorates on SSDs).
74 #ifdef CAM_IOSCHED_DYNAMIC
76 static bool do_dynamic_iosched = true;
77 SYSCTL_BOOL(_kern_cam_iosched, OID_AUTO, dynamic, CTLFLAG_RD | CTLFLAG_TUN,
78 &do_dynamic_iosched, 1,
79 "Enable Dynamic I/O scheduler optimizations.");
82 * For an EMA, with an alpha of alpha, we know
86 * where N is the number of samples that 86% of the current
87 * EMA is derived from.
89 * So we invent[*] alpha_bits:
90 * alpha_bits = -log_2(alpha)
91 * alpha = 2^-alpha_bits
93 * N = 1 + 2^(alpha_bits + 1)
95 * The default 9 gives a 1025 lookback for 86% of the data.
96 * For a brief intro: https://en.wikipedia.org/wiki/Moving_average
98 * [*] Steal from the load average code and many other places.
99 * Note: See computation of EMA and EMVAR for acceptable ranges of alpha.
101 static int alpha_bits = 9;
102 SYSCTL_INT(_kern_cam_iosched, OID_AUTO, alpha_bits, CTLFLAG_RW | CTLFLAG_TUN,
104 "Bits in EMA's alpha.");
107 * Different parameters for the buckets of latency we keep track of. These are all
108 * published read-only since at present they are compile time constants.
110 * Bucket base is the upper bounds of the first latency bucket. It's currently 20us.
111 * With 20 buckets (see below), that leads to a geometric progression with a max size
112 * of 5.2s which is safeily larger than 1s to help diagnose extreme outliers better.
115 #define BUCKET_BASE ((SBT_1S / 50000) + 1) /* 20us */
117 static sbintime_t bucket_base = BUCKET_BASE;
118 SYSCTL_SBINTIME_USEC(_kern_cam_iosched, OID_AUTO, bucket_base_us, CTLFLAG_RD,
120 "Size of the smallest latency bucket");
123 * Bucket ratio is the geometric progression for the bucket. For a bucket b_n
124 * the size of bucket b_n+1 is b_n * bucket_ratio / 100.
126 static int bucket_ratio = 200; /* Rather hard coded at the moment */
127 SYSCTL_INT(_kern_cam_iosched, OID_AUTO, bucket_ratio, CTLFLAG_RD,
129 "Latency Bucket Ratio for geometric progression.");
132 * Number of total buckets. Starting at BUCKET_BASE, each one is a power of 2.
135 #define LAT_BUCKETS 20 /* < 20us < 40us ... < 2^(n-1)*20us >= 2^(n-1)*20us */
137 static int lat_buckets = LAT_BUCKETS;
138 SYSCTL_INT(_kern_cam_iosched, OID_AUTO, buckets, CTLFLAG_RD,
139 &lat_buckets, LAT_BUCKETS,
140 "Total number of latency buckets published");
143 struct cam_iosched_softc;
145 int iosched_debug = 0;
148 none = 0, /* No limits */
149 queue_depth, /* Limit how many ops we queue to SIM */
150 iops, /* Limit # of IOPS to the drive */
151 bandwidth, /* Limit bandwidth to the drive */
155 static const char *cam_iosched_limiter_names[] =
156 { "none", "queue_depth", "iops", "bandwidth" };
159 * Called to initialize the bits of the iop_stats structure relevant to the
160 * limiter. Called just after the limiter is set.
162 typedef int l_init_t(struct iop_stats *);
167 typedef int l_tick_t(struct iop_stats *);
170 * Called to see if the limiter thinks this IOP can be allowed to
171 * proceed. If so, the limiter assumes that the IOP proceeded
172 * and makes any accounting of it that's needed.
174 typedef int l_iop_t(struct iop_stats *, struct bio *);
177 * Called when an I/O completes so the limiter can update its
178 * accounting. Pending I/Os may complete in any order (even when
179 * sent to the hardware at the same time), so the limiter may not
180 * make any assumptions other than this I/O has completed. If it
181 * returns 1, then xpt_schedule() needs to be called again.
183 typedef int l_iodone_t(struct iop_stats *, struct bio *);
185 static l_iop_t cam_iosched_qd_iop;
186 static l_iop_t cam_iosched_qd_caniop;
187 static l_iodone_t cam_iosched_qd_iodone;
189 static l_init_t cam_iosched_iops_init;
190 static l_tick_t cam_iosched_iops_tick;
191 static l_iop_t cam_iosched_iops_caniop;
192 static l_iop_t cam_iosched_iops_iop;
194 static l_init_t cam_iosched_bw_init;
195 static l_tick_t cam_iosched_bw_tick;
196 static l_iop_t cam_iosched_bw_caniop;
197 static l_iop_t cam_iosched_bw_iop;
204 l_iodone_t *l_iodone;
216 .l_caniop = cam_iosched_qd_caniop,
217 .l_iop = cam_iosched_qd_iop,
218 .l_iodone= cam_iosched_qd_iodone,
221 .l_init = cam_iosched_iops_init,
222 .l_tick = cam_iosched_iops_tick,
223 .l_caniop = cam_iosched_iops_caniop,
224 .l_iop = cam_iosched_iops_iop,
228 .l_init = cam_iosched_bw_init,
229 .l_tick = cam_iosched_bw_tick,
230 .l_caniop = cam_iosched_bw_caniop,
231 .l_iop = cam_iosched_bw_iop,
238 * sysctl state for this subnode.
240 struct sysctl_ctx_list sysctl_ctx;
241 struct sysctl_oid *sysctl_tree;
244 * Information about the current rate limiters, if any
246 io_limiter limiter; /* How are I/Os being limited */
247 int min; /* Low range of limit */
248 int max; /* High range of limit */
249 int current; /* Current rate limiter */
250 int l_value1; /* per-limiter scratch value 1. */
251 int l_value2; /* per-limiter scratch value 2. */
254 * Debug information about counts of I/Os that have gone through the
257 int pending; /* I/Os pending in the hardware */
258 int queued; /* number currently in the queue */
259 int total; /* Total for all time -- wraps */
260 int in; /* number queued all time -- wraps */
261 int out; /* number completed all time -- wraps */
262 int errs; /* Number of I/Os completed with error -- wraps */
265 * Statistics on different bits of the process.
267 /* Exp Moving Average, see alpha_bits for more details */
270 sbintime_t sd; /* Last computed sd */
272 uint32_t state_flags;
273 #define IOP_RATE_LIMITED 1u
275 uint64_t latencies[LAT_BUCKETS];
277 struct cam_iosched_softc *softc;
281 set_max = 0, /* current = max */
282 read_latency, /* Steer read latency by throttling writes */
283 cl_max /* Keep last */
286 static const char *cam_iosched_control_type_names[] =
287 { "set_max", "read_latency" };
289 struct control_loop {
291 * sysctl state for this subnode.
293 struct sysctl_ctx_list sysctl_ctx;
294 struct sysctl_oid *sysctl_tree;
296 sbintime_t next_steer; /* Time of next steer */
297 sbintime_t steer_interval; /* How often do we steer? */
301 control_type type; /* What type of control? */
302 int last_count; /* Last I/O count */
304 struct cam_iosched_softc *softc;
309 struct cam_iosched_softc {
310 struct bio_queue_head bio_queue;
311 struct bio_queue_head trim_queue;
312 /* scheduler flags < 16, user flags >= 16 */
315 int trim_goal; /* # of trims to queue before sending */
316 int trim_ticks; /* Max ticks to hold trims */
317 int last_trim_tick; /* Last 'tick' time ld a trim */
318 int queued_trims; /* Number of trims in the queue */
319 #ifdef CAM_IOSCHED_DYNAMIC
320 int read_bias; /* Read bias setting */
321 int current_read_bias; /* Current read bias state */
323 int load; /* EMA of 'load average' of disk / 2^16 */
325 struct bio_queue_head write_queue;
326 struct iop_stats read_stats, write_stats, trim_stats;
327 struct sysctl_ctx_list sysctl_ctx;
328 struct sysctl_oid *sysctl_tree;
330 int quanta; /* Number of quanta per second */
331 struct callout ticker; /* Callout for our quota system */
332 struct cam_periph *periph; /* cam periph associated with this device */
333 uint32_t this_frac; /* Fraction of a second (1024ths) for this tick */
334 sbintime_t last_time; /* Last time we ticked */
335 struct control_loop cl;
336 sbintime_t max_lat; /* when != 0, if iop latency > max_lat, call max_lat_fcn */
337 cam_iosched_latfcn_t latfcn;
342 #ifdef CAM_IOSCHED_DYNAMIC
344 * helper functions to call the limsw functions.
347 cam_iosched_limiter_init(struct iop_stats *ios)
349 int lim = ios->limiter;
351 /* maybe this should be a kassert */
352 if (lim < none || lim >= limiter_max)
355 if (limsw[lim].l_init)
356 return limsw[lim].l_init(ios);
362 cam_iosched_limiter_tick(struct iop_stats *ios)
364 int lim = ios->limiter;
366 /* maybe this should be a kassert */
367 if (lim < none || lim >= limiter_max)
370 if (limsw[lim].l_tick)
371 return limsw[lim].l_tick(ios);
377 cam_iosched_limiter_iop(struct iop_stats *ios, struct bio *bp)
379 int lim = ios->limiter;
381 /* maybe this should be a kassert */
382 if (lim < none || lim >= limiter_max)
385 if (limsw[lim].l_iop)
386 return limsw[lim].l_iop(ios, bp);
392 cam_iosched_limiter_caniop(struct iop_stats *ios, struct bio *bp)
394 int lim = ios->limiter;
396 /* maybe this should be a kassert */
397 if (lim < none || lim >= limiter_max)
400 if (limsw[lim].l_caniop)
401 return limsw[lim].l_caniop(ios, bp);
407 cam_iosched_limiter_iodone(struct iop_stats *ios, struct bio *bp)
409 int lim = ios->limiter;
411 /* maybe this should be a kassert */
412 if (lim < none || lim >= limiter_max)
415 if (limsw[lim].l_iodone)
416 return limsw[lim].l_iodone(ios, bp);
422 * Functions to implement the different kinds of limiters
426 cam_iosched_qd_iop(struct iop_stats *ios, struct bio *bp)
429 if (ios->current <= 0 || ios->pending < ios->current)
436 cam_iosched_qd_caniop(struct iop_stats *ios, struct bio *bp)
439 if (ios->current <= 0 || ios->pending < ios->current)
446 cam_iosched_qd_iodone(struct iop_stats *ios, struct bio *bp)
449 if (ios->current <= 0 || ios->pending != ios->current)
456 cam_iosched_iops_init(struct iop_stats *ios)
459 ios->l_value1 = ios->current / ios->softc->quanta;
460 if (ios->l_value1 <= 0)
468 cam_iosched_iops_tick(struct iop_stats *ios)
473 * Allow at least one IO per tick until all
474 * the IOs for this interval have been spent.
476 new_ios = (int)((ios->current * (uint64_t)ios->softc->this_frac) >> 16);
477 if (new_ios < 1 && ios->l_value2 < ios->current) {
483 * If this a new accounting interval, discard any "unspent" ios
484 * granted in the previous interval. Otherwise add the new ios to
485 * the previously granted ones that haven't been spent yet.
487 if ((ios->softc->total_ticks % ios->softc->quanta) == 0) {
488 ios->l_value1 = new_ios;
491 ios->l_value1 += new_ios;
498 cam_iosched_iops_caniop(struct iop_stats *ios, struct bio *bp)
502 * So if we have any more IOPs left, allow it,
503 * otherwise wait. If current iops is 0, treat that
504 * as unlimited as a failsafe.
506 if (ios->current > 0 && ios->l_value1 <= 0)
512 cam_iosched_iops_iop(struct iop_stats *ios, struct bio *bp)
516 rv = cam_iosched_limiter_caniop(ios, bp);
524 cam_iosched_bw_init(struct iop_stats *ios)
527 /* ios->current is in kB/s, so scale to bytes */
528 ios->l_value1 = ios->current * 1000 / ios->softc->quanta;
534 cam_iosched_bw_tick(struct iop_stats *ios)
539 * If we're in the hole for available quota from
540 * the last time, then add the quantum for this.
541 * If we have any left over from last quantum,
542 * then too bad, that's lost. Also, ios->current
543 * is in kB/s, so scale.
545 * We also allow up to 4 quanta of credits to
546 * accumulate to deal with burstiness. 4 is extremely
549 bw = (int)((ios->current * 1000ull * (uint64_t)ios->softc->this_frac) >> 16);
550 if (ios->l_value1 < bw * 4)
557 cam_iosched_bw_caniop(struct iop_stats *ios, struct bio *bp)
560 * So if we have any more bw quota left, allow it,
561 * otherwise wait. Note, we'll go negative and that's
562 * OK. We'll just get a little less next quota.
564 * Note on going negative: that allows us to process
565 * requests in order better, since we won't allow
566 * shorter reads to get around the long one that we
567 * don't have the quota to do just yet. It also prevents
568 * starvation by being a little more permissive about
569 * what we let through this quantum (to prevent the
570 * starvation), at the cost of getting a little less
573 * Also note that if the current limit is <= 0,
574 * we treat it as unlimited as a failsafe.
576 if (ios->current > 0 && ios->l_value1 <= 0)
583 cam_iosched_bw_iop(struct iop_stats *ios, struct bio *bp)
587 rv = cam_iosched_limiter_caniop(ios, bp);
589 ios->l_value1 -= bp->bio_length;
594 static void cam_iosched_cl_maybe_steer(struct control_loop *clp);
597 cam_iosched_ticker(void *arg)
599 struct cam_iosched_softc *isc = arg;
600 sbintime_t now, delta;
603 callout_reset(&isc->ticker, hz / isc->quanta, cam_iosched_ticker, isc);
606 delta = now - isc->last_time;
607 isc->this_frac = (uint32_t)delta >> 16; /* Note: discards seconds -- should be 0 harmless if not */
608 isc->last_time = now;
610 cam_iosched_cl_maybe_steer(&isc->cl);
612 cam_iosched_limiter_tick(&isc->read_stats);
613 cam_iosched_limiter_tick(&isc->write_stats);
614 cam_iosched_limiter_tick(&isc->trim_stats);
616 cam_iosched_schedule(isc, isc->periph);
619 * isc->load is an EMA of the pending I/Os at each tick. The number of
620 * pending I/Os is the sum of the I/Os queued to the hardware, and those
621 * in the software queue that could be queued to the hardware if there
624 * ios_stats.pending is a count of requests in the SIM right now for
625 * each of these types of I/O. So the total pending count is the sum of
626 * these I/Os and the sum of the queued I/Os still in the software queue
627 * for those operations that aren't being rate limited at the moment.
629 * The reason for the rate limiting bit is because those I/Os
630 * aren't part of the software queued load (since we could
631 * give them to hardware, but choose not to).
633 * Note: due to a bug in counting pending TRIM in the device, we
634 * don't include them in this count. We count each BIO_DELETE in
635 * the pending count, but the periph drivers collapse them down
636 * into one TRIM command. That one trim command gets the completion
637 * so the counts get off.
639 pending = isc->read_stats.pending + isc->write_stats.pending /* + isc->trim_stats.pending */;
640 pending += !!(isc->read_stats.state_flags & IOP_RATE_LIMITED) * isc->read_stats.queued +
641 !!(isc->write_stats.state_flags & IOP_RATE_LIMITED) * isc->write_stats.queued /* +
642 !!(isc->trim_stats.state_flags & IOP_RATE_LIMITED) * isc->trim_stats.queued */ ;
644 pending /= isc->periph->path->device->ccbq.total_openings;
646 isc->load = (pending + (isc->load << 13) - isc->load) >> 13; /* see above: 13 -> 16139 / 200/s = ~81s ~1 minute */
652 cam_iosched_cl_init(struct control_loop *clp, struct cam_iosched_softc *isc)
655 clp->next_steer = sbinuptime();
657 clp->steer_interval = SBT_1S * 5; /* Let's start out steering every 5s */
658 clp->lolat = 5 * SBT_1MS;
659 clp->hilat = 15 * SBT_1MS;
660 clp->alpha = 20; /* Alpha == gain. 20 = .2 */
665 cam_iosched_cl_maybe_steer(struct control_loop *clp)
667 struct cam_iosched_softc *isc;
672 now = isc->last_time;
673 if (now < clp->next_steer)
676 clp->next_steer = now + clp->steer_interval;
679 if (isc->write_stats.current != isc->write_stats.max)
680 printf("Steering write from %d kBps to %d kBps\n",
681 isc->write_stats.current, isc->write_stats.max);
682 isc->read_stats.current = isc->read_stats.max;
683 isc->write_stats.current = isc->write_stats.max;
684 isc->trim_stats.current = isc->trim_stats.max;
687 old = isc->write_stats.current;
688 lat = isc->read_stats.ema;
690 * Simple PLL-like engine. Since we're steering to a range for
691 * the SP (set point) that makes things a little more
692 * complicated. In addition, we're not directly controlling our
693 * PV (process variable), the read latency, but instead are
694 * manipulating the write bandwidth limit for our MV
695 * (manipulation variable), analysis of this code gets a bit
696 * messy. Also, the MV is a very noisy control surface for read
697 * latency since it is affected by many hidden processes inside
698 * the device which change how responsive read latency will be
699 * in reaction to changes in write bandwidth. Unlike the classic
700 * boiler control PLL. this may result in over-steering while
701 * the SSD takes its time to react to the new, lower load. This
702 * is why we use a relatively low alpha of between .1 and .25 to
703 * compensate for this effect. At .1, it takes ~22 steering
704 * intervals to back off by a factor of 10. At .2 it only takes
705 * ~10. At .25 it only takes ~8. However some preliminary data
706 * from the SSD drives suggests a reasponse time in 10's of
707 * seconds before latency drops regardless of the new write
708 * rate. Careful observation will be required to tune this
711 * Also, when there's no read traffic, we jack up the write
712 * limit too regardless of the last read latency. 10 is
713 * somewhat arbitrary.
715 if (lat < clp->lolat || isc->read_stats.total - clp->last_count < 10)
716 isc->write_stats.current = isc->write_stats.current *
717 (100 + clp->alpha) / 100; /* Scale up */
718 else if (lat > clp->hilat)
719 isc->write_stats.current = isc->write_stats.current *
720 (100 - clp->alpha) / 100; /* Scale down */
721 clp->last_count = isc->read_stats.total;
724 * Even if we don't steer, per se, enforce the min/max limits as
725 * those may have changed.
727 if (isc->write_stats.current < isc->write_stats.min)
728 isc->write_stats.current = isc->write_stats.min;
729 if (isc->write_stats.current > isc->write_stats.max)
730 isc->write_stats.current = isc->write_stats.max;
731 if (old != isc->write_stats.current && iosched_debug)
732 printf("Steering write from %d kBps to %d kBps due to latency of %jdus\n",
733 old, isc->write_stats.current,
734 (uintmax_t)((uint64_t)1000000 * (uint32_t)lat) >> 32);
743 * Trim or similar currently pending completion. Should only be set for
744 * those drivers wishing only one Trim active at a time.
746 #define CAM_IOSCHED_FLAG_TRIM_ACTIVE (1ul << 0)
747 /* Callout active, and needs to be torn down */
748 #define CAM_IOSCHED_FLAG_CALLOUT_ACTIVE (1ul << 1)
750 /* Periph drivers set these flags to indicate work */
751 #define CAM_IOSCHED_FLAG_WORK_FLAGS ((0xffffu) << 16)
753 #ifdef CAM_IOSCHED_DYNAMIC
755 cam_iosched_io_metric_update(struct cam_iosched_softc *isc,
756 sbintime_t sim_latency, int cmd, size_t size);
760 cam_iosched_has_flagged_work(struct cam_iosched_softc *isc)
762 return !!(isc->flags & CAM_IOSCHED_FLAG_WORK_FLAGS);
766 cam_iosched_has_io(struct cam_iosched_softc *isc)
768 #ifdef CAM_IOSCHED_DYNAMIC
769 if (do_dynamic_iosched) {
770 struct bio *rbp = bioq_first(&isc->bio_queue);
771 struct bio *wbp = bioq_first(&isc->write_queue);
772 bool can_write = wbp != NULL &&
773 cam_iosched_limiter_caniop(&isc->write_stats, wbp) == 0;
774 bool can_read = rbp != NULL &&
775 cam_iosched_limiter_caniop(&isc->read_stats, rbp) == 0;
776 if (iosched_debug > 2) {
777 printf("can write %d: pending_writes %d max_writes %d\n", can_write, isc->write_stats.pending, isc->write_stats.max);
778 printf("can read %d: read_stats.pending %d max_reads %d\n", can_read, isc->read_stats.pending, isc->read_stats.max);
779 printf("Queued reads %d writes %d\n", isc->read_stats.queued, isc->write_stats.queued);
781 return can_read || can_write;
784 return bioq_first(&isc->bio_queue) != NULL;
788 cam_iosched_has_more_trim(struct cam_iosched_softc *isc)
792 bp = bioq_first(&isc->trim_queue);
793 #ifdef CAM_IOSCHED_DYNAMIC
794 if (do_dynamic_iosched) {
796 * If we're limiting trims, then defer action on trims
799 if (bp == NULL || cam_iosched_limiter_caniop(&isc->trim_stats, bp) != 0)
805 * If we've set a trim_goal, then if we exceed that allow trims
806 * to be passed back to the driver. If we've also set a tick timeout
807 * allow trims back to the driver. Otherwise, don't allow trims yet.
809 if (isc->trim_goal > 0) {
810 if (isc->queued_trims >= isc->trim_goal)
812 if (isc->queued_trims > 0 &&
813 isc->trim_ticks > 0 &&
814 ticks - isc->last_trim_tick > isc->trim_ticks)
819 /* NB: Should perhaps have a max trim active independent of I/O limiters */
820 return !(isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) && bp != NULL;
823 #define cam_iosched_sort_queue(isc) ((isc)->sort_io_queue >= 0 ? \
824 (isc)->sort_io_queue : cam_sort_io_queues)
827 cam_iosched_has_work(struct cam_iosched_softc *isc)
829 #ifdef CAM_IOSCHED_DYNAMIC
830 if (iosched_debug > 2)
831 printf("has work: %d %d %d\n", cam_iosched_has_io(isc),
832 cam_iosched_has_more_trim(isc),
833 cam_iosched_has_flagged_work(isc));
836 return cam_iosched_has_io(isc) ||
837 cam_iosched_has_more_trim(isc) ||
838 cam_iosched_has_flagged_work(isc);
841 #ifdef CAM_IOSCHED_DYNAMIC
843 cam_iosched_iop_stats_init(struct cam_iosched_softc *isc, struct iop_stats *ios)
848 ios->max = ios->current = 300000;
858 cam_iosched_limiter_init(ios);
862 cam_iosched_limiter_sysctl(SYSCTL_HANDLER_ARGS)
865 struct iop_stats *ios;
866 struct cam_iosched_softc *isc;
872 value = ios->limiter;
873 if (value < none || value >= limiter_max)
876 p = cam_iosched_limiter_names[value];
878 strlcpy(buf, p, sizeof(buf));
879 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
880 if (error != 0 || req->newptr == NULL)
883 cam_periph_lock(isc->periph);
885 for (i = none; i < limiter_max; i++) {
886 if (strcmp(buf, cam_iosched_limiter_names[i]) != 0)
889 error = cam_iosched_limiter_init(ios);
891 ios->limiter = value;
892 cam_periph_unlock(isc->periph);
895 /* Note: disk load averate requires ticker to be always running */
896 callout_reset(&isc->ticker, hz / isc->quanta, cam_iosched_ticker, isc);
897 isc->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
899 cam_periph_unlock(isc->periph);
903 cam_periph_unlock(isc->periph);
908 cam_iosched_control_type_sysctl(SYSCTL_HANDLER_ARGS)
911 struct control_loop *clp;
912 struct cam_iosched_softc *isc;
919 if (value < none || value >= cl_max)
922 p = cam_iosched_control_type_names[value];
924 strlcpy(buf, p, sizeof(buf));
925 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
926 if (error != 0 || req->newptr == NULL)
929 for (i = set_max; i < cl_max; i++) {
930 if (strcmp(buf, cam_iosched_control_type_names[i]) != 0)
932 cam_periph_lock(isc->periph);
934 cam_periph_unlock(isc->periph);
942 cam_iosched_sbintime_sysctl(SYSCTL_HANDLER_ARGS)
949 value = *(sbintime_t *)arg1;
950 us = (uint64_t)value / SBT_1US;
951 snprintf(buf, sizeof(buf), "%ju", (intmax_t)us);
952 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
953 if (error != 0 || req->newptr == NULL)
955 us = strtoul(buf, NULL, 10);
958 *(sbintime_t *)arg1 = us * SBT_1US;
963 cam_iosched_sysctl_latencies(SYSCTL_HANDLER_ARGS)
970 sbuf_new_for_sysctl(&sb, NULL, LAT_BUCKETS * 16, req);
972 for (i = 0; i < LAT_BUCKETS - 1; i++)
973 sbuf_printf(&sb, "%jd,", (intmax_t)latencies[i]);
974 sbuf_printf(&sb, "%jd", (intmax_t)latencies[LAT_BUCKETS - 1]);
975 error = sbuf_finish(&sb);
982 cam_iosched_quanta_sysctl(SYSCTL_HANDLER_ARGS)
987 quanta = (unsigned *)arg1;
990 error = sysctl_handle_int(oidp, (int *)&value, 0, req);
991 if ((error != 0) || (req->newptr == NULL))
994 if (value < 1 || value > hz)
1003 cam_iosched_iop_stats_sysctl_init(struct cam_iosched_softc *isc, struct iop_stats *ios, char *name)
1005 struct sysctl_oid_list *n;
1006 struct sysctl_ctx_list *ctx;
1008 ios->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1009 SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, name,
1010 CTLFLAG_RD | CTLFLAG_MPSAFE, 0, name);
1011 n = SYSCTL_CHILDREN(ios->sysctl_tree);
1012 ctx = &ios->sysctl_ctx;
1014 SYSCTL_ADD_UQUAD(ctx, n,
1015 OID_AUTO, "ema", CTLFLAG_RD,
1017 "Fast Exponentially Weighted Moving Average");
1018 SYSCTL_ADD_UQUAD(ctx, n,
1019 OID_AUTO, "emvar", CTLFLAG_RD,
1021 "Fast Exponentially Weighted Moving Variance");
1023 SYSCTL_ADD_INT(ctx, n,
1024 OID_AUTO, "pending", CTLFLAG_RD,
1026 "Instantaneous # of pending transactions");
1027 SYSCTL_ADD_INT(ctx, n,
1028 OID_AUTO, "count", CTLFLAG_RD,
1030 "# of transactions submitted to hardware");
1031 SYSCTL_ADD_INT(ctx, n,
1032 OID_AUTO, "queued", CTLFLAG_RD,
1034 "# of transactions in the queue");
1035 SYSCTL_ADD_INT(ctx, n,
1036 OID_AUTO, "in", CTLFLAG_RD,
1038 "# of transactions queued to driver");
1039 SYSCTL_ADD_INT(ctx, n,
1040 OID_AUTO, "out", CTLFLAG_RD,
1042 "# of transactions completed (including with error)");
1043 SYSCTL_ADD_INT(ctx, n,
1044 OID_AUTO, "errs", CTLFLAG_RD,
1046 "# of transactions completed with an error");
1048 SYSCTL_ADD_PROC(ctx, n,
1049 OID_AUTO, "limiter",
1050 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
1051 ios, 0, cam_iosched_limiter_sysctl, "A",
1052 "Current limiting type.");
1053 SYSCTL_ADD_INT(ctx, n,
1054 OID_AUTO, "min", CTLFLAG_RW,
1057 SYSCTL_ADD_INT(ctx, n,
1058 OID_AUTO, "max", CTLFLAG_RW,
1061 SYSCTL_ADD_INT(ctx, n,
1062 OID_AUTO, "current", CTLFLAG_RW,
1064 "current resource");
1066 SYSCTL_ADD_PROC(ctx, n,
1067 OID_AUTO, "latencies",
1068 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1070 cam_iosched_sysctl_latencies, "A",
1071 "Array of power of 2 latency from 1ms to 1.024s");
1075 cam_iosched_iop_stats_fini(struct iop_stats *ios)
1077 if (ios->sysctl_tree)
1078 if (sysctl_ctx_free(&ios->sysctl_ctx) != 0)
1079 printf("can't remove iosched sysctl stats context\n");
1083 cam_iosched_cl_sysctl_init(struct cam_iosched_softc *isc)
1085 struct sysctl_oid_list *n;
1086 struct sysctl_ctx_list *ctx;
1087 struct control_loop *clp;
1090 clp->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1091 SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, "control",
1092 CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Control loop info");
1093 n = SYSCTL_CHILDREN(clp->sysctl_tree);
1094 ctx = &clp->sysctl_ctx;
1096 SYSCTL_ADD_PROC(ctx, n,
1098 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
1099 clp, 0, cam_iosched_control_type_sysctl, "A",
1100 "Control loop algorithm");
1101 SYSCTL_ADD_PROC(ctx, n,
1102 OID_AUTO, "steer_interval",
1103 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
1104 &clp->steer_interval, 0, cam_iosched_sbintime_sysctl, "A",
1105 "How often to steer (in us)");
1106 SYSCTL_ADD_PROC(ctx, n,
1108 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
1109 &clp->lolat, 0, cam_iosched_sbintime_sysctl, "A",
1110 "Low water mark for Latency (in us)");
1111 SYSCTL_ADD_PROC(ctx, n,
1113 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
1114 &clp->hilat, 0, cam_iosched_sbintime_sysctl, "A",
1115 "Hi water mark for Latency (in us)");
1116 SYSCTL_ADD_INT(ctx, n,
1117 OID_AUTO, "alpha", CTLFLAG_RW,
1119 "Alpha for PLL (x100) aka gain");
1123 cam_iosched_cl_sysctl_fini(struct control_loop *clp)
1125 if (clp->sysctl_tree)
1126 if (sysctl_ctx_free(&clp->sysctl_ctx) != 0)
1127 printf("can't remove iosched sysctl control loop context\n");
1132 * Allocate the iosched structure. This also insulates callers from knowing
1133 * sizeof struct cam_iosched_softc.
1136 cam_iosched_init(struct cam_iosched_softc **iscp, struct cam_periph *periph)
1139 *iscp = malloc(sizeof(**iscp), M_CAMSCHED, M_NOWAIT | M_ZERO);
1142 #ifdef CAM_IOSCHED_DYNAMIC
1144 printf("CAM IOSCHEDULER Allocating entry at %p\n", *iscp);
1146 (*iscp)->sort_io_queue = -1;
1147 bioq_init(&(*iscp)->bio_queue);
1148 bioq_init(&(*iscp)->trim_queue);
1149 #ifdef CAM_IOSCHED_DYNAMIC
1150 if (do_dynamic_iosched) {
1151 bioq_init(&(*iscp)->write_queue);
1152 (*iscp)->read_bias = 100;
1153 (*iscp)->current_read_bias = 100;
1154 (*iscp)->quanta = min(hz, 200);
1155 cam_iosched_iop_stats_init(*iscp, &(*iscp)->read_stats);
1156 cam_iosched_iop_stats_init(*iscp, &(*iscp)->write_stats);
1157 cam_iosched_iop_stats_init(*iscp, &(*iscp)->trim_stats);
1158 (*iscp)->trim_stats.max = 1; /* Trims are special: one at a time for now */
1159 (*iscp)->last_time = sbinuptime();
1160 callout_init_mtx(&(*iscp)->ticker, cam_periph_mtx(periph), 0);
1161 (*iscp)->periph = periph;
1162 cam_iosched_cl_init(&(*iscp)->cl, *iscp);
1163 callout_reset(&(*iscp)->ticker, hz / (*iscp)->quanta, cam_iosched_ticker, *iscp);
1164 (*iscp)->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
1172 * Reclaim all used resources. This assumes that other folks have
1173 * drained the requests in the hardware. Maybe an unwise assumption.
1176 cam_iosched_fini(struct cam_iosched_softc *isc)
1179 cam_iosched_flush(isc, NULL, ENXIO);
1180 #ifdef CAM_IOSCHED_DYNAMIC
1181 cam_iosched_iop_stats_fini(&isc->read_stats);
1182 cam_iosched_iop_stats_fini(&isc->write_stats);
1183 cam_iosched_iop_stats_fini(&isc->trim_stats);
1184 cam_iosched_cl_sysctl_fini(&isc->cl);
1185 if (isc->sysctl_tree)
1186 if (sysctl_ctx_free(&isc->sysctl_ctx) != 0)
1187 printf("can't remove iosched sysctl stats context\n");
1188 if (isc->flags & CAM_IOSCHED_FLAG_CALLOUT_ACTIVE) {
1189 callout_drain(&isc->ticker);
1190 isc->flags &= ~ CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
1193 free(isc, M_CAMSCHED);
1198 * After we're sure we're attaching a device, go ahead and add
1199 * hooks for any sysctl we may wish to honor.
1201 void cam_iosched_sysctl_init(struct cam_iosched_softc *isc,
1202 struct sysctl_ctx_list *ctx, struct sysctl_oid *node)
1204 struct sysctl_oid_list *n;
1206 n = SYSCTL_CHILDREN(node);
1207 SYSCTL_ADD_INT(ctx, n,
1208 OID_AUTO, "sort_io_queue", CTLFLAG_RW | CTLFLAG_MPSAFE,
1209 &isc->sort_io_queue, 0,
1210 "Sort IO queue to try and optimise disk access patterns");
1211 SYSCTL_ADD_INT(ctx, n,
1212 OID_AUTO, "trim_goal", CTLFLAG_RW,
1214 "Number of trims to try to accumulate before sending to hardware");
1215 SYSCTL_ADD_INT(ctx, n,
1216 OID_AUTO, "trim_ticks", CTLFLAG_RW,
1218 "IO Schedul qaunta to hold back trims for when accumulating");
1220 #ifdef CAM_IOSCHED_DYNAMIC
1221 if (!do_dynamic_iosched)
1224 isc->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1225 SYSCTL_CHILDREN(node), OID_AUTO, "iosched",
1226 CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "I/O scheduler statistics");
1227 n = SYSCTL_CHILDREN(isc->sysctl_tree);
1228 ctx = &isc->sysctl_ctx;
1230 cam_iosched_iop_stats_sysctl_init(isc, &isc->read_stats, "read");
1231 cam_iosched_iop_stats_sysctl_init(isc, &isc->write_stats, "write");
1232 cam_iosched_iop_stats_sysctl_init(isc, &isc->trim_stats, "trim");
1233 cam_iosched_cl_sysctl_init(isc);
1235 SYSCTL_ADD_INT(ctx, n,
1236 OID_AUTO, "read_bias", CTLFLAG_RW,
1237 &isc->read_bias, 100,
1238 "How biased towards read should we be independent of limits");
1240 SYSCTL_ADD_PROC(ctx, n,
1241 OID_AUTO, "quanta", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1242 &isc->quanta, 0, cam_iosched_quanta_sysctl, "I",
1243 "How many quanta per second do we slice the I/O up into");
1245 SYSCTL_ADD_INT(ctx, n,
1246 OID_AUTO, "total_ticks", CTLFLAG_RD,
1247 &isc->total_ticks, 0,
1248 "Total number of ticks we've done");
1250 SYSCTL_ADD_INT(ctx, n,
1251 OID_AUTO, "load", CTLFLAG_RD,
1253 "scaled load average / 100");
1255 SYSCTL_ADD_U64(ctx, n,
1256 OID_AUTO, "latency_trigger", CTLFLAG_RW,
1258 "Latency treshold to trigger callbacks");
1263 cam_iosched_set_latfcn(struct cam_iosched_softc *isc,
1264 cam_iosched_latfcn_t fnp, void *argp)
1266 #ifdef CAM_IOSCHED_DYNAMIC
1273 * Client drivers can set two parameters. "goal" is the number of BIO_DELETEs
1274 * that will be queued up before iosched will "release" the trims to the client
1275 * driver to wo with what they will (usually combine as many as possible). If we
1276 * don't get this many, after trim_ticks we'll submit the I/O anyway with
1277 * whatever we have. We do need an I/O of some kind of to clock the deferred
1278 * trims out to disk. Since we will eventually get a write for the super block
1279 * or something before we shutdown, the trims will complete. To be safe, when a
1280 * BIO_FLUSH is presented to the iosched work queue, we set the ticks time far
1281 * enough in the past so we'll present the BIO_DELETEs to the client driver.
1282 * There might be a race if no BIO_DELETESs were queued, a BIO_FLUSH comes in
1283 * and then a BIO_DELETE is sent down. No know client does this, and there's
1284 * already a race between an ordered BIO_FLUSH and any BIO_DELETEs in flight,
1285 * but no client depends on the ordering being honored.
1287 * XXX I'm not sure what the interaction between UFS direct BIOs and the BUF
1288 * flushing on shutdown. I think there's bufs that would be dependent on the BIO
1289 * finishing to write out at least metadata, so we'll be fine. To be safe, keep
1290 * the number of ticks low (less than maybe 10s) to avoid shutdown races.
1294 cam_iosched_set_trim_goal(struct cam_iosched_softc *isc, int goal)
1297 isc->trim_goal = goal;
1301 cam_iosched_set_trim_ticks(struct cam_iosched_softc *isc, int trim_ticks)
1304 isc->trim_ticks = trim_ticks;
1308 * Flush outstanding I/O. Consumers of this library don't know all the
1309 * queues we may keep, so this allows all I/O to be flushed in one
1313 cam_iosched_flush(struct cam_iosched_softc *isc, struct devstat *stp, int err)
1315 bioq_flush(&isc->bio_queue, stp, err);
1316 bioq_flush(&isc->trim_queue, stp, err);
1317 #ifdef CAM_IOSCHED_DYNAMIC
1318 if (do_dynamic_iosched)
1319 bioq_flush(&isc->write_queue, stp, err);
1323 #ifdef CAM_IOSCHED_DYNAMIC
1325 cam_iosched_get_write(struct cam_iosched_softc *isc)
1330 * We control the write rate by controlling how many requests we send
1331 * down to the drive at any one time. Fewer requests limits the
1332 * effects of both starvation when the requests take a while and write
1333 * amplification when each request is causing more than one write to
1334 * the NAND media. Limiting the queue depth like this will also limit
1335 * the write throughput and give and reads that want to compete to
1338 bp = bioq_first(&isc->write_queue);
1340 if (iosched_debug > 3)
1341 printf("No writes present in write_queue\n");
1346 * If pending read, prefer that based on current read bias
1349 if (bioq_first(&isc->bio_queue) && isc->current_read_bias) {
1352 "Reads present and current_read_bias is %d queued "
1353 "writes %d queued reads %d\n",
1354 isc->current_read_bias, isc->write_stats.queued,
1355 isc->read_stats.queued);
1356 isc->current_read_bias--;
1357 /* We're not limiting writes, per se, just doing reads first */
1362 * See if our current limiter allows this I/O.
1364 if (cam_iosched_limiter_iop(&isc->write_stats, bp) != 0) {
1366 printf("Can't write because limiter says no.\n");
1367 isc->write_stats.state_flags |= IOP_RATE_LIMITED;
1372 * Let's do this: We've passed all the gates and we're a go
1373 * to schedule the I/O in the SIM.
1375 isc->current_read_bias = isc->read_bias;
1376 bioq_remove(&isc->write_queue, bp);
1377 if (bp->bio_cmd == BIO_WRITE) {
1378 isc->write_stats.queued--;
1379 isc->write_stats.total++;
1380 isc->write_stats.pending++;
1382 if (iosched_debug > 9)
1383 printf("HWQ : %p %#x\n", bp, bp->bio_cmd);
1384 isc->write_stats.state_flags &= ~IOP_RATE_LIMITED;
1390 * Put back a trim that you weren't able to actually schedule this time.
1393 cam_iosched_put_back_trim(struct cam_iosched_softc *isc, struct bio *bp)
1395 bioq_insert_head(&isc->trim_queue, bp);
1396 if (isc->queued_trims == 0)
1397 isc->last_trim_tick = ticks;
1398 isc->queued_trims++;
1399 #ifdef CAM_IOSCHED_DYNAMIC
1400 isc->trim_stats.queued++;
1401 isc->trim_stats.total--; /* since we put it back, don't double count */
1402 isc->trim_stats.pending--;
1407 * gets the next trim from the trim queue.
1409 * Assumes we're called with the periph lock held. It removes this
1410 * trim from the queue and the device must explicitly reinsert it
1411 * should the need arise.
1414 cam_iosched_next_trim(struct cam_iosched_softc *isc)
1418 bp = bioq_first(&isc->trim_queue);
1421 bioq_remove(&isc->trim_queue, bp);
1422 isc->queued_trims--;
1423 isc->last_trim_tick = ticks; /* Reset the tick timer when we take trims */
1424 #ifdef CAM_IOSCHED_DYNAMIC
1425 isc->trim_stats.queued--;
1426 isc->trim_stats.total++;
1427 isc->trim_stats.pending++;
1433 * gets an available trim from the trim queue, if there's no trim
1434 * already pending. It removes this trim from the queue and the device
1435 * must explicitly reinsert it should the need arise.
1437 * Assumes we're called with the periph lock held.
1440 cam_iosched_get_trim(struct cam_iosched_softc *isc)
1442 #ifdef CAM_IOSCHED_DYNAMIC
1446 if (!cam_iosched_has_more_trim(isc))
1448 #ifdef CAM_IOSCHED_DYNAMIC
1449 bp = bioq_first(&isc->trim_queue);
1454 * If pending read, prefer that based on current read bias setting. The
1455 * read bias is shared for both writes and TRIMs, but on TRIMs the bias
1456 * is for a combined TRIM not a single TRIM request that's come in.
1458 if (do_dynamic_iosched) {
1459 if (bioq_first(&isc->bio_queue) && isc->current_read_bias) {
1461 printf("Reads present and current_read_bias is %d"
1462 " queued trims %d queued reads %d\n",
1463 isc->current_read_bias, isc->trim_stats.queued,
1464 isc->read_stats.queued);
1465 isc->current_read_bias--;
1466 /* We're not limiting TRIMS, per se, just doing reads first */
1470 * We're going to do a trim, so reset the bias.
1472 isc->current_read_bias = isc->read_bias;
1476 * See if our current limiter allows this I/O. Because we only call this
1477 * here, and not in next_trim, the 'bandwidth' limits for trims won't
1478 * work, while the iops or max queued limits will work. It's tricky
1479 * because we want the limits to be from the perspective of the
1480 * "commands sent to the device." To make iops work, we need to check
1481 * only here (since we want all the ops we combine to count as one). To
1482 * make bw limits work, we'd need to check in next_trim, but that would
1483 * have the effect of limiting the iops as seen from the upper layers.
1485 if (cam_iosched_limiter_iop(&isc->trim_stats, bp) != 0) {
1487 printf("Can't trim because limiter says no.\n");
1488 isc->trim_stats.state_flags |= IOP_RATE_LIMITED;
1491 isc->current_read_bias = isc->read_bias;
1492 isc->trim_stats.state_flags &= ~IOP_RATE_LIMITED;
1493 /* cam_iosched_next_trim below keeps proper book */
1495 return cam_iosched_next_trim(isc);
1499 * Determine what the next bit of work to do is for the periph. The
1500 * default implementation looks to see if we have trims to do, but no
1501 * trims outstanding. If so, we do that. Otherwise we see if we have
1502 * other work. If we do, then we do that. Otherwise why were we called?
1505 cam_iosched_next_bio(struct cam_iosched_softc *isc)
1510 * See if we have a trim that can be scheduled. We can only send one
1511 * at a time down, so this takes that into account.
1513 * XXX newer TRIM commands are queueable. Revisit this when we
1516 if ((bp = cam_iosched_get_trim(isc)) != NULL)
1519 #ifdef CAM_IOSCHED_DYNAMIC
1521 * See if we have any pending writes, and room in the queue for them,
1522 * and if so, those are next.
1524 if (do_dynamic_iosched) {
1525 if ((bp = cam_iosched_get_write(isc)) != NULL)
1531 * next, see if there's other, normal I/O waiting. If so return that.
1533 if ((bp = bioq_first(&isc->bio_queue)) == NULL)
1536 #ifdef CAM_IOSCHED_DYNAMIC
1538 * For the dynamic scheduler, bio_queue is only for reads, so enforce
1539 * the limits here. Enforce only for reads.
1541 if (do_dynamic_iosched) {
1542 if (bp->bio_cmd == BIO_READ &&
1543 cam_iosched_limiter_iop(&isc->read_stats, bp) != 0) {
1544 isc->read_stats.state_flags |= IOP_RATE_LIMITED;
1548 isc->read_stats.state_flags &= ~IOP_RATE_LIMITED;
1550 bioq_remove(&isc->bio_queue, bp);
1551 #ifdef CAM_IOSCHED_DYNAMIC
1552 if (do_dynamic_iosched) {
1553 if (bp->bio_cmd == BIO_READ) {
1554 isc->read_stats.queued--;
1555 isc->read_stats.total++;
1556 isc->read_stats.pending++;
1558 printf("Found bio_cmd = %#x\n", bp->bio_cmd);
1560 if (iosched_debug > 9)
1561 printf("HWQ : %p %#x\n", bp, bp->bio_cmd);
1567 * Driver has been given some work to do by the block layer. Tell the
1568 * scheduler about it and have it queue the work up. The scheduler module
1569 * will then return the currently most useful bit of work later, possibly
1570 * deferring work for various reasons.
1573 cam_iosched_queue_work(struct cam_iosched_softc *isc, struct bio *bp)
1577 * A BIO_SPEEDUP from the uppper layers means that they have a block
1578 * shortage. At the present, this is only sent when we're trying to
1579 * allocate blocks, but have a shortage before giving up. bio_length is
1580 * the size of their shortage. We will complete just enough BIO_DELETEs
1581 * in the queue to satisfy the need. If bio_length is 0, we'll complete
1582 * them all. This allows the scheduler to delay BIO_DELETEs to improve
1583 * read/write performance without worrying about the upper layers. When
1584 * it's possibly a problem, we respond by pretending the BIO_DELETEs
1585 * just worked. We can't do anything about the BIO_DELETEs in the
1586 * hardware, though. We have to wait for them to complete.
1588 if (bp->bio_cmd == BIO_SPEEDUP) {
1593 while (bioq_first(&isc->trim_queue) &&
1594 (bp->bio_length == 0 || len < bp->bio_length)) {
1595 nbp = bioq_takefirst(&isc->trim_queue);
1596 len += nbp->bio_length;
1600 if (bp->bio_length > 0) {
1601 if (bp->bio_length > len)
1602 bp->bio_resid = bp->bio_length - len;
1612 * If we get a BIO_FLUSH, and we're doing delayed BIO_DELETEs then we
1613 * set the last tick time to one less than the current ticks minus the
1614 * delay to force the BIO_DELETEs to be presented to the client driver.
1616 if (bp->bio_cmd == BIO_FLUSH && isc->trim_ticks > 0)
1617 isc->last_trim_tick = ticks - isc->trim_ticks - 1;
1620 * Put all trims on the trim queue. Otherwise put the work on the bio
1623 if (bp->bio_cmd == BIO_DELETE) {
1624 bioq_insert_tail(&isc->trim_queue, bp);
1625 if (isc->queued_trims == 0)
1626 isc->last_trim_tick = ticks;
1627 isc->queued_trims++;
1628 #ifdef CAM_IOSCHED_DYNAMIC
1629 isc->trim_stats.in++;
1630 isc->trim_stats.queued++;
1633 #ifdef CAM_IOSCHED_DYNAMIC
1634 else if (do_dynamic_iosched && (bp->bio_cmd != BIO_READ)) {
1635 if (cam_iosched_sort_queue(isc))
1636 bioq_disksort(&isc->write_queue, bp);
1638 bioq_insert_tail(&isc->write_queue, bp);
1639 if (iosched_debug > 9)
1640 printf("Qw : %p %#x\n", bp, bp->bio_cmd);
1641 if (bp->bio_cmd == BIO_WRITE) {
1642 isc->write_stats.in++;
1643 isc->write_stats.queued++;
1648 if (cam_iosched_sort_queue(isc))
1649 bioq_disksort(&isc->bio_queue, bp);
1651 bioq_insert_tail(&isc->bio_queue, bp);
1652 #ifdef CAM_IOSCHED_DYNAMIC
1653 if (iosched_debug > 9)
1654 printf("Qr : %p %#x\n", bp, bp->bio_cmd);
1655 if (bp->bio_cmd == BIO_READ) {
1656 isc->read_stats.in++;
1657 isc->read_stats.queued++;
1658 } else if (bp->bio_cmd == BIO_WRITE) {
1659 isc->write_stats.in++;
1660 isc->write_stats.queued++;
1667 * If we have work, get it scheduled. Called with the periph lock held.
1670 cam_iosched_schedule(struct cam_iosched_softc *isc, struct cam_periph *periph)
1673 if (cam_iosched_has_work(isc))
1674 xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1678 * Complete a trim request. Mark that we no longer have one in flight.
1681 cam_iosched_trim_done(struct cam_iosched_softc *isc)
1684 isc->flags &= ~CAM_IOSCHED_FLAG_TRIM_ACTIVE;
1688 * Complete a bio. Called before we release the ccb with xpt_release_ccb so we
1689 * might use notes in the ccb for statistics.
1692 cam_iosched_bio_complete(struct cam_iosched_softc *isc, struct bio *bp,
1693 union ccb *done_ccb)
1696 #ifdef CAM_IOSCHED_DYNAMIC
1697 if (!do_dynamic_iosched)
1700 if (iosched_debug > 10)
1701 printf("done: %p %#x\n", bp, bp->bio_cmd);
1702 if (bp->bio_cmd == BIO_WRITE) {
1703 retval = cam_iosched_limiter_iodone(&isc->write_stats, bp);
1704 if ((bp->bio_flags & BIO_ERROR) != 0)
1705 isc->write_stats.errs++;
1706 isc->write_stats.out++;
1707 isc->write_stats.pending--;
1708 } else if (bp->bio_cmd == BIO_READ) {
1709 retval = cam_iosched_limiter_iodone(&isc->read_stats, bp);
1710 if ((bp->bio_flags & BIO_ERROR) != 0)
1711 isc->read_stats.errs++;
1712 isc->read_stats.out++;
1713 isc->read_stats.pending--;
1714 } else if (bp->bio_cmd == BIO_DELETE) {
1715 if ((bp->bio_flags & BIO_ERROR) != 0)
1716 isc->trim_stats.errs++;
1717 isc->trim_stats.out++;
1718 isc->trim_stats.pending--;
1719 } else if (bp->bio_cmd != BIO_FLUSH) {
1721 printf("Completing command with bio_cmd == %#x\n", bp->bio_cmd);
1724 if ((bp->bio_flags & BIO_ERROR) == 0 && done_ccb != NULL &&
1725 (done_ccb->ccb_h.status & CAM_QOS_VALID) != 0) {
1726 sbintime_t sim_latency;
1728 sim_latency = cam_iosched_sbintime_t(done_ccb->ccb_h.qos.periph_data);
1730 cam_iosched_io_metric_update(isc, sim_latency,
1731 bp->bio_cmd, bp->bio_bcount);
1733 * Debugging code: allow callbacks to the periph driver when latency max
1734 * is exceeded. This can be useful for triggering external debugging actions.
1736 if (isc->latfcn && isc->max_lat != 0 && sim_latency > isc->max_lat)
1737 isc->latfcn(isc->latarg, sim_latency, bp);
1745 * Tell the io scheduler that you've pushed a trim down into the sim.
1746 * This also tells the I/O scheduler not to push any more trims down, so
1747 * some periphs do not call it if they can cope with multiple trims in flight.
1750 cam_iosched_submit_trim(struct cam_iosched_softc *isc)
1753 isc->flags |= CAM_IOSCHED_FLAG_TRIM_ACTIVE;
1757 * Change the sorting policy hint for I/O transactions for this device.
1760 cam_iosched_set_sort_queue(struct cam_iosched_softc *isc, int val)
1763 isc->sort_io_queue = val;
1767 cam_iosched_has_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1769 return isc->flags & flags;
1773 cam_iosched_set_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1775 isc->flags |= flags;
1779 cam_iosched_clr_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1781 isc->flags &= ~flags;
1784 #ifdef CAM_IOSCHED_DYNAMIC
1786 * After the method presented in Jack Crenshaw's 1998 article "Integer
1787 * Square Roots," reprinted at
1788 * http://www.embedded.com/electronics-blogs/programmer-s-toolbox/4219659/Integer-Square-Roots
1789 * and well worth the read. Briefly, we find the power of 4 that's the
1790 * largest smaller than val. We then check each smaller power of 4 to
1791 * see if val is still bigger. The right shifts at each step divide
1792 * the result by 2 which after successive application winds up
1793 * accumulating the right answer. It could also have been accumulated
1794 * using a separate root counter, but this code is smaller and faster
1795 * than that method. This method is also integer size invariant.
1796 * It returns floor(sqrt((float)val)), or the largest integer less than
1797 * or equal to the square root.
1800 isqrt64(uint64_t val)
1803 uint64_t bit = 1ULL << (sizeof(uint64_t) * NBBY - 2);
1806 * Find the largest power of 4 smaller than val.
1812 * Accumulate the answer, one bit at a time (we keep moving
1813 * them over since 2 is the square root of 4 and we test
1814 * powers of 4). We accumulate where we find the bit, but
1815 * the successive shifts land the bit in the right place
1819 if (val >= res + bit) {
1821 res = (res >> 1) + bit;
1830 static sbintime_t latencies[LAT_BUCKETS - 1] = {
1831 BUCKET_BASE << 0, /* 20us */
1849 BUCKET_BASE << 18 /* 5,242,880us */
1853 cam_iosched_update(struct iop_stats *iop, sbintime_t sim_latency)
1855 sbintime_t y, deltasq, delta;
1859 * Keep counts for latency. We do it by power of two buckets.
1860 * This helps us spot outlier behavior obscured by averages.
1862 for (i = 0; i < LAT_BUCKETS - 1; i++) {
1863 if (sim_latency < latencies[i]) {
1864 iop->latencies[i]++;
1868 if (i == LAT_BUCKETS - 1)
1869 iop->latencies[i]++; /* Put all > 8192ms values into the last bucket. */
1872 * Classic exponentially decaying average with a tiny alpha
1873 * (2 ^ -alpha_bits). For more info see the NIST statistical
1876 * ema_t = y_t * alpha + ema_t-1 * (1 - alpha) [nist]
1877 * ema_t = y_t * alpha + ema_t-1 - alpha * ema_t-1
1878 * ema_t = alpha * y_t - alpha * ema_t-1 + ema_t-1
1879 * alpha = 1 / (1 << alpha_bits)
1880 * sub e == ema_t-1, b == 1/alpha (== 1 << alpha_bits), d == y_t - ema_t-1
1881 * = y_t/b - e/b + be/b
1882 * = (y_t - e + be) / b
1885 * Since alpha is a power of two, we can compute this w/o any mult or
1888 * Variance can also be computed. Usually, it would be expressed as follows:
1889 * diff_t = y_t - ema_t-1
1890 * emvar_t = (1 - alpha) * (emavar_t-1 + diff_t^2 * alpha)
1891 * = emavar_t-1 - alpha * emavar_t-1 + delta_t^2 * alpha - (delta_t * alpha)^2
1892 * sub b == 1/alpha (== 1 << alpha_bits), e == emavar_t-1, d = delta_t^2
1893 * = e - e/b + dd/b + dd/bb
1894 * = (bbe - be + bdd + dd) / bb
1895 * = (bbe + b(dd-e) + dd) / bb (which is expanded below bb = 1<<(2*alpha_bits))
1898 * XXX possible numeric issues
1899 * o We assume right shifted integers do the right thing, since that's
1900 * implementation defined. You can change the right shifts to / (1LL << alpha).
1901 * o alpha_bits = 9 gives ema ceiling of 23 bits of seconds for ema and 14 bits
1902 * for emvar. This puts a ceiling of 13 bits on alpha since we need a
1903 * few tens of seconds of representation.
1904 * o We mitigate alpha issues by never setting it too high.
1907 delta = (y - iop->ema); /* d */
1908 iop->ema = ((iop->ema << alpha_bits) + delta) >> alpha_bits;
1911 * Were we to naively plow ahead at this point, we wind up with many numerical
1912 * issues making any SD > ~3ms unreliable. So, we shift right by 12. This leaves
1913 * us with microsecond level precision in the input, so the same in the
1914 * output. It means we can't overflow deltasq unless delta > 4k seconds. It
1915 * also means that emvar can be up 46 bits 40 of which are fraction, which
1916 * gives us a way to measure up to ~8s in the SD before the computation goes
1917 * unstable. Even the worst hard disk rarely has > 1s service time in the
1918 * drive. It does mean we have to shift left 12 bits after taking the
1919 * square root to compute the actual standard deviation estimate. This loss of
1920 * precision is preferable to needing int128 types to work. The above numbers
1921 * assume alpha=9. 10 or 11 are ok, but we start to run into issues at 12,
1922 * so 12 or 13 is OK for EMA, EMVAR and SD will be wrong in those cases.
1925 deltasq = delta * delta; /* dd */
1926 iop->emvar = ((iop->emvar << (2 * alpha_bits)) + /* bbe */
1927 ((deltasq - iop->emvar) << alpha_bits) + /* b(dd-e) */
1929 >> (2 * alpha_bits); /* div bb */
1930 iop->sd = (sbintime_t)isqrt64((uint64_t)iop->emvar) << 12;
1934 cam_iosched_io_metric_update(struct cam_iosched_softc *isc,
1935 sbintime_t sim_latency, int cmd, size_t size)
1937 /* xxx Do we need to scale based on the size of the I/O ? */
1940 cam_iosched_update(&isc->read_stats, sim_latency);
1943 cam_iosched_update(&isc->write_stats, sim_latency);
1946 cam_iosched_update(&isc->trim_stats, sim_latency);
1954 static int biolen(struct bio_queue_head *bq)
1959 TAILQ_FOREACH(bp, &bq->queue, bio_queue) {
1966 * Show the internal state of the I/O scheduler.
1968 DB_SHOW_COMMAND(iosched, cam_iosched_db_show)
1970 struct cam_iosched_softc *isc;
1973 db_printf("Need addr\n");
1976 isc = (struct cam_iosched_softc *)addr;
1977 db_printf("pending_reads: %d\n", isc->read_stats.pending);
1978 db_printf("min_reads: %d\n", isc->read_stats.min);
1979 db_printf("max_reads: %d\n", isc->read_stats.max);
1980 db_printf("reads: %d\n", isc->read_stats.total);
1981 db_printf("in_reads: %d\n", isc->read_stats.in);
1982 db_printf("out_reads: %d\n", isc->read_stats.out);
1983 db_printf("queued_reads: %d\n", isc->read_stats.queued);
1984 db_printf("Read Q len %d\n", biolen(&isc->bio_queue));
1985 db_printf("pending_writes: %d\n", isc->write_stats.pending);
1986 db_printf("min_writes: %d\n", isc->write_stats.min);
1987 db_printf("max_writes: %d\n", isc->write_stats.max);
1988 db_printf("writes: %d\n", isc->write_stats.total);
1989 db_printf("in_writes: %d\n", isc->write_stats.in);
1990 db_printf("out_writes: %d\n", isc->write_stats.out);
1991 db_printf("queued_writes: %d\n", isc->write_stats.queued);
1992 db_printf("Write Q len %d\n", biolen(&isc->write_queue));
1993 db_printf("pending_trims: %d\n", isc->trim_stats.pending);
1994 db_printf("min_trims: %d\n", isc->trim_stats.min);
1995 db_printf("max_trims: %d\n", isc->trim_stats.max);
1996 db_printf("trims: %d\n", isc->trim_stats.total);
1997 db_printf("in_trims: %d\n", isc->trim_stats.in);
1998 db_printf("out_trims: %d\n", isc->trim_stats.out);
1999 db_printf("queued_trims: %d\n", isc->trim_stats.queued);
2000 db_printf("Trim Q len %d\n", biolen(&isc->trim_queue));
2001 db_printf("read_bias: %d\n", isc->read_bias);
2002 db_printf("current_read_bias: %d\n", isc->current_read_bias);
2003 db_printf("Trim active? %s\n",
2004 (isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) ? "yes" : "no");