xref: /linux/net/sched/sch_fq.c (revision 78c1930198fc63f2d4761848cbe148c5b2958b01)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * net/sched/sch_fq.c Fair Queue Packet Scheduler (per flow pacing)
4  *
5  *  Copyright (C) 2013-2023 Eric Dumazet <edumazet@google.com>
6  *
7  *  Meant to be mostly used for locally generated traffic :
8  *  Fast classification depends on skb->sk being set before reaching us.
9  *  If not, (router workload), we use rxhash as fallback, with 32 bits wide hash.
10  *  All packets belonging to a socket are considered as a 'flow'.
11  *
12  *  Flows are dynamically allocated and stored in a hash table of RB trees
13  *  They are also part of one Round Robin 'queues' (new or old flows)
14  *
15  *  Burst avoidance (aka pacing) capability :
16  *
17  *  Transport (eg TCP) can set in sk->sk_pacing_rate a rate, enqueue a
18  *  bunch of packets, and this packet scheduler adds delay between
19  *  packets to respect rate limitation.
20  *
21  *  enqueue() :
22  *   - lookup one RB tree (out of 1024 or more) to find the flow.
23  *     If non existent flow, create it, add it to the tree.
24  *     Add skb to the per flow list of skb (fifo).
25  *   - Use a special fifo for high prio packets
26  *
27  *  dequeue() : serves flows in Round Robin
28  *  Note : When a flow becomes empty, we do not immediately remove it from
29  *  rb trees, for performance reasons (its expected to send additional packets,
30  *  or SLAB cache will reuse socket for another flow)
31  */
32 
33 #include <linux/module.h>
34 #include <linux/types.h>
35 #include <linux/kernel.h>
36 #include <linux/jiffies.h>
37 #include <linux/string.h>
38 #include <linux/in.h>
39 #include <linux/errno.h>
40 #include <linux/init.h>
41 #include <linux/skbuff.h>
42 #include <linux/slab.h>
43 #include <linux/rbtree.h>
44 #include <linux/hash.h>
45 #include <linux/prefetch.h>
46 #include <linux/vmalloc.h>
47 #include <net/netlink.h>
48 #include <net/pkt_sched.h>
49 #include <net/sock.h>
50 #include <net/tcp_states.h>
51 #include <net/tcp.h>
52 
53 struct fq_skb_cb {
54 	u64	time_to_send;
55 	u8	band;
56 };
57 
58 static inline struct fq_skb_cb *fq_skb_cb(struct sk_buff *skb)
59 {
60 	qdisc_cb_private_validate(skb, sizeof(struct fq_skb_cb));
61 	return (struct fq_skb_cb *)qdisc_skb_cb(skb)->data;
62 }
63 
64 /*
65  * Per flow structure, dynamically allocated.
66  * If packets have monotically increasing time_to_send, they are placed in O(1)
67  * in linear list (head,tail), otherwise are placed in a rbtree (t_root).
68  */
69 struct fq_flow {
70 /* First cache line : used in fq_gc(), fq_enqueue(), fq_dequeue() */
71 	struct rb_root	t_root;
72 	struct sk_buff	*head;		/* list of skbs for this flow : first skb */
73 	union {
74 		struct sk_buff *tail;	/* last skb in the list */
75 		unsigned long  age;	/* (jiffies | 1UL) when flow was emptied, for gc */
76 	};
77 	union {
78 		struct rb_node	fq_node;	/* anchor in fq_root[] trees */
79 		/* Following field is only used for q->internal,
80 		 * because q->internal is not hashed in fq_root[]
81 		 */
82 		u64		stat_fastpath_packets;
83 	};
84 	struct sock	*sk;
85 	u32		socket_hash;	/* sk_hash */
86 	int		qlen;		/* number of packets in flow queue */
87 
88 /* Second cache line */
89 	int		credit;
90 	int		band;
91 	struct fq_flow *next;		/* next pointer in RR lists */
92 
93 	struct rb_node  rate_node;	/* anchor in q->delayed tree */
94 	u64		time_next_packet;
95 };
96 
97 struct fq_flow_head {
98 	struct fq_flow *first;
99 	struct fq_flow *last;
100 };
101 
102 struct fq_perband_flows {
103 	struct fq_flow_head new_flows;
104 	struct fq_flow_head old_flows;
105 	int		    credit;
106 	int		    quantum; /* based on band nr : 576KB, 192KB, 64KB */
107 };
108 
109 #define FQ_PRIO2BAND_CRUMB_SIZE ((TC_PRIO_MAX + 1) >> 2)
110 
111 struct fq_sched_data {
112 /* Read mostly cache line */
113 
114 	u64		offload_horizon;
115 	u32		quantum;
116 	u32		initial_quantum;
117 	u32		flow_refill_delay;
118 	u32		flow_plimit;	/* max packets per flow */
119 	unsigned long	flow_max_rate;	/* optional max rate per flow */
120 	u64		ce_threshold;
121 	u64		horizon;	/* horizon in ns */
122 	u32		orphan_mask;	/* mask for orphaned skb */
123 	u32		low_rate_threshold;
124 	struct rb_root	*fq_root;
125 	u8		rate_enable;
126 	u8		fq_trees_log;
127 	u8		horizon_drop;
128 	u8		prio2band[FQ_PRIO2BAND_CRUMB_SIZE];
129 	u32		timer_slack; /* hrtimer slack in ns */
130 
131 /* Read/Write fields. */
132 
133 	unsigned int band_nr; /* band being serviced in fq_dequeue() */
134 
135 	struct fq_perband_flows band_flows[FQ_BANDS];
136 
137 	struct fq_flow	internal;	/* fastpath queue. */
138 	struct rb_root	delayed;	/* for rate limited flows */
139 	u64		time_next_delayed_flow;
140 	unsigned long	unthrottle_latency_ns;
141 
142 	u32		band_pkt_count[FQ_BANDS];
143 	u32		flows;
144 	u32		inactive_flows; /* Flows with no packet to send. */
145 	u32		throttled_flows;
146 
147 	u64		stat_throttled;
148 	struct qdisc_watchdog watchdog;
149 	u64		stat_gc_flows;
150 
151 /* Seldom used fields. */
152 
153 	u64		stat_band_drops[FQ_BANDS];
154 	u64		stat_ce_mark;
155 	u64		stat_horizon_drops;
156 	u64		stat_horizon_caps;
157 	u64		stat_flows_plimit;
158 	u64		stat_pkts_too_long;
159 	u64		stat_allocation_errors;
160 };
161 
162 /* return the i-th 2-bit value ("crumb") */
163 static u8 fq_prio2band(const u8 *prio2band, unsigned int prio)
164 {
165 	return (READ_ONCE(prio2band[prio / 4]) >> (2 * (prio & 0x3))) & 0x3;
166 }
167 
168 /*
169  * f->tail and f->age share the same location.
170  * We can use the low order bit to differentiate if this location points
171  * to a sk_buff or contains a jiffies value, if we force this value to be odd.
172  * This assumes f->tail low order bit must be 0 since alignof(struct sk_buff) >= 2
173  */
174 static void fq_flow_set_detached(struct fq_flow *f)
175 {
176 	f->age = jiffies | 1UL;
177 }
178 
179 static bool fq_flow_is_detached(const struct fq_flow *f)
180 {
181 	return !!(f->age & 1UL);
182 }
183 
184 /* special value to mark a throttled flow (not on old/new list) */
185 static struct fq_flow throttled;
186 
187 static bool fq_flow_is_throttled(const struct fq_flow *f)
188 {
189 	return f->next == &throttled;
190 }
191 
192 enum new_flow {
193 	NEW_FLOW,
194 	OLD_FLOW
195 };
196 
197 static void fq_flow_add_tail(struct fq_sched_data *q, struct fq_flow *flow,
198 			     enum new_flow list_sel)
199 {
200 	struct fq_perband_flows *pband = &q->band_flows[flow->band];
201 	struct fq_flow_head *head = (list_sel == NEW_FLOW) ?
202 					&pband->new_flows :
203 					&pband->old_flows;
204 
205 	if (head->first)
206 		head->last->next = flow;
207 	else
208 		head->first = flow;
209 	head->last = flow;
210 	flow->next = NULL;
211 }
212 
213 static void fq_flow_unset_throttled(struct fq_sched_data *q, struct fq_flow *f)
214 {
215 	rb_erase(&f->rate_node, &q->delayed);
216 	q->throttled_flows--;
217 	fq_flow_add_tail(q, f, OLD_FLOW);
218 }
219 
220 static void fq_flow_rb_insert(struct fq_sched_data *q, struct fq_flow *f)
221 {
222 	struct rb_node **p = &q->delayed.rb_node, *parent = NULL;
223 
224 	while (*p) {
225 		struct fq_flow *aux;
226 
227 		parent = *p;
228 		aux = rb_entry(parent, struct fq_flow, rate_node);
229 		if (f->time_next_packet >= aux->time_next_packet)
230 			p = &parent->rb_right;
231 		else
232 			p = &parent->rb_left;
233 	}
234 	rb_link_node(&f->rate_node, parent, p);
235 	rb_insert_color(&f->rate_node, &q->delayed);
236 
237 	if (q->time_next_delayed_flow > f->time_next_packet)
238 		q->time_next_delayed_flow = f->time_next_packet;
239 }
240 
241 static void fq_flow_set_throttled(struct fq_sched_data *q, struct fq_flow *f)
242 {
243 	fq_flow_rb_insert(q, f);
244 	q->throttled_flows++;
245 	q->stat_throttled++;
246 	f->next = &throttled;
247 }
248 
249 static struct kmem_cache *fq_flow_cachep __read_mostly;
250 
251 
252 #define FQ_GC_AGE (3*HZ)
253 
254 static bool fq_gc_candidate(const struct fq_flow *f)
255 {
256 	return fq_flow_is_detached(f) &&
257 	       time_after(jiffies, f->age + FQ_GC_AGE);
258 }
259 
260 static void fq_gc(struct fq_sched_data *q,
261 		  struct rb_root *root,
262 		  struct sock *sk)
263 {
264 	struct fq_flow *f, *tofree = NULL;
265 	struct rb_node **p, *parent;
266 	int fcnt;
267 
268 	p = &root->rb_node;
269 	parent = NULL;
270 	while (*p) {
271 		parent = *p;
272 
273 		f = rb_entry(parent, struct fq_flow, fq_node);
274 		if (f->sk == sk)
275 			break;
276 
277 		if (fq_gc_candidate(f)) {
278 			f->next = tofree;
279 			tofree = f;
280 		}
281 
282 		if (f->sk > sk)
283 			p = &parent->rb_right;
284 		else
285 			p = &parent->rb_left;
286 	}
287 
288 	if (!tofree)
289 		return;
290 
291 	fcnt = 0;
292 	while (tofree) {
293 		f = tofree;
294 		tofree = f->next;
295 		rb_erase(&f->fq_node, root);
296 		kmem_cache_free(fq_flow_cachep, f);
297 		fcnt++;
298 	}
299 	q->flows -= fcnt;
300 	q->inactive_flows -= fcnt;
301 	q->stat_gc_flows += fcnt;
302 }
303 
304 /* Fast path can be used if :
305  * 1) Packet tstamp is in the past, or within the pacing offload horizon.
306  * 2) FQ qlen == 0   OR
307  *   (no flow is currently eligible for transmit,
308  *    AND fast path queue has less than 8 packets)
309  * 3) No SO_MAX_PACING_RATE on the socket (if any).
310  * 4) No @maxrate attribute on this qdisc,
311  *
312  * FQ can not use generic TCQ_F_CAN_BYPASS infrastructure.
313  */
314 static bool fq_fastpath_check(const struct Qdisc *sch, struct sk_buff *skb,
315 			      u64 now)
316 {
317 	const struct fq_sched_data *q = qdisc_priv(sch);
318 	const struct sock *sk;
319 
320 	if (fq_skb_cb(skb)->time_to_send > now + q->offload_horizon)
321 		return false;
322 
323 	if (sch->q.qlen != 0) {
324 		/* Even if some packets are stored in this qdisc,
325 		 * we can still enable fast path if all of them are
326 		 * scheduled in the future (ie no flows are eligible)
327 		 * or in the fast path queue.
328 		 */
329 		if (q->flows != q->inactive_flows + q->throttled_flows)
330 			return false;
331 
332 		/* Do not allow fast path queue to explode, we want Fair Queue mode
333 		 * under pressure.
334 		 */
335 		if (q->internal.qlen >= 8)
336 			return false;
337 
338 		/* Ordering invariants fall apart if some delayed flows
339 		 * are ready but we haven't serviced them, yet.
340 		 */
341 		if (q->time_next_delayed_flow <= now + q->offload_horizon)
342 			return false;
343 	}
344 
345 	sk = skb->sk;
346 	if (sk && sk_fullsock(sk) && !sk_is_tcp(sk) &&
347 	    sk->sk_max_pacing_rate != ~0UL)
348 		return false;
349 
350 	if (q->flow_max_rate != ~0UL)
351 		return false;
352 
353 	return true;
354 }
355 
356 static struct fq_flow *fq_classify(struct Qdisc *sch, struct sk_buff *skb,
357 				   u64 now)
358 {
359 	struct fq_sched_data *q = qdisc_priv(sch);
360 	struct rb_node **p, *parent;
361 	struct sock *sk = skb->sk;
362 	struct rb_root *root;
363 	struct fq_flow *f;
364 
365 	/* SYNACK messages are attached to a TCP_NEW_SYN_RECV request socket
366 	 * or a listener (SYNCOOKIE mode)
367 	 * 1) request sockets are not full blown,
368 	 *    they do not contain sk_pacing_rate
369 	 * 2) They are not part of a 'flow' yet
370 	 * 3) We do not want to rate limit them (eg SYNFLOOD attack),
371 	 *    especially if the listener set SO_MAX_PACING_RATE
372 	 * 4) We pretend they are orphaned
373 	 * TCP can also associate TIME_WAIT sockets with RST or ACK packets.
374 	 */
375 	if (!sk || sk_listener_or_tw(sk)) {
376 		unsigned long hash = skb_get_hash(skb) & q->orphan_mask;
377 
378 		/* By forcing low order bit to 1, we make sure to not
379 		 * collide with a local flow (socket pointers are word aligned)
380 		 */
381 		sk = (struct sock *)((hash << 1) | 1UL);
382 		skb_orphan(skb);
383 	} else if (sk->sk_state == TCP_CLOSE) {
384 		unsigned long hash = skb_get_hash(skb) & q->orphan_mask;
385 		/*
386 		 * Sockets in TCP_CLOSE are non connected.
387 		 * Typical use case is UDP sockets, they can send packets
388 		 * with sendto() to many different destinations.
389 		 * We probably could use a generic bit advertising
390 		 * non connected sockets, instead of sk_state == TCP_CLOSE,
391 		 * if we care enough.
392 		 */
393 		sk = (struct sock *)((hash << 1) | 1UL);
394 	}
395 
396 	if (fq_fastpath_check(sch, skb, now)) {
397 		q->internal.stat_fastpath_packets++;
398 		if (skb->sk == sk && q->rate_enable &&
399 		    READ_ONCE(sk->sk_pacing_status) != SK_PACING_FQ)
400 			smp_store_release(&sk->sk_pacing_status,
401 					  SK_PACING_FQ);
402 		return &q->internal;
403 	}
404 
405 	root = &q->fq_root[hash_ptr(sk, q->fq_trees_log)];
406 
407 	fq_gc(q, root, sk);
408 
409 	p = &root->rb_node;
410 	parent = NULL;
411 	while (*p) {
412 		parent = *p;
413 
414 		f = rb_entry(parent, struct fq_flow, fq_node);
415 		if (f->sk == sk) {
416 			/* socket might have been reallocated, so check
417 			 * if its sk_hash is the same.
418 			 * It not, we need to refill credit with
419 			 * initial quantum
420 			 */
421 			if (unlikely(skb->sk == sk &&
422 				     f->socket_hash != sk->sk_hash)) {
423 				f->credit = q->initial_quantum;
424 				f->socket_hash = sk->sk_hash;
425 				if (q->rate_enable)
426 					smp_store_release(&sk->sk_pacing_status,
427 							  SK_PACING_FQ);
428 				if (fq_flow_is_throttled(f))
429 					fq_flow_unset_throttled(q, f);
430 				f->time_next_packet = 0ULL;
431 			}
432 			return f;
433 		}
434 		if (f->sk > sk)
435 			p = &parent->rb_right;
436 		else
437 			p = &parent->rb_left;
438 	}
439 
440 	f = kmem_cache_zalloc(fq_flow_cachep, GFP_ATOMIC | __GFP_NOWARN);
441 	if (unlikely(!f)) {
442 		q->stat_allocation_errors++;
443 		return &q->internal;
444 	}
445 	/* f->t_root is already zeroed after kmem_cache_zalloc() */
446 
447 	fq_flow_set_detached(f);
448 	f->sk = sk;
449 	if (skb->sk == sk) {
450 		f->socket_hash = sk->sk_hash;
451 		if (q->rate_enable)
452 			smp_store_release(&sk->sk_pacing_status,
453 					  SK_PACING_FQ);
454 	}
455 	f->credit = q->initial_quantum;
456 
457 	rb_link_node(&f->fq_node, parent, p);
458 	rb_insert_color(&f->fq_node, root);
459 
460 	q->flows++;
461 	q->inactive_flows++;
462 	return f;
463 }
464 
465 static struct sk_buff *fq_peek(struct fq_flow *flow)
466 {
467 	struct sk_buff *skb = skb_rb_first(&flow->t_root);
468 	struct sk_buff *head = flow->head;
469 
470 	if (!skb)
471 		return head;
472 
473 	if (!head)
474 		return skb;
475 
476 	if (fq_skb_cb(skb)->time_to_send < fq_skb_cb(head)->time_to_send)
477 		return skb;
478 	return head;
479 }
480 
481 static void fq_erase_head(struct Qdisc *sch, struct fq_flow *flow,
482 			  struct sk_buff *skb)
483 {
484 	if (skb == flow->head) {
485 		struct sk_buff *next = skb->next;
486 
487 		prefetch(next);
488 		flow->head = next;
489 	} else {
490 		rb_erase(&skb->rbnode, &flow->t_root);
491 		skb->dev = qdisc_dev(sch);
492 	}
493 }
494 
495 /* Remove one skb from flow queue.
496  * This skb must be the return value of prior fq_peek().
497  */
498 static void fq_dequeue_skb(struct Qdisc *sch, struct fq_flow *flow,
499 			   struct sk_buff *skb)
500 {
501 	fq_erase_head(sch, flow, skb);
502 	skb_mark_not_on_list(skb);
503 	qdisc_qstats_backlog_dec(sch, skb);
504 	qdisc_qlen_dec(sch);
505 	qdisc_bstats_update(sch, skb);
506 }
507 
508 static void flow_queue_add(struct fq_flow *flow, struct sk_buff *skb)
509 {
510 	struct rb_node **p, *parent;
511 	struct sk_buff *head, *aux;
512 
513 	head = flow->head;
514 	if (!head ||
515 	    fq_skb_cb(skb)->time_to_send >= fq_skb_cb(flow->tail)->time_to_send) {
516 		if (!head)
517 			flow->head = skb;
518 		else
519 			flow->tail->next = skb;
520 		flow->tail = skb;
521 		skb->next = NULL;
522 		return;
523 	}
524 
525 	p = &flow->t_root.rb_node;
526 	parent = NULL;
527 
528 	while (*p) {
529 		parent = *p;
530 		aux = rb_to_skb(parent);
531 		if (fq_skb_cb(skb)->time_to_send >= fq_skb_cb(aux)->time_to_send)
532 			p = &parent->rb_right;
533 		else
534 			p = &parent->rb_left;
535 	}
536 	rb_link_node(&skb->rbnode, parent, p);
537 	rb_insert_color(&skb->rbnode, &flow->t_root);
538 }
539 
540 static bool fq_packet_beyond_horizon(const struct sk_buff *skb,
541 				     const struct fq_sched_data *q, u64 now)
542 {
543 	return unlikely((s64)skb->tstamp > (s64)(now + q->horizon));
544 }
545 
546 static void fq_flow_adjust_timer(struct fq_sched_data *q, struct fq_flow *flow,
547 				 u64 time_to_send, u64 now)
548 {
549 	if (time_to_send <= now) {
550 		fq_flow_unset_throttled(q, flow);
551 		if (q->time_next_delayed_flow == flow->time_next_packet) {
552 			struct rb_node *p = rb_first(&q->delayed);
553 
554 			q->time_next_delayed_flow = p ? rb_entry(p, struct fq_flow, rate_node)->time_next_packet : ~0ULL;
555 		}
556 		flow->time_next_packet = time_to_send;
557 	} else {
558 		rb_erase(&flow->rate_node, &q->delayed);
559 		flow->time_next_packet = time_to_send;
560 		fq_flow_rb_insert(q, flow);
561 	}
562 }
563 
564 static int fq_enqueue(struct sk_buff *skb, struct Qdisc *sch,
565 		      struct sk_buff **to_free)
566 {
567 	struct fq_sched_data *q = qdisc_priv(sch);
568 	struct fq_flow *f;
569 	u64 now;
570 	u8 band;
571 
572 	band = fq_prio2band(q->prio2band, skb->priority & TC_PRIO_MAX);
573 	if (unlikely(q->band_pkt_count[band] >= sch->limit)) {
574 		q->stat_band_drops[band]++;
575 		return qdisc_drop_reason(skb, sch, to_free, QDISC_DROP_BAND_LIMIT);
576 	}
577 
578 	now = ktime_get_ns();
579 	if (!skb->tstamp) {
580 		fq_skb_cb(skb)->time_to_send = now;
581 	} else {
582 		/* Check if packet timestamp is too far in the future. */
583 		if (fq_packet_beyond_horizon(skb, q, now)) {
584 			if (q->horizon_drop) {
585 				q->stat_horizon_drops++;
586 				return qdisc_drop_reason(skb, sch, to_free,
587 							 QDISC_DROP_HORIZON_LIMIT);
588 			}
589 			q->stat_horizon_caps++;
590 			skb->tstamp = now + q->horizon;
591 		}
592 		fq_skb_cb(skb)->time_to_send = skb->tstamp;
593 	}
594 
595 	f = fq_classify(sch, skb, now);
596 
597 	if (f != &q->internal) {
598 		if (unlikely(f->qlen >= q->flow_plimit)) {
599 			q->stat_flows_plimit++;
600 			return qdisc_drop_reason(skb, sch, to_free,
601 						 QDISC_DROP_FLOW_LIMIT);
602 		}
603 
604 		if (fq_flow_is_detached(f)) {
605 			fq_flow_add_tail(q, f, NEW_FLOW);
606 			if (time_after(jiffies, f->age + q->flow_refill_delay))
607 				f->credit = max_t(u32, f->credit, q->quantum);
608 		}
609 
610 		f->band = band;
611 		q->band_pkt_count[band]++;
612 		fq_skb_cb(skb)->band = band;
613 		if (f->qlen == 0)
614 			q->inactive_flows--;
615 	}
616 
617 	f->qlen++;
618 	/* Note: this overwrites f->age */
619 	flow_queue_add(f, skb);
620 
621 	if (fq_skb_cb(skb)->time_to_send < f->time_next_packet && skb->tstamp &&
622 	    fq_flow_is_throttled(f) && q->flow_max_rate == ~0UL)
623 		fq_flow_adjust_timer(q, f, fq_skb_cb(skb)->time_to_send, now);
624 
625 	qdisc_qstats_backlog_inc(sch, skb);
626 	qdisc_qlen_inc(sch);
627 
628 	return NET_XMIT_SUCCESS;
629 }
630 
631 static void fq_check_throttled(struct fq_sched_data *q, u64 now)
632 {
633 	unsigned long sample;
634 	struct rb_node *p;
635 
636 	if (q->time_next_delayed_flow > now + q->offload_horizon)
637 		return;
638 
639 	/* Update unthrottle latency EWMA.
640 	 * This is cheap and can help diagnosing timer/latency problems.
641 	 */
642 	sample = (unsigned long)(now - q->time_next_delayed_flow);
643 	if ((long)sample > 0) {
644 		q->unthrottle_latency_ns -= q->unthrottle_latency_ns >> 3;
645 		q->unthrottle_latency_ns += sample >> 3;
646 	}
647 	now += q->offload_horizon;
648 
649 	q->time_next_delayed_flow = ~0ULL;
650 	while ((p = rb_first(&q->delayed)) != NULL) {
651 		struct fq_flow *f = rb_entry(p, struct fq_flow, rate_node);
652 
653 		if (f->time_next_packet > now) {
654 			q->time_next_delayed_flow = f->time_next_packet;
655 			break;
656 		}
657 		fq_flow_unset_throttled(q, f);
658 	}
659 }
660 
661 static struct fq_flow_head *fq_pband_head_select(struct fq_perband_flows *pband)
662 {
663 	if (pband->credit <= 0)
664 		return NULL;
665 
666 	if (pband->new_flows.first)
667 		return &pband->new_flows;
668 
669 	return pband->old_flows.first ? &pband->old_flows : NULL;
670 }
671 
672 static struct sk_buff *fq_dequeue(struct Qdisc *sch)
673 {
674 	struct fq_sched_data *q = qdisc_priv(sch);
675 	struct fq_perband_flows *pband;
676 	struct fq_flow_head *head;
677 	struct sk_buff *skb;
678 	struct fq_flow *f;
679 	unsigned long rate;
680 	int retry;
681 	u32 plen;
682 	u64 now;
683 
684 	if (!sch->q.qlen)
685 		return NULL;
686 
687 	skb = fq_peek(&q->internal);
688 	if (skb) {
689 		q->internal.qlen--;
690 		fq_dequeue_skb(sch, &q->internal, skb);
691 		goto out;
692 	}
693 
694 	now = ktime_get_ns();
695 	fq_check_throttled(q, now);
696 	retry = 0;
697 	pband = &q->band_flows[q->band_nr];
698 begin:
699 	head = fq_pband_head_select(pband);
700 	if (!head) {
701 		while (++retry <= FQ_BANDS) {
702 			if (++q->band_nr == FQ_BANDS)
703 				q->band_nr = 0;
704 			pband = &q->band_flows[q->band_nr];
705 			pband->credit = min(pband->credit + pband->quantum,
706 					    pband->quantum);
707 			if (pband->credit > 0)
708 				goto begin;
709 			retry = 0;
710 		}
711 		if (q->time_next_delayed_flow != ~0ULL)
712 			qdisc_watchdog_schedule_range_ns(&q->watchdog,
713 							q->time_next_delayed_flow,
714 							q->timer_slack);
715 		return NULL;
716 	}
717 	f = head->first;
718 	retry = 0;
719 	if (f->credit <= 0) {
720 		f->credit += q->quantum;
721 		head->first = f->next;
722 		fq_flow_add_tail(q, f, OLD_FLOW);
723 		goto begin;
724 	}
725 
726 	skb = fq_peek(f);
727 	if (skb) {
728 		u64 time_next_packet = max_t(u64, fq_skb_cb(skb)->time_to_send,
729 					     f->time_next_packet);
730 
731 		if (now + q->offload_horizon < time_next_packet) {
732 			head->first = f->next;
733 			f->time_next_packet = time_next_packet;
734 			fq_flow_set_throttled(q, f);
735 			goto begin;
736 		}
737 		prefetch(&skb->end);
738 		fq_dequeue_skb(sch, f, skb);
739 		if (unlikely((s64)(now - time_next_packet - q->ce_threshold) > 0)) {
740 			INET_ECN_set_ce(skb);
741 			q->stat_ce_mark++;
742 		}
743 		if (--f->qlen == 0)
744 			q->inactive_flows++;
745 		q->band_pkt_count[fq_skb_cb(skb)->band]--;
746 	} else {
747 		head->first = f->next;
748 		/* force a pass through old_flows to prevent starvation */
749 		if (head == &pband->new_flows) {
750 			fq_flow_add_tail(q, f, OLD_FLOW);
751 		} else {
752 			fq_flow_set_detached(f);
753 		}
754 		goto begin;
755 	}
756 	plen = qdisc_pkt_len(skb);
757 	f->credit -= plen;
758 	pband->credit -= plen;
759 
760 	if (!q->rate_enable)
761 		goto out;
762 
763 	rate = q->flow_max_rate;
764 
765 	/* If EDT time was provided for this skb, we need to
766 	 * update f->time_next_packet only if this qdisc enforces
767 	 * a flow max rate.
768 	 */
769 	if (!skb->tstamp) {
770 		if (skb->sk)
771 			rate = min(READ_ONCE(skb->sk->sk_pacing_rate), rate);
772 
773 		if (rate <= q->low_rate_threshold) {
774 			f->credit = 0;
775 		} else {
776 			plen = max(plen, q->quantum);
777 			if (f->credit > 0)
778 				goto out;
779 		}
780 	}
781 	if (rate != ~0UL) {
782 		u64 len = (u64)plen * NSEC_PER_SEC;
783 
784 		if (likely(rate))
785 			len = div64_ul(len, rate);
786 		/* Since socket rate can change later,
787 		 * clamp the delay to 1 second.
788 		 * Really, providers of too big packets should be fixed !
789 		 */
790 		if (unlikely(len > NSEC_PER_SEC)) {
791 			len = NSEC_PER_SEC;
792 			q->stat_pkts_too_long++;
793 		}
794 		/* Account for schedule/timers drifts.
795 		 * f->time_next_packet was set when prior packet was sent,
796 		 * and current time (@now) can be too late by tens of us.
797 		 */
798 		if (f->time_next_packet)
799 			len -= min(len/2, now - f->time_next_packet);
800 		f->time_next_packet = now + len;
801 	}
802 out:
803 	return skb;
804 }
805 
806 static void fq_flow_purge(struct fq_flow *flow)
807 {
808 	struct rb_node *p = rb_first(&flow->t_root);
809 
810 	while (p) {
811 		struct sk_buff *skb = rb_to_skb(p);
812 
813 		p = rb_next(p);
814 		rb_erase(&skb->rbnode, &flow->t_root);
815 		rtnl_kfree_skbs(skb, skb);
816 	}
817 	rtnl_kfree_skbs(flow->head, flow->tail);
818 	flow->head = NULL;
819 	flow->qlen = 0;
820 }
821 
822 static void fq_reset(struct Qdisc *sch)
823 {
824 	struct fq_sched_data *q = qdisc_priv(sch);
825 	struct rb_root *root;
826 	struct rb_node *p;
827 	struct fq_flow *f;
828 	unsigned int idx;
829 
830 	WRITE_ONCE(sch->q.qlen, 0);
831 	WRITE_ONCE(sch->qstats.backlog, 0);
832 
833 	fq_flow_purge(&q->internal);
834 
835 	if (!q->fq_root)
836 		return;
837 
838 	for (idx = 0; idx < (1U << q->fq_trees_log); idx++) {
839 		root = &q->fq_root[idx];
840 		while ((p = rb_first(root)) != NULL) {
841 			f = rb_entry(p, struct fq_flow, fq_node);
842 			rb_erase(p, root);
843 
844 			fq_flow_purge(f);
845 
846 			kmem_cache_free(fq_flow_cachep, f);
847 		}
848 	}
849 	for (idx = 0; idx < FQ_BANDS; idx++) {
850 		q->band_flows[idx].new_flows.first = NULL;
851 		q->band_flows[idx].old_flows.first = NULL;
852 		q->band_pkt_count[idx] = 0;
853 	}
854 	q->delayed		= RB_ROOT;
855 	q->flows		= 0;
856 	q->inactive_flows	= 0;
857 	q->throttled_flows	= 0;
858 }
859 
860 static void fq_rehash(struct fq_sched_data *q,
861 		      struct rb_root *old_array, u32 old_log,
862 		      struct rb_root *new_array, u32 new_log)
863 {
864 	struct rb_node *op, **np, *parent;
865 	struct rb_root *oroot, *nroot;
866 	struct fq_flow *of, *nf;
867 	int fcnt = 0;
868 	u32 idx;
869 
870 	for (idx = 0; idx < (1U << old_log); idx++) {
871 		oroot = &old_array[idx];
872 		while ((op = rb_first(oroot)) != NULL) {
873 			rb_erase(op, oroot);
874 			of = rb_entry(op, struct fq_flow, fq_node);
875 			if (fq_gc_candidate(of)) {
876 				fcnt++;
877 				kmem_cache_free(fq_flow_cachep, of);
878 				continue;
879 			}
880 			nroot = &new_array[hash_ptr(of->sk, new_log)];
881 
882 			np = &nroot->rb_node;
883 			parent = NULL;
884 			while (*np) {
885 				parent = *np;
886 
887 				nf = rb_entry(parent, struct fq_flow, fq_node);
888 				BUG_ON(nf->sk == of->sk);
889 
890 				if (nf->sk > of->sk)
891 					np = &parent->rb_right;
892 				else
893 					np = &parent->rb_left;
894 			}
895 
896 			rb_link_node(&of->fq_node, parent, np);
897 			rb_insert_color(&of->fq_node, nroot);
898 		}
899 	}
900 	q->flows -= fcnt;
901 	q->inactive_flows -= fcnt;
902 	q->stat_gc_flows += fcnt;
903 }
904 
905 static void fq_free(void *addr)
906 {
907 	kvfree(addr);
908 }
909 
910 static int fq_resize(struct Qdisc *sch, u32 log)
911 {
912 	struct fq_sched_data *q = qdisc_priv(sch);
913 	struct rb_root *array;
914 	void *old_fq_root;
915 	u32 idx;
916 
917 	if (q->fq_root && log == q->fq_trees_log)
918 		return 0;
919 
920 	/* If XPS was setup, we can allocate memory on right NUMA node */
921 	array = kvmalloc_node(sizeof(struct rb_root) << log, GFP_KERNEL | __GFP_RETRY_MAYFAIL,
922 			      netdev_queue_numa_node_read(sch->dev_queue));
923 	if (!array)
924 		return -ENOMEM;
925 
926 	for (idx = 0; idx < (1U << log); idx++)
927 		array[idx] = RB_ROOT;
928 
929 	sch_tree_lock(sch);
930 
931 	old_fq_root = q->fq_root;
932 	if (old_fq_root)
933 		fq_rehash(q, old_fq_root, q->fq_trees_log, array, log);
934 
935 	q->fq_root = array;
936 	WRITE_ONCE(q->fq_trees_log, log);
937 
938 	sch_tree_unlock(sch);
939 
940 	fq_free(old_fq_root);
941 
942 	return 0;
943 }
944 
945 static const struct netlink_range_validation iq_range = {
946 	.max = INT_MAX,
947 };
948 
949 static const struct nla_policy fq_policy[TCA_FQ_MAX + 1] = {
950 	[TCA_FQ_UNSPEC]			= { .strict_start_type = TCA_FQ_TIMER_SLACK },
951 
952 	[TCA_FQ_PLIMIT]			= { .type = NLA_U32 },
953 	[TCA_FQ_FLOW_PLIMIT]		= { .type = NLA_U32 },
954 	[TCA_FQ_QUANTUM]		= { .type = NLA_U32 },
955 	[TCA_FQ_INITIAL_QUANTUM]	= NLA_POLICY_FULL_RANGE(NLA_U32, &iq_range),
956 	[TCA_FQ_RATE_ENABLE]		= { .type = NLA_U32 },
957 	[TCA_FQ_FLOW_DEFAULT_RATE]	= { .type = NLA_U32 },
958 	[TCA_FQ_FLOW_MAX_RATE]		= { .type = NLA_U32 },
959 	[TCA_FQ_BUCKETS_LOG]		= { .type = NLA_U32 },
960 	[TCA_FQ_FLOW_REFILL_DELAY]	= { .type = NLA_U32 },
961 	[TCA_FQ_ORPHAN_MASK]		= { .type = NLA_U32 },
962 	[TCA_FQ_LOW_RATE_THRESHOLD]	= { .type = NLA_U32 },
963 	[TCA_FQ_CE_THRESHOLD]		= { .type = NLA_U32 },
964 	[TCA_FQ_TIMER_SLACK]		= { .type = NLA_U32 },
965 	[TCA_FQ_HORIZON]		= { .type = NLA_U32 },
966 	[TCA_FQ_HORIZON_DROP]		= { .type = NLA_U8 },
967 	[TCA_FQ_PRIOMAP]		= NLA_POLICY_EXACT_LEN(sizeof(struct tc_prio_qopt)),
968 	[TCA_FQ_WEIGHTS]		= NLA_POLICY_EXACT_LEN(FQ_BANDS * sizeof(s32)),
969 	[TCA_FQ_OFFLOAD_HORIZON]	= { .type = NLA_U32 },
970 };
971 
972 /* compress a u8 array with all elems <= 3 to an array of 2-bit fields */
973 static void fq_prio2band_compress_crumb(const u8 *in, u8 *out)
974 {
975 	const int num_elems = TC_PRIO_MAX + 1;
976 	u8 tmp[FQ_PRIO2BAND_CRUMB_SIZE];
977 	int i;
978 
979 	memset(tmp, 0, sizeof(tmp));
980 	for (i = 0; i < num_elems; i++)
981 		tmp[i / 4] |= in[i] << (2 * (i & 0x3));
982 
983 	for (i = 0; i < FQ_PRIO2BAND_CRUMB_SIZE; i++)
984 		WRITE_ONCE(out[i], tmp[i]);
985 }
986 
987 static void fq_prio2band_decompress_crumb(const u8 *in, u8 *out)
988 {
989 	const int num_elems = TC_PRIO_MAX + 1;
990 	int i;
991 
992 	for (i = 0; i < num_elems; i++)
993 		out[i] = fq_prio2band(in, i);
994 }
995 
996 static int fq_load_weights(struct fq_sched_data *q,
997 			   const struct nlattr *attr,
998 			   struct netlink_ext_ack *extack)
999 {
1000 	s32 *weights = nla_data(attr);
1001 	int i;
1002 
1003 	for (i = 0; i < FQ_BANDS; i++) {
1004 		if (weights[i] < FQ_MIN_WEIGHT) {
1005 			NL_SET_ERR_MSG_FMT_MOD(extack, "Weight %d less that minimum allowed %d",
1006 					       weights[i], FQ_MIN_WEIGHT);
1007 			return -EINVAL;
1008 		}
1009 	}
1010 	for (i = 0; i < FQ_BANDS; i++)
1011 		WRITE_ONCE(q->band_flows[i].quantum, weights[i]);
1012 	return 0;
1013 }
1014 
1015 static int fq_load_priomap(struct fq_sched_data *q,
1016 			   const struct nlattr *attr,
1017 			   struct netlink_ext_ack *extack)
1018 {
1019 	const struct tc_prio_qopt *map = nla_data(attr);
1020 	int i;
1021 
1022 	if (map->bands != FQ_BANDS) {
1023 		NL_SET_ERR_MSG_MOD(extack, "FQ only supports 3 bands");
1024 		return -EINVAL;
1025 	}
1026 	for (i = 0; i < TC_PRIO_MAX + 1; i++) {
1027 		if (map->priomap[i] >= FQ_BANDS) {
1028 			NL_SET_ERR_MSG_FMT_MOD(extack, "FQ priomap field %d maps to a too high band %d",
1029 					       i, map->priomap[i]);
1030 			return -EINVAL;
1031 		}
1032 	}
1033 	fq_prio2band_compress_crumb(map->priomap, q->prio2band);
1034 	return 0;
1035 }
1036 
1037 static int fq_change(struct Qdisc *sch, struct nlattr *opt,
1038 		     struct netlink_ext_ack *extack)
1039 {
1040 	unsigned int dropped_pkts = 0, dropped_bytes = 0;
1041 	struct fq_sched_data *q = qdisc_priv(sch);
1042 	struct nlattr *tb[TCA_FQ_MAX + 1];
1043 	u32 fq_log;
1044 	int err;
1045 
1046 	err = nla_parse_nested_deprecated(tb, TCA_FQ_MAX, opt, fq_policy,
1047 					  NULL);
1048 	if (err < 0)
1049 		return err;
1050 
1051 	sch_tree_lock(sch);
1052 
1053 	fq_log = q->fq_trees_log;
1054 
1055 	if (tb[TCA_FQ_BUCKETS_LOG]) {
1056 		u32 nval = nla_get_u32(tb[TCA_FQ_BUCKETS_LOG]);
1057 
1058 		if (nval >= 1 && nval <= ilog2(256*1024))
1059 			fq_log = nval;
1060 		else
1061 			err = -EINVAL;
1062 	}
1063 	if (tb[TCA_FQ_PLIMIT])
1064 		WRITE_ONCE(sch->limit,
1065 			   nla_get_u32(tb[TCA_FQ_PLIMIT]));
1066 
1067 	if (tb[TCA_FQ_FLOW_PLIMIT])
1068 		WRITE_ONCE(q->flow_plimit,
1069 			   nla_get_u32(tb[TCA_FQ_FLOW_PLIMIT]));
1070 
1071 	if (tb[TCA_FQ_QUANTUM]) {
1072 		u32 quantum = nla_get_u32(tb[TCA_FQ_QUANTUM]);
1073 
1074 		if (quantum > 0 && quantum <= (1 << 20)) {
1075 			WRITE_ONCE(q->quantum, quantum);
1076 		} else {
1077 			NL_SET_ERR_MSG_MOD(extack, "invalid quantum");
1078 			err = -EINVAL;
1079 		}
1080 	}
1081 
1082 	if (tb[TCA_FQ_INITIAL_QUANTUM])
1083 		WRITE_ONCE(q->initial_quantum,
1084 			   nla_get_u32(tb[TCA_FQ_INITIAL_QUANTUM]));
1085 
1086 	if (tb[TCA_FQ_FLOW_DEFAULT_RATE])
1087 		pr_warn_ratelimited("sch_fq: defrate %u ignored.\n",
1088 				    nla_get_u32(tb[TCA_FQ_FLOW_DEFAULT_RATE]));
1089 
1090 	if (tb[TCA_FQ_FLOW_MAX_RATE]) {
1091 		u32 rate = nla_get_u32(tb[TCA_FQ_FLOW_MAX_RATE]);
1092 
1093 		WRITE_ONCE(q->flow_max_rate,
1094 			   (rate == ~0U) ? ~0UL : rate);
1095 	}
1096 	if (tb[TCA_FQ_LOW_RATE_THRESHOLD])
1097 		WRITE_ONCE(q->low_rate_threshold,
1098 			   nla_get_u32(tb[TCA_FQ_LOW_RATE_THRESHOLD]));
1099 
1100 	if (tb[TCA_FQ_RATE_ENABLE]) {
1101 		u32 enable = nla_get_u32(tb[TCA_FQ_RATE_ENABLE]);
1102 
1103 		if (enable <= 1)
1104 			WRITE_ONCE(q->rate_enable,
1105 				   enable);
1106 		else
1107 			err = -EINVAL;
1108 	}
1109 
1110 	if (tb[TCA_FQ_FLOW_REFILL_DELAY]) {
1111 		u32 usecs_delay = nla_get_u32(tb[TCA_FQ_FLOW_REFILL_DELAY]) ;
1112 
1113 		WRITE_ONCE(q->flow_refill_delay,
1114 			   usecs_to_jiffies(usecs_delay));
1115 	}
1116 
1117 	if (!err && tb[TCA_FQ_PRIOMAP])
1118 		err = fq_load_priomap(q, tb[TCA_FQ_PRIOMAP], extack);
1119 
1120 	if (!err && tb[TCA_FQ_WEIGHTS])
1121 		err = fq_load_weights(q, tb[TCA_FQ_WEIGHTS], extack);
1122 
1123 	if (tb[TCA_FQ_ORPHAN_MASK])
1124 		WRITE_ONCE(q->orphan_mask,
1125 			   nla_get_u32(tb[TCA_FQ_ORPHAN_MASK]));
1126 
1127 	if (tb[TCA_FQ_CE_THRESHOLD])
1128 		WRITE_ONCE(q->ce_threshold,
1129 			   (u64)NSEC_PER_USEC *
1130 			   nla_get_u32(tb[TCA_FQ_CE_THRESHOLD]));
1131 
1132 	if (tb[TCA_FQ_TIMER_SLACK])
1133 		WRITE_ONCE(q->timer_slack,
1134 			   nla_get_u32(tb[TCA_FQ_TIMER_SLACK]));
1135 
1136 	if (tb[TCA_FQ_HORIZON])
1137 		WRITE_ONCE(q->horizon,
1138 			   (u64)NSEC_PER_USEC *
1139 			   nla_get_u32(tb[TCA_FQ_HORIZON]));
1140 
1141 	if (tb[TCA_FQ_HORIZON_DROP])
1142 		WRITE_ONCE(q->horizon_drop,
1143 			   nla_get_u8(tb[TCA_FQ_HORIZON_DROP]));
1144 
1145 	if (tb[TCA_FQ_OFFLOAD_HORIZON]) {
1146 		u64 offload_horizon = (u64)NSEC_PER_USEC *
1147 				      nla_get_u32(tb[TCA_FQ_OFFLOAD_HORIZON]);
1148 
1149 		if (offload_horizon <= qdisc_dev(sch)->max_pacing_offload_horizon) {
1150 			WRITE_ONCE(q->offload_horizon, offload_horizon);
1151 		} else {
1152 			NL_SET_ERR_MSG_MOD(extack, "invalid offload_horizon");
1153 			err = -EINVAL;
1154 		}
1155 	}
1156 	if (!err) {
1157 
1158 		sch_tree_unlock(sch);
1159 		err = fq_resize(sch, fq_log);
1160 		sch_tree_lock(sch);
1161 	}
1162 
1163 	while (sch->q.qlen > sch->limit) {
1164 		struct sk_buff *skb = qdisc_dequeue_internal(sch, false);
1165 
1166 		if (!skb)
1167 			break;
1168 
1169 		dropped_pkts++;
1170 		dropped_bytes += qdisc_pkt_len(skb);
1171 		rtnl_kfree_skbs(skb, skb);
1172 	}
1173 	qdisc_tree_reduce_backlog(sch, dropped_pkts, dropped_bytes);
1174 
1175 	sch_tree_unlock(sch);
1176 	return err;
1177 }
1178 
1179 static void fq_destroy(struct Qdisc *sch)
1180 {
1181 	struct fq_sched_data *q = qdisc_priv(sch);
1182 
1183 	fq_reset(sch);
1184 	fq_free(q->fq_root);
1185 	qdisc_watchdog_cancel(&q->watchdog);
1186 }
1187 
1188 static int fq_init(struct Qdisc *sch, struct nlattr *opt,
1189 		   struct netlink_ext_ack *extack)
1190 {
1191 	struct fq_sched_data *q = qdisc_priv(sch);
1192 	int i, err;
1193 
1194 	sch->limit		= 10000;
1195 	q->flow_plimit		= 100;
1196 	q->quantum		= 2 * psched_mtu(qdisc_dev(sch));
1197 	q->initial_quantum	= 10 * psched_mtu(qdisc_dev(sch));
1198 	q->flow_refill_delay	= msecs_to_jiffies(40);
1199 	q->flow_max_rate	= ~0UL;
1200 	q->time_next_delayed_flow = ~0ULL;
1201 	q->rate_enable		= 1;
1202 	for (i = 0; i < FQ_BANDS; i++) {
1203 		q->band_flows[i].new_flows.first = NULL;
1204 		q->band_flows[i].old_flows.first = NULL;
1205 	}
1206 	q->band_flows[0].quantum = 9 << 16;
1207 	q->band_flows[1].quantum = 3 << 16;
1208 	q->band_flows[2].quantum = 1 << 16;
1209 	q->delayed		= RB_ROOT;
1210 	q->fq_root		= NULL;
1211 	q->fq_trees_log		= ilog2(1024);
1212 	q->orphan_mask		= 1024 - 1;
1213 	q->low_rate_threshold	= 550000 / 8;
1214 
1215 	q->timer_slack = 10 * NSEC_PER_USEC; /* 10 usec of hrtimer slack */
1216 
1217 	q->horizon = 10ULL * NSEC_PER_SEC; /* 10 seconds */
1218 	q->horizon_drop = 1; /* by default, drop packets beyond horizon */
1219 
1220 	/* Default ce_threshold of 4294 seconds */
1221 	q->ce_threshold		= (u64)NSEC_PER_USEC * ~0U;
1222 
1223 	fq_prio2band_compress_crumb(sch_default_prio2band, q->prio2band);
1224 	qdisc_watchdog_init_clockid(&q->watchdog, sch, CLOCK_MONOTONIC);
1225 
1226 	if (opt)
1227 		err = fq_change(sch, opt, extack);
1228 	else
1229 		err = fq_resize(sch, q->fq_trees_log);
1230 
1231 	return err;
1232 }
1233 
1234 static int fq_dump(struct Qdisc *sch, struct sk_buff *skb)
1235 {
1236 	struct fq_sched_data *q = qdisc_priv(sch);
1237 	struct tc_prio_qopt prio = {
1238 		.bands = FQ_BANDS,
1239 	};
1240 	struct nlattr *opts;
1241 	u64 offload_horizon;
1242 	u64 ce_threshold;
1243 	s32 weights[3];
1244 	u64 horizon;
1245 
1246 	opts = nla_nest_start_noflag(skb, TCA_OPTIONS);
1247 	if (opts == NULL)
1248 		goto nla_put_failure;
1249 
1250 	/* TCA_FQ_FLOW_DEFAULT_RATE is not used anymore */
1251 
1252 	ce_threshold = READ_ONCE(q->ce_threshold);
1253 	do_div(ce_threshold, NSEC_PER_USEC);
1254 
1255 	horizon = READ_ONCE(q->horizon);
1256 	do_div(horizon, NSEC_PER_USEC);
1257 
1258 	offload_horizon = READ_ONCE(q->offload_horizon);
1259 	do_div(offload_horizon, NSEC_PER_USEC);
1260 
1261 	if (nla_put_u32(skb, TCA_FQ_PLIMIT,
1262 			READ_ONCE(sch->limit)) ||
1263 	    nla_put_u32(skb, TCA_FQ_FLOW_PLIMIT,
1264 			READ_ONCE(q->flow_plimit)) ||
1265 	    nla_put_u32(skb, TCA_FQ_QUANTUM,
1266 			READ_ONCE(q->quantum)) ||
1267 	    nla_put_u32(skb, TCA_FQ_INITIAL_QUANTUM,
1268 			READ_ONCE(q->initial_quantum)) ||
1269 	    nla_put_u32(skb, TCA_FQ_RATE_ENABLE,
1270 			READ_ONCE(q->rate_enable)) ||
1271 	    nla_put_u32(skb, TCA_FQ_FLOW_MAX_RATE,
1272 			min_t(unsigned long,
1273 			      READ_ONCE(q->flow_max_rate), ~0U)) ||
1274 	    nla_put_u32(skb, TCA_FQ_FLOW_REFILL_DELAY,
1275 			jiffies_to_usecs(READ_ONCE(q->flow_refill_delay))) ||
1276 	    nla_put_u32(skb, TCA_FQ_ORPHAN_MASK,
1277 			READ_ONCE(q->orphan_mask)) ||
1278 	    nla_put_u32(skb, TCA_FQ_LOW_RATE_THRESHOLD,
1279 			READ_ONCE(q->low_rate_threshold)) ||
1280 	    nla_put_u32(skb, TCA_FQ_CE_THRESHOLD, (u32)ce_threshold) ||
1281 	    nla_put_u32(skb, TCA_FQ_BUCKETS_LOG,
1282 			READ_ONCE(q->fq_trees_log)) ||
1283 	    nla_put_u32(skb, TCA_FQ_TIMER_SLACK,
1284 			READ_ONCE(q->timer_slack)) ||
1285 	    nla_put_u32(skb, TCA_FQ_HORIZON, (u32)horizon) ||
1286 	    nla_put_u32(skb, TCA_FQ_OFFLOAD_HORIZON, (u32)offload_horizon) ||
1287 	    nla_put_u8(skb, TCA_FQ_HORIZON_DROP,
1288 		       READ_ONCE(q->horizon_drop)))
1289 		goto nla_put_failure;
1290 
1291 	fq_prio2band_decompress_crumb(q->prio2band, prio.priomap);
1292 	if (nla_put(skb, TCA_FQ_PRIOMAP, sizeof(prio), &prio))
1293 		goto nla_put_failure;
1294 
1295 	weights[0] = READ_ONCE(q->band_flows[0].quantum);
1296 	weights[1] = READ_ONCE(q->band_flows[1].quantum);
1297 	weights[2] = READ_ONCE(q->band_flows[2].quantum);
1298 	if (nla_put(skb, TCA_FQ_WEIGHTS, sizeof(weights), &weights))
1299 		goto nla_put_failure;
1300 
1301 	return nla_nest_end(skb, opts);
1302 
1303 nla_put_failure:
1304 	return -1;
1305 }
1306 
1307 static int fq_dump_stats(struct Qdisc *sch, struct gnet_dump *d)
1308 {
1309 	struct fq_sched_data *q = qdisc_priv(sch);
1310 	struct tc_fq_qd_stats st;
1311 	int i;
1312 
1313 	st.pad = 0;
1314 
1315 	sch_tree_lock(sch);
1316 
1317 	st.gc_flows		  = q->stat_gc_flows;
1318 	st.highprio_packets	  = 0;
1319 	st.fastpath_packets	  = q->internal.stat_fastpath_packets;
1320 	st.tcp_retrans		  = 0;
1321 	st.throttled		  = q->stat_throttled;
1322 	st.flows_plimit		  = q->stat_flows_plimit;
1323 	st.pkts_too_long	  = q->stat_pkts_too_long;
1324 	st.allocation_errors	  = q->stat_allocation_errors;
1325 	st.time_next_delayed_flow = q->time_next_delayed_flow + q->timer_slack -
1326 				    ktime_get_ns();
1327 	st.flows		  = q->flows;
1328 	st.inactive_flows	  = q->inactive_flows;
1329 	st.throttled_flows	  = q->throttled_flows;
1330 	st.unthrottle_latency_ns  = min_t(unsigned long,
1331 					  q->unthrottle_latency_ns, ~0U);
1332 	st.ce_mark		  = q->stat_ce_mark;
1333 	st.horizon_drops	  = q->stat_horizon_drops;
1334 	st.horizon_caps		  = q->stat_horizon_caps;
1335 	for (i = 0; i < FQ_BANDS; i++) {
1336 		st.band_drops[i]  = q->stat_band_drops[i];
1337 		st.band_pkt_count[i] = q->band_pkt_count[i];
1338 	}
1339 	sch_tree_unlock(sch);
1340 
1341 	return gnet_stats_copy_app(d, &st, sizeof(st));
1342 }
1343 
1344 static struct Qdisc_ops fq_qdisc_ops __read_mostly = {
1345 	.id		=	"fq",
1346 	.priv_size	=	sizeof(struct fq_sched_data),
1347 
1348 	.enqueue	=	fq_enqueue,
1349 	.dequeue	=	fq_dequeue,
1350 	.peek		=	qdisc_peek_dequeued,
1351 	.init		=	fq_init,
1352 	.reset		=	fq_reset,
1353 	.destroy	=	fq_destroy,
1354 	.change		=	fq_change,
1355 	.dump		=	fq_dump,
1356 	.dump_stats	=	fq_dump_stats,
1357 	.owner		=	THIS_MODULE,
1358 };
1359 MODULE_ALIAS_NET_SCH("fq");
1360 
1361 static int __init fq_module_init(void)
1362 {
1363 	int ret;
1364 
1365 	fq_flow_cachep = kmem_cache_create("fq_flow_cache",
1366 					   sizeof(struct fq_flow),
1367 					   0, SLAB_HWCACHE_ALIGN, NULL);
1368 	if (!fq_flow_cachep)
1369 		return -ENOMEM;
1370 
1371 	ret = register_qdisc(&fq_qdisc_ops);
1372 	if (ret)
1373 		kmem_cache_destroy(fq_flow_cachep);
1374 	return ret;
1375 }
1376 
1377 static void __exit fq_module_exit(void)
1378 {
1379 	unregister_qdisc(&fq_qdisc_ops);
1380 	kmem_cache_destroy(fq_flow_cachep);
1381 }
1382 
1383 module_init(fq_module_init)
1384 module_exit(fq_module_exit)
1385 MODULE_AUTHOR("Eric Dumazet");
1386 MODULE_LICENSE("GPL");
1387 MODULE_DESCRIPTION("Fair Queue Packet Scheduler");
1388