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