2 * net/sched/sch_htb.c Hierarchical token bucket, feed tree version
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Martin Devera, <devik@cdi.cz>
11 * Credits (in time order) for older HTB versions:
12 * Stef Coene <stef.coene@docum.org>
13 * HTB support at LARTC mailing list
14 * Ondrej Kraus, <krauso@barr.cz>
15 * found missing INIT_QDISC(htb)
16 * Vladimir Smelhaus, Aamer Akhter, Bert Hubert
17 * helped a lot to locate nasty class stall bug
18 * Andi Kleen, Jamal Hadi, Bert Hubert
19 * code review and helpful comments on shaping
20 * Tomasz Wrona, <tw@eter.tym.pl>
21 * created test case so that I was able to fix nasty bug
23 * spotted bug in dequeue code and helped with fix
25 * fixed requeue routine
26 * and many others. thanks.
28 #include <linux/module.h>
29 #include <linux/moduleparam.h>
30 #include <linux/types.h>
31 #include <linux/kernel.h>
32 #include <linux/string.h>
33 #include <linux/errno.h>
34 #include <linux/skbuff.h>
35 #include <linux/list.h>
36 #include <linux/compiler.h>
37 #include <linux/rbtree.h>
38 #include <net/netlink.h>
39 #include <net/pkt_sched.h>
43 ========================================================================
44 HTB is like TBF with multiple classes. It is also similar to CBQ because
45 it allows to assign priority to each class in hierarchy.
46 In fact it is another implementation of Floyd's formal sharing.
49 Each class is assigned level. Leaf has ALWAYS level 0 and root
50 classes have level TC_HTB_MAXDEPTH-1. Interior nodes has level
51 one less than their parent.
54 #define HTB_HSIZE 16 /* classid hash size */
55 static int htb_hysteresis __read_mostly = 0; /* whether to use mode hysteresis for speedup */
56 #define HTB_VER 0x30011 /* major must be matched with number suplied by TC as version */
58 #if HTB_VER >> 16 != TC_HTB_PROTOVER
59 #error "Mismatched sch_htb.c and pkt_sch.h"
62 /* Module parameter and sysfs export */
63 module_param (htb_hysteresis, int, 0640);
64 MODULE_PARM_DESC(htb_hysteresis, "Hysteresis mode, less CPU load, less accurate");
66 /* used internaly to keep status of single class */
68 HTB_CANT_SEND, /* class can't send and can't borrow */
69 HTB_MAY_BORROW, /* class can't send but may borrow */
70 HTB_CAN_SEND /* class can send */
73 /* interior & leaf nodes; props specific to leaves are marked L: */
75 /* general class parameters */
77 struct gnet_stats_basic bstats;
78 struct gnet_stats_queue qstats;
79 struct gnet_stats_rate_est rate_est;
80 struct tc_htb_xstats xstats; /* our special stats */
81 int refcnt; /* usage count of this class */
84 int level; /* our level (see above) */
85 struct htb_class *parent; /* parent class */
86 struct hlist_node hlist; /* classid hash list item */
87 struct list_head sibling; /* sibling list item */
88 struct list_head children; /* children list */
91 struct htb_class_leaf {
96 int deficit[TC_HTB_MAXDEPTH];
97 struct list_head drop_list;
99 struct htb_class_inner {
100 struct rb_root feed[TC_HTB_NUMPRIO]; /* feed trees */
101 struct rb_node *ptr[TC_HTB_NUMPRIO]; /* current class ptr */
102 /* When class changes from state 1->2 and disconnects from
103 parent's feed then we lost ptr value and start from the
104 first child again. Here we store classid of the
105 last valid ptr (used when ptr is NULL). */
106 u32 last_ptr_id[TC_HTB_NUMPRIO];
109 struct rb_node node[TC_HTB_NUMPRIO]; /* node for self or feed tree */
110 struct rb_node pq_node; /* node for event queue */
111 psched_time_t pq_key;
113 int prio_activity; /* for which prios are we active */
114 enum htb_cmode cmode; /* current mode of the class */
116 /* class attached filters */
117 struct tcf_proto *filter_list;
120 int warned; /* only one warning about non work conserving .. */
122 /* token bucket parameters */
123 struct qdisc_rate_table *rate; /* rate table of the class itself */
124 struct qdisc_rate_table *ceil; /* ceiling rate (limits borrows too) */
125 long buffer, cbuffer; /* token bucket depth/rate */
126 psched_tdiff_t mbuffer; /* max wait time */
127 long tokens, ctokens; /* current number of tokens */
128 psched_time_t t_c; /* checkpoint time */
130 int prio; /* For parent to leaf return possible here */
131 int quantum; /* we do backup. Finally full replacement */
132 /* of un.leaf originals should be done. */
135 static inline long L2T(struct htb_class *cl, struct qdisc_rate_table *rate,
138 long result = qdisc_l2t(rate, size);
143 struct list_head root; /* root classes list */
144 struct hlist_head hash[HTB_HSIZE]; /* hashed by classid */
145 struct list_head drops[TC_HTB_NUMPRIO];/* active leaves (for drops) */
147 /* self list - roots of self generating tree */
148 struct rb_root row[TC_HTB_MAXDEPTH][TC_HTB_NUMPRIO];
149 int row_mask[TC_HTB_MAXDEPTH];
150 struct rb_node *ptr[TC_HTB_MAXDEPTH][TC_HTB_NUMPRIO];
151 u32 last_ptr_id[TC_HTB_MAXDEPTH][TC_HTB_NUMPRIO];
153 /* self wait list - roots of wait PQs per row */
154 struct rb_root wait_pq[TC_HTB_MAXDEPTH];
156 /* time of nearest event per level (row) */
157 psched_time_t near_ev_cache[TC_HTB_MAXDEPTH];
159 /* whether we hit non-work conserving class during this dequeue; we use */
160 int nwc_hit; /* this to disable mindelay complaint in dequeue */
162 int defcls; /* class where unclassified flows go to */
164 /* filters for qdisc itself */
165 struct tcf_proto *filter_list;
168 int rate2quantum; /* quant = rate / rate2quantum */
169 psched_time_t now; /* cached dequeue time */
170 struct qdisc_watchdog watchdog;
172 /* non shaped skbs; let them go directly thru */
173 struct sk_buff_head direct_queue;
174 int direct_qlen; /* max qlen of above */
179 /* compute hash of size HTB_HSIZE for given handle */
180 static inline int htb_hash(u32 h)
183 #error "Declare new hash for your HTB_HSIZE"
185 h ^= h >> 8; /* stolen from cbq_hash */
190 /* find class in global hash table using given handle */
191 static inline struct htb_class *htb_find(u32 handle, struct Qdisc *sch)
193 struct htb_sched *q = qdisc_priv(sch);
194 struct hlist_node *p;
195 struct htb_class *cl;
197 if (TC_H_MAJ(handle) != sch->handle)
200 hlist_for_each_entry(cl, p, q->hash + htb_hash(handle), hlist) {
201 if (cl->classid == handle)
208 * htb_classify - classify a packet into class
210 * It returns NULL if the packet should be dropped or -1 if the packet
211 * should be passed directly thru. In all other cases leaf class is returned.
212 * We allow direct class selection by classid in priority. The we examine
213 * filters in qdisc and in inner nodes (if higher filter points to the inner
214 * node). If we end up with classid MAJOR:0 we enqueue the skb into special
215 * internal fifo (direct). These packets then go directly thru. If we still
216 * have no valid leaf we try to use MAJOR:default leaf. It still unsuccessfull
217 * then finish and return direct queue.
219 #define HTB_DIRECT (struct htb_class*)-1
221 static struct htb_class *htb_classify(struct sk_buff *skb, struct Qdisc *sch,
224 struct htb_sched *q = qdisc_priv(sch);
225 struct htb_class *cl;
226 struct tcf_result res;
227 struct tcf_proto *tcf;
230 /* allow to select class by setting skb->priority to valid classid;
231 note that nfmark can be used too by attaching filter fw with no
233 if (skb->priority == sch->handle)
234 return HTB_DIRECT; /* X:0 (direct flow) selected */
235 if ((cl = htb_find(skb->priority, sch)) != NULL && cl->level == 0)
238 *qerr = NET_XMIT_BYPASS;
239 tcf = q->filter_list;
240 while (tcf && (result = tc_classify(skb, tcf, &res)) >= 0) {
241 #ifdef CONFIG_NET_CLS_ACT
245 *qerr = NET_XMIT_SUCCESS;
250 if ((cl = (void *)res.class) == NULL) {
251 if (res.classid == sch->handle)
252 return HTB_DIRECT; /* X:0 (direct flow) */
253 if ((cl = htb_find(res.classid, sch)) == NULL)
254 break; /* filter selected invalid classid */
257 return cl; /* we hit leaf; return it */
259 /* we have got inner class; apply inner filter chain */
260 tcf = cl->filter_list;
262 /* classification failed; try to use default class */
263 cl = htb_find(TC_H_MAKE(TC_H_MAJ(sch->handle), q->defcls), sch);
264 if (!cl || cl->level)
265 return HTB_DIRECT; /* bad default .. this is safe bet */
270 * htb_add_to_id_tree - adds class to the round robin list
272 * Routine adds class to the list (actually tree) sorted by classid.
273 * Make sure that class is not already on such list for given prio.
275 static void htb_add_to_id_tree(struct rb_root *root,
276 struct htb_class *cl, int prio)
278 struct rb_node **p = &root->rb_node, *parent = NULL;
283 c = rb_entry(parent, struct htb_class, node[prio]);
285 if (cl->classid > c->classid)
286 p = &parent->rb_right;
288 p = &parent->rb_left;
290 rb_link_node(&cl->node[prio], parent, p);
291 rb_insert_color(&cl->node[prio], root);
295 * htb_add_to_wait_tree - adds class to the event queue with delay
297 * The class is added to priority event queue to indicate that class will
298 * change its mode in cl->pq_key microseconds. Make sure that class is not
299 * already in the queue.
301 static void htb_add_to_wait_tree(struct htb_sched *q,
302 struct htb_class *cl, long delay)
304 struct rb_node **p = &q->wait_pq[cl->level].rb_node, *parent = NULL;
306 cl->pq_key = q->now + delay;
307 if (cl->pq_key == q->now)
310 /* update the nearest event cache */
311 if (q->near_ev_cache[cl->level] > cl->pq_key)
312 q->near_ev_cache[cl->level] = cl->pq_key;
317 c = rb_entry(parent, struct htb_class, pq_node);
318 if (cl->pq_key >= c->pq_key)
319 p = &parent->rb_right;
321 p = &parent->rb_left;
323 rb_link_node(&cl->pq_node, parent, p);
324 rb_insert_color(&cl->pq_node, &q->wait_pq[cl->level]);
328 * htb_next_rb_node - finds next node in binary tree
330 * When we are past last key we return NULL.
331 * Average complexity is 2 steps per call.
333 static inline void htb_next_rb_node(struct rb_node **n)
339 * htb_add_class_to_row - add class to its row
341 * The class is added to row at priorities marked in mask.
342 * It does nothing if mask == 0.
344 static inline void htb_add_class_to_row(struct htb_sched *q,
345 struct htb_class *cl, int mask)
347 q->row_mask[cl->level] |= mask;
349 int prio = ffz(~mask);
350 mask &= ~(1 << prio);
351 htb_add_to_id_tree(q->row[cl->level] + prio, cl, prio);
355 /* If this triggers, it is a bug in this code, but it need not be fatal */
356 static void htb_safe_rb_erase(struct rb_node *rb, struct rb_root *root)
358 if (RB_EMPTY_NODE(rb)) {
368 * htb_remove_class_from_row - removes class from its row
370 * The class is removed from row at priorities marked in mask.
371 * It does nothing if mask == 0.
373 static inline void htb_remove_class_from_row(struct htb_sched *q,
374 struct htb_class *cl, int mask)
379 int prio = ffz(~mask);
381 mask &= ~(1 << prio);
382 if (q->ptr[cl->level][prio] == cl->node + prio)
383 htb_next_rb_node(q->ptr[cl->level] + prio);
385 htb_safe_rb_erase(cl->node + prio, q->row[cl->level] + prio);
386 if (!q->row[cl->level][prio].rb_node)
389 q->row_mask[cl->level] &= ~m;
393 * htb_activate_prios - creates active classe's feed chain
395 * The class is connected to ancestors and/or appropriate rows
396 * for priorities it is participating on. cl->cmode must be new
397 * (activated) mode. It does nothing if cl->prio_activity == 0.
399 static void htb_activate_prios(struct htb_sched *q, struct htb_class *cl)
401 struct htb_class *p = cl->parent;
402 long m, mask = cl->prio_activity;
404 while (cl->cmode == HTB_MAY_BORROW && p && mask) {
410 if (p->un.inner.feed[prio].rb_node)
411 /* parent already has its feed in use so that
412 reset bit in mask as parent is already ok */
413 mask &= ~(1 << prio);
415 htb_add_to_id_tree(p->un.inner.feed + prio, cl, prio);
417 p->prio_activity |= mask;
422 if (cl->cmode == HTB_CAN_SEND && mask)
423 htb_add_class_to_row(q, cl, mask);
427 * htb_deactivate_prios - remove class from feed chain
429 * cl->cmode must represent old mode (before deactivation). It does
430 * nothing if cl->prio_activity == 0. Class is removed from all feed
433 static void htb_deactivate_prios(struct htb_sched *q, struct htb_class *cl)
435 struct htb_class *p = cl->parent;
436 long m, mask = cl->prio_activity;
438 while (cl->cmode == HTB_MAY_BORROW && p && mask) {
445 if (p->un.inner.ptr[prio] == cl->node + prio) {
446 /* we are removing child which is pointed to from
447 parent feed - forget the pointer but remember
449 p->un.inner.last_ptr_id[prio] = cl->classid;
450 p->un.inner.ptr[prio] = NULL;
453 htb_safe_rb_erase(cl->node + prio, p->un.inner.feed + prio);
455 if (!p->un.inner.feed[prio].rb_node)
459 p->prio_activity &= ~mask;
464 if (cl->cmode == HTB_CAN_SEND && mask)
465 htb_remove_class_from_row(q, cl, mask);
468 static inline long htb_lowater(const struct htb_class *cl)
471 return cl->cmode != HTB_CANT_SEND ? -cl->cbuffer : 0;
475 static inline long htb_hiwater(const struct htb_class *cl)
478 return cl->cmode == HTB_CAN_SEND ? -cl->buffer : 0;
485 * htb_class_mode - computes and returns current class mode
487 * It computes cl's mode at time cl->t_c+diff and returns it. If mode
488 * is not HTB_CAN_SEND then cl->pq_key is updated to time difference
489 * from now to time when cl will change its state.
490 * Also it is worth to note that class mode doesn't change simply
491 * at cl->{c,}tokens == 0 but there can rather be hysteresis of
492 * 0 .. -cl->{c,}buffer range. It is meant to limit number of
493 * mode transitions per time unit. The speed gain is about 1/6.
495 static inline enum htb_cmode
496 htb_class_mode(struct htb_class *cl, long *diff)
500 if ((toks = (cl->ctokens + *diff)) < htb_lowater(cl)) {
502 return HTB_CANT_SEND;
505 if ((toks = (cl->tokens + *diff)) >= htb_hiwater(cl))
509 return HTB_MAY_BORROW;
513 * htb_change_class_mode - changes classe's mode
515 * This should be the only way how to change classe's mode under normal
516 * cirsumstances. Routine will update feed lists linkage, change mode
517 * and add class to the wait event queue if appropriate. New mode should
518 * be different from old one and cl->pq_key has to be valid if changing
519 * to mode other than HTB_CAN_SEND (see htb_add_to_wait_tree).
522 htb_change_class_mode(struct htb_sched *q, struct htb_class *cl, long *diff)
524 enum htb_cmode new_mode = htb_class_mode(cl, diff);
526 if (new_mode == cl->cmode)
529 if (cl->prio_activity) { /* not necessary: speed optimization */
530 if (cl->cmode != HTB_CANT_SEND)
531 htb_deactivate_prios(q, cl);
532 cl->cmode = new_mode;
533 if (new_mode != HTB_CANT_SEND)
534 htb_activate_prios(q, cl);
536 cl->cmode = new_mode;
540 * htb_activate - inserts leaf cl into appropriate active feeds
542 * Routine learns (new) priority of leaf and activates feed chain
543 * for the prio. It can be called on already active leaf safely.
544 * It also adds leaf into droplist.
546 static inline void htb_activate(struct htb_sched *q, struct htb_class *cl)
548 BUG_TRAP(!cl->level && cl->un.leaf.q && cl->un.leaf.q->q.qlen);
550 if (!cl->prio_activity) {
551 cl->prio_activity = 1 << (cl->un.leaf.aprio = cl->un.leaf.prio);
552 htb_activate_prios(q, cl);
553 list_add_tail(&cl->un.leaf.drop_list,
554 q->drops + cl->un.leaf.aprio);
559 * htb_deactivate - remove leaf cl from active feeds
561 * Make sure that leaf is active. In the other words it can't be called
562 * with non-active leaf. It also removes class from the drop list.
564 static inline void htb_deactivate(struct htb_sched *q, struct htb_class *cl)
566 BUG_TRAP(cl->prio_activity);
568 htb_deactivate_prios(q, cl);
569 cl->prio_activity = 0;
570 list_del_init(&cl->un.leaf.drop_list);
573 static int htb_enqueue(struct sk_buff *skb, struct Qdisc *sch)
576 struct htb_sched *q = qdisc_priv(sch);
577 struct htb_class *cl = htb_classify(skb, sch, &ret);
579 if (cl == HTB_DIRECT) {
580 /* enqueue to helper queue */
581 if (q->direct_queue.qlen < q->direct_qlen) {
582 __skb_queue_tail(&q->direct_queue, skb);
587 return NET_XMIT_DROP;
589 #ifdef CONFIG_NET_CLS_ACT
591 if (ret == NET_XMIT_BYPASS)
596 } else if (cl->un.leaf.q->enqueue(skb, cl->un.leaf.q) !=
600 return NET_XMIT_DROP;
602 cl->bstats.packets +=
603 skb_is_gso(skb)?skb_shinfo(skb)->gso_segs:1;
604 cl->bstats.bytes += skb->len;
609 sch->bstats.packets += skb_is_gso(skb)?skb_shinfo(skb)->gso_segs:1;
610 sch->bstats.bytes += skb->len;
611 return NET_XMIT_SUCCESS;
614 /* TODO: requeuing packet charges it to policers again !! */
615 static int htb_requeue(struct sk_buff *skb, struct Qdisc *sch)
618 struct htb_sched *q = qdisc_priv(sch);
619 struct htb_class *cl = htb_classify(skb, sch, &ret);
620 struct sk_buff *tskb;
622 if (cl == HTB_DIRECT) {
623 /* enqueue to helper queue */
624 if (q->direct_queue.qlen < q->direct_qlen) {
625 __skb_queue_head(&q->direct_queue, skb);
627 __skb_queue_head(&q->direct_queue, skb);
628 tskb = __skb_dequeue_tail(&q->direct_queue);
633 #ifdef CONFIG_NET_CLS_ACT
635 if (ret == NET_XMIT_BYPASS)
640 } else if (cl->un.leaf.q->ops->requeue(skb, cl->un.leaf.q) !=
644 return NET_XMIT_DROP;
649 sch->qstats.requeues++;
650 return NET_XMIT_SUCCESS;
654 * htb_charge_class - charges amount "bytes" to leaf and ancestors
656 * Routine assumes that packet "bytes" long was dequeued from leaf cl
657 * borrowing from "level". It accounts bytes to ceil leaky bucket for
658 * leaf and all ancestors and to rate bucket for ancestors at levels
659 * "level" and higher. It also handles possible change of mode resulting
660 * from the update. Note that mode can also increase here (MAY_BORROW to
661 * CAN_SEND) because we can use more precise clock that event queue here.
662 * In such case we remove class from event queue first.
664 static void htb_charge_class(struct htb_sched *q, struct htb_class *cl,
665 int level, struct sk_buff *skb)
667 int bytes = skb->len;
669 enum htb_cmode old_mode;
671 #define HTB_ACCNT(T,B,R) toks = diff + cl->T; \
672 if (toks > cl->B) toks = cl->B; \
673 toks -= L2T(cl, cl->R, bytes); \
674 if (toks <= -cl->mbuffer) toks = 1-cl->mbuffer; \
678 diff = psched_tdiff_bounded(q->now, cl->t_c, cl->mbuffer);
679 if (cl->level >= level) {
680 if (cl->level == level)
682 HTB_ACCNT(tokens, buffer, rate);
684 cl->xstats.borrows++;
685 cl->tokens += diff; /* we moved t_c; update tokens */
687 HTB_ACCNT(ctokens, cbuffer, ceil);
690 old_mode = cl->cmode;
692 htb_change_class_mode(q, cl, &diff);
693 if (old_mode != cl->cmode) {
694 if (old_mode != HTB_CAN_SEND)
695 htb_safe_rb_erase(&cl->pq_node, q->wait_pq + cl->level);
696 if (cl->cmode != HTB_CAN_SEND)
697 htb_add_to_wait_tree(q, cl, diff);
700 /* update byte stats except for leaves which are already updated */
702 cl->bstats.bytes += bytes;
703 cl->bstats.packets += skb_is_gso(skb)?
704 skb_shinfo(skb)->gso_segs:1;
711 * htb_do_events - make mode changes to classes at the level
713 * Scans event queue for pending events and applies them. Returns time of
714 * next pending event (0 for no event in pq).
715 * Note: Applied are events whose have cl->pq_key <= q->now.
717 static psched_time_t htb_do_events(struct htb_sched *q, int level)
719 /* don't run for longer than 2 jiffies; 2 is used instead of
720 1 to simplify things when jiffy is going to be incremented
722 unsigned long stop_at = jiffies + 2;
723 while (time_before(jiffies, stop_at)) {
724 struct htb_class *cl;
726 struct rb_node *p = rb_first(&q->wait_pq[level]);
731 cl = rb_entry(p, struct htb_class, pq_node);
732 if (cl->pq_key > q->now)
735 htb_safe_rb_erase(p, q->wait_pq + level);
736 diff = psched_tdiff_bounded(q->now, cl->t_c, cl->mbuffer);
737 htb_change_class_mode(q, cl, &diff);
738 if (cl->cmode != HTB_CAN_SEND)
739 htb_add_to_wait_tree(q, cl, diff);
741 /* too much load - let's continue on next jiffie */
742 return q->now + PSCHED_TICKS_PER_SEC / HZ;
745 /* Returns class->node+prio from id-tree where classe's id is >= id. NULL
746 is no such one exists. */
747 static struct rb_node *htb_id_find_next_upper(int prio, struct rb_node *n,
750 struct rb_node *r = NULL;
752 struct htb_class *cl =
753 rb_entry(n, struct htb_class, node[prio]);
754 if (id == cl->classid)
757 if (id > cl->classid) {
768 * htb_lookup_leaf - returns next leaf class in DRR order
770 * Find leaf where current feed pointers points to.
772 static struct htb_class *htb_lookup_leaf(struct rb_root *tree, int prio,
773 struct rb_node **pptr, u32 * pid)
777 struct rb_node *root;
778 struct rb_node **pptr;
780 } stk[TC_HTB_MAXDEPTH], *sp = stk;
782 BUG_TRAP(tree->rb_node);
783 sp->root = tree->rb_node;
787 for (i = 0; i < 65535; i++) {
788 if (!*sp->pptr && *sp->pid) {
789 /* ptr was invalidated but id is valid - try to recover
790 the original or next ptr */
792 htb_id_find_next_upper(prio, sp->root, *sp->pid);
794 *sp->pid = 0; /* ptr is valid now so that remove this hint as it
795 can become out of date quickly */
796 if (!*sp->pptr) { /* we are at right end; rewind & go up */
797 *sp->pptr = sp->root;
798 while ((*sp->pptr)->rb_left)
799 *sp->pptr = (*sp->pptr)->rb_left;
805 htb_next_rb_node(sp->pptr);
808 struct htb_class *cl;
809 cl = rb_entry(*sp->pptr, struct htb_class, node[prio]);
812 (++sp)->root = cl->un.inner.feed[prio].rb_node;
813 sp->pptr = cl->un.inner.ptr + prio;
814 sp->pid = cl->un.inner.last_ptr_id + prio;
821 /* dequeues packet at given priority and level; call only if
822 you are sure that there is active class at prio/level */
823 static struct sk_buff *htb_dequeue_tree(struct htb_sched *q, int prio,
826 struct sk_buff *skb = NULL;
827 struct htb_class *cl, *start;
828 /* look initial class up in the row */
829 start = cl = htb_lookup_leaf(q->row[level] + prio, prio,
830 q->ptr[level] + prio,
831 q->last_ptr_id[level] + prio);
839 /* class can be empty - it is unlikely but can be true if leaf
840 qdisc drops packets in enqueue routine or if someone used
841 graft operation on the leaf since last dequeue;
842 simply deactivate and skip such class */
843 if (unlikely(cl->un.leaf.q->q.qlen == 0)) {
844 struct htb_class *next;
845 htb_deactivate(q, cl);
847 /* row/level might become empty */
848 if ((q->row_mask[level] & (1 << prio)) == 0)
851 next = htb_lookup_leaf(q->row[level] + prio,
852 prio, q->ptr[level] + prio,
853 q->last_ptr_id[level] + prio);
855 if (cl == start) /* fix start if we just deleted it */
861 skb = cl->un.leaf.q->dequeue(cl->un.leaf.q);
862 if (likely(skb != NULL))
866 "htb: class %X isn't work conserving ?!\n",
871 htb_next_rb_node((level ? cl->parent->un.inner.ptr : q->
873 cl = htb_lookup_leaf(q->row[level] + prio, prio,
874 q->ptr[level] + prio,
875 q->last_ptr_id[level] + prio);
877 } while (cl != start);
879 if (likely(skb != NULL)) {
880 if ((cl->un.leaf.deficit[level] -= skb->len) < 0) {
881 cl->un.leaf.deficit[level] += cl->un.leaf.quantum;
882 htb_next_rb_node((level ? cl->parent->un.inner.ptr : q->
885 /* this used to be after charge_class but this constelation
886 gives us slightly better performance */
887 if (!cl->un.leaf.q->q.qlen)
888 htb_deactivate(q, cl);
889 htb_charge_class(q, cl, level, skb);
894 static struct sk_buff *htb_dequeue(struct Qdisc *sch)
896 struct sk_buff *skb = NULL;
897 struct htb_sched *q = qdisc_priv(sch);
899 psched_time_t next_event;
901 /* try to dequeue direct packets as high prio (!) to minimize cpu work */
902 skb = __skb_dequeue(&q->direct_queue);
904 sch->flags &= ~TCQ_F_THROTTLED;
911 q->now = psched_get_time();
913 next_event = q->now + 5 * PSCHED_TICKS_PER_SEC;
915 for (level = 0; level < TC_HTB_MAXDEPTH; level++) {
916 /* common case optimization - skip event handler quickly */
920 if (q->now >= q->near_ev_cache[level]) {
921 event = htb_do_events(q, level);
923 event = q->now + PSCHED_TICKS_PER_SEC;
924 q->near_ev_cache[level] = event;
926 event = q->near_ev_cache[level];
928 if (event && next_event > event)
931 m = ~q->row_mask[level];
932 while (m != (int)(-1)) {
935 skb = htb_dequeue_tree(q, prio, level);
936 if (likely(skb != NULL)) {
938 sch->flags &= ~TCQ_F_THROTTLED;
943 sch->qstats.overlimits++;
944 qdisc_watchdog_schedule(&q->watchdog, next_event);
949 /* try to drop from each class (by prio) until one succeed */
950 static unsigned int htb_drop(struct Qdisc *sch)
952 struct htb_sched *q = qdisc_priv(sch);
955 for (prio = TC_HTB_NUMPRIO - 1; prio >= 0; prio--) {
957 list_for_each(p, q->drops + prio) {
958 struct htb_class *cl = list_entry(p, struct htb_class,
961 if (cl->un.leaf.q->ops->drop &&
962 (len = cl->un.leaf.q->ops->drop(cl->un.leaf.q))) {
964 if (!cl->un.leaf.q->q.qlen)
965 htb_deactivate(q, cl);
973 /* reset all classes */
974 /* always caled under BH & queue lock */
975 static void htb_reset(struct Qdisc *sch)
977 struct htb_sched *q = qdisc_priv(sch);
980 for (i = 0; i < HTB_HSIZE; i++) {
981 struct hlist_node *p;
982 struct htb_class *cl;
984 hlist_for_each_entry(cl, p, q->hash + i, hlist) {
986 memset(&cl->un.inner, 0, sizeof(cl->un.inner));
989 qdisc_reset(cl->un.leaf.q);
990 INIT_LIST_HEAD(&cl->un.leaf.drop_list);
992 cl->prio_activity = 0;
993 cl->cmode = HTB_CAN_SEND;
997 qdisc_watchdog_cancel(&q->watchdog);
998 __skb_queue_purge(&q->direct_queue);
1000 memset(q->row, 0, sizeof(q->row));
1001 memset(q->row_mask, 0, sizeof(q->row_mask));
1002 memset(q->wait_pq, 0, sizeof(q->wait_pq));
1003 memset(q->ptr, 0, sizeof(q->ptr));
1004 for (i = 0; i < TC_HTB_NUMPRIO; i++)
1005 INIT_LIST_HEAD(q->drops + i);
1008 static const struct nla_policy htb_policy[TCA_HTB_MAX + 1] = {
1009 [TCA_HTB_PARMS] = { .len = sizeof(struct tc_htb_opt) },
1010 [TCA_HTB_INIT] = { .len = sizeof(struct tc_htb_glob) },
1011 [TCA_HTB_CTAB] = { .type = NLA_BINARY, .len = TC_RTAB_SIZE },
1012 [TCA_HTB_RTAB] = { .type = NLA_BINARY, .len = TC_RTAB_SIZE },
1015 static int htb_init(struct Qdisc *sch, struct nlattr *opt)
1017 struct htb_sched *q = qdisc_priv(sch);
1018 struct nlattr *tb[TCA_HTB_INIT + 1];
1019 struct tc_htb_glob *gopt;
1026 err = nla_parse_nested(tb, TCA_HTB_INIT, opt, htb_policy);
1030 if (tb[TCA_HTB_INIT] == NULL) {
1031 printk(KERN_ERR "HTB: hey probably you have bad tc tool ?\n");
1034 gopt = nla_data(tb[TCA_HTB_INIT]);
1035 if (gopt->version != HTB_VER >> 16) {
1037 "HTB: need tc/htb version %d (minor is %d), you have %d\n",
1038 HTB_VER >> 16, HTB_VER & 0xffff, gopt->version);
1042 INIT_LIST_HEAD(&q->root);
1043 for (i = 0; i < HTB_HSIZE; i++)
1044 INIT_HLIST_HEAD(q->hash + i);
1045 for (i = 0; i < TC_HTB_NUMPRIO; i++)
1046 INIT_LIST_HEAD(q->drops + i);
1048 qdisc_watchdog_init(&q->watchdog, sch);
1049 skb_queue_head_init(&q->direct_queue);
1051 q->direct_qlen = sch->dev->tx_queue_len;
1052 if (q->direct_qlen < 2) /* some devices have zero tx_queue_len */
1055 if ((q->rate2quantum = gopt->rate2quantum) < 1)
1056 q->rate2quantum = 1;
1057 q->defcls = gopt->defcls;
1062 static int htb_dump(struct Qdisc *sch, struct sk_buff *skb)
1064 struct htb_sched *q = qdisc_priv(sch);
1065 struct nlattr *nest;
1066 struct tc_htb_glob gopt;
1068 spin_lock_bh(&sch->dev->queue_lock);
1070 gopt.direct_pkts = q->direct_pkts;
1071 gopt.version = HTB_VER;
1072 gopt.rate2quantum = q->rate2quantum;
1073 gopt.defcls = q->defcls;
1076 nest = nla_nest_start(skb, TCA_OPTIONS);
1078 goto nla_put_failure;
1079 NLA_PUT(skb, TCA_HTB_INIT, sizeof(gopt), &gopt);
1080 nla_nest_end(skb, nest);
1082 spin_unlock_bh(&sch->dev->queue_lock);
1086 spin_unlock_bh(&sch->dev->queue_lock);
1087 nla_nest_cancel(skb, nest);
1091 static int htb_dump_class(struct Qdisc *sch, unsigned long arg,
1092 struct sk_buff *skb, struct tcmsg *tcm)
1094 struct htb_class *cl = (struct htb_class *)arg;
1095 struct nlattr *nest;
1096 struct tc_htb_opt opt;
1098 spin_lock_bh(&sch->dev->queue_lock);
1099 tcm->tcm_parent = cl->parent ? cl->parent->classid : TC_H_ROOT;
1100 tcm->tcm_handle = cl->classid;
1101 if (!cl->level && cl->un.leaf.q)
1102 tcm->tcm_info = cl->un.leaf.q->handle;
1104 nest = nla_nest_start(skb, TCA_OPTIONS);
1106 goto nla_put_failure;
1108 memset(&opt, 0, sizeof(opt));
1110 opt.rate = cl->rate->rate;
1111 opt.buffer = cl->buffer;
1112 opt.ceil = cl->ceil->rate;
1113 opt.cbuffer = cl->cbuffer;
1114 opt.quantum = cl->un.leaf.quantum;
1115 opt.prio = cl->un.leaf.prio;
1116 opt.level = cl->level;
1117 NLA_PUT(skb, TCA_HTB_PARMS, sizeof(opt), &opt);
1119 nla_nest_end(skb, nest);
1120 spin_unlock_bh(&sch->dev->queue_lock);
1124 spin_unlock_bh(&sch->dev->queue_lock);
1125 nla_nest_cancel(skb, nest);
1130 htb_dump_class_stats(struct Qdisc *sch, unsigned long arg, struct gnet_dump *d)
1132 struct htb_class *cl = (struct htb_class *)arg;
1134 if (!cl->level && cl->un.leaf.q)
1135 cl->qstats.qlen = cl->un.leaf.q->q.qlen;
1136 cl->xstats.tokens = cl->tokens;
1137 cl->xstats.ctokens = cl->ctokens;
1139 if (gnet_stats_copy_basic(d, &cl->bstats) < 0 ||
1140 gnet_stats_copy_rate_est(d, &cl->rate_est) < 0 ||
1141 gnet_stats_copy_queue(d, &cl->qstats) < 0)
1144 return gnet_stats_copy_app(d, &cl->xstats, sizeof(cl->xstats));
1147 static int htb_graft(struct Qdisc *sch, unsigned long arg, struct Qdisc *new,
1150 struct htb_class *cl = (struct htb_class *)arg;
1152 if (cl && !cl->level) {
1154 (new = qdisc_create_dflt(sch->dev, &pfifo_qdisc_ops,
1159 if ((*old = xchg(&cl->un.leaf.q, new)) != NULL) {
1160 qdisc_tree_decrease_qlen(*old, (*old)->q.qlen);
1163 sch_tree_unlock(sch);
1169 static struct Qdisc *htb_leaf(struct Qdisc *sch, unsigned long arg)
1171 struct htb_class *cl = (struct htb_class *)arg;
1172 return (cl && !cl->level) ? cl->un.leaf.q : NULL;
1175 static void htb_qlen_notify(struct Qdisc *sch, unsigned long arg)
1177 struct htb_class *cl = (struct htb_class *)arg;
1179 if (cl->un.leaf.q->q.qlen == 0)
1180 htb_deactivate(qdisc_priv(sch), cl);
1183 static unsigned long htb_get(struct Qdisc *sch, u32 classid)
1185 struct htb_class *cl = htb_find(classid, sch);
1188 return (unsigned long)cl;
1191 static inline int htb_parent_last_child(struct htb_class *cl)
1194 /* the root class */
1197 if (!(cl->parent->children.next == &cl->sibling &&
1198 cl->parent->children.prev == &cl->sibling))
1199 /* not the last child */
1205 static void htb_parent_to_leaf(struct htb_sched *q, struct htb_class *cl,
1206 struct Qdisc *new_q)
1208 struct htb_class *parent = cl->parent;
1210 BUG_TRAP(!cl->level && cl->un.leaf.q && !cl->prio_activity);
1212 if (parent->cmode != HTB_CAN_SEND)
1213 htb_safe_rb_erase(&parent->pq_node, q->wait_pq + parent->level);
1216 memset(&parent->un.inner, 0, sizeof(parent->un.inner));
1217 INIT_LIST_HEAD(&parent->un.leaf.drop_list);
1218 parent->un.leaf.q = new_q ? new_q : &noop_qdisc;
1219 parent->un.leaf.quantum = parent->quantum;
1220 parent->un.leaf.prio = parent->prio;
1221 parent->tokens = parent->buffer;
1222 parent->ctokens = parent->cbuffer;
1223 parent->t_c = psched_get_time();
1224 parent->cmode = HTB_CAN_SEND;
1227 static void htb_destroy_class(struct Qdisc *sch, struct htb_class *cl)
1230 BUG_TRAP(cl->un.leaf.q);
1231 qdisc_destroy(cl->un.leaf.q);
1233 gen_kill_estimator(&cl->bstats, &cl->rate_est);
1234 qdisc_put_rtab(cl->rate);
1235 qdisc_put_rtab(cl->ceil);
1237 tcf_destroy_chain(&cl->filter_list);
1241 /* always caled under BH & queue lock */
1242 static void htb_destroy(struct Qdisc *sch)
1244 struct htb_sched *q = qdisc_priv(sch);
1245 struct hlist_node *n, *next;
1246 struct htb_class *cl;
1249 qdisc_watchdog_cancel(&q->watchdog);
1250 /* This line used to be after htb_destroy_class call below
1251 and surprisingly it worked in 2.4. But it must precede it
1252 because filter need its target class alive to be able to call
1253 unbind_filter on it (without Oops). */
1254 tcf_destroy_chain(&q->filter_list);
1256 for (i = 0; i < HTB_HSIZE; i++) {
1257 hlist_for_each_entry(cl, n, q->hash + i, hlist)
1258 tcf_destroy_chain(&cl->filter_list);
1260 for (i = 0; i < HTB_HSIZE; i++) {
1261 hlist_for_each_entry_safe(cl, n, next, q->hash + i, hlist)
1262 htb_destroy_class(sch, cl);
1264 __skb_queue_purge(&q->direct_queue);
1267 static int htb_delete(struct Qdisc *sch, unsigned long arg)
1269 struct htb_sched *q = qdisc_priv(sch);
1270 struct htb_class *cl = (struct htb_class *)arg;
1272 struct Qdisc *new_q = NULL;
1275 // TODO: why don't allow to delete subtree ? references ? does
1276 // tc subsys quarantee us that in htb_destroy it holds no class
1277 // refs so that we can remove children safely there ?
1278 if (!list_empty(&cl->children) || cl->filter_cnt)
1281 if (!cl->level && htb_parent_last_child(cl)) {
1282 new_q = qdisc_create_dflt(sch->dev, &pfifo_qdisc_ops,
1283 cl->parent->classid);
1290 qlen = cl->un.leaf.q->q.qlen;
1291 qdisc_reset(cl->un.leaf.q);
1292 qdisc_tree_decrease_qlen(cl->un.leaf.q, qlen);
1295 /* delete from hash, sibling list and active */
1296 hlist_del(&cl->hlist);
1297 list_del(&cl->sibling);
1299 if (cl->prio_activity)
1300 htb_deactivate(q, cl);
1302 if (cl->cmode != HTB_CAN_SEND)
1303 htb_safe_rb_erase(&cl->pq_node, q->wait_pq + cl->level);
1306 htb_parent_to_leaf(q, cl, new_q);
1308 if (--cl->refcnt == 0)
1309 htb_destroy_class(sch, cl);
1311 sch_tree_unlock(sch);
1315 static void htb_put(struct Qdisc *sch, unsigned long arg)
1317 struct htb_class *cl = (struct htb_class *)arg;
1319 if (--cl->refcnt == 0)
1320 htb_destroy_class(sch, cl);
1323 static int htb_change_class(struct Qdisc *sch, u32 classid,
1324 u32 parentid, struct nlattr **tca,
1328 struct htb_sched *q = qdisc_priv(sch);
1329 struct htb_class *cl = (struct htb_class *)*arg, *parent;
1330 struct nlattr *opt = tca[TCA_OPTIONS];
1331 struct qdisc_rate_table *rtab = NULL, *ctab = NULL;
1332 struct nlattr *tb[TCA_HTB_RTAB + 1];
1333 struct tc_htb_opt *hopt;
1335 /* extract all subattrs from opt attr */
1339 err = nla_parse_nested(tb, TCA_HTB_RTAB, opt, htb_policy);
1344 if (tb[TCA_HTB_PARMS] == NULL)
1347 parent = parentid == TC_H_ROOT ? NULL : htb_find(parentid, sch);
1349 hopt = nla_data(tb[TCA_HTB_PARMS]);
1351 rtab = qdisc_get_rtab(&hopt->rate, tb[TCA_HTB_RTAB]);
1352 ctab = qdisc_get_rtab(&hopt->ceil, tb[TCA_HTB_CTAB]);
1356 if (!cl) { /* new class */
1357 struct Qdisc *new_q;
1361 struct gnet_estimator opt;
1364 .nla_len = nla_attr_size(sizeof(est.opt)),
1365 .nla_type = TCA_RATE,
1368 /* 4s interval, 16s averaging constant */
1374 /* check for valid classid */
1375 if (!classid || TC_H_MAJ(classid ^ sch->handle)
1376 || htb_find(classid, sch))
1379 /* check maximal depth */
1380 if (parent && parent->parent && parent->parent->level < 2) {
1381 printk(KERN_ERR "htb: tree is too deep\n");
1385 if ((cl = kzalloc(sizeof(*cl), GFP_KERNEL)) == NULL)
1388 gen_new_estimator(&cl->bstats, &cl->rate_est,
1389 &sch->dev->queue_lock,
1390 tca[TCA_RATE] ? : &est.nla);
1392 INIT_LIST_HEAD(&cl->sibling);
1393 INIT_HLIST_NODE(&cl->hlist);
1394 INIT_LIST_HEAD(&cl->children);
1395 INIT_LIST_HEAD(&cl->un.leaf.drop_list);
1396 RB_CLEAR_NODE(&cl->pq_node);
1398 for (prio = 0; prio < TC_HTB_NUMPRIO; prio++)
1399 RB_CLEAR_NODE(&cl->node[prio]);
1401 /* create leaf qdisc early because it uses kmalloc(GFP_KERNEL)
1402 so that can't be used inside of sch_tree_lock
1403 -- thanks to Karlis Peisenieks */
1404 new_q = qdisc_create_dflt(sch->dev, &pfifo_qdisc_ops, classid);
1406 if (parent && !parent->level) {
1407 unsigned int qlen = parent->un.leaf.q->q.qlen;
1409 /* turn parent into inner node */
1410 qdisc_reset(parent->un.leaf.q);
1411 qdisc_tree_decrease_qlen(parent->un.leaf.q, qlen);
1412 qdisc_destroy(parent->un.leaf.q);
1413 if (parent->prio_activity)
1414 htb_deactivate(q, parent);
1416 /* remove from evt list because of level change */
1417 if (parent->cmode != HTB_CAN_SEND) {
1418 htb_safe_rb_erase(&parent->pq_node, q->wait_pq);
1419 parent->cmode = HTB_CAN_SEND;
1421 parent->level = (parent->parent ? parent->parent->level
1422 : TC_HTB_MAXDEPTH) - 1;
1423 memset(&parent->un.inner, 0, sizeof(parent->un.inner));
1425 /* leaf (we) needs elementary qdisc */
1426 cl->un.leaf.q = new_q ? new_q : &noop_qdisc;
1428 cl->classid = classid;
1429 cl->parent = parent;
1431 /* set class to be in HTB_CAN_SEND state */
1432 cl->tokens = hopt->buffer;
1433 cl->ctokens = hopt->cbuffer;
1434 cl->mbuffer = 60 * PSCHED_TICKS_PER_SEC; /* 1min */
1435 cl->t_c = psched_get_time();
1436 cl->cmode = HTB_CAN_SEND;
1438 /* attach to the hash list and parent's family */
1439 hlist_add_head(&cl->hlist, q->hash + htb_hash(classid));
1440 list_add_tail(&cl->sibling,
1441 parent ? &parent->children : &q->root);
1444 gen_replace_estimator(&cl->bstats, &cl->rate_est,
1445 &sch->dev->queue_lock,
1450 /* it used to be a nasty bug here, we have to check that node
1451 is really leaf before changing cl->un.leaf ! */
1453 cl->un.leaf.quantum = rtab->rate.rate / q->rate2quantum;
1454 if (!hopt->quantum && cl->un.leaf.quantum < 1000) {
1456 "HTB: quantum of class %X is small. Consider r2q change.\n",
1458 cl->un.leaf.quantum = 1000;
1460 if (!hopt->quantum && cl->un.leaf.quantum > 200000) {
1462 "HTB: quantum of class %X is big. Consider r2q change.\n",
1464 cl->un.leaf.quantum = 200000;
1467 cl->un.leaf.quantum = hopt->quantum;
1468 if ((cl->un.leaf.prio = hopt->prio) >= TC_HTB_NUMPRIO)
1469 cl->un.leaf.prio = TC_HTB_NUMPRIO - 1;
1471 /* backup for htb_parent_to_leaf */
1472 cl->quantum = cl->un.leaf.quantum;
1473 cl->prio = cl->un.leaf.prio;
1476 cl->buffer = hopt->buffer;
1477 cl->cbuffer = hopt->cbuffer;
1479 qdisc_put_rtab(cl->rate);
1482 qdisc_put_rtab(cl->ceil);
1484 sch_tree_unlock(sch);
1486 *arg = (unsigned long)cl;
1491 qdisc_put_rtab(rtab);
1493 qdisc_put_rtab(ctab);
1497 static struct tcf_proto **htb_find_tcf(struct Qdisc *sch, unsigned long arg)
1499 struct htb_sched *q = qdisc_priv(sch);
1500 struct htb_class *cl = (struct htb_class *)arg;
1501 struct tcf_proto **fl = cl ? &cl->filter_list : &q->filter_list;
1506 static unsigned long htb_bind_filter(struct Qdisc *sch, unsigned long parent,
1509 struct htb_sched *q = qdisc_priv(sch);
1510 struct htb_class *cl = htb_find(classid, sch);
1512 /*if (cl && !cl->level) return 0;
1513 The line above used to be there to prevent attaching filters to
1514 leaves. But at least tc_index filter uses this just to get class
1515 for other reasons so that we have to allow for it.
1517 19.6.2002 As Werner explained it is ok - bind filter is just
1518 another way to "lock" the class - unlike "get" this lock can
1519 be broken by class during destroy IIUC.
1525 return (unsigned long)cl;
1528 static void htb_unbind_filter(struct Qdisc *sch, unsigned long arg)
1530 struct htb_sched *q = qdisc_priv(sch);
1531 struct htb_class *cl = (struct htb_class *)arg;
1539 static void htb_walk(struct Qdisc *sch, struct qdisc_walker *arg)
1541 struct htb_sched *q = qdisc_priv(sch);
1547 for (i = 0; i < HTB_HSIZE; i++) {
1548 struct hlist_node *p;
1549 struct htb_class *cl;
1551 hlist_for_each_entry(cl, p, q->hash + i, hlist) {
1552 if (arg->count < arg->skip) {
1556 if (arg->fn(sch, (unsigned long)cl, arg) < 0) {
1565 static const struct Qdisc_class_ops htb_class_ops = {
1568 .qlen_notify = htb_qlen_notify,
1571 .change = htb_change_class,
1572 .delete = htb_delete,
1574 .tcf_chain = htb_find_tcf,
1575 .bind_tcf = htb_bind_filter,
1576 .unbind_tcf = htb_unbind_filter,
1577 .dump = htb_dump_class,
1578 .dump_stats = htb_dump_class_stats,
1581 static struct Qdisc_ops htb_qdisc_ops __read_mostly = {
1583 .cl_ops = &htb_class_ops,
1585 .priv_size = sizeof(struct htb_sched),
1586 .enqueue = htb_enqueue,
1587 .dequeue = htb_dequeue,
1588 .requeue = htb_requeue,
1592 .destroy = htb_destroy,
1593 .change = NULL /* htb_change */,
1595 .owner = THIS_MODULE,
1598 static int __init htb_module_init(void)
1600 return register_qdisc(&htb_qdisc_ops);
1602 static void __exit htb_module_exit(void)
1604 unregister_qdisc(&htb_qdisc_ops);
1607 module_init(htb_module_init)
1608 module_exit(htb_module_exit)
1609 MODULE_LICENSE("GPL");