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