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