xref: /freebsd/sys/netpfil/ipfw/dn_aqm_pie.c (revision dd41de95a84d979615a2ef11df6850622bf6184e)
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, pie,
166     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
167     "PIE");
168 
169 #ifdef SYSCTL_NODE
170 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, target,
171     CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
172     pie_sysctl_target_tupdate_maxb_handler, "L",
173     "queue target in microsecond");
174 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, tupdate,
175     CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
176     pie_sysctl_target_tupdate_maxb_handler, "L",
177     "the frequency of drop probability calculation in microsecond");
178 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, max_burst,
179     CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
180     pie_sysctl_target_tupdate_maxb_handler, "L",
181     "Burst allowance interval in microsecond");
182 
183 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, max_ecnth,
184     CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
185     pie_sysctl_max_ecnth_handler, "L",
186     "ECN safeguard threshold scaled by 1000");
187 
188 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, alpha,
189     CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
190     pie_sysctl_alpha_beta_handler, "L",
191     "PIE alpha scaled by 1000");
192 SYSCTL_PROC(_net_inet_ip_dummynet_pie, OID_AUTO, beta,
193     CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
194     pie_sysctl_alpha_beta_handler, "L",
195     "beta scaled by 1000");
196 #endif
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 	int p_isneg;
210 
211 	pprms = pst->parms;
212 	prob = pst->drop_prob;
213 
214 	/* calculate current qdelay using DRE method.
215 	 * If TS is used and no data in the queue, reset current_qdelay
216 	 * as it stays at last value during dequeue process.
217 	*/
218 	if (pprms->flags & PIE_DEPRATEEST_ENABLED)
219 		pst->current_qdelay = ((uint64_t)pst->pq->ni.len_bytes *
220 			pst->avg_dq_time) >> PIE_DQ_THRESHOLD_BITS;
221 	else
222 		if (!pst->pq->ni.len_bytes)
223 			 pst->current_qdelay = 0;
224 
225 	/* calculate drop probability */
226 	p = (int64_t)pprms->alpha *
227 		((int64_t)pst->current_qdelay - (int64_t)pprms->qdelay_ref);
228 	p +=(int64_t) pprms->beta *
229 		((int64_t)pst->current_qdelay - (int64_t)pst->qdelay_old);
230 
231 	/* take absolute value so right shift result is well defined */
232 	p_isneg = p < 0;
233 	if (p_isneg) {
234 		p = -p;
235 	}
236 
237 	/* We PIE_MAX_PROB shift by 12-bits to increase the division precision */
238 	p *= (PIE_MAX_PROB << 12) / AQM_TIME_1S;
239 
240 	/* auto-tune drop probability */
241 	if (prob < (PIE_MAX_PROB / 1000000)) /* 0.000001 */
242 		p >>= 11 + PIE_FIX_POINT_BITS + 12;
243 	else if (prob < (PIE_MAX_PROB / 100000)) /* 0.00001 */
244 		p >>= 9 + PIE_FIX_POINT_BITS + 12;
245 	else if (prob < (PIE_MAX_PROB / 10000)) /* 0.0001 */
246 		p >>= 7 + PIE_FIX_POINT_BITS + 12;
247 	else if (prob < (PIE_MAX_PROB / 1000)) /* 0.001 */
248 		p >>= 5 + PIE_FIX_POINT_BITS + 12;
249 	else if (prob < (PIE_MAX_PROB / 100)) /* 0.01 */
250 		p >>= 3 + PIE_FIX_POINT_BITS + 12;
251 	else if (prob < (PIE_MAX_PROB / 10)) /* 0.1 */
252 		p >>= 1 + PIE_FIX_POINT_BITS + 12;
253 	else
254 		p >>= PIE_FIX_POINT_BITS + 12;
255 
256 	oldprob = prob;
257 
258 	if (p_isneg) {
259 		prob = prob - p;
260 
261 		/* check for multiplication underflow */
262 		if (prob > oldprob) {
263 			prob= 0;
264 			D("underflow");
265 		}
266 	} else {
267 		/* Cap Drop adjustment */
268 		if ((pprms->flags & PIE_CAPDROP_ENABLED) &&
269 		    prob >= PIE_MAX_PROB / 10 &&
270 		    p > PIE_MAX_PROB / 50 ) {
271 			p = PIE_MAX_PROB / 50;
272 		}
273 
274 		prob = prob + p;
275 
276 		/* check for multiplication overflow */
277 		if (prob<oldprob) {
278 			D("overflow");
279 			prob= PIE_MAX_PROB;
280 		}
281 	}
282 
283 	/*
284 	 * decay the drop probability exponentially
285 	 * and restrict it to range 0 to PIE_MAX_PROB
286 	 */
287 	if (prob < 0) {
288 		prob = 0;
289 	} else {
290 		if (pst->current_qdelay == 0 && pst->qdelay_old == 0) {
291 			/* 0.98 ~= 1- 1/64 */
292 			prob = prob - (prob >> 6);
293 		}
294 
295 		if (prob > PIE_MAX_PROB) {
296 			prob = PIE_MAX_PROB;
297 		}
298 	}
299 
300 	pst->drop_prob = prob;
301 
302 	/* store current queue delay value in old queue delay*/
303 	pst->qdelay_old = pst->current_qdelay;
304 
305 	/* update burst allowance */
306 	if ((pst->sflags & PIE_ACTIVE) && pst->burst_allowance>0) {
307 
308 		if (pst->burst_allowance > pprms->tupdate )
309 			pst->burst_allowance -= pprms->tupdate;
310 		else
311 			pst->burst_allowance = 0;
312 	}
313 
314 	/* reschedule calculate_drop_prob function */
315 	if (pst->sflags & PIE_ACTIVE)
316 		callout_reset_sbt(&pst->aqm_pie_callout,
317 			(uint64_t)pprms->tupdate * SBT_1US, 0, calculate_drop_prob, pst, 0);
318 
319 	mtx_unlock(&pst->lock_mtx);
320 }
321 
322 /*
323  * Extract a packet from the head of queue 'q'
324  * Return a packet or NULL if the queue is empty.
325  * If getts is set, also extract packet's timestamp from mtag.
326  */
327 static struct mbuf *
328 pie_extract_head(struct dn_queue *q, aqm_time_t *pkt_ts, int getts)
329 {
330 	struct m_tag *mtag;
331 	struct mbuf *m = q->mq.head;
332 
333 	if (m == NULL)
334 		return m;
335 	q->mq.head = m->m_nextpkt;
336 
337 	/* Update stats */
338 	update_stats(q, -m->m_pkthdr.len, 0);
339 
340 	if (q->ni.length == 0) /* queue is now idle */
341 			q->q_time = dn_cfg.curr_time;
342 
343 	if (getts) {
344 		/* extract packet TS*/
345 		mtag = m_tag_locate(m, MTAG_ABI_COMPAT, DN_AQM_MTAG_TS, NULL);
346 		if (mtag == NULL) {
347 			D("PIE timestamp mtag not found!");
348 			*pkt_ts = 0;
349 		} else {
350 			*pkt_ts = *(aqm_time_t *)(mtag + 1);
351 			m_tag_delete(m,mtag);
352 		}
353 	}
354 	return m;
355 }
356 
357 /*
358  * Initiate PIE  variable and optionally activate it
359  */
360 __inline static void
361 init_activate_pie(struct pie_status *pst, int resettimer)
362 {
363 	struct dn_aqm_pie_parms *pprms;
364 
365 	mtx_lock(&pst->lock_mtx);
366 	pprms = pst->parms;
367 	pst->drop_prob = 0;
368 	pst->qdelay_old = 0;
369 	pst->burst_allowance = pprms->max_burst;
370 	pst->accu_prob = 0;
371 	pst->dq_count = 0;
372 	pst->avg_dq_time = 0;
373 	pst->sflags = PIE_INMEASUREMENT;
374 	pst->measurement_start = AQM_UNOW;
375 
376 	if (resettimer) {
377 		pst->sflags |= PIE_ACTIVE;
378 		callout_reset_sbt(&pst->aqm_pie_callout,
379 			(uint64_t)pprms->tupdate * SBT_1US,
380 			0, calculate_drop_prob, pst, 0);
381 	}
382 	//DX(2, "PIE Activated");
383 	mtx_unlock(&pst->lock_mtx);
384 }
385 
386 /*
387  * Deactivate PIE and stop probe update callout
388  */
389 __inline static void
390 deactivate_pie(struct pie_status *pst)
391 {
392 	mtx_lock(&pst->lock_mtx);
393 	pst->sflags &= ~(PIE_ACTIVE | PIE_INMEASUREMENT);
394 	callout_stop(&pst->aqm_pie_callout);
395 	//D("PIE Deactivated");
396 	mtx_unlock(&pst->lock_mtx);
397 }
398 
399 /*
400  * Dequeue and return a pcaket from queue 'q' or NULL if 'q' is empty.
401  * Also, caculate depature time or queue delay using timestamp
402  */
403 static struct mbuf *
404 aqm_pie_dequeue(struct dn_queue *q)
405 {
406 	struct mbuf *m;
407 	struct dn_flow *ni;	/* stats for scheduler instance */
408 	struct dn_aqm_pie_parms *pprms;
409 	struct pie_status *pst;
410 	aqm_time_t now;
411 	aqm_time_t pkt_ts, dq_time;
412 	int32_t w;
413 
414 	pst  = q->aqm_status;
415 	pprms = pst->parms;
416 	ni = &q->_si->ni;
417 
418 	/*we extarct packet ts only when Departure Rate Estimation dis not used*/
419 	m = pie_extract_head(q, &pkt_ts, !(pprms->flags & PIE_DEPRATEEST_ENABLED));
420 
421 	if (!m || !(pst->sflags & PIE_ACTIVE))
422 		return m;
423 
424 	now = AQM_UNOW;
425 	if (pprms->flags & PIE_DEPRATEEST_ENABLED) {
426 		/* calculate average depature time */
427 		if(pst->sflags & PIE_INMEASUREMENT) {
428 			pst->dq_count += m->m_pkthdr.len;
429 
430 			if (pst->dq_count >= PIE_DQ_THRESHOLD) {
431 				dq_time = now - pst->measurement_start;
432 
433 				/*
434 				 * if we don't have old avg dq_time i.e PIE is (re)initialized,
435 				 * don't use weight to calculate new avg_dq_time
436 				 */
437 				if(pst->avg_dq_time == 0)
438 					pst->avg_dq_time = dq_time;
439 				else {
440 					/*
441 					 * weight = PIE_DQ_THRESHOLD/2^6, but we scaled
442 					 * weight by 2^8. Thus, scaled
443 					 * weight = PIE_DQ_THRESHOLD /2^8
444 					 * */
445 					w = PIE_DQ_THRESHOLD >> 8;
446 					pst->avg_dq_time = (dq_time* w
447 						+ (pst->avg_dq_time * ((1L << 8) - w))) >> 8;
448 					pst->sflags &= ~PIE_INMEASUREMENT;
449 				}
450 			}
451 		}
452 
453 		/*
454 		 * Start new measurment cycle when the queue has
455 		 *  PIE_DQ_THRESHOLD worth of bytes.
456 		 */
457 		if(!(pst->sflags & PIE_INMEASUREMENT) &&
458 			q->ni.len_bytes >= PIE_DQ_THRESHOLD) {
459 			pst->sflags |= PIE_INMEASUREMENT;
460 			pst->measurement_start = now;
461 			pst->dq_count = 0;
462 		}
463 	}
464 	/* Optionally, use packet timestamp to estimate queue delay */
465 	else
466 		pst->current_qdelay = now - pkt_ts;
467 
468 	return m;
469 }
470 
471 /*
472  * Enqueue a packet in q, subject to space and  PIE queue management policy
473  * (whose parameters are in q->fs).
474  * Update stats for the queue and the scheduler.
475  * Return 0 on success, 1 on drop. The packet is consumed anyways.
476  */
477 static int
478 aqm_pie_enqueue(struct dn_queue *q, struct mbuf* m)
479 {
480 	struct dn_fs *f;
481 	uint64_t len;
482 	uint32_t qlen;
483 	struct pie_status *pst;
484 	struct dn_aqm_pie_parms *pprms;
485 	int t;
486 
487 	len = m->m_pkthdr.len;
488 	pst  = q->aqm_status;
489 	if(!pst) {
490 		DX(2, "PIE queue is not initialized\n");
491 		update_stats(q, 0, 1);
492 		FREE_PKT(m);
493 		return 1;
494 	}
495 
496 	f = &(q->fs->fs);
497 	pprms = pst->parms;
498 	t = ENQUE;
499 
500 	/* get current queue length in bytes or packets*/
501 	qlen = (f->flags & DN_QSIZE_BYTES) ?
502 		q->ni.len_bytes : q->ni.length;
503 
504 	/* check for queue size and drop the tail if exceed queue limit*/
505 	if (qlen >= f->qsize)
506 		t = DROP;
507 	/* drop/mark the packet when PIE is active and burst time elapsed */
508 	else if ((pst->sflags & PIE_ACTIVE) && pst->burst_allowance==0
509 			&& drop_early(pst, q->ni.len_bytes) == DROP) {
510 				/*
511 				 * if drop_prob over ECN threshold, drop the packet
512 				 * otherwise mark and enqueue it.
513 				 */
514 				if ((pprms->flags & PIE_ECN_ENABLED) && pst->drop_prob <
515 					(pprms->max_ecnth << (PIE_PROB_BITS - PIE_FIX_POINT_BITS))
516 					&& ecn_mark(m))
517 					t = ENQUE;
518 				else
519 					t = DROP;
520 	}
521 
522 	/* Turn PIE on when 1/3 of the queue is full */
523 	if (!(pst->sflags & PIE_ACTIVE) && qlen >= pst->one_third_q_size) {
524 		init_activate_pie(pst, 1);
525 	}
526 
527 	/*  Reset burst tolerance and optinally turn PIE off*/
528 	if ((pst->sflags & PIE_ACTIVE) && pst->drop_prob == 0 &&
529 		pst->current_qdelay < (pprms->qdelay_ref >> 1) &&
530 		pst->qdelay_old < (pprms->qdelay_ref >> 1)) {
531 			pst->burst_allowance = pprms->max_burst;
532 			if ((pprms->flags & PIE_ON_OFF_MODE_ENABLED) && qlen<=0)
533 				deactivate_pie(pst);
534 	}
535 
536 	/* Timestamp the packet if Departure Rate Estimation is disabled */
537 	if (t != DROP && !(pprms->flags & PIE_DEPRATEEST_ENABLED)) {
538 		/* Add TS to mbuf as a TAG */
539 		struct m_tag *mtag;
540 		mtag = m_tag_locate(m, MTAG_ABI_COMPAT, DN_AQM_MTAG_TS, NULL);
541 		if (mtag == NULL)
542 			mtag = m_tag_alloc(MTAG_ABI_COMPAT, DN_AQM_MTAG_TS,
543 				sizeof(aqm_time_t), M_NOWAIT);
544 		if (mtag == NULL) {
545 			t = DROP;
546 		} else {
547 			*(aqm_time_t *)(mtag + 1) = AQM_UNOW;
548 			m_tag_prepend(m, mtag);
549 		}
550 	}
551 
552 	if (t != DROP) {
553 		mq_append(&q->mq, m);
554 		update_stats(q, len, 0);
555 		return (0);
556 	} else {
557 		update_stats(q, 0, 1);
558 
559 		/* reset accu_prob after packet drop */
560 		pst->accu_prob = 0;
561 		FREE_PKT(m);
562 		return 1;
563 	}
564 	return 0;
565 }
566 
567 /*
568  * initialize PIE for queue 'q'
569  * First allocate memory for PIE status.
570  */
571 static int
572 aqm_pie_init(struct dn_queue *q)
573 {
574 	struct pie_status *pst;
575 	struct dn_aqm_pie_parms *pprms;
576 	int err = 0;
577 
578 	pprms = q->fs->aqmcfg;
579 
580 	do { /* exit with break when error occurs*/
581 		if (!pprms){
582 			DX(2, "AQM_PIE is not configured");
583 			err = EINVAL;
584 			break;
585 		}
586 
587 		q->aqm_status = malloc(sizeof(struct pie_status),
588 				 M_DUMMYNET, M_NOWAIT | M_ZERO);
589 		if (q->aqm_status == NULL) {
590 			D("cannot allocate PIE private data");
591 			err =  ENOMEM ;
592 			break;
593 		}
594 
595 		pst = q->aqm_status;
596 		/* increase reference count for PIE module */
597 		pie_desc.ref_count++;
598 
599 		pst->pq = q;
600 		pst->parms = pprms;
601 
602 		/* For speed optimization, we caculate 1/3 queue size once here */
603 		// we can use x/3 = (x >>2) + (x >>4) + (x >>7)
604 		pst->one_third_q_size = q->fs->fs.qsize/3;
605 
606 		mtx_init(&pst->lock_mtx, "mtx_pie", NULL, MTX_DEF);
607 		callout_init_mtx(&pst->aqm_pie_callout, &pst->lock_mtx,
608 			CALLOUT_RETURNUNLOCKED);
609 
610 		pst->current_qdelay = 0;
611 		init_activate_pie(pst, !(pprms->flags & PIE_ON_OFF_MODE_ENABLED));
612 
613 		//DX(2, "aqm_PIE_init");
614 
615 	} while(0);
616 
617 	return err;
618 }
619 
620 /*
621  * Callout function to destroy pie mtx and free PIE status memory
622  */
623 static void
624 pie_callout_cleanup(void *x)
625 {
626 	struct pie_status *pst = (struct pie_status *) x;
627 
628 	mtx_unlock(&pst->lock_mtx);
629 	mtx_destroy(&pst->lock_mtx);
630 	free(x, M_DUMMYNET);
631 	DN_BH_WLOCK();
632 	pie_desc.ref_count--;
633 	DN_BH_WUNLOCK();
634 }
635 
636 /*
637  * Clean up PIE status for queue 'q'
638  * Destroy memory allocated for PIE status.
639  */
640 static int
641 aqm_pie_cleanup(struct dn_queue *q)
642 {
643 
644 	if(!q) {
645 		D("q is null");
646 		return 0;
647 	}
648 	struct pie_status *pst  = q->aqm_status;
649 	if(!pst) {
650 		//D("queue is already cleaned up");
651 		return 0;
652 	}
653 	if(!q->fs || !q->fs->aqmcfg) {
654 		D("fs is null or no cfg");
655 		return 1;
656 	}
657 	if (q->fs->aqmfp && q->fs->aqmfp->type !=DN_AQM_PIE) {
658 		D("Not PIE fs (%d)", q->fs->fs.fs_nr);
659 		return 1;
660 	}
661 
662 	/*
663 	 * Free PIE status allocated memory using pie_callout_cleanup() callout
664 	 * function to avoid any potential race.
665 	 * We reset aqm_pie_callout to call pie_callout_cleanup() in next 1um. This
666 	 * stops the scheduled calculate_drop_prob() callout and call pie_callout_cleanup()
667 	 * which does memory freeing.
668 	 */
669 	mtx_lock(&pst->lock_mtx);
670 	callout_reset_sbt(&pst->aqm_pie_callout,
671 		SBT_1US, 0, pie_callout_cleanup, pst, 0);
672 	q->aqm_status = NULL;
673 	mtx_unlock(&pst->lock_mtx);
674 
675 	return 0;
676 }
677 
678 /*
679  * Config PIE parameters
680  * also allocate memory for PIE configurations
681  */
682 static int
683 aqm_pie_config(struct dn_fsk* fs, struct dn_extra_parms *ep, int len)
684 {
685 	struct dn_aqm_pie_parms *pcfg;
686 
687 	int l = sizeof(struct dn_extra_parms);
688 	if (len < l) {
689 		D("invalid sched parms length got %d need %d", len, l);
690 		return EINVAL;
691 	}
692 	/* we free the old cfg because maybe the orignal allocation
693 	 * was used for diffirent AQM type.
694 	 */
695 	if (fs->aqmcfg) {
696 		free(fs->aqmcfg, M_DUMMYNET);
697 		fs->aqmcfg = NULL;
698 	}
699 
700 	fs->aqmcfg = malloc(sizeof(struct dn_aqm_pie_parms),
701 			 M_DUMMYNET, M_NOWAIT | M_ZERO);
702 	if (fs->aqmcfg== NULL) {
703 		D("cannot allocate PIE configuration parameters");
704 		return ENOMEM;
705 	}
706 
707 	/* par array contains pie configuration as follow
708 	 * 0- qdelay_ref,1- tupdate, 2- max_burst
709 	 * 3- max_ecnth, 4- alpha, 5- beta, 6- flags
710 	 */
711 
712 	/* configure PIE parameters */
713 	pcfg = fs->aqmcfg;
714 
715 	if (ep->par[0] < 0)
716 		pcfg->qdelay_ref = pie_sysctl.qdelay_ref * AQM_TIME_1US;
717 	else
718 		pcfg->qdelay_ref = ep->par[0];
719 	if (ep->par[1] < 0)
720 		pcfg->tupdate = pie_sysctl.tupdate * AQM_TIME_1US;
721 	else
722 		pcfg->tupdate = ep->par[1];
723 	if (ep->par[2] < 0)
724 		pcfg->max_burst = pie_sysctl.max_burst * AQM_TIME_1US;
725 	else
726 		pcfg->max_burst = ep->par[2];
727 	if (ep->par[3] < 0)
728 		pcfg->max_ecnth = pie_sysctl.max_ecnth;
729 	else
730 		pcfg->max_ecnth = ep->par[3];
731 	if (ep->par[4] < 0)
732 		pcfg->alpha = pie_sysctl.alpha;
733 	else
734 		pcfg->alpha = ep->par[4];
735 	if (ep->par[5] < 0)
736 		pcfg->beta = pie_sysctl.beta;
737 	else
738 		pcfg->beta = ep->par[5];
739 	if (ep->par[6] < 0)
740 		pcfg->flags = pie_sysctl.flags;
741 	else
742 		pcfg->flags = ep->par[6];
743 
744 	/* bound PIE configurations */
745 	pcfg->qdelay_ref = BOUND_VAR(pcfg->qdelay_ref, 1, 10 * AQM_TIME_1S);
746 	pcfg->tupdate = BOUND_VAR(pcfg->tupdate, 1, 10 * AQM_TIME_1S);
747 	pcfg->max_burst = BOUND_VAR(pcfg->max_burst, 0, 10 * AQM_TIME_1S);
748 	pcfg->max_ecnth = BOUND_VAR(pcfg->max_ecnth, 0, PIE_SCALE);
749 	pcfg->alpha = BOUND_VAR(pcfg->alpha, 0, 7 * PIE_SCALE);
750 	pcfg->beta = BOUND_VAR(pcfg->beta, 0 , 7 * PIE_SCALE);
751 
752 	pie_desc.cfg_ref_count++;
753 	//D("pie cfg_ref_count=%d", pie_desc.cfg_ref_count);
754 	return 0;
755 }
756 
757 /*
758  * Deconfigure PIE and free memory allocation
759  */
760 static int
761 aqm_pie_deconfig(struct dn_fsk* fs)
762 {
763 	if (fs && fs->aqmcfg) {
764 		free(fs->aqmcfg, M_DUMMYNET);
765 		fs->aqmcfg = NULL;
766 		pie_desc.cfg_ref_count--;
767 	}
768 	return 0;
769 }
770 
771 /*
772  * Retrieve PIE configuration parameters.
773  */
774 static int
775 aqm_pie_getconfig (struct dn_fsk *fs, struct dn_extra_parms * ep)
776 {
777 	struct dn_aqm_pie_parms *pcfg;
778 	if (fs->aqmcfg) {
779 		strlcpy(ep->name, pie_desc.name, sizeof(ep->name));
780 		pcfg = fs->aqmcfg;
781 		ep->par[0] = pcfg->qdelay_ref / AQM_TIME_1US;
782 		ep->par[1] = pcfg->tupdate / AQM_TIME_1US;
783 		ep->par[2] = pcfg->max_burst / AQM_TIME_1US;
784 		ep->par[3] = pcfg->max_ecnth;
785 		ep->par[4] = pcfg->alpha;
786 		ep->par[5] = pcfg->beta;
787 		ep->par[6] = pcfg->flags;
788 
789 		return 0;
790 	}
791 	return 1;
792 }
793 
794 static struct dn_aqm pie_desc = {
795 	_SI( .type = )  DN_AQM_PIE,
796 	_SI( .name = )  "PIE",
797 	_SI( .ref_count = )  0,
798 	_SI( .cfg_ref_count = )  0,
799 	_SI( .enqueue = )  aqm_pie_enqueue,
800 	_SI( .dequeue = )  aqm_pie_dequeue,
801 	_SI( .config = )  aqm_pie_config,
802 	_SI( .deconfig = )  aqm_pie_deconfig,
803 	_SI( .getconfig = )  aqm_pie_getconfig,
804 	_SI( .init = )  aqm_pie_init,
805 	_SI( .cleanup = )  aqm_pie_cleanup,
806 };
807 
808 DECLARE_DNAQM_MODULE(dn_aqm_pie, &pie_desc);
809 #endif
810