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