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