xref: /linux/net/sched/sch_fq.c (revision fefe5dc4afeafe896c90d5b20b605f2759343c3b)
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 };
56 
57 static inline struct fq_skb_cb *fq_skb_cb(struct sk_buff *skb)
58 {
59 	qdisc_cb_private_validate(skb, sizeof(struct fq_skb_cb));
60 	return (struct fq_skb_cb *)qdisc_skb_cb(skb)->data;
61 }
62 
63 /*
64  * Per flow structure, dynamically allocated.
65  * If packets have monotically increasing time_to_send, they are placed in O(1)
66  * in linear list (head,tail), otherwise are placed in a rbtree (t_root).
67  */
68 struct fq_flow {
69 /* First cache line : used in fq_gc(), fq_enqueue(), fq_dequeue() */
70 	struct rb_root	t_root;
71 	struct sk_buff	*head;		/* list of skbs for this flow : first skb */
72 	union {
73 		struct sk_buff *tail;	/* last skb in the list */
74 		unsigned long  age;	/* (jiffies | 1UL) when flow was emptied, for gc */
75 	};
76 	union {
77 		struct rb_node	fq_node;	/* anchor in fq_root[] trees */
78 		/* Following field is only used for q->internal,
79 		 * because q->internal is not hashed in fq_root[]
80 		 */
81 		u64		stat_fastpath_packets;
82 	};
83 	struct sock	*sk;
84 	u32		socket_hash;	/* sk_hash */
85 	int		qlen;		/* number of packets in flow queue */
86 
87 /* Second cache line, used in fq_dequeue() */
88 	int		credit;
89 	/* 32bit hole on 64bit arches */
90 
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 } ____cacheline_aligned_in_smp;
96 
97 struct fq_flow_head {
98 	struct fq_flow *first;
99 	struct fq_flow *last;
100 };
101 
102 struct fq_sched_data {
103 	struct fq_flow_head new_flows;
104 
105 	struct fq_flow_head old_flows;
106 
107 	struct rb_root	delayed;	/* for rate limited flows */
108 	u64		time_next_delayed_flow;
109 	u64		ktime_cache;	/* copy of last ktime_get_ns() */
110 	unsigned long	unthrottle_latency_ns;
111 
112 	struct fq_flow	internal;	/* for non classified or high prio packets */
113 
114 /* Read mostly cache line */
115 
116 	u32		quantum;
117 	u32		initial_quantum;
118 	u32		flow_refill_delay;
119 	u32		flow_plimit;	/* max packets per flow */
120 	unsigned long	flow_max_rate;	/* optional max rate per flow */
121 	u64		ce_threshold;
122 	u64		horizon;	/* horizon in ns */
123 	u32		orphan_mask;	/* mask for orphaned skb */
124 	u32		low_rate_threshold;
125 	struct rb_root	*fq_root;
126 	u8		rate_enable;
127 	u8		fq_trees_log;
128 	u8		horizon_drop;
129 	u32		timer_slack; /* hrtimer slack in ns */
130 
131 /* Read/Write fields. */
132 
133 	u32		flows;
134 	u32		inactive_flows; /* Flows with no packet to send. */
135 	u32		throttled_flows;
136 
137 	u64		stat_throttled;
138 	struct qdisc_watchdog watchdog;
139 	u64		stat_gc_flows;
140 
141 /* Seldom used fields. */
142 
143 	u64		stat_internal_packets; /* aka highprio */
144 	u64		stat_ce_mark;
145 	u64		stat_horizon_drops;
146 	u64		stat_horizon_caps;
147 	u64		stat_flows_plimit;
148 	u64		stat_pkts_too_long;
149 	u64		stat_allocation_errors;
150 };
151 
152 /*
153  * f->tail and f->age share the same location.
154  * We can use the low order bit to differentiate if this location points
155  * to a sk_buff or contains a jiffies value, if we force this value to be odd.
156  * This assumes f->tail low order bit must be 0 since alignof(struct sk_buff) >= 2
157  */
158 static void fq_flow_set_detached(struct fq_flow *f)
159 {
160 	f->age = jiffies | 1UL;
161 }
162 
163 static bool fq_flow_is_detached(const struct fq_flow *f)
164 {
165 	return !!(f->age & 1UL);
166 }
167 
168 /* special value to mark a throttled flow (not on old/new list) */
169 static struct fq_flow throttled;
170 
171 static bool fq_flow_is_throttled(const struct fq_flow *f)
172 {
173 	return f->next == &throttled;
174 }
175 
176 static void fq_flow_add_tail(struct fq_flow_head *head, struct fq_flow *flow)
177 {
178 	if (head->first)
179 		head->last->next = flow;
180 	else
181 		head->first = flow;
182 	head->last = flow;
183 	flow->next = NULL;
184 }
185 
186 static void fq_flow_unset_throttled(struct fq_sched_data *q, struct fq_flow *f)
187 {
188 	rb_erase(&f->rate_node, &q->delayed);
189 	q->throttled_flows--;
190 	fq_flow_add_tail(&q->old_flows, f);
191 }
192 
193 static void fq_flow_set_throttled(struct fq_sched_data *q, struct fq_flow *f)
194 {
195 	struct rb_node **p = &q->delayed.rb_node, *parent = NULL;
196 
197 	while (*p) {
198 		struct fq_flow *aux;
199 
200 		parent = *p;
201 		aux = rb_entry(parent, struct fq_flow, rate_node);
202 		if (f->time_next_packet >= aux->time_next_packet)
203 			p = &parent->rb_right;
204 		else
205 			p = &parent->rb_left;
206 	}
207 	rb_link_node(&f->rate_node, parent, p);
208 	rb_insert_color(&f->rate_node, &q->delayed);
209 	q->throttled_flows++;
210 	q->stat_throttled++;
211 
212 	f->next = &throttled;
213 	if (q->time_next_delayed_flow > f->time_next_packet)
214 		q->time_next_delayed_flow = f->time_next_packet;
215 }
216 
217 
218 static struct kmem_cache *fq_flow_cachep __read_mostly;
219 
220 
221 /* limit number of collected flows per round */
222 #define FQ_GC_MAX 8
223 #define FQ_GC_AGE (3*HZ)
224 
225 static bool fq_gc_candidate(const struct fq_flow *f)
226 {
227 	return fq_flow_is_detached(f) &&
228 	       time_after(jiffies, f->age + FQ_GC_AGE);
229 }
230 
231 static void fq_gc(struct fq_sched_data *q,
232 		  struct rb_root *root,
233 		  struct sock *sk)
234 {
235 	struct rb_node **p, *parent;
236 	void *tofree[FQ_GC_MAX];
237 	struct fq_flow *f;
238 	int i, fcnt = 0;
239 
240 	p = &root->rb_node;
241 	parent = NULL;
242 	while (*p) {
243 		parent = *p;
244 
245 		f = rb_entry(parent, struct fq_flow, fq_node);
246 		if (f->sk == sk)
247 			break;
248 
249 		if (fq_gc_candidate(f)) {
250 			tofree[fcnt++] = f;
251 			if (fcnt == FQ_GC_MAX)
252 				break;
253 		}
254 
255 		if (f->sk > sk)
256 			p = &parent->rb_right;
257 		else
258 			p = &parent->rb_left;
259 	}
260 
261 	if (!fcnt)
262 		return;
263 
264 	for (i = fcnt; i > 0; ) {
265 		f = tofree[--i];
266 		rb_erase(&f->fq_node, root);
267 	}
268 	q->flows -= fcnt;
269 	q->inactive_flows -= fcnt;
270 	q->stat_gc_flows += fcnt;
271 
272 	kmem_cache_free_bulk(fq_flow_cachep, fcnt, tofree);
273 }
274 
275 /* Fast path can be used if :
276  * 1) Packet tstamp is in the past.
277  * 2) FQ qlen == 0   OR
278  *   (no flow is currently eligible for transmit,
279  *    AND fast path queue has less than 8 packets)
280  * 3) No SO_MAX_PACING_RATE on the socket (if any).
281  * 4) No @maxrate attribute on this qdisc,
282  *
283  * FQ can not use generic TCQ_F_CAN_BYPASS infrastructure.
284  */
285 static bool fq_fastpath_check(const struct Qdisc *sch, struct sk_buff *skb)
286 {
287 	const struct fq_sched_data *q = qdisc_priv(sch);
288 	const struct sock *sk;
289 
290 	if (fq_skb_cb(skb)->time_to_send > q->ktime_cache)
291 		return false;
292 
293 	if (sch->q.qlen != 0) {
294 		/* Even if some packets are stored in this qdisc,
295 		 * we can still enable fast path if all of them are
296 		 * scheduled in the future (ie no flows are eligible)
297 		 * or in the fast path queue.
298 		 */
299 		if (q->flows != q->inactive_flows + q->throttled_flows)
300 			return false;
301 
302 		/* Do not allow fast path queue to explode, we want Fair Queue mode
303 		 * under pressure.
304 		 */
305 		if (q->internal.qlen >= 8)
306 			return false;
307 	}
308 
309 	sk = skb->sk;
310 	if (sk && sk_fullsock(sk) && !sk_is_tcp(sk) &&
311 	    sk->sk_max_pacing_rate != ~0UL)
312 		return false;
313 
314 	if (q->flow_max_rate != ~0UL)
315 		return false;
316 
317 	return true;
318 }
319 
320 static struct fq_flow *fq_classify(struct Qdisc *sch, struct sk_buff *skb)
321 {
322 	struct fq_sched_data *q = qdisc_priv(sch);
323 	struct rb_node **p, *parent;
324 	struct sock *sk = skb->sk;
325 	struct rb_root *root;
326 	struct fq_flow *f;
327 
328 	/* warning: no starvation prevention... */
329 	if (unlikely((skb->priority & TC_PRIO_MAX) == TC_PRIO_CONTROL)) {
330 		q->stat_internal_packets++; /* highprio packet */
331 		return &q->internal;
332 	}
333 	/* SYNACK messages are attached to a TCP_NEW_SYN_RECV request socket
334 	 * or a listener (SYNCOOKIE mode)
335 	 * 1) request sockets are not full blown,
336 	 *    they do not contain sk_pacing_rate
337 	 * 2) They are not part of a 'flow' yet
338 	 * 3) We do not want to rate limit them (eg SYNFLOOD attack),
339 	 *    especially if the listener set SO_MAX_PACING_RATE
340 	 * 4) We pretend they are orphaned
341 	 */
342 	if (!sk || sk_listener(sk)) {
343 		unsigned long hash = skb_get_hash(skb) & q->orphan_mask;
344 
345 		/* By forcing low order bit to 1, we make sure to not
346 		 * collide with a local flow (socket pointers are word aligned)
347 		 */
348 		sk = (struct sock *)((hash << 1) | 1UL);
349 		skb_orphan(skb);
350 	} else if (sk->sk_state == TCP_CLOSE) {
351 		unsigned long hash = skb_get_hash(skb) & q->orphan_mask;
352 		/*
353 		 * Sockets in TCP_CLOSE are non connected.
354 		 * Typical use case is UDP sockets, they can send packets
355 		 * with sendto() to many different destinations.
356 		 * We probably could use a generic bit advertising
357 		 * non connected sockets, instead of sk_state == TCP_CLOSE,
358 		 * if we care enough.
359 		 */
360 		sk = (struct sock *)((hash << 1) | 1UL);
361 	}
362 
363 	if (fq_fastpath_check(sch, skb)) {
364 		q->internal.stat_fastpath_packets++;
365 		return &q->internal;
366 	}
367 
368 	root = &q->fq_root[hash_ptr(sk, q->fq_trees_log)];
369 
370 	fq_gc(q, root, sk);
371 
372 	p = &root->rb_node;
373 	parent = NULL;
374 	while (*p) {
375 		parent = *p;
376 
377 		f = rb_entry(parent, struct fq_flow, fq_node);
378 		if (f->sk == sk) {
379 			/* socket might have been reallocated, so check
380 			 * if its sk_hash is the same.
381 			 * It not, we need to refill credit with
382 			 * initial quantum
383 			 */
384 			if (unlikely(skb->sk == sk &&
385 				     f->socket_hash != sk->sk_hash)) {
386 				f->credit = q->initial_quantum;
387 				f->socket_hash = sk->sk_hash;
388 				if (q->rate_enable)
389 					smp_store_release(&sk->sk_pacing_status,
390 							  SK_PACING_FQ);
391 				if (fq_flow_is_throttled(f))
392 					fq_flow_unset_throttled(q, f);
393 				f->time_next_packet = 0ULL;
394 			}
395 			return f;
396 		}
397 		if (f->sk > sk)
398 			p = &parent->rb_right;
399 		else
400 			p = &parent->rb_left;
401 	}
402 
403 	f = kmem_cache_zalloc(fq_flow_cachep, GFP_ATOMIC | __GFP_NOWARN);
404 	if (unlikely(!f)) {
405 		q->stat_allocation_errors++;
406 		return &q->internal;
407 	}
408 	/* f->t_root is already zeroed after kmem_cache_zalloc() */
409 
410 	fq_flow_set_detached(f);
411 	f->sk = sk;
412 	if (skb->sk == sk) {
413 		f->socket_hash = sk->sk_hash;
414 		if (q->rate_enable)
415 			smp_store_release(&sk->sk_pacing_status,
416 					  SK_PACING_FQ);
417 	}
418 	f->credit = q->initial_quantum;
419 
420 	rb_link_node(&f->fq_node, parent, p);
421 	rb_insert_color(&f->fq_node, root);
422 
423 	q->flows++;
424 	q->inactive_flows++;
425 	return f;
426 }
427 
428 static struct sk_buff *fq_peek(struct fq_flow *flow)
429 {
430 	struct sk_buff *skb = skb_rb_first(&flow->t_root);
431 	struct sk_buff *head = flow->head;
432 
433 	if (!skb)
434 		return head;
435 
436 	if (!head)
437 		return skb;
438 
439 	if (fq_skb_cb(skb)->time_to_send < fq_skb_cb(head)->time_to_send)
440 		return skb;
441 	return head;
442 }
443 
444 static void fq_erase_head(struct Qdisc *sch, struct fq_flow *flow,
445 			  struct sk_buff *skb)
446 {
447 	if (skb == flow->head) {
448 		flow->head = skb->next;
449 	} else {
450 		rb_erase(&skb->rbnode, &flow->t_root);
451 		skb->dev = qdisc_dev(sch);
452 	}
453 }
454 
455 /* Remove one skb from flow queue.
456  * This skb must be the return value of prior fq_peek().
457  */
458 static void fq_dequeue_skb(struct Qdisc *sch, struct fq_flow *flow,
459 			   struct sk_buff *skb)
460 {
461 	fq_erase_head(sch, flow, skb);
462 	skb_mark_not_on_list(skb);
463 	qdisc_qstats_backlog_dec(sch, skb);
464 	sch->q.qlen--;
465 }
466 
467 static void flow_queue_add(struct fq_flow *flow, struct sk_buff *skb)
468 {
469 	struct rb_node **p, *parent;
470 	struct sk_buff *head, *aux;
471 
472 	head = flow->head;
473 	if (!head ||
474 	    fq_skb_cb(skb)->time_to_send >= fq_skb_cb(flow->tail)->time_to_send) {
475 		if (!head)
476 			flow->head = skb;
477 		else
478 			flow->tail->next = skb;
479 		flow->tail = skb;
480 		skb->next = NULL;
481 		return;
482 	}
483 
484 	p = &flow->t_root.rb_node;
485 	parent = NULL;
486 
487 	while (*p) {
488 		parent = *p;
489 		aux = rb_to_skb(parent);
490 		if (fq_skb_cb(skb)->time_to_send >= fq_skb_cb(aux)->time_to_send)
491 			p = &parent->rb_right;
492 		else
493 			p = &parent->rb_left;
494 	}
495 	rb_link_node(&skb->rbnode, parent, p);
496 	rb_insert_color(&skb->rbnode, &flow->t_root);
497 }
498 
499 static bool fq_packet_beyond_horizon(const struct sk_buff *skb,
500 				    const struct fq_sched_data *q)
501 {
502 	return unlikely((s64)skb->tstamp > (s64)(q->ktime_cache + q->horizon));
503 }
504 
505 static int fq_enqueue(struct sk_buff *skb, struct Qdisc *sch,
506 		      struct sk_buff **to_free)
507 {
508 	struct fq_sched_data *q = qdisc_priv(sch);
509 	struct fq_flow *f;
510 
511 	if (unlikely(sch->q.qlen >= sch->limit))
512 		return qdisc_drop(skb, sch, to_free);
513 
514 	q->ktime_cache = ktime_get_ns();
515 	if (!skb->tstamp) {
516 		fq_skb_cb(skb)->time_to_send = q->ktime_cache;
517 	} else {
518 		/* Check if packet timestamp is too far in the future. */
519 		if (fq_packet_beyond_horizon(skb, q)) {
520 			if (q->horizon_drop) {
521 					q->stat_horizon_drops++;
522 					return qdisc_drop(skb, sch, to_free);
523 			}
524 			q->stat_horizon_caps++;
525 			skb->tstamp = q->ktime_cache + q->horizon;
526 		}
527 		fq_skb_cb(skb)->time_to_send = skb->tstamp;
528 	}
529 
530 	f = fq_classify(sch, skb);
531 
532 	if (f != &q->internal) {
533 		if (unlikely(f->qlen >= q->flow_plimit)) {
534 			q->stat_flows_plimit++;
535 			return qdisc_drop(skb, sch, to_free);
536 		}
537 
538 		if (fq_flow_is_detached(f)) {
539 			fq_flow_add_tail(&q->new_flows, f);
540 			if (time_after(jiffies, f->age + q->flow_refill_delay))
541 				f->credit = max_t(u32, f->credit, q->quantum);
542 		}
543 
544 		if (f->qlen == 0)
545 			q->inactive_flows--;
546 	}
547 
548 	f->qlen++;
549 	/* Note: this overwrites f->age */
550 	flow_queue_add(f, skb);
551 
552 	qdisc_qstats_backlog_inc(sch, skb);
553 	sch->q.qlen++;
554 
555 	return NET_XMIT_SUCCESS;
556 }
557 
558 static void fq_check_throttled(struct fq_sched_data *q, u64 now)
559 {
560 	unsigned long sample;
561 	struct rb_node *p;
562 
563 	if (q->time_next_delayed_flow > now)
564 		return;
565 
566 	/* Update unthrottle latency EWMA.
567 	 * This is cheap and can help diagnosing timer/latency problems.
568 	 */
569 	sample = (unsigned long)(now - q->time_next_delayed_flow);
570 	q->unthrottle_latency_ns -= q->unthrottle_latency_ns >> 3;
571 	q->unthrottle_latency_ns += sample >> 3;
572 
573 	q->time_next_delayed_flow = ~0ULL;
574 	while ((p = rb_first(&q->delayed)) != NULL) {
575 		struct fq_flow *f = rb_entry(p, struct fq_flow, rate_node);
576 
577 		if (f->time_next_packet > now) {
578 			q->time_next_delayed_flow = f->time_next_packet;
579 			break;
580 		}
581 		fq_flow_unset_throttled(q, f);
582 	}
583 }
584 
585 static struct sk_buff *fq_dequeue(struct Qdisc *sch)
586 {
587 	struct fq_sched_data *q = qdisc_priv(sch);
588 	struct fq_flow_head *head;
589 	struct sk_buff *skb;
590 	struct fq_flow *f;
591 	unsigned long rate;
592 	u32 plen;
593 	u64 now;
594 
595 	if (!sch->q.qlen)
596 		return NULL;
597 
598 	skb = fq_peek(&q->internal);
599 	if (unlikely(skb)) {
600 		q->internal.qlen--;
601 		fq_dequeue_skb(sch, &q->internal, skb);
602 		goto out;
603 	}
604 
605 	q->ktime_cache = now = ktime_get_ns();
606 	fq_check_throttled(q, now);
607 begin:
608 	head = &q->new_flows;
609 	if (!head->first) {
610 		head = &q->old_flows;
611 		if (!head->first) {
612 			if (q->time_next_delayed_flow != ~0ULL)
613 				qdisc_watchdog_schedule_range_ns(&q->watchdog,
614 							q->time_next_delayed_flow,
615 							q->timer_slack);
616 			return NULL;
617 		}
618 	}
619 	f = head->first;
620 
621 	if (f->credit <= 0) {
622 		f->credit += q->quantum;
623 		head->first = f->next;
624 		fq_flow_add_tail(&q->old_flows, f);
625 		goto begin;
626 	}
627 
628 	skb = fq_peek(f);
629 	if (skb) {
630 		u64 time_next_packet = max_t(u64, fq_skb_cb(skb)->time_to_send,
631 					     f->time_next_packet);
632 
633 		if (now < time_next_packet) {
634 			head->first = f->next;
635 			f->time_next_packet = time_next_packet;
636 			fq_flow_set_throttled(q, f);
637 			goto begin;
638 		}
639 		prefetch(&skb->end);
640 		if ((s64)(now - time_next_packet - q->ce_threshold) > 0) {
641 			INET_ECN_set_ce(skb);
642 			q->stat_ce_mark++;
643 		}
644 		if (--f->qlen == 0)
645 			q->inactive_flows++;
646 		fq_dequeue_skb(sch, f, skb);
647 	} else {
648 		head->first = f->next;
649 		/* force a pass through old_flows to prevent starvation */
650 		if ((head == &q->new_flows) && q->old_flows.first) {
651 			fq_flow_add_tail(&q->old_flows, f);
652 		} else {
653 			fq_flow_set_detached(f);
654 		}
655 		goto begin;
656 	}
657 	plen = qdisc_pkt_len(skb);
658 	f->credit -= plen;
659 
660 	if (!q->rate_enable)
661 		goto out;
662 
663 	rate = q->flow_max_rate;
664 
665 	/* If EDT time was provided for this skb, we need to
666 	 * update f->time_next_packet only if this qdisc enforces
667 	 * a flow max rate.
668 	 */
669 	if (!skb->tstamp) {
670 		if (skb->sk)
671 			rate = min(READ_ONCE(skb->sk->sk_pacing_rate), rate);
672 
673 		if (rate <= q->low_rate_threshold) {
674 			f->credit = 0;
675 		} else {
676 			plen = max(plen, q->quantum);
677 			if (f->credit > 0)
678 				goto out;
679 		}
680 	}
681 	if (rate != ~0UL) {
682 		u64 len = (u64)plen * NSEC_PER_SEC;
683 
684 		if (likely(rate))
685 			len = div64_ul(len, rate);
686 		/* Since socket rate can change later,
687 		 * clamp the delay to 1 second.
688 		 * Really, providers of too big packets should be fixed !
689 		 */
690 		if (unlikely(len > NSEC_PER_SEC)) {
691 			len = NSEC_PER_SEC;
692 			q->stat_pkts_too_long++;
693 		}
694 		/* Account for schedule/timers drifts.
695 		 * f->time_next_packet was set when prior packet was sent,
696 		 * and current time (@now) can be too late by tens of us.
697 		 */
698 		if (f->time_next_packet)
699 			len -= min(len/2, now - f->time_next_packet);
700 		f->time_next_packet = now + len;
701 	}
702 out:
703 	qdisc_bstats_update(sch, skb);
704 	return skb;
705 }
706 
707 static void fq_flow_purge(struct fq_flow *flow)
708 {
709 	struct rb_node *p = rb_first(&flow->t_root);
710 
711 	while (p) {
712 		struct sk_buff *skb = rb_to_skb(p);
713 
714 		p = rb_next(p);
715 		rb_erase(&skb->rbnode, &flow->t_root);
716 		rtnl_kfree_skbs(skb, skb);
717 	}
718 	rtnl_kfree_skbs(flow->head, flow->tail);
719 	flow->head = NULL;
720 	flow->qlen = 0;
721 }
722 
723 static void fq_reset(struct Qdisc *sch)
724 {
725 	struct fq_sched_data *q = qdisc_priv(sch);
726 	struct rb_root *root;
727 	struct rb_node *p;
728 	struct fq_flow *f;
729 	unsigned int idx;
730 
731 	sch->q.qlen = 0;
732 	sch->qstats.backlog = 0;
733 
734 	fq_flow_purge(&q->internal);
735 
736 	if (!q->fq_root)
737 		return;
738 
739 	for (idx = 0; idx < (1U << q->fq_trees_log); idx++) {
740 		root = &q->fq_root[idx];
741 		while ((p = rb_first(root)) != NULL) {
742 			f = rb_entry(p, struct fq_flow, fq_node);
743 			rb_erase(p, root);
744 
745 			fq_flow_purge(f);
746 
747 			kmem_cache_free(fq_flow_cachep, f);
748 		}
749 	}
750 	q->new_flows.first	= NULL;
751 	q->old_flows.first	= NULL;
752 	q->delayed		= RB_ROOT;
753 	q->flows		= 0;
754 	q->inactive_flows	= 0;
755 	q->throttled_flows	= 0;
756 }
757 
758 static void fq_rehash(struct fq_sched_data *q,
759 		      struct rb_root *old_array, u32 old_log,
760 		      struct rb_root *new_array, u32 new_log)
761 {
762 	struct rb_node *op, **np, *parent;
763 	struct rb_root *oroot, *nroot;
764 	struct fq_flow *of, *nf;
765 	int fcnt = 0;
766 	u32 idx;
767 
768 	for (idx = 0; idx < (1U << old_log); idx++) {
769 		oroot = &old_array[idx];
770 		while ((op = rb_first(oroot)) != NULL) {
771 			rb_erase(op, oroot);
772 			of = rb_entry(op, struct fq_flow, fq_node);
773 			if (fq_gc_candidate(of)) {
774 				fcnt++;
775 				kmem_cache_free(fq_flow_cachep, of);
776 				continue;
777 			}
778 			nroot = &new_array[hash_ptr(of->sk, new_log)];
779 
780 			np = &nroot->rb_node;
781 			parent = NULL;
782 			while (*np) {
783 				parent = *np;
784 
785 				nf = rb_entry(parent, struct fq_flow, fq_node);
786 				BUG_ON(nf->sk == of->sk);
787 
788 				if (nf->sk > of->sk)
789 					np = &parent->rb_right;
790 				else
791 					np = &parent->rb_left;
792 			}
793 
794 			rb_link_node(&of->fq_node, parent, np);
795 			rb_insert_color(&of->fq_node, nroot);
796 		}
797 	}
798 	q->flows -= fcnt;
799 	q->inactive_flows -= fcnt;
800 	q->stat_gc_flows += fcnt;
801 }
802 
803 static void fq_free(void *addr)
804 {
805 	kvfree(addr);
806 }
807 
808 static int fq_resize(struct Qdisc *sch, u32 log)
809 {
810 	struct fq_sched_data *q = qdisc_priv(sch);
811 	struct rb_root *array;
812 	void *old_fq_root;
813 	u32 idx;
814 
815 	if (q->fq_root && log == q->fq_trees_log)
816 		return 0;
817 
818 	/* If XPS was setup, we can allocate memory on right NUMA node */
819 	array = kvmalloc_node(sizeof(struct rb_root) << log, GFP_KERNEL | __GFP_RETRY_MAYFAIL,
820 			      netdev_queue_numa_node_read(sch->dev_queue));
821 	if (!array)
822 		return -ENOMEM;
823 
824 	for (idx = 0; idx < (1U << log); idx++)
825 		array[idx] = RB_ROOT;
826 
827 	sch_tree_lock(sch);
828 
829 	old_fq_root = q->fq_root;
830 	if (old_fq_root)
831 		fq_rehash(q, old_fq_root, q->fq_trees_log, array, log);
832 
833 	q->fq_root = array;
834 	q->fq_trees_log = log;
835 
836 	sch_tree_unlock(sch);
837 
838 	fq_free(old_fq_root);
839 
840 	return 0;
841 }
842 
843 static struct netlink_range_validation iq_range = {
844 	.max = INT_MAX,
845 };
846 
847 static const struct nla_policy fq_policy[TCA_FQ_MAX + 1] = {
848 	[TCA_FQ_UNSPEC]			= { .strict_start_type = TCA_FQ_TIMER_SLACK },
849 
850 	[TCA_FQ_PLIMIT]			= { .type = NLA_U32 },
851 	[TCA_FQ_FLOW_PLIMIT]		= { .type = NLA_U32 },
852 	[TCA_FQ_QUANTUM]		= { .type = NLA_U32 },
853 	[TCA_FQ_INITIAL_QUANTUM]	= NLA_POLICY_FULL_RANGE(NLA_U32, &iq_range),
854 	[TCA_FQ_RATE_ENABLE]		= { .type = NLA_U32 },
855 	[TCA_FQ_FLOW_DEFAULT_RATE]	= { .type = NLA_U32 },
856 	[TCA_FQ_FLOW_MAX_RATE]		= { .type = NLA_U32 },
857 	[TCA_FQ_BUCKETS_LOG]		= { .type = NLA_U32 },
858 	[TCA_FQ_FLOW_REFILL_DELAY]	= { .type = NLA_U32 },
859 	[TCA_FQ_ORPHAN_MASK]		= { .type = NLA_U32 },
860 	[TCA_FQ_LOW_RATE_THRESHOLD]	= { .type = NLA_U32 },
861 	[TCA_FQ_CE_THRESHOLD]		= { .type = NLA_U32 },
862 	[TCA_FQ_TIMER_SLACK]		= { .type = NLA_U32 },
863 	[TCA_FQ_HORIZON]		= { .type = NLA_U32 },
864 	[TCA_FQ_HORIZON_DROP]		= { .type = NLA_U8 },
865 };
866 
867 static int fq_change(struct Qdisc *sch, struct nlattr *opt,
868 		     struct netlink_ext_ack *extack)
869 {
870 	struct fq_sched_data *q = qdisc_priv(sch);
871 	struct nlattr *tb[TCA_FQ_MAX + 1];
872 	int err, drop_count = 0;
873 	unsigned drop_len = 0;
874 	u32 fq_log;
875 
876 	err = nla_parse_nested_deprecated(tb, TCA_FQ_MAX, opt, fq_policy,
877 					  NULL);
878 	if (err < 0)
879 		return err;
880 
881 	sch_tree_lock(sch);
882 
883 	fq_log = q->fq_trees_log;
884 
885 	if (tb[TCA_FQ_BUCKETS_LOG]) {
886 		u32 nval = nla_get_u32(tb[TCA_FQ_BUCKETS_LOG]);
887 
888 		if (nval >= 1 && nval <= ilog2(256*1024))
889 			fq_log = nval;
890 		else
891 			err = -EINVAL;
892 	}
893 	if (tb[TCA_FQ_PLIMIT])
894 		sch->limit = nla_get_u32(tb[TCA_FQ_PLIMIT]);
895 
896 	if (tb[TCA_FQ_FLOW_PLIMIT])
897 		q->flow_plimit = nla_get_u32(tb[TCA_FQ_FLOW_PLIMIT]);
898 
899 	if (tb[TCA_FQ_QUANTUM]) {
900 		u32 quantum = nla_get_u32(tb[TCA_FQ_QUANTUM]);
901 
902 		if (quantum > 0 && quantum <= (1 << 20)) {
903 			q->quantum = quantum;
904 		} else {
905 			NL_SET_ERR_MSG_MOD(extack, "invalid quantum");
906 			err = -EINVAL;
907 		}
908 	}
909 
910 	if (tb[TCA_FQ_INITIAL_QUANTUM])
911 		q->initial_quantum = nla_get_u32(tb[TCA_FQ_INITIAL_QUANTUM]);
912 
913 	if (tb[TCA_FQ_FLOW_DEFAULT_RATE])
914 		pr_warn_ratelimited("sch_fq: defrate %u ignored.\n",
915 				    nla_get_u32(tb[TCA_FQ_FLOW_DEFAULT_RATE]));
916 
917 	if (tb[TCA_FQ_FLOW_MAX_RATE]) {
918 		u32 rate = nla_get_u32(tb[TCA_FQ_FLOW_MAX_RATE]);
919 
920 		q->flow_max_rate = (rate == ~0U) ? ~0UL : rate;
921 	}
922 	if (tb[TCA_FQ_LOW_RATE_THRESHOLD])
923 		q->low_rate_threshold =
924 			nla_get_u32(tb[TCA_FQ_LOW_RATE_THRESHOLD]);
925 
926 	if (tb[TCA_FQ_RATE_ENABLE]) {
927 		u32 enable = nla_get_u32(tb[TCA_FQ_RATE_ENABLE]);
928 
929 		if (enable <= 1)
930 			q->rate_enable = enable;
931 		else
932 			err = -EINVAL;
933 	}
934 
935 	if (tb[TCA_FQ_FLOW_REFILL_DELAY]) {
936 		u32 usecs_delay = nla_get_u32(tb[TCA_FQ_FLOW_REFILL_DELAY]) ;
937 
938 		q->flow_refill_delay = usecs_to_jiffies(usecs_delay);
939 	}
940 
941 	if (tb[TCA_FQ_ORPHAN_MASK])
942 		q->orphan_mask = nla_get_u32(tb[TCA_FQ_ORPHAN_MASK]);
943 
944 	if (tb[TCA_FQ_CE_THRESHOLD])
945 		q->ce_threshold = (u64)NSEC_PER_USEC *
946 				  nla_get_u32(tb[TCA_FQ_CE_THRESHOLD]);
947 
948 	if (tb[TCA_FQ_TIMER_SLACK])
949 		q->timer_slack = nla_get_u32(tb[TCA_FQ_TIMER_SLACK]);
950 
951 	if (tb[TCA_FQ_HORIZON])
952 		q->horizon = (u64)NSEC_PER_USEC *
953 				  nla_get_u32(tb[TCA_FQ_HORIZON]);
954 
955 	if (tb[TCA_FQ_HORIZON_DROP])
956 		q->horizon_drop = nla_get_u8(tb[TCA_FQ_HORIZON_DROP]);
957 
958 	if (!err) {
959 
960 		sch_tree_unlock(sch);
961 		err = fq_resize(sch, fq_log);
962 		sch_tree_lock(sch);
963 	}
964 	while (sch->q.qlen > sch->limit) {
965 		struct sk_buff *skb = fq_dequeue(sch);
966 
967 		if (!skb)
968 			break;
969 		drop_len += qdisc_pkt_len(skb);
970 		rtnl_kfree_skbs(skb, skb);
971 		drop_count++;
972 	}
973 	qdisc_tree_reduce_backlog(sch, drop_count, drop_len);
974 
975 	sch_tree_unlock(sch);
976 	return err;
977 }
978 
979 static void fq_destroy(struct Qdisc *sch)
980 {
981 	struct fq_sched_data *q = qdisc_priv(sch);
982 
983 	fq_reset(sch);
984 	fq_free(q->fq_root);
985 	qdisc_watchdog_cancel(&q->watchdog);
986 }
987 
988 static int fq_init(struct Qdisc *sch, struct nlattr *opt,
989 		   struct netlink_ext_ack *extack)
990 {
991 	struct fq_sched_data *q = qdisc_priv(sch);
992 	int err;
993 
994 	sch->limit		= 10000;
995 	q->flow_plimit		= 100;
996 	q->quantum		= 2 * psched_mtu(qdisc_dev(sch));
997 	q->initial_quantum	= 10 * psched_mtu(qdisc_dev(sch));
998 	q->flow_refill_delay	= msecs_to_jiffies(40);
999 	q->flow_max_rate	= ~0UL;
1000 	q->time_next_delayed_flow = ~0ULL;
1001 	q->rate_enable		= 1;
1002 	q->new_flows.first	= NULL;
1003 	q->old_flows.first	= NULL;
1004 	q->delayed		= RB_ROOT;
1005 	q->fq_root		= NULL;
1006 	q->fq_trees_log		= ilog2(1024);
1007 	q->orphan_mask		= 1024 - 1;
1008 	q->low_rate_threshold	= 550000 / 8;
1009 
1010 	q->timer_slack = 10 * NSEC_PER_USEC; /* 10 usec of hrtimer slack */
1011 
1012 	q->horizon = 10ULL * NSEC_PER_SEC; /* 10 seconds */
1013 	q->horizon_drop = 1; /* by default, drop packets beyond horizon */
1014 
1015 	/* Default ce_threshold of 4294 seconds */
1016 	q->ce_threshold		= (u64)NSEC_PER_USEC * ~0U;
1017 
1018 	qdisc_watchdog_init_clockid(&q->watchdog, sch, CLOCK_MONOTONIC);
1019 
1020 	if (opt)
1021 		err = fq_change(sch, opt, extack);
1022 	else
1023 		err = fq_resize(sch, q->fq_trees_log);
1024 
1025 	return err;
1026 }
1027 
1028 static int fq_dump(struct Qdisc *sch, struct sk_buff *skb)
1029 {
1030 	struct fq_sched_data *q = qdisc_priv(sch);
1031 	u64 ce_threshold = q->ce_threshold;
1032 	u64 horizon = q->horizon;
1033 	struct nlattr *opts;
1034 
1035 	opts = nla_nest_start_noflag(skb, TCA_OPTIONS);
1036 	if (opts == NULL)
1037 		goto nla_put_failure;
1038 
1039 	/* TCA_FQ_FLOW_DEFAULT_RATE is not used anymore */
1040 
1041 	do_div(ce_threshold, NSEC_PER_USEC);
1042 	do_div(horizon, NSEC_PER_USEC);
1043 
1044 	if (nla_put_u32(skb, TCA_FQ_PLIMIT, sch->limit) ||
1045 	    nla_put_u32(skb, TCA_FQ_FLOW_PLIMIT, q->flow_plimit) ||
1046 	    nla_put_u32(skb, TCA_FQ_QUANTUM, q->quantum) ||
1047 	    nla_put_u32(skb, TCA_FQ_INITIAL_QUANTUM, q->initial_quantum) ||
1048 	    nla_put_u32(skb, TCA_FQ_RATE_ENABLE, q->rate_enable) ||
1049 	    nla_put_u32(skb, TCA_FQ_FLOW_MAX_RATE,
1050 			min_t(unsigned long, q->flow_max_rate, ~0U)) ||
1051 	    nla_put_u32(skb, TCA_FQ_FLOW_REFILL_DELAY,
1052 			jiffies_to_usecs(q->flow_refill_delay)) ||
1053 	    nla_put_u32(skb, TCA_FQ_ORPHAN_MASK, q->orphan_mask) ||
1054 	    nla_put_u32(skb, TCA_FQ_LOW_RATE_THRESHOLD,
1055 			q->low_rate_threshold) ||
1056 	    nla_put_u32(skb, TCA_FQ_CE_THRESHOLD, (u32)ce_threshold) ||
1057 	    nla_put_u32(skb, TCA_FQ_BUCKETS_LOG, q->fq_trees_log) ||
1058 	    nla_put_u32(skb, TCA_FQ_TIMER_SLACK, q->timer_slack) ||
1059 	    nla_put_u32(skb, TCA_FQ_HORIZON, (u32)horizon) ||
1060 	    nla_put_u8(skb, TCA_FQ_HORIZON_DROP, q->horizon_drop))
1061 		goto nla_put_failure;
1062 
1063 	return nla_nest_end(skb, opts);
1064 
1065 nla_put_failure:
1066 	return -1;
1067 }
1068 
1069 static int fq_dump_stats(struct Qdisc *sch, struct gnet_dump *d)
1070 {
1071 	struct fq_sched_data *q = qdisc_priv(sch);
1072 	struct tc_fq_qd_stats st;
1073 
1074 	sch_tree_lock(sch);
1075 
1076 	st.gc_flows		  = q->stat_gc_flows;
1077 	st.highprio_packets	  = q->stat_internal_packets;
1078 	st.fastpath_packets	  = q->internal.stat_fastpath_packets;
1079 	st.tcp_retrans		  = 0;
1080 	st.throttled		  = q->stat_throttled;
1081 	st.flows_plimit		  = q->stat_flows_plimit;
1082 	st.pkts_too_long	  = q->stat_pkts_too_long;
1083 	st.allocation_errors	  = q->stat_allocation_errors;
1084 	st.time_next_delayed_flow = q->time_next_delayed_flow + q->timer_slack -
1085 				    ktime_get_ns();
1086 	st.flows		  = q->flows;
1087 	st.inactive_flows	  = q->inactive_flows;
1088 	st.throttled_flows	  = q->throttled_flows;
1089 	st.unthrottle_latency_ns  = min_t(unsigned long,
1090 					  q->unthrottle_latency_ns, ~0U);
1091 	st.ce_mark		  = q->stat_ce_mark;
1092 	st.horizon_drops	  = q->stat_horizon_drops;
1093 	st.horizon_caps		  = q->stat_horizon_caps;
1094 	sch_tree_unlock(sch);
1095 
1096 	return gnet_stats_copy_app(d, &st, sizeof(st));
1097 }
1098 
1099 static struct Qdisc_ops fq_qdisc_ops __read_mostly = {
1100 	.id		=	"fq",
1101 	.priv_size	=	sizeof(struct fq_sched_data),
1102 
1103 	.enqueue	=	fq_enqueue,
1104 	.dequeue	=	fq_dequeue,
1105 	.peek		=	qdisc_peek_dequeued,
1106 	.init		=	fq_init,
1107 	.reset		=	fq_reset,
1108 	.destroy	=	fq_destroy,
1109 	.change		=	fq_change,
1110 	.dump		=	fq_dump,
1111 	.dump_stats	=	fq_dump_stats,
1112 	.owner		=	THIS_MODULE,
1113 };
1114 
1115 static int __init fq_module_init(void)
1116 {
1117 	int ret;
1118 
1119 	fq_flow_cachep = kmem_cache_create("fq_flow_cache",
1120 					   sizeof(struct fq_flow),
1121 					   0, 0, NULL);
1122 	if (!fq_flow_cachep)
1123 		return -ENOMEM;
1124 
1125 	ret = register_qdisc(&fq_qdisc_ops);
1126 	if (ret)
1127 		kmem_cache_destroy(fq_flow_cachep);
1128 	return ret;
1129 }
1130 
1131 static void __exit fq_module_exit(void)
1132 {
1133 	unregister_qdisc(&fq_qdisc_ops);
1134 	kmem_cache_destroy(fq_flow_cachep);
1135 }
1136 
1137 module_init(fq_module_init)
1138 module_exit(fq_module_exit)
1139 MODULE_AUTHOR("Eric Dumazet");
1140 MODULE_LICENSE("GPL");
1141 MODULE_DESCRIPTION("Fair Queue Packet Scheduler");
1142