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