xref: /freebsd/sys/netpfil/ipfw/dn_aqm_pie.c (revision 282e23f07bf49b4e37aabdcc1c513a788db36d10)
1 /*
2  * PIE - Proportional Integral controller Enhanced AQM algorithm.
3  *
4  * $FreeBSD$
5  *
6  * Copyright (C) 2016 Centre for Advanced Internet Architectures,
7  *  Swinburne University of Technology, Melbourne, Australia.
8  * Portions of this code were made possible in part by a gift from
9  *  The Comcast Innovation Fund.
10  * Implemented by Rasool Al-Saadi <ralsaadi@swin.edu.au>
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 #include "opt_inet6.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
40 #include <sys/mbuf.h>
41 #include <sys/kernel.h>
42 #include <sys/lock.h>
43 #include <sys/module.h>
44 #include <sys/mutex.h>
45 #include <sys/priv.h>
46 #include <sys/proc.h>
47 #include <sys/rwlock.h>
48 #include <sys/socket.h>
49 #include <sys/time.h>
50 #include <sys/sysctl.h>
51 
52 #include <net/if.h>	/* IFNAMSIZ, struct ifaddr, ifq head, lock.h mutex.h */
53 #include <net/netisr.h>
54 #include <net/vnet.h>
55 
56 #include <netinet/in.h>
57 #include <netinet/ip.h>		/* ip_len, ip_off */
58 #include <netinet/ip_var.h>	/* ip_output(), IP_FORWARDING */
59 #include <netinet/ip_fw.h>
60 #include <netinet/ip_dummynet.h>
61 #include <netinet/if_ether.h> /* various ether_* routines */
62 #include <netinet/ip6.h>       /* for ip6_input, ip6_output prototypes */
63 #include <netinet6/ip6_var.h>
64 #include <netpfil/ipfw/dn_heap.h>
65 
66 #ifdef NEW_AQM
67 #include <netpfil/ipfw/ip_fw_private.h>
68 #include <netpfil/ipfw/ip_dn_private.h>
69 #include <netpfil/ipfw/dn_aqm.h>
70 #include <netpfil/ipfw/dn_aqm_pie.h>
71 #include <netpfil/ipfw/dn_sched.h>
72 
73 /* for debugging */
74 #include <sys/syslog.h>
75 
76 static struct dn_aqm pie_desc;
77 
78 /*  PIE defaults
79  * target=15ms, tupdate=15ms, max_burst=150ms,
80  * max_ecnth=0.1, alpha=0.125, beta=1.25,
81  */
82 struct dn_aqm_pie_parms pie_sysctl =
83 	{ 15 * AQM_TIME_1MS,  15 * AQM_TIME_1MS, 150 * AQM_TIME_1MS,
84 	PIE_SCALE/10 , PIE_SCALE * 0.125,  PIE_SCALE * 1.25 ,
85 	PIE_CAPDROP_ENABLED | PIE_DEPRATEEST_ENABLED | PIE_DERAND_ENABLED };
86 
87 static int
88 pie_sysctl_alpha_beta_handler(SYSCTL_HANDLER_ARGS)
89 {
90 	int error;
91 	long  value;
92 
93 	if (!strcmp(oidp->oid_name,"alpha"))
94 		value = pie_sysctl.alpha;
95 	else
96 		value = pie_sysctl.beta;
97 
98 	value = value * 1000 / PIE_SCALE;
99 	error = sysctl_handle_long(oidp, &value, 0, req);
100 	if (error != 0 || req->newptr == NULL)
101 		return (error);
102 	if (value < 1 || value > 7 * PIE_SCALE)
103 		return (EINVAL);
104 	value = (value * PIE_SCALE) / 1000;
105 	if (!strcmp(oidp->oid_name,"alpha"))
106 			pie_sysctl.alpha = value;
107 	else
108 		pie_sysctl.beta = value;
109 	return (0);
110 }
111 
112 static int
113 pie_sysctl_target_tupdate_maxb_handler(SYSCTL_HANDLER_ARGS)
114 {
115 	int error;
116 	long  value;
117 
118 	if (!strcmp(oidp->oid_name,"target"))
119 		value = pie_sysctl.qdelay_ref;
120 	else if (!strcmp(oidp->oid_name,"tupdate"))
121 		value = pie_sysctl.tupdate;
122 	else
123 		value = pie_sysctl.max_burst;
124 
125 	value = value / AQM_TIME_1US;
126 	error = sysctl_handle_long(oidp, &value, 0, req);
127 	if (error != 0 || req->newptr == NULL)
128 		return (error);
129 	if (value < 1 || value > 10 * AQM_TIME_1S)
130 		return (EINVAL);
131 	value = value * AQM_TIME_1US;
132 
133 	if (!strcmp(oidp->oid_name,"target"))
134 		pie_sysctl.qdelay_ref  = value;
135 	else if (!strcmp(oidp->oid_name,"tupdate"))
136 		pie_sysctl.tupdate  = value;
137 	else
138 		pie_sysctl.max_burst = value;
139 	return (0);
140 }
141 
142 static int
143 pie_sysctl_max_ecnth_handler(SYSCTL_HANDLER_ARGS)
144 {
145 	int error;
146 	long  value;
147 
148 	value = pie_sysctl.max_ecnth;
149 	value = value * 1000 / PIE_SCALE;
150 	error = sysctl_handle_long(oidp, &value, 0, req);
151 	if (error != 0 || req->newptr == NULL)
152 		return (error);
153 	if (value < 1 || value > PIE_SCALE)
154 		return (EINVAL);
155 	value = (value * PIE_SCALE) / 1000;
156 	pie_sysctl.max_ecnth = value;
157 	return (0);
158 }
159 
160 /* define PIE sysctl variables */
161 SYSBEGIN(f4)
162 SYSCTL_DECL(_net_inet);
163 SYSCTL_DECL(_net_inet_ip);
164 SYSCTL_DECL(_net_inet_ip_dummynet);
165 static SYSCTL_NODE(_net_inet_ip_dummynet, OID_AUTO,
166 	pie, CTLFLAG_RW, 0, "PIE");
167 
168 #ifdef SYSCTL_NODE
169 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, target,
170 	CTLTYPE_LONG | CTLFLAG_RW, NULL, 0,
171 	pie_sysctl_target_tupdate_maxb_handler, "L",
172 	"queue target in microsecond");
173 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, tupdate,
174 	CTLTYPE_LONG | CTLFLAG_RW, NULL, 0,
175 	pie_sysctl_target_tupdate_maxb_handler, "L",
176 	"the frequency of drop probability calculation in microsecond");
177 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, max_burst,
178 	CTLTYPE_LONG | CTLFLAG_RW, NULL, 0,
179 	pie_sysctl_target_tupdate_maxb_handler, "L",
180 	"Burst allowance interval in microsecond");
181 
182 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, max_ecnth,
183 	CTLTYPE_LONG | CTLFLAG_RW, NULL, 0,
184 	pie_sysctl_max_ecnth_handler, "L",
185 	"ECN safeguard threshold scaled by 1000");
186 
187 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, alpha,
188 	CTLTYPE_LONG | CTLFLAG_RW, NULL, 0,
189 	pie_sysctl_alpha_beta_handler, "L",
190 	"PIE alpha scaled by 1000");
191 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, beta,
192 	CTLTYPE_LONG | CTLFLAG_RW, NULL, 0,
193 	pie_sysctl_alpha_beta_handler, "L",
194 	"beta scaled by 1000");
195 #endif
196 
197 
198 /*
199  * Callout function for drop probability calculation
200  * This function is called over tupdate ms and takes pointer of PIE
201  * status variables as an argument
202   */
203 static void
204 calculate_drop_prob(void *x)
205 {
206 	int64_t p, prob, oldprob;
207 	struct dn_aqm_pie_parms *pprms;
208 	struct pie_status *pst = (struct pie_status *) x;
209 
210 	/* dealing with race condition */
211 	if (callout_pending(&pst->aqm_pie_callout)) {
212 		/* callout was reset */
213 		mtx_unlock(&pst->lock_mtx);
214 		return;
215 	}
216 
217 	if (!callout_active(&pst->aqm_pie_callout)) {
218 		/* callout was stopped */
219 		mtx_unlock(&pst->lock_mtx);
220 		mtx_destroy(&pst->lock_mtx);
221 		free(x, M_DUMMYNET);
222 		//pst->pq->aqm_status = NULL;
223 		pie_desc.ref_count--;
224 		return;
225 	}
226 	callout_deactivate(&pst->aqm_pie_callout);
227 
228 	pprms = pst->parms;
229 	prob = pst->drop_prob;
230 
231 	/* calculate current qdelay */
232 	if (pprms->flags & PIE_DEPRATEEST_ENABLED) {
233 		pst->current_qdelay = ((uint64_t)pst->pq->ni.len_bytes *
234 			pst->avg_dq_time) >> PIE_DQ_THRESHOLD_BITS;
235 	}
236 
237 	/* calculate drop probability */
238 	p = (int64_t)pprms->alpha *
239 		((int64_t)pst->current_qdelay - (int64_t)pprms->qdelay_ref);
240 	p +=(int64_t) pprms->beta *
241 		((int64_t)pst->current_qdelay - (int64_t)pst->qdelay_old);
242 
243 	/* We PIE_MAX_PROB shift by 12-bits to increase the division precision */
244 	p *= (PIE_MAX_PROB << 12) / AQM_TIME_1S;
245 
246 	/* auto-tune drop probability */
247 	if (prob < (PIE_MAX_PROB / 1000000)) /* 0.000001 */
248 		p >>= 11 + PIE_FIX_POINT_BITS + 12;
249 	else if (prob < (PIE_MAX_PROB / 100000)) /* 0.00001 */
250 		p >>= 9 + PIE_FIX_POINT_BITS + 12;
251 	else if (prob < (PIE_MAX_PROB / 10000)) /* 0.0001 */
252 		p >>= 7 + PIE_FIX_POINT_BITS + 12;
253 	else if (prob < (PIE_MAX_PROB / 1000)) /* 0.001 */
254 		p >>= 5 + PIE_FIX_POINT_BITS + 12;
255 	else if (prob < (PIE_MAX_PROB / 100)) /* 0.01 */
256 		p >>= 3 + PIE_FIX_POINT_BITS + 12;
257 	else if (prob < (PIE_MAX_PROB / 10)) /* 0.1 */
258 		p >>= 1 + PIE_FIX_POINT_BITS + 12;
259 	else
260 		p >>= PIE_FIX_POINT_BITS + 12;
261 
262 	oldprob = prob;
263 
264 	/* Cap Drop adjustment */
265 	if ((pprms->flags & PIE_CAPDROP_ENABLED) && prob >= PIE_MAX_PROB / 10
266 		&& p > PIE_MAX_PROB / 50 )
267 			p = PIE_MAX_PROB / 50;
268 
269 	prob = prob + p;
270 
271 	/* decay the drop probability exponentially */
272 	if (pst->current_qdelay == 0 && pst->qdelay_old == 0)
273 		/* 0.98 ~= 1- 1/64 */
274 		prob = prob - (prob >> 6);
275 
276 
277 	/* check for multiplication overflow/underflow */
278 	if (p>0) {
279 		if (prob<oldprob) {
280 			D("overflow");
281 			prob= PIE_MAX_PROB;
282 		}
283 	}
284 	else
285 		if (prob>oldprob) {
286 			prob= 0;
287 			D("underflow");
288 		}
289 
290 	/* make drop probability between 0 and PIE_MAX_PROB*/
291 	if (prob < 0)
292 		prob = 0;
293 	else if (prob > PIE_MAX_PROB)
294 		prob = PIE_MAX_PROB;
295 
296 	pst->drop_prob = prob;
297 
298 	/* store current queue delay value in old queue delay*/
299 	pst->qdelay_old = pst->current_qdelay;
300 
301 	/* update burst allowance */
302 	if ((pst->sflags & PIE_ACTIVE) && pst->burst_allowance>0) {
303 
304 		if (pst->burst_allowance > pprms->tupdate )
305 			pst->burst_allowance -= pprms->tupdate;
306 		else
307 			pst->burst_allowance = 0;
308 	}
309 
310 	/* reschedule calculate_drop_prob function */
311 	if (pst->sflags & PIE_ACTIVE)
312 		callout_reset_sbt(&pst->aqm_pie_callout,
313 			(uint64_t)pprms->tupdate * SBT_1US, 0, calculate_drop_prob, pst, 0);
314 
315 	mtx_unlock(&pst->lock_mtx);
316 }
317 
318 /*
319  * Extract a packet from the head of queue 'q'
320  * Return a packet or NULL if the queue is empty.
321  * If getts is set, also extract packet's timestamp from mtag.
322  */
323 static struct mbuf *
324 pie_extract_head(struct dn_queue *q, aqm_time_t *pkt_ts, int getts)
325 {
326 	struct m_tag *mtag;
327 	struct mbuf *m = q->mq.head;
328 
329 	if (m == NULL)
330 		return m;
331 	q->mq.head = m->m_nextpkt;
332 
333 	/* Update stats */
334 	update_stats(q, -m->m_pkthdr.len, 0);
335 
336 	if (q->ni.length == 0) /* queue is now idle */
337 			q->q_time = dn_cfg.curr_time;
338 
339 	if (getts) {
340 		/* extract packet TS*/
341 		mtag = m_tag_locate(m, MTAG_ABI_COMPAT, DN_AQM_MTAG_TS, NULL);
342 		if (mtag == NULL) {
343 			D("PIE timestamp mtag not found!");
344 			*pkt_ts = 0;
345 		} else {
346 			*pkt_ts = *(aqm_time_t *)(mtag + 1);
347 			m_tag_delete(m,mtag);
348 		}
349 	}
350 	return m;
351 }
352 
353 /*
354  * Initiate PIE  variable and optionally activate it
355  */
356 __inline static void
357 init_activate_pie(struct pie_status *pst, int resettimer)
358 {
359 	struct dn_aqm_pie_parms *pprms;
360 
361 	mtx_lock(&pst->lock_mtx);
362 	pprms = pst->parms;
363 	pst->drop_prob = 0;
364 	pst->qdelay_old = 0;
365 	pst->burst_allowance = pprms->max_burst;
366 	pst->accu_prob = 0;
367 	pst->dq_count = 0;
368 	pst->avg_dq_time = 0;
369 	pst->sflags = PIE_INMEASUREMENT;
370 	pst->measurement_start = AQM_UNOW;
371 
372 	if (resettimer) {
373 		pst->sflags |= PIE_ACTIVE;
374 		callout_reset_sbt(&pst->aqm_pie_callout,
375 			(uint64_t)pprms->tupdate * SBT_1US,
376 			0, calculate_drop_prob, pst, 0);
377 	}
378 	//DX(2, "PIE Activated");
379 	mtx_unlock(&pst->lock_mtx);
380 }
381 
382 /*
383  * Deactivate PIE and stop probe update callout
384  */
385 __inline static void
386 deactivate_pie(struct pie_status *pst)
387 {
388 	mtx_lock(&pst->lock_mtx);
389 	pst->sflags &= ~(PIE_ACTIVE | PIE_INMEASUREMENT);
390 	callout_stop(&pst->aqm_pie_callout);
391 	//D("PIE Deactivated");
392 	mtx_unlock(&pst->lock_mtx);
393 }
394 
395 /*
396  * Dequeue and return a pcaket from queue 'q' or NULL if 'q' is empty.
397  * Also, caculate depature time or queue delay using timestamp
398  */
399 static struct mbuf *
400 aqm_pie_dequeue(struct dn_queue *q)
401 {
402 	struct mbuf *m;
403 	struct dn_flow *ni;	/* stats for scheduler instance */
404 	struct dn_aqm_pie_parms *pprms;
405 	struct pie_status *pst;
406 	aqm_time_t now;
407 	aqm_time_t pkt_ts, dq_time;
408 	int32_t w;
409 
410 	pst  = q->aqm_status;
411 	pprms = pst->parms;
412 	ni = &q->_si->ni;
413 
414 	/*we extarct packet ts only when Departure Rate Estimation dis not used*/
415 	m = pie_extract_head(q, &pkt_ts, !(pprms->flags & PIE_DEPRATEEST_ENABLED));
416 
417 	if (!m || !(pst->sflags & PIE_ACTIVE))
418 		return m;
419 
420 	now = AQM_UNOW;
421 	if (pprms->flags & PIE_DEPRATEEST_ENABLED) {
422 		/* calculate average depature time */
423 		if(pst->sflags & PIE_INMEASUREMENT) {
424 			pst->dq_count += m->m_pkthdr.len;
425 
426 			if (pst->dq_count >= PIE_DQ_THRESHOLD) {
427 				dq_time = now - pst->measurement_start;
428 
429 				/*
430 				 * if we don't have old avg dq_time i.e PIE is (re)initialized,
431 				 * don't use weight to calculate new avg_dq_time
432 				 */
433 				if(pst->avg_dq_time == 0)
434 					pst->avg_dq_time = dq_time;
435 				else {
436 					/*
437 					 * weight = PIE_DQ_THRESHOLD/2^6, but we scaled
438 					 * weight by 2^8. Thus, scaled
439 					 * weight = PIE_DQ_THRESHOLD /2^8
440 					 * */
441 					w = PIE_DQ_THRESHOLD >> 8;
442 					pst->avg_dq_time = (dq_time* w
443 						+ (pst->avg_dq_time * ((1L << 8) - w))) >> 8;
444 					pst->sflags &= ~PIE_INMEASUREMENT;
445 				}
446 			}
447 		}
448 
449 		/*
450 		 * Start new measurment cycle when the queue has
451 		 *  PIE_DQ_THRESHOLD worth of bytes.
452 		 */
453 		if(!(pst->sflags & PIE_INMEASUREMENT) &&
454 			q->ni.len_bytes >= PIE_DQ_THRESHOLD) {
455 			pst->sflags |= PIE_INMEASUREMENT;
456 			pst->measurement_start = now;
457 			pst->dq_count = 0;
458 		}
459 	}
460 	/* Optionally, use packet timestamp to estimate queue delay */
461 	else
462 		pst->current_qdelay = now - pkt_ts;
463 
464 	return m;
465 }
466 
467 /*
468  * Enqueue a packet in q, subject to space and  PIE queue management policy
469  * (whose parameters are in q->fs).
470  * Update stats for the queue and the scheduler.
471  * Return 0 on success, 1 on drop. The packet is consumed anyways.
472  */
473 static int
474 aqm_pie_enqueue(struct dn_queue *q, struct mbuf* m)
475 {
476 	struct dn_fs *f;
477 	uint64_t len;
478 	uint32_t qlen;
479 	struct pie_status *pst;
480 	struct dn_aqm_pie_parms *pprms;
481 	int t;
482 
483 	len = m->m_pkthdr.len;
484 	pst  = q->aqm_status;
485 	if(!pst) {
486 		DX(2, "PIE queue is not initialized\n");
487 		update_stats(q, 0, 1);
488 		FREE_PKT(m);
489 		return 1;
490 	}
491 
492 	f = &(q->fs->fs);
493 	pprms = pst->parms;
494 	t = ENQUE;
495 
496 	/* get current queue length in bytes or packets*/
497 	qlen = (f->flags & DN_QSIZE_BYTES) ?
498 		q->ni.len_bytes : q->ni.length;
499 
500 	/* check for queue size and drop the tail if exceed queue limit*/
501 	if (qlen >= f->qsize)
502 		t = DROP;
503 	/* drop/mark the packet when PIE is active and burst time elapsed */
504 	else if ((pst->sflags & PIE_ACTIVE) && pst->burst_allowance==0
505 			&& drop_early(pst, q->ni.len_bytes) == DROP) {
506 				/*
507 				 * if drop_prob over ECN threshold, drop the packet
508 				 * otherwise mark and enqueue it.
509 				 */
510 				if ((pprms->flags & PIE_ECN_ENABLED) && pst->drop_prob <
511 					(pprms->max_ecnth << (PIE_PROB_BITS - PIE_FIX_POINT_BITS))
512 					&& ecn_mark(m))
513 					t = ENQUE;
514 				else
515 					t = DROP;
516 	}
517 
518 	/* Turn PIE on when 1/3 of the queue is full */
519 	if (!(pst->sflags & PIE_ACTIVE) && qlen >= pst->one_third_q_size) {
520 		init_activate_pie(pst, 1);
521 	}
522 
523 	/*  Reset burst tolerance and optinally turn PIE off*/
524 	if ((pst->sflags & PIE_ACTIVE) && pst->drop_prob == 0 &&
525 		pst->current_qdelay < (pprms->qdelay_ref >> 1) &&
526 		pst->qdelay_old < (pprms->qdelay_ref >> 1)) {
527 
528 			pst->burst_allowance = pprms->max_burst;
529 			if ((pprms->flags & PIE_ON_OFF_MODE_ENABLED) && qlen<=0)
530 				deactivate_pie(pst);
531 	}
532 
533 	/* Timestamp the packet if Departure Rate Estimation is disabled */
534 	if (t != DROP && !(pprms->flags & PIE_DEPRATEEST_ENABLED)) {
535 		/* Add TS to mbuf as a TAG */
536 		struct m_tag *mtag;
537 		mtag = m_tag_locate(m, MTAG_ABI_COMPAT, DN_AQM_MTAG_TS, NULL);
538 		if (mtag == NULL)
539 			mtag = m_tag_alloc(MTAG_ABI_COMPAT, DN_AQM_MTAG_TS,
540 				sizeof(aqm_time_t), M_NOWAIT);
541 		if (mtag == NULL) {
542 			m_freem(m);
543 			t = DROP;
544 		}
545 		*(aqm_time_t *)(mtag + 1) = AQM_UNOW;
546 		m_tag_prepend(m, mtag);
547 	}
548 
549 	if (t != DROP) {
550 		mq_append(&q->mq, m);
551 		update_stats(q, len, 0);
552 		return (0);
553 	} else {
554 		update_stats(q, 0, 1);
555 
556 		/* reset accu_prob after packet drop */
557 		pst->accu_prob = 0;
558 		FREE_PKT(m);
559 		return 1;
560 	}
561 	return 0;
562 }
563 
564 /*
565  * initialize PIE for queue 'q'
566  * First allocate memory for PIE status.
567  */
568 static int
569 aqm_pie_init(struct dn_queue *q)
570 {
571 	struct pie_status *pst;
572 	struct dn_aqm_pie_parms *pprms;
573 	int err = 0;
574 
575 	pprms = q->fs->aqmcfg;
576 
577 	do { /* exit with break when error occurs*/
578 		if (!pprms){
579 			D("AQM_PIE is not configured");
580 			err = EINVAL;
581 			break;
582 		}
583 
584 		q->aqm_status = malloc(sizeof(struct pie_status),
585 				 M_DUMMYNET, M_NOWAIT | M_ZERO);
586 		if (q->aqm_status == NULL) {
587 			D("cannot allocate PIE private data");
588 			err =  ENOMEM ;
589 			break;
590 		}
591 
592 		pst = q->aqm_status;
593 		/* increase reference count for PIE module */
594 		pie_desc.ref_count++;
595 
596 		pst->pq = q;
597 		pst->parms = pprms;
598 
599 		/* For speed optimization, we caculate 1/3 queue size once here */
600 		// we can use x/3 = (x >>2) + (x >>4) + (x >>7)
601 		pst->one_third_q_size = q->fs->fs.qsize/3;
602 
603 		mtx_init(&pst->lock_mtx, "mtx_pie", NULL, MTX_DEF);
604 		callout_init_mtx(&pst->aqm_pie_callout, &pst->lock_mtx,
605 			CALLOUT_RETURNUNLOCKED);
606 
607 		pst->current_qdelay = 0;
608 		init_activate_pie(pst, !(pprms->flags & PIE_ON_OFF_MODE_ENABLED));
609 
610 		//DX(2, "aqm_PIE_init");
611 
612 	} while(0);
613 
614 	return err;
615 }
616 
617 /*
618  * Clean up PIE status for queue 'q'
619  * Destroy memory allocated for PIE status.
620  */
621 static int
622 aqm_pie_cleanup(struct dn_queue *q)
623 {
624 
625 	if(!q) {
626 		D("q is null");
627 		return 0;
628 	}
629 	struct pie_status *pst  = q->aqm_status;
630 	if(!pst) {
631 		//D("queue is already cleaned up");
632 		return 0;
633 	}
634 	if(!q->fs || !q->fs->aqmcfg) {
635 		D("fs is null or no cfg");
636 		return 1;
637 	}
638 	if (q->fs->aqmfp && q->fs->aqmfp->type !=DN_AQM_PIE) {
639 		D("Not PIE fs (%d)", q->fs->fs.fs_nr);
640 		return 1;
641 	}
642 
643 	mtx_lock(&pst->lock_mtx);
644 
645 	/* stop callout timer */
646 	if (callout_stop(&pst->aqm_pie_callout) || !(pst->sflags & PIE_ACTIVE)) {
647 		mtx_unlock(&pst->lock_mtx);
648 		mtx_destroy(&pst->lock_mtx);
649 		free(q->aqm_status, M_DUMMYNET);
650 		q->aqm_status = NULL;
651 		pie_desc.ref_count--;
652 		return 0;
653 	} else {
654 		q->aqm_status = NULL;
655 		mtx_unlock(&pst->lock_mtx);
656 		DX(2, "PIE callout has not been stoped from cleanup!");
657 		return EBUSY;
658 	}
659 	return 0;
660 }
661 
662 /*
663  * Config PIE parameters
664  * also allocate memory for PIE configurations
665  */
666 static int
667 aqm_pie_config(struct dn_fsk* fs, struct dn_extra_parms *ep, int len)
668 {
669 	struct dn_aqm_pie_parms *pcfg;
670 
671 	int l = sizeof(struct dn_extra_parms);
672 	if (len < l) {
673 		D("invalid sched parms length got %d need %d", len, l);
674 		return EINVAL;
675 	}
676 	/* we free the old cfg because maybe the orignal allocation
677 	 * was used for diffirent AQM type.
678 	 */
679 	if (fs->aqmcfg) {
680 		free(fs->aqmcfg, M_DUMMYNET);
681 		fs->aqmcfg = NULL;
682 	}
683 
684 	fs->aqmcfg = malloc(sizeof(struct dn_aqm_pie_parms),
685 			 M_DUMMYNET, M_NOWAIT | M_ZERO);
686 	if (fs->aqmcfg== NULL) {
687 		D("cannot allocate PIE configuration parameters");
688 		return ENOMEM;
689 	}
690 
691 	/* par array contains pie configuration as follow
692 	 * 0- qdelay_ref,1- tupdate, 2- max_burst
693 	 * 3- max_ecnth, 4- alpha, 5- beta, 6- flags
694 	 */
695 
696 	/* configure PIE parameters */
697 	pcfg = fs->aqmcfg;
698 
699 	if (ep->par[0] < 0)
700 		pcfg->qdelay_ref = pie_sysctl.qdelay_ref * AQM_TIME_1US;
701 	else
702 		pcfg->qdelay_ref = ep->par[0];
703 	if (ep->par[1] < 0)
704 		pcfg->tupdate = pie_sysctl.tupdate * AQM_TIME_1US;
705 	else
706 		pcfg->tupdate = ep->par[1];
707 	if (ep->par[2] < 0)
708 		pcfg->max_burst = pie_sysctl.max_burst * AQM_TIME_1US;
709 	else
710 		pcfg->max_burst = ep->par[2];
711 	if (ep->par[3] < 0)
712 		pcfg->max_ecnth = pie_sysctl.max_ecnth;
713 	else
714 		pcfg->max_ecnth = ep->par[3];
715 	if (ep->par[4] < 0)
716 		pcfg->alpha = pie_sysctl.alpha;
717 	else
718 		pcfg->alpha = ep->par[4];
719 	if (ep->par[5] < 0)
720 		pcfg->beta = pie_sysctl.beta;
721 	else
722 		pcfg->beta = ep->par[5];
723 	if (ep->par[6] < 0)
724 		pcfg->flags = pie_sysctl.flags;
725 	else
726 		pcfg->flags = ep->par[6];
727 
728 	/* bound PIE configurations */
729 	pcfg->qdelay_ref = BOUND_VAR(pcfg->qdelay_ref, 1, 10 * AQM_TIME_1S);
730 	pcfg->tupdate = BOUND_VAR(pcfg->tupdate, 1, 10 * AQM_TIME_1S);
731 	pcfg->max_burst = BOUND_VAR(pcfg->max_burst, 0, 10 * AQM_TIME_1S);
732 	pcfg->max_ecnth = BOUND_VAR(pcfg->max_ecnth, 0, PIE_SCALE);
733 	pcfg->alpha = BOUND_VAR(pcfg->alpha, 0, 7 * PIE_SCALE);
734 	pcfg->beta = BOUND_VAR(pcfg->beta, 0 , 7 * PIE_SCALE);
735 
736 	pie_desc.cfg_ref_count++;
737 	//D("pie cfg_ref_count=%d", pie_desc.cfg_ref_count);
738 	return 0;
739 }
740 
741 /*
742  * Deconfigure PIE and free memory allocation
743  */
744 static int
745 aqm_pie_deconfig(struct dn_fsk* fs)
746 {
747 	if (fs && fs->aqmcfg) {
748 		free(fs->aqmcfg, M_DUMMYNET);
749 		fs->aqmcfg = NULL;
750 		pie_desc.cfg_ref_count--;
751 	}
752 	return 0;
753 }
754 
755 /*
756  * Retrieve PIE configuration parameters.
757  */
758 static int
759 aqm_pie_getconfig (struct dn_fsk *fs, struct dn_extra_parms * ep)
760 {
761 	struct dn_aqm_pie_parms *pcfg;
762 	if (fs->aqmcfg) {
763 		strcpy(ep->name, pie_desc.name);
764 		pcfg = fs->aqmcfg;
765 		ep->par[0] = pcfg->qdelay_ref / AQM_TIME_1US;
766 		ep->par[1] = pcfg->tupdate / AQM_TIME_1US;
767 		ep->par[2] = pcfg->max_burst / AQM_TIME_1US;
768 		ep->par[3] = pcfg->max_ecnth;
769 		ep->par[4] = pcfg->alpha;
770 		ep->par[5] = pcfg->beta;
771 		ep->par[6] = pcfg->flags;
772 
773 		return 0;
774 	}
775 	return 1;
776 }
777 
778 static struct dn_aqm pie_desc = {
779 	_SI( .type = )  DN_AQM_PIE,
780 	_SI( .name = )  "PIE",
781 	_SI( .ref_count = )  0,
782 	_SI( .cfg_ref_count = )  0,
783 	_SI( .enqueue = )  aqm_pie_enqueue,
784 	_SI( .dequeue = )  aqm_pie_dequeue,
785 	_SI( .config = )  aqm_pie_config,
786 	_SI( .deconfig = )  aqm_pie_deconfig,
787 	_SI( .getconfig = )  aqm_pie_getconfig,
788 	_SI( .init = )  aqm_pie_init,
789 	_SI( .cleanup = )  aqm_pie_cleanup,
790 };
791 
792 DECLARE_DNAQM_MODULE(dn_aqm_pie, &pie_desc);
793 #endif
794