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