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