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