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