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