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