xref: /freebsd/sys/cam/cam_iosched.c (revision f6a3b357e9be4c6423c85eff9a847163a0d307c8)
1 /*-
2  * CAM IO Scheduler Interface
3  *
4  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5  *
6  * Copyright (c) 2015 Netflix, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
16  *
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
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include "opt_cam.h"
33 #include "opt_ddb.h"
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include <sys/param.h>
39 
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/bio.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/mutex.h>
46 #include <sys/sbuf.h>
47 #include <sys/sysctl.h>
48 
49 #include <cam/cam.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>
55 
56 #include <ddb/ddb.h>
57 
58 static MALLOC_DEFINE(M_CAMSCHED, "CAM I/O Scheduler",
59     "CAM I/O Scheduler buffers");
60 
61 /*
62  * Default I/O scheduler for FreeBSD. This implementation is just a thin-vineer
63  * over the bioq_* interface, with notions of separate calls for normal I/O and
64  * for trims.
65  *
66  * When CAM_IOSCHED_DYNAMIC is defined, the scheduler is enhanced to dynamically
67  * steer the rate of one type of traffic to help other types of traffic (eg
68  * limit writes when read latency deteriorates on SSDs).
69  */
70 
71 #ifdef CAM_IOSCHED_DYNAMIC
72 
73 static int do_dynamic_iosched = 1;
74 TUNABLE_INT("kern.cam.do_dynamic_iosched", &do_dynamic_iosched);
75 SYSCTL_INT(_kern_cam, OID_AUTO, do_dynamic_iosched, CTLFLAG_RD,
76     &do_dynamic_iosched, 1,
77     "Enable Dynamic I/O scheduler optimizations.");
78 
79 /*
80  * For an EMA, with an alpha of alpha, we know
81  * 	alpha = 2 / (N + 1)
82  * or
83  * 	N = 1 + (2 / alpha)
84  * where N is the number of samples that 86% of the current
85  * EMA is derived from.
86  *
87  * So we invent[*] alpha_bits:
88  *	alpha_bits = -log_2(alpha)
89  *	alpha = 2^-alpha_bits
90  * So
91  *	N = 1 + 2^(alpha_bits + 1)
92  *
93  * The default 9 gives a 1025 lookback for 86% of the data.
94  * For a brief intro: https://en.wikipedia.org/wiki/Moving_average
95  *
96  * [*] Steal from the load average code and many other places.
97  * Note: See computation of EMA and EMVAR for acceptable ranges of alpha.
98  */
99 static int alpha_bits = 9;
100 TUNABLE_INT("kern.cam.iosched_alpha_bits", &alpha_bits);
101 SYSCTL_INT(_kern_cam, OID_AUTO, iosched_alpha_bits, CTLFLAG_RW,
102     &alpha_bits, 1,
103     "Bits in EMA's alpha.");
104 
105 struct iop_stats;
106 struct cam_iosched_softc;
107 
108 int iosched_debug = 0;
109 
110 typedef enum {
111 	none = 0,				/* No limits */
112 	queue_depth,			/* Limit how many ops we queue to SIM */
113 	iops,				/* Limit # of IOPS to the drive */
114 	bandwidth,			/* Limit bandwidth to the drive */
115 	limiter_max
116 } io_limiter;
117 
118 static const char *cam_iosched_limiter_names[] =
119     { "none", "queue_depth", "iops", "bandwidth" };
120 
121 /*
122  * Called to initialize the bits of the iop_stats structure relevant to the
123  * limiter. Called just after the limiter is set.
124  */
125 typedef int l_init_t(struct iop_stats *);
126 
127 /*
128  * Called every tick.
129  */
130 typedef int l_tick_t(struct iop_stats *);
131 
132 /*
133  * Called to see if the limiter thinks this IOP can be allowed to
134  * proceed. If so, the limiter assumes that the IOP proceeded
135  * and makes any accounting of it that's needed.
136  */
137 typedef int l_iop_t(struct iop_stats *, struct bio *);
138 
139 /*
140  * Called when an I/O completes so the limiter can update its
141  * accounting. Pending I/Os may complete in any order (even when
142  * sent to the hardware at the same time), so the limiter may not
143  * make any assumptions other than this I/O has completed. If it
144  * returns 1, then xpt_schedule() needs to be called again.
145  */
146 typedef int l_iodone_t(struct iop_stats *, struct bio *);
147 
148 static l_iop_t cam_iosched_qd_iop;
149 static l_iop_t cam_iosched_qd_caniop;
150 static l_iodone_t cam_iosched_qd_iodone;
151 
152 static l_init_t cam_iosched_iops_init;
153 static l_tick_t cam_iosched_iops_tick;
154 static l_iop_t cam_iosched_iops_caniop;
155 static l_iop_t cam_iosched_iops_iop;
156 
157 static l_init_t cam_iosched_bw_init;
158 static l_tick_t cam_iosched_bw_tick;
159 static l_iop_t cam_iosched_bw_caniop;
160 static l_iop_t cam_iosched_bw_iop;
161 
162 struct limswitch {
163 	l_init_t	*l_init;
164 	l_tick_t	*l_tick;
165 	l_iop_t		*l_iop;
166 	l_iop_t		*l_caniop;
167 	l_iodone_t	*l_iodone;
168 } limsw[] =
169 {
170 	{	/* none */
171 		.l_init = NULL,
172 		.l_tick = NULL,
173 		.l_iop = NULL,
174 		.l_iodone= NULL,
175 	},
176 	{	/* queue_depth */
177 		.l_init = NULL,
178 		.l_tick = NULL,
179 		.l_caniop = cam_iosched_qd_caniop,
180 		.l_iop = cam_iosched_qd_iop,
181 		.l_iodone= cam_iosched_qd_iodone,
182 	},
183 	{	/* iops */
184 		.l_init = cam_iosched_iops_init,
185 		.l_tick = cam_iosched_iops_tick,
186 		.l_caniop = cam_iosched_iops_caniop,
187 		.l_iop = cam_iosched_iops_iop,
188 		.l_iodone= NULL,
189 	},
190 	{	/* bandwidth */
191 		.l_init = cam_iosched_bw_init,
192 		.l_tick = cam_iosched_bw_tick,
193 		.l_caniop = cam_iosched_bw_caniop,
194 		.l_iop = cam_iosched_bw_iop,
195 		.l_iodone= NULL,
196 	},
197 };
198 
199 struct iop_stats {
200 	/*
201 	 * sysctl state for this subnode.
202 	 */
203 	struct sysctl_ctx_list	sysctl_ctx;
204 	struct sysctl_oid	*sysctl_tree;
205 
206 	/*
207 	 * Information about the current rate limiters, if any
208 	 */
209 	io_limiter	limiter;	/* How are I/Os being limited */
210 	int		min;		/* Low range of limit */
211 	int		max;		/* High range of limit */
212 	int		current;	/* Current rate limiter */
213 	int		l_value1;	/* per-limiter scratch value 1. */
214 	int		l_value2;	/* per-limiter scratch value 2. */
215 
216 	/*
217 	 * Debug information about counts of I/Os that have gone through the
218 	 * scheduler.
219 	 */
220 	int		pending;	/* I/Os pending in the hardware */
221 	int		queued;		/* number currently in the queue */
222 	int		total;		/* Total for all time -- wraps */
223 	int		in;		/* number queued all time -- wraps */
224 	int		out;		/* number completed all time -- wraps */
225 	int		errs;		/* Number of I/Os completed with error --  wraps */
226 
227 	/*
228 	 * Statistics on different bits of the process.
229 	 */
230 		/* Exp Moving Average, see alpha_bits for more details */
231 	sbintime_t      ema;
232 	sbintime_t      emvar;
233 	sbintime_t      sd;		/* Last computed sd */
234 
235 	uint32_t	state_flags;
236 #define IOP_RATE_LIMITED		1u
237 
238 #define LAT_BUCKETS 15			/* < 1ms < 2ms ... < 2^(n-1)ms >= 2^(n-1)ms*/
239 	uint64_t	latencies[LAT_BUCKETS];
240 
241 	struct cam_iosched_softc *softc;
242 };
243 
244 
245 typedef enum {
246 	set_max = 0,			/* current = max */
247 	read_latency,			/* Steer read latency by throttling writes */
248 	cl_max				/* Keep last */
249 } control_type;
250 
251 static const char *cam_iosched_control_type_names[] =
252     { "set_max", "read_latency" };
253 
254 struct control_loop {
255 	/*
256 	 * sysctl state for this subnode.
257 	 */
258 	struct sysctl_ctx_list	sysctl_ctx;
259 	struct sysctl_oid	*sysctl_tree;
260 
261 	sbintime_t	next_steer;		/* Time of next steer */
262 	sbintime_t	steer_interval;		/* How often do we steer? */
263 	sbintime_t	lolat;
264 	sbintime_t	hilat;
265 	int		alpha;
266 	control_type	type;			/* What type of control? */
267 	int		last_count;		/* Last I/O count */
268 
269 	struct cam_iosched_softc *softc;
270 };
271 
272 #endif
273 
274 struct cam_iosched_softc {
275 	struct bio_queue_head bio_queue;
276 	struct bio_queue_head trim_queue;
277 				/* scheduler flags < 16, user flags >= 16 */
278 	uint32_t	flags;
279 	int		sort_io_queue;
280 	int		trim_goal;		/* # of trims to queue before sending */
281 	int		trim_ticks;		/* Max ticks to hold trims */
282 	int		last_trim_tick;		/* Last 'tick' time ld a trim */
283 	int		queued_trims;		/* Number of trims in the queue */
284 #ifdef CAM_IOSCHED_DYNAMIC
285 	int		read_bias;		/* Read bias setting */
286 	int		current_read_bias;	/* Current read bias state */
287 	int		total_ticks;
288 	int		load;			/* EMA of 'load average' of disk / 2^16 */
289 
290 	struct bio_queue_head write_queue;
291 	struct iop_stats read_stats, write_stats, trim_stats;
292 	struct sysctl_ctx_list	sysctl_ctx;
293 	struct sysctl_oid	*sysctl_tree;
294 
295 	int		quanta;			/* Number of quanta per second */
296 	struct callout	ticker;			/* Callout for our quota system */
297 	struct cam_periph *periph;		/* cam periph associated with this device */
298 	uint32_t	this_frac;		/* Fraction of a second (1024ths) for this tick */
299 	sbintime_t	last_time;		/* Last time we ticked */
300 	struct control_loop cl;
301 	sbintime_t	max_lat;		/* when != 0, if iop latency > max_lat, call max_lat_fcn */
302 	cam_iosched_latfcn_t	latfcn;
303 	void		*latarg;
304 #endif
305 };
306 
307 #ifdef CAM_IOSCHED_DYNAMIC
308 /*
309  * helper functions to call the limsw functions.
310  */
311 static int
312 cam_iosched_limiter_init(struct iop_stats *ios)
313 {
314 	int lim = ios->limiter;
315 
316 	/* maybe this should be a kassert */
317 	if (lim < none || lim >= limiter_max)
318 		return EINVAL;
319 
320 	if (limsw[lim].l_init)
321 		return limsw[lim].l_init(ios);
322 
323 	return 0;
324 }
325 
326 static int
327 cam_iosched_limiter_tick(struct iop_stats *ios)
328 {
329 	int lim = ios->limiter;
330 
331 	/* maybe this should be a kassert */
332 	if (lim < none || lim >= limiter_max)
333 		return EINVAL;
334 
335 	if (limsw[lim].l_tick)
336 		return limsw[lim].l_tick(ios);
337 
338 	return 0;
339 }
340 
341 static int
342 cam_iosched_limiter_iop(struct iop_stats *ios, struct bio *bp)
343 {
344 	int lim = ios->limiter;
345 
346 	/* maybe this should be a kassert */
347 	if (lim < none || lim >= limiter_max)
348 		return EINVAL;
349 
350 	if (limsw[lim].l_iop)
351 		return limsw[lim].l_iop(ios, bp);
352 
353 	return 0;
354 }
355 
356 static int
357 cam_iosched_limiter_caniop(struct iop_stats *ios, struct bio *bp)
358 {
359 	int lim = ios->limiter;
360 
361 	/* maybe this should be a kassert */
362 	if (lim < none || lim >= limiter_max)
363 		return EINVAL;
364 
365 	if (limsw[lim].l_caniop)
366 		return limsw[lim].l_caniop(ios, bp);
367 
368 	return 0;
369 }
370 
371 static int
372 cam_iosched_limiter_iodone(struct iop_stats *ios, struct bio *bp)
373 {
374 	int lim = ios->limiter;
375 
376 	/* maybe this should be a kassert */
377 	if (lim < none || lim >= limiter_max)
378 		return 0;
379 
380 	if (limsw[lim].l_iodone)
381 		return limsw[lim].l_iodone(ios, bp);
382 
383 	return 0;
384 }
385 
386 /*
387  * Functions to implement the different kinds of limiters
388  */
389 
390 static int
391 cam_iosched_qd_iop(struct iop_stats *ios, struct bio *bp)
392 {
393 
394 	if (ios->current <= 0 || ios->pending < ios->current)
395 		return 0;
396 
397 	return EAGAIN;
398 }
399 
400 static int
401 cam_iosched_qd_caniop(struct iop_stats *ios, struct bio *bp)
402 {
403 
404 	if (ios->current <= 0 || ios->pending < ios->current)
405 		return 0;
406 
407 	return EAGAIN;
408 }
409 
410 static int
411 cam_iosched_qd_iodone(struct iop_stats *ios, struct bio *bp)
412 {
413 
414 	if (ios->current <= 0 || ios->pending != ios->current)
415 		return 0;
416 
417 	return 1;
418 }
419 
420 static int
421 cam_iosched_iops_init(struct iop_stats *ios)
422 {
423 
424 	ios->l_value1 = ios->current / ios->softc->quanta;
425 	if (ios->l_value1 <= 0)
426 		ios->l_value1 = 1;
427 	ios->l_value2 = 0;
428 
429 	return 0;
430 }
431 
432 static int
433 cam_iosched_iops_tick(struct iop_stats *ios)
434 {
435 	int new_ios;
436 
437 	/*
438 	 * Allow at least one IO per tick until all
439 	 * the IOs for this interval have been spent.
440 	 */
441 	new_ios = (int)((ios->current * (uint64_t)ios->softc->this_frac) >> 16);
442 	if (new_ios < 1 && ios->l_value2 < ios->current) {
443 		new_ios = 1;
444 		ios->l_value2++;
445 	}
446 
447 	/*
448 	 * If this a new accounting interval, discard any "unspent" ios
449 	 * granted in the previous interval.  Otherwise add the new ios to
450 	 * the previously granted ones that haven't been spent yet.
451 	 */
452 	if ((ios->softc->total_ticks % ios->softc->quanta) == 0) {
453 		ios->l_value1 = new_ios;
454 		ios->l_value2 = 1;
455 	} else {
456 		ios->l_value1 += new_ios;
457 	}
458 
459 
460 	return 0;
461 }
462 
463 static int
464 cam_iosched_iops_caniop(struct iop_stats *ios, struct bio *bp)
465 {
466 
467 	/*
468 	 * So if we have any more IOPs left, allow it,
469 	 * otherwise wait. If current iops is 0, treat that
470 	 * as unlimited as a failsafe.
471 	 */
472 	if (ios->current > 0 && ios->l_value1 <= 0)
473 		return EAGAIN;
474 	return 0;
475 }
476 
477 static int
478 cam_iosched_iops_iop(struct iop_stats *ios, struct bio *bp)
479 {
480 	int rv;
481 
482 	rv = cam_iosched_limiter_caniop(ios, bp);
483 	if (rv == 0)
484 		ios->l_value1--;
485 
486 	return rv;
487 }
488 
489 static int
490 cam_iosched_bw_init(struct iop_stats *ios)
491 {
492 
493 	/* ios->current is in kB/s, so scale to bytes */
494 	ios->l_value1 = ios->current * 1000 / ios->softc->quanta;
495 
496 	return 0;
497 }
498 
499 static int
500 cam_iosched_bw_tick(struct iop_stats *ios)
501 {
502 	int bw;
503 
504 	/*
505 	 * If we're in the hole for available quota from
506 	 * the last time, then add the quantum for this.
507 	 * If we have any left over from last quantum,
508 	 * then too bad, that's lost. Also, ios->current
509 	 * is in kB/s, so scale.
510 	 *
511 	 * We also allow up to 4 quanta of credits to
512 	 * accumulate to deal with burstiness. 4 is extremely
513 	 * arbitrary.
514 	 */
515 	bw = (int)((ios->current * 1000ull * (uint64_t)ios->softc->this_frac) >> 16);
516 	if (ios->l_value1 < bw * 4)
517 		ios->l_value1 += bw;
518 
519 	return 0;
520 }
521 
522 static int
523 cam_iosched_bw_caniop(struct iop_stats *ios, struct bio *bp)
524 {
525 	/*
526 	 * So if we have any more bw quota left, allow it,
527 	 * otherwise wait. Note, we'll go negative and that's
528 	 * OK. We'll just get a little less next quota.
529 	 *
530 	 * Note on going negative: that allows us to process
531 	 * requests in order better, since we won't allow
532 	 * shorter reads to get around the long one that we
533 	 * don't have the quota to do just yet. It also prevents
534 	 * starvation by being a little more permissive about
535 	 * what we let through this quantum (to prevent the
536 	 * starvation), at the cost of getting a little less
537 	 * next quantum.
538 	 *
539 	 * Also note that if the current limit is <= 0,
540 	 * we treat it as unlimited as a failsafe.
541 	 */
542 	if (ios->current > 0 && ios->l_value1 <= 0)
543 		return EAGAIN;
544 
545 
546 	return 0;
547 }
548 
549 static int
550 cam_iosched_bw_iop(struct iop_stats *ios, struct bio *bp)
551 {
552 	int rv;
553 
554 	rv = cam_iosched_limiter_caniop(ios, bp);
555 	if (rv == 0)
556 		ios->l_value1 -= bp->bio_length;
557 
558 	return rv;
559 }
560 
561 static void cam_iosched_cl_maybe_steer(struct control_loop *clp);
562 
563 static void
564 cam_iosched_ticker(void *arg)
565 {
566 	struct cam_iosched_softc *isc = arg;
567 	sbintime_t now, delta;
568 	int pending;
569 
570 	callout_reset(&isc->ticker, hz / isc->quanta, cam_iosched_ticker, isc);
571 
572 	now = sbinuptime();
573 	delta = now - isc->last_time;
574 	isc->this_frac = (uint32_t)delta >> 16;		/* Note: discards seconds -- should be 0 harmless if not */
575 	isc->last_time = now;
576 
577 	cam_iosched_cl_maybe_steer(&isc->cl);
578 
579 	cam_iosched_limiter_tick(&isc->read_stats);
580 	cam_iosched_limiter_tick(&isc->write_stats);
581 	cam_iosched_limiter_tick(&isc->trim_stats);
582 
583 	cam_iosched_schedule(isc, isc->periph);
584 
585 	/*
586 	 * isc->load is an EMA of the pending I/Os at each tick. The number of
587 	 * pending I/Os is the sum of the I/Os queued to the hardware, and those
588 	 * in the software queue that could be queued to the hardware if there
589 	 * were slots.
590 	 *
591 	 * ios_stats.pending is a count of requests in the SIM right now for
592 	 * each of these types of I/O. So the total pending count is the sum of
593 	 * these I/Os and the sum of the queued I/Os still in the software queue
594 	 * for those operations that aren't being rate limited at the moment.
595 	 *
596 	 * The reason for the rate limiting bit is because those I/Os
597 	 * aren't part of the software queued load (since we could
598 	 * give them to hardware, but choose not to).
599 	 *
600 	 * Note: due to a bug in counting pending TRIM in the device, we
601 	 * don't include them in this count. We count each BIO_DELETE in
602 	 * the pending count, but the periph drivers collapse them down
603 	 * into one TRIM command. That one trim command gets the completion
604 	 * so the counts get off.
605 	 */
606 	pending = isc->read_stats.pending + isc->write_stats.pending /* + isc->trim_stats.pending */;
607 	pending += !!(isc->read_stats.state_flags & IOP_RATE_LIMITED) * isc->read_stats.queued +
608 	    !!(isc->write_stats.state_flags & IOP_RATE_LIMITED) * isc->write_stats.queued /* +
609 	    !!(isc->trim_stats.state_flags & IOP_RATE_LIMITED) * isc->trim_stats.queued */ ;
610 	pending <<= 16;
611 	pending /= isc->periph->path->device->ccbq.total_openings;
612 
613 	isc->load = (pending + (isc->load << 13) - isc->load) >> 13; /* see above: 13 -> 16139 / 200/s = ~81s ~1 minute */
614 
615 	isc->total_ticks++;
616 }
617 
618 
619 static void
620 cam_iosched_cl_init(struct control_loop *clp, struct cam_iosched_softc *isc)
621 {
622 
623 	clp->next_steer = sbinuptime();
624 	clp->softc = isc;
625 	clp->steer_interval = SBT_1S * 5;	/* Let's start out steering every 5s */
626 	clp->lolat = 5 * SBT_1MS;
627 	clp->hilat = 15 * SBT_1MS;
628 	clp->alpha = 20;			/* Alpha == gain. 20 = .2 */
629 	clp->type = set_max;
630 }
631 
632 static void
633 cam_iosched_cl_maybe_steer(struct control_loop *clp)
634 {
635 	struct cam_iosched_softc *isc;
636 	sbintime_t now, lat;
637 	int old;
638 
639 	isc = clp->softc;
640 	now = isc->last_time;
641 	if (now < clp->next_steer)
642 		return;
643 
644 	clp->next_steer = now + clp->steer_interval;
645 	switch (clp->type) {
646 	case set_max:
647 		if (isc->write_stats.current != isc->write_stats.max)
648 			printf("Steering write from %d kBps to %d kBps\n",
649 			    isc->write_stats.current, isc->write_stats.max);
650 		isc->read_stats.current = isc->read_stats.max;
651 		isc->write_stats.current = isc->write_stats.max;
652 		isc->trim_stats.current = isc->trim_stats.max;
653 		break;
654 	case read_latency:
655 		old = isc->write_stats.current;
656 		lat = isc->read_stats.ema;
657 		/*
658 		 * Simple PLL-like engine. Since we're steering to a range for
659 		 * the SP (set point) that makes things a little more
660 		 * complicated. In addition, we're not directly controlling our
661 		 * PV (process variable), the read latency, but instead are
662 		 * manipulating the write bandwidth limit for our MV
663 		 * (manipulation variable), analysis of this code gets a bit
664 		 * messy. Also, the MV is a very noisy control surface for read
665 		 * latency since it is affected by many hidden processes inside
666 		 * the device which change how responsive read latency will be
667 		 * in reaction to changes in write bandwidth. Unlike the classic
668 		 * boiler control PLL. this may result in over-steering while
669 		 * the SSD takes its time to react to the new, lower load. This
670 		 * is why we use a relatively low alpha of between .1 and .25 to
671 		 * compensate for this effect. At .1, it takes ~22 steering
672 		 * intervals to back off by a factor of 10. At .2 it only takes
673 		 * ~10. At .25 it only takes ~8. However some preliminary data
674 		 * from the SSD drives suggests a reasponse time in 10's of
675 		 * seconds before latency drops regardless of the new write
676 		 * rate. Careful observation will be required to tune this
677 		 * effectively.
678 		 *
679 		 * Also, when there's no read traffic, we jack up the write
680 		 * limit too regardless of the last read latency.  10 is
681 		 * somewhat arbitrary.
682 		 */
683 		if (lat < clp->lolat || isc->read_stats.total - clp->last_count < 10)
684 			isc->write_stats.current = isc->write_stats.current *
685 			    (100 + clp->alpha) / 100;	/* Scale up */
686 		else if (lat > clp->hilat)
687 			isc->write_stats.current = isc->write_stats.current *
688 			    (100 - clp->alpha) / 100;	/* Scale down */
689 		clp->last_count = isc->read_stats.total;
690 
691 		/*
692 		 * Even if we don't steer, per se, enforce the min/max limits as
693 		 * those may have changed.
694 		 */
695 		if (isc->write_stats.current < isc->write_stats.min)
696 			isc->write_stats.current = isc->write_stats.min;
697 		if (isc->write_stats.current > isc->write_stats.max)
698 			isc->write_stats.current = isc->write_stats.max;
699 		if (old != isc->write_stats.current && 	iosched_debug)
700 			printf("Steering write from %d kBps to %d kBps due to latency of %jdus\n",
701 			    old, isc->write_stats.current,
702 			    (uintmax_t)((uint64_t)1000000 * (uint32_t)lat) >> 32);
703 		break;
704 	case cl_max:
705 		break;
706 	}
707 }
708 #endif
709 
710 /*
711  * Trim or similar currently pending completion. Should only be set for
712  * those drivers wishing only one Trim active at a time.
713  */
714 #define CAM_IOSCHED_FLAG_TRIM_ACTIVE	(1ul << 0)
715 			/* Callout active, and needs to be torn down */
716 #define CAM_IOSCHED_FLAG_CALLOUT_ACTIVE (1ul << 1)
717 
718 			/* Periph drivers set these flags to indicate work */
719 #define CAM_IOSCHED_FLAG_WORK_FLAGS	((0xffffu) << 16)
720 
721 #ifdef CAM_IOSCHED_DYNAMIC
722 static void
723 cam_iosched_io_metric_update(struct cam_iosched_softc *isc,
724     sbintime_t sim_latency, int cmd, size_t size);
725 #endif
726 
727 static inline bool
728 cam_iosched_has_flagged_work(struct cam_iosched_softc *isc)
729 {
730 	return !!(isc->flags & CAM_IOSCHED_FLAG_WORK_FLAGS);
731 }
732 
733 static inline bool
734 cam_iosched_has_io(struct cam_iosched_softc *isc)
735 {
736 #ifdef CAM_IOSCHED_DYNAMIC
737 	if (do_dynamic_iosched) {
738 		struct bio *rbp = bioq_first(&isc->bio_queue);
739 		struct bio *wbp = bioq_first(&isc->write_queue);
740 		bool can_write = wbp != NULL &&
741 		    cam_iosched_limiter_caniop(&isc->write_stats, wbp) == 0;
742 		bool can_read = rbp != NULL &&
743 		    cam_iosched_limiter_caniop(&isc->read_stats, rbp) == 0;
744 		if (iosched_debug > 2) {
745 			printf("can write %d: pending_writes %d max_writes %d\n", can_write, isc->write_stats.pending, isc->write_stats.max);
746 			printf("can read %d: read_stats.pending %d max_reads %d\n", can_read, isc->read_stats.pending, isc->read_stats.max);
747 			printf("Queued reads %d writes %d\n", isc->read_stats.queued, isc->write_stats.queued);
748 		}
749 		return can_read || can_write;
750 	}
751 #endif
752 	return bioq_first(&isc->bio_queue) != NULL;
753 }
754 
755 static inline bool
756 cam_iosched_has_more_trim(struct cam_iosched_softc *isc)
757 {
758 
759 	/*
760 	 * If we've set a trim_goal, then if we exceed that allow trims
761 	 * to be passed back to the driver. If we've also set a tick timeout
762 	 * allow trims back to the driver. Otherwise, don't allow trims yet.
763 	 */
764 	if (isc->trim_goal > 0) {
765 		if (isc->queued_trims >= isc->trim_goal)
766 			return true;
767 		if (isc->queued_trims > 0 &&
768 		    isc->trim_ticks > 0 &&
769 		    ticks - isc->last_trim_tick > isc->trim_ticks)
770 			return true;
771 		return false;
772 	}
773 
774 	return !(isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) &&
775 	    bioq_first(&isc->trim_queue);
776 }
777 
778 #define cam_iosched_sort_queue(isc)	((isc)->sort_io_queue >= 0 ?	\
779     (isc)->sort_io_queue : cam_sort_io_queues)
780 
781 
782 static inline bool
783 cam_iosched_has_work(struct cam_iosched_softc *isc)
784 {
785 #ifdef CAM_IOSCHED_DYNAMIC
786 	if (iosched_debug > 2)
787 		printf("has work: %d %d %d\n", cam_iosched_has_io(isc),
788 		    cam_iosched_has_more_trim(isc),
789 		    cam_iosched_has_flagged_work(isc));
790 #endif
791 
792 	return cam_iosched_has_io(isc) ||
793 		cam_iosched_has_more_trim(isc) ||
794 		cam_iosched_has_flagged_work(isc);
795 }
796 
797 #ifdef CAM_IOSCHED_DYNAMIC
798 static void
799 cam_iosched_iop_stats_init(struct cam_iosched_softc *isc, struct iop_stats *ios)
800 {
801 
802 	ios->limiter = none;
803 	ios->in = 0;
804 	ios->max = ios->current = 300000;
805 	ios->min = 1;
806 	ios->out = 0;
807 	ios->errs = 0;
808 	ios->pending = 0;
809 	ios->queued = 0;
810 	ios->total = 0;
811 	ios->ema = 0;
812 	ios->emvar = 0;
813 	ios->softc = isc;
814 	cam_iosched_limiter_init(ios);
815 }
816 
817 static int
818 cam_iosched_limiter_sysctl(SYSCTL_HANDLER_ARGS)
819 {
820 	char buf[16];
821 	struct iop_stats *ios;
822 	struct cam_iosched_softc *isc;
823 	int value, i, error;
824 	const char *p;
825 
826 	ios = arg1;
827 	isc = ios->softc;
828 	value = ios->limiter;
829 	if (value < none || value >= limiter_max)
830 		p = "UNKNOWN";
831 	else
832 		p = cam_iosched_limiter_names[value];
833 
834 	strlcpy(buf, p, sizeof(buf));
835 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
836 	if (error != 0 || req->newptr == NULL)
837 		return error;
838 
839 	cam_periph_lock(isc->periph);
840 
841 	for (i = none; i < limiter_max; i++) {
842 		if (strcmp(buf, cam_iosched_limiter_names[i]) != 0)
843 			continue;
844 		ios->limiter = i;
845 		error = cam_iosched_limiter_init(ios);
846 		if (error != 0) {
847 			ios->limiter = value;
848 			cam_periph_unlock(isc->periph);
849 			return error;
850 		}
851 		/* Note: disk load averate requires ticker to be always running */
852 		callout_reset(&isc->ticker, hz / isc->quanta, cam_iosched_ticker, isc);
853 		isc->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
854 
855 		cam_periph_unlock(isc->periph);
856 		return 0;
857 	}
858 
859 	cam_periph_unlock(isc->periph);
860 	return EINVAL;
861 }
862 
863 static int
864 cam_iosched_control_type_sysctl(SYSCTL_HANDLER_ARGS)
865 {
866 	char buf[16];
867 	struct control_loop *clp;
868 	struct cam_iosched_softc *isc;
869 	int value, i, error;
870 	const char *p;
871 
872 	clp = arg1;
873 	isc = clp->softc;
874 	value = clp->type;
875 	if (value < none || value >= cl_max)
876 		p = "UNKNOWN";
877 	else
878 		p = cam_iosched_control_type_names[value];
879 
880 	strlcpy(buf, p, sizeof(buf));
881 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
882 	if (error != 0 || req->newptr == NULL)
883 		return error;
884 
885 	for (i = set_max; i < cl_max; i++) {
886 		if (strcmp(buf, cam_iosched_control_type_names[i]) != 0)
887 			continue;
888 		cam_periph_lock(isc->periph);
889 		clp->type = i;
890 		cam_periph_unlock(isc->periph);
891 		return 0;
892 	}
893 
894 	return EINVAL;
895 }
896 
897 static int
898 cam_iosched_sbintime_sysctl(SYSCTL_HANDLER_ARGS)
899 {
900 	char buf[16];
901 	sbintime_t value;
902 	int error;
903 	uint64_t us;
904 
905 	value = *(sbintime_t *)arg1;
906 	us = (uint64_t)value / SBT_1US;
907 	snprintf(buf, sizeof(buf), "%ju", (intmax_t)us);
908 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
909 	if (error != 0 || req->newptr == NULL)
910 		return error;
911 	us = strtoul(buf, NULL, 10);
912 	if (us == 0)
913 		return EINVAL;
914 	*(sbintime_t *)arg1 = us * SBT_1US;
915 	return 0;
916 }
917 
918 static int
919 cam_iosched_sysctl_latencies(SYSCTL_HANDLER_ARGS)
920 {
921 	int i, error;
922 	struct sbuf sb;
923 	uint64_t *latencies;
924 
925 	latencies = arg1;
926 	sbuf_new_for_sysctl(&sb, NULL, LAT_BUCKETS * 16, req);
927 
928 	for (i = 0; i < LAT_BUCKETS - 1; i++)
929 		sbuf_printf(&sb, "%jd,", (intmax_t)latencies[i]);
930 	sbuf_printf(&sb, "%jd", (intmax_t)latencies[LAT_BUCKETS - 1]);
931 	error = sbuf_finish(&sb);
932 	sbuf_delete(&sb);
933 
934 	return (error);
935 }
936 
937 static int
938 cam_iosched_quanta_sysctl(SYSCTL_HANDLER_ARGS)
939 {
940 	int *quanta;
941 	int error, value;
942 
943 	quanta = (unsigned *)arg1;
944 	value = *quanta;
945 
946 	error = sysctl_handle_int(oidp, (int *)&value, 0, req);
947 	if ((error != 0) || (req->newptr == NULL))
948 		return (error);
949 
950 	if (value < 1 || value > hz)
951 		return (EINVAL);
952 
953 	*quanta = value;
954 
955 	return (0);
956 }
957 
958 static void
959 cam_iosched_iop_stats_sysctl_init(struct cam_iosched_softc *isc, struct iop_stats *ios, char *name)
960 {
961 	struct sysctl_oid_list *n;
962 	struct sysctl_ctx_list *ctx;
963 
964 	ios->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
965 	    SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, name,
966 	    CTLFLAG_RD, 0, name);
967 	n = SYSCTL_CHILDREN(ios->sysctl_tree);
968 	ctx = &ios->sysctl_ctx;
969 
970 	SYSCTL_ADD_UQUAD(ctx, n,
971 	    OID_AUTO, "ema", CTLFLAG_RD,
972 	    &ios->ema,
973 	    "Fast Exponentially Weighted Moving Average");
974 	SYSCTL_ADD_UQUAD(ctx, n,
975 	    OID_AUTO, "emvar", CTLFLAG_RD,
976 	    &ios->emvar,
977 	    "Fast Exponentially Weighted Moving Variance");
978 
979 	SYSCTL_ADD_INT(ctx, n,
980 	    OID_AUTO, "pending", CTLFLAG_RD,
981 	    &ios->pending, 0,
982 	    "Instantaneous # of pending transactions");
983 	SYSCTL_ADD_INT(ctx, n,
984 	    OID_AUTO, "count", CTLFLAG_RD,
985 	    &ios->total, 0,
986 	    "# of transactions submitted to hardware");
987 	SYSCTL_ADD_INT(ctx, n,
988 	    OID_AUTO, "queued", CTLFLAG_RD,
989 	    &ios->queued, 0,
990 	    "# of transactions in the queue");
991 	SYSCTL_ADD_INT(ctx, n,
992 	    OID_AUTO, "in", CTLFLAG_RD,
993 	    &ios->in, 0,
994 	    "# of transactions queued to driver");
995 	SYSCTL_ADD_INT(ctx, n,
996 	    OID_AUTO, "out", CTLFLAG_RD,
997 	    &ios->out, 0,
998 	    "# of transactions completed (including with error)");
999 	SYSCTL_ADD_INT(ctx, n,
1000 	    OID_AUTO, "errs", CTLFLAG_RD,
1001 	    &ios->errs, 0,
1002 	    "# of transactions completed with an error");
1003 
1004 	SYSCTL_ADD_PROC(ctx, n,
1005 	    OID_AUTO, "limiter", CTLTYPE_STRING | CTLFLAG_RW,
1006 	    ios, 0, cam_iosched_limiter_sysctl, "A",
1007 	    "Current limiting type.");
1008 	SYSCTL_ADD_INT(ctx, n,
1009 	    OID_AUTO, "min", CTLFLAG_RW,
1010 	    &ios->min, 0,
1011 	    "min resource");
1012 	SYSCTL_ADD_INT(ctx, n,
1013 	    OID_AUTO, "max", CTLFLAG_RW,
1014 	    &ios->max, 0,
1015 	    "max resource");
1016 	SYSCTL_ADD_INT(ctx, n,
1017 	    OID_AUTO, "current", CTLFLAG_RW,
1018 	    &ios->current, 0,
1019 	    "current resource");
1020 
1021 	SYSCTL_ADD_PROC(ctx, n,
1022 	    OID_AUTO, "latencies", CTLTYPE_STRING | CTLFLAG_RD,
1023 	    &ios->latencies, 0,
1024 	    cam_iosched_sysctl_latencies, "A",
1025 	    "Array of power of 2 latency from 1ms to 1.024s");
1026 }
1027 
1028 static void
1029 cam_iosched_iop_stats_fini(struct iop_stats *ios)
1030 {
1031 	if (ios->sysctl_tree)
1032 		if (sysctl_ctx_free(&ios->sysctl_ctx) != 0)
1033 			printf("can't remove iosched sysctl stats context\n");
1034 }
1035 
1036 static void
1037 cam_iosched_cl_sysctl_init(struct cam_iosched_softc *isc)
1038 {
1039 	struct sysctl_oid_list *n;
1040 	struct sysctl_ctx_list *ctx;
1041 	struct control_loop *clp;
1042 
1043 	clp = &isc->cl;
1044 	clp->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1045 	    SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, "control",
1046 	    CTLFLAG_RD, 0, "Control loop info");
1047 	n = SYSCTL_CHILDREN(clp->sysctl_tree);
1048 	ctx = &clp->sysctl_ctx;
1049 
1050 	SYSCTL_ADD_PROC(ctx, n,
1051 	    OID_AUTO, "type", CTLTYPE_STRING | CTLFLAG_RW,
1052 	    clp, 0, cam_iosched_control_type_sysctl, "A",
1053 	    "Control loop algorithm");
1054 	SYSCTL_ADD_PROC(ctx, n,
1055 	    OID_AUTO, "steer_interval", CTLTYPE_STRING | CTLFLAG_RW,
1056 	    &clp->steer_interval, 0, cam_iosched_sbintime_sysctl, "A",
1057 	    "How often to steer (in us)");
1058 	SYSCTL_ADD_PROC(ctx, n,
1059 	    OID_AUTO, "lolat", CTLTYPE_STRING | CTLFLAG_RW,
1060 	    &clp->lolat, 0, cam_iosched_sbintime_sysctl, "A",
1061 	    "Low water mark for Latency (in us)");
1062 	SYSCTL_ADD_PROC(ctx, n,
1063 	    OID_AUTO, "hilat", CTLTYPE_STRING | CTLFLAG_RW,
1064 	    &clp->hilat, 0, cam_iosched_sbintime_sysctl, "A",
1065 	    "Hi water mark for Latency (in us)");
1066 	SYSCTL_ADD_INT(ctx, n,
1067 	    OID_AUTO, "alpha", CTLFLAG_RW,
1068 	    &clp->alpha, 0,
1069 	    "Alpha for PLL (x100) aka gain");
1070 }
1071 
1072 static void
1073 cam_iosched_cl_sysctl_fini(struct control_loop *clp)
1074 {
1075 	if (clp->sysctl_tree)
1076 		if (sysctl_ctx_free(&clp->sysctl_ctx) != 0)
1077 			printf("can't remove iosched sysctl control loop context\n");
1078 }
1079 #endif
1080 
1081 /*
1082  * Allocate the iosched structure. This also insulates callers from knowing
1083  * sizeof struct cam_iosched_softc.
1084  */
1085 int
1086 cam_iosched_init(struct cam_iosched_softc **iscp, struct cam_periph *periph)
1087 {
1088 
1089 	*iscp = malloc(sizeof(**iscp), M_CAMSCHED, M_NOWAIT | M_ZERO);
1090 	if (*iscp == NULL)
1091 		return ENOMEM;
1092 #ifdef CAM_IOSCHED_DYNAMIC
1093 	if (iosched_debug)
1094 		printf("CAM IOSCHEDULER Allocating entry at %p\n", *iscp);
1095 #endif
1096 	(*iscp)->sort_io_queue = -1;
1097 	bioq_init(&(*iscp)->bio_queue);
1098 	bioq_init(&(*iscp)->trim_queue);
1099 #ifdef CAM_IOSCHED_DYNAMIC
1100 	if (do_dynamic_iosched) {
1101 		bioq_init(&(*iscp)->write_queue);
1102 		(*iscp)->read_bias = 100;
1103 		(*iscp)->current_read_bias = 100;
1104 		(*iscp)->quanta = min(hz, 200);
1105 		cam_iosched_iop_stats_init(*iscp, &(*iscp)->read_stats);
1106 		cam_iosched_iop_stats_init(*iscp, &(*iscp)->write_stats);
1107 		cam_iosched_iop_stats_init(*iscp, &(*iscp)->trim_stats);
1108 		(*iscp)->trim_stats.max = 1;	/* Trims are special: one at a time for now */
1109 		(*iscp)->last_time = sbinuptime();
1110 		callout_init_mtx(&(*iscp)->ticker, cam_periph_mtx(periph), 0);
1111 		(*iscp)->periph = periph;
1112 		cam_iosched_cl_init(&(*iscp)->cl, *iscp);
1113 		callout_reset(&(*iscp)->ticker, hz / (*iscp)->quanta, cam_iosched_ticker, *iscp);
1114 		(*iscp)->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
1115 	}
1116 #endif
1117 
1118 	return 0;
1119 }
1120 
1121 /*
1122  * Reclaim all used resources. This assumes that other folks have
1123  * drained the requests in the hardware. Maybe an unwise assumption.
1124  */
1125 void
1126 cam_iosched_fini(struct cam_iosched_softc *isc)
1127 {
1128 	if (isc) {
1129 		cam_iosched_flush(isc, NULL, ENXIO);
1130 #ifdef CAM_IOSCHED_DYNAMIC
1131 		cam_iosched_iop_stats_fini(&isc->read_stats);
1132 		cam_iosched_iop_stats_fini(&isc->write_stats);
1133 		cam_iosched_iop_stats_fini(&isc->trim_stats);
1134 		cam_iosched_cl_sysctl_fini(&isc->cl);
1135 		if (isc->sysctl_tree)
1136 			if (sysctl_ctx_free(&isc->sysctl_ctx) != 0)
1137 				printf("can't remove iosched sysctl stats context\n");
1138 		if (isc->flags & CAM_IOSCHED_FLAG_CALLOUT_ACTIVE) {
1139 			callout_drain(&isc->ticker);
1140 			isc->flags &= ~ CAM_IOSCHED_FLAG_CALLOUT_ACTIVE;
1141 		}
1142 #endif
1143 		free(isc, M_CAMSCHED);
1144 	}
1145 }
1146 
1147 /*
1148  * After we're sure we're attaching a device, go ahead and add
1149  * hooks for any sysctl we may wish to honor.
1150  */
1151 void cam_iosched_sysctl_init(struct cam_iosched_softc *isc,
1152     struct sysctl_ctx_list *ctx, struct sysctl_oid *node)
1153 {
1154 	struct sysctl_oid_list *n;
1155 
1156 	n = SYSCTL_CHILDREN(node);
1157 	SYSCTL_ADD_INT(ctx, n,
1158 		OID_AUTO, "sort_io_queue", CTLFLAG_RW | CTLFLAG_MPSAFE,
1159 		&isc->sort_io_queue, 0,
1160 		"Sort IO queue to try and optimise disk access patterns");
1161 	SYSCTL_ADD_INT(ctx, n,
1162 	    OID_AUTO, "trim_goal", CTLFLAG_RW,
1163 	    &isc->trim_goal, 0,
1164 	    "Number of trims to try to accumulate before sending to hardware");
1165 	SYSCTL_ADD_INT(ctx, n,
1166 	    OID_AUTO, "trim_ticks", CTLFLAG_RW,
1167 	    &isc->trim_goal, 0,
1168 	    "IO Schedul qaunta to hold back trims for when accumulating");
1169 
1170 #ifdef CAM_IOSCHED_DYNAMIC
1171 	if (!do_dynamic_iosched)
1172 		return;
1173 
1174 	isc->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx,
1175 	    SYSCTL_CHILDREN(node), OID_AUTO, "iosched",
1176 	    CTLFLAG_RD, 0, "I/O scheduler statistics");
1177 	n = SYSCTL_CHILDREN(isc->sysctl_tree);
1178 	ctx = &isc->sysctl_ctx;
1179 
1180 	cam_iosched_iop_stats_sysctl_init(isc, &isc->read_stats, "read");
1181 	cam_iosched_iop_stats_sysctl_init(isc, &isc->write_stats, "write");
1182 	cam_iosched_iop_stats_sysctl_init(isc, &isc->trim_stats, "trim");
1183 	cam_iosched_cl_sysctl_init(isc);
1184 
1185 	SYSCTL_ADD_INT(ctx, n,
1186 	    OID_AUTO, "read_bias", CTLFLAG_RW,
1187 	    &isc->read_bias, 100,
1188 	    "How biased towards read should we be independent of limits");
1189 
1190 	SYSCTL_ADD_PROC(ctx, n,
1191 	    OID_AUTO, "quanta", CTLTYPE_UINT | CTLFLAG_RW,
1192 	    &isc->quanta, 0, cam_iosched_quanta_sysctl, "I",
1193 	    "How many quanta per second do we slice the I/O up into");
1194 
1195 	SYSCTL_ADD_INT(ctx, n,
1196 	    OID_AUTO, "total_ticks", CTLFLAG_RD,
1197 	    &isc->total_ticks, 0,
1198 	    "Total number of ticks we've done");
1199 
1200 	SYSCTL_ADD_INT(ctx, n,
1201 	    OID_AUTO, "load", CTLFLAG_RD,
1202 	    &isc->load, 0,
1203 	    "scaled load average / 100");
1204 
1205 	SYSCTL_ADD_U64(ctx, n,
1206 	    OID_AUTO, "latency_trigger", CTLFLAG_RW,
1207 	    &isc->max_lat, 0,
1208 	    "Latency treshold to trigger callbacks");
1209 #endif
1210 }
1211 
1212 void
1213 cam_iosched_set_latfcn(struct cam_iosched_softc *isc,
1214     cam_iosched_latfcn_t fnp, void *argp)
1215 {
1216 #ifdef CAM_IOSCHED_DYNAMIC
1217 	isc->latfcn = fnp;
1218 	isc->latarg = argp;
1219 #endif
1220 }
1221 
1222 /*
1223  * Client drivers can set two parameters. "goal" is the number of BIO_DELETEs
1224  * that will be queued up before iosched will "release" the trims to the client
1225  * driver to wo with what they will (usually combine as many as possible). If we
1226  * don't get this many, after trim_ticks we'll submit the I/O anyway with
1227  * whatever we have.  We do need an I/O of some kind of to clock the deferred
1228  * trims out to disk. Since we will eventually get a write for the super block
1229  * or something before we shutdown, the trims will complete. To be safe, when a
1230  * BIO_FLUSH is presented to the iosched work queue, we set the ticks time far
1231  * enough in the past so we'll present the BIO_DELETEs to the client driver.
1232  * There might be a race if no BIO_DELETESs were queued, a BIO_FLUSH comes in
1233  * and then a BIO_DELETE is sent down. No know client does this, and there's
1234  * already a race between an ordered BIO_FLUSH and any BIO_DELETEs in flight,
1235  * but no client depends on the ordering being honored.
1236  *
1237  * XXX I'm not sure what the interaction between UFS direct BIOs and the BUF
1238  * flushing on shutdown. I think there's bufs that would be dependent on the BIO
1239  * finishing to write out at least metadata, so we'll be fine. To be safe, keep
1240  * the number of ticks low (less than maybe 10s) to avoid shutdown races.
1241  */
1242 
1243 void
1244 cam_iosched_set_trim_goal(struct cam_iosched_softc *isc, int goal)
1245 {
1246 
1247 	isc->trim_goal = goal;
1248 }
1249 
1250 void
1251 cam_iosched_set_trim_ticks(struct cam_iosched_softc *isc, int trim_ticks)
1252 {
1253 
1254 	isc->trim_ticks = trim_ticks;
1255 }
1256 
1257 /*
1258  * Flush outstanding I/O. Consumers of this library don't know all the
1259  * queues we may keep, so this allows all I/O to be flushed in one
1260  * convenient call.
1261  */
1262 void
1263 cam_iosched_flush(struct cam_iosched_softc *isc, struct devstat *stp, int err)
1264 {
1265 	bioq_flush(&isc->bio_queue, stp, err);
1266 	bioq_flush(&isc->trim_queue, stp, err);
1267 #ifdef CAM_IOSCHED_DYNAMIC
1268 	if (do_dynamic_iosched)
1269 		bioq_flush(&isc->write_queue, stp, err);
1270 #endif
1271 }
1272 
1273 #ifdef CAM_IOSCHED_DYNAMIC
1274 static struct bio *
1275 cam_iosched_get_write(struct cam_iosched_softc *isc)
1276 {
1277 	struct bio *bp;
1278 
1279 	/*
1280 	 * We control the write rate by controlling how many requests we send
1281 	 * down to the drive at any one time. Fewer requests limits the
1282 	 * effects of both starvation when the requests take a while and write
1283 	 * amplification when each request is causing more than one write to
1284 	 * the NAND media. Limiting the queue depth like this will also limit
1285 	 * the write throughput and give and reads that want to compete to
1286 	 * compete unfairly.
1287 	 */
1288 	bp = bioq_first(&isc->write_queue);
1289 	if (bp == NULL) {
1290 		if (iosched_debug > 3)
1291 			printf("No writes present in write_queue\n");
1292 		return NULL;
1293 	}
1294 
1295 	/*
1296 	 * If pending read, prefer that based on current read bias
1297 	 * setting.
1298 	 */
1299 	if (bioq_first(&isc->bio_queue) && isc->current_read_bias) {
1300 		if (iosched_debug)
1301 			printf(
1302 			    "Reads present and current_read_bias is %d queued "
1303 			    "writes %d queued reads %d\n",
1304 			    isc->current_read_bias, isc->write_stats.queued,
1305 			    isc->read_stats.queued);
1306 		isc->current_read_bias--;
1307 		/* We're not limiting writes, per se, just doing reads first */
1308 		return NULL;
1309 	}
1310 
1311 	/*
1312 	 * See if our current limiter allows this I/O.
1313 	 */
1314 	if (cam_iosched_limiter_iop(&isc->write_stats, bp) != 0) {
1315 		if (iosched_debug)
1316 			printf("Can't write because limiter says no.\n");
1317 		isc->write_stats.state_flags |= IOP_RATE_LIMITED;
1318 		return NULL;
1319 	}
1320 
1321 	/*
1322 	 * Let's do this: We've passed all the gates and we're a go
1323 	 * to schedule the I/O in the SIM.
1324 	 */
1325 	isc->current_read_bias = isc->read_bias;
1326 	bioq_remove(&isc->write_queue, bp);
1327 	if (bp->bio_cmd == BIO_WRITE) {
1328 		isc->write_stats.queued--;
1329 		isc->write_stats.total++;
1330 		isc->write_stats.pending++;
1331 	}
1332 	if (iosched_debug > 9)
1333 		printf("HWQ : %p %#x\n", bp, bp->bio_cmd);
1334 	isc->write_stats.state_flags &= ~IOP_RATE_LIMITED;
1335 	return bp;
1336 }
1337 #endif
1338 
1339 /*
1340  * Put back a trim that you weren't able to actually schedule this time.
1341  */
1342 void
1343 cam_iosched_put_back_trim(struct cam_iosched_softc *isc, struct bio *bp)
1344 {
1345 	bioq_insert_head(&isc->trim_queue, bp);
1346 	if (isc->queued_trims == 0)
1347 		isc->last_trim_tick = ticks;
1348 	isc->queued_trims++;
1349 #ifdef CAM_IOSCHED_DYNAMIC
1350 	isc->trim_stats.queued++;
1351 	isc->trim_stats.total--;		/* since we put it back, don't double count */
1352 	isc->trim_stats.pending--;
1353 #endif
1354 }
1355 
1356 /*
1357  * gets the next trim from the trim queue.
1358  *
1359  * Assumes we're called with the periph lock held.  It removes this
1360  * trim from the queue and the device must explicitly reinsert it
1361  * should the need arise.
1362  */
1363 struct bio *
1364 cam_iosched_next_trim(struct cam_iosched_softc *isc)
1365 {
1366 	struct bio *bp;
1367 
1368 	bp  = bioq_first(&isc->trim_queue);
1369 	if (bp == NULL)
1370 		return NULL;
1371 	bioq_remove(&isc->trim_queue, bp);
1372 	isc->queued_trims--;
1373 	isc->last_trim_tick = ticks;	/* Reset the tick timer when we take trims */
1374 #ifdef CAM_IOSCHED_DYNAMIC
1375 	isc->trim_stats.queued--;
1376 	isc->trim_stats.total++;
1377 	isc->trim_stats.pending++;
1378 #endif
1379 	return bp;
1380 }
1381 
1382 /*
1383  * gets an available trim from the trim queue, if there's no trim
1384  * already pending. It removes this trim from the queue and the device
1385  * must explicitly reinsert it should the need arise.
1386  *
1387  * Assumes we're called with the periph lock held.
1388  */
1389 struct bio *
1390 cam_iosched_get_trim(struct cam_iosched_softc *isc)
1391 {
1392 
1393 	if (!cam_iosched_has_more_trim(isc))
1394 		return NULL;
1395 #ifdef CAM_IOSCHED_DYNAMIC
1396 	/*
1397 	 * If pending read, prefer that based on current read bias setting. The
1398 	 * read bias is shared for both writes and TRIMs, but on TRIMs the bias
1399 	 * is for a combined TRIM not a single TRIM request that's come in.
1400 	 */
1401 	if (do_dynamic_iosched) {
1402 		if (bioq_first(&isc->bio_queue) && isc->current_read_bias) {
1403 			if (iosched_debug)
1404 				printf("Reads present and current_read_bias is %d"
1405 				    " queued trims %d queued reads %d\n",
1406 				    isc->current_read_bias, isc->trim_stats.queued,
1407 				    isc->read_stats.queued);
1408 			isc->current_read_bias--;
1409 			/* We're not limiting TRIMS, per se, just doing reads first */
1410 			return NULL;
1411 		}
1412 		/*
1413 		 * We're going to do a trim, so reset the bias.
1414 		 */
1415 		isc->current_read_bias = isc->read_bias;
1416 	}
1417 #endif
1418 	return cam_iosched_next_trim(isc);
1419 }
1420 
1421 /*
1422  * Determine what the next bit of work to do is for the periph. The
1423  * default implementation looks to see if we have trims to do, but no
1424  * trims outstanding. If so, we do that. Otherwise we see if we have
1425  * other work. If we do, then we do that. Otherwise why were we called?
1426  */
1427 struct bio *
1428 cam_iosched_next_bio(struct cam_iosched_softc *isc)
1429 {
1430 	struct bio *bp;
1431 
1432 	/*
1433 	 * See if we have a trim that can be scheduled. We can only send one
1434 	 * at a time down, so this takes that into account.
1435 	 *
1436 	 * XXX newer TRIM commands are queueable. Revisit this when we
1437 	 * implement them.
1438 	 */
1439 	if ((bp = cam_iosched_get_trim(isc)) != NULL)
1440 		return bp;
1441 
1442 #ifdef CAM_IOSCHED_DYNAMIC
1443 	/*
1444 	 * See if we have any pending writes, and room in the queue for them,
1445 	 * and if so, those are next.
1446 	 */
1447 	if (do_dynamic_iosched) {
1448 		if ((bp = cam_iosched_get_write(isc)) != NULL)
1449 			return bp;
1450 	}
1451 #endif
1452 
1453 	/*
1454 	 * next, see if there's other, normal I/O waiting. If so return that.
1455 	 */
1456 	if ((bp = bioq_first(&isc->bio_queue)) == NULL)
1457 		return NULL;
1458 
1459 #ifdef CAM_IOSCHED_DYNAMIC
1460 	/*
1461 	 * For the dynamic scheduler, bio_queue is only for reads, so enforce
1462 	 * the limits here. Enforce only for reads.
1463 	 */
1464 	if (do_dynamic_iosched) {
1465 		if (bp->bio_cmd == BIO_READ &&
1466 		    cam_iosched_limiter_iop(&isc->read_stats, bp) != 0) {
1467 			isc->read_stats.state_flags |= IOP_RATE_LIMITED;
1468 			return NULL;
1469 		}
1470 	}
1471 	isc->read_stats.state_flags &= ~IOP_RATE_LIMITED;
1472 #endif
1473 	bioq_remove(&isc->bio_queue, bp);
1474 #ifdef CAM_IOSCHED_DYNAMIC
1475 	if (do_dynamic_iosched) {
1476 		if (bp->bio_cmd == BIO_READ) {
1477 			isc->read_stats.queued--;
1478 			isc->read_stats.total++;
1479 			isc->read_stats.pending++;
1480 		} else
1481 			printf("Found bio_cmd = %#x\n", bp->bio_cmd);
1482 	}
1483 	if (iosched_debug > 9)
1484 		printf("HWQ : %p %#x\n", bp, bp->bio_cmd);
1485 #endif
1486 	return bp;
1487 }
1488 
1489 /*
1490  * Driver has been given some work to do by the block layer. Tell the
1491  * scheduler about it and have it queue the work up. The scheduler module
1492  * will then return the currently most useful bit of work later, possibly
1493  * deferring work for various reasons.
1494  */
1495 void
1496 cam_iosched_queue_work(struct cam_iosched_softc *isc, struct bio *bp)
1497 {
1498 
1499 	/*
1500 	 * If we get a BIO_FLUSH, and we're doing delayed BIO_DELETEs then we
1501 	 * set the last tick time to one less than the current ticks minus the
1502 	 * delay to force the BIO_DELETEs to be presented to the client driver.
1503 	 */
1504 	if (bp->bio_cmd == BIO_FLUSH && isc->trim_ticks > 0)
1505 		isc->last_trim_tick = ticks - isc->trim_ticks - 1;
1506 
1507 	/*
1508 	 * Put all trims on the trim queue. Otherwise put the work on the bio
1509 	 * queue.
1510 	 */
1511 	if (bp->bio_cmd == BIO_DELETE) {
1512 		bioq_insert_tail(&isc->trim_queue, bp);
1513 		if (isc->queued_trims == 0)
1514 			isc->last_trim_tick = ticks;
1515 		isc->queued_trims++;
1516 #ifdef CAM_IOSCHED_DYNAMIC
1517 		isc->trim_stats.in++;
1518 		isc->trim_stats.queued++;
1519 #endif
1520 	}
1521 #ifdef CAM_IOSCHED_DYNAMIC
1522 	else if (do_dynamic_iosched && (bp->bio_cmd != BIO_READ)) {
1523 		if (cam_iosched_sort_queue(isc))
1524 			bioq_disksort(&isc->write_queue, bp);
1525 		else
1526 			bioq_insert_tail(&isc->write_queue, bp);
1527 		if (iosched_debug > 9)
1528 			printf("Qw  : %p %#x\n", bp, bp->bio_cmd);
1529 		if (bp->bio_cmd == BIO_WRITE) {
1530 			isc->write_stats.in++;
1531 			isc->write_stats.queued++;
1532 		}
1533 	}
1534 #endif
1535 	else {
1536 		if (cam_iosched_sort_queue(isc))
1537 			bioq_disksort(&isc->bio_queue, bp);
1538 		else
1539 			bioq_insert_tail(&isc->bio_queue, bp);
1540 #ifdef CAM_IOSCHED_DYNAMIC
1541 		if (iosched_debug > 9)
1542 			printf("Qr  : %p %#x\n", bp, bp->bio_cmd);
1543 		if (bp->bio_cmd == BIO_READ) {
1544 			isc->read_stats.in++;
1545 			isc->read_stats.queued++;
1546 		} else if (bp->bio_cmd == BIO_WRITE) {
1547 			isc->write_stats.in++;
1548 			isc->write_stats.queued++;
1549 		}
1550 #endif
1551 	}
1552 }
1553 
1554 /*
1555  * If we have work, get it scheduled. Called with the periph lock held.
1556  */
1557 void
1558 cam_iosched_schedule(struct cam_iosched_softc *isc, struct cam_periph *periph)
1559 {
1560 
1561 	if (cam_iosched_has_work(isc))
1562 		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1563 }
1564 
1565 /*
1566  * Complete a trim request. Mark that we no longer have one in flight.
1567  */
1568 void
1569 cam_iosched_trim_done(struct cam_iosched_softc *isc)
1570 {
1571 
1572 	isc->flags &= ~CAM_IOSCHED_FLAG_TRIM_ACTIVE;
1573 }
1574 
1575 /*
1576  * Complete a bio. Called before we release the ccb with xpt_release_ccb so we
1577  * might use notes in the ccb for statistics.
1578  */
1579 int
1580 cam_iosched_bio_complete(struct cam_iosched_softc *isc, struct bio *bp,
1581     union ccb *done_ccb)
1582 {
1583 	int retval = 0;
1584 #ifdef CAM_IOSCHED_DYNAMIC
1585 	if (!do_dynamic_iosched)
1586 		return retval;
1587 
1588 	if (iosched_debug > 10)
1589 		printf("done: %p %#x\n", bp, bp->bio_cmd);
1590 	if (bp->bio_cmd == BIO_WRITE) {
1591 		retval = cam_iosched_limiter_iodone(&isc->write_stats, bp);
1592 		if ((bp->bio_flags & BIO_ERROR) != 0)
1593 			isc->write_stats.errs++;
1594 		isc->write_stats.out++;
1595 		isc->write_stats.pending--;
1596 	} else if (bp->bio_cmd == BIO_READ) {
1597 		retval = cam_iosched_limiter_iodone(&isc->read_stats, bp);
1598 		if ((bp->bio_flags & BIO_ERROR) != 0)
1599 			isc->read_stats.errs++;
1600 		isc->read_stats.out++;
1601 		isc->read_stats.pending--;
1602 	} else if (bp->bio_cmd == BIO_DELETE) {
1603 		if ((bp->bio_flags & BIO_ERROR) != 0)
1604 			isc->trim_stats.errs++;
1605 		isc->trim_stats.out++;
1606 		isc->trim_stats.pending--;
1607 	} else if (bp->bio_cmd != BIO_FLUSH) {
1608 		if (iosched_debug)
1609 			printf("Completing command with bio_cmd == %#x\n", bp->bio_cmd);
1610 	}
1611 
1612 	if (!(bp->bio_flags & BIO_ERROR) && done_ccb != NULL) {
1613 		sbintime_t sim_latency;
1614 
1615 		sim_latency = cam_iosched_sbintime_t(done_ccb->ccb_h.qos.periph_data);
1616 
1617 		cam_iosched_io_metric_update(isc, sim_latency,
1618 		    bp->bio_cmd, bp->bio_bcount);
1619 		/*
1620 		 * Debugging code: allow callbacks to the periph driver when latency max
1621 		 * is exceeded. This can be useful for triggering external debugging actions.
1622 		 */
1623 		if (isc->latfcn && isc->max_lat != 0 && sim_latency > isc->max_lat)
1624 			isc->latfcn(isc->latarg, sim_latency, bp);
1625 	}
1626 
1627 #endif
1628 	return retval;
1629 }
1630 
1631 /*
1632  * Tell the io scheduler that you've pushed a trim down into the sim.
1633  * This also tells the I/O scheduler not to push any more trims down, so
1634  * some periphs do not call it if they can cope with multiple trims in flight.
1635  */
1636 void
1637 cam_iosched_submit_trim(struct cam_iosched_softc *isc)
1638 {
1639 
1640 	isc->flags |= CAM_IOSCHED_FLAG_TRIM_ACTIVE;
1641 }
1642 
1643 /*
1644  * Change the sorting policy hint for I/O transactions for this device.
1645  */
1646 void
1647 cam_iosched_set_sort_queue(struct cam_iosched_softc *isc, int val)
1648 {
1649 
1650 	isc->sort_io_queue = val;
1651 }
1652 
1653 int
1654 cam_iosched_has_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1655 {
1656 	return isc->flags & flags;
1657 }
1658 
1659 void
1660 cam_iosched_set_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1661 {
1662 	isc->flags |= flags;
1663 }
1664 
1665 void
1666 cam_iosched_clr_work_flags(struct cam_iosched_softc *isc, uint32_t flags)
1667 {
1668 	isc->flags &= ~flags;
1669 }
1670 
1671 #ifdef CAM_IOSCHED_DYNAMIC
1672 /*
1673  * After the method presented in Jack Crenshaw's 1998 article "Integer
1674  * Square Roots," reprinted at
1675  * http://www.embedded.com/electronics-blogs/programmer-s-toolbox/4219659/Integer-Square-Roots
1676  * and well worth the read. Briefly, we find the power of 4 that's the
1677  * largest smaller than val. We then check each smaller power of 4 to
1678  * see if val is still bigger. The right shifts at each step divide
1679  * the result by 2 which after successive application winds up
1680  * accumulating the right answer. It could also have been accumulated
1681  * using a separate root counter, but this code is smaller and faster
1682  * than that method. This method is also integer size invariant.
1683  * It returns floor(sqrt((float)val)), or the largest integer less than
1684  * or equal to the square root.
1685  */
1686 static uint64_t
1687 isqrt64(uint64_t val)
1688 {
1689 	uint64_t res = 0;
1690 	uint64_t bit = 1ULL << (sizeof(uint64_t) * NBBY - 2);
1691 
1692 	/*
1693 	 * Find the largest power of 4 smaller than val.
1694 	 */
1695 	while (bit > val)
1696 		bit >>= 2;
1697 
1698 	/*
1699 	 * Accumulate the answer, one bit at a time (we keep moving
1700 	 * them over since 2 is the square root of 4 and we test
1701 	 * powers of 4). We accumulate where we find the bit, but
1702 	 * the successive shifts land the bit in the right place
1703 	 * by the end.
1704 	 */
1705 	while (bit != 0) {
1706 		if (val >= res + bit) {
1707 			val -= res + bit;
1708 			res = (res >> 1) + bit;
1709 		} else
1710 			res >>= 1;
1711 		bit >>= 2;
1712 	}
1713 
1714 	return res;
1715 }
1716 
1717 static sbintime_t latencies[LAT_BUCKETS - 1] = {
1718 	SBT_1MS <<  0,
1719 	SBT_1MS <<  1,
1720 	SBT_1MS <<  2,
1721 	SBT_1MS <<  3,
1722 	SBT_1MS <<  4,
1723 	SBT_1MS <<  5,
1724 	SBT_1MS <<  6,
1725 	SBT_1MS <<  7,
1726 	SBT_1MS <<  8,
1727 	SBT_1MS <<  9,
1728 	SBT_1MS << 10,
1729 	SBT_1MS << 11,
1730 	SBT_1MS << 12,
1731 	SBT_1MS << 13		/* 8.192s */
1732 };
1733 
1734 static void
1735 cam_iosched_update(struct iop_stats *iop, sbintime_t sim_latency)
1736 {
1737 	sbintime_t y, deltasq, delta;
1738 	int i;
1739 
1740 	/*
1741 	 * Keep counts for latency. We do it by power of two buckets.
1742 	 * This helps us spot outlier behavior obscured by averages.
1743 	 */
1744 	for (i = 0; i < LAT_BUCKETS - 1; i++) {
1745 		if (sim_latency < latencies[i]) {
1746 			iop->latencies[i]++;
1747 			break;
1748 		}
1749 	}
1750 	if (i == LAT_BUCKETS - 1)
1751 		iop->latencies[i]++; 	 /* Put all > 1024ms values into the last bucket. */
1752 
1753 	/*
1754 	 * Classic exponentially decaying average with a tiny alpha
1755 	 * (2 ^ -alpha_bits). For more info see the NIST statistical
1756 	 * handbook.
1757 	 *
1758 	 * ema_t = y_t * alpha + ema_t-1 * (1 - alpha)		[nist]
1759 	 * ema_t = y_t * alpha + ema_t-1 - alpha * ema_t-1
1760 	 * ema_t = alpha * y_t - alpha * ema_t-1 + ema_t-1
1761 	 * alpha = 1 / (1 << alpha_bits)
1762 	 * sub e == ema_t-1, b == 1/alpha (== 1 << alpha_bits), d == y_t - ema_t-1
1763 	 *	= y_t/b - e/b + be/b
1764 	 *      = (y_t - e + be) / b
1765 	 *	= (e + d) / b
1766 	 *
1767 	 * Since alpha is a power of two, we can compute this w/o any mult or
1768 	 * division.
1769 	 *
1770 	 * Variance can also be computed. Usually, it would be expressed as follows:
1771 	 *	diff_t = y_t - ema_t-1
1772 	 *	emvar_t = (1 - alpha) * (emavar_t-1 + diff_t^2 * alpha)
1773 	 *	  = emavar_t-1 - alpha * emavar_t-1 + delta_t^2 * alpha - (delta_t * alpha)^2
1774 	 * sub b == 1/alpha (== 1 << alpha_bits), e == emavar_t-1, d = delta_t^2
1775 	 *	  = e - e/b + dd/b + dd/bb
1776 	 *	  = (bbe - be + bdd + dd) / bb
1777 	 *	  = (bbe + b(dd-e) + dd) / bb (which is expanded below bb = 1<<(2*alpha_bits))
1778 	 */
1779 	/*
1780 	 * XXX possible numeric issues
1781 	 *	o We assume right shifted integers do the right thing, since that's
1782 	 *	  implementation defined. You can change the right shifts to / (1LL << alpha).
1783 	 *	o alpha_bits = 9 gives ema ceiling of 23 bits of seconds for ema and 14 bits
1784 	 *	  for emvar. This puts a ceiling of 13 bits on alpha since we need a
1785 	 *	  few tens of seconds of representation.
1786 	 *	o We mitigate alpha issues by never setting it too high.
1787 	 */
1788 	y = sim_latency;
1789 	delta = (y - iop->ema);					/* d */
1790 	iop->ema = ((iop->ema << alpha_bits) + delta) >> alpha_bits;
1791 
1792 	/*
1793 	 * Were we to naively plow ahead at this point, we wind up with many numerical
1794 	 * issues making any SD > ~3ms unreliable. So, we shift right by 12. This leaves
1795 	 * us with microsecond level precision in the input, so the same in the
1796 	 * output. It means we can't overflow deltasq unless delta > 4k seconds. It
1797 	 * also means that emvar can be up 46 bits 40 of which are fraction, which
1798 	 * gives us a way to measure up to ~8s in the SD before the computation goes
1799 	 * unstable. Even the worst hard disk rarely has > 1s service time in the
1800 	 * drive. It does mean we have to shift left 12 bits after taking the
1801 	 * square root to compute the actual standard deviation estimate. This loss of
1802 	 * precision is preferable to needing int128 types to work. The above numbers
1803 	 * assume alpha=9. 10 or 11 are ok, but we start to run into issues at 12,
1804 	 * so 12 or 13 is OK for EMA, EMVAR and SD will be wrong in those cases.
1805 	 */
1806 	delta >>= 12;
1807 	deltasq = delta * delta;				/* dd */
1808 	iop->emvar = ((iop->emvar << (2 * alpha_bits)) +	/* bbe */
1809 	    ((deltasq - iop->emvar) << alpha_bits) +		/* b(dd-e) */
1810 	    deltasq)						/* dd */
1811 	    >> (2 * alpha_bits);				/* div bb */
1812 	iop->sd = (sbintime_t)isqrt64((uint64_t)iop->emvar) << 12;
1813 }
1814 
1815 static void
1816 cam_iosched_io_metric_update(struct cam_iosched_softc *isc,
1817     sbintime_t sim_latency, int cmd, size_t size)
1818 {
1819 	/* xxx Do we need to scale based on the size of the I/O ? */
1820 	switch (cmd) {
1821 	case BIO_READ:
1822 		cam_iosched_update(&isc->read_stats, sim_latency);
1823 		break;
1824 	case BIO_WRITE:
1825 		cam_iosched_update(&isc->write_stats, sim_latency);
1826 		break;
1827 	case BIO_DELETE:
1828 		cam_iosched_update(&isc->trim_stats, sim_latency);
1829 		break;
1830 	default:
1831 		break;
1832 	}
1833 }
1834 
1835 #ifdef DDB
1836 static int biolen(struct bio_queue_head *bq)
1837 {
1838 	int i = 0;
1839 	struct bio *bp;
1840 
1841 	TAILQ_FOREACH(bp, &bq->queue, bio_queue) {
1842 		i++;
1843 	}
1844 	return i;
1845 }
1846 
1847 /*
1848  * Show the internal state of the I/O scheduler.
1849  */
1850 DB_SHOW_COMMAND(iosched, cam_iosched_db_show)
1851 {
1852 	struct cam_iosched_softc *isc;
1853 
1854 	if (!have_addr) {
1855 		db_printf("Need addr\n");
1856 		return;
1857 	}
1858 	isc = (struct cam_iosched_softc *)addr;
1859 	db_printf("pending_reads:     %d\n", isc->read_stats.pending);
1860 	db_printf("min_reads:         %d\n", isc->read_stats.min);
1861 	db_printf("max_reads:         %d\n", isc->read_stats.max);
1862 	db_printf("reads:             %d\n", isc->read_stats.total);
1863 	db_printf("in_reads:          %d\n", isc->read_stats.in);
1864 	db_printf("out_reads:         %d\n", isc->read_stats.out);
1865 	db_printf("queued_reads:      %d\n", isc->read_stats.queued);
1866 	db_printf("Current Q len      %d\n", biolen(&isc->bio_queue));
1867 	db_printf("pending_writes:    %d\n", isc->write_stats.pending);
1868 	db_printf("min_writes:        %d\n", isc->write_stats.min);
1869 	db_printf("max_writes:        %d\n", isc->write_stats.max);
1870 	db_printf("writes:            %d\n", isc->write_stats.total);
1871 	db_printf("in_writes:         %d\n", isc->write_stats.in);
1872 	db_printf("out_writes:        %d\n", isc->write_stats.out);
1873 	db_printf("queued_writes:     %d\n", isc->write_stats.queued);
1874 	db_printf("Current Q len      %d\n", biolen(&isc->write_queue));
1875 	db_printf("pending_trims:     %d\n", isc->trim_stats.pending);
1876 	db_printf("min_trims:         %d\n", isc->trim_stats.min);
1877 	db_printf("max_trims:         %d\n", isc->trim_stats.max);
1878 	db_printf("trims:             %d\n", isc->trim_stats.total);
1879 	db_printf("in_trims:          %d\n", isc->trim_stats.in);
1880 	db_printf("out_trims:         %d\n", isc->trim_stats.out);
1881 	db_printf("queued_trims:      %d\n", isc->trim_stats.queued);
1882 	db_printf("Current Q len      %d\n", biolen(&isc->trim_queue));
1883 	db_printf("read_bias:         %d\n", isc->read_bias);
1884 	db_printf("current_read_bias: %d\n", isc->current_read_bias);
1885 	db_printf("Trim active?       %s\n",
1886 	    (isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) ? "yes" : "no");
1887 }
1888 #endif
1889 #endif
1890