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