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