xref: /linux/net/sched/sch_cake.c (revision fab183d632628381b466a41479489541ac0e29a0)
1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 
3 /* COMMON Applications Kept Enhanced (CAKE) discipline
4  *
5  * Copyright (C) 2014-2018 Jonathan Morton <chromatix99@gmail.com>
6  * Copyright (C) 2015-2018 Toke Høiland-Jørgensen <toke@toke.dk>
7  * Copyright (C) 2014-2018 Dave Täht <dave.taht@gmail.com>
8  * Copyright (C) 2015-2018 Sebastian Moeller <moeller0@gmx.de>
9  * (C) 2015-2018 Kevin Darbyshire-Bryant <kevin@darbyshire-bryant.me.uk>
10  * Copyright (C) 2017-2018 Ryan Mounce <ryan@mounce.com.au>
11  *
12  * The CAKE Principles:
13  *		   (or, how to have your cake and eat it too)
14  *
15  * This is a combination of several shaping, AQM and FQ techniques into one
16  * easy-to-use package:
17  *
18  * - An overall bandwidth shaper, to move the bottleneck away from dumb CPE
19  *   equipment and bloated MACs.  This operates in deficit mode (as in sch_fq),
20  *   eliminating the need for any sort of burst parameter (eg. token bucket
21  *   depth).  Burst support is limited to that necessary to overcome scheduling
22  *   latency.
23  *
24  * - A Diffserv-aware priority queue, giving more priority to certain classes,
25  *   up to a specified fraction of bandwidth.  Above that bandwidth threshold,
26  *   the priority is reduced to avoid starving other tins.
27  *
28  * - Each priority tin has a separate Flow Queue system, to isolate traffic
29  *   flows from each other.  This prevents a burst on one flow from increasing
30  *   the delay to another.  Flows are distributed to queues using a
31  *   set-associative hash function.
32  *
33  * - Each queue is actively managed by Cobalt, which is a combination of the
34  *   Codel and Blue AQM algorithms.  This serves flows fairly, and signals
35  *   congestion early via ECN (if available) and/or packet drops, to keep
36  *   latency low.  The codel parameters are auto-tuned based on the bandwidth
37  *   setting, as is necessary at low bandwidths.
38  *
39  * The configuration parameters are kept deliberately simple for ease of use.
40  * Everything has sane defaults.  Complete generality of configuration is *not*
41  * a goal.
42  *
43  * The priority queue operates according to a weighted DRR scheme, combined with
44  * a bandwidth tracker which reuses the shaper logic to detect which side of the
45  * bandwidth sharing threshold the tin is operating.  This determines whether a
46  * priority-based weight (high) or a bandwidth-based weight (low) is used for
47  * that tin in the current pass.
48  *
49  * This qdisc was inspired by Eric Dumazet's fq_codel code, which he kindly
50  * granted us permission to leverage.
51  */
52 
53 #include <linux/module.h>
54 #include <linux/types.h>
55 #include <linux/kernel.h>
56 #include <linux/jiffies.h>
57 #include <linux/string.h>
58 #include <linux/in.h>
59 #include <linux/errno.h>
60 #include <linux/init.h>
61 #include <linux/skbuff.h>
62 #include <linux/jhash.h>
63 #include <linux/slab.h>
64 #include <linux/vmalloc.h>
65 #include <linux/reciprocal_div.h>
66 #include <net/netlink.h>
67 #include <linux/if_vlan.h>
68 #include <net/gso.h>
69 #include <net/pkt_sched.h>
70 #include <net/sch_priv.h>
71 #include <net/pkt_cls.h>
72 #include <net/tcp.h>
73 #include <net/flow_dissector.h>
74 
75 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
76 #include <net/netfilter/nf_conntrack_core.h>
77 #endif
78 
79 #define CAKE_SET_WAYS (8)
80 #define CAKE_MAX_TINS (8)
81 #define CAKE_QUEUES (1024)
82 #define CAKE_FLOW_MASK 63
83 #define CAKE_FLOW_NAT_FLAG 64
84 
85 /* struct cobalt_params - contains codel and blue parameters
86  * @interval:	codel initial drop rate
87  * @target:     maximum persistent sojourn time & blue update rate
88  * @mtu_time:   serialisation delay of maximum-size packet
89  * @p_inc:      increment of blue drop probability (0.32 fxp)
90  * @p_dec:      decrement of blue drop probability (0.32 fxp)
91  */
92 struct cobalt_params {
93 	u64	interval;
94 	u64	target;
95 	u64	mtu_time;
96 	u32	p_inc;
97 	u32	p_dec;
98 };
99 
100 /* struct cobalt_vars - contains codel and blue variables
101  * @count:		codel dropping frequency
102  * @rec_inv_sqrt:	reciprocal value of sqrt(count) >> 1
103  * @drop_next:		time to drop next packet, or when we dropped last
104  * @blue_timer:		Blue time to next drop
105  * @p_drop:		BLUE drop probability (0.32 fxp)
106  * @dropping:		set if in dropping state
107  * @ecn_marked:		set if marked
108  */
109 struct cobalt_vars {
110 	u32	count;
111 	u32	rec_inv_sqrt;
112 	ktime_t	drop_next;
113 	ktime_t	blue_timer;
114 	u32     p_drop;
115 	bool	dropping;
116 	bool    ecn_marked;
117 };
118 
119 enum {
120 	CAKE_SET_NONE = 0,
121 	CAKE_SET_SPARSE,
122 	CAKE_SET_SPARSE_WAIT, /* counted in SPARSE, actually in BULK */
123 	CAKE_SET_BULK,
124 	CAKE_SET_DECAYING
125 };
126 
127 struct cake_flow {
128 	/* this stuff is all needed per-flow at dequeue time */
129 	struct sk_buff	  *head;
130 	struct sk_buff	  *tail;
131 	struct list_head  flowchain;
132 	s32		  deficit;
133 	u32		  dropped;
134 	struct cobalt_vars cvars;
135 	u16		  srchost; /* index into cake_host table */
136 	u16		  dsthost;
137 	u8		  set;
138 }; /* please try to keep this structure <= 64 bytes */
139 
140 struct cake_host {
141 	u32 srchost_tag;
142 	u32 dsthost_tag;
143 	u16 srchost_bulk_flow_count;
144 	u16 dsthost_bulk_flow_count;
145 };
146 
147 struct cake_heap_entry {
148 	u16 t:3, b:10;
149 };
150 
151 struct cake_tin_data {
152 	struct cake_flow flows[CAKE_QUEUES];
153 	u32	backlogs[CAKE_QUEUES];
154 	u32	tags[CAKE_QUEUES]; /* for set association */
155 	u16	overflow_idx[CAKE_QUEUES];
156 	struct cake_host hosts[CAKE_QUEUES]; /* for triple isolation */
157 	u16	flow_quantum;
158 
159 	struct cobalt_params cparams;
160 	u32	drop_overlimit;
161 	u16	bulk_flow_count;
162 	u16	sparse_flow_count;
163 	u16	decaying_flow_count;
164 	u16	unresponsive_flow_count;
165 
166 	u32	max_skblen;
167 
168 	struct list_head new_flows;
169 	struct list_head old_flows;
170 	struct list_head decaying_flows;
171 
172 	/* time_next = time_this + ((len * rate_ns) >> rate_shft) */
173 	ktime_t	time_next_packet;
174 	u64	tin_rate_ns;
175 	u64	tin_rate_bps;
176 	u16	tin_rate_shft;
177 
178 	u16	tin_quantum;
179 	s32	tin_deficit;
180 	u32	tin_backlog;
181 	u32	tin_dropped;
182 	u32	tin_ecn_mark;
183 
184 	u32	packets;
185 	u64	bytes;
186 
187 	u32	ack_drops;
188 
189 	/* moving averages */
190 	u64 avge_delay;
191 	u64 peak_delay;
192 	u64 base_delay;
193 
194 	/* hash function stats */
195 	u32	way_directs;
196 	u32	way_hits;
197 	u32	way_misses;
198 	u32	way_collisions;
199 }; /* number of tins is small, so size of this struct doesn't matter much */
200 
201 struct cake_sched_config {
202 	u64		rate_bps;
203 	u64		interval;
204 	u64		target;
205 	u64		sync_time;
206 	u32		buffer_config_limit;
207 	u32		fwmark_mask;
208 	u16		fwmark_shft;
209 	s16		rate_overhead;
210 	u16		rate_mpu;
211 	u16		rate_flags;
212 	u8		tin_mode;
213 	u8		flow_mode;
214 	u8		atm_mode;
215 	u8		ack_filter;
216 	u8		is_shared;
217 };
218 
219 struct cake_sched_data {
220 	struct tcf_proto __rcu *filter_list; /* optional external classifier */
221 	struct tcf_block *block;
222 	struct cake_tin_data *tins;
223 	struct cake_sched_config *config;
224 	struct cake_sched_config initial_config;
225 
226 	struct cake_heap_entry overflow_heap[CAKE_QUEUES * CAKE_MAX_TINS];
227 
228 	/* time_next = time_this + ((len * rate_ns) >> rate_shft) */
229 	ktime_t		time_next_packet;
230 	ktime_t		failsafe_next_packet;
231 	u64		rate_ns;
232 	u16		rate_shft;
233 	u16		overflow_timeout;
234 	u16		tin_cnt;
235 
236 	/* resource tracking */
237 	u32		buffer_used;
238 	u32		buffer_max_used;
239 	u32		buffer_limit;
240 
241 	/* indices for dequeue */
242 	u16		cur_tin;
243 	u16		cur_flow;
244 
245 	struct qdisc_watchdog watchdog;
246 	const u8	*tin_index;
247 	const u8	*tin_order;
248 
249 	/* bandwidth capacity estimate */
250 	ktime_t		last_packet_time;
251 	ktime_t		avg_window_begin;
252 	u64		avg_packet_interval;
253 	u64		avg_window_bytes;
254 	u64		avg_peak_bandwidth;
255 	ktime_t		last_reconfig_time;
256 
257 	/* packet length stats */
258 	u32		avg_netoff;
259 	u16		max_netlen;
260 	u16		max_adjlen;
261 	u16		min_netlen;
262 	u16		min_adjlen;
263 
264 	/* mq sync state */
265 	u64		last_checked_active;
266 	u64		last_active;
267 	u32		active_queues;
268 };
269 
270 enum {
271 	CAKE_FLAG_OVERHEAD	   = BIT(0),
272 	CAKE_FLAG_AUTORATE_INGRESS = BIT(1),
273 	CAKE_FLAG_INGRESS	   = BIT(2),
274 	CAKE_FLAG_WASH		   = BIT(3),
275 	CAKE_FLAG_SPLIT_GSO	   = BIT(4)
276 };
277 
278 /* COBALT operates the Codel and BLUE algorithms in parallel, in order to
279  * obtain the best features of each.  Codel is excellent on flows which
280  * respond to congestion signals in a TCP-like way.  BLUE is more effective on
281  * unresponsive flows.
282  */
283 
284 struct cobalt_skb_cb {
285 	ktime_t enqueue_time;
286 	u32     adjusted_len;
287 };
288 
us_to_ns(u64 us)289 static u64 us_to_ns(u64 us)
290 {
291 	return us * NSEC_PER_USEC;
292 }
293 
get_cobalt_cb(const struct sk_buff * skb)294 static struct cobalt_skb_cb *get_cobalt_cb(const struct sk_buff *skb)
295 {
296 	qdisc_cb_private_validate(skb, sizeof(struct cobalt_skb_cb));
297 	return (struct cobalt_skb_cb *)qdisc_skb_cb(skb)->data;
298 }
299 
cobalt_get_enqueue_time(const struct sk_buff * skb)300 static ktime_t cobalt_get_enqueue_time(const struct sk_buff *skb)
301 {
302 	return get_cobalt_cb(skb)->enqueue_time;
303 }
304 
cobalt_set_enqueue_time(struct sk_buff * skb,ktime_t now)305 static void cobalt_set_enqueue_time(struct sk_buff *skb,
306 				    ktime_t now)
307 {
308 	get_cobalt_cb(skb)->enqueue_time = now;
309 }
310 
311 static u16 quantum_div[CAKE_QUEUES + 1] = {0};
312 
313 /* Diffserv lookup tables */
314 
315 static const u8 precedence[] = {
316 	0, 0, 0, 0, 0, 0, 0, 0,
317 	1, 1, 1, 1, 1, 1, 1, 1,
318 	2, 2, 2, 2, 2, 2, 2, 2,
319 	3, 3, 3, 3, 3, 3, 3, 3,
320 	4, 4, 4, 4, 4, 4, 4, 4,
321 	5, 5, 5, 5, 5, 5, 5, 5,
322 	6, 6, 6, 6, 6, 6, 6, 6,
323 	7, 7, 7, 7, 7, 7, 7, 7,
324 };
325 
326 static const u8 diffserv8[] = {
327 	2, 0, 1, 2, 4, 2, 2, 2,
328 	1, 2, 1, 2, 1, 2, 1, 2,
329 	5, 2, 4, 2, 4, 2, 4, 2,
330 	3, 2, 3, 2, 3, 2, 3, 2,
331 	6, 2, 3, 2, 3, 2, 3, 2,
332 	6, 2, 2, 2, 6, 2, 6, 2,
333 	7, 2, 2, 2, 2, 2, 2, 2,
334 	7, 2, 2, 2, 2, 2, 2, 2,
335 };
336 
337 static const u8 diffserv4[] = {
338 	0, 1, 0, 0, 2, 0, 0, 0,
339 	1, 0, 0, 0, 0, 0, 0, 0,
340 	2, 0, 2, 0, 2, 0, 2, 0,
341 	2, 0, 2, 0, 2, 0, 2, 0,
342 	3, 0, 2, 0, 2, 0, 2, 0,
343 	3, 0, 0, 0, 3, 0, 3, 0,
344 	3, 0, 0, 0, 0, 0, 0, 0,
345 	3, 0, 0, 0, 0, 0, 0, 0,
346 };
347 
348 static const u8 diffserv3[] = {
349 	0, 1, 0, 0, 2, 0, 0, 0,
350 	1, 0, 0, 0, 0, 0, 0, 0,
351 	0, 0, 0, 0, 0, 0, 0, 0,
352 	0, 0, 0, 0, 0, 0, 0, 0,
353 	0, 0, 0, 0, 0, 0, 0, 0,
354 	0, 0, 0, 0, 2, 0, 2, 0,
355 	2, 0, 0, 0, 0, 0, 0, 0,
356 	2, 0, 0, 0, 0, 0, 0, 0,
357 };
358 
359 static const u8 besteffort[] = {
360 	0, 0, 0, 0, 0, 0, 0, 0,
361 	0, 0, 0, 0, 0, 0, 0, 0,
362 	0, 0, 0, 0, 0, 0, 0, 0,
363 	0, 0, 0, 0, 0, 0, 0, 0,
364 	0, 0, 0, 0, 0, 0, 0, 0,
365 	0, 0, 0, 0, 0, 0, 0, 0,
366 	0, 0, 0, 0, 0, 0, 0, 0,
367 	0, 0, 0, 0, 0, 0, 0, 0,
368 };
369 
370 /* tin priority order for stats dumping */
371 
372 static const u8 normal_order[] = {0, 1, 2, 3, 4, 5, 6, 7};
373 static const u8 bulk_order[] = {1, 0, 2, 3};
374 
375 /* There is a big difference in timing between the accurate values placed in the
376  * cache and the approximations given by a single Newton step for small count
377  * values, particularly when stepping from count 1 to 2 or vice versa. Hence,
378  * these values are calculated using eight Newton steps, using the
379  * implementation below. Above 16, a single Newton step gives sufficient
380  * accuracy in either direction, given the precision stored.
381  *
382  * The magnitude of the error when stepping up to count 2 is such as to give the
383  * value that *should* have been produced at count 4.
384  */
385 
386 #define REC_INV_SQRT_CACHE (16)
387 static const u32 inv_sqrt_cache[REC_INV_SQRT_CACHE] = {
388 		~0,         ~0, 3037000500, 2479700525,
389 	2147483647, 1920767767, 1753413056, 1623345051,
390 	1518500250, 1431655765, 1358187914, 1294981364,
391 	1239850263, 1191209601, 1147878294, 1108955788
392 };
393 
394 static void cake_configure_rates(struct Qdisc *sch, u64 rate, bool rate_adjust);
395 
396 /* http://en.wikipedia.org/wiki/Methods_of_computing_square_roots
397  * new_invsqrt = (invsqrt / 2) * (3 - count * invsqrt^2)
398  *
399  * Here, invsqrt is a fixed point number (< 1.0), 32bit mantissa, aka Q0.32
400  */
401 
cobalt_newton_step(struct cobalt_vars * vars,u32 count)402 static void cobalt_newton_step(struct cobalt_vars *vars, u32 count)
403 {
404 	u32 invsqrt, invsqrt2;
405 	u64 val;
406 
407 	invsqrt = vars->rec_inv_sqrt;
408 	invsqrt2 = ((u64)invsqrt * invsqrt) >> 32;
409 	val = (3LL << 32) - ((u64)count * invsqrt2);
410 
411 	val >>= 2; /* avoid overflow in following multiply */
412 	val = (val * invsqrt) >> (32 - 2 + 1);
413 
414 	vars->rec_inv_sqrt = val;
415 }
416 
cobalt_invsqrt(struct cobalt_vars * vars,u32 count)417 static void cobalt_invsqrt(struct cobalt_vars *vars, u32 count)
418 {
419 	if (count < REC_INV_SQRT_CACHE)
420 		vars->rec_inv_sqrt = inv_sqrt_cache[count];
421 	else
422 		cobalt_newton_step(vars, count);
423 }
424 
cobalt_vars_init(struct cobalt_vars * vars)425 static void cobalt_vars_init(struct cobalt_vars *vars)
426 {
427 	memset(vars, 0, sizeof(*vars));
428 }
429 
430 /* CoDel control_law is t + interval/sqrt(count)
431  * We maintain in rec_inv_sqrt the reciprocal value of sqrt(count) to avoid
432  * both sqrt() and divide operation.
433  */
cobalt_control(ktime_t t,u64 interval,u32 rec_inv_sqrt)434 static ktime_t cobalt_control(ktime_t t,
435 			      u64 interval,
436 			      u32 rec_inv_sqrt)
437 {
438 	return ktime_add_ns(t, reciprocal_scale(interval,
439 						rec_inv_sqrt));
440 }
441 
442 /* Call this when a packet had to be dropped due to queue overflow.  Returns
443  * true if the BLUE state was quiescent before but active after this call.
444  */
cobalt_queue_full(struct cobalt_vars * vars,struct cobalt_params * p,ktime_t now)445 static bool cobalt_queue_full(struct cobalt_vars *vars,
446 			      struct cobalt_params *p,
447 			      ktime_t now)
448 {
449 	bool up = false;
450 
451 	if (ktime_to_ns(ktime_sub(now, vars->blue_timer)) > p->target) {
452 		u32 p_drop = vars->p_drop;
453 
454 		up = !p_drop;
455 		p_drop += p->p_inc;
456 		if (p_drop < p->p_inc)
457 			p_drop = ~0;
458 		WRITE_ONCE(vars->p_drop, p_drop);
459 		WRITE_ONCE(vars->blue_timer, now);
460 	}
461 	WRITE_ONCE(vars->dropping, true);
462 	WRITE_ONCE(vars->drop_next, now);
463 	if (!vars->count)
464 		WRITE_ONCE(vars->count, 1);
465 
466 	return up;
467 }
468 
469 /* Call this when the queue was serviced but turned out to be empty.  Returns
470  * true if the BLUE state was active before but quiescent after this call.
471  */
cobalt_queue_empty(struct cobalt_vars * vars,struct cobalt_params * p,ktime_t now)472 static bool cobalt_queue_empty(struct cobalt_vars *vars,
473 			       struct cobalt_params *p,
474 			       ktime_t now)
475 {
476 	bool down = false;
477 
478 	if (vars->p_drop &&
479 	    ktime_to_ns(ktime_sub(now, vars->blue_timer)) > p->target) {
480 		if (vars->p_drop < p->p_dec)
481 			WRITE_ONCE(vars->p_drop, 0);
482 		else
483 			WRITE_ONCE(vars->p_drop, vars->p_drop - p->p_dec);
484 		WRITE_ONCE(vars->blue_timer, now);
485 		down = !vars->p_drop;
486 	}
487 	WRITE_ONCE(vars->dropping, false);
488 
489 	if (vars->count && ktime_to_ns(ktime_sub(now, vars->drop_next)) >= 0) {
490 		WRITE_ONCE(vars->count, vars->count - 1);
491 		cobalt_invsqrt(vars, vars->count);
492 		WRITE_ONCE(vars->drop_next,
493 			   cobalt_control(vars->drop_next, p->interval,
494 					  vars->rec_inv_sqrt));
495 	}
496 
497 	return down;
498 }
499 
500 /* Call this with a freshly dequeued packet for possible congestion marking.
501  * Returns true as an instruction to drop the packet, false for delivery.
502  */
cobalt_should_drop(struct cobalt_vars * vars,struct cobalt_params * p,ktime_t now,struct sk_buff * skb,u32 bulk_flows)503 static enum qdisc_drop_reason cobalt_should_drop(struct cobalt_vars *vars,
504 						 struct cobalt_params *p,
505 						 ktime_t now,
506 						 struct sk_buff *skb,
507 						 u32 bulk_flows)
508 {
509 	enum qdisc_drop_reason reason = QDISC_DROP_UNSPEC;
510 	bool next_due, over_target;
511 	ktime_t schedule;
512 	u64 sojourn;
513 	u32 count;
514 
515 /* The 'schedule' variable records, in its sign, whether 'now' is before or
516  * after 'drop_next'.  This allows 'drop_next' to be updated before the next
517  * scheduling decision is actually branched, without destroying that
518  * information.  Similarly, the first 'schedule' value calculated is preserved
519  * in the boolean 'next_due'.
520  *
521  * As for 'drop_next', we take advantage of the fact that 'interval' is both
522  * the delay between first exceeding 'target' and the first signalling event,
523  * *and* the scaling factor for the signalling frequency.  It's therefore very
524  * natural to use a single mechanism for both purposes, and eliminates a
525  * significant amount of reference Codel's spaghetti code.  To help with this,
526  * both the '0' and '1' entries in the invsqrt cache are 0xFFFFFFFF, as close
527  * as possible to 1.0 in fixed-point.
528  */
529 
530 	sojourn = ktime_to_ns(ktime_sub(now, cobalt_get_enqueue_time(skb)));
531 	schedule = ktime_sub(now, vars->drop_next);
532 	over_target = sojourn > p->target &&
533 		      sojourn > p->mtu_time * bulk_flows * 2 &&
534 		      sojourn > p->mtu_time * 4;
535 	count = vars->count;
536 	next_due = count && ktime_to_ns(schedule) >= 0;
537 
538 	vars->ecn_marked = false;
539 
540 	if (over_target) {
541 		if (!vars->dropping) {
542 			WRITE_ONCE(vars->dropping, true);
543 			WRITE_ONCE(vars->drop_next,
544 				   cobalt_control(now, p->interval,
545 						  vars->rec_inv_sqrt));
546 		}
547 		if (!count)
548 			count = 1;
549 	} else if (vars->dropping) {
550 		WRITE_ONCE(vars->dropping, false);
551 	}
552 
553 	if (next_due && vars->dropping) {
554 		/* Use ECN mark if possible, otherwise drop */
555 		if (!(vars->ecn_marked = INET_ECN_set_ce(skb)))
556 			reason = QDISC_DROP_CONGESTED;
557 
558 		count++;
559 		if (!count)
560 			count--;
561 		cobalt_invsqrt(vars, count);
562 		WRITE_ONCE(vars->drop_next,
563 			   cobalt_control(vars->drop_next, p->interval,
564 					  vars->rec_inv_sqrt));
565 		schedule = ktime_sub(now, vars->drop_next);
566 	} else {
567 		while (next_due) {
568 			count--;
569 			cobalt_invsqrt(vars, count);
570 			WRITE_ONCE(vars->drop_next,
571 				   cobalt_control(vars->drop_next, p->interval,
572 						  vars->rec_inv_sqrt));
573 			schedule = ktime_sub(now, vars->drop_next);
574 			next_due = count && ktime_to_ns(schedule) >= 0;
575 		}
576 	}
577 
578 	/* Simple BLUE implementation.  Lack of ECN is deliberate. */
579 	if (vars->p_drop && reason == QDISC_DROP_UNSPEC &&
580 	    get_random_u32() < vars->p_drop)
581 		reason = QDISC_DROP_FLOOD_PROTECTION;
582 
583 	WRITE_ONCE(vars->count, count);
584 	/* Overload the drop_next field as an activity timeout */
585 	if (!count)
586 		WRITE_ONCE(vars->drop_next, ktime_add_ns(now, p->interval));
587 	else if (ktime_to_ns(schedule) > 0 && reason == QDISC_DROP_UNSPEC)
588 		WRITE_ONCE(vars->drop_next, now);
589 
590 	return reason;
591 }
592 
cake_update_flowkeys(struct flow_keys * keys,const struct sk_buff * skb)593 static bool cake_update_flowkeys(struct flow_keys *keys,
594 				 const struct sk_buff *skb)
595 {
596 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
597 	struct nf_conntrack_tuple tuple = {};
598 	bool rev = !skb->_nfct, upd = false;
599 	__be32 ip;
600 
601 	if (skb_protocol(skb, true) != htons(ETH_P_IP))
602 		return false;
603 
604 	if (!nf_ct_get_tuple_skb(&tuple, skb))
605 		return false;
606 
607 	ip = rev ? tuple.dst.u3.ip : tuple.src.u3.ip;
608 	if (ip != keys->addrs.v4addrs.src) {
609 		keys->addrs.v4addrs.src = ip;
610 		upd = true;
611 	}
612 	ip = rev ? tuple.src.u3.ip : tuple.dst.u3.ip;
613 	if (ip != keys->addrs.v4addrs.dst) {
614 		keys->addrs.v4addrs.dst = ip;
615 		upd = true;
616 	}
617 
618 	if (keys->ports.ports) {
619 		__be16 port;
620 
621 		port = rev ? tuple.dst.u.all : tuple.src.u.all;
622 		if (port != keys->ports.src) {
623 			keys->ports.src = port;
624 			upd = true;
625 		}
626 		port = rev ? tuple.src.u.all : tuple.dst.u.all;
627 		if (port != keys->ports.dst) {
628 			keys->ports.dst = port;
629 			upd = true;
630 		}
631 	}
632 	return upd;
633 #else
634 	return false;
635 #endif
636 }
637 
638 /* Cake has several subtle multiple bit settings. In these cases you
639  *  would be matching triple isolate mode as well.
640  */
641 
cake_dsrc(int flow_mode)642 static bool cake_dsrc(int flow_mode)
643 {
644 	return (flow_mode & CAKE_FLOW_DUAL_SRC) == CAKE_FLOW_DUAL_SRC;
645 }
646 
cake_ddst(int flow_mode)647 static bool cake_ddst(int flow_mode)
648 {
649 	return (flow_mode & CAKE_FLOW_DUAL_DST) == CAKE_FLOW_DUAL_DST;
650 }
651 
cake_dec_srchost_bulk_flow_count(struct cake_tin_data * q,struct cake_flow * flow,int flow_mode)652 static void cake_dec_srchost_bulk_flow_count(struct cake_tin_data *q,
653 					     struct cake_flow *flow,
654 					     int flow_mode)
655 {
656 	if (likely(cake_dsrc(flow_mode) &&
657 		   q->hosts[flow->srchost].srchost_bulk_flow_count))
658 		q->hosts[flow->srchost].srchost_bulk_flow_count--;
659 }
660 
cake_inc_srchost_bulk_flow_count(struct cake_tin_data * q,struct cake_flow * flow,int flow_mode)661 static void cake_inc_srchost_bulk_flow_count(struct cake_tin_data *q,
662 					     struct cake_flow *flow,
663 					     int flow_mode)
664 {
665 	if (likely(cake_dsrc(flow_mode) &&
666 		   q->hosts[flow->srchost].srchost_bulk_flow_count < CAKE_QUEUES))
667 		q->hosts[flow->srchost].srchost_bulk_flow_count++;
668 }
669 
cake_dec_dsthost_bulk_flow_count(struct cake_tin_data * q,struct cake_flow * flow,int flow_mode)670 static void cake_dec_dsthost_bulk_flow_count(struct cake_tin_data *q,
671 					     struct cake_flow *flow,
672 					     int flow_mode)
673 {
674 	if (likely(cake_ddst(flow_mode) &&
675 		   q->hosts[flow->dsthost].dsthost_bulk_flow_count))
676 		q->hosts[flow->dsthost].dsthost_bulk_flow_count--;
677 }
678 
cake_inc_dsthost_bulk_flow_count(struct cake_tin_data * q,struct cake_flow * flow,int flow_mode)679 static void cake_inc_dsthost_bulk_flow_count(struct cake_tin_data *q,
680 					     struct cake_flow *flow,
681 					     int flow_mode)
682 {
683 	if (likely(cake_ddst(flow_mode) &&
684 		   q->hosts[flow->dsthost].dsthost_bulk_flow_count < CAKE_QUEUES))
685 		q->hosts[flow->dsthost].dsthost_bulk_flow_count++;
686 }
687 
cake_get_flow_quantum(struct cake_tin_data * q,struct cake_flow * flow,int flow_mode)688 static u16 cake_get_flow_quantum(struct cake_tin_data *q,
689 				 struct cake_flow *flow,
690 				 int flow_mode)
691 {
692 	u16 host_load = 1;
693 
694 	if (cake_dsrc(flow_mode))
695 		host_load = max(host_load,
696 				q->hosts[flow->srchost].srchost_bulk_flow_count);
697 
698 	if (cake_ddst(flow_mode))
699 		host_load = max(host_load,
700 				q->hosts[flow->dsthost].dsthost_bulk_flow_count);
701 
702 	/* The get_random_u16() is a way to apply dithering to avoid
703 	 * accumulating roundoff errors
704 	 */
705 	return (q->flow_quantum * quantum_div[host_load] +
706 		get_random_u16()) >> 16;
707 }
708 
cake_hash(struct cake_tin_data * q,const struct sk_buff * skb,int flow_mode,u16 flow_override,u16 host_override)709 static u32 cake_hash(struct cake_tin_data *q, const struct sk_buff *skb,
710 		     int flow_mode, u16 flow_override, u16 host_override)
711 {
712 	bool hash_flows = (!flow_override && !!(flow_mode & CAKE_FLOW_FLOWS));
713 	bool hash_hosts = (!host_override && !!(flow_mode & CAKE_FLOW_HOSTS));
714 	bool nat_enabled = !!(flow_mode & CAKE_FLOW_NAT_FLAG);
715 	u32 flow_hash = 0, srchost_hash = 0, dsthost_hash = 0;
716 	u16 reduced_hash, srchost_idx, dsthost_idx;
717 	struct flow_keys keys, host_keys;
718 	bool use_skbhash = skb->l4_hash;
719 
720 	if (unlikely(flow_mode == CAKE_FLOW_NONE))
721 		return 0;
722 
723 	/* If both overrides are set, or we can use the SKB hash and nat mode is
724 	 * disabled, we can skip packet dissection entirely. If nat mode is
725 	 * enabled there's another check below after doing the conntrack lookup.
726 	 */
727 	if ((!hash_flows || (use_skbhash && !nat_enabled)) && !hash_hosts)
728 		goto skip_hash;
729 
730 	skb_flow_dissect_flow_keys(skb, &keys,
731 				   FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL);
732 
733 	/* Don't use the SKB hash if we change the lookup keys from conntrack */
734 	if (nat_enabled && cake_update_flowkeys(&keys, skb))
735 		use_skbhash = false;
736 
737 	/* If we can still use the SKB hash and don't need the host hash, we can
738 	 * skip the rest of the hashing procedure
739 	 */
740 	if (use_skbhash && !hash_hosts)
741 		goto skip_hash;
742 
743 	/* flow_hash_from_keys() sorts the addresses by value, so we have
744 	 * to preserve their order in a separate data structure to treat
745 	 * src and dst host addresses as independently selectable.
746 	 */
747 	host_keys = keys;
748 	host_keys.ports.ports     = 0;
749 	host_keys.basic.ip_proto  = 0;
750 	host_keys.keyid.keyid     = 0;
751 	host_keys.tags.flow_label = 0;
752 
753 	switch (host_keys.control.addr_type) {
754 	case FLOW_DISSECTOR_KEY_IPV4_ADDRS:
755 		host_keys.addrs.v4addrs.src = 0;
756 		dsthost_hash = flow_hash_from_keys(&host_keys);
757 		host_keys.addrs.v4addrs.src = keys.addrs.v4addrs.src;
758 		host_keys.addrs.v4addrs.dst = 0;
759 		srchost_hash = flow_hash_from_keys(&host_keys);
760 		break;
761 
762 	case FLOW_DISSECTOR_KEY_IPV6_ADDRS:
763 		memset(&host_keys.addrs.v6addrs.src, 0,
764 		       sizeof(host_keys.addrs.v6addrs.src));
765 		dsthost_hash = flow_hash_from_keys(&host_keys);
766 		host_keys.addrs.v6addrs.src = keys.addrs.v6addrs.src;
767 		memset(&host_keys.addrs.v6addrs.dst, 0,
768 		       sizeof(host_keys.addrs.v6addrs.dst));
769 		srchost_hash = flow_hash_from_keys(&host_keys);
770 		break;
771 
772 	default:
773 		dsthost_hash = 0;
774 		srchost_hash = 0;
775 	}
776 
777 	/* This *must* be after the above switch, since as a
778 	 * side-effect it sorts the src and dst addresses.
779 	 */
780 	if (hash_flows && !use_skbhash)
781 		flow_hash = flow_hash_from_keys(&keys);
782 
783 skip_hash:
784 	if (flow_override)
785 		flow_hash = flow_override - 1;
786 	else if (use_skbhash && (flow_mode & CAKE_FLOW_FLOWS))
787 		flow_hash = skb->hash;
788 	if (host_override) {
789 		dsthost_hash = host_override - 1;
790 		srchost_hash = host_override - 1;
791 	}
792 
793 	if (!(flow_mode & CAKE_FLOW_FLOWS)) {
794 		if (flow_mode & CAKE_FLOW_SRC_IP)
795 			flow_hash ^= srchost_hash;
796 
797 		if (flow_mode & CAKE_FLOW_DST_IP)
798 			flow_hash ^= dsthost_hash;
799 	}
800 
801 	reduced_hash = flow_hash % CAKE_QUEUES;
802 
803 	/* set-associative hashing */
804 	/* fast path if no hash collision (direct lookup succeeds) */
805 	if (likely(q->tags[reduced_hash] == flow_hash &&
806 		   q->flows[reduced_hash].set)) {
807 		q->way_directs++;
808 	} else {
809 		u32 inner_hash = reduced_hash % CAKE_SET_WAYS;
810 		u32 outer_hash = reduced_hash - inner_hash;
811 		bool allocate_src = false;
812 		bool allocate_dst = false;
813 		u32 i, k;
814 
815 		/* check if any active queue in the set is reserved for
816 		 * this flow.
817 		 */
818 		for (i = 0, k = inner_hash; i < CAKE_SET_WAYS;
819 		     i++, k = (k + 1) % CAKE_SET_WAYS) {
820 			if (q->tags[outer_hash + k] == flow_hash) {
821 				if (i)
822 					WRITE_ONCE(q->way_hits, q->way_hits + 1);
823 
824 				if (!q->flows[outer_hash + k].set) {
825 					/* need to increment host refcnts */
826 					allocate_src = cake_dsrc(flow_mode);
827 					allocate_dst = cake_ddst(flow_mode);
828 				}
829 
830 				goto found;
831 			}
832 		}
833 
834 		/* no queue is reserved for this flow, look for an
835 		 * empty one.
836 		 */
837 		for (i = 0; i < CAKE_SET_WAYS;
838 			 i++, k = (k + 1) % CAKE_SET_WAYS) {
839 			if (!q->flows[outer_hash + k].set) {
840 				WRITE_ONCE(q->way_misses, q->way_misses + 1);
841 				allocate_src = cake_dsrc(flow_mode);
842 				allocate_dst = cake_ddst(flow_mode);
843 				goto found;
844 			}
845 		}
846 
847 		/* With no empty queues, default to the original
848 		 * queue, accept the collision, update the host tags.
849 		 */
850 		WRITE_ONCE(q->way_collisions, q->way_collisions + 1);
851 		allocate_src = cake_dsrc(flow_mode);
852 		allocate_dst = cake_ddst(flow_mode);
853 
854 		if (q->flows[outer_hash + k].set == CAKE_SET_BULK) {
855 			cake_dec_srchost_bulk_flow_count(q, &q->flows[outer_hash + k], flow_mode);
856 			cake_dec_dsthost_bulk_flow_count(q, &q->flows[outer_hash + k], flow_mode);
857 		}
858 found:
859 		/* reserve queue for future packets in same flow */
860 		reduced_hash = outer_hash + k;
861 		q->tags[reduced_hash] = flow_hash;
862 
863 		if (allocate_src) {
864 			srchost_idx = srchost_hash % CAKE_QUEUES;
865 			inner_hash = srchost_idx % CAKE_SET_WAYS;
866 			outer_hash = srchost_idx - inner_hash;
867 			for (i = 0, k = inner_hash; i < CAKE_SET_WAYS;
868 				i++, k = (k + 1) % CAKE_SET_WAYS) {
869 				if (q->hosts[outer_hash + k].srchost_tag ==
870 				    srchost_hash)
871 					goto found_src;
872 			}
873 			for (i = 0; i < CAKE_SET_WAYS;
874 				i++, k = (k + 1) % CAKE_SET_WAYS) {
875 				if (!q->hosts[outer_hash + k].srchost_bulk_flow_count)
876 					break;
877 			}
878 			q->hosts[outer_hash + k].srchost_tag = srchost_hash;
879 found_src:
880 			srchost_idx = outer_hash + k;
881 			q->flows[reduced_hash].srchost = srchost_idx;
882 
883 			if (q->flows[reduced_hash].set == CAKE_SET_BULK)
884 				cake_inc_srchost_bulk_flow_count(q, &q->flows[reduced_hash], flow_mode);
885 		}
886 
887 		if (allocate_dst) {
888 			dsthost_idx = dsthost_hash % CAKE_QUEUES;
889 			inner_hash = dsthost_idx % CAKE_SET_WAYS;
890 			outer_hash = dsthost_idx - inner_hash;
891 			for (i = 0, k = inner_hash; i < CAKE_SET_WAYS;
892 			     i++, k = (k + 1) % CAKE_SET_WAYS) {
893 				if (q->hosts[outer_hash + k].dsthost_tag ==
894 				    dsthost_hash)
895 					goto found_dst;
896 			}
897 			for (i = 0; i < CAKE_SET_WAYS;
898 			     i++, k = (k + 1) % CAKE_SET_WAYS) {
899 				if (!q->hosts[outer_hash + k].dsthost_bulk_flow_count)
900 					break;
901 			}
902 			q->hosts[outer_hash + k].dsthost_tag = dsthost_hash;
903 found_dst:
904 			dsthost_idx = outer_hash + k;
905 			q->flows[reduced_hash].dsthost = dsthost_idx;
906 
907 			if (q->flows[reduced_hash].set == CAKE_SET_BULK)
908 				cake_inc_dsthost_bulk_flow_count(q, &q->flows[reduced_hash], flow_mode);
909 		}
910 	}
911 
912 	return reduced_hash;
913 }
914 
915 /* helper functions : might be changed when/if skb use a standard list_head */
916 /* remove one skb from head of slot queue */
917 
dequeue_head(struct cake_flow * flow)918 static struct sk_buff *dequeue_head(struct cake_flow *flow)
919 {
920 	struct sk_buff *skb = flow->head;
921 
922 	if (skb) {
923 		WRITE_ONCE(flow->head, skb->next);
924 		skb_mark_not_on_list(skb);
925 	}
926 
927 	return skb;
928 }
929 
930 /* add skb to flow queue (tail add) */
931 
flow_queue_add(struct cake_flow * flow,struct sk_buff * skb)932 static void flow_queue_add(struct cake_flow *flow, struct sk_buff *skb)
933 {
934 	if (!flow->head)
935 		WRITE_ONCE(flow->head, skb);
936 	else
937 		flow->tail->next = skb;
938 	flow->tail = skb;
939 	skb->next = NULL;
940 }
941 
cake_get_iphdr(const struct sk_buff * skb,struct ipv6hdr * buf)942 static struct iphdr *cake_get_iphdr(const struct sk_buff *skb,
943 				    struct ipv6hdr *buf)
944 {
945 	unsigned int offset = skb_network_offset(skb);
946 	struct iphdr *iph;
947 
948 	iph = skb_header_pointer(skb, offset, sizeof(struct iphdr), buf);
949 
950 	if (!iph)
951 		return NULL;
952 
953 	if (iph->version == 4 && iph->protocol == IPPROTO_IPV6)
954 		return skb_header_pointer(skb, offset + iph->ihl * 4,
955 					  sizeof(struct ipv6hdr), buf);
956 
957 	else if (iph->version == 4)
958 		return iph;
959 
960 	else if (iph->version == 6)
961 		return skb_header_pointer(skb, offset, sizeof(struct ipv6hdr),
962 					  buf);
963 
964 	return NULL;
965 }
966 
cake_get_tcphdr(const struct sk_buff * skb,void * buf,unsigned int bufsize)967 static struct tcphdr *cake_get_tcphdr(const struct sk_buff *skb,
968 				      void *buf, unsigned int bufsize)
969 {
970 	unsigned int offset = skb_network_offset(skb);
971 	const struct ipv6hdr *ipv6h;
972 	const struct tcphdr *tcph;
973 	const struct iphdr *iph;
974 	struct ipv6hdr _ipv6h;
975 	struct tcphdr _tcph;
976 
977 	ipv6h = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
978 
979 	if (!ipv6h)
980 		return NULL;
981 
982 	if (ipv6h->version == 4) {
983 		iph = (struct iphdr *)ipv6h;
984 		offset += iph->ihl * 4;
985 
986 		/* special-case 6in4 tunnelling, as that is a common way to get
987 		 * v6 connectivity in the home
988 		 */
989 		if (iph->protocol == IPPROTO_IPV6) {
990 			ipv6h = skb_header_pointer(skb, offset,
991 						   sizeof(_ipv6h), &_ipv6h);
992 
993 			if (!ipv6h || ipv6h->nexthdr != IPPROTO_TCP)
994 				return NULL;
995 
996 			offset += sizeof(struct ipv6hdr);
997 
998 		} else if (iph->protocol != IPPROTO_TCP) {
999 			return NULL;
1000 		}
1001 
1002 	} else if (ipv6h->version == 6) {
1003 		if (ipv6h->nexthdr != IPPROTO_TCP)
1004 			return NULL;
1005 
1006 		offset += sizeof(struct ipv6hdr);
1007 	} else {
1008 		return NULL;
1009 	}
1010 
1011 	tcph = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
1012 	if (!tcph || tcph->doff < 5)
1013 		return NULL;
1014 
1015 	return skb_header_pointer(skb, offset,
1016 				  min(__tcp_hdrlen(tcph), bufsize), buf);
1017 }
1018 
cake_get_tcpopt(const struct tcphdr * tcph,int code,int * oplen)1019 static const void *cake_get_tcpopt(const struct tcphdr *tcph,
1020 				   int code, int *oplen)
1021 {
1022 	/* inspired by tcp_parse_options in tcp_input.c */
1023 	int length = __tcp_hdrlen(tcph) - sizeof(struct tcphdr);
1024 	const u8 *ptr = (const u8 *)(tcph + 1);
1025 
1026 	while (length > 0) {
1027 		int opcode = *ptr++;
1028 		int opsize;
1029 
1030 		if (opcode == TCPOPT_EOL)
1031 			break;
1032 		if (opcode == TCPOPT_NOP) {
1033 			length--;
1034 			continue;
1035 		}
1036 		if (length < 2)
1037 			break;
1038 		opsize = *ptr++;
1039 		if (opsize < 2 || opsize > length)
1040 			break;
1041 
1042 		if (opcode == code) {
1043 			*oplen = opsize;
1044 			return ptr;
1045 		}
1046 
1047 		ptr += opsize - 2;
1048 		length -= opsize;
1049 	}
1050 
1051 	return NULL;
1052 }
1053 
1054 /* Compare two SACK sequences. A sequence is considered greater if it SACKs more
1055  * bytes than the other. In the case where both sequences ACKs bytes that the
1056  * other doesn't, A is considered greater. DSACKs in A also makes A be
1057  * considered greater.
1058  *
1059  * @return -1, 0 or 1 as normal compare functions
1060  */
cake_tcph_sack_compare(const struct tcphdr * tcph_a,const struct tcphdr * tcph_b)1061 static int cake_tcph_sack_compare(const struct tcphdr *tcph_a,
1062 				  const struct tcphdr *tcph_b)
1063 {
1064 	const struct tcp_sack_block_wire *sack_a, *sack_b;
1065 	u32 ack_seq_a = ntohl(tcph_a->ack_seq);
1066 	u32 bytes_a = 0, bytes_b = 0;
1067 	int oplen_a, oplen_b;
1068 	bool first = true;
1069 
1070 	sack_a = cake_get_tcpopt(tcph_a, TCPOPT_SACK, &oplen_a);
1071 	sack_b = cake_get_tcpopt(tcph_b, TCPOPT_SACK, &oplen_b);
1072 
1073 	/* pointers point to option contents */
1074 	oplen_a -= TCPOLEN_SACK_BASE;
1075 	oplen_b -= TCPOLEN_SACK_BASE;
1076 
1077 	if (sack_a && oplen_a >= sizeof(*sack_a) &&
1078 	    (!sack_b || oplen_b < sizeof(*sack_b)))
1079 		return -1;
1080 	else if (sack_b && oplen_b >= sizeof(*sack_b) &&
1081 		 (!sack_a || oplen_a < sizeof(*sack_a)))
1082 		return 1;
1083 	else if ((!sack_a || oplen_a < sizeof(*sack_a)) &&
1084 		 (!sack_b || oplen_b < sizeof(*sack_b)))
1085 		return 0;
1086 
1087 	while (oplen_a >= sizeof(*sack_a)) {
1088 		const struct tcp_sack_block_wire *sack_tmp = sack_b;
1089 		u32 start_a = get_unaligned_be32(&sack_a->start_seq);
1090 		u32 end_a = get_unaligned_be32(&sack_a->end_seq);
1091 		int oplen_tmp = oplen_b;
1092 		bool found = false;
1093 
1094 		/* DSACK; always considered greater to prevent dropping */
1095 		if (before(start_a, ack_seq_a))
1096 			return -1;
1097 
1098 		bytes_a += end_a - start_a;
1099 
1100 		while (oplen_tmp >= sizeof(*sack_tmp)) {
1101 			u32 start_b = get_unaligned_be32(&sack_tmp->start_seq);
1102 			u32 end_b = get_unaligned_be32(&sack_tmp->end_seq);
1103 
1104 			/* first time through we count the total size */
1105 			if (first)
1106 				bytes_b += end_b - start_b;
1107 
1108 			if (!after(start_b, start_a) && !before(end_b, end_a)) {
1109 				found = true;
1110 				if (!first)
1111 					break;
1112 			}
1113 			oplen_tmp -= sizeof(*sack_tmp);
1114 			sack_tmp++;
1115 		}
1116 
1117 		if (!found)
1118 			return -1;
1119 
1120 		oplen_a -= sizeof(*sack_a);
1121 		sack_a++;
1122 		first = false;
1123 	}
1124 
1125 	/* If we made it this far, all ranges SACKed by A are covered by B, so
1126 	 * either the SACKs are equal, or B SACKs more bytes.
1127 	 */
1128 	return bytes_b > bytes_a ? 1 : 0;
1129 }
1130 
cake_tcph_get_tstamp(const struct tcphdr * tcph,u32 * tsval,u32 * tsecr)1131 static void cake_tcph_get_tstamp(const struct tcphdr *tcph,
1132 				 u32 *tsval, u32 *tsecr)
1133 {
1134 	const u8 *ptr;
1135 	int opsize;
1136 
1137 	ptr = cake_get_tcpopt(tcph, TCPOPT_TIMESTAMP, &opsize);
1138 
1139 	if (ptr && opsize == TCPOLEN_TIMESTAMP) {
1140 		*tsval = get_unaligned_be32(ptr);
1141 		*tsecr = get_unaligned_be32(ptr + 4);
1142 	}
1143 }
1144 
cake_tcph_may_drop(const struct tcphdr * tcph,u32 tstamp_new,u32 tsecr_new)1145 static bool cake_tcph_may_drop(const struct tcphdr *tcph,
1146 			       u32 tstamp_new, u32 tsecr_new)
1147 {
1148 	/* inspired by tcp_parse_options in tcp_input.c */
1149 	int length = __tcp_hdrlen(tcph) - sizeof(struct tcphdr);
1150 	const u8 *ptr = (const u8 *)(tcph + 1);
1151 	u32 tstamp, tsecr;
1152 
1153 	/* 3 reserved flags must be unset to avoid future breakage
1154 	 * ACK must be set
1155 	 * ECE/CWR are handled separately
1156 	 * All other flags URG/PSH/RST/SYN/FIN must be unset
1157 	 * 0x0FFF0000 = all TCP flags (confirm ACK=1, others zero)
1158 	 * 0x00C00000 = CWR/ECE (handled separately)
1159 	 * 0x0F3F0000 = 0x0FFF0000 & ~0x00C00000
1160 	 */
1161 	if (((tcp_flag_word(tcph) &
1162 	      cpu_to_be32(0x0F3F0000)) != TCP_FLAG_ACK))
1163 		return false;
1164 
1165 	while (length > 0) {
1166 		int opcode = *ptr++;
1167 		int opsize;
1168 
1169 		if (opcode == TCPOPT_EOL)
1170 			break;
1171 		if (opcode == TCPOPT_NOP) {
1172 			length--;
1173 			continue;
1174 		}
1175 		if (length < 2)
1176 			break;
1177 		opsize = *ptr++;
1178 		if (opsize < 2 || opsize > length)
1179 			break;
1180 
1181 		switch (opcode) {
1182 		case TCPOPT_MD5SIG: /* doesn't influence state */
1183 			break;
1184 
1185 		case TCPOPT_SACK: /* stricter checking performed later */
1186 			if (opsize % 8 != 2)
1187 				return false;
1188 			break;
1189 
1190 		case TCPOPT_TIMESTAMP:
1191 			/* only drop timestamps lower than new */
1192 			if (opsize != TCPOLEN_TIMESTAMP)
1193 				return false;
1194 			tstamp = get_unaligned_be32(ptr);
1195 			tsecr = get_unaligned_be32(ptr + 4);
1196 			if (after(tstamp, tstamp_new) ||
1197 			    after(tsecr, tsecr_new))
1198 				return false;
1199 			break;
1200 
1201 		case TCPOPT_MSS:  /* these should only be set on SYN */
1202 		case TCPOPT_WINDOW:
1203 		case TCPOPT_SACK_PERM:
1204 		case TCPOPT_FASTOPEN:
1205 		case TCPOPT_EXP:
1206 		default: /* don't drop if any unknown options are present */
1207 			return false;
1208 		}
1209 
1210 		ptr += opsize - 2;
1211 		length -= opsize;
1212 	}
1213 
1214 	return true;
1215 }
1216 
cake_ack_filter(struct cake_sched_data * q,struct cake_flow * flow)1217 static struct sk_buff *cake_ack_filter(struct cake_sched_data *q,
1218 				       struct cake_flow *flow)
1219 {
1220 	bool aggressive = q->config->ack_filter == CAKE_ACK_AGGRESSIVE;
1221 	struct sk_buff *elig_ack = NULL, *elig_ack_prev = NULL;
1222 	struct sk_buff *skb_check, *skb_prev = NULL;
1223 	const struct ipv6hdr *ipv6h, *ipv6h_check;
1224 	unsigned char _tcph[64], _tcph_check[64];
1225 	const struct tcphdr *tcph, *tcph_check;
1226 	const struct iphdr *iph, *iph_check;
1227 	struct ipv6hdr _iph, _iph_check;
1228 	const struct sk_buff *skb;
1229 	int seglen, num_found = 0;
1230 	u32 tstamp = 0, tsecr = 0;
1231 	__be32 elig_flags = 0;
1232 	int sack_comp;
1233 
1234 	/* no other possible ACKs to filter */
1235 	if (flow->head == flow->tail)
1236 		return NULL;
1237 
1238 	skb = flow->tail;
1239 	tcph = cake_get_tcphdr(skb, _tcph, sizeof(_tcph));
1240 	iph = cake_get_iphdr(skb, &_iph);
1241 	if (!tcph)
1242 		return NULL;
1243 
1244 	cake_tcph_get_tstamp(tcph, &tstamp, &tsecr);
1245 
1246 	/* the 'triggering' packet need only have the ACK flag set.
1247 	 * also check that SYN is not set, as there won't be any previous ACKs.
1248 	 */
1249 	if ((tcp_flag_word(tcph) &
1250 	     (TCP_FLAG_ACK | TCP_FLAG_SYN)) != TCP_FLAG_ACK)
1251 		return NULL;
1252 
1253 	/* the 'triggering' ACK is at the tail of the queue, we have already
1254 	 * returned if it is the only packet in the flow. loop through the rest
1255 	 * of the queue looking for pure ACKs with the same 5-tuple as the
1256 	 * triggering one.
1257 	 */
1258 	for (skb_check = flow->head;
1259 	     skb_check && skb_check != skb;
1260 	     skb_prev = skb_check, skb_check = skb_check->next) {
1261 		iph_check = cake_get_iphdr(skb_check, &_iph_check);
1262 		tcph_check = cake_get_tcphdr(skb_check, &_tcph_check,
1263 					     sizeof(_tcph_check));
1264 
1265 		/* only TCP packets with matching 5-tuple are eligible, and only
1266 		 * drop safe headers
1267 		 */
1268 		if (!tcph_check || iph->version != iph_check->version ||
1269 		    tcph_check->source != tcph->source ||
1270 		    tcph_check->dest != tcph->dest)
1271 			continue;
1272 
1273 		if (iph_check->version == 4) {
1274 			if (iph_check->saddr != iph->saddr ||
1275 			    iph_check->daddr != iph->daddr)
1276 				continue;
1277 
1278 			seglen = iph_totlen(skb, iph_check) -
1279 				       (4 * iph_check->ihl);
1280 		} else if (iph_check->version == 6) {
1281 			ipv6h = (struct ipv6hdr *)iph;
1282 			ipv6h_check = (struct ipv6hdr *)iph_check;
1283 
1284 			if (ipv6_addr_cmp(&ipv6h_check->saddr, &ipv6h->saddr) ||
1285 			    ipv6_addr_cmp(&ipv6h_check->daddr, &ipv6h->daddr))
1286 				continue;
1287 
1288 			seglen = ipv6_payload_len(skb, ipv6h_check);
1289 		} else {
1290 			continue;
1291 		}
1292 
1293 		/* If the ECE/CWR flags changed from the previous eligible
1294 		 * packet in the same flow, we should no longer be dropping that
1295 		 * previous packet as this would lose information.
1296 		 */
1297 		if (elig_ack && (tcp_flag_word(tcph_check) &
1298 				 (TCP_FLAG_ECE | TCP_FLAG_CWR)) != elig_flags) {
1299 			elig_ack = NULL;
1300 			elig_ack_prev = NULL;
1301 			num_found--;
1302 		}
1303 
1304 		/* Check TCP options and flags, don't drop ACKs with segment
1305 		 * data, and don't drop ACKs with a higher cumulative ACK
1306 		 * counter than the triggering packet. Check ACK seqno here to
1307 		 * avoid parsing SACK options of packets we are going to exclude
1308 		 * anyway.
1309 		 */
1310 		if (!cake_tcph_may_drop(tcph_check, tstamp, tsecr) ||
1311 		    (seglen - __tcp_hdrlen(tcph_check)) != 0 ||
1312 		    after(ntohl(tcph_check->ack_seq), ntohl(tcph->ack_seq)))
1313 			continue;
1314 
1315 		/* Check SACK options. The triggering packet must SACK more data
1316 		 * than the ACK under consideration, or SACK the same range but
1317 		 * have a larger cumulative ACK counter. The latter is a
1318 		 * pathological case, but is contained in the following check
1319 		 * anyway, just to be safe.
1320 		 */
1321 		sack_comp = cake_tcph_sack_compare(tcph_check, tcph);
1322 
1323 		if (sack_comp < 0 ||
1324 		    (ntohl(tcph_check->ack_seq) == ntohl(tcph->ack_seq) &&
1325 		     sack_comp == 0))
1326 			continue;
1327 
1328 		/* At this point we have found an eligible pure ACK to drop; if
1329 		 * we are in aggressive mode, we are done. Otherwise, keep
1330 		 * searching unless this is the second eligible ACK we
1331 		 * found.
1332 		 *
1333 		 * Since we want to drop ACK closest to the head of the queue,
1334 		 * save the first eligible ACK we find, even if we need to loop
1335 		 * again.
1336 		 */
1337 		if (!elig_ack) {
1338 			elig_ack = skb_check;
1339 			elig_ack_prev = skb_prev;
1340 			elig_flags = (tcp_flag_word(tcph_check)
1341 				      & (TCP_FLAG_ECE | TCP_FLAG_CWR));
1342 		}
1343 
1344 		if (num_found++ > 0)
1345 			goto found;
1346 	}
1347 
1348 	/* We made it through the queue without finding two eligible ACKs . If
1349 	 * we found a single eligible ACK we can drop it in aggressive mode if
1350 	 * we can guarantee that this does not interfere with ECN flag
1351 	 * information. We ensure this by dropping it only if the enqueued
1352 	 * packet is consecutive with the eligible ACK, and their flags match.
1353 	 */
1354 	if (elig_ack && aggressive && elig_ack->next == skb &&
1355 	    (elig_flags == (tcp_flag_word(tcph) &
1356 			    (TCP_FLAG_ECE | TCP_FLAG_CWR))))
1357 		goto found;
1358 
1359 	return NULL;
1360 
1361 found:
1362 	if (elig_ack_prev)
1363 		elig_ack_prev->next = elig_ack->next;
1364 	else
1365 		WRITE_ONCE(flow->head, elig_ack->next);
1366 
1367 	skb_mark_not_on_list(elig_ack);
1368 
1369 	return elig_ack;
1370 }
1371 
cake_ewma(u64 avg,u64 sample,u32 shift)1372 static u64 cake_ewma(u64 avg, u64 sample, u32 shift)
1373 {
1374 	avg -= avg >> shift;
1375 	avg += sample >> shift;
1376 	return avg;
1377 }
1378 
cake_calc_overhead(struct cake_sched_data * qd,u32 len,u32 off)1379 static u32 cake_calc_overhead(struct cake_sched_data *qd, u32 len, u32 off)
1380 {
1381 	struct cake_sched_config *q = qd->config;
1382 
1383 	if (q->rate_flags & CAKE_FLAG_OVERHEAD)
1384 		len -= off;
1385 
1386 	if (qd->max_netlen < len)
1387 		WRITE_ONCE(qd->max_netlen, len);
1388 	if (qd->min_netlen > len)
1389 		WRITE_ONCE(qd->min_netlen, len);
1390 
1391 	len = max((s32)len + q->rate_overhead, (s32)q->rate_mpu);
1392 
1393 	if (q->atm_mode == CAKE_ATM_ATM) {
1394 		len += 47;
1395 		len /= 48;
1396 		len *= 53;
1397 	} else if (q->atm_mode == CAKE_ATM_PTM) {
1398 		/* Add one byte per 64 bytes or part thereof.
1399 		 * This is conservative and easier to calculate than the
1400 		 * precise value.
1401 		 */
1402 		len += (len + 63) / 64;
1403 	}
1404 
1405 	if (qd->max_adjlen < len)
1406 		WRITE_ONCE(qd->max_adjlen, len);
1407 	if (qd->min_adjlen > len)
1408 		WRITE_ONCE(qd->min_adjlen, len);
1409 
1410 	return len;
1411 }
1412 
cake_overhead(struct cake_sched_data * q,const struct sk_buff * skb)1413 static u32 cake_overhead(struct cake_sched_data *q, const struct sk_buff *skb)
1414 {
1415 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
1416 	unsigned int hdr_len, last_len = 0;
1417 	u32 off = skb_network_offset(skb);
1418 	u16 segs = qdisc_pkt_segs(skb);
1419 	u32 len = qdisc_pkt_len(skb);
1420 
1421 	WRITE_ONCE(q->avg_netoff, cake_ewma(q->avg_netoff, off << 16, 8));
1422 
1423 	if (segs == 1)
1424 		return cake_calc_overhead(q, len, off);
1425 
1426 	/* borrowed from qdisc_pkt_len_segs_init() */
1427 	if (!skb->encapsulation)
1428 		hdr_len = skb_transport_offset(skb);
1429 	else
1430 		hdr_len = skb_inner_transport_offset(skb);
1431 
1432 	/* + transport layer */
1433 	if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 |
1434 						SKB_GSO_TCPV6))) {
1435 		const struct tcphdr *th;
1436 		struct tcphdr _tcphdr;
1437 
1438 		th = skb_header_pointer(skb, hdr_len,
1439 					sizeof(_tcphdr), &_tcphdr);
1440 		if (likely(th))
1441 			hdr_len += __tcp_hdrlen(th);
1442 	} else {
1443 		struct udphdr _udphdr;
1444 
1445 		if (skb_header_pointer(skb, hdr_len,
1446 				       sizeof(_udphdr), &_udphdr))
1447 			hdr_len += sizeof(struct udphdr);
1448 	}
1449 
1450 	len = shinfo->gso_size + hdr_len;
1451 	last_len = skb->len - shinfo->gso_size * (segs - 1);
1452 
1453 	return (cake_calc_overhead(q, len, off) * (segs - 1) +
1454 		cake_calc_overhead(q, last_len, off));
1455 }
1456 
cake_heap_swap(struct cake_sched_data * q,u16 i,u16 j)1457 static void cake_heap_swap(struct cake_sched_data *q, u16 i, u16 j)
1458 {
1459 	struct cake_heap_entry ii = q->overflow_heap[i];
1460 	struct cake_heap_entry jj = q->overflow_heap[j];
1461 
1462 	q->overflow_heap[i] = jj;
1463 	q->overflow_heap[j] = ii;
1464 
1465 	q->tins[ii.t].overflow_idx[ii.b] = j;
1466 	q->tins[jj.t].overflow_idx[jj.b] = i;
1467 }
1468 
cake_heap_get_backlog(const struct cake_sched_data * q,u16 i)1469 static u32 cake_heap_get_backlog(const struct cake_sched_data *q, u16 i)
1470 {
1471 	struct cake_heap_entry ii = q->overflow_heap[i];
1472 
1473 	return q->tins[ii.t].backlogs[ii.b];
1474 }
1475 
cake_heapify(struct cake_sched_data * q,u16 i)1476 static void cake_heapify(struct cake_sched_data *q, u16 i)
1477 {
1478 	static const u32 a = CAKE_MAX_TINS * CAKE_QUEUES;
1479 	u32 mb = cake_heap_get_backlog(q, i);
1480 	u32 m = i;
1481 
1482 	while (m < a) {
1483 		u32 l = m + m + 1;
1484 		u32 r = l + 1;
1485 
1486 		if (l < a) {
1487 			u32 lb = cake_heap_get_backlog(q, l);
1488 
1489 			if (lb > mb) {
1490 				m  = l;
1491 				mb = lb;
1492 			}
1493 		}
1494 
1495 		if (r < a) {
1496 			u32 rb = cake_heap_get_backlog(q, r);
1497 
1498 			if (rb > mb) {
1499 				m  = r;
1500 				mb = rb;
1501 			}
1502 		}
1503 
1504 		if (m != i) {
1505 			cake_heap_swap(q, i, m);
1506 			i = m;
1507 		} else {
1508 			break;
1509 		}
1510 	}
1511 }
1512 
cake_heapify_up(struct cake_sched_data * q,u16 i)1513 static void cake_heapify_up(struct cake_sched_data *q, u16 i)
1514 {
1515 	while (i > 0 && i < CAKE_MAX_TINS * CAKE_QUEUES) {
1516 		u16 p = (i - 1) >> 1;
1517 		u32 ib = cake_heap_get_backlog(q, i);
1518 		u32 pb = cake_heap_get_backlog(q, p);
1519 
1520 		if (ib > pb) {
1521 			cake_heap_swap(q, i, p);
1522 			i = p;
1523 		} else {
1524 			break;
1525 		}
1526 	}
1527 }
1528 
cake_advance_shaper(struct cake_sched_data * q,struct cake_tin_data * b,struct sk_buff * skb,ktime_t now,bool drop)1529 static int cake_advance_shaper(struct cake_sched_data *q,
1530 			       struct cake_tin_data *b,
1531 			       struct sk_buff *skb,
1532 			       ktime_t now, bool drop)
1533 {
1534 	u32 len = get_cobalt_cb(skb)->adjusted_len;
1535 
1536 	/* charge packet bandwidth to this tin
1537 	 * and to the global shaper.
1538 	 */
1539 	if (q->rate_ns) {
1540 		u64 tin_dur = (len * b->tin_rate_ns) >> b->tin_rate_shft;
1541 		u64 global_dur = (len * q->rate_ns) >> q->rate_shft;
1542 		u64 failsafe_dur = global_dur + (global_dur >> 1);
1543 
1544 		if (ktime_before(b->time_next_packet, now))
1545 			b->time_next_packet = ktime_add_ns(b->time_next_packet,
1546 							   tin_dur);
1547 
1548 		else if (ktime_before(b->time_next_packet,
1549 				      ktime_add_ns(now, tin_dur)))
1550 			b->time_next_packet = ktime_add_ns(now, tin_dur);
1551 
1552 		q->time_next_packet = ktime_add_ns(q->time_next_packet,
1553 						   global_dur);
1554 		if (!drop)
1555 			q->failsafe_next_packet = \
1556 				ktime_add_ns(q->failsafe_next_packet,
1557 					     failsafe_dur);
1558 	}
1559 	return len;
1560 }
1561 
cake_drop(struct Qdisc * sch,struct sk_buff ** to_free)1562 static unsigned int cake_drop(struct Qdisc *sch, struct sk_buff **to_free)
1563 {
1564 	struct cake_sched_data *q = qdisc_priv(sch);
1565 	ktime_t now = ktime_get();
1566 	u32 idx = 0, tin = 0, len;
1567 	struct cake_heap_entry qq;
1568 	struct cake_tin_data *b;
1569 	struct cake_flow *flow;
1570 	struct sk_buff *skb;
1571 
1572 	if (!q->overflow_timeout) {
1573 		int i;
1574 		/* Build fresh max-heap */
1575 		for (i = CAKE_MAX_TINS * CAKE_QUEUES / 2 - 1; i >= 0; i--)
1576 			cake_heapify(q, i);
1577 	}
1578 	q->overflow_timeout = 65535;
1579 
1580 	/* select longest queue for pruning */
1581 	qq  = q->overflow_heap[0];
1582 	tin = qq.t;
1583 	idx = qq.b;
1584 
1585 	b = &q->tins[tin];
1586 	flow = &b->flows[idx];
1587 	skb = dequeue_head(flow);
1588 	if (unlikely(!skb)) {
1589 		/* heap has gone wrong, rebuild it next time */
1590 		q->overflow_timeout = 0;
1591 		return idx + (tin << 16);
1592 	}
1593 
1594 	if (cobalt_queue_full(&flow->cvars, &b->cparams, now))
1595 		WRITE_ONCE(b->unresponsive_flow_count,
1596 			   b->unresponsive_flow_count + 1);
1597 
1598 	len = qdisc_pkt_len(skb);
1599 	qstats_backlog_sub(sch, len);
1600 	q->buffer_used -= skb->truesize;
1601 	WRITE_ONCE(b->tin_backlog, b->tin_backlog - len);
1602 	WRITE_ONCE(b->backlogs[idx], b->backlogs[idx] - len);
1603 
1604 	WRITE_ONCE(flow->dropped, flow->dropped + 1);
1605 	WRITE_ONCE(b->tin_dropped, b->tin_dropped + 1);
1606 
1607 	if (q->config->rate_flags & CAKE_FLAG_INGRESS)
1608 		cake_advance_shaper(q, b, skb, now, true);
1609 
1610 	qdisc_drop_reason(skb, sch, to_free, QDISC_DROP_OVERLIMIT);
1611 	qdisc_qlen_dec(sch);
1612 
1613 	cake_heapify(q, 0);
1614 
1615 	return idx + (tin << 16);
1616 }
1617 
cake_handle_diffserv(struct sk_buff * skb,bool wash)1618 static u8 cake_handle_diffserv(struct sk_buff *skb, bool wash)
1619 {
1620 	const int offset = skb_network_offset(skb);
1621 	u16 *buf, buf_;
1622 	u8 dscp;
1623 
1624 	switch (skb_protocol(skb, true)) {
1625 	case htons(ETH_P_IP):
1626 		buf = skb_header_pointer(skb, offset, sizeof(buf_), &buf_);
1627 		if (unlikely(!buf))
1628 			return 0;
1629 
1630 		/* ToS is in the second byte of iphdr */
1631 		dscp = ipv4_get_dsfield((struct iphdr *)buf) >> 2;
1632 
1633 		if (wash && dscp) {
1634 			const int wlen = offset + sizeof(struct iphdr);
1635 
1636 			if (!pskb_may_pull(skb, wlen) ||
1637 			    skb_try_make_writable(skb, wlen))
1638 				return 0;
1639 
1640 			ipv4_change_dsfield(ip_hdr(skb), INET_ECN_MASK, 0);
1641 		}
1642 
1643 		return dscp;
1644 
1645 	case htons(ETH_P_IPV6):
1646 		buf = skb_header_pointer(skb, offset, sizeof(buf_), &buf_);
1647 		if (unlikely(!buf))
1648 			return 0;
1649 
1650 		/* Traffic class is in the first and second bytes of ipv6hdr */
1651 		dscp = ipv6_get_dsfield((struct ipv6hdr *)buf) >> 2;
1652 
1653 		if (wash && dscp) {
1654 			const int wlen = offset + sizeof(struct ipv6hdr);
1655 
1656 			if (!pskb_may_pull(skb, wlen) ||
1657 			    skb_try_make_writable(skb, wlen))
1658 				return 0;
1659 
1660 			ipv6_change_dsfield(ipv6_hdr(skb), INET_ECN_MASK, 0);
1661 		}
1662 
1663 		return dscp;
1664 
1665 	case htons(ETH_P_ARP):
1666 		return 0x38;  /* CS7 - Net Control */
1667 
1668 	default:
1669 		/* If there is no Diffserv field, treat as best-effort */
1670 		return 0;
1671 	}
1672 }
1673 
cake_select_tin(struct Qdisc * sch,struct sk_buff * skb)1674 static struct cake_tin_data *cake_select_tin(struct Qdisc *sch,
1675 					     struct sk_buff *skb)
1676 {
1677 	struct cake_sched_data *qd = qdisc_priv(sch);
1678 	struct cake_sched_config *q = qd->config;
1679 	u32 tin, mark;
1680 	bool wash;
1681 	u8 dscp;
1682 
1683 	/* Tin selection: Default to diffserv-based selection, allow overriding
1684 	 * using firewall marks or skb->priority. Call DSCP parsing early if
1685 	 * wash is enabled, otherwise defer to below to skip unneeded parsing.
1686 	 */
1687 	mark = (skb->mark & q->fwmark_mask) >> q->fwmark_shft;
1688 	wash = !!(q->rate_flags & CAKE_FLAG_WASH);
1689 	if (wash)
1690 		dscp = cake_handle_diffserv(skb, wash);
1691 
1692 	if (q->tin_mode == CAKE_DIFFSERV_BESTEFFORT)
1693 		tin = 0;
1694 
1695 	else if (mark && mark <= qd->tin_cnt)
1696 		tin = qd->tin_order[mark - 1];
1697 
1698 	else if (TC_H_MAJ(skb->priority) == sch->handle &&
1699 		 TC_H_MIN(skb->priority) > 0 &&
1700 		 TC_H_MIN(skb->priority) <= qd->tin_cnt)
1701 		tin = qd->tin_order[TC_H_MIN(skb->priority) - 1];
1702 
1703 	else {
1704 		if (!wash)
1705 			dscp = cake_handle_diffserv(skb, wash);
1706 		tin = qd->tin_index[dscp];
1707 
1708 		if (unlikely(tin >= qd->tin_cnt))
1709 			tin = 0;
1710 	}
1711 
1712 	return &qd->tins[tin];
1713 }
1714 
cake_classify(struct Qdisc * sch,struct cake_tin_data ** t,struct sk_buff * skb,int flow_mode,int * qerr)1715 static u32 cake_classify(struct Qdisc *sch, struct cake_tin_data **t,
1716 			 struct sk_buff *skb, int flow_mode, int *qerr)
1717 {
1718 	struct cake_sched_data *q = qdisc_priv(sch);
1719 	struct tcf_proto *filter;
1720 	struct tcf_result res;
1721 	u16 flow = 0, host = 0;
1722 	int result;
1723 
1724 	filter = rcu_dereference_bh(q->filter_list);
1725 	if (!filter)
1726 		goto hash;
1727 
1728 	*qerr = NET_XMIT_SUCCESS | __NET_XMIT_BYPASS;
1729 	result = tcf_classify_qdisc(skb, filter, &res, false);
1730 
1731 	if (result >= 0) {
1732 #ifdef CONFIG_NET_CLS_ACT
1733 		switch (result) {
1734 		case TC_ACT_STOLEN:
1735 		case TC_ACT_QUEUED:
1736 		case TC_ACT_TRAP:
1737 			*qerr = NET_XMIT_SUCCESS | __NET_XMIT_STOLEN;
1738 			fallthrough;
1739 		case TC_ACT_SHOT:
1740 			return 0;
1741 		}
1742 #endif
1743 		if (TC_H_MIN(res.classid) <= CAKE_QUEUES)
1744 			flow = TC_H_MIN(res.classid);
1745 		if (TC_H_MAJ(res.classid) <= (CAKE_QUEUES << 16))
1746 			host = TC_H_MAJ(res.classid) >> 16;
1747 	}
1748 hash:
1749 	*t = cake_select_tin(sch, skb);
1750 	return cake_hash(*t, skb, flow_mode, flow, host) + 1;
1751 }
1752 
1753 static void cake_reconfigure(struct Qdisc *sch);
1754 
cake_enqueue(struct sk_buff * skb,struct Qdisc * sch,struct sk_buff ** to_free)1755 static s32 cake_enqueue(struct sk_buff *skb, struct Qdisc *sch,
1756 			struct sk_buff **to_free)
1757 {
1758 	u32 idx, tin, prev_qlen, prev_backlog, drop_id;
1759 	struct cake_sched_data *q = qdisc_priv(sch);
1760 	int len = qdisc_pkt_len(skb), ret;
1761 	struct sk_buff *ack = NULL;
1762 	ktime_t now = ktime_get();
1763 	struct cake_tin_data *b;
1764 	struct cake_flow *flow;
1765 	bool same_flow = false;
1766 
1767 	/* choose flow to insert into */
1768 	idx = cake_classify(sch, &b, skb, q->config->flow_mode, &ret);
1769 	if (idx == 0) {
1770 		if (ret & __NET_XMIT_BYPASS)
1771 			qdisc_qstats_drop(sch);
1772 		__qdisc_drop(skb, to_free);
1773 		return ret;
1774 	}
1775 	tin = (u32)(b - q->tins);
1776 	idx--;
1777 	flow = &b->flows[idx];
1778 
1779 	/* ensure shaper state isn't stale */
1780 	if (!b->tin_backlog) {
1781 		if (ktime_before(b->time_next_packet, now))
1782 			b->time_next_packet = now;
1783 
1784 		if (!sch->q.qlen) {
1785 			if (ktime_before(q->time_next_packet, now)) {
1786 				q->failsafe_next_packet = now;
1787 				q->time_next_packet = now;
1788 			} else if (ktime_after(q->time_next_packet, now) &&
1789 				   ktime_after(q->failsafe_next_packet, now)) {
1790 				u64 next = \
1791 					min(ktime_to_ns(q->time_next_packet),
1792 					    ktime_to_ns(
1793 						   q->failsafe_next_packet));
1794 				sch->qstats.overlimits++;
1795 				qdisc_watchdog_schedule_ns(&q->watchdog, next);
1796 			}
1797 		}
1798 	}
1799 
1800 	if (unlikely(len > b->max_skblen))
1801 		WRITE_ONCE(b->max_skblen, len);
1802 
1803 	if (qdisc_pkt_segs(skb) > 1 && q->config->rate_flags & CAKE_FLAG_SPLIT_GSO) {
1804 		struct sk_buff *segs, *nskb;
1805 		netdev_features_t features = netif_skb_features(skb);
1806 		unsigned int slen = 0, numsegs = 0;
1807 
1808 		segs = skb_gso_segment(skb, features & ~NETIF_F_GSO_MASK);
1809 		if (IS_ERR_OR_NULL(segs))
1810 			return qdisc_drop(skb, sch, to_free);
1811 
1812 		skb_list_walk_safe(segs, segs, nskb) {
1813 			skb_mark_not_on_list(segs);
1814 			qdisc_skb_cb(segs)->pkt_len = segs->len;
1815 			qdisc_skb_cb(segs)->pkt_segs = 1;
1816 			cobalt_set_enqueue_time(segs, now);
1817 			get_cobalt_cb(segs)->adjusted_len = cake_overhead(q,
1818 									  segs);
1819 			flow_queue_add(flow, segs);
1820 
1821 			qdisc_qlen_inc(sch);
1822 			numsegs++;
1823 			slen += segs->len;
1824 			q->buffer_used += segs->truesize;
1825 			WRITE_ONCE(b->packets, b->packets + 1);
1826 		}
1827 
1828 		/* stats */
1829 		qstats_backlog_add(sch, slen);
1830 		q->avg_window_bytes += slen;
1831 		WRITE_ONCE(b->bytes, b->bytes + slen);
1832 		WRITE_ONCE(b->tin_backlog, b->tin_backlog + slen);
1833 		WRITE_ONCE(b->backlogs[idx], b->backlogs[idx] + slen);
1834 
1835 		qdisc_tree_reduce_backlog(sch, 1-numsegs, len-slen);
1836 		consume_skb(skb);
1837 	} else {
1838 		/* not splitting */
1839 		int ack_pkt_len = 0;
1840 
1841 		cobalt_set_enqueue_time(skb, now);
1842 		get_cobalt_cb(skb)->adjusted_len = cake_overhead(q, skb);
1843 		flow_queue_add(flow, skb);
1844 
1845 		if (q->config->ack_filter)
1846 			ack = cake_ack_filter(q, flow);
1847 
1848 		if (ack) {
1849 			WRITE_ONCE(b->ack_drops, b->ack_drops + 1);
1850 			qdisc_qstats_drop(sch);
1851 			ack_pkt_len = qdisc_pkt_len(ack);
1852 			WRITE_ONCE(b->bytes, b->bytes + ack_pkt_len);
1853 			q->buffer_used += skb->truesize - ack->truesize;
1854 			if (q->config->rate_flags & CAKE_FLAG_INGRESS)
1855 				cake_advance_shaper(q, b, ack, now, true);
1856 
1857 			qdisc_tree_reduce_backlog(sch, 1, ack_pkt_len);
1858 			consume_skb(ack);
1859 		} else {
1860 			qdisc_qlen_inc(sch);
1861 			q->buffer_used      += skb->truesize;
1862 		}
1863 
1864 		/* stats */
1865 		WRITE_ONCE(b->packets, b->packets + 1);
1866 		qstats_backlog_add(sch, len - ack_pkt_len);
1867 		q->avg_window_bytes += len - ack_pkt_len;
1868 		WRITE_ONCE(b->bytes, b->bytes + len - ack_pkt_len);
1869 		WRITE_ONCE(b->tin_backlog, b->tin_backlog + len - ack_pkt_len);
1870 		WRITE_ONCE(b->backlogs[idx], b->backlogs[idx] + len - ack_pkt_len);
1871 	}
1872 
1873 	if (q->overflow_timeout)
1874 		cake_heapify_up(q, b->overflow_idx[idx]);
1875 
1876 	/* incoming bandwidth capacity estimate */
1877 	if (q->config->rate_flags & CAKE_FLAG_AUTORATE_INGRESS) {
1878 		u64 packet_interval = \
1879 			ktime_to_ns(ktime_sub(now, q->last_packet_time));
1880 
1881 		if (packet_interval > NSEC_PER_SEC)
1882 			packet_interval = NSEC_PER_SEC;
1883 
1884 		/* filter out short-term bursts, eg. wifi aggregation */
1885 		q->avg_packet_interval = \
1886 			cake_ewma(q->avg_packet_interval,
1887 				  packet_interval,
1888 				  (packet_interval > q->avg_packet_interval ?
1889 					  2 : 8));
1890 
1891 		q->last_packet_time = now;
1892 
1893 		if (packet_interval > q->avg_packet_interval) {
1894 			u64 window_interval = \
1895 				ktime_to_ns(ktime_sub(now,
1896 						      q->avg_window_begin));
1897 			u64 b = q->avg_window_bytes * (u64)NSEC_PER_SEC;
1898 
1899 			b = div64_u64(b, window_interval);
1900 			WRITE_ONCE(q->avg_peak_bandwidth,
1901 				   cake_ewma(q->avg_peak_bandwidth, b,
1902 					     b > q->avg_peak_bandwidth ? 2 : 8));
1903 			q->avg_window_bytes = 0;
1904 			q->avg_window_begin = now;
1905 
1906 			if (ktime_after(now,
1907 					ktime_add_ms(q->last_reconfig_time,
1908 						     250))) {
1909 				q->config->rate_bps = (q->avg_peak_bandwidth * 15) >> 4;
1910 				cake_reconfigure(sch);
1911 			}
1912 		}
1913 	} else {
1914 		q->avg_window_bytes = 0;
1915 		q->last_packet_time = now;
1916 	}
1917 
1918 	/* flowchain */
1919 	if (!flow->set || flow->set == CAKE_SET_DECAYING) {
1920 		if (!flow->set) {
1921 			list_add_tail(&flow->flowchain, &b->new_flows);
1922 		} else {
1923 			WRITE_ONCE(b->decaying_flow_count, b->decaying_flow_count - 1);
1924 			list_move_tail(&flow->flowchain, &b->new_flows);
1925 		}
1926 		flow->set = CAKE_SET_SPARSE;
1927 		WRITE_ONCE(b->sparse_flow_count, b->sparse_flow_count + 1);
1928 
1929 		WRITE_ONCE(flow->deficit, cake_get_flow_quantum(b, flow, q->config->flow_mode));
1930 	} else if (flow->set == CAKE_SET_SPARSE_WAIT) {
1931 		/* this flow was empty, accounted as a sparse flow, but actually
1932 		 * in the bulk rotation.
1933 		 */
1934 		flow->set = CAKE_SET_BULK;
1935 		WRITE_ONCE(b->sparse_flow_count, b->sparse_flow_count - 1);
1936 		WRITE_ONCE(b->bulk_flow_count, b->bulk_flow_count + 1);
1937 
1938 		cake_inc_srchost_bulk_flow_count(b, flow, q->config->flow_mode);
1939 		cake_inc_dsthost_bulk_flow_count(b, flow, q->config->flow_mode);
1940 	}
1941 
1942 	if (q->buffer_used > q->buffer_max_used)
1943 		WRITE_ONCE(q->buffer_max_used, q->buffer_used);
1944 
1945 	if (q->buffer_used <= q->buffer_limit)
1946 		return NET_XMIT_SUCCESS;
1947 
1948 	prev_qlen = sch->q.qlen;
1949 	prev_backlog = sch->qstats.backlog;
1950 
1951 	while (q->buffer_used > q->buffer_limit) {
1952 		drop_id = cake_drop(sch, to_free);
1953 		if ((drop_id >> 16) == tin &&
1954 		    (drop_id & 0xFFFF) == idx)
1955 			same_flow = true;
1956 	}
1957 
1958 	prev_qlen -= sch->q.qlen;
1959 	prev_backlog -= sch->qstats.backlog;
1960 	b->drop_overlimit += prev_qlen;
1961 
1962 	if (same_flow) {
1963 		qdisc_tree_reduce_backlog(sch, prev_qlen - 1,
1964 					  prev_backlog - len);
1965 		return NET_XMIT_CN;
1966 	}
1967 	qdisc_tree_reduce_backlog(sch, prev_qlen, prev_backlog);
1968 	return NET_XMIT_SUCCESS;
1969 }
1970 
cake_dequeue_one(struct Qdisc * sch)1971 static struct sk_buff *cake_dequeue_one(struct Qdisc *sch)
1972 {
1973 	struct cake_sched_data *q = qdisc_priv(sch);
1974 	struct cake_tin_data *b = &q->tins[q->cur_tin];
1975 	struct cake_flow *flow = &b->flows[q->cur_flow];
1976 	struct sk_buff *skb = NULL;
1977 	u32 len;
1978 
1979 	if (flow->head) {
1980 		skb = dequeue_head(flow);
1981 		len = qdisc_pkt_len(skb);
1982 		WRITE_ONCE(b->backlogs[q->cur_flow], b->backlogs[q->cur_flow] - len);
1983 		WRITE_ONCE(b->tin_backlog, b->tin_backlog - len);
1984 		qstats_backlog_sub(sch, len);
1985 		q->buffer_used		 -= skb->truesize;
1986 		qdisc_qlen_dec(sch);
1987 
1988 		if (q->overflow_timeout)
1989 			cake_heapify(q, b->overflow_idx[q->cur_flow]);
1990 	}
1991 	return skb;
1992 }
1993 
1994 /* Discard leftover packets from a tin no longer in use. */
cake_clear_tin(struct Qdisc * sch,u16 tin)1995 static void cake_clear_tin(struct Qdisc *sch, u16 tin)
1996 {
1997 	struct cake_sched_data *q = qdisc_priv(sch);
1998 	struct sk_buff *skb;
1999 
2000 	q->cur_tin = tin;
2001 	for (q->cur_flow = 0; q->cur_flow < CAKE_QUEUES; q->cur_flow++)
2002 		while (!!(skb = cake_dequeue_one(sch)))
2003 			kfree_skb_reason(skb, SKB_DROP_REASON_QUEUE_PURGE);
2004 }
2005 
cake_dequeue(struct Qdisc * sch)2006 static struct sk_buff *cake_dequeue(struct Qdisc *sch)
2007 {
2008 	struct cake_sched_data *q = qdisc_priv(sch);
2009 	struct cake_tin_data *b = &q->tins[q->cur_tin];
2010 	enum qdisc_drop_reason reason;
2011 	ktime_t now = ktime_get();
2012 	struct cake_flow *flow;
2013 	struct list_head *head;
2014 	bool first_flow = true;
2015 	struct sk_buff *skb;
2016 	u64 delay;
2017 	u32 len;
2018 
2019 	if (q->config->is_shared && q->rate_ns &&
2020 	    now - q->last_checked_active >= q->config->sync_time) {
2021 		struct net_device *dev = qdisc_dev(sch);
2022 		struct cake_sched_data *other_priv;
2023 		u64 new_rate = q->config->rate_bps;
2024 		u64 other_qlen, other_last_active;
2025 		struct Qdisc *other_sch;
2026 		u32 num_active_qs = 1;
2027 		unsigned int ntx;
2028 
2029 		for (ntx = 0; ntx < dev->num_tx_queues; ntx++) {
2030 			other_sch = rcu_dereference(netdev_get_tx_queue(dev, ntx)->qdisc_sleeping);
2031 			other_priv = qdisc_priv(other_sch);
2032 
2033 			if (other_priv == q)
2034 				continue;
2035 
2036 			other_qlen = READ_ONCE(other_sch->q.qlen);
2037 			other_last_active = READ_ONCE(other_priv->last_active);
2038 
2039 			if (other_qlen || other_last_active > q->last_checked_active)
2040 				num_active_qs++;
2041 		}
2042 
2043 		if (num_active_qs > 1)
2044 			new_rate = div64_u64(q->config->rate_bps, num_active_qs);
2045 
2046 		cake_configure_rates(sch, new_rate, true);
2047 		q->last_checked_active = now;
2048 		WRITE_ONCE(q->active_queues, num_active_qs);
2049 	}
2050 
2051 begin:
2052 	if (!sch->q.qlen)
2053 		return NULL;
2054 
2055 	/* global hard shaper */
2056 	if (ktime_after(q->time_next_packet, now) &&
2057 	    ktime_after(q->failsafe_next_packet, now)) {
2058 		u64 next = min(ktime_to_ns(q->time_next_packet),
2059 			       ktime_to_ns(q->failsafe_next_packet));
2060 
2061 		sch->qstats.overlimits++;
2062 		qdisc_watchdog_schedule_ns(&q->watchdog, next);
2063 		return NULL;
2064 	}
2065 
2066 	/* Choose a class to work on. */
2067 	if (!q->rate_ns) {
2068 		/* In unlimited mode, can't rely on shaper timings, just balance
2069 		 * with DRR
2070 		 */
2071 		bool wrapped = false, empty = true;
2072 
2073 		while (b->tin_deficit < 0 ||
2074 		       !(b->sparse_flow_count + b->bulk_flow_count)) {
2075 			if (b->tin_deficit <= 0)
2076 				b->tin_deficit += b->tin_quantum;
2077 			if (b->sparse_flow_count + b->bulk_flow_count)
2078 				empty = false;
2079 
2080 			q->cur_tin++;
2081 			b++;
2082 			if (q->cur_tin >= q->tin_cnt) {
2083 				q->cur_tin = 0;
2084 				b = q->tins;
2085 
2086 				if (wrapped) {
2087 					/* It's possible for q->qlen to be
2088 					 * nonzero when we actually have no
2089 					 * packets anywhere.
2090 					 */
2091 					if (empty)
2092 						return NULL;
2093 				} else {
2094 					wrapped = true;
2095 				}
2096 			}
2097 		}
2098 	} else {
2099 		/* In shaped mode, choose:
2100 		 * - Highest-priority tin with queue and meeting schedule, or
2101 		 * - The earliest-scheduled tin with queue.
2102 		 */
2103 		ktime_t best_time = KTIME_MAX;
2104 		int tin, best_tin = 0;
2105 
2106 		for (tin = 0; tin < q->tin_cnt; tin++) {
2107 			b = q->tins + tin;
2108 			if ((b->sparse_flow_count + b->bulk_flow_count) > 0) {
2109 				ktime_t time_to_pkt = \
2110 					ktime_sub(b->time_next_packet, now);
2111 
2112 				if (ktime_to_ns(time_to_pkt) <= 0 ||
2113 				    ktime_compare(time_to_pkt,
2114 						  best_time) <= 0) {
2115 					best_time = time_to_pkt;
2116 					best_tin = tin;
2117 				}
2118 			}
2119 		}
2120 
2121 		q->cur_tin = best_tin;
2122 		b = q->tins + best_tin;
2123 
2124 		/* No point in going further if no packets to deliver. */
2125 		if (unlikely(!(b->sparse_flow_count + b->bulk_flow_count)))
2126 			return NULL;
2127 	}
2128 
2129 retry:
2130 	/* service this class */
2131 	head = &b->decaying_flows;
2132 	if (!first_flow || list_empty(head)) {
2133 		head = &b->new_flows;
2134 		if (list_empty(head)) {
2135 			head = &b->old_flows;
2136 			if (unlikely(list_empty(head))) {
2137 				head = &b->decaying_flows;
2138 				if (unlikely(list_empty(head)))
2139 					goto begin;
2140 			}
2141 		}
2142 	}
2143 	flow = list_first_entry(head, struct cake_flow, flowchain);
2144 	q->cur_flow = flow - b->flows;
2145 	first_flow = false;
2146 
2147 	/* flow isolation (DRR++) */
2148 	if (flow->deficit <= 0) {
2149 		/* Keep all flows with deficits out of the sparse and decaying
2150 		 * rotations.  No non-empty flow can go into the decaying
2151 		 * rotation, so they can't get deficits
2152 		 */
2153 		if (flow->set == CAKE_SET_SPARSE) {
2154 			if (flow->head) {
2155 				WRITE_ONCE(b->sparse_flow_count, b->sparse_flow_count - 1);
2156 				WRITE_ONCE(b->bulk_flow_count, b->bulk_flow_count + 1);
2157 
2158 				cake_inc_srchost_bulk_flow_count(b, flow, q->config->flow_mode);
2159 				cake_inc_dsthost_bulk_flow_count(b, flow, q->config->flow_mode);
2160 
2161 				flow->set = CAKE_SET_BULK;
2162 			} else {
2163 				/* we've moved it to the bulk rotation for
2164 				 * correct deficit accounting but we still want
2165 				 * to count it as a sparse flow, not a bulk one.
2166 				 */
2167 				flow->set = CAKE_SET_SPARSE_WAIT;
2168 			}
2169 		}
2170 
2171 		WRITE_ONCE(flow->deficit,
2172 			   flow->deficit + cake_get_flow_quantum(b, flow, q->config->flow_mode));
2173 		list_move_tail(&flow->flowchain, &b->old_flows);
2174 
2175 		goto retry;
2176 	}
2177 
2178 	/* Retrieve a packet via the AQM */
2179 	while (1) {
2180 		skb = cake_dequeue_one(sch);
2181 		if (!skb) {
2182 			/* this queue was actually empty */
2183 			if (cobalt_queue_empty(&flow->cvars, &b->cparams, now))
2184 				WRITE_ONCE(b->unresponsive_flow_count,
2185 					   b->unresponsive_flow_count - 1);
2186 
2187 			if (flow->cvars.p_drop || flow->cvars.count ||
2188 			    ktime_before(now, flow->cvars.drop_next)) {
2189 				/* keep in the flowchain until the state has
2190 				 * decayed to rest
2191 				 */
2192 				list_move_tail(&flow->flowchain,
2193 					       &b->decaying_flows);
2194 				if (flow->set == CAKE_SET_BULK) {
2195 					WRITE_ONCE(b->bulk_flow_count, b->bulk_flow_count - 1);
2196 
2197 					cake_dec_srchost_bulk_flow_count(b, flow, q->config->flow_mode);
2198 					cake_dec_dsthost_bulk_flow_count(b, flow, q->config->flow_mode);
2199 
2200 					WRITE_ONCE(b->decaying_flow_count, b->decaying_flow_count + 1);
2201 				} else if (flow->set == CAKE_SET_SPARSE ||
2202 					   flow->set == CAKE_SET_SPARSE_WAIT) {
2203 					WRITE_ONCE(b->sparse_flow_count, b->sparse_flow_count - 1);
2204 					WRITE_ONCE(b->decaying_flow_count, b->decaying_flow_count + 1);
2205 				}
2206 				flow->set = CAKE_SET_DECAYING;
2207 			} else {
2208 				/* remove empty queue from the flowchain */
2209 				list_del_init(&flow->flowchain);
2210 				if (flow->set == CAKE_SET_SPARSE ||
2211 				    flow->set == CAKE_SET_SPARSE_WAIT) {
2212 					WRITE_ONCE(b->sparse_flow_count, b->sparse_flow_count - 1);
2213 				} else if (flow->set == CAKE_SET_BULK) {
2214 					WRITE_ONCE(b->bulk_flow_count, b->bulk_flow_count - 1);
2215 
2216 					cake_dec_srchost_bulk_flow_count(b, flow, q->config->flow_mode);
2217 					cake_dec_dsthost_bulk_flow_count(b, flow, q->config->flow_mode);
2218 				} else {
2219 					WRITE_ONCE(b->decaying_flow_count, b->decaying_flow_count - 1);
2220 				}
2221 				flow->set = CAKE_SET_NONE;
2222 			}
2223 			goto begin;
2224 		}
2225 
2226 		reason = cobalt_should_drop(&flow->cvars, &b->cparams, now, skb,
2227 					    (b->bulk_flow_count *
2228 					     !!(q->config->rate_flags &
2229 						CAKE_FLAG_INGRESS)));
2230 		/* Last packet in queue may be marked, shouldn't be dropped */
2231 		if (reason == QDISC_DROP_UNSPEC || !flow->head)
2232 			break;
2233 
2234 		/* drop this packet, get another one */
2235 		if (q->config->rate_flags & CAKE_FLAG_INGRESS) {
2236 			len = cake_advance_shaper(q, b, skb,
2237 						  now, true);
2238 			WRITE_ONCE(flow->deficit, flow->deficit - len);
2239 			b->tin_deficit -= len;
2240 		}
2241 		WRITE_ONCE(flow->dropped, flow->dropped + 1);
2242 		WRITE_ONCE(b->tin_dropped, b->tin_dropped + 1);
2243 		qdisc_tree_reduce_backlog(sch, 1, qdisc_pkt_len(skb));
2244 		qdisc_qstats_drop(sch);
2245 		qdisc_dequeue_drop(sch, skb, reason);
2246 		if (q->config->rate_flags & CAKE_FLAG_INGRESS)
2247 			goto retry;
2248 	}
2249 
2250 	WRITE_ONCE(b->tin_ecn_mark, b->tin_ecn_mark + !!flow->cvars.ecn_marked);
2251 	qdisc_bstats_update(sch, skb);
2252 	WRITE_ONCE(q->last_active, now);
2253 
2254 	/* collect delay stats */
2255 	delay = ktime_to_ns(ktime_sub(now, cobalt_get_enqueue_time(skb)));
2256 	WRITE_ONCE(b->avge_delay, cake_ewma(b->avge_delay, delay, 8));
2257 	WRITE_ONCE(b->peak_delay,
2258 		   cake_ewma(b->peak_delay, delay,
2259 			     delay > b->peak_delay ? 2 : 8));
2260 	WRITE_ONCE(b->base_delay,
2261 		   cake_ewma(b->base_delay, delay,
2262 			     delay < b->base_delay ? 2 : 8));
2263 
2264 	len = cake_advance_shaper(q, b, skb, now, false);
2265 	WRITE_ONCE(flow->deficit, flow->deficit - len);
2266 	b->tin_deficit -= len;
2267 
2268 	if (ktime_after(q->time_next_packet, now) && sch->q.qlen) {
2269 		u64 next = min(ktime_to_ns(q->time_next_packet),
2270 			       ktime_to_ns(q->failsafe_next_packet));
2271 
2272 		qdisc_watchdog_schedule_ns(&q->watchdog, next);
2273 	} else if (!sch->q.qlen) {
2274 		int i;
2275 
2276 		for (i = 0; i < q->tin_cnt; i++) {
2277 			if (q->tins[i].decaying_flow_count) {
2278 				ktime_t next = \
2279 					ktime_add_ns(now,
2280 						     q->tins[i].cparams.target);
2281 
2282 				qdisc_watchdog_schedule_ns(&q->watchdog,
2283 							   ktime_to_ns(next));
2284 				break;
2285 			}
2286 		}
2287 	}
2288 
2289 	if (q->overflow_timeout)
2290 		q->overflow_timeout--;
2291 
2292 	return skb;
2293 }
2294 
cake_reset(struct Qdisc * sch)2295 static void cake_reset(struct Qdisc *sch)
2296 {
2297 	struct cake_sched_data *q = qdisc_priv(sch);
2298 	u32 c;
2299 
2300 	if (!q->tins)
2301 		return;
2302 
2303 	for (c = 0; c < CAKE_MAX_TINS; c++)
2304 		cake_clear_tin(sch, c);
2305 }
2306 
2307 static const struct nla_policy cake_policy[TCA_CAKE_MAX + 1] = {
2308 	[TCA_CAKE_BASE_RATE64]   = { .type = NLA_U64 },
2309 	[TCA_CAKE_DIFFSERV_MODE] = { .type = NLA_U32 },
2310 	[TCA_CAKE_ATM]		 = { .type = NLA_U32 },
2311 	[TCA_CAKE_FLOW_MODE]     = { .type = NLA_U32 },
2312 	[TCA_CAKE_OVERHEAD]      = { .type = NLA_S32 },
2313 	[TCA_CAKE_RTT]		 = { .type = NLA_U32 },
2314 	[TCA_CAKE_TARGET]	 = { .type = NLA_U32 },
2315 	[TCA_CAKE_AUTORATE]      = { .type = NLA_U32 },
2316 	[TCA_CAKE_MEMORY]	 = { .type = NLA_U32 },
2317 	[TCA_CAKE_NAT]		 = { .type = NLA_U32 },
2318 	[TCA_CAKE_RAW]		 = { .type = NLA_U32 },
2319 	[TCA_CAKE_WASH]		 = { .type = NLA_U32 },
2320 	[TCA_CAKE_MPU]		 = { .type = NLA_U32 },
2321 	[TCA_CAKE_INGRESS]	 = { .type = NLA_U32 },
2322 	[TCA_CAKE_ACK_FILTER]	 = { .type = NLA_U32 },
2323 	[TCA_CAKE_SPLIT_GSO]	 = { .type = NLA_U32 },
2324 	[TCA_CAKE_FWMARK]	 = { .type = NLA_U32 },
2325 };
2326 
cake_set_rate(struct cake_tin_data * b,u64 rate,u32 mtu,u64 target_ns,u64 rtt_est_ns)2327 static void cake_set_rate(struct cake_tin_data *b, u64 rate, u32 mtu,
2328 			  u64 target_ns, u64 rtt_est_ns)
2329 {
2330 	/* convert byte-rate into time-per-byte
2331 	 * so it will always unwedge in reasonable time.
2332 	 */
2333 	static const u64 MIN_RATE = 64;
2334 	u32 byte_target = mtu;
2335 	u64 byte_target_ns;
2336 	u8  rate_shft = 0;
2337 	u64 rate_ns = 0;
2338 
2339 	if (rate) {
2340 		WRITE_ONCE(b->flow_quantum,
2341 			   max(min(rate >> 12, 1514ULL), 300ULL));
2342 		rate_shft = 34;
2343 		rate_ns = ((u64)NSEC_PER_SEC) << rate_shft;
2344 		rate_ns = div64_u64(rate_ns, max(MIN_RATE, rate));
2345 		while (!!(rate_ns >> 34)) {
2346 			rate_ns >>= 1;
2347 			rate_shft--;
2348 		}
2349 	} else {
2350 		/* else unlimited, ie. zero delay */
2351 		WRITE_ONCE(b->flow_quantum, 1514);
2352 	}
2353 	WRITE_ONCE(b->tin_rate_bps, rate);
2354 	b->tin_rate_ns   = rate_ns;
2355 	b->tin_rate_shft = rate_shft;
2356 
2357 	if (mtu == 0)
2358 		return;
2359 
2360 	byte_target_ns = (byte_target * rate_ns) >> rate_shft;
2361 
2362 	WRITE_ONCE(b->cparams.target,
2363 		   max((byte_target_ns * 3) / 2, target_ns));
2364 	WRITE_ONCE(b->cparams.interval,
2365 		   max(rtt_est_ns + b->cparams.target - target_ns,
2366 		       b->cparams.target * 2));
2367 	b->cparams.mtu_time = byte_target_ns;
2368 	b->cparams.p_inc = 1 << 24; /* 1/256 */
2369 	b->cparams.p_dec = 1 << 20; /* 1/4096 */
2370 }
2371 
cake_config_besteffort(struct Qdisc * sch,u64 rate,u32 mtu)2372 static int cake_config_besteffort(struct Qdisc *sch, u64 rate, u32 mtu)
2373 {
2374 	struct cake_sched_data *q = qdisc_priv(sch);
2375 	struct cake_tin_data *b = &q->tins[0];
2376 
2377 	q->tin_cnt = 1;
2378 
2379 	q->tin_index = besteffort;
2380 	q->tin_order = normal_order;
2381 
2382 	cake_set_rate(b, rate, mtu,
2383 		      us_to_ns(q->config->target), us_to_ns(q->config->interval));
2384 	b->tin_quantum = 65535;
2385 
2386 	return 0;
2387 }
2388 
cake_config_precedence(struct Qdisc * sch,u64 rate,u32 mtu)2389 static int cake_config_precedence(struct Qdisc *sch, u64 rate, u32 mtu)
2390 {
2391 	/* convert high-level (user visible) parameters into internal format */
2392 	struct cake_sched_data *q = qdisc_priv(sch);
2393 	u32 quantum = 256;
2394 	u32 i;
2395 
2396 	q->tin_cnt = 8;
2397 	q->tin_index = precedence;
2398 	q->tin_order = normal_order;
2399 
2400 	for (i = 0; i < q->tin_cnt; i++) {
2401 		struct cake_tin_data *b = &q->tins[i];
2402 
2403 		cake_set_rate(b, rate, mtu, us_to_ns(q->config->target),
2404 			      us_to_ns(q->config->interval));
2405 
2406 		b->tin_quantum = max_t(u16, 1U, quantum);
2407 
2408 		/* calculate next class's parameters */
2409 		rate  *= 7;
2410 		rate >>= 3;
2411 
2412 		quantum  *= 7;
2413 		quantum >>= 3;
2414 	}
2415 
2416 	return 0;
2417 }
2418 
2419 /*	List of known Diffserv codepoints:
2420  *
2421  *	Default Forwarding (DF/CS0) - Best Effort
2422  *	Max Throughput (TOS2)
2423  *	Min Delay (TOS4)
2424  *	LLT "La" (TOS5)
2425  *	Assured Forwarding 1 (AF1x) - x3
2426  *	Assured Forwarding 2 (AF2x) - x3
2427  *	Assured Forwarding 3 (AF3x) - x3
2428  *	Assured Forwarding 4 (AF4x) - x3
2429  *	Precedence Class 1 (CS1)
2430  *	Precedence Class 2 (CS2)
2431  *	Precedence Class 3 (CS3)
2432  *	Precedence Class 4 (CS4)
2433  *	Precedence Class 5 (CS5)
2434  *	Precedence Class 6 (CS6)
2435  *	Precedence Class 7 (CS7)
2436  *	Voice Admit (VA)
2437  *	Expedited Forwarding (EF)
2438  *	Lower Effort (LE)
2439  *
2440  *	Total 26 codepoints.
2441  */
2442 
2443 /*	List of traffic classes in RFC 4594, updated by RFC 8622:
2444  *		(roughly descending order of contended priority)
2445  *		(roughly ascending order of uncontended throughput)
2446  *
2447  *	Network Control (CS6,CS7)      - routing traffic
2448  *	Telephony (EF,VA)         - aka. VoIP streams
2449  *	Signalling (CS5)               - VoIP setup
2450  *	Multimedia Conferencing (AF4x) - aka. video calls
2451  *	Realtime Interactive (CS4)     - eg. games
2452  *	Multimedia Streaming (AF3x)    - eg. YouTube, NetFlix, Twitch
2453  *	Broadcast Video (CS3)
2454  *	Low-Latency Data (AF2x,TOS4)      - eg. database
2455  *	Ops, Admin, Management (CS2)      - eg. ssh
2456  *	Standard Service (DF & unrecognised codepoints)
2457  *	High-Throughput Data (AF1x,TOS2)  - eg. web traffic
2458  *	Low-Priority Data (LE,CS1)        - eg. BitTorrent
2459  *
2460  *	Total 12 traffic classes.
2461  */
2462 
cake_config_diffserv8(struct Qdisc * sch,u64 rate,u32 mtu)2463 static int cake_config_diffserv8(struct Qdisc *sch, u64 rate, u32 mtu)
2464 {
2465 /*	Pruned list of traffic classes for typical applications:
2466  *
2467  *		Network Control          (CS6, CS7)
2468  *		Minimum Latency          (EF, VA, CS5, CS4)
2469  *		Interactive Shell        (CS2)
2470  *		Low Latency Transactions (AF2x, TOS4)
2471  *		Video Streaming          (AF4x, AF3x, CS3)
2472  *		Bog Standard             (DF etc.)
2473  *		High Throughput          (AF1x, TOS2, CS1)
2474  *		Background Traffic       (LE)
2475  *
2476  *		Total 8 traffic classes.
2477  */
2478 
2479 	struct cake_sched_data *q = qdisc_priv(sch);
2480 	u32 quantum = 256;
2481 	u32 i;
2482 
2483 	q->tin_cnt = 8;
2484 
2485 	/* codepoint to class mapping */
2486 	q->tin_index = diffserv8;
2487 	q->tin_order = normal_order;
2488 
2489 	/* class characteristics */
2490 	for (i = 0; i < q->tin_cnt; i++) {
2491 		struct cake_tin_data *b = &q->tins[i];
2492 
2493 		cake_set_rate(b, rate, mtu, us_to_ns(q->config->target),
2494 			      us_to_ns(q->config->interval));
2495 
2496 		b->tin_quantum = max_t(u16, 1U, quantum);
2497 
2498 		/* calculate next class's parameters */
2499 		rate  *= 7;
2500 		rate >>= 3;
2501 
2502 		quantum  *= 7;
2503 		quantum >>= 3;
2504 	}
2505 
2506 	return 0;
2507 }
2508 
cake_config_diffserv4(struct Qdisc * sch,u64 rate,u32 mtu)2509 static int cake_config_diffserv4(struct Qdisc *sch, u64 rate, u32 mtu)
2510 {
2511 /*  Further pruned list of traffic classes for four-class system:
2512  *
2513  *	    Latency Sensitive  (CS7, CS6, EF, VA, CS5, CS4)
2514  *	    Streaming Media    (AF4x, AF3x, CS3, AF2x, TOS4, CS2)
2515  *	    Best Effort        (DF, AF1x, TOS2, and those not specified)
2516  *	    Background Traffic (LE, CS1)
2517  *
2518  *		Total 4 traffic classes.
2519  */
2520 
2521 	struct cake_sched_data *q = qdisc_priv(sch);
2522 	u32 quantum = 1024;
2523 
2524 	q->tin_cnt = 4;
2525 
2526 	/* codepoint to class mapping */
2527 	q->tin_index = diffserv4;
2528 	q->tin_order = bulk_order;
2529 
2530 	/* class characteristics */
2531 	cake_set_rate(&q->tins[0], rate, mtu,
2532 		      us_to_ns(q->config->target), us_to_ns(q->config->interval));
2533 	cake_set_rate(&q->tins[1], rate >> 4, mtu,
2534 		      us_to_ns(q->config->target), us_to_ns(q->config->interval));
2535 	cake_set_rate(&q->tins[2], rate >> 1, mtu,
2536 		      us_to_ns(q->config->target), us_to_ns(q->config->interval));
2537 	cake_set_rate(&q->tins[3], rate >> 2, mtu,
2538 		      us_to_ns(q->config->target), us_to_ns(q->config->interval));
2539 
2540 	/* bandwidth-sharing weights */
2541 	q->tins[0].tin_quantum = quantum;
2542 	q->tins[1].tin_quantum = quantum >> 4;
2543 	q->tins[2].tin_quantum = quantum >> 1;
2544 	q->tins[3].tin_quantum = quantum >> 2;
2545 
2546 	return 0;
2547 }
2548 
cake_config_diffserv3(struct Qdisc * sch,u64 rate,u32 mtu)2549 static int cake_config_diffserv3(struct Qdisc *sch, u64 rate, u32 mtu)
2550 {
2551 /*  Simplified Diffserv structure with 3 tins.
2552  *		Latency Sensitive	(CS7, CS6, EF, VA, TOS4)
2553  *		Best Effort
2554  *		Low Priority		(LE, CS1)
2555  */
2556 	struct cake_sched_data *q = qdisc_priv(sch);
2557 	u32 quantum = 1024;
2558 
2559 	q->tin_cnt = 3;
2560 
2561 	/* codepoint to class mapping */
2562 	q->tin_index = diffserv3;
2563 	q->tin_order = bulk_order;
2564 
2565 	/* class characteristics */
2566 	cake_set_rate(&q->tins[0], rate, mtu,
2567 		      us_to_ns(q->config->target), us_to_ns(q->config->interval));
2568 	cake_set_rate(&q->tins[1], rate >> 4, mtu,
2569 		      us_to_ns(q->config->target), us_to_ns(q->config->interval));
2570 	cake_set_rate(&q->tins[2], rate >> 2, mtu,
2571 		      us_to_ns(q->config->target), us_to_ns(q->config->interval));
2572 
2573 	/* bandwidth-sharing weights */
2574 	q->tins[0].tin_quantum = quantum;
2575 	q->tins[1].tin_quantum = quantum >> 4;
2576 	q->tins[2].tin_quantum = quantum >> 2;
2577 
2578 	return 0;
2579 }
2580 
cake_configure_rates(struct Qdisc * sch,u64 rate,bool rate_adjust)2581 static void cake_configure_rates(struct Qdisc *sch, u64 rate, bool rate_adjust)
2582 {
2583 	u32 mtu = likely(rate_adjust) ? 0 : psched_mtu(qdisc_dev(sch));
2584 	struct cake_sched_data *qd = qdisc_priv(sch);
2585 	struct cake_sched_config *q = qd->config;
2586 	int c, ft;
2587 
2588 	switch (q->tin_mode) {
2589 	case CAKE_DIFFSERV_BESTEFFORT:
2590 		ft = cake_config_besteffort(sch, rate, mtu);
2591 		break;
2592 
2593 	case CAKE_DIFFSERV_PRECEDENCE:
2594 		ft = cake_config_precedence(sch, rate, mtu);
2595 		break;
2596 
2597 	case CAKE_DIFFSERV_DIFFSERV8:
2598 		ft = cake_config_diffserv8(sch, rate, mtu);
2599 		break;
2600 
2601 	case CAKE_DIFFSERV_DIFFSERV4:
2602 		ft = cake_config_diffserv4(sch, rate, mtu);
2603 		break;
2604 
2605 	case CAKE_DIFFSERV_DIFFSERV3:
2606 	default:
2607 		ft = cake_config_diffserv3(sch, rate, mtu);
2608 		break;
2609 	}
2610 
2611 	if (!rate_adjust) {
2612 		for (c = qd->tin_cnt; c < CAKE_MAX_TINS; c++) {
2613 			cake_clear_tin(sch, c);
2614 			qd->tins[c].cparams.mtu_time = qd->tins[ft].cparams.mtu_time;
2615 		}
2616 	}
2617 
2618 	qd->rate_ns   = qd->tins[ft].tin_rate_ns;
2619 	qd->rate_shft = qd->tins[ft].tin_rate_shft;
2620 }
2621 
cake_reconfigure(struct Qdisc * sch)2622 static void cake_reconfigure(struct Qdisc *sch)
2623 {
2624 	struct cake_sched_data *qd = qdisc_priv(sch);
2625 	struct cake_sched_config *q = qd->config;
2626 	u32 buffer_limit;
2627 
2628 	cake_configure_rates(sch, qd->config->rate_bps, false);
2629 
2630 	if (q->buffer_config_limit) {
2631 		buffer_limit = q->buffer_config_limit;
2632 	} else if (q->rate_bps) {
2633 		u64 t = q->rate_bps * q->interval;
2634 
2635 		do_div(t, USEC_PER_SEC / 4);
2636 		buffer_limit = max_t(u32, t, 4U << 20);
2637 	} else {
2638 		buffer_limit = ~0;
2639 	}
2640 
2641 	sch->flags &= ~TCQ_F_CAN_BYPASS;
2642 
2643 	WRITE_ONCE(qd->buffer_limit,
2644 		   min(buffer_limit,
2645 		       max(sch->limit * psched_mtu(qdisc_dev(sch)),
2646 			   q->buffer_config_limit)));
2647 }
2648 
cake_config_change(struct cake_sched_config * q,struct nlattr * opt,struct netlink_ext_ack * extack,bool * overhead_changed)2649 static int cake_config_change(struct cake_sched_config *q, struct nlattr *opt,
2650 			      struct netlink_ext_ack *extack, bool *overhead_changed)
2651 {
2652 	struct nlattr *tb[TCA_CAKE_MAX + 1];
2653 	u16 rate_flags = q->rate_flags;
2654 	u8 flow_mode = q->flow_mode;
2655 	int err;
2656 
2657 	err = nla_parse_nested_deprecated(tb, TCA_CAKE_MAX, opt, cake_policy,
2658 					  extack);
2659 	if (err < 0)
2660 		return err;
2661 
2662 	if (tb[TCA_CAKE_NAT]) {
2663 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
2664 		flow_mode &= ~CAKE_FLOW_NAT_FLAG;
2665 		flow_mode |= CAKE_FLOW_NAT_FLAG *
2666 			!!nla_get_u32(tb[TCA_CAKE_NAT]);
2667 #else
2668 		NL_SET_ERR_MSG_ATTR(extack, tb[TCA_CAKE_NAT],
2669 				    "No conntrack support in kernel");
2670 		return -EOPNOTSUPP;
2671 #endif
2672 	}
2673 
2674 	if (tb[TCA_CAKE_AUTORATE]) {
2675 		if (!!nla_get_u32(tb[TCA_CAKE_AUTORATE])) {
2676 			if (q->is_shared) {
2677 				NL_SET_ERR_MSG_ATTR(extack, tb[TCA_CAKE_AUTORATE],
2678 						    "Can't use autorate-ingress with cake_mq");
2679 				return -EOPNOTSUPP;
2680 			}
2681 			rate_flags |= CAKE_FLAG_AUTORATE_INGRESS;
2682 		} else {
2683 			rate_flags &= ~CAKE_FLAG_AUTORATE_INGRESS;
2684 		}
2685 	}
2686 
2687 	if (tb[TCA_CAKE_BASE_RATE64])
2688 		WRITE_ONCE(q->rate_bps,
2689 			   nla_get_u64(tb[TCA_CAKE_BASE_RATE64]));
2690 
2691 	if (tb[TCA_CAKE_DIFFSERV_MODE])
2692 		WRITE_ONCE(q->tin_mode,
2693 			   nla_get_u32(tb[TCA_CAKE_DIFFSERV_MODE]));
2694 
2695 	if (tb[TCA_CAKE_WASH]) {
2696 		if (!!nla_get_u32(tb[TCA_CAKE_WASH]))
2697 			rate_flags |= CAKE_FLAG_WASH;
2698 		else
2699 			rate_flags &= ~CAKE_FLAG_WASH;
2700 	}
2701 
2702 	if (tb[TCA_CAKE_FLOW_MODE])
2703 		flow_mode = ((flow_mode & CAKE_FLOW_NAT_FLAG) |
2704 				(nla_get_u32(tb[TCA_CAKE_FLOW_MODE]) &
2705 					CAKE_FLOW_MASK));
2706 
2707 	if (tb[TCA_CAKE_ATM])
2708 		WRITE_ONCE(q->atm_mode,
2709 			   nla_get_u32(tb[TCA_CAKE_ATM]));
2710 
2711 	if (tb[TCA_CAKE_OVERHEAD]) {
2712 		WRITE_ONCE(q->rate_overhead,
2713 			   nla_get_s32(tb[TCA_CAKE_OVERHEAD]));
2714 		rate_flags |= CAKE_FLAG_OVERHEAD;
2715 		*overhead_changed = true;
2716 	}
2717 
2718 	if (tb[TCA_CAKE_RAW]) {
2719 		rate_flags &= ~CAKE_FLAG_OVERHEAD;
2720 		*overhead_changed = true;
2721 	}
2722 
2723 	if (tb[TCA_CAKE_MPU])
2724 		WRITE_ONCE(q->rate_mpu,
2725 			   nla_get_u32(tb[TCA_CAKE_MPU]));
2726 
2727 	if (tb[TCA_CAKE_RTT]) {
2728 		u32 interval = nla_get_u32(tb[TCA_CAKE_RTT]);
2729 
2730 		WRITE_ONCE(q->interval, max(interval, 1U));
2731 	}
2732 
2733 	if (tb[TCA_CAKE_TARGET]) {
2734 		u32 target = nla_get_u32(tb[TCA_CAKE_TARGET]);
2735 
2736 		WRITE_ONCE(q->target, max(target, 1U));
2737 	}
2738 
2739 	if (tb[TCA_CAKE_INGRESS]) {
2740 		if (!!nla_get_u32(tb[TCA_CAKE_INGRESS]))
2741 			rate_flags |= CAKE_FLAG_INGRESS;
2742 		else
2743 			rate_flags &= ~CAKE_FLAG_INGRESS;
2744 	}
2745 
2746 	if (tb[TCA_CAKE_ACK_FILTER])
2747 		WRITE_ONCE(q->ack_filter,
2748 			   nla_get_u32(tb[TCA_CAKE_ACK_FILTER]));
2749 
2750 	if (tb[TCA_CAKE_MEMORY])
2751 		WRITE_ONCE(q->buffer_config_limit,
2752 			   nla_get_u32(tb[TCA_CAKE_MEMORY]));
2753 
2754 	if (tb[TCA_CAKE_SPLIT_GSO]) {
2755 		if (!!nla_get_u32(tb[TCA_CAKE_SPLIT_GSO]))
2756 			rate_flags |= CAKE_FLAG_SPLIT_GSO;
2757 		else
2758 			rate_flags &= ~CAKE_FLAG_SPLIT_GSO;
2759 	}
2760 
2761 	if (tb[TCA_CAKE_FWMARK]) {
2762 		WRITE_ONCE(q->fwmark_mask, nla_get_u32(tb[TCA_CAKE_FWMARK]));
2763 		WRITE_ONCE(q->fwmark_shft,
2764 			   q->fwmark_mask ? __ffs(q->fwmark_mask) : 0);
2765 	}
2766 
2767 	WRITE_ONCE(q->rate_flags, rate_flags);
2768 	WRITE_ONCE(q->flow_mode, flow_mode);
2769 
2770 	return 0;
2771 }
2772 
cake_change(struct Qdisc * sch,struct nlattr * opt,struct netlink_ext_ack * extack)2773 static int cake_change(struct Qdisc *sch, struct nlattr *opt,
2774 		       struct netlink_ext_ack *extack)
2775 {
2776 	struct cake_sched_data *qd = qdisc_priv(sch);
2777 	struct cake_sched_config *q = qd->config;
2778 	bool overhead_changed = false;
2779 	int ret;
2780 
2781 	if (q->is_shared) {
2782 		NL_SET_ERR_MSG(extack, "can't reconfigure cake_mq sub-qdiscs");
2783 		return -EOPNOTSUPP;
2784 	}
2785 
2786 	ret = cake_config_change(q, opt, extack, &overhead_changed);
2787 	if (ret)
2788 		return ret;
2789 
2790 	if (overhead_changed) {
2791 		WRITE_ONCE(qd->max_netlen, 0);
2792 		WRITE_ONCE(qd->max_adjlen, 0);
2793 		WRITE_ONCE(qd->min_netlen, ~0);
2794 		WRITE_ONCE(qd->min_adjlen, ~0);
2795 	}
2796 
2797 	if (qd->tins) {
2798 		sch_tree_lock(sch);
2799 		cake_reconfigure(sch);
2800 		sch_tree_unlock(sch);
2801 	}
2802 
2803 	return 0;
2804 }
2805 
cake_destroy(struct Qdisc * sch)2806 static void cake_destroy(struct Qdisc *sch)
2807 {
2808 	struct cake_sched_data *q = qdisc_priv(sch);
2809 
2810 	qdisc_watchdog_cancel(&q->watchdog);
2811 	tcf_block_put(q->block);
2812 	kvfree(q->tins);
2813 }
2814 
cake_config_init(struct cake_sched_config * q,bool is_shared)2815 static void cake_config_init(struct cake_sched_config *q, bool is_shared)
2816 {
2817 	q->tin_mode = CAKE_DIFFSERV_DIFFSERV3;
2818 	q->flow_mode  = CAKE_FLOW_TRIPLE;
2819 
2820 	q->rate_bps = 0; /* unlimited by default */
2821 
2822 	q->interval = 100000; /* 100ms default */
2823 	q->target   =   5000; /* 5ms: codel RFC argues
2824 			       * for 5 to 10% of interval
2825 			       */
2826 	q->rate_flags |= CAKE_FLAG_SPLIT_GSO;
2827 	q->is_shared = is_shared;
2828 	q->sync_time = 200 * NSEC_PER_USEC;
2829 }
2830 
cake_init(struct Qdisc * sch,struct nlattr * opt,struct netlink_ext_ack * extack)2831 static int cake_init(struct Qdisc *sch, struct nlattr *opt,
2832 		     struct netlink_ext_ack *extack)
2833 {
2834 	struct cake_sched_data *qd = qdisc_priv(sch);
2835 	struct cake_sched_config *q = &qd->initial_config;
2836 	int i, j, err;
2837 
2838 	cake_config_init(q, false);
2839 
2840 	sch->limit = 10240;
2841 	sch->flags |= TCQ_F_DEQUEUE_DROPS;
2842 
2843 	qd->cur_tin = 0;
2844 	qd->cur_flow  = 0;
2845 	qd->config = q;
2846 
2847 	qdisc_watchdog_init(&qd->watchdog, sch);
2848 
2849 	if (opt) {
2850 		err = cake_change(sch, opt, extack);
2851 		if (err)
2852 			return err;
2853 	}
2854 
2855 	err = tcf_block_get(&qd->block, &qd->filter_list, sch, extack);
2856 	if (err)
2857 		return err;
2858 
2859 	quantum_div[0] = ~0;
2860 	for (i = 1; i <= CAKE_QUEUES; i++)
2861 		quantum_div[i] = 65535 / i;
2862 
2863 	qd->tins = kvzalloc_objs(struct cake_tin_data, CAKE_MAX_TINS);
2864 	if (!qd->tins)
2865 		return -ENOMEM;
2866 
2867 	for (i = 0; i < CAKE_MAX_TINS; i++) {
2868 		struct cake_tin_data *b = qd->tins + i;
2869 
2870 		INIT_LIST_HEAD(&b->new_flows);
2871 		INIT_LIST_HEAD(&b->old_flows);
2872 		INIT_LIST_HEAD(&b->decaying_flows);
2873 		b->sparse_flow_count = 0;
2874 		b->bulk_flow_count = 0;
2875 		b->decaying_flow_count = 0;
2876 
2877 		for (j = 0; j < CAKE_QUEUES; j++) {
2878 			struct cake_flow *flow = b->flows + j;
2879 			u32 k = j * CAKE_MAX_TINS + i;
2880 
2881 			INIT_LIST_HEAD(&flow->flowchain);
2882 			cobalt_vars_init(&flow->cvars);
2883 
2884 			qd->overflow_heap[k].t = i;
2885 			qd->overflow_heap[k].b = j;
2886 			b->overflow_idx[j] = k;
2887 		}
2888 	}
2889 
2890 	cake_reconfigure(sch);
2891 	qd->avg_peak_bandwidth = q->rate_bps;
2892 	qd->min_netlen = ~0;
2893 	qd->min_adjlen = ~0;
2894 	qd->active_queues = 0;
2895 	qd->last_checked_active = 0;
2896 
2897 	return 0;
2898 }
2899 
cake_config_replace(struct Qdisc * sch,struct cake_sched_config * cfg)2900 static void cake_config_replace(struct Qdisc *sch, struct cake_sched_config *cfg)
2901 {
2902 	struct cake_sched_data *qd = qdisc_priv(sch);
2903 
2904 	qd->config = cfg;
2905 	cake_reconfigure(sch);
2906 }
2907 
cake_config_dump(struct cake_sched_config * q,struct sk_buff * skb)2908 static int cake_config_dump(struct cake_sched_config *q, struct sk_buff *skb)
2909 {
2910 	struct nlattr *opts;
2911 	u16 rate_flags;
2912 	u8 flow_mode;
2913 
2914 	opts = nla_nest_start_noflag(skb, TCA_OPTIONS);
2915 	if (!opts)
2916 		goto nla_put_failure;
2917 
2918 	if (nla_put_u64_64bit(skb, TCA_CAKE_BASE_RATE64,
2919 			      READ_ONCE(q->rate_bps), TCA_CAKE_PAD))
2920 		goto nla_put_failure;
2921 
2922 	flow_mode = READ_ONCE(q->flow_mode);
2923 	if (nla_put_u32(skb, TCA_CAKE_FLOW_MODE, flow_mode & CAKE_FLOW_MASK))
2924 		goto nla_put_failure;
2925 
2926 	if (nla_put_u32(skb, TCA_CAKE_RTT, READ_ONCE(q->interval)))
2927 		goto nla_put_failure;
2928 
2929 	if (nla_put_u32(skb, TCA_CAKE_TARGET, READ_ONCE(q->target)))
2930 		goto nla_put_failure;
2931 
2932 	if (nla_put_u32(skb, TCA_CAKE_MEMORY,
2933 			READ_ONCE(q->buffer_config_limit)))
2934 		goto nla_put_failure;
2935 
2936 	rate_flags = READ_ONCE(q->rate_flags);
2937 	if (nla_put_u32(skb, TCA_CAKE_AUTORATE,
2938 			!!(rate_flags & CAKE_FLAG_AUTORATE_INGRESS)))
2939 		goto nla_put_failure;
2940 
2941 	if (nla_put_u32(skb, TCA_CAKE_INGRESS,
2942 			!!(rate_flags & CAKE_FLAG_INGRESS)))
2943 		goto nla_put_failure;
2944 
2945 	if (nla_put_u32(skb, TCA_CAKE_ACK_FILTER, READ_ONCE(q->ack_filter)))
2946 		goto nla_put_failure;
2947 
2948 	if (nla_put_u32(skb, TCA_CAKE_NAT,
2949 			!!(flow_mode & CAKE_FLOW_NAT_FLAG)))
2950 		goto nla_put_failure;
2951 
2952 	if (nla_put_u32(skb, TCA_CAKE_DIFFSERV_MODE, READ_ONCE(q->tin_mode)))
2953 		goto nla_put_failure;
2954 
2955 	if (nla_put_u32(skb, TCA_CAKE_WASH,
2956 			!!(rate_flags & CAKE_FLAG_WASH)))
2957 		goto nla_put_failure;
2958 
2959 	if (nla_put_u32(skb, TCA_CAKE_OVERHEAD, READ_ONCE(q->rate_overhead)))
2960 		goto nla_put_failure;
2961 
2962 	if (!(rate_flags & CAKE_FLAG_OVERHEAD))
2963 		if (nla_put_u32(skb, TCA_CAKE_RAW, 0))
2964 			goto nla_put_failure;
2965 
2966 	if (nla_put_u32(skb, TCA_CAKE_ATM, READ_ONCE(q->atm_mode)))
2967 		goto nla_put_failure;
2968 
2969 	if (nla_put_u32(skb, TCA_CAKE_MPU, READ_ONCE(q->rate_mpu)))
2970 		goto nla_put_failure;
2971 
2972 	if (nla_put_u32(skb, TCA_CAKE_SPLIT_GSO,
2973 			!!(rate_flags & CAKE_FLAG_SPLIT_GSO)))
2974 		goto nla_put_failure;
2975 
2976 	if (nla_put_u32(skb, TCA_CAKE_FWMARK, READ_ONCE(q->fwmark_mask)))
2977 		goto nla_put_failure;
2978 
2979 	return nla_nest_end(skb, opts);
2980 
2981 nla_put_failure:
2982 	return -1;
2983 }
2984 
cake_dump(struct Qdisc * sch,struct sk_buff * skb)2985 static int cake_dump(struct Qdisc *sch, struct sk_buff *skb)
2986 {
2987 	struct cake_sched_data *qd = qdisc_priv(sch);
2988 
2989 	return cake_config_dump(qd->config, skb);
2990 }
2991 
cake_dump_stats(struct Qdisc * sch,struct gnet_dump * d)2992 static int cake_dump_stats(struct Qdisc *sch, struct gnet_dump *d)
2993 {
2994 	struct nlattr *stats = nla_nest_start_noflag(d->skb, TCA_STATS_APP);
2995 	struct cake_sched_data *q = qdisc_priv(sch);
2996 	struct nlattr *tstats, *ts;
2997 	int i;
2998 
2999 	if (!stats)
3000 		return -1;
3001 
3002 #define PUT_STAT_U32(attr, data) do {				       \
3003 		if (nla_put_u32(d->skb, TCA_CAKE_STATS_ ## attr, data)) \
3004 			goto nla_put_failure;			       \
3005 	} while (0)
3006 #define PUT_STAT_U64(attr, data) do {				       \
3007 		if (nla_put_u64_64bit(d->skb, TCA_CAKE_STATS_ ## attr, \
3008 					data, TCA_CAKE_STATS_PAD)) \
3009 			goto nla_put_failure;			       \
3010 	} while (0)
3011 
3012 	PUT_STAT_U64(CAPACITY_ESTIMATE64, READ_ONCE(q->avg_peak_bandwidth));
3013 	PUT_STAT_U32(MEMORY_LIMIT, READ_ONCE(q->buffer_limit));
3014 	PUT_STAT_U32(MEMORY_USED, READ_ONCE(q->buffer_max_used));
3015 	PUT_STAT_U32(AVG_NETOFF, ((READ_ONCE(q->avg_netoff) + 0x8000) >> 16));
3016 	PUT_STAT_U32(MAX_NETLEN, READ_ONCE(q->max_netlen));
3017 	PUT_STAT_U32(MAX_ADJLEN, READ_ONCE(q->max_adjlen));
3018 	PUT_STAT_U32(MIN_NETLEN, READ_ONCE(q->min_netlen));
3019 	PUT_STAT_U32(MIN_ADJLEN, READ_ONCE(q->min_adjlen));
3020 	PUT_STAT_U32(ACTIVE_QUEUES, READ_ONCE(q->active_queues));
3021 
3022 #undef PUT_STAT_U32
3023 #undef PUT_STAT_U64
3024 
3025 	tstats = nla_nest_start_noflag(d->skb, TCA_CAKE_STATS_TIN_STATS);
3026 	if (!tstats)
3027 		goto nla_put_failure;
3028 
3029 #define PUT_TSTAT_U32(attr, data) do {					\
3030 		if (nla_put_u32(d->skb, TCA_CAKE_TIN_STATS_ ## attr, data)) \
3031 			goto nla_put_failure;				\
3032 	} while (0)
3033 #define PUT_TSTAT_U64(attr, data) do {					\
3034 		if (nla_put_u64_64bit(d->skb, TCA_CAKE_TIN_STATS_ ## attr, \
3035 					data, TCA_CAKE_TIN_STATS_PAD))	\
3036 			goto nla_put_failure;				\
3037 	} while (0)
3038 
3039 	for (i = 0; i < q->tin_cnt; i++) {
3040 		struct cake_tin_data *b = &q->tins[q->tin_order[i]];
3041 
3042 		ts = nla_nest_start_noflag(d->skb, i + 1);
3043 		if (!ts)
3044 			goto nla_put_failure;
3045 
3046 		PUT_TSTAT_U64(THRESHOLD_RATE64, READ_ONCE(b->tin_rate_bps));
3047 		PUT_TSTAT_U64(SENT_BYTES64, READ_ONCE(b->bytes));
3048 		PUT_TSTAT_U32(BACKLOG_BYTES, READ_ONCE(b->tin_backlog));
3049 
3050 		PUT_TSTAT_U32(TARGET_US,
3051 			      ktime_to_us(ns_to_ktime(READ_ONCE(b->cparams.target))));
3052 		PUT_TSTAT_U32(INTERVAL_US,
3053 			      ktime_to_us(ns_to_ktime(READ_ONCE(b->cparams.interval))));
3054 
3055 		PUT_TSTAT_U32(SENT_PACKETS, READ_ONCE(b->packets));
3056 		PUT_TSTAT_U32(DROPPED_PACKETS, READ_ONCE(b->tin_dropped));
3057 		PUT_TSTAT_U32(ECN_MARKED_PACKETS, READ_ONCE(b->tin_ecn_mark));
3058 		PUT_TSTAT_U32(ACKS_DROPPED_PACKETS, READ_ONCE(b->ack_drops));
3059 
3060 		PUT_TSTAT_U32(PEAK_DELAY_US,
3061 			      ktime_to_us(ns_to_ktime(READ_ONCE(b->peak_delay))));
3062 		PUT_TSTAT_U32(AVG_DELAY_US,
3063 			      ktime_to_us(ns_to_ktime(READ_ONCE(b->avge_delay))));
3064 		PUT_TSTAT_U32(BASE_DELAY_US,
3065 			      ktime_to_us(ns_to_ktime(READ_ONCE(b->base_delay))));
3066 
3067 		PUT_TSTAT_U32(WAY_INDIRECT_HITS, READ_ONCE(b->way_hits));
3068 		PUT_TSTAT_U32(WAY_MISSES, READ_ONCE(b->way_misses));
3069 		PUT_TSTAT_U32(WAY_COLLISIONS, READ_ONCE(b->way_collisions));
3070 
3071 		PUT_TSTAT_U32(SPARSE_FLOWS, READ_ONCE(b->sparse_flow_count) +
3072 					    READ_ONCE(b->decaying_flow_count));
3073 		PUT_TSTAT_U32(BULK_FLOWS, READ_ONCE(b->bulk_flow_count));
3074 		PUT_TSTAT_U32(UNRESPONSIVE_FLOWS, READ_ONCE(b->unresponsive_flow_count));
3075 		PUT_TSTAT_U32(MAX_SKBLEN, READ_ONCE(b->max_skblen));
3076 
3077 		PUT_TSTAT_U32(FLOW_QUANTUM, READ_ONCE(b->flow_quantum));
3078 		nla_nest_end(d->skb, ts);
3079 	}
3080 
3081 #undef PUT_TSTAT_U32
3082 #undef PUT_TSTAT_U64
3083 
3084 	nla_nest_end(d->skb, tstats);
3085 	return nla_nest_end(d->skb, stats);
3086 
3087 nla_put_failure:
3088 	nla_nest_cancel(d->skb, stats);
3089 	return -1;
3090 }
3091 
cake_leaf(struct Qdisc * sch,unsigned long arg)3092 static struct Qdisc *cake_leaf(struct Qdisc *sch, unsigned long arg)
3093 {
3094 	return NULL;
3095 }
3096 
cake_find(struct Qdisc * sch,u32 classid)3097 static unsigned long cake_find(struct Qdisc *sch, u32 classid)
3098 {
3099 	return 0;
3100 }
3101 
cake_bind(struct Qdisc * sch,unsigned long parent,u32 classid)3102 static unsigned long cake_bind(struct Qdisc *sch, unsigned long parent,
3103 			       u32 classid)
3104 {
3105 	return 0;
3106 }
3107 
cake_unbind(struct Qdisc * q,unsigned long cl)3108 static void cake_unbind(struct Qdisc *q, unsigned long cl)
3109 {
3110 }
3111 
cake_tcf_block(struct Qdisc * sch,unsigned long cl,struct netlink_ext_ack * extack)3112 static struct tcf_block *cake_tcf_block(struct Qdisc *sch, unsigned long cl,
3113 					struct netlink_ext_ack *extack)
3114 {
3115 	struct cake_sched_data *q = qdisc_priv(sch);
3116 
3117 	if (cl)
3118 		return NULL;
3119 	return q->block;
3120 }
3121 
cake_dump_class(struct Qdisc * sch,unsigned long cl,struct sk_buff * skb,struct tcmsg * tcm)3122 static int cake_dump_class(struct Qdisc *sch, unsigned long cl,
3123 			   struct sk_buff *skb, struct tcmsg *tcm)
3124 {
3125 	tcm->tcm_handle |= TC_H_MIN(cl);
3126 	return 0;
3127 }
3128 
cake_dump_class_stats(struct Qdisc * sch,unsigned long cl,struct gnet_dump * d)3129 static int cake_dump_class_stats(struct Qdisc *sch, unsigned long cl,
3130 				 struct gnet_dump *d)
3131 {
3132 	struct cake_sched_data *q = qdisc_priv(sch);
3133 	const struct cake_flow *flow = NULL;
3134 	struct gnet_stats_queue qs = { 0 };
3135 	struct nlattr *stats;
3136 	u32 idx = cl - 1;
3137 
3138 	if (idx < CAKE_QUEUES * q->tin_cnt) {
3139 		const struct cake_tin_data *b = \
3140 			&q->tins[q->tin_order[idx / CAKE_QUEUES]];
3141 		const struct sk_buff *skb;
3142 
3143 		flow = &b->flows[idx % CAKE_QUEUES];
3144 
3145 		if (READ_ONCE(flow->head)) {
3146 			sch_tree_lock(sch);
3147 			skb = flow->head;
3148 			while (skb) {
3149 				qs.qlen++;
3150 				skb = skb->next;
3151 			}
3152 			sch_tree_unlock(sch);
3153 		}
3154 		qs.backlog = READ_ONCE(b->backlogs[idx % CAKE_QUEUES]);
3155 		qs.drops = READ_ONCE(flow->dropped);
3156 	}
3157 	if (gnet_stats_copy_queue(d, NULL, &qs, qs.qlen) < 0)
3158 		return -1;
3159 	if (flow) {
3160 		ktime_t now = ktime_get();
3161 		bool dropping;
3162 		u32 p_drop;
3163 
3164 		stats = nla_nest_start_noflag(d->skb, TCA_STATS_APP);
3165 		if (!stats)
3166 			return -1;
3167 
3168 #define PUT_STAT_U32(attr, data) do {				       \
3169 		if (nla_put_u32(d->skb, TCA_CAKE_STATS_ ## attr, data)) \
3170 			goto nla_put_failure;			       \
3171 	} while (0)
3172 #define PUT_STAT_S32(attr, data) do {				       \
3173 		if (nla_put_s32(d->skb, TCA_CAKE_STATS_ ## attr, data)) \
3174 			goto nla_put_failure;			       \
3175 	} while (0)
3176 
3177 		PUT_STAT_S32(DEFICIT, READ_ONCE(flow->deficit));
3178 		dropping = READ_ONCE(flow->cvars.dropping);
3179 		PUT_STAT_U32(DROPPING, dropping);
3180 		PUT_STAT_U32(COBALT_COUNT, READ_ONCE(flow->cvars.count));
3181 		p_drop = READ_ONCE(flow->cvars.p_drop);
3182 		PUT_STAT_U32(P_DROP, p_drop);
3183 		if (p_drop) {
3184 			PUT_STAT_S32(BLUE_TIMER_US,
3185 				     ktime_to_us(
3186 					     ktime_sub(now,
3187 						       READ_ONCE(flow->cvars.blue_timer))));
3188 		}
3189 		if (dropping) {
3190 			PUT_STAT_S32(DROP_NEXT_US,
3191 				     ktime_to_us(
3192 					     ktime_sub(now,
3193 						       READ_ONCE(flow->cvars.drop_next))));
3194 		}
3195 
3196 		if (nla_nest_end(d->skb, stats) < 0)
3197 			return -1;
3198 	}
3199 
3200 	return 0;
3201 
3202 nla_put_failure:
3203 	nla_nest_cancel(d->skb, stats);
3204 	return -1;
3205 }
3206 
cake_walk(struct Qdisc * sch,struct qdisc_walker * arg)3207 static void cake_walk(struct Qdisc *sch, struct qdisc_walker *arg)
3208 {
3209 	struct cake_sched_data *q = qdisc_priv(sch);
3210 	unsigned int i, j;
3211 
3212 	if (arg->stop)
3213 		return;
3214 
3215 	for (i = 0; i < q->tin_cnt; i++) {
3216 		struct cake_tin_data *b = &q->tins[q->tin_order[i]];
3217 
3218 		for (j = 0; j < CAKE_QUEUES; j++) {
3219 			if (list_empty(&b->flows[j].flowchain)) {
3220 				arg->count++;
3221 				continue;
3222 			}
3223 			if (!tc_qdisc_stats_dump(sch, i * CAKE_QUEUES + j + 1,
3224 						 arg))
3225 				break;
3226 		}
3227 	}
3228 }
3229 
3230 static const struct Qdisc_class_ops cake_class_ops = {
3231 	.leaf		=	cake_leaf,
3232 	.find		=	cake_find,
3233 	.tcf_block	=	cake_tcf_block,
3234 	.bind_tcf	=	cake_bind,
3235 	.unbind_tcf	=	cake_unbind,
3236 	.dump		=	cake_dump_class,
3237 	.dump_stats	=	cake_dump_class_stats,
3238 	.walk		=	cake_walk,
3239 };
3240 
3241 static struct Qdisc_ops cake_qdisc_ops __read_mostly = {
3242 	.cl_ops		=	&cake_class_ops,
3243 	.id		=	"cake",
3244 	.priv_size	=	sizeof(struct cake_sched_data),
3245 	.enqueue	=	cake_enqueue,
3246 	.dequeue	=	cake_dequeue,
3247 	.peek		=	qdisc_peek_dequeued,
3248 	.init		=	cake_init,
3249 	.reset		=	cake_reset,
3250 	.destroy	=	cake_destroy,
3251 	.change		=	cake_change,
3252 	.dump		=	cake_dump,
3253 	.dump_stats	=	cake_dump_stats,
3254 	.owner		=	THIS_MODULE,
3255 };
3256 MODULE_ALIAS_NET_SCH("cake");
3257 
3258 struct cake_mq_sched {
3259 	struct mq_sched mq_priv; /* must be first */
3260 	struct cake_sched_config cake_config;
3261 };
3262 
cake_mq_destroy(struct Qdisc * sch)3263 static void cake_mq_destroy(struct Qdisc *sch)
3264 {
3265 	mq_destroy_common(sch);
3266 }
3267 
cake_mq_init(struct Qdisc * sch,struct nlattr * opt,struct netlink_ext_ack * extack)3268 static int cake_mq_init(struct Qdisc *sch, struct nlattr *opt,
3269 			struct netlink_ext_ack *extack)
3270 {
3271 	struct cake_mq_sched *priv = qdisc_priv(sch);
3272 	struct net_device *dev = qdisc_dev(sch);
3273 	int ret, ntx;
3274 	bool _unused;
3275 
3276 	cake_config_init(&priv->cake_config, true);
3277 	if (opt) {
3278 		ret = cake_config_change(&priv->cake_config, opt, extack, &_unused);
3279 		if (ret)
3280 			return ret;
3281 	}
3282 
3283 	ret = mq_init_common(sch, opt, extack, &cake_qdisc_ops);
3284 	if (ret)
3285 		return ret;
3286 
3287 	for (ntx = 0; ntx < dev->num_tx_queues; ntx++)
3288 		cake_config_replace(priv->mq_priv.qdiscs[ntx], &priv->cake_config);
3289 
3290 	return 0;
3291 }
3292 
cake_mq_dump(struct Qdisc * sch,struct sk_buff * skb)3293 static int cake_mq_dump(struct Qdisc *sch, struct sk_buff *skb)
3294 {
3295 	struct cake_mq_sched *priv = qdisc_priv(sch);
3296 
3297 	mq_dump_common(sch, skb);
3298 	return cake_config_dump(&priv->cake_config, skb);
3299 }
3300 
cake_mq_change(struct Qdisc * sch,struct nlattr * opt,struct netlink_ext_ack * extack)3301 static int cake_mq_change(struct Qdisc *sch, struct nlattr *opt,
3302 			  struct netlink_ext_ack *extack)
3303 {
3304 	struct cake_mq_sched *priv = qdisc_priv(sch);
3305 	struct net_device *dev = qdisc_dev(sch);
3306 	bool overhead_changed = false;
3307 	unsigned int ntx;
3308 	int ret;
3309 
3310 	ret = cake_config_change(&priv->cake_config, opt, extack, &overhead_changed);
3311 	if (ret)
3312 		return ret;
3313 
3314 	for (ntx = 0; ntx < dev->num_tx_queues; ntx++) {
3315 		struct Qdisc *chld = rtnl_dereference(netdev_get_tx_queue(dev, ntx)->qdisc_sleeping);
3316 		struct cake_sched_data *qd = qdisc_priv(chld);
3317 
3318 		if (overhead_changed) {
3319 			WRITE_ONCE(qd->max_netlen, 0);
3320 			WRITE_ONCE(qd->max_adjlen, 0);
3321 			WRITE_ONCE(qd->min_netlen, ~0);
3322 			WRITE_ONCE(qd->min_adjlen, ~0);
3323 		}
3324 
3325 		if (qd->tins) {
3326 			sch_tree_lock(chld);
3327 			cake_reconfigure(chld);
3328 			sch_tree_unlock(chld);
3329 		}
3330 	}
3331 
3332 	return 0;
3333 }
3334 
cake_mq_graft(struct Qdisc * sch,unsigned long cl,struct Qdisc * new,struct Qdisc ** old,struct netlink_ext_ack * extack)3335 static int cake_mq_graft(struct Qdisc *sch, unsigned long cl, struct Qdisc *new,
3336 			 struct Qdisc **old, struct netlink_ext_ack *extack)
3337 {
3338 	NL_SET_ERR_MSG(extack, "can't replace cake_mq sub-qdiscs");
3339 	return -EOPNOTSUPP;
3340 }
3341 
3342 static const struct Qdisc_class_ops cake_mq_class_ops = {
3343 	.select_queue	= mq_select_queue,
3344 	.graft		= cake_mq_graft,
3345 	.leaf		= mq_leaf,
3346 	.find		= mq_find,
3347 	.walk		= mq_walk,
3348 	.dump		= mq_dump_class,
3349 	.dump_stats	= mq_dump_class_stats,
3350 };
3351 
3352 static struct Qdisc_ops cake_mq_qdisc_ops __read_mostly = {
3353 	.cl_ops		=	&cake_mq_class_ops,
3354 	.id		=	"cake_mq",
3355 	.priv_size	=	sizeof(struct cake_mq_sched),
3356 	.init		=	cake_mq_init,
3357 	.destroy	=	cake_mq_destroy,
3358 	.attach		=	mq_attach,
3359 	.change		=	cake_mq_change,
3360 	.change_real_num_tx = mq_change_real_num_tx,
3361 	.dump		=	cake_mq_dump,
3362 	.owner		=	THIS_MODULE,
3363 };
3364 MODULE_ALIAS_NET_SCH("cake_mq");
3365 
cake_module_init(void)3366 static int __init cake_module_init(void)
3367 {
3368 	int ret;
3369 
3370 	ret = register_qdisc(&cake_qdisc_ops);
3371 	if (ret)
3372 		return ret;
3373 
3374 	ret = register_qdisc(&cake_mq_qdisc_ops);
3375 	if (ret)
3376 		unregister_qdisc(&cake_qdisc_ops);
3377 
3378 	return ret;
3379 }
3380 
cake_module_exit(void)3381 static void __exit cake_module_exit(void)
3382 {
3383 	unregister_qdisc(&cake_qdisc_ops);
3384 	unregister_qdisc(&cake_mq_qdisc_ops);
3385 }
3386 
3387 module_init(cake_module_init)
3388 module_exit(cake_module_exit)
3389 MODULE_AUTHOR("Jonathan Morton");
3390 MODULE_LICENSE("Dual BSD/GPL");
3391 MODULE_DESCRIPTION("The CAKE shaper.");
3392 MODULE_IMPORT_NS("NET_SCHED_INTERNAL");
3393