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