2 /* $KAME: altq_rmclass.c,v 1.18 2003/11/06 06:32:53 kjc Exp $ */
5 * Copyright (c) 1991-1997 Regents of the University of California.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
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
40 #ident "@(#)rm_class.c 1.48 97/12/05 SMI"
42 #if defined(__FreeBSD__) || defined(__NetBSD__)
44 #if (__FreeBSD__ != 2)
47 #include "opt_inet6.h"
50 #endif /* __FreeBSD__ || __NetBSD__ */
51 #ifdef ALTQ_CBQ /* cbq is enabled by ALTQ_CBQ option in opt_altq.h */
53 #include <sys/param.h>
54 #include <sys/malloc.h>
56 #include <sys/socket.h>
57 #include <sys/systm.h>
58 #include <sys/errno.h>
61 #include <sys/kernel.h>
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
71 #include <altq/altq.h>
72 #include <altq/altq_rmclass.h>
73 #include <altq/altq_rmclass_debug.h>
74 #include <altq/altq_red.h>
75 #include <altq/altq_rio.h>
81 #define reset_cutoff(ifd) { ifd->cutoff_ = RM_MAXDEPTH; }
87 static int rmc_satisfied(struct rm_class *, struct timeval *);
88 static void rmc_wrr_set_weights(struct rm_ifdat *);
89 static void rmc_depth_compute(struct rm_class *);
90 static void rmc_depth_recompute(rm_class_t *);
92 static mbuf_t *_rmc_wrr_dequeue_next(struct rm_ifdat *, int);
93 static mbuf_t *_rmc_prr_dequeue_next(struct rm_ifdat *, int);
95 static int _rmc_addq(rm_class_t *, mbuf_t *);
96 static void _rmc_dropq(rm_class_t *);
97 static mbuf_t *_rmc_getq(rm_class_t *);
98 static mbuf_t *_rmc_pollq(rm_class_t *);
100 static int rmc_under_limit(struct rm_class *, struct timeval *);
101 static void rmc_tl_satisfied(struct rm_ifdat *, struct timeval *);
102 static void rmc_drop_action(struct rm_class *);
103 static void rmc_restart(struct rm_class *);
104 static void rmc_root_overlimit(struct rm_class *, struct rm_class *);
106 #define BORROW_OFFTIME
108 * BORROW_OFFTIME (experimental):
109 * borrow the offtime of the class borrowing from.
110 * the reason is that when its own offtime is set, the class is unable
111 * to borrow much, especially when cutoff is taking effect.
112 * but when the borrowed class is overloaded (advidle is close to minidle),
113 * use the borrowing class's offtime to avoid overload.
115 #define ADJUST_CUTOFF
117 * ADJUST_CUTOFF (experimental):
118 * if no underlimit class is found due to cutoff, increase cutoff and
119 * retry the scheduling loop.
120 * also, don't invoke delay_actions while cutoff is taking effect,
121 * since a sleeping class won't have a chance to be scheduled in the
124 * now heuristics for setting the top-level variable (cutoff_) becomes:
125 * 1. if a packet arrives for a not-overlimit class, set cutoff
126 * to the depth of the class.
127 * 2. if cutoff is i, and a packet arrives for an overlimit class
128 * with an underlimit ancestor at a lower level than i (say j),
129 * then set cutoff to j.
130 * 3. at scheduling a packet, if there is no underlimit class
131 * due to the current cutoff level, increase cutoff by 1 and
132 * then try to schedule again.
137 * rmc_newclass(...) - Create a new resource management class at priority
138 * 'pri' on the interface given by 'ifd'.
140 * nsecPerByte is the data rate of the interface in nanoseconds/byte.
141 * E.g., 800 for a 10Mb/s ethernet. If the class gets less
142 * than 100% of the bandwidth, this number should be the
143 * 'effective' rate for the class. Let f be the
144 * bandwidth fraction allocated to this class, and let
145 * nsPerByte be the data rate of the output link in
146 * nanoseconds/byte. Then nsecPerByte is set to
147 * nsPerByte / f. E.g., 1600 (= 800 / .5)
148 * for a class that gets 50% of an ethernet's bandwidth.
150 * action the routine to call when the class is over limit.
152 * maxq max allowable queue size for class (in packets).
154 * parent parent class pointer.
156 * borrow class to borrow from (should be either 'parent' or null).
158 * maxidle max value allowed for class 'idle' time estimate (this
159 * parameter determines how large an initial burst of packets
160 * can be before overlimit action is invoked.
162 * offtime how long 'delay' action will delay when class goes over
163 * limit (this parameter determines the steady-state burst
164 * size when a class is running over its limit).
166 * Maxidle and offtime have to be computed from the following: If the
167 * average packet size is s, the bandwidth fraction allocated to this
168 * class is f, we want to allow b packet bursts, and the gain of the
169 * averaging filter is g (= 1 - 2^(-RM_FILTER_GAIN)), then:
171 * ptime = s * nsPerByte * (1 - f) / f
172 * maxidle = ptime * (1 - g^b) / g^b
173 * minidle = -ptime * (1 / (f - 1))
174 * offtime = ptime * (1 + 1/(1 - g) * (1 - g^(b - 1)) / g^(b - 1)
176 * Operationally, it's convenient to specify maxidle & offtime in units
177 * independent of the link bandwidth so the maxidle & offtime passed to
178 * this routine are the above values multiplied by 8*f/(1000*nsPerByte).
179 * (The constant factor is a scale factor needed to make the parameters
180 * integers. This scaling also means that the 'unscaled' values of
181 * maxidle*nsecPerByte/8 and offtime*nsecPerByte/8 will be in microseconds,
182 * not nanoseconds.) Also note that the 'idle' filter computation keeps
183 * an estimate scaled upward by 2^RM_FILTER_GAIN so the passed value of
184 * maxidle also must be scaled upward by this value. Thus, the passed
185 * values for maxidle and offtime can be computed as follows:
187 * maxidle = maxidle * 2^RM_FILTER_GAIN * 8 / (1000 * nsecPerByte)
188 * offtime = offtime * 8 / (1000 * nsecPerByte)
190 * When USE_HRTIME is employed, then maxidle and offtime become:
191 * maxidle = maxilde * (8.0 / nsecPerByte);
192 * offtime = offtime * (8.0 / nsecPerByte);
195 rmc_newclass(int pri, struct rm_ifdat *ifd, u_int nsecPerByte,
196 void (*action)(rm_class_t *, rm_class_t *), int maxq,
197 struct rm_class *parent, struct rm_class *borrow, u_int maxidle,
198 int minidle, u_int offtime, int pktsize, int flags)
201 struct rm_class *peer;
204 if (pri >= RM_MAXPRIO)
207 if (flags & RMCF_RED) {
209 printf("rmc_newclass: RED not configured for CBQ!\n");
215 if (flags & RMCF_RIO) {
217 printf("rmc_newclass: RIO not configured for CBQ!\n");
223 cl = malloc(sizeof(struct rm_class),
227 bzero(cl, sizeof(struct rm_class));
228 CALLOUT_INIT(&cl->callout_);
229 cl->q_ = malloc(sizeof(class_queue_t),
231 if (cl->q_ == NULL) {
235 bzero(cl->q_, sizeof(class_queue_t));
238 * Class initialization.
240 cl->children_ = NULL;
241 cl->parent_ = parent;
242 cl->borrow_ = borrow;
246 cl->allotment_ = RM_NS_PER_SEC / nsecPerByte; /* Bytes per sec */
249 cl->ns_per_byte_ = nsecPerByte;
251 qlimit(cl->q_) = maxq;
252 qtype(cl->q_) = Q_DROPHEAD;
256 #if 1 /* minidle is also scaled in ALTQ */
257 cl->minidle_ = (minidle * (int)nsecPerByte) / 8;
258 if (cl->minidle_ > 0)
261 cl->minidle_ = minidle;
263 cl->maxidle_ = (maxidle * nsecPerByte) / 8;
264 if (cl->maxidle_ == 0)
266 #if 1 /* offtime is also scaled in ALTQ */
267 cl->avgidle_ = cl->maxidle_;
268 cl->offtime_ = ((offtime * nsecPerByte) / 8) >> RM_FILTER_GAIN;
269 if (cl->offtime_ == 0)
273 cl->offtime_ = (offtime * nsecPerByte) / 8;
275 cl->overlimit = action;
278 if (flags & (RMCF_RED|RMCF_RIO)) {
279 int red_flags, red_pkttime;
282 if (flags & RMCF_ECN)
283 red_flags |= REDF_ECN;
284 if (flags & RMCF_FLOWVALVE)
285 red_flags |= REDF_FLOWVALVE;
287 if (flags & RMCF_CLEARDSCP)
288 red_flags |= RIOF_CLEARDSCP;
290 red_pkttime = nsecPerByte * pktsize / 1000;
292 if (flags & RMCF_RED) {
293 cl->red_ = red_alloc(0, 0,
294 qlimit(cl->q_) * 10/100,
295 qlimit(cl->q_) * 30/100,
296 red_flags, red_pkttime);
297 if (cl->red_ != NULL)
298 qtype(cl->q_) = Q_RED;
302 cl->red_ = (red_t *)rio_alloc(0, NULL,
303 red_flags, red_pkttime);
304 if (cl->red_ != NULL)
305 qtype(cl->q_) = Q_RIO;
309 #endif /* ALTQ_RED */
312 * put the class into the class tree
320 if ((peer = ifd->active_[pri]) != NULL) {
321 /* find the last class at this pri */
323 while (peer->peer_ != ifd->active_[pri])
327 ifd->active_[pri] = cl;
332 cl->next_ = parent->children_;
333 parent->children_ = cl;
338 * Compute the depth of this class and its ancestors in the class
341 rmc_depth_compute(cl);
344 * If CBQ's WRR is enabled, then initialize the class WRR state.
348 ifd->alloc_[pri] += cl->allotment_;
349 rmc_wrr_set_weights(ifd);
351 IFQ_UNLOCK(ifd->ifq_);
357 rmc_modclass(struct rm_class *cl, u_int nsecPerByte, int maxq, u_int maxidle,
358 int minidle, u_int offtime, int pktsize)
360 struct rm_ifdat *ifd;
365 old_allotment = cl->allotment_;
373 cl->allotment_ = RM_NS_PER_SEC / nsecPerByte; /* Bytes per sec */
375 cl->ns_per_byte_ = nsecPerByte;
377 qlimit(cl->q_) = maxq;
379 #if 1 /* minidle is also scaled in ALTQ */
380 cl->minidle_ = (minidle * nsecPerByte) / 8;
381 if (cl->minidle_ > 0)
384 cl->minidle_ = minidle;
386 cl->maxidle_ = (maxidle * nsecPerByte) / 8;
387 if (cl->maxidle_ == 0)
389 #if 1 /* offtime is also scaled in ALTQ */
390 cl->avgidle_ = cl->maxidle_;
391 cl->offtime_ = ((offtime * nsecPerByte) / 8) >> RM_FILTER_GAIN;
392 if (cl->offtime_ == 0)
396 cl->offtime_ = (offtime * nsecPerByte) / 8;
400 * If CBQ's WRR is enabled, then initialize the class WRR state.
403 ifd->alloc_[cl->pri_] += cl->allotment_ - old_allotment;
404 rmc_wrr_set_weights(ifd);
406 IFQ_UNLOCK(ifd->ifq_);
413 * rmc_wrr_set_weights(struct rm_ifdat *ifdat) - This function computes
414 * the appropriate run robin weights for the CBQ weighted round robin
421 rmc_wrr_set_weights(struct rm_ifdat *ifd)
424 struct rm_class *cl, *clh;
426 for (i = 0; i < RM_MAXPRIO; i++) {
428 * This is inverted from that of the simulator to
429 * maintain precision.
431 if (ifd->num_[i] == 0)
434 ifd->M_[i] = ifd->alloc_[i] /
435 (ifd->num_[i] * ifd->maxpkt_);
437 * Compute the weighted allotment for each class.
438 * This takes the expensive div instruction out
439 * of the main loop for the wrr scheduling path.
440 * These only get recomputed when a class comes or
443 if (ifd->active_[i] != NULL) {
444 clh = cl = ifd->active_[i];
446 /* safe-guard for slow link or alloc_ == 0 */
448 cl->w_allotment_ = 0;
450 cl->w_allotment_ = cl->allotment_ /
453 } while ((cl != NULL) && (cl != clh));
459 rmc_get_weight(struct rm_ifdat *ifd, int pri)
461 if ((pri >= 0) && (pri < RM_MAXPRIO))
462 return (ifd->M_[pri]);
469 * rmc_depth_compute(struct rm_class *cl) - This function computes the
470 * appropriate depth of class 'cl' and its ancestors.
476 rmc_depth_compute(struct rm_class *cl)
478 rm_class_t *t = cl, *p;
481 * Recompute the depth for the branch of the tree.
485 if (p && (t->depth_ >= p->depth_)) {
486 p->depth_ = t->depth_ + 1;
495 * rmc_depth_recompute(struct rm_class *cl) - This function re-computes
496 * the depth of the tree after a class has been deleted.
502 rmc_depth_recompute(rm_class_t *cl)
509 if ((t = p->children_) == NULL) {
515 if (t->depth_ > cdepth)
520 if (p->depth_ == cdepth + 1)
521 /* no change to this parent */
524 p->depth_ = cdepth + 1;
532 if (cl->depth_ >= 1) {
533 if (cl->children_ == NULL) {
535 } else if ((t = cl->children_) != NULL) {
537 if (t->children_ != NULL)
538 rmc_depth_recompute(t);
542 rmc_depth_compute(cl);
549 * rmc_delete_class(struct rm_ifdat *ifdat, struct rm_class *cl) - This
550 * function deletes a class from the link-sharing structure and frees
551 * all resources associated with the class.
557 rmc_delete_class(struct rm_ifdat *ifd, struct rm_class *cl)
559 struct rm_class *p, *head, *previous;
562 ASSERT(cl->children_ == NULL);
565 CALLOUT_STOP(&cl->callout_);
574 * Free packets in the packet queue.
575 * XXX - this may not be a desired behavior. Packets should be
581 * If the class has a parent, then remove the class from the
582 * class from the parent's children chain.
584 if (cl->parent_ != NULL) {
585 head = cl->parent_->children_;
587 if (head->next_ == NULL) {
589 cl->parent_->children_ = NULL;
590 cl->parent_->leaf_ = 1;
591 } else while (p != NULL) {
594 cl->parent_->children_ = cl->next_;
596 previous->next_ = cl->next_;
607 * Delete class from class priority peer list.
609 if ((p = ifd->active_[cl->pri_]) != NULL) {
611 * If there is more than one member of this priority
612 * level, then look for class(cl) in the priority level.
615 while (p->peer_ != cl)
617 p->peer_ = cl->peer_;
619 if (ifd->active_[cl->pri_] == cl)
620 ifd->active_[cl->pri_] = cl->peer_;
623 ifd->active_[cl->pri_] = NULL;
628 * Recompute the WRR weights.
631 ifd->alloc_[cl->pri_] -= cl->allotment_;
632 ifd->num_[cl->pri_]--;
633 rmc_wrr_set_weights(ifd);
637 * Re-compute the depth of the tree.
640 rmc_depth_recompute(cl->parent_);
642 rmc_depth_recompute(ifd->root_);
645 IFQ_UNLOCK(ifd->ifq_);
649 * Free the class structure.
651 if (cl->red_ != NULL) {
653 if (q_is_rio(cl->q_))
654 rio_destroy((rio_t *)cl->red_);
657 if (q_is_red(cl->q_))
658 red_destroy(cl->red_);
661 free(cl->q_, M_DEVBUF);
668 * rmc_init(...) - Initialize the resource management data structures
669 * associated with the output portion of interface 'ifp'. 'ifd' is
670 * where the structures will be built (for backwards compatibility, the
671 * structures aren't kept in the ifnet struct). 'nsecPerByte'
672 * gives the link speed (inverse of bandwidth) in nanoseconds/byte.
673 * 'restart' is the driver-specific routine that the generic 'delay
674 * until under limit' action will call to restart output. `maxq'
675 * is the queue size of the 'link' & 'default' classes. 'maxqueued'
676 * is the maximum number of packets that the resource management
677 * code will allow to be queued 'downstream' (this is typically 1).
683 rmc_init(struct ifaltq *ifq, struct rm_ifdat *ifd, u_int nsecPerByte,
684 void (*restart)(struct ifaltq *), int maxq, int maxqueued, u_int maxidle,
685 int minidle, u_int offtime, int flags)
690 * Initialize the CBQ tracing/debug facility.
694 bzero((char *)ifd, sizeof (*ifd));
695 mtu = ifq->altq_ifp->if_mtu;
697 ifd->restart = restart;
698 ifd->maxqueued_ = maxqueued;
699 ifd->ns_per_byte_ = nsecPerByte;
701 ifd->wrr_ = (flags & RMCF_WRR) ? 1 : 0;
702 ifd->efficient_ = (flags & RMCF_EFFICIENT) ? 1 : 0;
704 ifd->maxiftime_ = mtu * nsecPerByte / 1000 * 16;
705 if (mtu * nsecPerByte > 10 * 1000000)
706 ifd->maxiftime_ /= 4;
710 CBQTRACE(rmc_init, 'INIT', ifd->cutoff_);
713 * Initialize the CBQ's WRR state.
715 for (i = 0; i < RM_MAXPRIO; i++) {
720 ifd->active_[i] = NULL;
724 * Initialize current packet state.
728 for (i = 0; i < RM_MAXQUEUED; i++) {
729 ifd->class_[i] = NULL;
731 ifd->borrowed_[i] = NULL;
735 * Create the root class of the link-sharing structure.
737 if ((ifd->root_ = rmc_newclass(0, ifd,
739 rmc_root_overlimit, maxq, 0, 0,
740 maxidle, minidle, offtime,
742 printf("rmc_init: root class not allocated\n");
745 ifd->root_->depth_ = 0;
750 * rmc_queue_packet(struct rm_class *cl, mbuf_t *m) - Add packet given by
751 * mbuf 'm' to queue for resource class 'cl'. This routine is called
752 * by a driver's if_output routine. This routine must be called with
753 * output packet completion interrupts locked out (to avoid racing with
756 * Returns: 0 on successful queueing
757 * -1 when packet drop occurs
760 rmc_queue_packet(struct rm_class *cl, mbuf_t *m)
763 struct rm_ifdat *ifd = cl->ifdat_;
765 int is_empty = qempty(cl->q_);
768 if (ifd->cutoff_ > 0) {
769 if (TV_LT(&cl->undertime_, &now)) {
770 if (ifd->cutoff_ > cl->depth_)
771 ifd->cutoff_ = cl->depth_;
772 CBQTRACE(rmc_queue_packet, 'ffoc', cl->depth_);
777 * the class is overlimit. if the class has
778 * underlimit ancestors, set cutoff to the lowest
781 struct rm_class *borrow = cl->borrow_;
783 while (borrow != NULL &&
784 borrow->depth_ < ifd->cutoff_) {
785 if (TV_LT(&borrow->undertime_, &now)) {
786 ifd->cutoff_ = borrow->depth_;
787 CBQTRACE(rmc_queue_packet, 'ffob', ifd->cutoff_);
790 borrow = borrow->borrow_;
794 else if ((ifd->cutoff_ > 1) && cl->borrow_) {
795 if (TV_LT(&cl->borrow_->undertime_, &now)) {
796 ifd->cutoff_ = cl->borrow_->depth_;
797 CBQTRACE(rmc_queue_packet, 'ffob',
798 cl->borrow_->depth_);
804 if (_rmc_addq(cl, m) < 0)
809 CBQTRACE(rmc_queue_packet, 'ytpe', cl->stats_.handle);
813 if (qlen(cl->q_) > qlimit(cl->q_)) {
814 /* note: qlimit can be set to 0 or 1 */
823 * rmc_tl_satisfied(struct rm_ifdat *ifd, struct timeval *now) - Check all
824 * classes to see if there are satified.
828 rmc_tl_satisfied(struct rm_ifdat *ifd, struct timeval *now)
833 for (i = RM_MAXPRIO - 1; i >= 0; i--) {
834 if ((bp = ifd->active_[i]) != NULL) {
837 if (!rmc_satisfied(p, now)) {
838 ifd->cutoff_ = p->depth_;
850 * rmc_satisfied - Return 1 of the class is satisfied. O, otherwise.
854 rmc_satisfied(struct rm_class *cl, struct timeval *now)
860 if (TV_LT(now, &cl->undertime_))
862 if (cl->depth_ == 0) {
863 if (!cl->sleeping_ && (qlen(cl->q_) > cl->qthresh_))
868 if (cl->children_ != NULL) {
871 if (!rmc_satisfied(p, now))
881 * Return 1 if class 'cl' is under limit or can borrow from a parent,
882 * 0 if overlimit. As a side-effect, this routine will invoke the
883 * class overlimit action if the class if overlimit.
887 rmc_under_limit(struct rm_class *cl, struct timeval *now)
891 struct rm_ifdat *ifd = cl->ifdat_;
893 ifd->borrowed_[ifd->qi_] = NULL;
895 * If cl is the root class, then always return that it is
896 * underlimit. Otherwise, check to see if the class is underlimit.
898 if (cl->parent_ == NULL)
902 if (TV_LT(now, &cl->undertime_))
905 CALLOUT_STOP(&cl->callout_);
907 cl->undertime_.tv_sec = 0;
912 while (cl->undertime_.tv_sec && TV_LT(now, &cl->undertime_)) {
913 if (((cl = cl->borrow_) == NULL) ||
914 (cl->depth_ > ifd->cutoff_)) {
917 /* cutoff is taking effect, just
918 return false without calling
922 #ifdef BORROW_OFFTIME
924 * check if the class can borrow offtime too.
925 * borrow offtime from the top of the borrow
926 * chain if the top class is not overloaded.
929 /* cutoff is taking effect, use this class as top. */
931 CBQTRACE(rmc_under_limit, 'ffou', ifd->cutoff_);
933 if (top != NULL && top->avgidle_ == top->minidle_)
936 (p->overlimit)(p, top);
939 (p->overlimit)(p, NULL);
947 ifd->borrowed_[ifd->qi_] = cl;
952 * _rmc_wrr_dequeue_next() - This is scheduler for WRR as opposed to
953 * Packet-by-packet round robin.
955 * The heart of the weighted round-robin scheduler, which decides which
956 * class next gets to send a packet. Highest priority first, then
957 * weighted round-robin within priorites.
959 * Each able-to-send class gets to send until its byte allocation is
960 * exhausted. Thus, the active pointer is only changed after a class has
961 * exhausted its allocation.
963 * If the scheduler finds no class that is underlimit or able to borrow,
964 * then the first class found that had a nonzero queue and is allowed to
965 * borrow gets to send.
969 _rmc_wrr_dequeue_next(struct rm_ifdat *ifd, int op)
971 struct rm_class *cl = NULL, *first = NULL;
980 * if the driver polls the top of the queue and then removes
981 * the polled packet, we must return the same packet.
983 if (op == ALTDQ_REMOVE && ifd->pollcache_) {
984 cl = ifd->pollcache_;
986 if (ifd->efficient_) {
987 /* check if this class is overlimit */
988 if (cl->undertime_.tv_sec != 0 &&
989 rmc_under_limit(cl, &now) == 0)
992 ifd->pollcache_ = NULL;
996 /* mode == ALTDQ_POLL || pollcache == NULL */
997 ifd->pollcache_ = NULL;
998 ifd->borrowed_[ifd->qi_] = NULL;
1000 #ifdef ADJUST_CUTOFF
1003 for (cpri = RM_MAXPRIO - 1; cpri >= 0; cpri--) {
1004 if (ifd->na_[cpri] == 0)
1008 * Loop through twice for a priority level, if some class
1009 * was unable to send a packet the first round because
1010 * of the weighted round-robin mechanism.
1011 * During the second loop at this level, deficit==2.
1012 * (This second loop is not needed if for every class,
1013 * "M[cl->pri_])" times "cl->allotment" is greater than
1014 * the byte size for the largest packet in the class.)
1017 cl = ifd->active_[cpri];
1020 if ((deficit < 2) && (cl->bytes_alloc_ <= 0))
1021 cl->bytes_alloc_ += cl->w_allotment_;
1022 if (!qempty(cl->q_)) {
1023 if ((cl->undertime_.tv_sec == 0) ||
1024 rmc_under_limit(cl, &now)) {
1025 if (cl->bytes_alloc_ > 0 || deficit > 1)
1028 /* underlimit but no alloc */
1031 ifd->borrowed_[ifd->qi_] = NULL;
1034 else if (first == NULL && cl->borrow_ != NULL)
1035 first = cl; /* borrowing candidate */
1038 cl->bytes_alloc_ = 0;
1040 } while (cl != ifd->active_[cpri]);
1043 /* first loop found an underlimit class with deficit */
1044 /* Loop on same priority level, with new deficit. */
1050 #ifdef ADJUST_CUTOFF
1052 * no underlimit class found. if cutoff is taking effect,
1053 * increase cutoff and try again.
1055 if (first != NULL && ifd->cutoff_ < ifd->root_->depth_) {
1057 CBQTRACE(_rmc_wrr_dequeue_next, 'ojda', ifd->cutoff_);
1060 #endif /* ADJUST_CUTOFF */
1062 * If LINK_EFFICIENCY is turned on, then the first overlimit
1063 * class we encounter will send a packet if all the classes
1064 * of the link-sharing structure are overlimit.
1067 CBQTRACE(_rmc_wrr_dequeue_next, 'otsr', ifd->cutoff_);
1069 if (!ifd->efficient_ || first == NULL)
1074 #if 0 /* too time-consuming for nothing */
1076 CALLOUT_STOP(&cl->callout_);
1078 cl->undertime_.tv_sec = 0;
1080 ifd->borrowed_[ifd->qi_] = cl->borrow_;
1081 ifd->cutoff_ = cl->borrow_->depth_;
1084 * Deque the packet and do the book keeping...
1087 if (op == ALTDQ_REMOVE) {
1090 panic("_rmc_wrr_dequeue_next");
1095 * Update class statistics and link data.
1097 if (cl->bytes_alloc_ > 0)
1098 cl->bytes_alloc_ -= m_pktlen(m);
1100 if ((cl->bytes_alloc_ <= 0) || first == cl)
1101 ifd->active_[cl->pri_] = cl->peer_;
1103 ifd->active_[cl->pri_] = cl;
1105 ifd->class_[ifd->qi_] = cl;
1106 ifd->curlen_[ifd->qi_] = m_pktlen(m);
1107 ifd->now_[ifd->qi_] = now;
1108 ifd->qi_ = (ifd->qi_ + 1) % ifd->maxqueued_;
1111 /* mode == ALTDQ_PPOLL */
1113 ifd->pollcache_ = cl;
1119 * Dequeue & return next packet from the highest priority class that
1120 * has a packet to send & has enough allocation to send it. This
1121 * routine is called by a driver whenever it needs a new packet to
1125 _rmc_prr_dequeue_next(struct rm_ifdat *ifd, int op)
1129 struct rm_class *cl, *first = NULL;
1135 * if the driver polls the top of the queue and then removes
1136 * the polled packet, we must return the same packet.
1138 if (op == ALTDQ_REMOVE && ifd->pollcache_) {
1139 cl = ifd->pollcache_;
1141 ifd->pollcache_ = NULL;
1144 /* mode == ALTDQ_POLL || pollcache == NULL */
1145 ifd->pollcache_ = NULL;
1146 ifd->borrowed_[ifd->qi_] = NULL;
1148 #ifdef ADJUST_CUTOFF
1151 for (cpri = RM_MAXPRIO - 1; cpri >= 0; cpri--) {
1152 if (ifd->na_[cpri] == 0)
1154 cl = ifd->active_[cpri];
1157 if (!qempty(cl->q_)) {
1158 if ((cl->undertime_.tv_sec == 0) ||
1159 rmc_under_limit(cl, &now))
1161 if (first == NULL && cl->borrow_ != NULL)
1165 } while (cl != ifd->active_[cpri]);
1168 #ifdef ADJUST_CUTOFF
1170 * no underlimit class found. if cutoff is taking effect, increase
1171 * cutoff and try again.
1173 if (first != NULL && ifd->cutoff_ < ifd->root_->depth_) {
1177 #endif /* ADJUST_CUTOFF */
1179 * If LINK_EFFICIENCY is turned on, then the first overlimit
1180 * class we encounter will send a packet if all the classes
1181 * of the link-sharing structure are overlimit.
1184 if (!ifd->efficient_ || first == NULL)
1189 #if 0 /* too time-consuming for nothing */
1191 CALLOUT_STOP(&cl->callout_);
1193 cl->undertime_.tv_sec = 0;
1195 ifd->borrowed_[ifd->qi_] = cl->borrow_;
1196 ifd->cutoff_ = cl->borrow_->depth_;
1199 * Deque the packet and do the book keeping...
1202 if (op == ALTDQ_REMOVE) {
1205 panic("_rmc_prr_dequeue_next");
1209 ifd->active_[cpri] = cl->peer_;
1211 ifd->class_[ifd->qi_] = cl;
1212 ifd->curlen_[ifd->qi_] = m_pktlen(m);
1213 ifd->now_[ifd->qi_] = now;
1214 ifd->qi_ = (ifd->qi_ + 1) % ifd->maxqueued_;
1217 /* mode == ALTDQ_POLL */
1219 ifd->pollcache_ = cl;
1226 * rmc_dequeue_next(struct rm_ifdat *ifd, struct timeval *now) - this function
1227 * is invoked by the packet driver to get the next packet to be
1228 * dequeued and output on the link. If WRR is enabled, then the
1229 * WRR dequeue next routine will determine the next packet to sent.
1230 * Otherwise, packet-by-packet round robin is invoked.
1232 * Returns: NULL, if a packet is not available or if all
1233 * classes are overlimit.
1235 * Otherwise, Pointer to the next packet.
1239 rmc_dequeue_next(struct rm_ifdat *ifd, int mode)
1241 if (ifd->queued_ >= ifd->maxqueued_)
1244 return (_rmc_wrr_dequeue_next(ifd, mode));
1246 return (_rmc_prr_dequeue_next(ifd, mode));
1250 * Update the utilization estimate for the packet that just completed.
1251 * The packet's class & the parent(s) of that class all get their
1252 * estimators updated. This routine is called by the driver's output-
1253 * packet-completion interrupt service routine.
1257 * a macro to approximate "divide by 1000" that gives 0.000999,
1258 * if a value has enough effective digits.
1259 * (on pentium, mul takes 9 cycles but div takes 46!)
1261 #define NSEC_TO_USEC(t) (((t) >> 10) + ((t) >> 16) + ((t) >> 17))
1263 rmc_update_class_util(struct rm_ifdat *ifd)
1265 int idle, avgidle, pktlen;
1266 int pkt_time, tidle;
1267 rm_class_t *cl, *borrowed;
1268 rm_class_t *borrows;
1269 struct timeval *nowp;
1272 * Get the most recent completed class.
1274 if ((cl = ifd->class_[ifd->qo_]) == NULL)
1277 pktlen = ifd->curlen_[ifd->qo_];
1278 borrowed = ifd->borrowed_[ifd->qo_];
1281 PKTCNTR_ADD(&cl->stats_.xmit_cnt, pktlen);
1284 * Run estimator on class and its ancestors.
1287 * rm_update_class_util is designed to be called when the
1288 * transfer is completed from a xmit complete interrupt,
1289 * but most drivers don't implement an upcall for that.
1290 * so, just use estimated completion time.
1291 * as a result, ifd->qi_ and ifd->qo_ are always synced.
1293 nowp = &ifd->now_[ifd->qo_];
1294 /* get pkt_time (for link) in usec */
1295 #if 1 /* use approximation */
1296 pkt_time = ifd->curlen_[ifd->qo_] * ifd->ns_per_byte_;
1297 pkt_time = NSEC_TO_USEC(pkt_time);
1299 pkt_time = ifd->curlen_[ifd->qo_] * ifd->ns_per_byte_ / 1000;
1301 #if 1 /* ALTQ4PPP */
1302 if (TV_LT(nowp, &ifd->ifnow_)) {
1306 * make sure the estimated completion time does not go
1307 * too far. it can happen when the link layer supports
1308 * data compression or the interface speed is set to
1309 * a much lower value.
1311 TV_DELTA(&ifd->ifnow_, nowp, iftime);
1312 if (iftime+pkt_time < ifd->maxiftime_) {
1313 TV_ADD_DELTA(&ifd->ifnow_, pkt_time, &ifd->ifnow_);
1315 TV_ADD_DELTA(nowp, ifd->maxiftime_, &ifd->ifnow_);
1318 TV_ADD_DELTA(nowp, pkt_time, &ifd->ifnow_);
1321 if (TV_LT(nowp, &ifd->ifnow_)) {
1322 TV_ADD_DELTA(&ifd->ifnow_, pkt_time, &ifd->ifnow_);
1324 TV_ADD_DELTA(nowp, pkt_time, &ifd->ifnow_);
1328 while (cl != NULL) {
1329 TV_DELTA(&ifd->ifnow_, &cl->last_, idle);
1330 if (idle >= 2000000)
1332 * this class is idle enough, reset avgidle.
1333 * (TV_DELTA returns 2000000 us when delta is large.)
1335 cl->avgidle_ = cl->maxidle_;
1337 /* get pkt_time (for class) in usec */
1338 #if 1 /* use approximation */
1339 pkt_time = pktlen * cl->ns_per_byte_;
1340 pkt_time = NSEC_TO_USEC(pkt_time);
1342 pkt_time = pktlen * cl->ns_per_byte_ / 1000;
1346 avgidle = cl->avgidle_;
1347 avgidle += idle - (avgidle >> RM_FILTER_GAIN);
1348 cl->avgidle_ = avgidle;
1350 /* Are we overlimit ? */
1352 CBQTRACE(rmc_update_class_util, 'milo', cl->stats_.handle);
1355 * need some lower bound for avgidle, otherwise
1356 * a borrowing class gets unbounded penalty.
1358 if (avgidle < cl->minidle_)
1359 avgidle = cl->avgidle_ = cl->minidle_;
1361 /* set next idle to make avgidle 0 */
1363 (((1 - RM_POWER) * avgidle) >> RM_FILTER_GAIN);
1364 TV_ADD_DELTA(nowp, tidle, &cl->undertime_);
1368 (avgidle > cl->maxidle_) ? cl->maxidle_ : avgidle;
1369 cl->undertime_.tv_sec = 0;
1370 if (cl->sleeping_) {
1371 CALLOUT_STOP(&cl->callout_);
1376 if (borrows != NULL) {
1378 ++cl->stats_.borrows;
1382 cl->last_ = ifd->ifnow_;
1383 cl->last_pkttime_ = pkt_time;
1386 if (cl->parent_ == NULL) {
1387 /* take stats of root class */
1388 PKTCNTR_ADD(&cl->stats_.xmit_cnt, pktlen);
1396 * Check to see if cutoff needs to set to a new level.
1398 cl = ifd->class_[ifd->qo_];
1399 if (borrowed && (ifd->cutoff_ >= borrowed->depth_)) {
1401 if ((qlen(cl->q_) <= 0) || TV_LT(nowp, &borrowed->undertime_)) {
1402 rmc_tl_satisfied(ifd, nowp);
1403 CBQTRACE(rmc_update_class_util, 'broe', ifd->cutoff_);
1405 ifd->cutoff_ = borrowed->depth_;
1406 CBQTRACE(rmc_update_class_util, 'ffob', borrowed->depth_);
1409 if ((qlen(cl->q_) <= 1) || TV_LT(&now, &borrowed->undertime_)) {
1412 rmc_tl_satisfied(ifd, &now);
1414 CBQTRACE(rmc_update_class_util, 'broe', ifd->cutoff_);
1416 ifd->cutoff_ = borrowed->depth_;
1417 CBQTRACE(rmc_update_class_util, 'ffob', borrowed->depth_);
1423 * Release class slot
1425 ifd->borrowed_[ifd->qo_] = NULL;
1426 ifd->class_[ifd->qo_] = NULL;
1427 ifd->qo_ = (ifd->qo_ + 1) % ifd->maxqueued_;
1433 * rmc_drop_action(struct rm_class *cl) - Generic (not protocol-specific)
1434 * over-limit action routines. These get invoked by rmc_under_limit()
1435 * if a class with packets to send if over its bandwidth limit & can't
1436 * borrow from a parent class.
1442 rmc_drop_action(struct rm_class *cl)
1444 struct rm_ifdat *ifd = cl->ifdat_;
1446 ASSERT(qlen(cl->q_) > 0);
1449 ifd->na_[cl->pri_]--;
1452 void rmc_dropall(struct rm_class *cl)
1454 struct rm_ifdat *ifd = cl->ifdat_;
1456 if (!qempty(cl->q_)) {
1459 ifd->na_[cl->pri_]--;
1463 #if (__FreeBSD_version > 300000)
1464 /* hzto() is removed from FreeBSD-3.0 */
1465 static int hzto(struct timeval *);
1474 t2.tv_sec = tv->tv_sec - t2.tv_sec;
1475 t2.tv_usec = tv->tv_usec - t2.tv_usec;
1476 return (tvtohz(&t2));
1478 #endif /* __FreeBSD_version > 300000 */
1482 * rmc_delay_action(struct rm_class *cl) - This function is the generic CBQ
1483 * delay action routine. It is invoked via rmc_under_limit when the
1484 * packet is discoverd to be overlimit.
1486 * If the delay action is result of borrow class being overlimit, then
1487 * delay for the offtime of the borrowing class that is overlimit.
1493 rmc_delay_action(struct rm_class *cl, struct rm_class *borrow)
1495 int delay, t, extradelay;
1497 cl->stats_.overactions++;
1498 TV_DELTA(&cl->undertime_, &cl->overtime_, delay);
1499 #ifndef BORROW_OFFTIME
1500 delay += cl->offtime_;
1503 if (!cl->sleeping_) {
1504 CBQTRACE(rmc_delay_action, 'yled', cl->stats_.handle);
1505 #ifdef BORROW_OFFTIME
1507 extradelay = borrow->offtime_;
1510 extradelay = cl->offtime_;
1514 * XXX recalculate suspend time:
1515 * current undertime is (tidle + pkt_time) calculated
1516 * from the last transmission.
1517 * tidle: time required to bring avgidle back to 0
1518 * pkt_time: target waiting time for this class
1519 * we need to replace pkt_time by offtime
1521 extradelay -= cl->last_pkttime_;
1523 if (extradelay > 0) {
1524 TV_ADD_DELTA(&cl->undertime_, extradelay, &cl->undertime_);
1525 delay += extradelay;
1529 cl->stats_.delays++;
1532 * Since packets are phased randomly with respect to the
1533 * clock, 1 tick (the next clock tick) can be an arbitrarily
1534 * short time so we have to wait for at least two ticks.
1535 * NOTE: If there's no other traffic, we need the timer as
1536 * a 'backstop' to restart this class.
1538 if (delay > tick * 2) {
1540 /* FreeBSD rounds up the tick */
1541 t = hzto(&cl->undertime_);
1543 /* other BSDs round down the tick */
1544 t = hzto(&cl->undertime_) + 1;
1548 CALLOUT_RESET(&cl->callout_, t,
1549 (timeout_t *)rmc_restart, (caddr_t)cl);
1555 * rmc_restart() - is just a helper routine for rmc_delay_action -- it is
1556 * called by the system timer code & is responsible checking if the
1557 * class is still sleeping (it might have been restarted as a side
1558 * effect of the queue scan on a packet arrival) and, if so, restarting
1559 * output for the class. Inspecting the class state & restarting output
1560 * require locking the class structure. In general the driver is
1561 * responsible for locking but this is the only routine that is not
1562 * called directly or indirectly from the interface driver so it has
1563 * know about system locking conventions. Under bsd, locking is done
1564 * by raising IPL to splimp so that's what's implemented here. On a
1565 * different system this would probably need to be changed.
1571 rmc_restart(struct rm_class *cl)
1573 struct rm_ifdat *ifd = cl->ifdat_;
1581 IFQ_LOCK(ifd->ifq_);
1582 if (cl->sleeping_) {
1584 cl->undertime_.tv_sec = 0;
1586 if (ifd->queued_ < ifd->maxqueued_ && ifd->restart != NULL) {
1587 CBQTRACE(rmc_restart, 'trts', cl->stats_.handle);
1588 (ifd->restart)(ifd->ifq_);
1591 IFQ_UNLOCK(ifd->ifq_);
1597 * rmc_root_overlimit(struct rm_class *cl) - This the generic overlimit
1598 * handling routine for the root class of the link sharing structure.
1604 rmc_root_overlimit(struct rm_class *cl, struct rm_class *borrow)
1606 panic("rmc_root_overlimit");
1610 * Packet Queue handling routines. Eventually, this is to localize the
1611 * effects on the code whether queues are red queues or droptail
1616 _rmc_addq(rm_class_t *cl, mbuf_t *m)
1619 if (q_is_rio(cl->q_))
1620 return rio_addq((rio_t *)cl->red_, cl->q_, m, cl->pktattr_);
1623 if (q_is_red(cl->q_))
1624 return red_addq(cl->red_, cl->q_, m, cl->pktattr_);
1625 #endif /* ALTQ_RED */
1627 if (cl->flags_ & RMCF_CLEARDSCP)
1628 write_dsfield(m, cl->pktattr_, 0);
1634 /* note: _rmc_dropq is not called for red */
1636 _rmc_dropq(rm_class_t *cl)
1640 if ((m = _getq(cl->q_)) != NULL)
1645 _rmc_getq(rm_class_t *cl)
1648 if (q_is_rio(cl->q_))
1649 return rio_getq((rio_t *)cl->red_, cl->q_);
1652 if (q_is_red(cl->q_))
1653 return red_getq(cl->red_, cl->q_);
1655 return _getq(cl->q_);
1659 _rmc_pollq(rm_class_t *cl)
1661 return qhead(cl->q_);
1666 struct cbqtrace cbqtrace_buffer[NCBQTRACE+1];
1667 struct cbqtrace *cbqtrace_ptr = NULL;
1671 * DDB hook to trace cbq events:
1672 * the last 1024 events are held in a circular buffer.
1673 * use "call cbqtrace_dump(N)" to display 20 events from Nth event.
1675 void cbqtrace_dump(int);
1676 static char *rmc_funcname(void *);
1678 static struct rmc_funcs {
1683 rmc_init, "rmc_init",
1684 rmc_queue_packet, "rmc_queue_packet",
1685 rmc_under_limit, "rmc_under_limit",
1686 rmc_update_class_util, "rmc_update_class_util",
1687 rmc_delay_action, "rmc_delay_action",
1688 rmc_restart, "rmc_restart",
1689 _rmc_wrr_dequeue_next, "_rmc_wrr_dequeue_next",
1693 static char *rmc_funcname(void *func)
1695 struct rmc_funcs *fp;
1697 for (fp = rmc_funcs; fp->func != NULL; fp++)
1698 if (fp->func == func)
1703 void cbqtrace_dump(int counter)
1708 counter = counter % NCBQTRACE;
1709 p = (int *)&cbqtrace_buffer[counter];
1711 for (i=0; i<20; i++) {
1712 printf("[0x%x] ", *p++);
1713 printf("%s: ", rmc_funcname((void *)*p++));
1715 printf("%c%c%c%c: ", cp[0], cp[1], cp[2], cp[3]);
1716 printf("%d\n",*p++);
1718 if (p >= (int *)&cbqtrace_buffer[NCBQTRACE])
1719 p = (int *)cbqtrace_buffer;
1722 #endif /* CBQ_TRACE */
1723 #endif /* ALTQ_CBQ */
1725 #if defined(ALTQ_CBQ) || defined(ALTQ_RED) || defined(ALTQ_RIO) || defined(ALTQ_HFSC) || defined(ALTQ_PRIQ)
1726 #if !defined(__GNUC__) || defined(ALTQ_DEBUG)
1729 _addq(class_queue_t *q, mbuf_t *m)
1733 if ((m0 = qtail(q)) != NULL)
1734 m->m_nextpkt = m0->m_nextpkt;
1743 _getq(class_queue_t *q)
1747 if ((m = qtail(q)) == NULL)
1749 if ((m0 = m->m_nextpkt) != m)
1750 m->m_nextpkt = m0->m_nextpkt;
1752 ASSERT(qlen(q) == 1);
1756 m0->m_nextpkt = NULL;
1760 /* drop a packet at the tail of the queue */
1762 _getq_tail(class_queue_t *q)
1764 mbuf_t *m, *m0, *prev;
1766 if ((m = m0 = qtail(q)) == NULL)
1772 prev->m_nextpkt = m->m_nextpkt;
1774 ASSERT(qlen(q) == 1);
1779 m->m_nextpkt = NULL;
1783 /* randomly select a packet in the queue */
1785 _getq_random(class_queue_t *q)
1790 if ((m = qtail(q)) == NULL)
1792 if (m->m_nextpkt == m) {
1793 ASSERT(qlen(q) == 1);
1796 struct mbuf *prev = NULL;
1798 n = arc4random() % qlen(q) + 1;
1799 for (i = 0; i < n; i++) {
1803 prev->m_nextpkt = m->m_nextpkt;
1808 m->m_nextpkt = NULL;
1813 _removeq(class_queue_t *q, mbuf_t *m)
1822 prev->m_nextpkt = m->m_nextpkt;
1825 else if (qtail(q) == m)
1831 _flushq(class_queue_t *q)
1835 while ((m = _getq(q)) != NULL)
1837 ASSERT(qlen(q) == 0);
1840 #endif /* !__GNUC__ || ALTQ_DEBUG */
1841 #endif /* ALTQ_CBQ || ALTQ_RED || ALTQ_RIO || ALTQ_HFSC || ALTQ_PRIQ */