Merge from vendor branch FILE:
[dragonfly.git] / sys / net / altq / altq_rmclass.c
1 /*      $KAME: altq_rmclass.c,v 1.18 2003/11/06 06:32:53 kjc Exp $      */
2 /*      $DragonFly: src/sys/net/altq/altq_rmclass.c,v 1.2 2005/05/25 01:44:33 dillon Exp $ */
3
4 /*
5  * Copyright (c) 1991-1997 Regents of the University of California.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the Network Research
19  *      Group at Lawrence Berkeley Laboratory.
20  * 4. Neither the name of the University nor of the Laboratory may be used
21  *    to endorse or promote products derived from this software without
22  *    specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * LBL code modified by speer@eng.sun.com, May 1977.
37  * For questions and/or comments, please send mail to cbq@ee.lbl.gov
38  */
39
40 #ident "@(#)rm_class.c  1.48     97/12/05 SMI"
41
42 #include "opt_altq.h"
43 #include "opt_inet.h"
44 #include "opt_inet6.h"
45
46 #ifdef ALTQ_CBQ /* cbq is enabled by ALTQ_CBQ option in opt_altq.h */
47
48 #include <sys/param.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/socket.h>
52 #include <sys/systm.h>
53 #include <sys/callout.h>
54 #include <sys/errno.h>
55 #include <sys/time.h>
56 #include <sys/thread.h>
57
58 #include <net/if.h>
59
60 #include <net/altq/altq.h>
61 #include <net/altq/altq_rmclass.h>
62 #include <net/altq/altq_rmclass_debug.h>
63 #include <net/altq/altq_red.h>
64 #include <net/altq/altq_rio.h>
65
66 #include <sys/thread2.h>
67
68 #ifdef CBQ_TRACE
69 static struct cbqtrace cbqtrace_buffer[NCBQTRACE+1];
70 static struct cbqtrace *cbqtrace_ptr = NULL;
71 static int cbqtrace_count;
72 #endif
73
74 /*
75  * Local Macros
76  */
77
78 #define reset_cutoff(ifd)       { ifd->cutoff_ = RM_MAXDEPTH; }
79
80 /*
81  * Local routines.
82  */
83
84 static int      rmc_satisfied(struct rm_class *, struct timeval *);
85 static void     rmc_wrr_set_weights(struct rm_ifdat *);
86 static void     rmc_depth_compute(struct rm_class *);
87 static void     rmc_depth_recompute(rm_class_t *);
88
89 static struct mbuf *_rmc_wrr_dequeue_next(struct rm_ifdat *, int);
90 static struct mbuf *_rmc_prr_dequeue_next(struct rm_ifdat *, int);
91
92 static int      _rmc_addq(rm_class_t *, struct mbuf *);
93 static void     _rmc_dropq(rm_class_t *);
94 static struct mbuf *_rmc_getq(rm_class_t *);
95 static struct mbuf *_rmc_pollq(rm_class_t *);
96
97 static int      rmc_under_limit(struct rm_class *, struct timeval *);
98 static void     rmc_tl_satisfied(struct rm_ifdat *, struct timeval *);
99 static void     rmc_drop_action(struct rm_class *);
100 static void     rmc_restart(void *);
101 static void     rmc_root_overlimit(struct rm_class *, struct rm_class *);
102
103 #define BORROW_OFFTIME
104 /*
105  * BORROW_OFFTIME (experimental):
106  * borrow the offtime of the class borrowing from.
107  * the reason is that when its own offtime is set, the class is unable
108  * to borrow much, especially when cutoff is taking effect.
109  * but when the borrowed class is overloaded (advidle is close to minidle),
110  * use the borrowing class's offtime to avoid overload.
111  */
112 #define ADJUST_CUTOFF
113 /*
114  * ADJUST_CUTOFF (experimental):
115  * if no underlimit class is found due to cutoff, increase cutoff and
116  * retry the scheduling loop.
117  * also, don't invoke delay_actions while cutoff is taking effect,
118  * since a sleeping class won't have a chance to be scheduled in the
119  * next loop.
120  *
121  * now heuristics for setting the top-level variable (cutoff_) becomes:
122  *      1. if a packet arrives for a not-overlimit class, set cutoff
123  *         to the depth of the class.
124  *      2. if cutoff is i, and a packet arrives for an overlimit class
125  *         with an underlimit ancestor at a lower level than i (say j),
126  *         then set cutoff to j.
127  *      3. at scheduling a packet, if there is no underlimit class
128  *         due to the current cutoff level, increase cutoff by 1 and
129  *         then try to schedule again.
130  */
131
132 /*
133  * rm_class_t *
134  * rmc_newclass(...) - Create a new resource management class at priority
135  * 'pri' on the interface given by 'ifd'.
136  *
137  * nsecPerByte  is the data rate of the interface in nanoseconds/byte.
138  *              E.g., 800 for a 10Mb/s ethernet.  If the class gets less
139  *              than 100% of the bandwidth, this number should be the
140  *              'effective' rate for the class.  Let f be the
141  *              bandwidth fraction allocated to this class, and let
142  *              nsPerByte be the data rate of the output link in
143  *              nanoseconds/byte.  Then nsecPerByte is set to
144  *              nsPerByte / f.  E.g., 1600 (= 800 / .5)
145  *              for a class that gets 50% of an ethernet's bandwidth.
146  *
147  * action       the routine to call when the class is over limit.
148  *
149  * maxq         max allowable queue size for class (in packets).
150  *
151  * parent       parent class pointer.
152  *
153  * borrow       class to borrow from (should be either 'parent' or null).
154  *
155  * maxidle      max value allowed for class 'idle' time estimate (this
156  *              parameter determines how large an initial burst of packets
157  *              can be before overlimit action is invoked.
158  *
159  * offtime      how long 'delay' action will delay when class goes over
160  *              limit (this parameter determines the steady-state burst
161  *              size when a class is running over its limit).
162  *
163  * Maxidle and offtime have to be computed from the following:  If the
164  * average packet size is s, the bandwidth fraction allocated to this
165  * class is f, we want to allow b packet bursts, and the gain of the
166  * averaging filter is g (= 1 - 2^(-RM_FILTER_GAIN)), then:
167  *
168  *   ptime = s * nsPerByte * (1 - f) / f
169  *   maxidle = ptime * (1 - g^b) / g^b
170  *   minidle = -ptime * (1 / (f - 1))
171  *   offtime = ptime * (1 + 1/(1 - g) * (1 - g^(b - 1)) / g^(b - 1)
172  *
173  * Operationally, it's convenient to specify maxidle & offtime in units
174  * independent of the link bandwidth so the maxidle & offtime passed to
175  * this routine are the above values multiplied by 8*f/(1000*nsPerByte).
176  * (The constant factor is a scale factor needed to make the parameters
177  * integers.  This scaling also means that the 'unscaled' values of
178  * maxidle*nsecPerByte/8 and offtime*nsecPerByte/8 will be in microseconds,
179  * not nanoseconds.)  Also note that the 'idle' filter computation keeps
180  * an estimate scaled upward by 2^RM_FILTER_GAIN so the passed value of
181  * maxidle also must be scaled upward by this value.  Thus, the passed
182  * values for maxidle and offtime can be computed as follows:
183  *
184  * maxidle = maxidle * 2^RM_FILTER_GAIN * 8 / (1000 * nsecPerByte)
185  * offtime = offtime * 8 / (1000 * nsecPerByte)
186  *
187  * When USE_HRTIME is employed, then maxidle and offtime become:
188  *      maxidle = maxilde * (8.0 / nsecPerByte);
189  *      offtime = offtime * (8.0 / nsecPerByte);
190  */
191 struct rm_class *
192 rmc_newclass(int pri, struct rm_ifdat *ifd, u_int nsecPerByte,
193              void (*action)(rm_class_t *, rm_class_t *), int maxq,
194              struct rm_class *parent, struct rm_class *borrow, u_int maxidle,
195              int minidle, u_int offtime, int pktsize, int flags)
196 {
197         struct rm_class *cl;
198         struct rm_class *peer;
199         int s;
200
201         if (pri >= RM_MAXPRIO)
202                 return (NULL);
203 #ifndef ALTQ_RED
204         if (flags & RMCF_RED) {
205 #ifdef ALTQ_DEBUG
206                 printf("rmc_newclass: RED not configured for CBQ!\n");
207 #endif
208                 return (NULL);
209         }
210 #endif
211 #ifndef ALTQ_RIO
212         if (flags & RMCF_RIO) {
213 #ifdef ALTQ_DEBUG
214                 printf("rmc_newclass: RIO not configured for CBQ!\n");
215 #endif
216                 return (NULL);
217         }
218 #endif
219
220         cl = malloc(sizeof(*cl), M_ALTQ, M_WAITOK | M_ZERO);
221         callout_init(&cl->callout_);
222         cl->q_ = malloc(sizeof(*cl->q_), M_ALTQ, M_WAITOK | M_ZERO);
223
224         /*
225          * Class initialization.
226          */
227         cl->children_ = NULL;
228         cl->parent_ = parent;
229         cl->borrow_ = borrow;
230         cl->leaf_ = 1;
231         cl->ifdat_ = ifd;
232         cl->pri_ = pri;
233         cl->allotment_ = RM_NS_PER_SEC / nsecPerByte; /* Bytes per sec */
234         cl->depth_ = 0;
235         cl->qthresh_ = 0;
236         cl->ns_per_byte_ = nsecPerByte;
237
238         qlimit(cl->q_) = maxq;
239         qtype(cl->q_) = Q_DROPHEAD;
240         qlen(cl->q_) = 0;
241         cl->flags_ = flags;
242
243 #if 1 /* minidle is also scaled in ALTQ */
244         cl->minidle_ = (minidle * (int)nsecPerByte) / 8;
245         if (cl->minidle_ > 0)
246                 cl->minidle_ = 0;
247 #else
248         cl->minidle_ = minidle;
249 #endif
250         cl->maxidle_ = (maxidle * nsecPerByte) / 8;
251         if (cl->maxidle_ == 0)
252                 cl->maxidle_ = 1;
253 #if 1 /* offtime is also scaled in ALTQ */
254         cl->avgidle_ = cl->maxidle_;
255         cl->offtime_ = ((offtime * nsecPerByte) / 8) >> RM_FILTER_GAIN;
256         if (cl->offtime_ == 0)
257                 cl->offtime_ = 1;
258 #else
259         cl->avgidle_ = 0;
260         cl->offtime_ = (offtime * nsecPerByte) / 8;
261 #endif
262         cl->overlimit = action;
263
264 #ifdef ALTQ_RED
265         if (flags & (RMCF_RED|RMCF_RIO)) {
266                 int red_flags, red_pkttime;
267
268                 red_flags = 0;
269                 if (flags & RMCF_ECN)
270                         red_flags |= REDF_ECN;
271 #ifdef ALTQ_RIO
272                 if (flags & RMCF_CLEARDSCP)
273                         red_flags |= RIOF_CLEARDSCP;
274 #endif
275                 red_pkttime = nsecPerByte * pktsize  / 1000;
276
277                 if (flags & RMCF_RED) {
278                         cl->red_ = red_alloc(0, 0,
279                             qlimit(cl->q_) * 10/100,
280                             qlimit(cl->q_) * 30/100,
281                             red_flags, red_pkttime);
282                         if (cl->red_ != NULL)
283                                 qtype(cl->q_) = Q_RED;
284                 }
285 #ifdef ALTQ_RIO
286                 else {
287                         cl->red_ = (red_t *)rio_alloc(0, NULL,
288                                                       red_flags, red_pkttime);
289                         if (cl->red_ != NULL)
290                                 qtype(cl->q_) = Q_RIO;
291                 }
292 #endif
293         }
294 #endif /* ALTQ_RED */
295
296         /*
297          * put the class into the class tree
298          */
299         s = splimp();
300         if ((peer = ifd->active_[pri]) != NULL) {
301                 /* find the last class at this pri */
302                 cl->peer_ = peer;
303                 while (peer->peer_ != ifd->active_[pri])
304                         peer = peer->peer_;
305                 peer->peer_ = cl;
306         } else {
307                 ifd->active_[pri] = cl;
308                 cl->peer_ = cl;
309         }
310
311         if (cl->parent_) {
312                 cl->next_ = parent->children_;
313                 parent->children_ = cl;
314                 parent->leaf_ = 0;
315         }
316
317         /*
318          * Compute the depth of this class and its ancestors in the class
319          * hierarchy.
320          */
321         rmc_depth_compute(cl);
322
323         /*
324          * If CBQ's WRR is enabled, then initialize the class WRR state.
325          */
326         if (ifd->wrr_) {
327                 ifd->num_[pri]++;
328                 ifd->alloc_[pri] += cl->allotment_;
329                 rmc_wrr_set_weights(ifd);
330         }
331         splx(s);
332         return (cl);
333 }
334
335 int
336 rmc_modclass(struct rm_class *cl, u_int nsecPerByte, int maxq, u_int maxidle,
337              int minidle, u_int offtime, int pktsize)
338 {
339         struct rm_ifdat *ifd;
340         u_int old_allotment;
341         int s;
342
343         ifd = cl->ifdat_;
344         old_allotment = cl->allotment_;
345
346         s = splimp();
347         cl->allotment_ = RM_NS_PER_SEC / nsecPerByte; /* Bytes per sec */
348         cl->qthresh_ = 0;
349         cl->ns_per_byte_ = nsecPerByte;
350
351         qlimit(cl->q_) = maxq;
352
353 #if 1 /* minidle is also scaled in ALTQ */
354         cl->minidle_ = (minidle * nsecPerByte) / 8;
355         if (cl->minidle_ > 0)
356                 cl->minidle_ = 0;
357 #else
358         cl->minidle_ = minidle;
359 #endif
360         cl->maxidle_ = (maxidle * nsecPerByte) / 8;
361         if (cl->maxidle_ == 0)
362                 cl->maxidle_ = 1;
363 #if 1 /* offtime is also scaled in ALTQ */
364         cl->avgidle_ = cl->maxidle_;
365         cl->offtime_ = ((offtime * nsecPerByte) / 8) >> RM_FILTER_GAIN;
366         if (cl->offtime_ == 0)
367                 cl->offtime_ = 1;
368 #else
369         cl->avgidle_ = 0;
370         cl->offtime_ = (offtime * nsecPerByte) / 8;
371 #endif
372
373         /*
374          * If CBQ's WRR is enabled, then initialize the class WRR state.
375          */
376         if (ifd->wrr_) {
377                 ifd->alloc_[cl->pri_] += cl->allotment_ - old_allotment;
378                 rmc_wrr_set_weights(ifd);
379         }
380         splx(s);
381         return (0);
382 }
383
384 /*
385  * static void
386  * rmc_wrr_set_weights(struct rm_ifdat *ifdat) - This function computes
387  *      the appropriate run robin weights for the CBQ weighted round robin
388  *      algorithm.
389  *
390  *      Returns: NONE
391  */
392
393 static void
394 rmc_wrr_set_weights(struct rm_ifdat *ifd)
395 {
396         int i;
397         struct rm_class *cl, *clh;
398
399         for (i = 0; i < RM_MAXPRIO; i++) {
400                 /*
401                  * This is inverted from that of the simulator to
402                  * maintain precision.
403                  */
404                 if (ifd->num_[i] == 0)
405                         ifd->M_[i] = 0;
406                 else
407                         ifd->M_[i] = ifd->alloc_[i] /
408                                 (ifd->num_[i] * ifd->maxpkt_);
409                 /*
410                  * Compute the weighted allotment for each class.
411                  * This takes the expensive div instruction out
412                  * of the main loop for the wrr scheduling path.
413                  * These only get recomputed when a class comes or
414                  * goes.
415                  */
416                 if (ifd->active_[i] != NULL) {
417                         clh = cl = ifd->active_[i];
418                         do {
419                                 /* safe-guard for slow link or alloc_ == 0 */
420                                 if (ifd->M_[i] == 0)
421                                         cl->w_allotment_ = 0;
422                                 else
423                                         cl->w_allotment_ = cl->allotment_ /
424                                                 ifd->M_[i];
425                                 cl = cl->peer_;
426                         } while ((cl != NULL) && (cl != clh));
427                 }
428         }
429 }
430
431 int
432 rmc_get_weight(struct rm_ifdat *ifd, int pri)
433 {
434         if ((pri >= 0) && (pri < RM_MAXPRIO))
435                 return (ifd->M_[pri]);
436         else
437                 return (0);
438 }
439
440 /*
441  * static void
442  * rmc_depth_compute(struct rm_class *cl) - This function computes the
443  *      appropriate depth of class 'cl' and its ancestors.
444  *
445  *      Returns:        NONE
446  */
447
448 static void
449 rmc_depth_compute(struct rm_class *cl)
450 {
451         rm_class_t *t = cl, *p;
452
453         /*
454          * Recompute the depth for the branch of the tree.
455          */
456         while (t != NULL) {
457                 p = t->parent_;
458                 if (p && (t->depth_ >= p->depth_)) {
459                         p->depth_ = t->depth_ + 1;
460                         t = p;
461                 } else
462                         t = NULL;
463         }
464 }
465
466 /*
467  * static void
468  * rmc_depth_recompute(struct rm_class *cl) - This function re-computes
469  *      the depth of the tree after a class has been deleted.
470  *
471  *      Returns:        NONE
472  */
473
474 static void
475 rmc_depth_recompute(rm_class_t *cl)
476 {
477 #if 1 /* ALTQ */
478         rm_class_t *p, *t;
479
480         p = cl;
481         while (p != NULL) {
482                 if ((t = p->children_) == NULL) {
483                         p->depth_ = 0;
484                 } else {
485                         int cdepth = 0;
486
487                         while (t != NULL) {
488                                 if (t->depth_ > cdepth)
489                                         cdepth = t->depth_;
490                                 t = t->next_;
491                         }
492
493                         if (p->depth_ == cdepth + 1)
494                                 /* no change to this parent */
495                                 return;
496
497                         p->depth_ = cdepth + 1;
498                 }
499
500                 p = p->parent_;
501         }
502 #else
503         rm_class_t      *t;
504
505         if (cl->depth_ >= 1) {
506                 if (cl->children_ == NULL) {
507                         cl->depth_ = 0;
508                 } else if ((t = cl->children_) != NULL) {
509                         while (t != NULL) {
510                                 if (t->children_ != NULL)
511                                         rmc_depth_recompute(t);
512                                 t = t->next_;
513                         }
514                 } else
515                         rmc_depth_compute(cl);
516         }
517 #endif
518 }
519
520 /*
521  * void
522  * rmc_delete_class(struct rm_ifdat *ifdat, struct rm_class *cl) - This
523  *      function deletes a class from the link-sharing structure and frees
524  *      all resources associated with the class.
525  *
526  *      Returns: NONE
527  */
528
529 void
530 rmc_delete_class(struct rm_ifdat *ifd, struct rm_class *cl)
531 {
532         struct rm_class *p, *head, *previous;
533         int s;
534
535         KKASSERT(cl->children_ == NULL);
536
537         if (cl->sleeping_)
538                 callout_stop(&cl->callout_);
539
540         s = splimp();
541         /*
542          * Free packets in the packet queue.
543          * XXX - this may not be a desired behavior.  Packets should be
544          *              re-queued.
545          */
546         rmc_dropall(cl);
547
548         /*
549          * If the class has a parent, then remove the class from the
550          * class from the parent's children chain.
551          */
552         if (cl->parent_ != NULL) {
553                 head = cl->parent_->children_;
554                 p = previous = head;
555                 if (head->next_ == NULL) {
556                         KKASSERT(head == cl);
557                         cl->parent_->children_ = NULL;
558                         cl->parent_->leaf_ = 1;
559                 } else while (p != NULL) {
560                         if (p == cl) {
561                                 if (cl == head)
562                                         cl->parent_->children_ = cl->next_;
563                                 else
564                                         previous->next_ = cl->next_;
565                                 cl->next_ = NULL;
566                                 p = NULL;
567                         } else {
568                                 previous = p;
569                                 p = p->next_;
570                         }
571                 }
572         }
573
574         /*
575          * Delete class from class priority peer list.
576          */
577         if ((p = ifd->active_[cl->pri_]) != NULL) {
578                 /*
579                  * If there is more than one member of this priority
580                  * level, then look for class(cl) in the priority level.
581                  */
582                 if (p != p->peer_) {
583                         while (p->peer_ != cl)
584                                 p = p->peer_;
585                         p->peer_ = cl->peer_;
586
587                         if (ifd->active_[cl->pri_] == cl)
588                                 ifd->active_[cl->pri_] = cl->peer_;
589                 } else {
590                         KKASSERT(p == cl);
591                         ifd->active_[cl->pri_] = NULL;
592                 }
593         }
594
595         /*
596          * Recompute the WRR weights.
597          */
598         if (ifd->wrr_) {
599                 ifd->alloc_[cl->pri_] -= cl->allotment_;
600                 ifd->num_[cl->pri_]--;
601                 rmc_wrr_set_weights(ifd);
602         }
603
604         /*
605          * Re-compute the depth of the tree.
606          */
607 #if 1 /* ALTQ */
608         rmc_depth_recompute(cl->parent_);
609 #else
610         rmc_depth_recompute(ifd->root_);
611 #endif
612
613         splx(s);
614
615         /*
616          * Free the class structure.
617          */
618         if (cl->red_ != NULL) {
619 #ifdef ALTQ_RIO
620                 if (q_is_rio(cl->q_))
621                         rio_destroy((rio_t *)cl->red_);
622 #endif
623 #ifdef ALTQ_RED
624                 if (q_is_red(cl->q_))
625                         red_destroy(cl->red_);
626 #endif
627         }
628         free(cl->q_, M_ALTQ);
629         free(cl, M_ALTQ);
630 }
631
632 /*
633  * void
634  * rmc_init(...) - Initialize the resource management data structures
635  *      associated with the output portion of interface 'ifp'.  'ifd' is
636  *      where the structures will be built (for backwards compatibility, the
637  *      structures aren't kept in the ifnet struct).  'nsecPerByte'
638  *      gives the link speed (inverse of bandwidth) in nanoseconds/byte.
639  *      'restart' is the driver-specific routine that the generic 'delay
640  *      until under limit' action will call to restart output.  `maxq'
641  *      is the queue size of the 'link' & 'default' classes.  'maxqueued'
642  *      is the maximum number of packets that the resource management
643  *      code will allow to be queued 'downstream' (this is typically 1).
644  *
645  *      Returns:        NONE
646  */
647
648 void
649 rmc_init(struct ifaltq *ifq, struct rm_ifdat *ifd, u_int nsecPerByte,
650          void (*restart)(struct ifaltq *), int maxq, int maxqueued, u_int maxidle,
651          int minidle, u_int offtime, int flags)
652 {
653         int i, mtu;
654
655         /*
656          * Initialize the CBQ tracing/debug facility.
657          */
658         CBQTRACEINIT();
659
660         bzero(ifd, sizeof (*ifd));
661         mtu = ifq->altq_ifp->if_mtu;
662         ifd->ifq_ = ifq;
663         ifd->restart = restart;
664         ifd->maxqueued_ = maxqueued;
665         ifd->ns_per_byte_ = nsecPerByte;
666         ifd->maxpkt_ = mtu;
667         ifd->wrr_ = (flags & RMCF_WRR) ? 1 : 0;
668         ifd->efficient_ = (flags & RMCF_EFFICIENT) ? 1 : 0;
669 #if 1
670         ifd->maxiftime_ = mtu * nsecPerByte / 1000 * 16;
671         if (mtu * nsecPerByte > 10 * 1000000)
672                 ifd->maxiftime_ /= 4;
673 #endif
674
675         reset_cutoff(ifd);
676         CBQTRACE(rmc_init, 'INIT', ifd->cutoff_);
677
678         /*
679          * Initialize the CBQ's WRR state.
680          */
681         for (i = 0; i < RM_MAXPRIO; i++) {
682                 ifd->alloc_[i] = 0;
683                 ifd->M_[i] = 0;
684                 ifd->num_[i] = 0;
685                 ifd->na_[i] = 0;
686                 ifd->active_[i] = NULL;
687         }
688
689         /*
690          * Initialize current packet state.
691          */
692         ifd->qi_ = 0;
693         ifd->qo_ = 0;
694         for (i = 0; i < RM_MAXQUEUED; i++) {
695                 ifd->class_[i] = NULL;
696                 ifd->curlen_[i] = 0;
697                 ifd->borrowed_[i] = NULL;
698         }
699
700         /*
701          * Create the root class of the link-sharing structure.
702          */
703         ifd->root_ = rmc_newclass(0, ifd, nsecPerByte, rmc_root_overlimit,
704                                   maxq, 0, 0, maxidle, minidle, offtime, 0, 0);
705         if (ifd->root_ == NULL) {
706                 printf("rmc_init: root class not allocated\n");
707                 return ;
708         }
709         ifd->root_->depth_ = 0;
710 }
711
712 /*
713  * void
714  * rmc_queue_packet(struct rm_class *cl, struct mbuf *m) - Add packet given by
715  *      mbuf 'm' to queue for resource class 'cl'.  This routine is called
716  *      by a driver's if_output routine.  This routine must be called with
717  *      output packet completion interrupts locked out (to avoid racing with
718  *      rmc_dequeue_next).
719  *
720  *      Returns:        0 on successful queueing
721  *                      -1 when packet drop occurs
722  */
723 int
724 rmc_queue_packet(struct rm_class *cl, struct mbuf *m)
725 {
726         struct timeval now;
727         struct rm_ifdat *ifd = cl->ifdat_;
728         int cpri = cl->pri_;
729         int is_empty = qempty(cl->q_);
730
731         RM_GETTIME(now);
732         if (ifd->cutoff_ > 0) {
733                 if (TV_LT(&cl->undertime_, &now)) {
734                         if (ifd->cutoff_ > cl->depth_)
735                                 ifd->cutoff_ = cl->depth_;
736                         CBQTRACE(rmc_queue_packet, 'ffoc', cl->depth_);
737                 }
738 #if 1 /* ALTQ */
739                 else {
740                         /*
741                          * the class is overlimit. if the class has
742                          * underlimit ancestors, set cutoff to the lowest
743                          * depth among them.
744                          */
745                         struct rm_class *borrow = cl->borrow_;
746
747                         while (borrow != NULL &&
748                                borrow->depth_ < ifd->cutoff_) {
749                                 if (TV_LT(&borrow->undertime_, &now)) {
750                                         ifd->cutoff_ = borrow->depth_;
751                                         CBQTRACE(rmc_queue_packet, 'ffob', ifd->cutoff_);
752                                         break;
753                                 }
754                                 borrow = borrow->borrow_;
755                         }
756                 }
757 #else /* !ALTQ */
758                 else if ((ifd->cutoff_ > 1) && cl->borrow_) {
759                         if (TV_LT(&cl->borrow_->undertime_, &now)) {
760                                 ifd->cutoff_ = cl->borrow_->depth_;
761                                 CBQTRACE(rmc_queue_packet, 'ffob',
762                                          cl->borrow_->depth_);
763                         }
764                 }
765 #endif /* !ALTQ */
766         }
767
768         if (_rmc_addq(cl, m) < 0)
769                 /* failed */
770                 return (-1);
771
772         if (is_empty) {
773                 CBQTRACE(rmc_queue_packet, 'ytpe', cl->stats_.handle);
774                 ifd->na_[cpri]++;
775         }
776
777         if (qlen(cl->q_) > qlimit(cl->q_)) {
778                 /* note: qlimit can be set to 0 or 1 */
779                 rmc_drop_action(cl);
780                 return (-1);
781         }
782         return (0);
783 }
784
785 /*
786  * void
787  * rmc_tl_satisfied(struct rm_ifdat *ifd, struct timeval *now) - Check all
788  *      classes to see if there are satified.
789  */
790
791 static void
792 rmc_tl_satisfied(struct rm_ifdat *ifd, struct timeval *now)
793 {
794         int i;
795         rm_class_t *p, *bp;
796
797         for (i = RM_MAXPRIO - 1; i >= 0; i--) {
798                 if ((bp = ifd->active_[i]) != NULL) {
799                         p = bp;
800                         do {
801                                 if (!rmc_satisfied(p, now)) {
802                                         ifd->cutoff_ = p->depth_;
803                                         return;
804                                 }
805                                 p = p->peer_;
806                         } while (p != bp);
807                 }
808         }
809
810         reset_cutoff(ifd);
811 }
812
813 /*
814  * rmc_satisfied - Return 1 of the class is satisfied.  O, otherwise.
815  */
816
817 static int
818 rmc_satisfied(struct rm_class *cl, struct timeval *now)
819 {
820         rm_class_t *p;
821
822         if (cl == NULL)
823                 return (1);
824         if (TV_LT(now, &cl->undertime_))
825                 return (1);
826         if (cl->depth_ == 0) {
827                 if (!cl->sleeping_ && (qlen(cl->q_) > cl->qthresh_))
828                         return (0);
829                 else
830                         return (1);
831         }
832         if (cl->children_ != NULL) {
833                 p = cl->children_;
834                 while (p != NULL) {
835                         if (!rmc_satisfied(p, now))
836                                 return (0);
837                         p = p->next_;
838                 }
839         }
840
841         return (1);
842 }
843
844 /*
845  * Return 1 if class 'cl' is under limit or can borrow from a parent,
846  * 0 if overlimit.  As a side-effect, this routine will invoke the
847  * class overlimit action if the class if overlimit.
848  */
849
850 static int
851 rmc_under_limit(struct rm_class *cl, struct timeval *now)
852 {
853         rm_class_t *p = cl;
854         rm_class_t *top;
855         struct rm_ifdat *ifd = cl->ifdat_;
856
857         ifd->borrowed_[ifd->qi_] = NULL;
858         /*
859          * If cl is the root class, then always return that it is
860          * underlimit.  Otherwise, check to see if the class is underlimit.
861          */
862         if (cl->parent_ == NULL)
863                 return (1);
864
865         if (cl->sleeping_) {
866                 if (TV_LT(now, &cl->undertime_))
867                         return (0);
868
869                 callout_stop(&cl->callout_);
870                 cl->sleeping_ = 0;
871                 cl->undertime_.tv_sec = 0;
872                 return (1);
873         }
874
875         top = NULL;
876         while (cl->undertime_.tv_sec && TV_LT(now, &cl->undertime_)) {
877                 if (((cl = cl->borrow_) == NULL) ||
878                     (cl->depth_ > ifd->cutoff_)) {
879 #ifdef ADJUST_CUTOFF
880                         if (cl != NULL)
881                                 /* cutoff is taking effect, just
882                                    return false without calling
883                                    the delay action. */
884                                 return (0);
885 #endif
886 #ifdef BORROW_OFFTIME
887                         /*
888                          * check if the class can borrow offtime too.
889                          * borrow offtime from the top of the borrow
890                          * chain if the top class is not overloaded.
891                          */
892                         if (cl != NULL) {
893                                 /* cutoff is taking effect, use this class as top. */
894                                 top = cl;
895                                 CBQTRACE(rmc_under_limit, 'ffou', ifd->cutoff_);
896                         }
897                         if (top != NULL && top->avgidle_ == top->minidle_)
898                                 top = NULL;
899                         p->overtime_ = *now;
900                         (p->overlimit)(p, top);
901 #else
902                         p->overtime_ = *now;
903                         (p->overlimit)(p, NULL);
904 #endif
905                         return (0);
906                 }
907                 top = cl;
908         }
909
910         if (cl != p)
911                 ifd->borrowed_[ifd->qi_] = cl;
912         return (1);
913 }
914
915 /*
916  * _rmc_wrr_dequeue_next() - This is scheduler for WRR as opposed to
917  *      Packet-by-packet round robin.
918  *
919  * The heart of the weighted round-robin scheduler, which decides which
920  * class next gets to send a packet.  Highest priority first, then
921  * weighted round-robin within priorites.
922  *
923  * Each able-to-send class gets to send until its byte allocation is
924  * exhausted.  Thus, the active pointer is only changed after a class has
925  * exhausted its allocation.
926  *
927  * If the scheduler finds no class that is underlimit or able to borrow,
928  * then the first class found that had a nonzero queue and is allowed to
929  * borrow gets to send.
930  */
931
932 static struct mbuf *
933 _rmc_wrr_dequeue_next(struct rm_ifdat *ifd, int op)
934 {
935         struct rm_class *cl = NULL, *first = NULL;
936         u_int deficit;
937         int cpri;
938         struct mbuf *m;
939         struct timeval now;
940
941         RM_GETTIME(now);
942
943         /*
944          * if the driver polls the top of the queue and then removes
945          * the polled packet, we must return the same packet.
946          */
947         if (op == ALTDQ_REMOVE && ifd->pollcache_) {
948                 cl = ifd->pollcache_;
949                 cpri = cl->pri_;
950                 if (ifd->efficient_) {
951                         /* check if this class is overlimit */
952                         if (cl->undertime_.tv_sec != 0 &&
953                             rmc_under_limit(cl, &now) == 0)
954                                 first = cl;
955                 }
956                 ifd->pollcache_ = NULL;
957                 goto _wrr_out;
958         }
959         else {
960                 /* mode == ALTDQ_POLL || pollcache == NULL */
961                 ifd->pollcache_ = NULL;
962                 ifd->borrowed_[ifd->qi_] = NULL;
963         }
964 #ifdef ADJUST_CUTOFF
965  _again:
966 #endif
967         for (cpri = RM_MAXPRIO - 1; cpri >= 0; cpri--) {
968                 if (ifd->na_[cpri] == 0)
969                         continue;
970                 deficit = 0;
971                 /*
972                  * Loop through twice for a priority level, if some class
973                  * was unable to send a packet the first round because
974                  * of the weighted round-robin mechanism.
975                  * During the second loop at this level, deficit==2.
976                  * (This second loop is not needed if for every class,
977                  * "M[cl->pri_])" times "cl->allotment" is greater than
978                  * the byte size for the largest packet in the class.)
979                  */
980  _wrr_loop:
981                 cl = ifd->active_[cpri];
982                 KKASSERT(cl != NULL);
983                 do {
984                         if ((deficit < 2) && (cl->bytes_alloc_ <= 0))
985                                 cl->bytes_alloc_ += cl->w_allotment_;
986                         if (!qempty(cl->q_)) {
987                                 if ((cl->undertime_.tv_sec == 0) ||
988                                     rmc_under_limit(cl, &now)) {
989                                         if (cl->bytes_alloc_ > 0 || deficit > 1)
990                                                 goto _wrr_out;
991
992                                         /* underlimit but no alloc */
993                                         deficit = 1;
994 #if 1
995                                         ifd->borrowed_[ifd->qi_] = NULL;
996 #endif
997                                 }
998                                 else if (first == NULL && cl->borrow_ != NULL)
999                                         first = cl; /* borrowing candidate */
1000                         }
1001
1002                         cl->bytes_alloc_ = 0;
1003                         cl = cl->peer_;
1004                 } while (cl != ifd->active_[cpri]);
1005
1006                 if (deficit == 1) {
1007                         /* first loop found an underlimit class with deficit */
1008                         /* Loop on same priority level, with new deficit.  */
1009                         deficit = 2;
1010                         goto _wrr_loop;
1011                 }
1012         }
1013
1014 #ifdef ADJUST_CUTOFF
1015         /*
1016          * no underlimit class found.  if cutoff is taking effect,
1017          * increase cutoff and try again.
1018          */
1019         if (first != NULL && ifd->cutoff_ < ifd->root_->depth_) {
1020                 ifd->cutoff_++;
1021                 CBQTRACE(_rmc_wrr_dequeue_next, 'ojda', ifd->cutoff_);
1022                 goto _again;
1023         }
1024 #endif /* ADJUST_CUTOFF */
1025         /*
1026          * If LINK_EFFICIENCY is turned on, then the first overlimit
1027          * class we encounter will send a packet if all the classes
1028          * of the link-sharing structure are overlimit.
1029          */
1030         reset_cutoff(ifd);
1031         CBQTRACE(_rmc_wrr_dequeue_next, 'otsr', ifd->cutoff_);
1032
1033         if (!ifd->efficient_ || first == NULL)
1034                 return (NULL);
1035
1036         cl = first;
1037         cpri = cl->pri_;
1038 #if 0   /* too time-consuming for nothing */
1039         if (cl->sleeping_)
1040                 callout_stop(&cl->callout_);
1041         cl->sleeping_ = 0;
1042         cl->undertime_.tv_sec = 0;
1043 #endif
1044         ifd->borrowed_[ifd->qi_] = cl->borrow_;
1045         ifd->cutoff_ = cl->borrow_->depth_;
1046
1047         /*
1048          * Deque the packet and do the book keeping...
1049          */
1050  _wrr_out:
1051         if (op == ALTDQ_REMOVE) {
1052                 m = _rmc_getq(cl);
1053                 if (m == NULL)
1054                         panic("_rmc_wrr_dequeue_next");
1055                 if (qempty(cl->q_))
1056                         ifd->na_[cpri]--;
1057
1058                 /*
1059                  * Update class statistics and link data.
1060                  */
1061                 if (cl->bytes_alloc_ > 0)
1062                         cl->bytes_alloc_ -= m_pktlen(m);
1063
1064                 if ((cl->bytes_alloc_ <= 0) || first == cl)
1065                         ifd->active_[cl->pri_] = cl->peer_;
1066                 else
1067                         ifd->active_[cl->pri_] = cl;
1068
1069                 ifd->class_[ifd->qi_] = cl;
1070                 ifd->curlen_[ifd->qi_] = m_pktlen(m);
1071                 ifd->now_[ifd->qi_] = now;
1072                 ifd->qi_ = (ifd->qi_ + 1) % ifd->maxqueued_;
1073                 ifd->queued_++;
1074         } else {
1075                 /* mode == ALTDQ_PPOLL */
1076                 m = _rmc_pollq(cl);
1077                 ifd->pollcache_ = cl;
1078         }
1079         return (m);
1080 }
1081
1082 /*
1083  * Dequeue & return next packet from the highest priority class that
1084  * has a packet to send & has enough allocation to send it.  This
1085  * routine is called by a driver whenever it needs a new packet to
1086  * output.
1087  */
1088 static struct mbuf *
1089 _rmc_prr_dequeue_next(struct rm_ifdat *ifd, int op)
1090 {
1091         struct mbuf *m;
1092         int cpri;
1093         struct rm_class *cl, *first = NULL;
1094         struct timeval now;
1095
1096         RM_GETTIME(now);
1097
1098         /*
1099          * if the driver polls the top of the queue and then removes
1100          * the polled packet, we must return the same packet.
1101          */
1102         if (op == ALTDQ_REMOVE && ifd->pollcache_) {
1103                 cl = ifd->pollcache_;
1104                 cpri = cl->pri_;
1105                 ifd->pollcache_ = NULL;
1106                 goto _prr_out;
1107         } else {
1108                 /* mode == ALTDQ_POLL || pollcache == NULL */
1109                 ifd->pollcache_ = NULL;
1110                 ifd->borrowed_[ifd->qi_] = NULL;
1111         }
1112 #ifdef ADJUST_CUTOFF
1113  _again:
1114 #endif
1115         for (cpri = RM_MAXPRIO - 1; cpri >= 0; cpri--) {
1116                 if (ifd->na_[cpri] == 0)
1117                         continue;
1118                 cl = ifd->active_[cpri];
1119                 KKASSERT(cl != NULL);
1120                 do {
1121                         if (!qempty(cl->q_)) {
1122                                 if ((cl->undertime_.tv_sec == 0) ||
1123                                     rmc_under_limit(cl, &now))
1124                                         goto _prr_out;
1125                                 if (first == NULL && cl->borrow_ != NULL)
1126                                         first = cl;
1127                         }
1128                         cl = cl->peer_;
1129                 } while (cl != ifd->active_[cpri]);
1130         }
1131
1132 #ifdef ADJUST_CUTOFF
1133         /*
1134          * no underlimit class found.  if cutoff is taking effect, increase
1135          * cutoff and try again.
1136          */
1137         if (first != NULL && ifd->cutoff_ < ifd->root_->depth_) {
1138                 ifd->cutoff_++;
1139                 goto _again;
1140         }
1141 #endif /* ADJUST_CUTOFF */
1142         /*
1143          * If LINK_EFFICIENCY is turned on, then the first overlimit
1144          * class we encounter will send a packet if all the classes
1145          * of the link-sharing structure are overlimit.
1146          */
1147         reset_cutoff(ifd);
1148         if (!ifd->efficient_ || first == NULL)
1149                 return (NULL);
1150
1151         cl = first;
1152         cpri = cl->pri_;
1153 #if 0   /* too time-consuming for nothing */
1154         if (cl->sleeping_)
1155                 callout_stop(&cl->callout_);
1156         cl->sleeping_ = 0;
1157         cl->undertime_.tv_sec = 0;
1158 #endif
1159         ifd->borrowed_[ifd->qi_] = cl->borrow_;
1160         ifd->cutoff_ = cl->borrow_->depth_;
1161
1162         /*
1163          * Deque the packet and do the book keeping...
1164          */
1165  _prr_out:
1166         if (op == ALTDQ_REMOVE) {
1167                 m = _rmc_getq(cl);
1168                 if (m == NULL)
1169                         panic("_rmc_prr_dequeue_next");
1170                 if (qempty(cl->q_))
1171                         ifd->na_[cpri]--;
1172
1173                 ifd->active_[cpri] = cl->peer_;
1174
1175                 ifd->class_[ifd->qi_] = cl;
1176                 ifd->curlen_[ifd->qi_] = m_pktlen(m);
1177                 ifd->now_[ifd->qi_] = now;
1178                 ifd->qi_ = (ifd->qi_ + 1) % ifd->maxqueued_;
1179                 ifd->queued_++;
1180         } else {
1181                 /* mode == ALTDQ_POLL */
1182                 m = _rmc_pollq(cl);
1183                 ifd->pollcache_ = cl;
1184         }
1185         return (m);
1186 }
1187
1188 /*
1189  * struct mbuf *
1190  * rmc_dequeue_next(struct rm_ifdat *ifd, struct timeval *now) - this function
1191  *      is invoked by the packet driver to get the next packet to be
1192  *      dequeued and output on the link.  If WRR is enabled, then the
1193  *      WRR dequeue next routine will determine the next packet to sent.
1194  *      Otherwise, packet-by-packet round robin is invoked.
1195  *
1196  *      Returns:        NULL, if a packet is not available or if all
1197  *                      classes are overlimit.
1198  *
1199  *                      Otherwise, Pointer to the next packet.
1200  */
1201
1202 struct mbuf *
1203 rmc_dequeue_next(struct rm_ifdat *ifd, int mode)
1204 {
1205         if (ifd->queued_ >= ifd->maxqueued_)
1206                 return (NULL);
1207         else if (ifd->wrr_)
1208                 return (_rmc_wrr_dequeue_next(ifd, mode));
1209         else
1210                 return (_rmc_prr_dequeue_next(ifd, mode));
1211 }
1212
1213 /*
1214  * Update the utilization estimate for the packet that just completed.
1215  * The packet's class & the parent(s) of that class all get their
1216  * estimators updated.  This routine is called by the driver's output-
1217  * packet-completion interrupt service routine.
1218  */
1219
1220 /*
1221  * a macro to approximate "divide by 1000" that gives 0.000999,
1222  * if a value has enough effective digits.
1223  * (on pentium, mul takes 9 cycles but div takes 46!)
1224  */
1225 #define NSEC_TO_USEC(t) (((t) >> 10) + ((t) >> 16) + ((t) >> 17))
1226 void
1227 rmc_update_class_util(struct rm_ifdat *ifd)
1228 {
1229         int idle, avgidle, pktlen;
1230         int pkt_time, tidle;
1231         rm_class_t *cl, *borrowed;
1232         rm_class_t *borrows;
1233         struct timeval *nowp;
1234
1235         /*
1236          * Get the most recent completed class.
1237          */
1238         if ((cl = ifd->class_[ifd->qo_]) == NULL)
1239                 return;
1240
1241         pktlen = ifd->curlen_[ifd->qo_];
1242         borrowed = ifd->borrowed_[ifd->qo_];
1243         borrows = borrowed;
1244
1245         PKTCNTR_ADD(&cl->stats_.xmit_cnt, pktlen);
1246
1247         /*
1248          * Run estimator on class and its ancestors.
1249          */
1250         /*
1251          * rm_update_class_util is designed to be called when the
1252          * transfer is completed from a xmit complete interrupt,
1253          * but most drivers don't implement an upcall for that.
1254          * so, just use estimated completion time.
1255          * as a result, ifd->qi_ and ifd->qo_ are always synced.
1256          */
1257         nowp = &ifd->now_[ifd->qo_];
1258         /* get pkt_time (for link) in usec */
1259 #if 1  /* use approximation */
1260         pkt_time = ifd->curlen_[ifd->qo_] * ifd->ns_per_byte_;
1261         pkt_time = NSEC_TO_USEC(pkt_time);
1262 #else
1263         pkt_time = ifd->curlen_[ifd->qo_] * ifd->ns_per_byte_ / 1000;
1264 #endif
1265 #if 1 /* ALTQ4PPP */
1266         if (TV_LT(nowp, &ifd->ifnow_)) {
1267                 int iftime;
1268
1269                 /*
1270                  * make sure the estimated completion time does not go
1271                  * too far.  it can happen when the link layer supports
1272                  * data compression or the interface speed is set to
1273                  * a much lower value.
1274                  */
1275                 TV_DELTA(&ifd->ifnow_, nowp, iftime);
1276                 if (iftime+pkt_time < ifd->maxiftime_) {
1277                         TV_ADD_DELTA(&ifd->ifnow_, pkt_time, &ifd->ifnow_);
1278                 } else {
1279                         TV_ADD_DELTA(nowp, ifd->maxiftime_, &ifd->ifnow_);
1280                 }
1281         } else {
1282                 TV_ADD_DELTA(nowp, pkt_time, &ifd->ifnow_);
1283         }
1284 #else
1285         if (TV_LT(nowp, &ifd->ifnow_)) {
1286                 TV_ADD_DELTA(&ifd->ifnow_, pkt_time, &ifd->ifnow_);
1287         } else {
1288                 TV_ADD_DELTA(nowp, pkt_time, &ifd->ifnow_);
1289         }
1290 #endif
1291
1292         while (cl != NULL) {
1293                 TV_DELTA(&ifd->ifnow_, &cl->last_, idle);
1294                 if (idle >= 2000000)
1295                         /*
1296                          * this class is idle enough, reset avgidle.
1297                          * (TV_DELTA returns 2000000 us when delta is large.)
1298                          */
1299                         cl->avgidle_ = cl->maxidle_;
1300
1301                 /* get pkt_time (for class) in usec */
1302 #if 1  /* use approximation */
1303                 pkt_time = pktlen * cl->ns_per_byte_;
1304                 pkt_time = NSEC_TO_USEC(pkt_time);
1305 #else
1306                 pkt_time = pktlen * cl->ns_per_byte_ / 1000;
1307 #endif
1308                 idle -= pkt_time;
1309
1310                 avgidle = cl->avgidle_;
1311                 avgidle += idle - (avgidle >> RM_FILTER_GAIN);
1312                 cl->avgidle_ = avgidle;
1313
1314                 /* Are we overlimit ? */
1315                 if (avgidle <= 0) {
1316                         CBQTRACE(rmc_update_class_util, 'milo', cl->stats_.handle);
1317 #if 1 /* ALTQ */
1318                         /*
1319                          * need some lower bound for avgidle, otherwise
1320                          * a borrowing class gets unbounded penalty.
1321                          */
1322                         if (avgidle < cl->minidle_)
1323                                 avgidle = cl->avgidle_ = cl->minidle_;
1324 #endif
1325                         /* set next idle to make avgidle 0 */
1326                         tidle = pkt_time +
1327                                 (((1 - RM_POWER) * avgidle) >> RM_FILTER_GAIN);
1328                         TV_ADD_DELTA(nowp, tidle, &cl->undertime_);
1329                         ++cl->stats_.over;
1330                 } else {
1331                         cl->avgidle_ =
1332                             (avgidle > cl->maxidle_) ? cl->maxidle_ : avgidle;
1333                         cl->undertime_.tv_sec = 0;
1334                         if (cl->sleeping_) {
1335                                 callout_stop(&cl->callout_);
1336                                 cl->sleeping_ = 0;
1337                         }
1338                 }
1339
1340                 if (borrows != NULL) {
1341                         if (borrows != cl)
1342                                 ++cl->stats_.borrows;
1343                         else
1344                                 borrows = NULL;
1345                 }
1346                 cl->last_ = ifd->ifnow_;
1347                 cl->last_pkttime_ = pkt_time;
1348
1349 #if 1
1350                 if (cl->parent_ == NULL) {
1351                         /* take stats of root class */
1352                         PKTCNTR_ADD(&cl->stats_.xmit_cnt, pktlen);
1353                 }
1354 #endif
1355
1356                 cl = cl->parent_;
1357         }
1358
1359         /*
1360          * Check to see if cutoff needs to set to a new level.
1361          */
1362         cl = ifd->class_[ifd->qo_];
1363         if (borrowed && (ifd->cutoff_ >= borrowed->depth_)) {
1364 #if 1 /* ALTQ */
1365                 if ((qlen(cl->q_) <= 0) || TV_LT(nowp, &borrowed->undertime_)) {
1366                         rmc_tl_satisfied(ifd, nowp);
1367                         CBQTRACE(rmc_update_class_util, 'broe', ifd->cutoff_);
1368                 } else {
1369                         ifd->cutoff_ = borrowed->depth_;
1370                         CBQTRACE(rmc_update_class_util, 'ffob', borrowed->depth_);
1371                 }
1372 #else /* !ALTQ */
1373                 if ((qlen(cl->q_) <= 1) || TV_LT(&now, &borrowed->undertime_)) {
1374                         reset_cutoff(ifd);
1375 #ifdef notdef
1376                         rmc_tl_satisfied(ifd, &now);
1377 #endif
1378                         CBQTRACE(rmc_update_class_util, 'broe', ifd->cutoff_);
1379                 } else {
1380                         ifd->cutoff_ = borrowed->depth_;
1381                         CBQTRACE(rmc_update_class_util, 'ffob', borrowed->depth_);
1382                 }
1383 #endif /* !ALTQ */
1384         }
1385
1386         /*
1387          * Release class slot
1388          */
1389         ifd->borrowed_[ifd->qo_] = NULL;
1390         ifd->class_[ifd->qo_] = NULL;
1391         ifd->qo_ = (ifd->qo_ + 1) % ifd->maxqueued_;
1392         ifd->queued_--;
1393 }
1394
1395 /*
1396  * void
1397  * rmc_drop_action(struct rm_class *cl) - Generic (not protocol-specific)
1398  *      over-limit action routines.  These get invoked by rmc_under_limit()
1399  *      if a class with packets to send if over its bandwidth limit & can't
1400  *      borrow from a parent class.
1401  *
1402  *      Returns: NONE
1403  */
1404
1405 static void
1406 rmc_drop_action(struct rm_class *cl)
1407 {
1408         struct rm_ifdat *ifd = cl->ifdat_;
1409
1410         KKASSERT(qlen(cl->q_) > 0);
1411         _rmc_dropq(cl);
1412         if (qempty(cl->q_))
1413                 ifd->na_[cl->pri_]--;
1414 }
1415
1416 void rmc_dropall(struct rm_class *cl)
1417 {
1418         struct rm_ifdat *ifd = cl->ifdat_;
1419
1420         if (!qempty(cl->q_)) {
1421                 _flushq(cl->q_);
1422
1423                 ifd->na_[cl->pri_]--;
1424         }
1425 }
1426
1427 /*
1428  * void
1429  * rmc_delay_action(struct rm_class *cl) - This function is the generic CBQ
1430  *      delay action routine.  It is invoked via rmc_under_limit when the
1431  *      packet is discoverd to be overlimit.
1432  *
1433  *      If the delay action is result of borrow class being overlimit, then
1434  *      delay for the offtime of the borrowing class that is overlimit.
1435  *
1436  *      Returns: NONE
1437  */
1438
1439 void
1440 rmc_delay_action(struct rm_class *cl, struct rm_class *borrow)
1441 {
1442         int delay, t, extradelay;
1443
1444         cl->stats_.overactions++;
1445         TV_DELTA(&cl->undertime_, &cl->overtime_, delay);
1446 #ifndef BORROW_OFFTIME
1447         delay += cl->offtime_;
1448 #endif
1449
1450         if (!cl->sleeping_) {
1451                 CBQTRACE(rmc_delay_action, 'yled', cl->stats_.handle);
1452 #ifdef BORROW_OFFTIME
1453                 if (borrow != NULL)
1454                         extradelay = borrow->offtime_;
1455                 else
1456 #endif
1457                         extradelay = cl->offtime_;
1458
1459 #ifdef ALTQ
1460                 /*
1461                  * XXX recalculate suspend time:
1462                  * current undertime is (tidle + pkt_time) calculated
1463                  * from the last transmission.
1464                  *      tidle: time required to bring avgidle back to 0
1465                  *      pkt_time: target waiting time for this class
1466                  * we need to replace pkt_time by offtime
1467                  */
1468                 extradelay -= cl->last_pkttime_;
1469 #endif
1470                 if (extradelay > 0) {
1471                         TV_ADD_DELTA(&cl->undertime_, extradelay, &cl->undertime_);
1472                         delay += extradelay;
1473                 }
1474
1475                 cl->sleeping_ = 1;
1476                 cl->stats_.delays++;
1477
1478                 /*
1479                  * Since packets are phased randomly with respect to the
1480                  * clock, 1 tick (the next clock tick) can be an arbitrarily
1481                  * short time so we have to wait for at least two ticks.
1482                  * NOTE:  If there's no other traffic, we need the timer as
1483                  * a 'backstop' to restart this class.
1484                  */
1485                 if (delay > tick * 2)
1486                         t = (delay + tick - 1) / tick;
1487                 else
1488                         t = 2;
1489                 callout_reset(&cl->callout_, t, rmc_restart, cl);
1490         }
1491 }
1492
1493 /*
1494  * void
1495  * rmc_restart() - is just a helper routine for rmc_delay_action -- it is
1496  *      called by the system timer code & is responsible checking if the
1497  *      class is still sleeping (it might have been restarted as a side
1498  *      effect of the queue scan on a packet arrival) and, if so, restarting
1499  *      output for the class.  Inspecting the class state & restarting output
1500  *      require locking the class structure.  In general the driver is
1501  *      responsible for locking but this is the only routine that is not
1502  *      called directly or indirectly from the interface driver so it has
1503  *      know about system locking conventions.  Under bsd, locking is done
1504  *      by raising IPL to splimp so that's what's implemented here.  On a
1505  *      different system this would probably need to be changed.
1506  *
1507  *      Returns:        NONE
1508  */
1509
1510 static void
1511 rmc_restart(void *arg)
1512 {
1513         struct rm_class *cl = arg;
1514         struct rm_ifdat *ifd = cl->ifdat_;
1515
1516         crit_enter();
1517         if (cl->sleeping_) {
1518                 cl->sleeping_ = 0;
1519                 cl->undertime_.tv_sec = 0;
1520
1521                 if (ifd->queued_ < ifd->maxqueued_ && ifd->restart != NULL) {
1522                         CBQTRACE(rmc_restart, 'trts', cl->stats_.handle);
1523                         (ifd->restart)(ifd->ifq_);
1524                 }
1525         }
1526         crit_exit();
1527 }
1528
1529 /*
1530  * void
1531  * rmc_root_overlimit(struct rm_class *cl) - This the generic overlimit
1532  *      handling routine for the root class of the link sharing structure.
1533  *
1534  *      Returns: NONE
1535  */
1536
1537 static void
1538 rmc_root_overlimit(struct rm_class *cl, struct rm_class *borrow)
1539 {
1540         panic("rmc_root_overlimit");
1541 }
1542
1543 /*
1544  * Packet Queue handling routines.  Eventually, this is to localize the
1545  *      effects on the code whether queues are red queues or droptail
1546  *      queues.
1547  */
1548
1549 static int
1550 _rmc_addq(rm_class_t *cl, struct mbuf *m)
1551 {
1552 #ifdef ALTQ_RIO
1553         if (q_is_rio(cl->q_))
1554                 return rio_addq((rio_t *)cl->red_, cl->q_, m, cl->pktattr_);
1555 #endif
1556 #ifdef ALTQ_RED
1557         if (q_is_red(cl->q_))
1558                 return red_addq(cl->red_, cl->q_, m, cl->pktattr_);
1559 #endif /* ALTQ_RED */
1560
1561         if (cl->flags_ & RMCF_CLEARDSCP)
1562                 write_dsfield(m, cl->pktattr_, 0);
1563
1564         _addq(cl->q_, m);
1565         return (0);
1566 }
1567
1568 /* note: _rmc_dropq is not called for red */
1569 static void
1570 _rmc_dropq(rm_class_t *cl)
1571 {
1572         struct mbuf *m;
1573
1574         if ((m = _getq(cl->q_)) != NULL)
1575                 m_freem(m);
1576 }
1577
1578 static struct mbuf *
1579 _rmc_getq(rm_class_t *cl)
1580 {
1581 #ifdef ALTQ_RIO
1582         if (q_is_rio(cl->q_))
1583                 return rio_getq((rio_t *)cl->red_, cl->q_);
1584 #endif
1585 #ifdef ALTQ_RED
1586         if (q_is_red(cl->q_))
1587                 return red_getq(cl->red_, cl->q_);
1588 #endif
1589         return _getq(cl->q_);
1590 }
1591
1592 static struct mbuf *
1593 _rmc_pollq(rm_class_t *cl)
1594 {
1595         return qhead(cl->q_);
1596 }
1597
1598 #ifdef CBQ_TRACE
1599 /*
1600  * DDB hook to trace cbq events:
1601  *  the last 1024 events are held in a circular buffer.
1602  *  use "call cbqtrace_dump(N)" to display 20 events from Nth event.
1603  */
1604 void            cbqtrace_dump(int);
1605 static char     *rmc_funcname(void *);
1606
1607 static struct rmc_funcs {
1608         void    *func;
1609         char    *name;
1610 } rmc_funcs[] = {
1611         rmc_init,               "rmc_init",
1612         rmc_queue_packet,       "rmc_queue_packet",
1613         rmc_under_limit,        "rmc_under_limit",
1614         rmc_update_class_util,  "rmc_update_class_util",
1615         rmc_delay_action,       "rmc_delay_action",
1616         rmc_restart,            "rmc_restart",
1617         _rmc_wrr_dequeue_next,  "_rmc_wrr_dequeue_next",
1618         NULL,                   NULL
1619 };
1620
1621 static char *rmc_funcname(void *func)
1622 {
1623         struct rmc_funcs *fp;
1624
1625         for (fp = rmc_funcs; fp->func != NULL; fp++) {
1626                 if (fp->func == func)
1627                         return (fp->name);
1628         }
1629
1630         return ("unknown");
1631 }
1632
1633 void
1634 cbqtrace_dump(int counter)
1635 {
1636         int i, *p;
1637         char *cp;
1638
1639         counter = counter % NCBQTRACE;
1640         p = (int *)&cbqtrace_buffer[counter];
1641
1642         for (i=0; i<20; i++) {
1643                 printf("[0x%x] ", *p++);
1644                 printf("%s: ", rmc_funcname((void *)*p++));
1645                 cp = (char *)p++;
1646                 printf("%c%c%c%c: ", cp[0], cp[1], cp[2], cp[3]);
1647                 printf("%d\n",*p++);
1648
1649                 if (p >= (int *)&cbqtrace_buffer[NCBQTRACE])
1650                         p = (int *)cbqtrace_buffer;
1651         }
1652 }
1653 #endif /* CBQ_TRACE */
1654 #endif /* ALTQ_CBQ */