xref: /freebsd/sys/netpfil/ipfw/dn_sched_qfq.c (revision 06c3fb27)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2010 Fabio Checconi, Luigi Rizzo, Paolo Valente
5  * All rights reserved
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /*
30  */
31 
32 #ifdef _KERNEL
33 #include <sys/malloc.h>
34 #include <sys/socket.h>
35 #include <sys/socketvar.h>
36 #include <sys/kernel.h>
37 #include <sys/lock.h>
38 #include <sys/mbuf.h>
39 #include <sys/module.h>
40 #include <sys/rwlock.h>
41 #include <net/if.h>	/* IFNAMSIZ */
42 #include <netinet/in.h>
43 #include <netinet/ip_var.h>		/* ipfw_rule_ref */
44 #include <netinet/ip_fw.h>	/* flow_id */
45 #include <netinet/ip_dummynet.h>
46 #include <netpfil/ipfw/ip_fw_private.h>
47 #include <netpfil/ipfw/dn_heap.h>
48 #include <netpfil/ipfw/ip_dn_private.h>
49 #ifdef NEW_AQM
50 #include <netpfil/ipfw/dn_aqm.h>
51 #endif
52 #include <netpfil/ipfw/dn_sched.h>
53 #else
54 #include <dn_test.h>
55 #endif
56 
57 #ifdef QFQ_DEBUG
58 #define _P64	unsigned long long	/* cast for printing uint64_t */
59 struct qfq_sched;
60 static void dump_sched(struct qfq_sched *q, const char *msg);
61 #define	NO(x)	x
62 #else
63 #define NO(x)
64 #endif
65 #define DN_SCHED_QFQ	4 // XXX Where?
66 typedef	unsigned long	bitmap;
67 
68 /*
69  * bitmaps ops are critical. Some linux versions have __fls
70  * and the bitmap ops. Some machines have ffs
71  * NOTE: fls() returns 1 for the least significant bit,
72  *       __fls() returns 0 for the same case.
73  * We use the base-0 version __fls() to match the description in
74  * the ToN QFQ paper
75  */
76 #if defined(_WIN32) || (defined(__MIPSEL__) && defined(LINUX_24))
77 int fls(unsigned int n)
78 {
79 	int i = 0;
80 	for (i = 0; n > 0; n >>= 1, i++)
81 		;
82 	return i;
83 }
84 #endif
85 
86 #if !defined(_KERNEL) || defined( __FreeBSD__ ) || defined(_WIN32) || (defined(__MIPSEL__) && defined(LINUX_24))
87 static inline unsigned long __fls(unsigned long word)
88 {
89 	return fls(word) - 1;
90 }
91 #endif
92 
93 #if !defined(_KERNEL) || !defined(__linux__)
94 #ifdef QFQ_DEBUG
95 static int test_bit(int ix, bitmap *p)
96 {
97 	if (ix < 0 || ix > 31)
98 		D("bad index %d", ix);
99 	return *p & (1<<ix);
100 }
101 static void __set_bit(int ix, bitmap *p)
102 {
103 	if (ix < 0 || ix > 31)
104 		D("bad index %d", ix);
105 	*p |= (1<<ix);
106 }
107 static void __clear_bit(int ix, bitmap *p)
108 {
109 	if (ix < 0 || ix > 31)
110 		D("bad index %d", ix);
111 	*p &= ~(1<<ix);
112 }
113 #else /* !QFQ_DEBUG */
114 /* XXX do we have fast version, or leave it to the compiler ? */
115 #define test_bit(ix, pData)	((*pData) & (1<<(ix)))
116 #define __set_bit(ix, pData)	(*pData) |= (1<<(ix))
117 #define __clear_bit(ix, pData)	(*pData) &= ~(1<<(ix))
118 #endif /* !QFQ_DEBUG */
119 #endif /* !__linux__ */
120 
121 #ifdef __MIPSEL__
122 #define __clear_bit(ix, pData)	(*pData) &= ~(1<<(ix))
123 #endif
124 
125 /*-------------------------------------------*/
126 /*
127 
128 Virtual time computations.
129 
130 S, F and V are all computed in fixed point arithmetic with
131 FRAC_BITS decimal bits.
132 
133    QFQ_MAX_INDEX is the maximum index allowed for a group. We need
134   	one bit per index.
135    QFQ_MAX_WSHIFT is the maximum power of two supported as a weight.
136    The layout of the bits is as below:
137 
138                    [ MTU_SHIFT ][      FRAC_BITS    ]
139                    [ MAX_INDEX    ][ MIN_SLOT_SHIFT ]
140   				 ^.__grp->index = 0
141   				 *.__grp->slot_shift
142 
143    where MIN_SLOT_SHIFT is derived by difference from the others.
144 
145 The max group index corresponds to Lmax/w_min, where
146 Lmax=1<<MTU_SHIFT, w_min = 1 .
147 From this, and knowing how many groups (MAX_INDEX) we want,
148 we can derive the shift corresponding to each group.
149 
150 Because we often need to compute
151 	F = S + len/w_i  and V = V + len/wsum
152 instead of storing w_i store the value
153 	inv_w = (1<<FRAC_BITS)/w_i
154 so we can do F = S + len * inv_w * wsum.
155 We use W_TOT in the formulas so we can easily move between
156 static and adaptive weight sum.
157 
158 The per-scheduler-instance data contain all the data structures
159 for the scheduler: bitmaps and bucket lists.
160 
161  */
162 /*
163  * Maximum number of consecutive slots occupied by backlogged classes
164  * inside a group. This is approx lmax/lmin + 5.
165  * XXX check because it poses constraints on MAX_INDEX
166  */
167 #define QFQ_MAX_SLOTS	32
168 /*
169  * Shifts used for class<->group mapping. Class weights are
170  * in the range [1, QFQ_MAX_WEIGHT], we to map each class i to the
171  * group with the smallest index that can support the L_i / r_i
172  * configured for the class.
173  *
174  * grp->index is the index of the group; and grp->slot_shift
175  * is the shift for the corresponding (scaled) sigma_i.
176  *
177  * When computing the group index, we do (len<<FP_SHIFT)/weight,
178  * then compute an FLS (which is like a log2()), and if the result
179  * is below the MAX_INDEX region we use 0 (which is the same as
180  * using a larger len).
181  */
182 #define QFQ_MAX_INDEX		19
183 #define QFQ_MAX_WSHIFT		16	/* log2(max_weight) */
184 
185 #define	QFQ_MAX_WEIGHT		(1<<QFQ_MAX_WSHIFT)
186 #define QFQ_MAX_WSUM		(2*QFQ_MAX_WEIGHT)
187 
188 #define FRAC_BITS		30	/* fixed point arithmetic */
189 #define ONE_FP			(1UL << FRAC_BITS)
190 
191 #define QFQ_MTU_SHIFT		11	/* log2(max_len) */
192 #define QFQ_MIN_SLOT_SHIFT	(FRAC_BITS + QFQ_MTU_SHIFT - QFQ_MAX_INDEX)
193 
194 /*
195  * Possible group states, also indexes for the bitmaps array in
196  * struct qfq_queue. We rely on ER, IR, EB, IB being numbered 0..3
197  */
198 enum qfq_state { ER, IR, EB, IB, QFQ_MAX_STATE };
199 
200 struct qfq_group;
201 /*
202  * additional queue info. Some of this info should come from
203  * the flowset, we copy them here for faster processing.
204  * This is an overlay of the struct dn_queue
205  */
206 struct qfq_class {
207 	struct dn_queue _q;
208 	uint64_t S, F;		/* flow timestamps (exact) */
209 	struct qfq_class *next; /* Link for the slot list. */
210 
211 	/* group we belong to. In principle we would need the index,
212 	 * which is log_2(lmax/weight), but we never reference it
213 	 * directly, only the group.
214 	 */
215 	struct qfq_group *grp;
216 
217 	/* these are copied from the flowset. */
218 	uint32_t	inv_w;	/* ONE_FP/weight */
219 	uint32_t 	lmax;	/* Max packet size for this flow. */
220 };
221 
222 /* Group descriptor, see the paper for details.
223  * Basically this contains the bucket lists
224  */
225 struct qfq_group {
226 	uint64_t S, F;			/* group timestamps (approx). */
227 	unsigned int slot_shift;	/* Slot shift. */
228 	unsigned int index;		/* Group index. */
229 	unsigned int front;		/* Index of the front slot. */
230 	bitmap full_slots;		/* non-empty slots */
231 
232 	/* Array of lists of active classes. */
233 	struct qfq_class *slots[QFQ_MAX_SLOTS];
234 };
235 
236 /* scheduler instance descriptor. */
237 struct qfq_sched {
238 	uint64_t	V;		/* Precise virtual time. */
239 	uint32_t	wsum;		/* weight sum */
240 	uint32_t	iwsum;		/* inverse weight sum */
241 	NO(uint32_t	i_wsum;)	/* ONE_FP/w_sum */
242 	NO(uint32_t	queued;)	/* debugging */
243 	NO(uint32_t	loops;)		/* debugging */
244 	bitmap bitmaps[QFQ_MAX_STATE];	/* Group bitmaps. */
245 	struct qfq_group groups[QFQ_MAX_INDEX + 1]; /* The groups. */
246 };
247 
248 /*---- support functions ----------------------------*/
249 
250 /* Generic comparison function, handling wraparound. */
251 static inline int qfq_gt(uint64_t a, uint64_t b)
252 {
253 	return (int64_t)(a - b) > 0;
254 }
255 
256 /* Round a precise timestamp to its slotted value. */
257 static inline uint64_t qfq_round_down(uint64_t ts, unsigned int shift)
258 {
259 	return ts & ~((1ULL << shift) - 1);
260 }
261 
262 /* return the pointer to the group with lowest index in the bitmap */
263 static inline struct qfq_group *qfq_ffs(struct qfq_sched *q,
264 					unsigned long bitmap)
265 {
266 	int index = ffs(bitmap) - 1; // zero-based
267 	return &q->groups[index];
268 }
269 
270 /*
271  * Calculate a flow index, given its weight and maximum packet length.
272  * index = log_2(maxlen/weight) but we need to apply the scaling.
273  * This is used only once at flow creation.
274  */
275 static int qfq_calc_index(uint32_t inv_w, unsigned int maxlen)
276 {
277 	uint64_t slot_size = (uint64_t)maxlen *inv_w;
278 	unsigned long size_map;
279 	int index = 0;
280 
281 	size_map = (unsigned long)(slot_size >> QFQ_MIN_SLOT_SHIFT);
282 	if (!size_map)
283 		goto out;
284 
285 	index = __fls(size_map) + 1;	// basically a log_2()
286 	index -= !(slot_size - (1ULL << (index + QFQ_MIN_SLOT_SHIFT - 1)));
287 
288 	if (index < 0)
289 		index = 0;
290 
291 out:
292 	ND("W = %d, L = %d, I = %d\n", ONE_FP/inv_w, maxlen, index);
293 	return index;
294 }
295 /*---- end support functions ----*/
296 
297 /*-------- API calls --------------------------------*/
298 /*
299  * Validate and copy parameters from flowset.
300  */
301 static int
302 qfq_new_queue(struct dn_queue *_q)
303 {
304 	struct qfq_sched *q = (struct qfq_sched *)(_q->_si + 1);
305 	struct qfq_class *cl = (struct qfq_class *)_q;
306 	int i;
307 	uint32_t w;	/* approximated weight */
308 
309 	/* import parameters from the flowset. They should be correct
310 	 * already.
311 	 */
312 	w = _q->fs->fs.par[0];
313 	cl->lmax = _q->fs->fs.par[1];
314 	if (!w || w > QFQ_MAX_WEIGHT) {
315 		w = 1;
316 		D("rounding weight to 1");
317 	}
318 	cl->inv_w = ONE_FP/w;
319 	w = ONE_FP/cl->inv_w;
320 	if (q->wsum + w > QFQ_MAX_WSUM)
321 		return EINVAL;
322 
323 	i = qfq_calc_index(cl->inv_w, cl->lmax);
324 	cl->grp = &q->groups[i];
325 	q->wsum += w;
326 	q->iwsum = ONE_FP / q->wsum; /* XXX note theory */
327 	// XXX cl->S = q->V; ?
328 	return 0;
329 }
330 
331 /* remove an empty queue */
332 static int
333 qfq_free_queue(struct dn_queue *_q)
334 {
335 	struct qfq_sched *q = (struct qfq_sched *)(_q->_si + 1);
336 	struct qfq_class *cl = (struct qfq_class *)_q;
337 	if (cl->inv_w) {
338 		q->wsum -= ONE_FP/cl->inv_w;
339 		if (q->wsum != 0)
340 			q->iwsum = ONE_FP / q->wsum;
341 		cl->inv_w = 0; /* reset weight to avoid run twice */
342 	}
343 	return 0;
344 }
345 
346 /* Calculate a mask to mimic what would be ffs_from(). */
347 static inline unsigned long
348 mask_from(unsigned long bitmap, int from)
349 {
350 	return bitmap & ~((1UL << from) - 1);
351 }
352 
353 /*
354  * The state computation relies on ER=0, IR=1, EB=2, IB=3
355  * First compute eligibility comparing grp->S, q->V,
356  * then check if someone is blocking us and possibly add EB
357  */
358 static inline unsigned int
359 qfq_calc_state(struct qfq_sched *q, struct qfq_group *grp)
360 {
361 	/* if S > V we are not eligible */
362 	unsigned int state = qfq_gt(grp->S, q->V);
363 	unsigned long mask = mask_from(q->bitmaps[ER], grp->index);
364 	struct qfq_group *next;
365 
366 	if (mask) {
367 		next = qfq_ffs(q, mask);
368 		if (qfq_gt(grp->F, next->F))
369 			state |= EB;
370 	}
371 
372 	return state;
373 }
374 
375 /*
376  * In principle
377  *	q->bitmaps[dst] |= q->bitmaps[src] & mask;
378  *	q->bitmaps[src] &= ~mask;
379  * but we should make sure that src != dst
380  */
381 static inline void
382 qfq_move_groups(struct qfq_sched *q, unsigned long mask, int src, int dst)
383 {
384 	q->bitmaps[dst] |= q->bitmaps[src] & mask;
385 	q->bitmaps[src] &= ~mask;
386 }
387 
388 static inline void
389 qfq_unblock_groups(struct qfq_sched *q, int index, uint64_t old_finish)
390 {
391 	unsigned long mask = mask_from(q->bitmaps[ER], index + 1);
392 	struct qfq_group *next;
393 
394 	if (mask) {
395 		next = qfq_ffs(q, mask);
396 		if (!qfq_gt(next->F, old_finish))
397 			return;
398 	}
399 
400 	mask = (1UL << index) - 1;
401 	qfq_move_groups(q, mask, EB, ER);
402 	qfq_move_groups(q, mask, IB, IR);
403 }
404 
405 /*
406  * perhaps
407  *
408 	old_V ^= q->V;
409 	old_V >>= QFQ_MIN_SLOT_SHIFT;
410 	if (old_V) {
411 		...
412 	}
413  *
414  */
415 static inline void
416 qfq_make_eligible(struct qfq_sched *q, uint64_t old_V)
417 {
418 	unsigned long mask, vslot, old_vslot;
419 
420 	vslot = q->V >> QFQ_MIN_SLOT_SHIFT;
421 	old_vslot = old_V >> QFQ_MIN_SLOT_SHIFT;
422 
423 	if (vslot != old_vslot) {
424 		/* must be 2ULL, see ToN QFQ article fig.5, we use base-0 fls */
425 		mask = (2ULL << (__fls(vslot ^ old_vslot))) - 1;
426 		qfq_move_groups(q, mask, IR, ER);
427 		qfq_move_groups(q, mask, IB, EB);
428 	}
429 }
430 
431 /*
432  * XXX we should make sure that slot becomes less than 32.
433  * This is guaranteed by the input values.
434  * roundedS is always cl->S rounded on grp->slot_shift bits.
435  */
436 static inline void
437 qfq_slot_insert(struct qfq_group *grp, struct qfq_class *cl, uint64_t roundedS)
438 {
439 	uint64_t slot = (roundedS - grp->S) >> grp->slot_shift;
440 	unsigned int i = (grp->front + slot) % QFQ_MAX_SLOTS;
441 
442 	cl->next = grp->slots[i];
443 	grp->slots[i] = cl;
444 	__set_bit(slot, &grp->full_slots);
445 }
446 
447 /*
448  * remove the entry from the slot
449  */
450 static inline void
451 qfq_front_slot_remove(struct qfq_group *grp)
452 {
453 	struct qfq_class **h = &grp->slots[grp->front];
454 
455 	*h = (*h)->next;
456 	if (!*h)
457 		__clear_bit(0, &grp->full_slots);
458 }
459 
460 /*
461  * Returns the first full queue in a group. As a side effect,
462  * adjust the bucket list so the first non-empty bucket is at
463  * position 0 in full_slots.
464  */
465 static inline struct qfq_class *
466 qfq_slot_scan(struct qfq_group *grp)
467 {
468 	int i;
469 
470 	ND("grp %d full %x", grp->index, grp->full_slots);
471 	if (!grp->full_slots)
472 		return NULL;
473 
474 	i = ffs(grp->full_slots) - 1; // zero-based
475 	if (i > 0) {
476 		grp->front = (grp->front + i) % QFQ_MAX_SLOTS;
477 		grp->full_slots >>= i;
478 	}
479 
480 	return grp->slots[grp->front];
481 }
482 
483 /*
484  * adjust the bucket list. When the start time of a group decreases,
485  * we move the index down (modulo QFQ_MAX_SLOTS) so we don't need to
486  * move the objects. The mask of occupied slots must be shifted
487  * because we use ffs() to find the first non-empty slot.
488  * This covers decreases in the group's start time, but what about
489  * increases of the start time ?
490  * Here too we should make sure that i is less than 32
491  */
492 static inline void
493 qfq_slot_rotate(struct qfq_sched *q, struct qfq_group *grp, uint64_t roundedS)
494 {
495 	unsigned int i = (grp->S - roundedS) >> grp->slot_shift;
496 
497 	(void)q;
498 	grp->full_slots <<= i;
499 	grp->front = (grp->front - i) % QFQ_MAX_SLOTS;
500 }
501 
502 static inline void
503 qfq_update_eligible(struct qfq_sched *q, uint64_t old_V)
504 {
505 	bitmap ineligible;
506 
507 	ineligible = q->bitmaps[IR] | q->bitmaps[IB];
508 	if (ineligible) {
509 		if (!q->bitmaps[ER]) {
510 			struct qfq_group *grp;
511 			grp = qfq_ffs(q, ineligible);
512 			if (qfq_gt(grp->S, q->V))
513 				q->V = grp->S;
514 		}
515 		qfq_make_eligible(q, old_V);
516 	}
517 }
518 
519 /*
520  * Updates the class, returns true if also the group needs to be updated.
521  */
522 static inline int
523 qfq_update_class(struct qfq_sched *q, struct qfq_group *grp,
524 	    struct qfq_class *cl)
525 {
526 
527 	(void)q;
528 	cl->S = cl->F;
529 	if (cl->_q.mq.head == NULL)  {
530 		qfq_front_slot_remove(grp);
531 	} else {
532 		unsigned int len;
533 		uint64_t roundedS;
534 
535 		len = cl->_q.mq.head->m_pkthdr.len;
536 		cl->F = cl->S + (uint64_t)len * cl->inv_w;
537 		roundedS = qfq_round_down(cl->S, grp->slot_shift);
538 		if (roundedS == grp->S)
539 			return 0;
540 
541 		qfq_front_slot_remove(grp);
542 		qfq_slot_insert(grp, cl, roundedS);
543 	}
544 	return 1;
545 }
546 
547 static struct mbuf *
548 qfq_dequeue(struct dn_sch_inst *si)
549 {
550 	struct qfq_sched *q = (struct qfq_sched *)(si + 1);
551 	struct qfq_group *grp;
552 	struct qfq_class *cl;
553 	struct mbuf *m;
554 	uint64_t old_V;
555 
556 	NO(q->loops++;)
557 	if (!q->bitmaps[ER]) {
558 		NO(if (q->queued)
559 			dump_sched(q, "start dequeue");)
560 		return NULL;
561 	}
562 
563 	grp = qfq_ffs(q, q->bitmaps[ER]);
564 
565 	cl = grp->slots[grp->front];
566 	/* extract from the first bucket in the bucket list */
567 	m = dn_dequeue(&cl->_q);
568 
569 	if (!m) {
570 		D("BUG/* non-workconserving leaf */");
571 		return NULL;
572 	}
573 	NO(q->queued--;)
574 	old_V = q->V;
575 	q->V += (uint64_t)m->m_pkthdr.len * q->iwsum;
576 	ND("m is %p F 0x%llx V now 0x%llx", m, cl->F, q->V);
577 
578 	if (qfq_update_class(q, grp, cl)) {
579 		uint64_t old_F = grp->F;
580 		cl = qfq_slot_scan(grp);
581 		if (!cl) { /* group gone, remove from ER */
582 			__clear_bit(grp->index, &q->bitmaps[ER]);
583 			// grp->S = grp->F + 1; // XXX debugging only
584 		} else {
585 			uint64_t roundedS = qfq_round_down(cl->S, grp->slot_shift);
586 			unsigned int s;
587 
588 			if (grp->S == roundedS)
589 				goto skip_unblock;
590 			grp->S = roundedS;
591 			grp->F = roundedS + (2ULL << grp->slot_shift);
592 			/* remove from ER and put in the new set */
593 			__clear_bit(grp->index, &q->bitmaps[ER]);
594 			s = qfq_calc_state(q, grp);
595 			__set_bit(grp->index, &q->bitmaps[s]);
596 		}
597 		/* we need to unblock even if the group has gone away */
598 		qfq_unblock_groups(q, grp->index, old_F);
599 	}
600 
601 skip_unblock:
602 	qfq_update_eligible(q, old_V);
603 	NO(if (!q->bitmaps[ER] && q->queued)
604 		dump_sched(q, "end dequeue");)
605 
606 	return m;
607 }
608 
609 /*
610  * Assign a reasonable start time for a new flow k in group i.
611  * Admissible values for \hat(F) are multiples of \sigma_i
612  * no greater than V+\sigma_i . Larger values mean that
613  * we had a wraparound so we consider the timestamp to be stale.
614  *
615  * If F is not stale and F >= V then we set S = F.
616  * Otherwise we should assign S = V, but this may violate
617  * the ordering in ER. So, if we have groups in ER, set S to
618  * the F_j of the first group j which would be blocking us.
619  * We are guaranteed not to move S backward because
620  * otherwise our group i would still be blocked.
621  */
622 static inline void
623 qfq_update_start(struct qfq_sched *q, struct qfq_class *cl)
624 {
625 	unsigned long mask;
626 	uint64_t limit, roundedF;
627 	int slot_shift = cl->grp->slot_shift;
628 
629 	roundedF = qfq_round_down(cl->F, slot_shift);
630 	limit = qfq_round_down(q->V, slot_shift) + (1ULL << slot_shift);
631 
632 	if (!qfq_gt(cl->F, q->V) || qfq_gt(roundedF, limit)) {
633 		/* timestamp was stale */
634 		mask = mask_from(q->bitmaps[ER], cl->grp->index);
635 		if (mask) {
636 			struct qfq_group *next = qfq_ffs(q, mask);
637 			if (qfq_gt(roundedF, next->F)) {
638 				/* from pv 71261956973ba9e0637848a5adb4a5819b4bae83 */
639 				if (qfq_gt(limit, next->F))
640 					cl->S = next->F;
641 				else /* preserve timestamp correctness */
642 					cl->S = limit;
643 				return;
644 			}
645 		}
646 		cl->S = q->V;
647 	} else { /* timestamp is not stale */
648 		cl->S = cl->F;
649 	}
650 }
651 
652 static int
653 qfq_enqueue(struct dn_sch_inst *si, struct dn_queue *_q, struct mbuf *m)
654 {
655 	struct qfq_sched *q = (struct qfq_sched *)(si + 1);
656 	struct qfq_group *grp;
657 	struct qfq_class *cl = (struct qfq_class *)_q;
658 	uint64_t roundedS;
659 	int s;
660 
661 	NO(q->loops++;)
662 	DX(4, "len %d flow %p inv_w 0x%x grp %d", m->m_pkthdr.len,
663 		_q, cl->inv_w, cl->grp->index);
664 	/* XXX verify that the packet obeys the parameters */
665 	if (m != _q->mq.head) {
666 		if (dn_enqueue(_q, m, 0)) /* packet was dropped */
667 			return 1;
668 		NO(q->queued++;)
669 		if (m != _q->mq.head)
670 			return 0;
671 	}
672 	/* If reach this point, queue q was idle */
673 	grp = cl->grp;
674 	qfq_update_start(q, cl); /* adjust start time */
675 	/* compute new finish time and rounded start. */
676 	cl->F = cl->S + (uint64_t)(m->m_pkthdr.len) * cl->inv_w;
677 	roundedS = qfq_round_down(cl->S, grp->slot_shift);
678 
679 	/*
680 	 * insert cl in the correct bucket.
681 	 * If cl->S >= grp->S we don't need to adjust the
682 	 * bucket list and simply go to the insertion phase.
683 	 * Otherwise grp->S is decreasing, we must make room
684 	 * in the bucket list, and also recompute the group state.
685 	 * Finally, if there were no flows in this group and nobody
686 	 * was in ER make sure to adjust V.
687 	 */
688 	if (grp->full_slots) {
689 		if (!qfq_gt(grp->S, cl->S))
690 			goto skip_update;
691 		/* create a slot for this cl->S */
692 		qfq_slot_rotate(q, grp, roundedS);
693 		/* group was surely ineligible, remove */
694 		__clear_bit(grp->index, &q->bitmaps[IR]);
695 		__clear_bit(grp->index, &q->bitmaps[IB]);
696 	} else if (!q->bitmaps[ER] && qfq_gt(roundedS, q->V))
697 		q->V = roundedS;
698 
699 	grp->S = roundedS;
700 	grp->F = roundedS + (2ULL << grp->slot_shift); // i.e. 2\sigma_i
701 	s = qfq_calc_state(q, grp);
702 	__set_bit(grp->index, &q->bitmaps[s]);
703 	ND("new state %d 0x%x", s, q->bitmaps[s]);
704 	ND("S %llx F %llx V %llx", cl->S, cl->F, q->V);
705 skip_update:
706 	qfq_slot_insert(grp, cl, roundedS);
707 
708 	return 0;
709 }
710 
711 #if 0
712 static inline void
713 qfq_slot_remove(struct qfq_sched *q, struct qfq_group *grp,
714 	struct qfq_class *cl, struct qfq_class **pprev)
715 {
716 	unsigned int i, offset;
717 	uint64_t roundedS;
718 
719 	roundedS = qfq_round_down(cl->S, grp->slot_shift);
720 	offset = (roundedS - grp->S) >> grp->slot_shift;
721 	i = (grp->front + offset) % QFQ_MAX_SLOTS;
722 
723 #ifdef notyet
724 	if (!pprev) {
725 		pprev = &grp->slots[i];
726 		while (*pprev && *pprev != cl)
727 			pprev = &(*pprev)->next;
728 	}
729 #endif
730 
731 	*pprev = cl->next;
732 	if (!grp->slots[i])
733 		__clear_bit(offset, &grp->full_slots);
734 }
735 
736 /*
737  * called to forcibly destroy a queue.
738  * If the queue is not in the front bucket, or if it has
739  * other queues in the front bucket, we can simply remove
740  * the queue with no other side effects.
741  * Otherwise we must propagate the event up.
742  * XXX description to be completed.
743  */
744 static void
745 qfq_deactivate_class(struct qfq_sched *q, struct qfq_class *cl,
746 				 struct qfq_class **pprev)
747 {
748 	struct qfq_group *grp = &q->groups[cl->index];
749 	unsigned long mask;
750 	uint64_t roundedS;
751 	int s;
752 
753 	cl->F = cl->S;	// not needed if the class goes away.
754 	qfq_slot_remove(q, grp, cl, pprev);
755 
756 	if (!grp->full_slots) {
757 		/* nothing left in the group, remove from all sets.
758 		 * Do ER last because if we were blocking other groups
759 		 * we must unblock them.
760 		 */
761 		__clear_bit(grp->index, &q->bitmaps[IR]);
762 		__clear_bit(grp->index, &q->bitmaps[EB]);
763 		__clear_bit(grp->index, &q->bitmaps[IB]);
764 
765 		if (test_bit(grp->index, &q->bitmaps[ER]) &&
766 		    !(q->bitmaps[ER] & ~((1UL << grp->index) - 1))) {
767 			mask = q->bitmaps[ER] & ((1UL << grp->index) - 1);
768 			if (mask)
769 				mask = ~((1UL << __fls(mask)) - 1);
770 			else
771 				mask = ~0UL;
772 			qfq_move_groups(q, mask, EB, ER);
773 			qfq_move_groups(q, mask, IB, IR);
774 		}
775 		__clear_bit(grp->index, &q->bitmaps[ER]);
776 	} else if (!grp->slots[grp->front]) {
777 		cl = qfq_slot_scan(grp);
778 		roundedS = qfq_round_down(cl->S, grp->slot_shift);
779 		if (grp->S != roundedS) {
780 			__clear_bit(grp->index, &q->bitmaps[ER]);
781 			__clear_bit(grp->index, &q->bitmaps[IR]);
782 			__clear_bit(grp->index, &q->bitmaps[EB]);
783 			__clear_bit(grp->index, &q->bitmaps[IB]);
784 			grp->S = roundedS;
785 			grp->F = roundedS + (2ULL << grp->slot_shift);
786 			s = qfq_calc_state(q, grp);
787 			__set_bit(grp->index, &q->bitmaps[s]);
788 		}
789 	}
790 	qfq_update_eligible(q, q->V);
791 }
792 #endif
793 
794 static int
795 qfq_new_fsk(struct dn_fsk *f)
796 {
797 	ipdn_bound_var(&f->fs.par[0], 1, 1, QFQ_MAX_WEIGHT, "qfq weight");
798 	ipdn_bound_var(&f->fs.par[1], 1500, 1, 2000, "qfq maxlen");
799 	ND("weight %d len %d\n", f->fs.par[0], f->fs.par[1]);
800 	return 0;
801 }
802 
803 /*
804  * initialize a new scheduler instance
805  */
806 static int
807 qfq_new_sched(struct dn_sch_inst *si)
808 {
809 	struct qfq_sched *q = (struct qfq_sched *)(si + 1);
810 	struct qfq_group *grp;
811 	int i;
812 
813 	for (i = 0; i <= QFQ_MAX_INDEX; i++) {
814 		grp = &q->groups[i];
815 		grp->index = i;
816 		grp->slot_shift = QFQ_MTU_SHIFT + FRAC_BITS -
817 					(QFQ_MAX_INDEX - i);
818 	}
819 	return 0;
820 }
821 
822 /*
823  * QFQ scheduler descriptor
824  */
825 static struct dn_alg qfq_desc = {
826 	_SI( .type = ) DN_SCHED_QFQ,
827 	_SI( .name = ) "QFQ",
828 	_SI( .flags = ) DN_MULTIQUEUE,
829 
830 	_SI( .schk_datalen = ) 0,
831 	_SI( .si_datalen = ) sizeof(struct qfq_sched),
832 	_SI( .q_datalen = ) sizeof(struct qfq_class) - sizeof(struct dn_queue),
833 
834 	_SI( .enqueue = ) qfq_enqueue,
835 	_SI( .dequeue = ) qfq_dequeue,
836 
837 	_SI( .config = )  NULL,
838 	_SI( .destroy = )  NULL,
839 	_SI( .new_sched = ) qfq_new_sched,
840 	_SI( .free_sched = )  NULL,
841 	_SI( .new_fsk = ) qfq_new_fsk,
842 	_SI( .free_fsk = )  NULL,
843 	_SI( .new_queue = ) qfq_new_queue,
844 	_SI( .free_queue = ) qfq_free_queue,
845 #ifdef NEW_AQM
846 	_SI( .getconfig = )  NULL,
847 #endif
848 };
849 
850 DECLARE_DNSCHED_MODULE(dn_qfq, &qfq_desc);
851 
852 #ifdef QFQ_DEBUG
853 static void
854 dump_groups(struct qfq_sched *q, uint32_t mask)
855 {
856 	int i, j;
857 
858 	for (i = 0; i < QFQ_MAX_INDEX + 1; i++) {
859 		struct qfq_group *g = &q->groups[i];
860 
861 		if (0 == (mask & (1<<i)))
862 			continue;
863 		for (j = 0; j < QFQ_MAX_SLOTS; j++) {
864 			if (g->slots[j])
865 				D("    bucket %d %p", j, g->slots[j]);
866 		}
867 		D("full_slots 0x%llx", (_P64)g->full_slots);
868 		D("        %2d S 0x%20llx F 0x%llx %c", i,
869 			(_P64)g->S, (_P64)g->F,
870 			mask & (1<<i) ? '1' : '0');
871 	}
872 }
873 
874 static void
875 dump_sched(struct qfq_sched *q, const char *msg)
876 {
877 	D("--- in %s: ---", msg);
878 	D("loops %d queued %d V 0x%llx", q->loops, q->queued, (_P64)q->V);
879 	D("    ER 0x%08x", (unsigned)q->bitmaps[ER]);
880 	D("    EB 0x%08x", (unsigned)q->bitmaps[EB]);
881 	D("    IR 0x%08x", (unsigned)q->bitmaps[IR]);
882 	D("    IB 0x%08x", (unsigned)q->bitmaps[IB]);
883 	dump_groups(q, 0xffffffff);
884 };
885 #endif /* QFQ_DEBUG */
886