xref: /linux/net/sched/sch_qfq.c (revision 25aee3debe0464f6c680173041fa3de30ec9ff54)
1 /*
2  * net/sched/sch_qfq.c         Quick Fair Queueing Scheduler.
3  *
4  * Copyright (c) 2009 Fabio Checconi, Luigi Rizzo, and Paolo Valente.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * version 2 as published by the Free Software Foundation.
9  */
10 
11 #include <linux/module.h>
12 #include <linux/init.h>
13 #include <linux/bitops.h>
14 #include <linux/errno.h>
15 #include <linux/netdevice.h>
16 #include <linux/pkt_sched.h>
17 #include <net/sch_generic.h>
18 #include <net/pkt_sched.h>
19 #include <net/pkt_cls.h>
20 
21 
22 /*  Quick Fair Queueing
23     ===================
24 
25     Sources:
26 
27     Fabio Checconi, Luigi Rizzo, and Paolo Valente: "QFQ: Efficient
28     Packet Scheduling with Tight Bandwidth Distribution Guarantees."
29 
30     See also:
31     http://retis.sssup.it/~fabio/linux/qfq/
32  */
33 
34 /*
35 
36   Virtual time computations.
37 
38   S, F and V are all computed in fixed point arithmetic with
39   FRAC_BITS decimal bits.
40 
41   QFQ_MAX_INDEX is the maximum index allowed for a group. We need
42 	one bit per index.
43   QFQ_MAX_WSHIFT is the maximum power of two supported as a weight.
44 
45   The layout of the bits is as below:
46 
47                    [ MTU_SHIFT ][      FRAC_BITS    ]
48                    [ MAX_INDEX    ][ MIN_SLOT_SHIFT ]
49 				 ^.__grp->index = 0
50 				 *.__grp->slot_shift
51 
52   where MIN_SLOT_SHIFT is derived by difference from the others.
53 
54   The max group index corresponds to Lmax/w_min, where
55   Lmax=1<<MTU_SHIFT, w_min = 1 .
56   From this, and knowing how many groups (MAX_INDEX) we want,
57   we can derive the shift corresponding to each group.
58 
59   Because we often need to compute
60 	F = S + len/w_i  and V = V + len/wsum
61   instead of storing w_i store the value
62 	inv_w = (1<<FRAC_BITS)/w_i
63   so we can do F = S + len * inv_w * wsum.
64   We use W_TOT in the formulas so we can easily move between
65   static and adaptive weight sum.
66 
67   The per-scheduler-instance data contain all the data structures
68   for the scheduler: bitmaps and bucket lists.
69 
70  */
71 
72 /*
73  * Maximum number of consecutive slots occupied by backlogged classes
74  * inside a group.
75  */
76 #define QFQ_MAX_SLOTS	32
77 
78 /*
79  * Shifts used for class<->group mapping.  We allow class weights that are
80  * in the range [1, 2^MAX_WSHIFT], and we try to map each class i to the
81  * group with the smallest index that can support the L_i / r_i configured
82  * for the class.
83  *
84  * grp->index is the index of the group; and grp->slot_shift
85  * is the shift for the corresponding (scaled) sigma_i.
86  */
87 #define QFQ_MAX_INDEX		19
88 #define QFQ_MAX_WSHIFT		16
89 
90 #define	QFQ_MAX_WEIGHT		(1<<QFQ_MAX_WSHIFT)
91 #define QFQ_MAX_WSUM		(2*QFQ_MAX_WEIGHT)
92 
93 #define FRAC_BITS		30	/* fixed point arithmetic */
94 #define ONE_FP			(1UL << FRAC_BITS)
95 #define IWSUM			(ONE_FP/QFQ_MAX_WSUM)
96 
97 #define QFQ_MTU_SHIFT		11
98 #define QFQ_MIN_SLOT_SHIFT	(FRAC_BITS + QFQ_MTU_SHIFT - QFQ_MAX_INDEX)
99 
100 /*
101  * Possible group states.  These values are used as indexes for the bitmaps
102  * array of struct qfq_queue.
103  */
104 enum qfq_state { ER, IR, EB, IB, QFQ_MAX_STATE };
105 
106 struct qfq_group;
107 
108 struct qfq_class {
109 	struct Qdisc_class_common common;
110 
111 	unsigned int refcnt;
112 	unsigned int filter_cnt;
113 
114 	struct gnet_stats_basic_packed bstats;
115 	struct gnet_stats_queue qstats;
116 	struct gnet_stats_rate_est rate_est;
117 	struct Qdisc *qdisc;
118 
119 	struct hlist_node next;	/* Link for the slot list. */
120 	u64 S, F;		/* flow timestamps (exact) */
121 
122 	/* group we belong to. In principle we would need the index,
123 	 * which is log_2(lmax/weight), but we never reference it
124 	 * directly, only the group.
125 	 */
126 	struct qfq_group *grp;
127 
128 	/* these are copied from the flowset. */
129 	u32	inv_w;		/* ONE_FP/weight */
130 	u32	lmax;		/* Max packet size for this flow. */
131 };
132 
133 struct qfq_group {
134 	u64 S, F;			/* group timestamps (approx). */
135 	unsigned int slot_shift;	/* Slot shift. */
136 	unsigned int index;		/* Group index. */
137 	unsigned int front;		/* Index of the front slot. */
138 	unsigned long full_slots;	/* non-empty slots */
139 
140 	/* Array of RR lists of active classes. */
141 	struct hlist_head slots[QFQ_MAX_SLOTS];
142 };
143 
144 struct qfq_sched {
145 	struct tcf_proto *filter_list;
146 	struct Qdisc_class_hash clhash;
147 
148 	u64		V;		/* Precise virtual time. */
149 	u32		wsum;		/* weight sum */
150 
151 	unsigned long bitmaps[QFQ_MAX_STATE];	    /* Group bitmaps. */
152 	struct qfq_group groups[QFQ_MAX_INDEX + 1]; /* The groups. */
153 };
154 
155 static struct qfq_class *qfq_find_class(struct Qdisc *sch, u32 classid)
156 {
157 	struct qfq_sched *q = qdisc_priv(sch);
158 	struct Qdisc_class_common *clc;
159 
160 	clc = qdisc_class_find(&q->clhash, classid);
161 	if (clc == NULL)
162 		return NULL;
163 	return container_of(clc, struct qfq_class, common);
164 }
165 
166 static void qfq_purge_queue(struct qfq_class *cl)
167 {
168 	unsigned int len = cl->qdisc->q.qlen;
169 
170 	qdisc_reset(cl->qdisc);
171 	qdisc_tree_decrease_qlen(cl->qdisc, len);
172 }
173 
174 static const struct nla_policy qfq_policy[TCA_QFQ_MAX + 1] = {
175 	[TCA_QFQ_WEIGHT] = { .type = NLA_U32 },
176 	[TCA_QFQ_LMAX] = { .type = NLA_U32 },
177 };
178 
179 /*
180  * Calculate a flow index, given its weight and maximum packet length.
181  * index = log_2(maxlen/weight) but we need to apply the scaling.
182  * This is used only once at flow creation.
183  */
184 static int qfq_calc_index(u32 inv_w, unsigned int maxlen)
185 {
186 	u64 slot_size = (u64)maxlen * inv_w;
187 	unsigned long size_map;
188 	int index = 0;
189 
190 	size_map = slot_size >> QFQ_MIN_SLOT_SHIFT;
191 	if (!size_map)
192 		goto out;
193 
194 	index = __fls(size_map) + 1;	/* basically a log_2 */
195 	index -= !(slot_size - (1ULL << (index + QFQ_MIN_SLOT_SHIFT - 1)));
196 
197 	if (index < 0)
198 		index = 0;
199 out:
200 	pr_debug("qfq calc_index: W = %lu, L = %u, I = %d\n",
201 		 (unsigned long) ONE_FP/inv_w, maxlen, index);
202 
203 	return index;
204 }
205 
206 static int qfq_change_class(struct Qdisc *sch, u32 classid, u32 parentid,
207 			    struct nlattr **tca, unsigned long *arg)
208 {
209 	struct qfq_sched *q = qdisc_priv(sch);
210 	struct qfq_class *cl = (struct qfq_class *)*arg;
211 	struct nlattr *tb[TCA_QFQ_MAX + 1];
212 	u32 weight, lmax, inv_w;
213 	int i, err;
214 	int delta_w;
215 
216 	if (tca[TCA_OPTIONS] == NULL) {
217 		pr_notice("qfq: no options\n");
218 		return -EINVAL;
219 	}
220 
221 	err = nla_parse_nested(tb, TCA_QFQ_MAX, tca[TCA_OPTIONS], qfq_policy);
222 	if (err < 0)
223 		return err;
224 
225 	if (tb[TCA_QFQ_WEIGHT]) {
226 		weight = nla_get_u32(tb[TCA_QFQ_WEIGHT]);
227 		if (!weight || weight > (1UL << QFQ_MAX_WSHIFT)) {
228 			pr_notice("qfq: invalid weight %u\n", weight);
229 			return -EINVAL;
230 		}
231 	} else
232 		weight = 1;
233 
234 	inv_w = ONE_FP / weight;
235 	weight = ONE_FP / inv_w;
236 	delta_w = weight - (cl ? ONE_FP / cl->inv_w : 0);
237 	if (q->wsum + delta_w > QFQ_MAX_WSUM) {
238 		pr_notice("qfq: total weight out of range (%u + %u)\n",
239 			  delta_w, q->wsum);
240 		return -EINVAL;
241 	}
242 
243 	if (tb[TCA_QFQ_LMAX]) {
244 		lmax = nla_get_u32(tb[TCA_QFQ_LMAX]);
245 		if (!lmax || lmax > (1UL << QFQ_MTU_SHIFT)) {
246 			pr_notice("qfq: invalid max length %u\n", lmax);
247 			return -EINVAL;
248 		}
249 	} else
250 		lmax = 1UL << QFQ_MTU_SHIFT;
251 
252 	if (cl != NULL) {
253 		if (tca[TCA_RATE]) {
254 			err = gen_replace_estimator(&cl->bstats, &cl->rate_est,
255 						    qdisc_root_sleeping_lock(sch),
256 						    tca[TCA_RATE]);
257 			if (err)
258 				return err;
259 		}
260 
261 		if (inv_w != cl->inv_w) {
262 			sch_tree_lock(sch);
263 			q->wsum += delta_w;
264 			cl->inv_w = inv_w;
265 			sch_tree_unlock(sch);
266 		}
267 		return 0;
268 	}
269 
270 	cl = kzalloc(sizeof(struct qfq_class), GFP_KERNEL);
271 	if (cl == NULL)
272 		return -ENOBUFS;
273 
274 	cl->refcnt = 1;
275 	cl->common.classid = classid;
276 	cl->lmax = lmax;
277 	cl->inv_w = inv_w;
278 	i = qfq_calc_index(cl->inv_w, cl->lmax);
279 
280 	cl->grp = &q->groups[i];
281 
282 	cl->qdisc = qdisc_create_dflt(sch->dev_queue,
283 				      &pfifo_qdisc_ops, classid);
284 	if (cl->qdisc == NULL)
285 		cl->qdisc = &noop_qdisc;
286 
287 	if (tca[TCA_RATE]) {
288 		err = gen_new_estimator(&cl->bstats, &cl->rate_est,
289 					qdisc_root_sleeping_lock(sch),
290 					tca[TCA_RATE]);
291 		if (err) {
292 			qdisc_destroy(cl->qdisc);
293 			kfree(cl);
294 			return err;
295 		}
296 	}
297 	q->wsum += weight;
298 
299 	sch_tree_lock(sch);
300 	qdisc_class_hash_insert(&q->clhash, &cl->common);
301 	sch_tree_unlock(sch);
302 
303 	qdisc_class_hash_grow(sch, &q->clhash);
304 
305 	*arg = (unsigned long)cl;
306 	return 0;
307 }
308 
309 static void qfq_destroy_class(struct Qdisc *sch, struct qfq_class *cl)
310 {
311 	struct qfq_sched *q = qdisc_priv(sch);
312 
313 	if (cl->inv_w) {
314 		q->wsum -= ONE_FP / cl->inv_w;
315 		cl->inv_w = 0;
316 	}
317 
318 	gen_kill_estimator(&cl->bstats, &cl->rate_est);
319 	qdisc_destroy(cl->qdisc);
320 	kfree(cl);
321 }
322 
323 static int qfq_delete_class(struct Qdisc *sch, unsigned long arg)
324 {
325 	struct qfq_sched *q = qdisc_priv(sch);
326 	struct qfq_class *cl = (struct qfq_class *)arg;
327 
328 	if (cl->filter_cnt > 0)
329 		return -EBUSY;
330 
331 	sch_tree_lock(sch);
332 
333 	qfq_purge_queue(cl);
334 	qdisc_class_hash_remove(&q->clhash, &cl->common);
335 
336 	BUG_ON(--cl->refcnt == 0);
337 	/*
338 	 * This shouldn't happen: we "hold" one cops->get() when called
339 	 * from tc_ctl_tclass; the destroy method is done from cops->put().
340 	 */
341 
342 	sch_tree_unlock(sch);
343 	return 0;
344 }
345 
346 static unsigned long qfq_get_class(struct Qdisc *sch, u32 classid)
347 {
348 	struct qfq_class *cl = qfq_find_class(sch, classid);
349 
350 	if (cl != NULL)
351 		cl->refcnt++;
352 
353 	return (unsigned long)cl;
354 }
355 
356 static void qfq_put_class(struct Qdisc *sch, unsigned long arg)
357 {
358 	struct qfq_class *cl = (struct qfq_class *)arg;
359 
360 	if (--cl->refcnt == 0)
361 		qfq_destroy_class(sch, cl);
362 }
363 
364 static struct tcf_proto **qfq_tcf_chain(struct Qdisc *sch, unsigned long cl)
365 {
366 	struct qfq_sched *q = qdisc_priv(sch);
367 
368 	if (cl)
369 		return NULL;
370 
371 	return &q->filter_list;
372 }
373 
374 static unsigned long qfq_bind_tcf(struct Qdisc *sch, unsigned long parent,
375 				  u32 classid)
376 {
377 	struct qfq_class *cl = qfq_find_class(sch, classid);
378 
379 	if (cl != NULL)
380 		cl->filter_cnt++;
381 
382 	return (unsigned long)cl;
383 }
384 
385 static void qfq_unbind_tcf(struct Qdisc *sch, unsigned long arg)
386 {
387 	struct qfq_class *cl = (struct qfq_class *)arg;
388 
389 	cl->filter_cnt--;
390 }
391 
392 static int qfq_graft_class(struct Qdisc *sch, unsigned long arg,
393 			   struct Qdisc *new, struct Qdisc **old)
394 {
395 	struct qfq_class *cl = (struct qfq_class *)arg;
396 
397 	if (new == NULL) {
398 		new = qdisc_create_dflt(sch->dev_queue,
399 					&pfifo_qdisc_ops, cl->common.classid);
400 		if (new == NULL)
401 			new = &noop_qdisc;
402 	}
403 
404 	sch_tree_lock(sch);
405 	qfq_purge_queue(cl);
406 	*old = cl->qdisc;
407 	cl->qdisc = new;
408 	sch_tree_unlock(sch);
409 	return 0;
410 }
411 
412 static struct Qdisc *qfq_class_leaf(struct Qdisc *sch, unsigned long arg)
413 {
414 	struct qfq_class *cl = (struct qfq_class *)arg;
415 
416 	return cl->qdisc;
417 }
418 
419 static int qfq_dump_class(struct Qdisc *sch, unsigned long arg,
420 			  struct sk_buff *skb, struct tcmsg *tcm)
421 {
422 	struct qfq_class *cl = (struct qfq_class *)arg;
423 	struct nlattr *nest;
424 
425 	tcm->tcm_parent	= TC_H_ROOT;
426 	tcm->tcm_handle	= cl->common.classid;
427 	tcm->tcm_info	= cl->qdisc->handle;
428 
429 	nest = nla_nest_start(skb, TCA_OPTIONS);
430 	if (nest == NULL)
431 		goto nla_put_failure;
432 	if (nla_put_u32(skb, TCA_QFQ_WEIGHT, ONE_FP/cl->inv_w) ||
433 	    nla_put_u32(skb, TCA_QFQ_LMAX, cl->lmax))
434 		goto nla_put_failure;
435 	return nla_nest_end(skb, nest);
436 
437 nla_put_failure:
438 	nla_nest_cancel(skb, nest);
439 	return -EMSGSIZE;
440 }
441 
442 static int qfq_dump_class_stats(struct Qdisc *sch, unsigned long arg,
443 				struct gnet_dump *d)
444 {
445 	struct qfq_class *cl = (struct qfq_class *)arg;
446 	struct tc_qfq_stats xstats;
447 
448 	memset(&xstats, 0, sizeof(xstats));
449 	cl->qdisc->qstats.qlen = cl->qdisc->q.qlen;
450 
451 	xstats.weight = ONE_FP/cl->inv_w;
452 	xstats.lmax = cl->lmax;
453 
454 	if (gnet_stats_copy_basic(d, &cl->bstats) < 0 ||
455 	    gnet_stats_copy_rate_est(d, &cl->bstats, &cl->rate_est) < 0 ||
456 	    gnet_stats_copy_queue(d, &cl->qdisc->qstats) < 0)
457 		return -1;
458 
459 	return gnet_stats_copy_app(d, &xstats, sizeof(xstats));
460 }
461 
462 static void qfq_walk(struct Qdisc *sch, struct qdisc_walker *arg)
463 {
464 	struct qfq_sched *q = qdisc_priv(sch);
465 	struct qfq_class *cl;
466 	struct hlist_node *n;
467 	unsigned int i;
468 
469 	if (arg->stop)
470 		return;
471 
472 	for (i = 0; i < q->clhash.hashsize; i++) {
473 		hlist_for_each_entry(cl, n, &q->clhash.hash[i], common.hnode) {
474 			if (arg->count < arg->skip) {
475 				arg->count++;
476 				continue;
477 			}
478 			if (arg->fn(sch, (unsigned long)cl, arg) < 0) {
479 				arg->stop = 1;
480 				return;
481 			}
482 			arg->count++;
483 		}
484 	}
485 }
486 
487 static struct qfq_class *qfq_classify(struct sk_buff *skb, struct Qdisc *sch,
488 				      int *qerr)
489 {
490 	struct qfq_sched *q = qdisc_priv(sch);
491 	struct qfq_class *cl;
492 	struct tcf_result res;
493 	int result;
494 
495 	if (TC_H_MAJ(skb->priority ^ sch->handle) == 0) {
496 		pr_debug("qfq_classify: found %d\n", skb->priority);
497 		cl = qfq_find_class(sch, skb->priority);
498 		if (cl != NULL)
499 			return cl;
500 	}
501 
502 	*qerr = NET_XMIT_SUCCESS | __NET_XMIT_BYPASS;
503 	result = tc_classify(skb, q->filter_list, &res);
504 	if (result >= 0) {
505 #ifdef CONFIG_NET_CLS_ACT
506 		switch (result) {
507 		case TC_ACT_QUEUED:
508 		case TC_ACT_STOLEN:
509 			*qerr = NET_XMIT_SUCCESS | __NET_XMIT_STOLEN;
510 		case TC_ACT_SHOT:
511 			return NULL;
512 		}
513 #endif
514 		cl = (struct qfq_class *)res.class;
515 		if (cl == NULL)
516 			cl = qfq_find_class(sch, res.classid);
517 		return cl;
518 	}
519 
520 	return NULL;
521 }
522 
523 /* Generic comparison function, handling wraparound. */
524 static inline int qfq_gt(u64 a, u64 b)
525 {
526 	return (s64)(a - b) > 0;
527 }
528 
529 /* Round a precise timestamp to its slotted value. */
530 static inline u64 qfq_round_down(u64 ts, unsigned int shift)
531 {
532 	return ts & ~((1ULL << shift) - 1);
533 }
534 
535 /* return the pointer to the group with lowest index in the bitmap */
536 static inline struct qfq_group *qfq_ffs(struct qfq_sched *q,
537 					unsigned long bitmap)
538 {
539 	int index = __ffs(bitmap);
540 	return &q->groups[index];
541 }
542 /* Calculate a mask to mimic what would be ffs_from(). */
543 static inline unsigned long mask_from(unsigned long bitmap, int from)
544 {
545 	return bitmap & ~((1UL << from) - 1);
546 }
547 
548 /*
549  * The state computation relies on ER=0, IR=1, EB=2, IB=3
550  * First compute eligibility comparing grp->S, q->V,
551  * then check if someone is blocking us and possibly add EB
552  */
553 static int qfq_calc_state(struct qfq_sched *q, const struct qfq_group *grp)
554 {
555 	/* if S > V we are not eligible */
556 	unsigned int state = qfq_gt(grp->S, q->V);
557 	unsigned long mask = mask_from(q->bitmaps[ER], grp->index);
558 	struct qfq_group *next;
559 
560 	if (mask) {
561 		next = qfq_ffs(q, mask);
562 		if (qfq_gt(grp->F, next->F))
563 			state |= EB;
564 	}
565 
566 	return state;
567 }
568 
569 
570 /*
571  * In principle
572  *	q->bitmaps[dst] |= q->bitmaps[src] & mask;
573  *	q->bitmaps[src] &= ~mask;
574  * but we should make sure that src != dst
575  */
576 static inline void qfq_move_groups(struct qfq_sched *q, unsigned long mask,
577 				   int src, int dst)
578 {
579 	q->bitmaps[dst] |= q->bitmaps[src] & mask;
580 	q->bitmaps[src] &= ~mask;
581 }
582 
583 static void qfq_unblock_groups(struct qfq_sched *q, int index, u64 old_F)
584 {
585 	unsigned long mask = mask_from(q->bitmaps[ER], index + 1);
586 	struct qfq_group *next;
587 
588 	if (mask) {
589 		next = qfq_ffs(q, mask);
590 		if (!qfq_gt(next->F, old_F))
591 			return;
592 	}
593 
594 	mask = (1UL << index) - 1;
595 	qfq_move_groups(q, mask, EB, ER);
596 	qfq_move_groups(q, mask, IB, IR);
597 }
598 
599 /*
600  * perhaps
601  *
602 	old_V ^= q->V;
603 	old_V >>= QFQ_MIN_SLOT_SHIFT;
604 	if (old_V) {
605 		...
606 	}
607  *
608  */
609 static void qfq_make_eligible(struct qfq_sched *q, u64 old_V)
610 {
611 	unsigned long vslot = q->V >> QFQ_MIN_SLOT_SHIFT;
612 	unsigned long old_vslot = old_V >> QFQ_MIN_SLOT_SHIFT;
613 
614 	if (vslot != old_vslot) {
615 		unsigned long mask = (1UL << fls(vslot ^ old_vslot)) - 1;
616 		qfq_move_groups(q, mask, IR, ER);
617 		qfq_move_groups(q, mask, IB, EB);
618 	}
619 }
620 
621 
622 /*
623  * XXX we should make sure that slot becomes less than 32.
624  * This is guaranteed by the input values.
625  * roundedS is always cl->S rounded on grp->slot_shift bits.
626  */
627 static void qfq_slot_insert(struct qfq_group *grp, struct qfq_class *cl,
628 			    u64 roundedS)
629 {
630 	u64 slot = (roundedS - grp->S) >> grp->slot_shift;
631 	unsigned int i = (grp->front + slot) % QFQ_MAX_SLOTS;
632 
633 	hlist_add_head(&cl->next, &grp->slots[i]);
634 	__set_bit(slot, &grp->full_slots);
635 }
636 
637 /* Maybe introduce hlist_first_entry?? */
638 static struct qfq_class *qfq_slot_head(struct qfq_group *grp)
639 {
640 	return hlist_entry(grp->slots[grp->front].first,
641 			   struct qfq_class, next);
642 }
643 
644 /*
645  * remove the entry from the slot
646  */
647 static void qfq_front_slot_remove(struct qfq_group *grp)
648 {
649 	struct qfq_class *cl = qfq_slot_head(grp);
650 
651 	BUG_ON(!cl);
652 	hlist_del(&cl->next);
653 	if (hlist_empty(&grp->slots[grp->front]))
654 		__clear_bit(0, &grp->full_slots);
655 }
656 
657 /*
658  * Returns the first full queue in a group. As a side effect,
659  * adjust the bucket list so the first non-empty bucket is at
660  * position 0 in full_slots.
661  */
662 static struct qfq_class *qfq_slot_scan(struct qfq_group *grp)
663 {
664 	unsigned int i;
665 
666 	pr_debug("qfq slot_scan: grp %u full %#lx\n",
667 		 grp->index, grp->full_slots);
668 
669 	if (grp->full_slots == 0)
670 		return NULL;
671 
672 	i = __ffs(grp->full_slots);  /* zero based */
673 	if (i > 0) {
674 		grp->front = (grp->front + i) % QFQ_MAX_SLOTS;
675 		grp->full_slots >>= i;
676 	}
677 
678 	return qfq_slot_head(grp);
679 }
680 
681 /*
682  * adjust the bucket list. When the start time of a group decreases,
683  * we move the index down (modulo QFQ_MAX_SLOTS) so we don't need to
684  * move the objects. The mask of occupied slots must be shifted
685  * because we use ffs() to find the first non-empty slot.
686  * This covers decreases in the group's start time, but what about
687  * increases of the start time ?
688  * Here too we should make sure that i is less than 32
689  */
690 static void qfq_slot_rotate(struct qfq_group *grp, u64 roundedS)
691 {
692 	unsigned int i = (grp->S - roundedS) >> grp->slot_shift;
693 
694 	grp->full_slots <<= i;
695 	grp->front = (grp->front - i) % QFQ_MAX_SLOTS;
696 }
697 
698 static void qfq_update_eligible(struct qfq_sched *q, u64 old_V)
699 {
700 	struct qfq_group *grp;
701 	unsigned long ineligible;
702 
703 	ineligible = q->bitmaps[IR] | q->bitmaps[IB];
704 	if (ineligible) {
705 		if (!q->bitmaps[ER]) {
706 			grp = qfq_ffs(q, ineligible);
707 			if (qfq_gt(grp->S, q->V))
708 				q->V = grp->S;
709 		}
710 		qfq_make_eligible(q, old_V);
711 	}
712 }
713 
714 /* What is length of next packet in queue (0 if queue is empty) */
715 static unsigned int qdisc_peek_len(struct Qdisc *sch)
716 {
717 	struct sk_buff *skb;
718 
719 	skb = sch->ops->peek(sch);
720 	return skb ? qdisc_pkt_len(skb) : 0;
721 }
722 
723 /*
724  * Updates the class, returns true if also the group needs to be updated.
725  */
726 static bool qfq_update_class(struct qfq_group *grp, struct qfq_class *cl)
727 {
728 	unsigned int len = qdisc_peek_len(cl->qdisc);
729 
730 	cl->S = cl->F;
731 	if (!len)
732 		qfq_front_slot_remove(grp);	/* queue is empty */
733 	else {
734 		u64 roundedS;
735 
736 		cl->F = cl->S + (u64)len * cl->inv_w;
737 		roundedS = qfq_round_down(cl->S, grp->slot_shift);
738 		if (roundedS == grp->S)
739 			return false;
740 
741 		qfq_front_slot_remove(grp);
742 		qfq_slot_insert(grp, cl, roundedS);
743 	}
744 
745 	return true;
746 }
747 
748 static struct sk_buff *qfq_dequeue(struct Qdisc *sch)
749 {
750 	struct qfq_sched *q = qdisc_priv(sch);
751 	struct qfq_group *grp;
752 	struct qfq_class *cl;
753 	struct sk_buff *skb;
754 	unsigned int len;
755 	u64 old_V;
756 
757 	if (!q->bitmaps[ER])
758 		return NULL;
759 
760 	grp = qfq_ffs(q, q->bitmaps[ER]);
761 
762 	cl = qfq_slot_head(grp);
763 	skb = qdisc_dequeue_peeked(cl->qdisc);
764 	if (!skb) {
765 		WARN_ONCE(1, "qfq_dequeue: non-workconserving leaf\n");
766 		return NULL;
767 	}
768 
769 	sch->q.qlen--;
770 	qdisc_bstats_update(sch, skb);
771 
772 	old_V = q->V;
773 	len = qdisc_pkt_len(skb);
774 	q->V += (u64)len * IWSUM;
775 	pr_debug("qfq dequeue: len %u F %lld now %lld\n",
776 		 len, (unsigned long long) cl->F, (unsigned long long) q->V);
777 
778 	if (qfq_update_class(grp, cl)) {
779 		u64 old_F = grp->F;
780 
781 		cl = qfq_slot_scan(grp);
782 		if (!cl)
783 			__clear_bit(grp->index, &q->bitmaps[ER]);
784 		else {
785 			u64 roundedS = qfq_round_down(cl->S, grp->slot_shift);
786 			unsigned int s;
787 
788 			if (grp->S == roundedS)
789 				goto skip_unblock;
790 			grp->S = roundedS;
791 			grp->F = roundedS + (2ULL << grp->slot_shift);
792 			__clear_bit(grp->index, &q->bitmaps[ER]);
793 			s = qfq_calc_state(q, grp);
794 			__set_bit(grp->index, &q->bitmaps[s]);
795 		}
796 
797 		qfq_unblock_groups(q, grp->index, old_F);
798 	}
799 
800 skip_unblock:
801 	qfq_update_eligible(q, old_V);
802 
803 	return skb;
804 }
805 
806 /*
807  * Assign a reasonable start time for a new flow k in group i.
808  * Admissible values for \hat(F) are multiples of \sigma_i
809  * no greater than V+\sigma_i . Larger values mean that
810  * we had a wraparound so we consider the timestamp to be stale.
811  *
812  * If F is not stale and F >= V then we set S = F.
813  * Otherwise we should assign S = V, but this may violate
814  * the ordering in ER. So, if we have groups in ER, set S to
815  * the F_j of the first group j which would be blocking us.
816  * We are guaranteed not to move S backward because
817  * otherwise our group i would still be blocked.
818  */
819 static void qfq_update_start(struct qfq_sched *q, struct qfq_class *cl)
820 {
821 	unsigned long mask;
822 	u64 limit, roundedF;
823 	int slot_shift = cl->grp->slot_shift;
824 
825 	roundedF = qfq_round_down(cl->F, slot_shift);
826 	limit = qfq_round_down(q->V, slot_shift) + (1ULL << slot_shift);
827 
828 	if (!qfq_gt(cl->F, q->V) || qfq_gt(roundedF, limit)) {
829 		/* timestamp was stale */
830 		mask = mask_from(q->bitmaps[ER], cl->grp->index);
831 		if (mask) {
832 			struct qfq_group *next = qfq_ffs(q, mask);
833 			if (qfq_gt(roundedF, next->F)) {
834 				cl->S = next->F;
835 				return;
836 			}
837 		}
838 		cl->S = q->V;
839 	} else  /* timestamp is not stale */
840 		cl->S = cl->F;
841 }
842 
843 static int qfq_enqueue(struct sk_buff *skb, struct Qdisc *sch)
844 {
845 	struct qfq_sched *q = qdisc_priv(sch);
846 	struct qfq_group *grp;
847 	struct qfq_class *cl;
848 	int err;
849 	u64 roundedS;
850 	int s;
851 
852 	cl = qfq_classify(skb, sch, &err);
853 	if (cl == NULL) {
854 		if (err & __NET_XMIT_BYPASS)
855 			sch->qstats.drops++;
856 		kfree_skb(skb);
857 		return err;
858 	}
859 	pr_debug("qfq_enqueue: cl = %x\n", cl->common.classid);
860 
861 	err = qdisc_enqueue(skb, cl->qdisc);
862 	if (unlikely(err != NET_XMIT_SUCCESS)) {
863 		pr_debug("qfq_enqueue: enqueue failed %d\n", err);
864 		if (net_xmit_drop_count(err)) {
865 			cl->qstats.drops++;
866 			sch->qstats.drops++;
867 		}
868 		return err;
869 	}
870 
871 	bstats_update(&cl->bstats, skb);
872 	++sch->q.qlen;
873 
874 	/* If the new skb is not the head of queue, then done here. */
875 	if (cl->qdisc->q.qlen != 1)
876 		return err;
877 
878 	/* If reach this point, queue q was idle */
879 	grp = cl->grp;
880 	qfq_update_start(q, cl);
881 
882 	/* compute new finish time and rounded start. */
883 	cl->F = cl->S + (u64)qdisc_pkt_len(skb) * cl->inv_w;
884 	roundedS = qfq_round_down(cl->S, grp->slot_shift);
885 
886 	/*
887 	 * insert cl in the correct bucket.
888 	 * If cl->S >= grp->S we don't need to adjust the
889 	 * bucket list and simply go to the insertion phase.
890 	 * Otherwise grp->S is decreasing, we must make room
891 	 * in the bucket list, and also recompute the group state.
892 	 * Finally, if there were no flows in this group and nobody
893 	 * was in ER make sure to adjust V.
894 	 */
895 	if (grp->full_slots) {
896 		if (!qfq_gt(grp->S, cl->S))
897 			goto skip_update;
898 
899 		/* create a slot for this cl->S */
900 		qfq_slot_rotate(grp, roundedS);
901 		/* group was surely ineligible, remove */
902 		__clear_bit(grp->index, &q->bitmaps[IR]);
903 		__clear_bit(grp->index, &q->bitmaps[IB]);
904 	} else if (!q->bitmaps[ER] && qfq_gt(roundedS, q->V))
905 		q->V = roundedS;
906 
907 	grp->S = roundedS;
908 	grp->F = roundedS + (2ULL << grp->slot_shift);
909 	s = qfq_calc_state(q, grp);
910 	__set_bit(grp->index, &q->bitmaps[s]);
911 
912 	pr_debug("qfq enqueue: new state %d %#lx S %lld F %lld V %lld\n",
913 		 s, q->bitmaps[s],
914 		 (unsigned long long) cl->S,
915 		 (unsigned long long) cl->F,
916 		 (unsigned long long) q->V);
917 
918 skip_update:
919 	qfq_slot_insert(grp, cl, roundedS);
920 
921 	return err;
922 }
923 
924 
925 static void qfq_slot_remove(struct qfq_sched *q, struct qfq_group *grp,
926 			    struct qfq_class *cl)
927 {
928 	unsigned int i, offset;
929 	u64 roundedS;
930 
931 	roundedS = qfq_round_down(cl->S, grp->slot_shift);
932 	offset = (roundedS - grp->S) >> grp->slot_shift;
933 	i = (grp->front + offset) % QFQ_MAX_SLOTS;
934 
935 	hlist_del(&cl->next);
936 	if (hlist_empty(&grp->slots[i]))
937 		__clear_bit(offset, &grp->full_slots);
938 }
939 
940 /*
941  * called to forcibly destroy a queue.
942  * If the queue is not in the front bucket, or if it has
943  * other queues in the front bucket, we can simply remove
944  * the queue with no other side effects.
945  * Otherwise we must propagate the event up.
946  */
947 static void qfq_deactivate_class(struct qfq_sched *q, struct qfq_class *cl)
948 {
949 	struct qfq_group *grp = cl->grp;
950 	unsigned long mask;
951 	u64 roundedS;
952 	int s;
953 
954 	cl->F = cl->S;
955 	qfq_slot_remove(q, grp, cl);
956 
957 	if (!grp->full_slots) {
958 		__clear_bit(grp->index, &q->bitmaps[IR]);
959 		__clear_bit(grp->index, &q->bitmaps[EB]);
960 		__clear_bit(grp->index, &q->bitmaps[IB]);
961 
962 		if (test_bit(grp->index, &q->bitmaps[ER]) &&
963 		    !(q->bitmaps[ER] & ~((1UL << grp->index) - 1))) {
964 			mask = q->bitmaps[ER] & ((1UL << grp->index) - 1);
965 			if (mask)
966 				mask = ~((1UL << __fls(mask)) - 1);
967 			else
968 				mask = ~0UL;
969 			qfq_move_groups(q, mask, EB, ER);
970 			qfq_move_groups(q, mask, IB, IR);
971 		}
972 		__clear_bit(grp->index, &q->bitmaps[ER]);
973 	} else if (hlist_empty(&grp->slots[grp->front])) {
974 		cl = qfq_slot_scan(grp);
975 		roundedS = qfq_round_down(cl->S, grp->slot_shift);
976 		if (grp->S != roundedS) {
977 			__clear_bit(grp->index, &q->bitmaps[ER]);
978 			__clear_bit(grp->index, &q->bitmaps[IR]);
979 			__clear_bit(grp->index, &q->bitmaps[EB]);
980 			__clear_bit(grp->index, &q->bitmaps[IB]);
981 			grp->S = roundedS;
982 			grp->F = roundedS + (2ULL << grp->slot_shift);
983 			s = qfq_calc_state(q, grp);
984 			__set_bit(grp->index, &q->bitmaps[s]);
985 		}
986 	}
987 
988 	qfq_update_eligible(q, q->V);
989 }
990 
991 static void qfq_qlen_notify(struct Qdisc *sch, unsigned long arg)
992 {
993 	struct qfq_sched *q = qdisc_priv(sch);
994 	struct qfq_class *cl = (struct qfq_class *)arg;
995 
996 	if (cl->qdisc->q.qlen == 0)
997 		qfq_deactivate_class(q, cl);
998 }
999 
1000 static unsigned int qfq_drop(struct Qdisc *sch)
1001 {
1002 	struct qfq_sched *q = qdisc_priv(sch);
1003 	struct qfq_group *grp;
1004 	unsigned int i, j, len;
1005 
1006 	for (i = 0; i <= QFQ_MAX_INDEX; i++) {
1007 		grp = &q->groups[i];
1008 		for (j = 0; j < QFQ_MAX_SLOTS; j++) {
1009 			struct qfq_class *cl;
1010 			struct hlist_node *n;
1011 
1012 			hlist_for_each_entry(cl, n, &grp->slots[j], next) {
1013 
1014 				if (!cl->qdisc->ops->drop)
1015 					continue;
1016 
1017 				len = cl->qdisc->ops->drop(cl->qdisc);
1018 				if (len > 0) {
1019 					sch->q.qlen--;
1020 					if (!cl->qdisc->q.qlen)
1021 						qfq_deactivate_class(q, cl);
1022 
1023 					return len;
1024 				}
1025 			}
1026 		}
1027 	}
1028 
1029 	return 0;
1030 }
1031 
1032 static int qfq_init_qdisc(struct Qdisc *sch, struct nlattr *opt)
1033 {
1034 	struct qfq_sched *q = qdisc_priv(sch);
1035 	struct qfq_group *grp;
1036 	int i, j, err;
1037 
1038 	err = qdisc_class_hash_init(&q->clhash);
1039 	if (err < 0)
1040 		return err;
1041 
1042 	for (i = 0; i <= QFQ_MAX_INDEX; i++) {
1043 		grp = &q->groups[i];
1044 		grp->index = i;
1045 		grp->slot_shift = QFQ_MTU_SHIFT + FRAC_BITS
1046 				   - (QFQ_MAX_INDEX - i);
1047 		for (j = 0; j < QFQ_MAX_SLOTS; j++)
1048 			INIT_HLIST_HEAD(&grp->slots[j]);
1049 	}
1050 
1051 	return 0;
1052 }
1053 
1054 static void qfq_reset_qdisc(struct Qdisc *sch)
1055 {
1056 	struct qfq_sched *q = qdisc_priv(sch);
1057 	struct qfq_group *grp;
1058 	struct qfq_class *cl;
1059 	struct hlist_node *n, *tmp;
1060 	unsigned int i, j;
1061 
1062 	for (i = 0; i <= QFQ_MAX_INDEX; i++) {
1063 		grp = &q->groups[i];
1064 		for (j = 0; j < QFQ_MAX_SLOTS; j++) {
1065 			hlist_for_each_entry_safe(cl, n, tmp,
1066 						  &grp->slots[j], next) {
1067 				qfq_deactivate_class(q, cl);
1068 			}
1069 		}
1070 	}
1071 
1072 	for (i = 0; i < q->clhash.hashsize; i++) {
1073 		hlist_for_each_entry(cl, n, &q->clhash.hash[i], common.hnode)
1074 			qdisc_reset(cl->qdisc);
1075 	}
1076 	sch->q.qlen = 0;
1077 }
1078 
1079 static void qfq_destroy_qdisc(struct Qdisc *sch)
1080 {
1081 	struct qfq_sched *q = qdisc_priv(sch);
1082 	struct qfq_class *cl;
1083 	struct hlist_node *n, *next;
1084 	unsigned int i;
1085 
1086 	tcf_destroy_chain(&q->filter_list);
1087 
1088 	for (i = 0; i < q->clhash.hashsize; i++) {
1089 		hlist_for_each_entry_safe(cl, n, next, &q->clhash.hash[i],
1090 					  common.hnode) {
1091 			qfq_destroy_class(sch, cl);
1092 		}
1093 	}
1094 	qdisc_class_hash_destroy(&q->clhash);
1095 }
1096 
1097 static const struct Qdisc_class_ops qfq_class_ops = {
1098 	.change		= qfq_change_class,
1099 	.delete		= qfq_delete_class,
1100 	.get		= qfq_get_class,
1101 	.put		= qfq_put_class,
1102 	.tcf_chain	= qfq_tcf_chain,
1103 	.bind_tcf	= qfq_bind_tcf,
1104 	.unbind_tcf	= qfq_unbind_tcf,
1105 	.graft		= qfq_graft_class,
1106 	.leaf		= qfq_class_leaf,
1107 	.qlen_notify	= qfq_qlen_notify,
1108 	.dump		= qfq_dump_class,
1109 	.dump_stats	= qfq_dump_class_stats,
1110 	.walk		= qfq_walk,
1111 };
1112 
1113 static struct Qdisc_ops qfq_qdisc_ops __read_mostly = {
1114 	.cl_ops		= &qfq_class_ops,
1115 	.id		= "qfq",
1116 	.priv_size	= sizeof(struct qfq_sched),
1117 	.enqueue	= qfq_enqueue,
1118 	.dequeue	= qfq_dequeue,
1119 	.peek		= qdisc_peek_dequeued,
1120 	.drop		= qfq_drop,
1121 	.init		= qfq_init_qdisc,
1122 	.reset		= qfq_reset_qdisc,
1123 	.destroy	= qfq_destroy_qdisc,
1124 	.owner		= THIS_MODULE,
1125 };
1126 
1127 static int __init qfq_init(void)
1128 {
1129 	return register_qdisc(&qfq_qdisc_ops);
1130 }
1131 
1132 static void __exit qfq_exit(void)
1133 {
1134 	unregister_qdisc(&qfq_qdisc_ops);
1135 }
1136 
1137 module_init(qfq_init);
1138 module_exit(qfq_exit);
1139 MODULE_LICENSE("GPL");
1140