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