xref: /linux/net/sched/sch_htb.c (revision 67f8bc848ee31831336bd478e57d2f993551902e)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * net/sched/sch_htb.c	Hierarchical token bucket, feed tree version
4  *
5  * Authors:	Martin Devera, <devik@cdi.cz>
6  *
7  * Credits (in time order) for older HTB versions:
8  *              Stef Coene <stef.coene@docum.org>
9  *			HTB support at LARTC mailing list
10  *		Ondrej Kraus, <krauso@barr.cz>
11  *			found missing INIT_QDISC(htb)
12  *		Vladimir Smelhaus, Aamer Akhter, Bert Hubert
13  *			helped a lot to locate nasty class stall bug
14  *		Andi Kleen, Jamal Hadi, Bert Hubert
15  *			code review and helpful comments on shaping
16  *		Tomasz Wrona, <tw@eter.tym.pl>
17  *			created test case so that I was able to fix nasty bug
18  *		Wilfried Weissmann
19  *			spotted bug in dequeue code and helped with fix
20  *		Jiri Fojtasek
21  *			fixed requeue routine
22  *		and many others. thanks.
23  */
24 #include <linux/module.h>
25 #include <linux/moduleparam.h>
26 #include <linux/types.h>
27 #include <linux/kernel.h>
28 #include <linux/string.h>
29 #include <linux/errno.h>
30 #include <linux/skbuff.h>
31 #include <linux/list.h>
32 #include <linux/compiler.h>
33 #include <linux/rbtree.h>
34 #include <linux/workqueue.h>
35 #include <linux/slab.h>
36 #include <net/netlink.h>
37 #include <net/sch_generic.h>
38 #include <net/pkt_sched.h>
39 #include <net/pkt_cls.h>
40 
41 /* HTB algorithm.
42     Author: devik@cdi.cz
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.
47 
48     Levels:
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.
52 */
53 
54 static int htb_hysteresis __read_mostly = 0; /* whether to use mode hysteresis for speedup */
55 #define HTB_VER 0x30011		/* major must be matched with number supplied by TC as version */
56 
57 #if HTB_VER >> 16 != TC_HTB_PROTOVER
58 #error "Mismatched sch_htb.c and pkt_sch.h"
59 #endif
60 
61 /* Module parameter and sysfs export */
62 module_param    (htb_hysteresis, int, 0640);
63 MODULE_PARM_DESC(htb_hysteresis, "Hysteresis mode, less CPU load, less accurate");
64 
65 static int htb_rate_est = 0; /* htb classes have a default rate estimator */
66 module_param(htb_rate_est, int, 0640);
67 MODULE_PARM_DESC(htb_rate_est, "setup a default rate estimator (4sec 16sec) for htb classes");
68 
69 /* used internaly to keep status of single class */
70 enum htb_cmode {
71 	HTB_CANT_SEND,		/* class can't send and can't borrow */
72 	HTB_MAY_BORROW,		/* class can't send but may borrow */
73 	HTB_CAN_SEND		/* class can send */
74 };
75 
76 struct htb_prio {
77 	union {
78 		struct rb_root	row;
79 		struct rb_root	feed;
80 	};
81 	struct rb_node	*ptr;
82 	/* When class changes from state 1->2 and disconnects from
83 	 * parent's feed then we lost ptr value and start from the
84 	 * first child again. Here we store classid of the
85 	 * last valid ptr (used when ptr is NULL).
86 	 */
87 	u32		last_ptr_id;
88 };
89 
90 /* interior & leaf nodes; props specific to leaves are marked L:
91  * To reduce false sharing, place mostly read fields at beginning,
92  * and mostly written ones at the end.
93  */
94 struct htb_class {
95 	struct Qdisc_class_common common;
96 	struct psched_ratecfg	rate;
97 	struct psched_ratecfg	ceil;
98 	s64			buffer, cbuffer;/* token bucket depth/rate */
99 	s64			mbuffer;	/* max wait time */
100 	u32			prio;		/* these two are used only by leaves... */
101 	int			quantum;	/* but stored for parent-to-leaf return */
102 
103 	struct tcf_proto __rcu	*filter_list;	/* class attached filters */
104 	struct tcf_block	*block;
105 
106 	int			level;		/* our level (see above) */
107 	unsigned int		children;
108 	struct htb_class	*parent;	/* parent class */
109 
110 	struct net_rate_estimator __rcu *rate_est;
111 
112 	/*
113 	 * Written often fields
114 	 */
115 	struct gnet_stats_basic_sync bstats;
116 	struct gnet_stats_basic_sync bstats_bias;
117 	u32			xstats_lends;
118 	u32			xstats_borrows;
119 
120 	/* token bucket parameters */
121 	s64			tokens, ctokens;/* current number of tokens */
122 	s64			t_c;		/* checkpoint time */
123 
124 	union {
125 		struct htb_class_leaf {
126 			int		deficit[TC_HTB_MAXDEPTH];
127 			struct Qdisc	*q;
128 			struct netdev_queue *offload_queue;
129 		} leaf;
130 		struct htb_class_inner {
131 			struct htb_prio clprio[TC_HTB_NUMPRIO];
132 		} inner;
133 	};
134 	s64			pq_key;
135 
136 	int			prio_activity;	/* for which prios are we active */
137 	enum htb_cmode		cmode;		/* current mode of the class */
138 	struct rb_node		pq_node;	/* node for event queue */
139 	struct rb_node		node[TC_HTB_NUMPRIO];	/* node for self or feed tree */
140 
141 	unsigned int drops ____cacheline_aligned_in_smp;
142 	unsigned int		overlimits;
143 };
144 
145 struct htb_level {
146 	struct rb_root	wait_pq;
147 	struct htb_prio hprio[TC_HTB_NUMPRIO];
148 };
149 
150 struct htb_sched {
151 	struct Qdisc_class_hash clhash;
152 	int			defcls;		/* class where unclassified flows go to */
153 	int			rate2quantum;	/* quant = rate / rate2quantum */
154 
155 	/* filters for qdisc itself */
156 	struct tcf_proto __rcu	*filter_list;
157 	struct tcf_block	*block;
158 
159 #define HTB_WARN_TOOMANYEVENTS	0x1
160 	unsigned int		warned;	/* only one warning */
161 	int			direct_qlen;
162 	struct work_struct	work;
163 
164 	/* non shaped skbs; let them go directly thru */
165 	struct qdisc_skb_head	direct_queue;
166 	u32			direct_pkts;
167 	u32			overlimits;
168 
169 	struct qdisc_watchdog	watchdog;
170 
171 	s64			now;	/* cached dequeue time */
172 
173 	/* time of nearest event per level (row) */
174 	s64			near_ev_cache[TC_HTB_MAXDEPTH];
175 
176 	int			row_mask[TC_HTB_MAXDEPTH];
177 
178 	struct htb_level	hlevel[TC_HTB_MAXDEPTH];
179 
180 	struct Qdisc		**direct_qdiscs;
181 	unsigned int            num_direct_qdiscs;
182 
183 	bool			offload;
184 };
185 
186 /* find class in global hash table using given handle */
187 static inline struct htb_class *htb_find(u32 handle, struct Qdisc *sch)
188 {
189 	struct htb_sched *q = qdisc_priv(sch);
190 	struct Qdisc_class_common *clc;
191 
192 	clc = qdisc_class_find(&q->clhash, handle);
193 	if (clc == NULL)
194 		return NULL;
195 	return container_of(clc, struct htb_class, common);
196 }
197 
198 static unsigned long htb_search(struct Qdisc *sch, u32 handle)
199 {
200 	return (unsigned long)htb_find(handle, sch);
201 }
202 
203 #define HTB_DIRECT ((struct htb_class *)-1L)
204 
205 /**
206  * htb_classify - classify a packet into class
207  * @skb: the socket buffer
208  * @sch: the active queue discipline
209  * @qerr: pointer for returned status code
210  *
211  * It returns NULL if the packet should be dropped or -1 if the packet
212  * should be passed directly thru. In all other cases leaf class is returned.
213  * We allow direct class selection by classid in priority. The we examine
214  * filters in qdisc and in inner nodes (if higher filter points to the inner
215  * node). If we end up with classid MAJOR:0 we enqueue the skb into special
216  * internal fifo (direct). These packets then go directly thru. If we still
217  * have no valid leaf we try to use MAJOR:default leaf. It still unsuccessful
218  * then finish and return direct queue.
219  */
220 static struct htb_class *htb_classify(struct sk_buff *skb, struct Qdisc *sch,
221 				      int *qerr)
222 {
223 	struct htb_sched *q = qdisc_priv(sch);
224 	struct htb_class *cl;
225 	struct tcf_result res;
226 	struct tcf_proto *tcf;
227 	unsigned int hops = 0;
228 	int result;
229 
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
232 	 * rules in it
233 	 */
234 	if (skb->priority == sch->handle)
235 		return HTB_DIRECT;	/* X:0 (direct flow) selected */
236 	cl = htb_find(skb->priority, sch);
237 	if (cl) {
238 		if (cl->level == 0)
239 			return cl;
240 		/* Start with inner filter chain if a non-leaf class is selected */
241 		tcf = rcu_dereference_bh(cl->filter_list);
242 	} else {
243 		tcf = rcu_dereference_bh(q->filter_list);
244 	}
245 
246 	*qerr = NET_XMIT_SUCCESS | __NET_XMIT_BYPASS;
247 	while (tcf && (result = tcf_classify_qdisc(skb, tcf, &res, false)) >= 0) {
248 #ifdef CONFIG_NET_CLS_ACT
249 		switch (result) {
250 		case TC_ACT_QUEUED:
251 		case TC_ACT_STOLEN:
252 		case TC_ACT_TRAP:
253 			*qerr = NET_XMIT_SUCCESS | __NET_XMIT_STOLEN;
254 			fallthrough;
255 		case TC_ACT_SHOT:
256 			return NULL;
257 		}
258 #endif
259 		cl = (void *)res.class;
260 		if (!cl) {
261 			if (res.classid == sch->handle)
262 				return HTB_DIRECT;	/* X:0 (direct flow) */
263 			cl = htb_find(res.classid, sch);
264 			if (!cl)
265 				break;	/* filter selected invalid classid */
266 		}
267 		if (!cl->level)
268 			return cl;	/* we hit leaf; return it */
269 
270 		if (++hops > TC_HTB_MAXDEPTH) {
271 			pr_warn_ratelimited("htb: classify loop detected, dropping packet\n");
272 			return NULL;
273 		}
274 		/* we have got inner class; apply inner filter chain */
275 		tcf = rcu_dereference_bh(cl->filter_list);
276 	}
277 	/* classification failed; try to use default class */
278 	cl = htb_find(TC_H_MAKE(TC_H_MAJ(sch->handle), q->defcls), sch);
279 	if (!cl || cl->level)
280 		return HTB_DIRECT;	/* bad default .. this is safe bet */
281 	return cl;
282 }
283 
284 /**
285  * htb_add_to_id_tree - adds class to the round robin list
286  * @root: the root of the tree
287  * @cl: the class to add
288  * @prio: the give prio in class
289  *
290  * Routine adds class to the list (actually tree) sorted by classid.
291  * Make sure that class is not already on such list for given prio.
292  */
293 static void htb_add_to_id_tree(struct rb_root *root,
294 			       struct htb_class *cl, int prio)
295 {
296 	struct rb_node **p = &root->rb_node, *parent = NULL;
297 
298 	while (*p) {
299 		struct htb_class *c;
300 		parent = *p;
301 		c = rb_entry(parent, struct htb_class, node[prio]);
302 
303 		if (cl->common.classid > c->common.classid)
304 			p = &parent->rb_right;
305 		else
306 			p = &parent->rb_left;
307 	}
308 	rb_link_node(&cl->node[prio], parent, p);
309 	rb_insert_color(&cl->node[prio], root);
310 }
311 
312 /**
313  * htb_add_to_wait_tree - adds class to the event queue with delay
314  * @q: the priority event queue
315  * @cl: the class to add
316  * @delay: delay in microseconds
317  *
318  * The class is added to priority event queue to indicate that class will
319  * change its mode in cl->pq_key microseconds. Make sure that class is not
320  * already in the queue.
321  */
322 static void htb_add_to_wait_tree(struct htb_sched *q,
323 				 struct htb_class *cl, s64 delay)
324 {
325 	struct rb_node **p = &q->hlevel[cl->level].wait_pq.rb_node, *parent = NULL;
326 
327 	cl->pq_key = q->now + delay;
328 	if (cl->pq_key == q->now)
329 		cl->pq_key++;
330 
331 	/* update the nearest event cache */
332 	if (q->near_ev_cache[cl->level] > cl->pq_key)
333 		q->near_ev_cache[cl->level] = cl->pq_key;
334 
335 	while (*p) {
336 		struct htb_class *c;
337 		parent = *p;
338 		c = rb_entry(parent, struct htb_class, pq_node);
339 		if (cl->pq_key >= c->pq_key)
340 			p = &parent->rb_right;
341 		else
342 			p = &parent->rb_left;
343 	}
344 	rb_link_node(&cl->pq_node, parent, p);
345 	rb_insert_color(&cl->pq_node, &q->hlevel[cl->level].wait_pq);
346 }
347 
348 /**
349  * htb_next_rb_node - finds next node in binary tree
350  * @n: the current node in binary tree
351  *
352  * When we are past last key we return NULL.
353  * Average complexity is 2 steps per call.
354  */
355 static inline void htb_next_rb_node(struct rb_node **n)
356 {
357 	if (*n)
358 		*n = rb_next(*n);
359 }
360 
361 /**
362  * htb_add_class_to_row - add class to its row
363  * @q: the priority event queue
364  * @cl: the class to add
365  * @mask: the given priorities in class in bitmap
366  *
367  * The class is added to row at priorities marked in mask.
368  * It does nothing if mask == 0.
369  */
370 static inline void htb_add_class_to_row(struct htb_sched *q,
371 					struct htb_class *cl, int mask)
372 {
373 	q->row_mask[cl->level] |= mask;
374 	while (mask) {
375 		int prio = ffz(~mask);
376 		mask &= ~(1 << prio);
377 		htb_add_to_id_tree(&q->hlevel[cl->level].hprio[prio].row, cl, prio);
378 	}
379 }
380 
381 /* If this triggers, it is a bug in this code, but it need not be fatal */
382 static void htb_safe_rb_erase(struct rb_node *rb, struct rb_root *root)
383 {
384 	if (RB_EMPTY_NODE(rb)) {
385 		WARN_ON(1);
386 	} else {
387 		rb_erase(rb, root);
388 		RB_CLEAR_NODE(rb);
389 	}
390 }
391 
392 
393 /**
394  * htb_remove_class_from_row - removes class from its row
395  * @q: the priority event queue
396  * @cl: the class to add
397  * @mask: the given priorities in class in bitmap
398  *
399  * The class is removed from row at priorities marked in mask.
400  * It does nothing if mask == 0.
401  */
402 static inline void htb_remove_class_from_row(struct htb_sched *q,
403 						 struct htb_class *cl, int mask)
404 {
405 	int m = 0;
406 	struct htb_level *hlevel = &q->hlevel[cl->level];
407 
408 	while (mask) {
409 		int prio = ffz(~mask);
410 		struct htb_prio *hprio = &hlevel->hprio[prio];
411 
412 		mask &= ~(1 << prio);
413 		if (hprio->ptr == cl->node + prio)
414 			htb_next_rb_node(&hprio->ptr);
415 
416 		htb_safe_rb_erase(cl->node + prio, &hprio->row);
417 		if (!hprio->row.rb_node)
418 			m |= 1 << prio;
419 	}
420 	q->row_mask[cl->level] &= ~m;
421 }
422 
423 /**
424  * htb_activate_prios - creates active classe's feed chain
425  * @q: the priority event queue
426  * @cl: the class to activate
427  *
428  * The class is connected to ancestors and/or appropriate rows
429  * for priorities it is participating on. cl->cmode must be new
430  * (activated) mode. It does nothing if cl->prio_activity == 0.
431  */
432 static void htb_activate_prios(struct htb_sched *q, struct htb_class *cl)
433 {
434 	struct htb_class *p = cl->parent;
435 	long m, mask = cl->prio_activity;
436 
437 	while (cl->cmode == HTB_MAY_BORROW && p && mask) {
438 		m = mask;
439 		while (m) {
440 			unsigned int prio = ffz(~m);
441 
442 			if (WARN_ON_ONCE(prio >= ARRAY_SIZE(p->inner.clprio)))
443 				break;
444 			m &= ~(1 << prio);
445 
446 			if (p->inner.clprio[prio].feed.rb_node)
447 				/* parent already has its feed in use so that
448 				 * reset bit in mask as parent is already ok
449 				 */
450 				mask &= ~(1 << prio);
451 
452 			htb_add_to_id_tree(&p->inner.clprio[prio].feed, cl, prio);
453 		}
454 		p->prio_activity |= mask;
455 		cl = p;
456 		p = cl->parent;
457 
458 	}
459 	if (cl->cmode == HTB_CAN_SEND && mask)
460 		htb_add_class_to_row(q, cl, mask);
461 }
462 
463 /**
464  * htb_deactivate_prios - remove class from feed chain
465  * @q: the priority event queue
466  * @cl: the class to deactivate
467  *
468  * cl->cmode must represent old mode (before deactivation). It does
469  * nothing if cl->prio_activity == 0. Class is removed from all feed
470  * chains and rows.
471  */
472 static void htb_deactivate_prios(struct htb_sched *q, struct htb_class *cl)
473 {
474 	struct htb_class *p = cl->parent;
475 	long m, mask = cl->prio_activity;
476 
477 	while (cl->cmode == HTB_MAY_BORROW && p && mask) {
478 		m = mask;
479 		mask = 0;
480 		while (m) {
481 			int prio = ffz(~m);
482 			m &= ~(1 << prio);
483 
484 			if (p->inner.clprio[prio].ptr == cl->node + prio) {
485 				/* we are removing child which is pointed to from
486 				 * parent feed - forget the pointer but remember
487 				 * classid
488 				 */
489 				p->inner.clprio[prio].last_ptr_id = cl->common.classid;
490 				p->inner.clprio[prio].ptr = NULL;
491 			}
492 
493 			htb_safe_rb_erase(cl->node + prio,
494 					  &p->inner.clprio[prio].feed);
495 
496 			if (!p->inner.clprio[prio].feed.rb_node)
497 				mask |= 1 << prio;
498 		}
499 
500 		p->prio_activity &= ~mask;
501 		cl = p;
502 		p = cl->parent;
503 
504 	}
505 	if (cl->cmode == HTB_CAN_SEND && mask)
506 		htb_remove_class_from_row(q, cl, mask);
507 }
508 
509 static inline s64 htb_lowater(const struct htb_class *cl)
510 {
511 	if (htb_hysteresis)
512 		return cl->cmode != HTB_CANT_SEND ? -cl->cbuffer : 0;
513 	else
514 		return 0;
515 }
516 static inline s64 htb_hiwater(const struct htb_class *cl)
517 {
518 	if (htb_hysteresis)
519 		return cl->cmode == HTB_CAN_SEND ? -cl->buffer : 0;
520 	else
521 		return 0;
522 }
523 
524 
525 /**
526  * htb_class_mode - computes and returns current class mode
527  * @cl: the target class
528  * @diff: diff time in microseconds
529  *
530  * It computes cl's mode at time cl->t_c+diff and returns it. If mode
531  * is not HTB_CAN_SEND then cl->pq_key is updated to time difference
532  * from now to time when cl will change its state.
533  * Also it is worth to note that class mode doesn't change simply
534  * at cl->{c,}tokens == 0 but there can rather be hysteresis of
535  * 0 .. -cl->{c,}buffer range. It is meant to limit number of
536  * mode transitions per time unit. The speed gain is about 1/6.
537  */
538 static inline enum htb_cmode
539 htb_class_mode(struct htb_class *cl, s64 *diff)
540 {
541 	s64 toks;
542 
543 	if ((toks = (cl->ctokens + *diff)) < htb_lowater(cl)) {
544 		*diff = -toks;
545 		return HTB_CANT_SEND;
546 	}
547 
548 	if ((toks = (cl->tokens + *diff)) >= htb_hiwater(cl))
549 		return HTB_CAN_SEND;
550 
551 	*diff = -toks;
552 	return HTB_MAY_BORROW;
553 }
554 
555 /**
556  * htb_change_class_mode - changes classe's mode
557  * @q: the priority event queue
558  * @cl: the target class
559  * @diff: diff time in microseconds
560  *
561  * This should be the only way how to change classe's mode under normal
562  * circumstances. Routine will update feed lists linkage, change mode
563  * and add class to the wait event queue if appropriate. New mode should
564  * be different from old one and cl->pq_key has to be valid if changing
565  * to mode other than HTB_CAN_SEND (see htb_add_to_wait_tree).
566  */
567 static void
568 htb_change_class_mode(struct htb_sched *q, struct htb_class *cl, s64 *diff)
569 {
570 	enum htb_cmode new_mode = htb_class_mode(cl, diff);
571 
572 	if (new_mode == cl->cmode)
573 		return;
574 
575 	if (new_mode == HTB_CANT_SEND) {
576 		WRITE_ONCE(cl->overlimits, cl->overlimits + 1);
577 		WRITE_ONCE(q->overlimits, q->overlimits + 1);
578 	}
579 
580 	if (cl->prio_activity) {	/* not necessary: speed optimization */
581 		if (cl->cmode != HTB_CANT_SEND)
582 			htb_deactivate_prios(q, cl);
583 		cl->cmode = new_mode;
584 		if (new_mode != HTB_CANT_SEND)
585 			htb_activate_prios(q, cl);
586 	} else
587 		cl->cmode = new_mode;
588 }
589 
590 /**
591  * htb_activate - inserts leaf cl into appropriate active feeds
592  * @q: the priority event queue
593  * @cl: the target class
594  *
595  * Routine learns (new) priority of leaf and activates feed chain
596  * for the prio. It can be called on already active leaf safely.
597  * It also adds leaf into droplist.
598  */
599 static inline void htb_activate(struct htb_sched *q, struct htb_class *cl)
600 {
601 	WARN_ON(cl->level || !cl->leaf.q);
602 
603 	if (!cl->prio_activity) {
604 		cl->prio_activity = 1 << cl->prio;
605 		htb_activate_prios(q, cl);
606 	}
607 }
608 
609 /**
610  * htb_deactivate - remove leaf cl from active feeds
611  * @q: the priority event queue
612  * @cl: the target class
613  *
614  * Make sure that leaf is active. In the other words it can't be called
615  * with non-active leaf. It also removes class from the drop list.
616  */
617 static inline void htb_deactivate(struct htb_sched *q, struct htb_class *cl)
618 {
619 	if (!cl->prio_activity)
620 		return;
621 	htb_deactivate_prios(q, cl);
622 	cl->prio_activity = 0;
623 }
624 
625 static int htb_enqueue(struct sk_buff *skb, struct Qdisc *sch,
626 		       struct sk_buff **to_free)
627 {
628 	int ret;
629 	unsigned int len = qdisc_pkt_len(skb);
630 	struct htb_sched *q = qdisc_priv(sch);
631 	struct htb_class *cl = htb_classify(skb, sch, &ret);
632 
633 	if (cl == HTB_DIRECT) {
634 		/* enqueue to helper queue */
635 		if (q->direct_queue.qlen < q->direct_qlen) {
636 			__qdisc_enqueue_tail(skb, &q->direct_queue);
637 			WRITE_ONCE(q->direct_pkts, q->direct_pkts + 1);
638 		} else {
639 			return qdisc_drop(skb, sch, to_free);
640 		}
641 	} else if (!cl) {
642 		if (ret & __NET_XMIT_BYPASS)
643 			qdisc_qstats_drop(sch);
644 		__qdisc_drop(skb, to_free);
645 		return ret;
646 	} else if ((ret = qdisc_enqueue(skb, cl->leaf.q,
647 					to_free)) != NET_XMIT_SUCCESS) {
648 		if (net_xmit_drop_count(ret)) {
649 			qdisc_qstats_drop(sch);
650 			WRITE_ONCE(cl->drops, cl->drops + 1);
651 		}
652 		return ret;
653 	} else {
654 		htb_activate(q, cl);
655 	}
656 
657 	qstats_backlog_add(sch, len);
658 	qdisc_qlen_inc(sch);
659 	return NET_XMIT_SUCCESS;
660 }
661 
662 static inline void htb_accnt_tokens(struct htb_class *cl, int bytes, s64 diff)
663 {
664 	s64 toks = diff + cl->tokens;
665 
666 	if (toks > cl->buffer)
667 		toks = cl->buffer;
668 	toks -= (s64) psched_l2t_ns(&cl->rate, bytes);
669 	if (toks <= -cl->mbuffer)
670 		toks = 1 - cl->mbuffer;
671 
672 	WRITE_ONCE(cl->tokens, toks);
673 }
674 
675 static inline void htb_accnt_ctokens(struct htb_class *cl, int bytes, s64 diff)
676 {
677 	s64 toks = diff + cl->ctokens;
678 
679 	if (toks > cl->cbuffer)
680 		toks = cl->cbuffer;
681 	toks -= (s64) psched_l2t_ns(&cl->ceil, bytes);
682 	if (toks <= -cl->mbuffer)
683 		toks = 1 - cl->mbuffer;
684 
685 	WRITE_ONCE(cl->ctokens, toks);
686 }
687 
688 /**
689  * htb_charge_class - charges amount "bytes" to leaf and ancestors
690  * @q: the priority event queue
691  * @cl: the class to start iterate
692  * @level: the minimum level to account
693  * @skb: the socket buffer
694  *
695  * Routine assumes that packet "bytes" long was dequeued from leaf cl
696  * borrowing from "level". It accounts bytes to ceil leaky bucket for
697  * leaf and all ancestors and to rate bucket for ancestors at levels
698  * "level" and higher. It also handles possible change of mode resulting
699  * from the update. Note that mode can also increase here (MAY_BORROW to
700  * CAN_SEND) because we can use more precise clock that event queue here.
701  * In such case we remove class from event queue first.
702  */
703 static void htb_charge_class(struct htb_sched *q, struct htb_class *cl,
704 			     int level, struct sk_buff *skb)
705 {
706 	int bytes = qdisc_pkt_len(skb);
707 	enum htb_cmode old_mode;
708 	s64 diff;
709 
710 	while (cl) {
711 		diff = min_t(s64, q->now - cl->t_c, cl->mbuffer);
712 		if (cl->level >= level) {
713 			if (cl->level == level)
714 				WRITE_ONCE(cl->xstats_lends, cl->xstats_lends + 1);
715 			htb_accnt_tokens(cl, bytes, diff);
716 		} else {
717 			WRITE_ONCE(cl->xstats_borrows, cl->xstats_borrows + 1);
718 			/* we moved t_c; update tokens */
719 			WRITE_ONCE(cl->tokens, cl->tokens + diff);
720 		}
721 		htb_accnt_ctokens(cl, bytes, diff);
722 		cl->t_c = q->now;
723 
724 		old_mode = cl->cmode;
725 		diff = 0;
726 		htb_change_class_mode(q, cl, &diff);
727 		if (old_mode != cl->cmode) {
728 			if (old_mode != HTB_CAN_SEND)
729 				htb_safe_rb_erase(&cl->pq_node, &q->hlevel[cl->level].wait_pq);
730 			if (cl->cmode != HTB_CAN_SEND)
731 				htb_add_to_wait_tree(q, cl, diff);
732 		}
733 
734 		/* update basic stats except for leaves which are already updated */
735 		if (cl->level)
736 			bstats_update(&cl->bstats, skb);
737 
738 		cl = cl->parent;
739 	}
740 }
741 
742 /**
743  * htb_do_events - make mode changes to classes at the level
744  * @q: the priority event queue
745  * @level: which wait_pq in 'q->hlevel'
746  * @start: start jiffies
747  *
748  * Scans event queue for pending events and applies them. Returns time of
749  * next pending event (0 for no event in pq, q->now for too many events).
750  * Note: Applied are events whose have cl->pq_key <= q->now.
751  */
752 static s64 htb_do_events(struct htb_sched *q, const int level,
753 			 unsigned long start)
754 {
755 	/* don't run for longer than 2 jiffies; 2 is used instead of
756 	 * 1 to simplify things when jiffy is going to be incremented
757 	 * too soon
758 	 */
759 	unsigned long stop_at = start + 2;
760 	struct rb_root *wait_pq = &q->hlevel[level].wait_pq;
761 
762 	while (time_before(jiffies, stop_at)) {
763 		struct htb_class *cl;
764 		s64 diff;
765 		struct rb_node *p = rb_first(wait_pq);
766 
767 		if (!p)
768 			return 0;
769 
770 		cl = rb_entry(p, struct htb_class, pq_node);
771 		if (cl->pq_key > q->now)
772 			return cl->pq_key;
773 
774 		htb_safe_rb_erase(p, wait_pq);
775 		diff = min_t(s64, q->now - cl->t_c, cl->mbuffer);
776 		htb_change_class_mode(q, cl, &diff);
777 		if (cl->cmode != HTB_CAN_SEND)
778 			htb_add_to_wait_tree(q, cl, diff);
779 	}
780 
781 	/* too much load - let's continue after a break for scheduling */
782 	if (!(q->warned & HTB_WARN_TOOMANYEVENTS)) {
783 		pr_warn("htb: too many events!\n");
784 		q->warned |= HTB_WARN_TOOMANYEVENTS;
785 	}
786 
787 	return q->now;
788 }
789 
790 /* Returns class->node+prio from id-tree where classe's id is >= id. NULL
791  * is no such one exists.
792  */
793 static struct rb_node *htb_id_find_next_upper(int prio, struct rb_node *n,
794 					      u32 id)
795 {
796 	struct rb_node *r = NULL;
797 	while (n) {
798 		struct htb_class *cl =
799 		    rb_entry(n, struct htb_class, node[prio]);
800 
801 		if (id > cl->common.classid) {
802 			n = n->rb_right;
803 		} else if (id < cl->common.classid) {
804 			r = n;
805 			n = n->rb_left;
806 		} else {
807 			return n;
808 		}
809 	}
810 	return r;
811 }
812 
813 /**
814  * htb_lookup_leaf - returns next leaf class in DRR order
815  * @hprio: the current one
816  * @prio: which prio in class
817  *
818  * Find leaf where current feed pointers points to.
819  */
820 static struct htb_class *htb_lookup_leaf(struct htb_prio *hprio, const int prio)
821 {
822 	int i;
823 	struct {
824 		struct rb_node *root;
825 		struct rb_node **pptr;
826 		u32 *pid;
827 	} stk[TC_HTB_MAXDEPTH], *sp = stk;
828 
829 	if (unlikely(!hprio->row.rb_node))
830 		return NULL;
831 
832 	sp->root = hprio->row.rb_node;
833 	sp->pptr = &hprio->ptr;
834 	sp->pid = &hprio->last_ptr_id;
835 
836 	for (i = 0; i < 65535; i++) {
837 		if (!*sp->pptr && *sp->pid) {
838 			/* ptr was invalidated but id is valid - try to recover
839 			 * the original or next ptr
840 			 */
841 			*sp->pptr =
842 			    htb_id_find_next_upper(prio, sp->root, *sp->pid);
843 		}
844 		*sp->pid = 0;	/* ptr is valid now so that remove this hint as it
845 				 * can become out of date quickly
846 				 */
847 		if (!*sp->pptr) {	/* we are at right end; rewind & go up */
848 			*sp->pptr = sp->root;
849 			while ((*sp->pptr)->rb_left)
850 				*sp->pptr = (*sp->pptr)->rb_left;
851 			if (sp > stk) {
852 				sp--;
853 				if (!*sp->pptr) {
854 					WARN_ON(1);
855 					return NULL;
856 				}
857 				htb_next_rb_node(sp->pptr);
858 			}
859 		} else {
860 			struct htb_class *cl;
861 			struct htb_prio *clp;
862 
863 			cl = rb_entry(*sp->pptr, struct htb_class, node[prio]);
864 			if (!cl->level)
865 				return cl;
866 			clp = &cl->inner.clprio[prio];
867 			(++sp)->root = clp->feed.rb_node;
868 			sp->pptr = &clp->ptr;
869 			sp->pid = &clp->last_ptr_id;
870 		}
871 	}
872 	WARN_ON(1);
873 	return NULL;
874 }
875 
876 /* dequeues packet at given priority and level; call only if
877  * you are sure that there is active class at prio/level
878  */
879 static struct sk_buff *htb_dequeue_tree(struct htb_sched *q, const int prio,
880 					const int level)
881 {
882 	struct sk_buff *skb = NULL;
883 	struct htb_class *cl, *start;
884 	struct htb_level *hlevel = &q->hlevel[level];
885 	struct htb_prio *hprio = &hlevel->hprio[prio];
886 
887 	/* look initial class up in the row */
888 	start = cl = htb_lookup_leaf(hprio, prio);
889 
890 	do {
891 next:
892 		if (unlikely(!cl))
893 			return NULL;
894 
895 		/* class can be empty - it is unlikely but can be true if leaf
896 		 * qdisc drops packets in enqueue routine or if someone used
897 		 * graft operation on the leaf since last dequeue;
898 		 * simply deactivate and skip such class
899 		 */
900 		if (unlikely(cl->leaf.q->q.qlen == 0)) {
901 			struct htb_class *next;
902 			htb_deactivate(q, cl);
903 
904 			/* row/level might become empty */
905 			if ((q->row_mask[level] & (1 << prio)) == 0)
906 				return NULL;
907 
908 			next = htb_lookup_leaf(hprio, prio);
909 
910 			if (cl == start)	/* fix start if we just deleted it */
911 				start = next;
912 			cl = next;
913 			goto next;
914 		}
915 
916 		skb = cl->leaf.q->dequeue(cl->leaf.q);
917 		if (likely(skb != NULL))
918 			break;
919 
920 		qdisc_warn_nonwc("htb", cl->leaf.q);
921 		htb_next_rb_node(level ? &cl->parent->inner.clprio[prio].ptr:
922 					 &q->hlevel[0].hprio[prio].ptr);
923 		cl = htb_lookup_leaf(hprio, prio);
924 
925 	} while (cl != start);
926 
927 	if (likely(skb != NULL)) {
928 		bstats_update(&cl->bstats, skb);
929 		cl->leaf.deficit[level] -= qdisc_pkt_len(skb);
930 		if (cl->leaf.deficit[level] < 0) {
931 			cl->leaf.deficit[level] += cl->quantum;
932 			htb_next_rb_node(level ? &cl->parent->inner.clprio[prio].ptr :
933 						 &q->hlevel[0].hprio[prio].ptr);
934 		}
935 		/* this used to be after charge_class but this constelation
936 		 * gives us slightly better performance
937 		 */
938 		if (!cl->leaf.q->q.qlen)
939 			htb_deactivate(q, cl);
940 		htb_charge_class(q, cl, level, skb);
941 	}
942 	return skb;
943 }
944 
945 static struct sk_buff *htb_dequeue(struct Qdisc *sch)
946 {
947 	struct sk_buff *skb;
948 	struct htb_sched *q = qdisc_priv(sch);
949 	int level;
950 	s64 next_event;
951 	unsigned long start_at;
952 
953 	/* try to dequeue direct packets as high prio (!) to minimize cpu work */
954 	skb = __qdisc_dequeue_head(&q->direct_queue);
955 	if (skb != NULL) {
956 ok:
957 		qdisc_bstats_update(sch, skb);
958 		qdisc_qstats_backlog_dec(sch, skb);
959 		qdisc_qlen_dec(sch);
960 		return skb;
961 	}
962 
963 	if (!sch->q.qlen)
964 		goto fin;
965 	q->now = ktime_get_ns();
966 	start_at = jiffies;
967 
968 	next_event = q->now + 5LLU * NSEC_PER_SEC;
969 
970 	for (level = 0; level < TC_HTB_MAXDEPTH; level++) {
971 		/* common case optimization - skip event handler quickly */
972 		int m;
973 		s64 event = q->near_ev_cache[level];
974 
975 		if (q->now >= event) {
976 			event = htb_do_events(q, level, start_at);
977 			if (!event)
978 				event = q->now + NSEC_PER_SEC;
979 			q->near_ev_cache[level] = event;
980 		}
981 
982 		if (next_event > event)
983 			next_event = event;
984 
985 		m = ~q->row_mask[level];
986 		while (m != (int)(-1)) {
987 			int prio = ffz(m);
988 
989 			m |= 1 << prio;
990 			skb = htb_dequeue_tree(q, prio, level);
991 			if (likely(skb != NULL))
992 				goto ok;
993 		}
994 	}
995 	if (likely(next_event > q->now))
996 		qdisc_watchdog_schedule_ns(&q->watchdog, next_event);
997 	else
998 		schedule_work(&q->work);
999 fin:
1000 	return skb;
1001 }
1002 
1003 /* reset all classes */
1004 /* always caled under BH & queue lock */
1005 static void htb_reset(struct Qdisc *sch)
1006 {
1007 	struct htb_sched *q = qdisc_priv(sch);
1008 	struct htb_class *cl;
1009 	unsigned int i;
1010 
1011 	for (i = 0; i < q->clhash.hashsize; i++) {
1012 		hlist_for_each_entry(cl, &q->clhash.hash[i], common.hnode) {
1013 			if (cl->level)
1014 				memset(&cl->inner, 0, sizeof(cl->inner));
1015 			else {
1016 				if (cl->leaf.q && !q->offload)
1017 					qdisc_reset(cl->leaf.q);
1018 			}
1019 			cl->prio_activity = 0;
1020 			cl->cmode = HTB_CAN_SEND;
1021 		}
1022 	}
1023 	qdisc_watchdog_cancel(&q->watchdog);
1024 	__qdisc_reset_queue(&q->direct_queue);
1025 	memset(q->hlevel, 0, sizeof(q->hlevel));
1026 	memset(q->row_mask, 0, sizeof(q->row_mask));
1027 }
1028 
1029 static const struct nla_policy htb_policy[TCA_HTB_MAX + 1] = {
1030 	[TCA_HTB_PARMS]	= { .len = sizeof(struct tc_htb_opt) },
1031 	[TCA_HTB_INIT]	= { .len = sizeof(struct tc_htb_glob) },
1032 	[TCA_HTB_CTAB]	= { .type = NLA_BINARY, .len = TC_RTAB_SIZE },
1033 	[TCA_HTB_RTAB]	= { .type = NLA_BINARY, .len = TC_RTAB_SIZE },
1034 	[TCA_HTB_DIRECT_QLEN] = { .type = NLA_U32 },
1035 	[TCA_HTB_RATE64] = { .type = NLA_U64 },
1036 	[TCA_HTB_CEIL64] = { .type = NLA_U64 },
1037 	[TCA_HTB_OFFLOAD] = { .type = NLA_FLAG },
1038 };
1039 
1040 static void htb_work_func(struct work_struct *work)
1041 {
1042 	struct htb_sched *q = container_of(work, struct htb_sched, work);
1043 	struct Qdisc *sch = q->watchdog.qdisc;
1044 
1045 	rcu_read_lock();
1046 	__netif_schedule(qdisc_root(sch));
1047 	rcu_read_unlock();
1048 }
1049 
1050 static int htb_offload(struct net_device *dev, struct tc_htb_qopt_offload *opt)
1051 {
1052 	return dev->netdev_ops->ndo_setup_tc(dev, TC_SETUP_QDISC_HTB, opt);
1053 }
1054 
1055 static int htb_init(struct Qdisc *sch, struct nlattr *opt,
1056 		    struct netlink_ext_ack *extack)
1057 {
1058 	struct net_device *dev = qdisc_dev(sch);
1059 	struct tc_htb_qopt_offload offload_opt;
1060 	struct htb_sched *q = qdisc_priv(sch);
1061 	struct nlattr *tb[TCA_HTB_MAX + 1];
1062 	struct tc_htb_glob *gopt;
1063 	unsigned int ntx;
1064 	bool offload;
1065 	int err;
1066 
1067 	qdisc_watchdog_init(&q->watchdog, sch);
1068 	INIT_WORK(&q->work, htb_work_func);
1069 
1070 	if (!opt)
1071 		return -EINVAL;
1072 
1073 	err = tcf_block_get(&q->block, &q->filter_list, sch, extack);
1074 	if (err)
1075 		return err;
1076 
1077 	err = nla_parse_nested_deprecated(tb, TCA_HTB_MAX, opt, htb_policy,
1078 					  NULL);
1079 	if (err < 0)
1080 		return err;
1081 
1082 	if (!tb[TCA_HTB_INIT])
1083 		return -EINVAL;
1084 
1085 	gopt = nla_data(tb[TCA_HTB_INIT]);
1086 	if (gopt->version != HTB_VER >> 16)
1087 		return -EINVAL;
1088 
1089 	offload = nla_get_flag(tb[TCA_HTB_OFFLOAD]);
1090 
1091 	if (offload) {
1092 		if (sch->parent != TC_H_ROOT) {
1093 			NL_SET_ERR_MSG(extack, "HTB must be the root qdisc to use offload");
1094 			return -EOPNOTSUPP;
1095 		}
1096 
1097 		if (!tc_can_offload(dev) || !dev->netdev_ops->ndo_setup_tc) {
1098 			NL_SET_ERR_MSG(extack, "hw-tc-offload ethtool feature flag must be on");
1099 			return -EOPNOTSUPP;
1100 		}
1101 
1102 		q->num_direct_qdiscs = dev->real_num_tx_queues;
1103 		q->direct_qdiscs = kzalloc_objs(*q->direct_qdiscs,
1104 						q->num_direct_qdiscs);
1105 		if (!q->direct_qdiscs)
1106 			return -ENOMEM;
1107 	}
1108 
1109 	err = qdisc_class_hash_init(&q->clhash);
1110 	if (err < 0)
1111 		return err;
1112 
1113 	if (tb[TCA_HTB_DIRECT_QLEN])
1114 		q->direct_qlen = nla_get_u32(tb[TCA_HTB_DIRECT_QLEN]);
1115 	else
1116 		q->direct_qlen = qdisc_dev(sch)->tx_queue_len;
1117 
1118 	if ((q->rate2quantum = gopt->rate2quantum) < 1)
1119 		q->rate2quantum = 1;
1120 	q->defcls = gopt->defcls;
1121 
1122 	if (!offload)
1123 		return 0;
1124 
1125 	for (ntx = 0; ntx < q->num_direct_qdiscs; ntx++) {
1126 		struct netdev_queue *dev_queue = netdev_get_tx_queue(dev, ntx);
1127 		struct Qdisc *qdisc;
1128 
1129 		qdisc = qdisc_create_dflt(dev_queue, &pfifo_qdisc_ops,
1130 					  TC_H_MAKE(sch->handle, 0), extack);
1131 		if (!qdisc) {
1132 			return -ENOMEM;
1133 		}
1134 
1135 		q->direct_qdiscs[ntx] = qdisc;
1136 		qdisc->flags |= TCQ_F_ONETXQUEUE | TCQ_F_NOPARENT;
1137 	}
1138 
1139 	sch->flags |= TCQ_F_MQROOT;
1140 
1141 	offload_opt = (struct tc_htb_qopt_offload) {
1142 		.command = TC_HTB_CREATE,
1143 		.parent_classid = TC_H_MAJ(sch->handle) >> 16,
1144 		.classid = TC_H_MIN(q->defcls),
1145 		.extack = extack,
1146 	};
1147 	err = htb_offload(dev, &offload_opt);
1148 	if (err)
1149 		return err;
1150 
1151 	/* Defer this assignment, so that htb_destroy skips offload-related
1152 	 * parts (especially calling ndo_setup_tc) on errors.
1153 	 */
1154 	q->offload = true;
1155 	sch->flags |= TCQ_F_OFFLOADED;
1156 
1157 	return 0;
1158 }
1159 
1160 static void htb_attach_offload(struct Qdisc *sch)
1161 {
1162 	struct net_device *dev = qdisc_dev(sch);
1163 	struct htb_sched *q = qdisc_priv(sch);
1164 	unsigned int ntx;
1165 
1166 	for (ntx = 0; ntx < q->num_direct_qdiscs; ntx++) {
1167 		struct Qdisc *old, *qdisc = q->direct_qdiscs[ntx];
1168 
1169 		old = dev_graft_qdisc(qdisc->dev_queue, qdisc);
1170 		qdisc_put(old);
1171 		qdisc_hash_add(qdisc, false);
1172 	}
1173 	for (ntx = q->num_direct_qdiscs; ntx < dev->num_tx_queues; ntx++) {
1174 		struct netdev_queue *dev_queue = netdev_get_tx_queue(dev, ntx);
1175 		struct Qdisc *old = dev_graft_qdisc(dev_queue, NULL);
1176 
1177 		qdisc_put(old);
1178 	}
1179 
1180 	kfree(q->direct_qdiscs);
1181 	q->direct_qdiscs = NULL;
1182 }
1183 
1184 static void htb_attach_software(struct Qdisc *sch)
1185 {
1186 	struct net_device *dev = qdisc_dev(sch);
1187 	unsigned int ntx;
1188 
1189 	/* Resemble qdisc_graft behavior. */
1190 	for (ntx = 0; ntx < dev->num_tx_queues; ntx++) {
1191 		struct netdev_queue *dev_queue = netdev_get_tx_queue(dev, ntx);
1192 		struct Qdisc *old = dev_graft_qdisc(dev_queue, sch);
1193 
1194 		qdisc_refcount_inc(sch);
1195 
1196 		qdisc_put(old);
1197 	}
1198 }
1199 
1200 static void htb_attach(struct Qdisc *sch)
1201 {
1202 	struct htb_sched *q = qdisc_priv(sch);
1203 
1204 	if (q->offload)
1205 		htb_attach_offload(sch);
1206 	else
1207 		htb_attach_software(sch);
1208 }
1209 
1210 static int htb_dump(struct Qdisc *sch, struct sk_buff *skb)
1211 {
1212 	struct htb_sched *q = qdisc_priv(sch);
1213 	struct nlattr *nest;
1214 	struct tc_htb_glob gopt;
1215 
1216 	sch->qstats.overlimits = READ_ONCE(q->overlimits);
1217 	/* Its safe to not acquire qdisc lock. As we hold RTNL,
1218 	 * no change can happen on the qdisc parameters.
1219 	 */
1220 
1221 	gopt.direct_pkts = READ_ONCE(q->direct_pkts);
1222 	gopt.version = HTB_VER;
1223 	gopt.rate2quantum = q->rate2quantum;
1224 	gopt.defcls = q->defcls;
1225 	gopt.debug = 0;
1226 
1227 	nest = nla_nest_start_noflag(skb, TCA_OPTIONS);
1228 	if (nest == NULL)
1229 		goto nla_put_failure;
1230 	if (nla_put(skb, TCA_HTB_INIT, sizeof(gopt), &gopt) ||
1231 	    nla_put_u32(skb, TCA_HTB_DIRECT_QLEN, q->direct_qlen))
1232 		goto nla_put_failure;
1233 	if (q->offload && nla_put_flag(skb, TCA_HTB_OFFLOAD))
1234 		goto nla_put_failure;
1235 
1236 	return nla_nest_end(skb, nest);
1237 
1238 nla_put_failure:
1239 	nla_nest_cancel(skb, nest);
1240 	return -1;
1241 }
1242 
1243 static int htb_dump_class(struct Qdisc *sch, unsigned long arg,
1244 			  struct sk_buff *skb, struct tcmsg *tcm)
1245 {
1246 	struct htb_class *cl = (struct htb_class *)arg;
1247 	struct htb_sched *q = qdisc_priv(sch);
1248 	struct nlattr *nest;
1249 	struct tc_htb_opt opt;
1250 
1251 	/* Its safe to not acquire qdisc lock. As we hold RTNL,
1252 	 * no change can happen on the class parameters.
1253 	 */
1254 	tcm->tcm_parent = cl->parent ? cl->parent->common.classid : TC_H_ROOT;
1255 	tcm->tcm_handle = cl->common.classid;
1256 	if (!cl->level && cl->leaf.q)
1257 		tcm->tcm_info = cl->leaf.q->handle;
1258 
1259 	nest = nla_nest_start_noflag(skb, TCA_OPTIONS);
1260 	if (nest == NULL)
1261 		goto nla_put_failure;
1262 
1263 	memset(&opt, 0, sizeof(opt));
1264 
1265 	psched_ratecfg_getrate(&opt.rate, &cl->rate);
1266 	opt.buffer = PSCHED_NS2TICKS(cl->buffer);
1267 	psched_ratecfg_getrate(&opt.ceil, &cl->ceil);
1268 	opt.cbuffer = PSCHED_NS2TICKS(cl->cbuffer);
1269 	opt.quantum = cl->quantum;
1270 	opt.prio = cl->prio;
1271 	opt.level = cl->level;
1272 	if (nla_put(skb, TCA_HTB_PARMS, sizeof(opt), &opt))
1273 		goto nla_put_failure;
1274 	if (q->offload && nla_put_flag(skb, TCA_HTB_OFFLOAD))
1275 		goto nla_put_failure;
1276 	if ((cl->rate.rate_bytes_ps >= (1ULL << 32)) &&
1277 	    nla_put_u64_64bit(skb, TCA_HTB_RATE64, cl->rate.rate_bytes_ps,
1278 			      TCA_HTB_PAD))
1279 		goto nla_put_failure;
1280 	if ((cl->ceil.rate_bytes_ps >= (1ULL << 32)) &&
1281 	    nla_put_u64_64bit(skb, TCA_HTB_CEIL64, cl->ceil.rate_bytes_ps,
1282 			      TCA_HTB_PAD))
1283 		goto nla_put_failure;
1284 
1285 	return nla_nest_end(skb, nest);
1286 
1287 nla_put_failure:
1288 	nla_nest_cancel(skb, nest);
1289 	return -1;
1290 }
1291 
1292 static void htb_offload_aggregate_stats(struct htb_sched *q,
1293 					struct htb_class *cl)
1294 {
1295 	u64 bytes = 0, packets = 0;
1296 	struct htb_class *c;
1297 	unsigned int i;
1298 
1299 	for (i = 0; i < q->clhash.hashsize; i++) {
1300 		hlist_for_each_entry(c, &q->clhash.hash[i], common.hnode) {
1301 			struct htb_class *p = c;
1302 
1303 			while (p && p->level < cl->level)
1304 				p = p->parent;
1305 
1306 			if (p != cl)
1307 				continue;
1308 
1309 			bytes += u64_stats_read(&c->bstats_bias.bytes);
1310 			packets += u64_stats_read(&c->bstats_bias.packets);
1311 			if (c->level == 0) {
1312 				bytes += u64_stats_read(&c->leaf.q->bstats.bytes);
1313 				packets += u64_stats_read(&c->leaf.q->bstats.packets);
1314 			}
1315 		}
1316 	}
1317 	_bstats_set(&cl->bstats, bytes, packets);
1318 }
1319 
1320 static int
1321 htb_dump_class_stats(struct Qdisc *sch, unsigned long arg, struct gnet_dump *d)
1322 {
1323 	struct htb_class *cl = (struct htb_class *)arg;
1324 	struct htb_sched *q = qdisc_priv(sch);
1325 	struct tc_htb_xstats xstats = {
1326 		.lends = READ_ONCE(cl->xstats_lends),
1327 		.borrows = READ_ONCE(cl->xstats_borrows),
1328 	};
1329 	struct gnet_stats_queue qs = {
1330 		.drops = READ_ONCE(cl->drops),
1331 		.overlimits = READ_ONCE(cl->overlimits),
1332 	};
1333 	__u32 qlen = 0;
1334 
1335 	if (!cl->level && cl->leaf.q)
1336 		qdisc_qstats_qlen_backlog(cl->leaf.q, &qlen, &qs.backlog);
1337 
1338 	xstats.tokens = clamp_t(s64, PSCHED_NS2TICKS(READ_ONCE(cl->tokens)),
1339 				INT_MIN, INT_MAX);
1340 	xstats.ctokens = clamp_t(s64, PSCHED_NS2TICKS(READ_ONCE(cl->ctokens)),
1341 				 INT_MIN, INT_MAX);
1342 
1343 	if (q->offload) {
1344 		spin_lock_bh(qdisc_lock(sch));
1345 		if (!cl->level) {
1346 			u64 bytes = 0, packets = 0;
1347 
1348 			if (cl->leaf.q) {
1349 				bytes = u64_stats_read(&cl->leaf.q->bstats.bytes);
1350 				packets = u64_stats_read(&cl->leaf.q->bstats.packets);
1351 			}
1352 			bytes += u64_stats_read(&cl->bstats_bias.bytes);
1353 			packets += u64_stats_read(&cl->bstats_bias.packets);
1354 			_bstats_set(&cl->bstats, bytes, packets);
1355 		} else {
1356 			htb_offload_aggregate_stats(q, cl);
1357 		}
1358 		spin_unlock_bh(qdisc_lock(sch));
1359 	}
1360 
1361 	if (gnet_stats_copy_basic(d, NULL, &cl->bstats, true) < 0 ||
1362 	    gnet_stats_copy_rate_est(d, &cl->rate_est) < 0 ||
1363 	    gnet_stats_copy_queue(d, NULL, &qs, qlen) < 0)
1364 		return -1;
1365 
1366 	return gnet_stats_copy_app(d, &xstats, sizeof(xstats));
1367 }
1368 
1369 static struct netdev_queue *
1370 htb_select_queue(struct Qdisc *sch, struct tcmsg *tcm)
1371 {
1372 	struct net_device *dev = qdisc_dev(sch);
1373 	struct tc_htb_qopt_offload offload_opt;
1374 	struct htb_sched *q = qdisc_priv(sch);
1375 	int err;
1376 
1377 	if (!q->offload)
1378 		return sch->dev_queue;
1379 
1380 	offload_opt = (struct tc_htb_qopt_offload) {
1381 		.command = TC_HTB_LEAF_QUERY_QUEUE,
1382 		.classid = TC_H_MIN(tcm->tcm_parent),
1383 	};
1384 	err = htb_offload(dev, &offload_opt);
1385 	if (err || offload_opt.qid >= dev->num_tx_queues)
1386 		return NULL;
1387 	return netdev_get_tx_queue(dev, offload_opt.qid);
1388 }
1389 
1390 static struct Qdisc *
1391 htb_graft_helper(struct netdev_queue *dev_queue, struct Qdisc *new_q)
1392 {
1393 	struct net_device *dev = dev_queue->dev;
1394 	struct Qdisc *old_q;
1395 
1396 	if (dev->flags & IFF_UP)
1397 		dev_deactivate(dev, false);
1398 	old_q = dev_graft_qdisc(dev_queue, new_q);
1399 	if (new_q)
1400 		new_q->flags |= TCQ_F_ONETXQUEUE | TCQ_F_NOPARENT;
1401 	if (dev->flags & IFF_UP)
1402 		dev_activate(dev);
1403 
1404 	return old_q;
1405 }
1406 
1407 static struct netdev_queue *htb_offload_get_queue(struct htb_class *cl)
1408 {
1409 	struct netdev_queue *queue;
1410 
1411 	queue = cl->leaf.offload_queue;
1412 	if (!(cl->leaf.q->flags & TCQ_F_BUILTIN))
1413 		WARN_ON(cl->leaf.q->dev_queue != queue);
1414 
1415 	return queue;
1416 }
1417 
1418 static void htb_offload_move_qdisc(struct Qdisc *sch, struct htb_class *cl_old,
1419 				   struct htb_class *cl_new, bool destroying)
1420 {
1421 	struct netdev_queue *queue_old, *queue_new;
1422 	struct net_device *dev = qdisc_dev(sch);
1423 
1424 	queue_old = htb_offload_get_queue(cl_old);
1425 	queue_new = htb_offload_get_queue(cl_new);
1426 
1427 	if (!destroying) {
1428 		struct Qdisc *qdisc;
1429 
1430 		if (dev->flags & IFF_UP)
1431 			dev_deactivate(dev, false);
1432 		qdisc = dev_graft_qdisc(queue_old, NULL);
1433 		WARN_ON(qdisc != cl_old->leaf.q);
1434 	}
1435 
1436 	if (!(cl_old->leaf.q->flags & TCQ_F_BUILTIN))
1437 		cl_old->leaf.q->dev_queue = queue_new;
1438 	cl_old->leaf.offload_queue = queue_new;
1439 
1440 	if (!destroying) {
1441 		struct Qdisc *qdisc;
1442 
1443 		qdisc = dev_graft_qdisc(queue_new, cl_old->leaf.q);
1444 		if (dev->flags & IFF_UP)
1445 			dev_activate(dev);
1446 		WARN_ON(!(qdisc->flags & TCQ_F_BUILTIN));
1447 	}
1448 }
1449 
1450 static int htb_graft(struct Qdisc *sch, unsigned long arg, struct Qdisc *new,
1451 		     struct Qdisc **old, struct netlink_ext_ack *extack)
1452 {
1453 	struct netdev_queue *dev_queue = sch->dev_queue;
1454 	struct htb_class *cl = (struct htb_class *)arg;
1455 	struct htb_sched *q = qdisc_priv(sch);
1456 	struct Qdisc *old_q;
1457 
1458 	if (cl->level)
1459 		return -EINVAL;
1460 
1461 	if (q->offload)
1462 		dev_queue = htb_offload_get_queue(cl);
1463 
1464 	if (!new) {
1465 		new = qdisc_create_dflt(dev_queue, &pfifo_qdisc_ops,
1466 					cl->common.classid, extack);
1467 		if (!new)
1468 			return -ENOBUFS;
1469 	}
1470 
1471 	if (q->offload) {
1472 		/* One ref for cl->leaf.q, the other for dev_queue->qdisc. */
1473 		qdisc_refcount_inc(new);
1474 		old_q = htb_graft_helper(dev_queue, new);
1475 	}
1476 
1477 	*old = qdisc_replace(sch, new, &cl->leaf.q);
1478 
1479 	if (q->offload) {
1480 		WARN_ON(old_q != *old);
1481 		qdisc_put(old_q);
1482 	}
1483 
1484 	return 0;
1485 }
1486 
1487 static struct Qdisc *htb_leaf(struct Qdisc *sch, unsigned long arg)
1488 {
1489 	struct htb_class *cl = (struct htb_class *)arg;
1490 	return !cl->level ? cl->leaf.q : NULL;
1491 }
1492 
1493 static void htb_qlen_notify(struct Qdisc *sch, unsigned long arg)
1494 {
1495 	struct htb_class *cl = (struct htb_class *)arg;
1496 
1497 	htb_deactivate(qdisc_priv(sch), cl);
1498 }
1499 
1500 static inline int htb_parent_last_child(struct htb_class *cl)
1501 {
1502 	if (!cl->parent)
1503 		/* the root class */
1504 		return 0;
1505 	if (cl->parent->children > 1)
1506 		/* not the last child */
1507 		return 0;
1508 	return 1;
1509 }
1510 
1511 static void htb_parent_to_leaf(struct Qdisc *sch, struct htb_class *cl,
1512 			       struct Qdisc *new_q)
1513 {
1514 	struct htb_sched *q = qdisc_priv(sch);
1515 	struct htb_class *parent = cl->parent;
1516 
1517 	WARN_ON(cl->level || !cl->leaf.q || cl->prio_activity);
1518 
1519 	if (parent->cmode != HTB_CAN_SEND)
1520 		htb_safe_rb_erase(&parent->pq_node,
1521 				  &q->hlevel[parent->level].wait_pq);
1522 
1523 	parent->level = 0;
1524 	memset(&parent->inner, 0, sizeof(parent->inner));
1525 	parent->leaf.q = new_q ? new_q : &noop_qdisc;
1526 	WRITE_ONCE(parent->tokens, parent->buffer);
1527 	WRITE_ONCE(parent->ctokens, parent->cbuffer);
1528 	parent->t_c = ktime_get_ns();
1529 	parent->cmode = HTB_CAN_SEND;
1530 	if (q->offload)
1531 		parent->leaf.offload_queue = cl->leaf.offload_queue;
1532 }
1533 
1534 static void htb_parent_to_leaf_offload(struct Qdisc *sch,
1535 				       struct netdev_queue *dev_queue,
1536 				       struct Qdisc *new_q)
1537 {
1538 	struct Qdisc *old_q;
1539 
1540 	/* One ref for cl->leaf.q, the other for dev_queue->qdisc. */
1541 	if (new_q)
1542 		qdisc_refcount_inc(new_q);
1543 	old_q = htb_graft_helper(dev_queue, new_q);
1544 	WARN_ON(!(old_q->flags & TCQ_F_BUILTIN));
1545 }
1546 
1547 static int htb_destroy_class_offload(struct Qdisc *sch, struct htb_class *cl,
1548 				     bool last_child, bool destroying,
1549 				     struct netlink_ext_ack *extack)
1550 {
1551 	struct tc_htb_qopt_offload offload_opt;
1552 	struct netdev_queue *dev_queue;
1553 	struct Qdisc *q = cl->leaf.q;
1554 	struct Qdisc *old;
1555 	int err;
1556 
1557 	if (cl->level)
1558 		return -EINVAL;
1559 
1560 	WARN_ON(!q);
1561 	dev_queue = htb_offload_get_queue(cl);
1562 	/* When destroying, caller qdisc_graft grafts the new qdisc and invokes
1563 	 * qdisc_put for the qdisc being destroyed. htb_destroy_class_offload
1564 	 * does not need to graft or qdisc_put the qdisc being destroyed.
1565 	 */
1566 	if (!destroying) {
1567 		old = htb_graft_helper(dev_queue, NULL);
1568 		/* Last qdisc grafted should be the same as cl->leaf.q when
1569 		 * calling htb_delete.
1570 		 */
1571 		WARN_ON(old != q);
1572 	}
1573 
1574 	if (cl->parent) {
1575 		_bstats_update(&cl->parent->bstats_bias,
1576 			       u64_stats_read(&q->bstats.bytes),
1577 			       u64_stats_read(&q->bstats.packets));
1578 	}
1579 
1580 	offload_opt = (struct tc_htb_qopt_offload) {
1581 		.command = !last_child ? TC_HTB_LEAF_DEL :
1582 			   destroying ? TC_HTB_LEAF_DEL_LAST_FORCE :
1583 			   TC_HTB_LEAF_DEL_LAST,
1584 		.classid = cl->common.classid,
1585 		.extack = extack,
1586 	};
1587 	err = htb_offload(qdisc_dev(sch), &offload_opt);
1588 
1589 	if (!destroying) {
1590 		if (!err)
1591 			qdisc_put(old);
1592 		else
1593 			htb_graft_helper(dev_queue, old);
1594 	}
1595 
1596 	if (last_child)
1597 		return err;
1598 
1599 	if (!err && offload_opt.classid != TC_H_MIN(cl->common.classid)) {
1600 		u32 classid = TC_H_MAJ(sch->handle) |
1601 			      TC_H_MIN(offload_opt.classid);
1602 		struct htb_class *moved_cl = htb_find(classid, sch);
1603 
1604 		htb_offload_move_qdisc(sch, moved_cl, cl, destroying);
1605 	}
1606 
1607 	return err;
1608 }
1609 
1610 static void htb_destroy_class(struct Qdisc *sch, struct htb_class *cl)
1611 {
1612 	if (!cl->level) {
1613 		WARN_ON(!cl->leaf.q);
1614 		qdisc_put(cl->leaf.q);
1615 	}
1616 	gen_kill_estimator(&cl->rate_est);
1617 	tcf_block_put(cl->block);
1618 	kfree(cl);
1619 }
1620 
1621 static void htb_destroy(struct Qdisc *sch)
1622 {
1623 	struct net_device *dev = qdisc_dev(sch);
1624 	struct tc_htb_qopt_offload offload_opt;
1625 	struct htb_sched *q = qdisc_priv(sch);
1626 	struct hlist_node *next;
1627 	bool nonempty, changed;
1628 	struct htb_class *cl;
1629 	unsigned int i;
1630 
1631 	cancel_work_sync(&q->work);
1632 	qdisc_watchdog_cancel(&q->watchdog);
1633 	/* This line used to be after htb_destroy_class call below
1634 	 * and surprisingly it worked in 2.4. But it must precede it
1635 	 * because filter need its target class alive to be able to call
1636 	 * unbind_filter on it (without Oops).
1637 	 */
1638 	tcf_block_put(q->block);
1639 
1640 	for (i = 0; i < q->clhash.hashsize; i++) {
1641 		hlist_for_each_entry(cl, &q->clhash.hash[i], common.hnode) {
1642 			tcf_block_put(cl->block);
1643 			cl->block = NULL;
1644 		}
1645 	}
1646 
1647 	do {
1648 		nonempty = false;
1649 		changed = false;
1650 		for (i = 0; i < q->clhash.hashsize; i++) {
1651 			hlist_for_each_entry_safe(cl, next, &q->clhash.hash[i],
1652 						  common.hnode) {
1653 				bool last_child;
1654 
1655 				if (!q->offload) {
1656 					htb_destroy_class(sch, cl);
1657 					continue;
1658 				}
1659 
1660 				nonempty = true;
1661 
1662 				if (cl->level)
1663 					continue;
1664 
1665 				changed = true;
1666 
1667 				last_child = htb_parent_last_child(cl);
1668 				htb_destroy_class_offload(sch, cl, last_child,
1669 							  true, NULL);
1670 				qdisc_class_hash_remove(&q->clhash,
1671 							&cl->common);
1672 				if (cl->parent)
1673 					cl->parent->children--;
1674 				if (last_child)
1675 					htb_parent_to_leaf(sch, cl, NULL);
1676 				htb_destroy_class(sch, cl);
1677 			}
1678 		}
1679 	} while (changed);
1680 	WARN_ON(nonempty);
1681 
1682 	qdisc_class_hash_destroy(&q->clhash);
1683 	__qdisc_reset_queue(&q->direct_queue);
1684 
1685 	if (q->offload) {
1686 		offload_opt = (struct tc_htb_qopt_offload) {
1687 			.command = TC_HTB_DESTROY,
1688 		};
1689 		htb_offload(dev, &offload_opt);
1690 	}
1691 
1692 	if (!q->direct_qdiscs)
1693 		return;
1694 	for (i = 0; i < q->num_direct_qdiscs && q->direct_qdiscs[i]; i++)
1695 		qdisc_put(q->direct_qdiscs[i]);
1696 	kfree(q->direct_qdiscs);
1697 }
1698 
1699 static int htb_delete(struct Qdisc *sch, unsigned long arg,
1700 		      struct netlink_ext_ack *extack)
1701 {
1702 	struct htb_sched *q = qdisc_priv(sch);
1703 	struct htb_class *cl = (struct htb_class *)arg;
1704 	struct Qdisc *new_q = NULL;
1705 	int last_child = 0;
1706 	int err;
1707 
1708 	/* TODO: why don't allow to delete subtree ? references ? does
1709 	 * tc subsys guarantee us that in htb_destroy it holds no class
1710 	 * refs so that we can remove children safely there ?
1711 	 */
1712 	if (cl->children || qdisc_class_in_use(&cl->common)) {
1713 		NL_SET_ERR_MSG(extack, "HTB class in use");
1714 		return -EBUSY;
1715 	}
1716 
1717 	if (!cl->level && htb_parent_last_child(cl))
1718 		last_child = 1;
1719 
1720 	if (q->offload) {
1721 		err = htb_destroy_class_offload(sch, cl, last_child, false,
1722 						extack);
1723 		if (err)
1724 			return err;
1725 	}
1726 
1727 	if (last_child) {
1728 		struct netdev_queue *dev_queue = sch->dev_queue;
1729 
1730 		if (q->offload)
1731 			dev_queue = htb_offload_get_queue(cl);
1732 
1733 		new_q = qdisc_create_dflt(dev_queue, &pfifo_qdisc_ops,
1734 					  cl->parent->common.classid,
1735 					  NULL);
1736 		if (q->offload)
1737 			htb_parent_to_leaf_offload(sch, dev_queue, new_q);
1738 	}
1739 
1740 	sch_tree_lock(sch);
1741 
1742 	if (!cl->level)
1743 		qdisc_purge_queue(cl->leaf.q);
1744 
1745 	/* delete from hash and active; remainder in destroy_class */
1746 	qdisc_class_hash_remove(&q->clhash, &cl->common);
1747 	if (cl->parent)
1748 		cl->parent->children--;
1749 
1750 	htb_deactivate(q, cl);
1751 
1752 	if (cl->cmode != HTB_CAN_SEND)
1753 		htb_safe_rb_erase(&cl->pq_node,
1754 				  &q->hlevel[cl->level].wait_pq);
1755 
1756 	if (last_child)
1757 		htb_parent_to_leaf(sch, cl, new_q);
1758 
1759 	sch_tree_unlock(sch);
1760 
1761 	htb_destroy_class(sch, cl);
1762 	return 0;
1763 }
1764 
1765 static int htb_change_class(struct Qdisc *sch, u32 classid,
1766 			    u32 parentid, struct nlattr **tca,
1767 			    unsigned long *arg, struct netlink_ext_ack *extack)
1768 {
1769 	int err = -EINVAL;
1770 	struct htb_sched *q = qdisc_priv(sch);
1771 	struct htb_class *cl = (struct htb_class *)*arg, *parent;
1772 	struct tc_htb_qopt_offload offload_opt;
1773 	struct nlattr *opt = tca[TCA_OPTIONS];
1774 	struct nlattr *tb[TCA_HTB_MAX + 1];
1775 	struct Qdisc *parent_qdisc = NULL;
1776 	struct netdev_queue *dev_queue;
1777 	struct tc_htb_opt *hopt;
1778 	u64 rate64, ceil64;
1779 	int warn = 0;
1780 
1781 	/* extract all subattrs from opt attr */
1782 	if (!opt)
1783 		goto failure;
1784 
1785 	err = nla_parse_nested_deprecated(tb, TCA_HTB_MAX, opt, htb_policy,
1786 					  extack);
1787 	if (err < 0)
1788 		goto failure;
1789 
1790 	err = -EINVAL;
1791 	if (tb[TCA_HTB_PARMS] == NULL)
1792 		goto failure;
1793 
1794 	parent = parentid == TC_H_ROOT ? NULL : htb_find(parentid, sch);
1795 
1796 	hopt = nla_data(tb[TCA_HTB_PARMS]);
1797 	if (!hopt->rate.rate || !hopt->ceil.rate)
1798 		goto failure;
1799 
1800 	if (q->offload) {
1801 		/* Options not supported by the offload. */
1802 		if (hopt->rate.overhead || hopt->ceil.overhead) {
1803 			NL_SET_ERR_MSG(extack, "HTB offload doesn't support the overhead parameter");
1804 			goto failure;
1805 		}
1806 		if (hopt->rate.mpu || hopt->ceil.mpu) {
1807 			NL_SET_ERR_MSG(extack, "HTB offload doesn't support the mpu parameter");
1808 			goto failure;
1809 		}
1810 	}
1811 
1812 	/* Keeping backward compatible with rate_table based iproute2 tc */
1813 	if (hopt->rate.linklayer == TC_LINKLAYER_UNAWARE)
1814 		qdisc_put_rtab(qdisc_get_rtab(&hopt->rate, tb[TCA_HTB_RTAB],
1815 					      NULL));
1816 
1817 	if (hopt->ceil.linklayer == TC_LINKLAYER_UNAWARE)
1818 		qdisc_put_rtab(qdisc_get_rtab(&hopt->ceil, tb[TCA_HTB_CTAB],
1819 					      NULL));
1820 
1821 	rate64 = nla_get_u64_default(tb[TCA_HTB_RATE64], 0);
1822 	ceil64 = nla_get_u64_default(tb[TCA_HTB_CEIL64], 0);
1823 
1824 	if (!cl) {		/* new class */
1825 		struct net_device *dev = qdisc_dev(sch);
1826 		struct Qdisc *new_q, *old_q;
1827 		int prio;
1828 		struct {
1829 			struct nlattr		nla;
1830 			struct gnet_estimator	opt;
1831 		} est = {
1832 			.nla = {
1833 				.nla_len	= nla_attr_size(sizeof(est.opt)),
1834 				.nla_type	= TCA_RATE,
1835 			},
1836 			.opt = {
1837 				/* 4s interval, 16s averaging constant */
1838 				.interval	= 2,
1839 				.ewma_log	= 2,
1840 			},
1841 		};
1842 
1843 		/* check for valid classid */
1844 		if (!classid || TC_H_MAJ(classid ^ sch->handle) ||
1845 		    htb_find(classid, sch))
1846 			goto failure;
1847 
1848 		/* check maximal depth */
1849 		if (parent && parent->parent && parent->parent->level < 2) {
1850 			NL_SET_ERR_MSG_MOD(extack, "tree is too deep");
1851 			goto failure;
1852 		}
1853 		err = -ENOBUFS;
1854 		cl = kzalloc_obj(*cl);
1855 		if (!cl)
1856 			goto failure;
1857 
1858 		gnet_stats_basic_sync_init(&cl->bstats);
1859 		gnet_stats_basic_sync_init(&cl->bstats_bias);
1860 
1861 		err = tcf_block_get(&cl->block, &cl->filter_list, sch, extack);
1862 		if (err) {
1863 			kfree(cl);
1864 			goto failure;
1865 		}
1866 		if (htb_rate_est || tca[TCA_RATE]) {
1867 			err = gen_new_estimator(&cl->bstats, NULL,
1868 						&cl->rate_est,
1869 						NULL,
1870 						true,
1871 						tca[TCA_RATE] ? : &est.nla);
1872 			if (err)
1873 				goto err_block_put;
1874 		}
1875 
1876 		cl->children = 0;
1877 		RB_CLEAR_NODE(&cl->pq_node);
1878 
1879 		for (prio = 0; prio < TC_HTB_NUMPRIO; prio++)
1880 			RB_CLEAR_NODE(&cl->node[prio]);
1881 
1882 		cl->common.classid = classid;
1883 
1884 		/* Make sure nothing interrupts us in between of two
1885 		 * ndo_setup_tc calls.
1886 		 */
1887 		ASSERT_RTNL();
1888 
1889 		/* create leaf qdisc early because it uses kmalloc(GFP_KERNEL)
1890 		 * so that can't be used inside of sch_tree_lock
1891 		 * -- thanks to Karlis Peisenieks
1892 		 */
1893 		if (!q->offload) {
1894 			dev_queue = sch->dev_queue;
1895 		} else if (!(parent && !parent->level)) {
1896 			/* Assign a dev_queue to this classid. */
1897 			offload_opt = (struct tc_htb_qopt_offload) {
1898 				.command = TC_HTB_LEAF_ALLOC_QUEUE,
1899 				.classid = cl->common.classid,
1900 				.parent_classid = parent ?
1901 					TC_H_MIN(parent->common.classid) :
1902 					TC_HTB_CLASSID_ROOT,
1903 				.rate = max_t(u64, hopt->rate.rate, rate64),
1904 				.ceil = max_t(u64, hopt->ceil.rate, ceil64),
1905 				.prio = hopt->prio,
1906 				.quantum = hopt->quantum,
1907 				.extack = extack,
1908 			};
1909 			err = htb_offload(dev, &offload_opt);
1910 			if (err) {
1911 				NL_SET_ERR_MSG_WEAK(extack,
1912 						    "Failed to offload TC_HTB_LEAF_ALLOC_QUEUE");
1913 				goto err_kill_estimator;
1914 			}
1915 			dev_queue = netdev_get_tx_queue(dev, offload_opt.qid);
1916 		} else { /* First child. */
1917 			dev_queue = htb_offload_get_queue(parent);
1918 			old_q = htb_graft_helper(dev_queue, NULL);
1919 			WARN_ON(old_q != parent->leaf.q);
1920 			offload_opt = (struct tc_htb_qopt_offload) {
1921 				.command = TC_HTB_LEAF_TO_INNER,
1922 				.classid = cl->common.classid,
1923 				.parent_classid =
1924 					TC_H_MIN(parent->common.classid),
1925 				.rate = max_t(u64, hopt->rate.rate, rate64),
1926 				.ceil = max_t(u64, hopt->ceil.rate, ceil64),
1927 				.prio = hopt->prio,
1928 				.quantum = hopt->quantum,
1929 				.extack = extack,
1930 			};
1931 			err = htb_offload(dev, &offload_opt);
1932 			if (err) {
1933 				NL_SET_ERR_MSG_WEAK(extack,
1934 						    "Failed to offload TC_HTB_LEAF_TO_INNER");
1935 				htb_graft_helper(dev_queue, old_q);
1936 				goto err_kill_estimator;
1937 			}
1938 			_bstats_update(&parent->bstats_bias,
1939 				       u64_stats_read(&old_q->bstats.bytes),
1940 				       u64_stats_read(&old_q->bstats.packets));
1941 			qdisc_put(old_q);
1942 		}
1943 		new_q = qdisc_create_dflt(dev_queue, &pfifo_qdisc_ops,
1944 					  classid, NULL);
1945 		if (q->offload) {
1946 			/* One ref for cl->leaf.q, the other for dev_queue->qdisc. */
1947 			if (new_q)
1948 				qdisc_refcount_inc(new_q);
1949 			old_q = htb_graft_helper(dev_queue, new_q);
1950 			/* No qdisc_put needed. */
1951 			WARN_ON(!(old_q->flags & TCQ_F_BUILTIN));
1952 		}
1953 		sch_tree_lock(sch);
1954 		if (parent && !parent->level) {
1955 			/* turn parent into inner node */
1956 			qdisc_purge_queue(parent->leaf.q);
1957 			parent_qdisc = parent->leaf.q;
1958 			htb_deactivate(q, parent);
1959 
1960 			/* remove from evt list because of level change */
1961 			if (parent->cmode != HTB_CAN_SEND) {
1962 				htb_safe_rb_erase(&parent->pq_node, &q->hlevel[0].wait_pq);
1963 				parent->cmode = HTB_CAN_SEND;
1964 			}
1965 			parent->level = (parent->parent ? parent->parent->level
1966 					 : TC_HTB_MAXDEPTH) - 1;
1967 			memset(&parent->inner, 0, sizeof(parent->inner));
1968 		}
1969 
1970 		/* leaf (we) needs elementary qdisc */
1971 		cl->leaf.q = new_q ? new_q : &noop_qdisc;
1972 		if (q->offload)
1973 			cl->leaf.offload_queue = dev_queue;
1974 
1975 		cl->parent = parent;
1976 
1977 		/* set class to be in HTB_CAN_SEND state */
1978 		cl->tokens = PSCHED_TICKS2NS(hopt->buffer);
1979 		cl->ctokens = PSCHED_TICKS2NS(hopt->cbuffer);
1980 		cl->mbuffer = 60ULL * NSEC_PER_SEC;	/* 1min */
1981 		cl->t_c = ktime_get_ns();
1982 		cl->cmode = HTB_CAN_SEND;
1983 
1984 		/* attach to the hash list and parent's family */
1985 		qdisc_class_hash_insert(&q->clhash, &cl->common);
1986 		if (parent)
1987 			parent->children++;
1988 		if (cl->leaf.q != &noop_qdisc)
1989 			qdisc_hash_add(cl->leaf.q, true);
1990 	} else {
1991 		if (tca[TCA_RATE]) {
1992 			err = gen_replace_estimator(&cl->bstats, NULL,
1993 						    &cl->rate_est,
1994 						    NULL,
1995 						    true,
1996 						    tca[TCA_RATE]);
1997 			if (err)
1998 				return err;
1999 		}
2000 
2001 		if (q->offload) {
2002 			struct net_device *dev = qdisc_dev(sch);
2003 
2004 			offload_opt = (struct tc_htb_qopt_offload) {
2005 				.command = TC_HTB_NODE_MODIFY,
2006 				.classid = cl->common.classid,
2007 				.rate = max_t(u64, hopt->rate.rate, rate64),
2008 				.ceil = max_t(u64, hopt->ceil.rate, ceil64),
2009 				.prio = hopt->prio,
2010 				.quantum = hopt->quantum,
2011 				.extack = extack,
2012 			};
2013 			err = htb_offload(dev, &offload_opt);
2014 			if (err)
2015 				/* Estimator was replaced, and rollback may fail
2016 				 * as well, so we don't try to recover it, and
2017 				 * the estimator won't work property with the
2018 				 * offload anyway, because bstats are updated
2019 				 * only when the stats are queried.
2020 				 */
2021 				return err;
2022 		}
2023 
2024 		sch_tree_lock(sch);
2025 	}
2026 
2027 	psched_ratecfg_precompute(&cl->rate, &hopt->rate, rate64);
2028 	psched_ratecfg_precompute(&cl->ceil, &hopt->ceil, ceil64);
2029 
2030 	/* it used to be a nasty bug here, we have to check that node
2031 	 * is really leaf before changing cl->leaf !
2032 	 */
2033 	if (!cl->level) {
2034 		u64 quantum = cl->rate.rate_bytes_ps;
2035 
2036 		do_div(quantum, q->rate2quantum);
2037 		cl->quantum = min_t(u64, quantum, INT_MAX);
2038 
2039 		if (!hopt->quantum && cl->quantum < 1000) {
2040 			warn = -1;
2041 			cl->quantum = 1000;
2042 		}
2043 		if (!hopt->quantum && cl->quantum > 200000) {
2044 			warn = 1;
2045 			cl->quantum = 200000;
2046 		}
2047 		if (hopt->quantum)
2048 			cl->quantum = hopt->quantum;
2049 		if ((cl->prio = hopt->prio) >= TC_HTB_NUMPRIO)
2050 			cl->prio = TC_HTB_NUMPRIO - 1;
2051 	}
2052 
2053 	cl->buffer = PSCHED_TICKS2NS(hopt->buffer);
2054 	cl->cbuffer = PSCHED_TICKS2NS(hopt->cbuffer);
2055 
2056 	sch_tree_unlock(sch);
2057 	qdisc_put(parent_qdisc);
2058 
2059 	if (warn)
2060 		NL_SET_ERR_MSG_FMT_MOD(extack,
2061 				       "quantum of class %X is %s. Consider r2q change.",
2062 				       cl->common.classid, (warn == -1 ? "small" : "big"));
2063 
2064 	qdisc_class_hash_grow(sch, &q->clhash);
2065 
2066 	*arg = (unsigned long)cl;
2067 	return 0;
2068 
2069 err_kill_estimator:
2070 	gen_kill_estimator(&cl->rate_est);
2071 err_block_put:
2072 	tcf_block_put(cl->block);
2073 	kfree(cl);
2074 failure:
2075 	return err;
2076 }
2077 
2078 static struct tcf_block *htb_tcf_block(struct Qdisc *sch, unsigned long arg,
2079 				       struct netlink_ext_ack *extack)
2080 {
2081 	struct htb_sched *q = qdisc_priv(sch);
2082 	struct htb_class *cl = (struct htb_class *)arg;
2083 
2084 	return cl ? cl->block : q->block;
2085 }
2086 
2087 static unsigned long htb_bind_filter(struct Qdisc *sch, unsigned long parent,
2088 				     u32 classid)
2089 {
2090 	struct htb_class *cl = htb_find(classid, sch);
2091 
2092 	/*if (cl && !cl->level) return 0;
2093 	 * The line above used to be there to prevent attaching filters to
2094 	 * leaves. But at least tc_index filter uses this just to get class
2095 	 * for other reasons so that we have to allow for it.
2096 	 * ----
2097 	 * 19.6.2002 As Werner explained it is ok - bind filter is just
2098 	 * another way to "lock" the class - unlike "get" this lock can
2099 	 * be broken by class during destroy IIUC.
2100 	 */
2101 	if (cl)
2102 		qdisc_class_get(&cl->common);
2103 	return (unsigned long)cl;
2104 }
2105 
2106 static void htb_unbind_filter(struct Qdisc *sch, unsigned long arg)
2107 {
2108 	struct htb_class *cl = (struct htb_class *)arg;
2109 
2110 	qdisc_class_put(&cl->common);
2111 }
2112 
2113 static void htb_walk(struct Qdisc *sch, struct qdisc_walker *arg)
2114 {
2115 	struct htb_sched *q = qdisc_priv(sch);
2116 	struct htb_class *cl;
2117 	unsigned int i;
2118 
2119 	if (arg->stop)
2120 		return;
2121 
2122 	for (i = 0; i < q->clhash.hashsize; i++) {
2123 		hlist_for_each_entry(cl, &q->clhash.hash[i], common.hnode) {
2124 			if (!tc_qdisc_stats_dump(sch, (unsigned long)cl, arg))
2125 				return;
2126 		}
2127 	}
2128 }
2129 
2130 static const struct Qdisc_class_ops htb_class_ops = {
2131 	.select_queue	=	htb_select_queue,
2132 	.graft		=	htb_graft,
2133 	.leaf		=	htb_leaf,
2134 	.qlen_notify	=	htb_qlen_notify,
2135 	.find		=	htb_search,
2136 	.change		=	htb_change_class,
2137 	.delete		=	htb_delete,
2138 	.walk		=	htb_walk,
2139 	.tcf_block	=	htb_tcf_block,
2140 	.bind_tcf	=	htb_bind_filter,
2141 	.unbind_tcf	=	htb_unbind_filter,
2142 	.dump		=	htb_dump_class,
2143 	.dump_stats	=	htb_dump_class_stats,
2144 };
2145 
2146 static struct Qdisc_ops htb_qdisc_ops __read_mostly = {
2147 	.cl_ops		=	&htb_class_ops,
2148 	.id		=	"htb",
2149 	.priv_size	=	sizeof(struct htb_sched),
2150 	.enqueue	=	htb_enqueue,
2151 	.dequeue	=	htb_dequeue,
2152 	.peek		=	qdisc_peek_dequeued,
2153 	.init		=	htb_init,
2154 	.attach		=	htb_attach,
2155 	.reset		=	htb_reset,
2156 	.destroy	=	htb_destroy,
2157 	.dump		=	htb_dump,
2158 	.owner		=	THIS_MODULE,
2159 };
2160 MODULE_ALIAS_NET_SCH("htb");
2161 
2162 static int __init htb_module_init(void)
2163 {
2164 	return register_qdisc(&htb_qdisc_ops);
2165 }
2166 static void __exit htb_module_exit(void)
2167 {
2168 	unregister_qdisc(&htb_qdisc_ops);
2169 }
2170 
2171 module_init(htb_module_init)
2172 module_exit(htb_module_exit)
2173 MODULE_LICENSE("GPL");
2174 MODULE_DESCRIPTION("Hierarchical Token Bucket scheduler");
2175