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