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