Path: blob/main/sys/netpfil/ipfw/dn_sched_fq_pie.c
39482 views
/*1* FQ_PIE - The FlowQueue-PIE scheduler/AQM2*3* Copyright (C) 2016 Centre for Advanced Internet Architectures,4* Swinburne University of Technology, Melbourne, Australia.5* Portions of this code were made possible in part by a gift from6* The Comcast Innovation Fund.7* Implemented by Rasool Al-Saadi <[email protected]>8*9* Redistribution and use in source and binary forms, with or without10* modification, are permitted provided that the following conditions11* are met:12* 1. Redistributions of source code must retain the above copyright13* notice, this list of conditions and the following disclaimer.14* 2. Redistributions in binary form must reproduce the above copyright15* notice, this list of conditions and the following disclaimer in the16* documentation and/or other materials provided with the distribution.17*18* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND19* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE20* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE21* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE22* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL23* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS24* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)25* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT26* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY27* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF28* SUCH DAMAGE.29*/3031/* Important note:32* As there is no an office document for FQ-PIE specification, we used33* FQ-CoDel algorithm with some modifications to implement FQ-PIE.34* This FQ-PIE implementation is a beta version and have not been tested35* extensively. Our FQ-PIE uses stand-alone PIE AQM per sub-queue. By36* default, timestamp is used to calculate queue delay instead of departure37* rate estimation method. Although departure rate estimation is available38* as testing option, the results could be incorrect. Moreover, turning PIE on39* and off option is available but it does not work properly in this version.40*/4142#ifdef _KERNEL43#include <sys/malloc.h>44#include <sys/socket.h>45#include <sys/kernel.h>46#include <sys/mbuf.h>47#include <sys/lock.h>48#include <sys/module.h>49#include <sys/mutex.h>50#include <net/if.h> /* IFNAMSIZ */51#include <netinet/in.h>52#include <netinet/ip_var.h> /* ipfw_rule_ref */53#include <netinet/ip_fw.h> /* flow_id */54#include <netinet/ip_dummynet.h>5556#include <sys/proc.h>57#include <sys/rwlock.h>5859#include <netpfil/ipfw/ip_fw_private.h>60#include <sys/sysctl.h>61#include <netinet/ip.h>62#include <netinet/ip6.h>63#include <netinet/ip_icmp.h>64#include <netinet/tcp.h>65#include <netinet/udp.h>66#include <sys/queue.h>67#include <sys/hash.h>6869#include <netpfil/ipfw/dn_heap.h>70#include <netpfil/ipfw/ip_dn_private.h>7172#include <netpfil/ipfw/dn_aqm.h>73#include <netpfil/ipfw/dn_aqm_pie.h>74#include <netpfil/ipfw/dn_sched.h>7576#else77#include <dn_test.h>78#endif7980#define DN_SCHED_FQ_PIE 78182/* list of queues */83STAILQ_HEAD(fq_pie_list, fq_pie_flow);8485/* FQ_PIE parameters including PIE */86struct dn_sch_fq_pie_parms {87struct dn_aqm_pie_parms pcfg; /* PIE configuration Parameters */88/* FQ_PIE Parameters */89uint32_t flows_cnt; /* number of flows */90uint32_t limit; /* hard limit of FQ_PIE queue size*/91uint32_t quantum;92};9394/* flow (sub-queue) stats */95struct flow_stats {96uint64_t tot_pkts; /* statistics counters */97uint64_t tot_bytes;98uint32_t length; /* Queue length, in packets */99uint32_t len_bytes; /* Queue length, in bytes */100uint32_t drops;101};102103/* A flow of packets (sub-queue)*/104struct fq_pie_flow {105struct mq mq; /* list of packets */106struct flow_stats stats; /* statistics */107int deficit;108int active; /* 1: flow is active (in a list) */109struct pie_status pst; /* pie status variables */110struct fq_pie_si_extra *psi_extra;111STAILQ_ENTRY(fq_pie_flow) flowchain;112};113114/* extra fq_pie scheduler configurations */115struct fq_pie_schk {116struct dn_sch_fq_pie_parms cfg;117};118119/* fq_pie scheduler instance extra state vars.120* The purpose of separation this structure is to preserve number of active121* sub-queues and the flows array pointer even after the scheduler instance122* is destroyed.123* Preserving these varaiables allows freeing the allocated memory by124* fqpie_callout_cleanup() independently from fq_pie_free_sched().125*/126struct fq_pie_si_extra {127uint32_t nr_active_q; /* number of active queues */128struct fq_pie_flow *flows; /* array of flows (queues) */129};130131/* fq_pie scheduler instance */132struct fq_pie_si {133struct dn_sch_inst _si; /* standard scheduler instance. SHOULD BE FIRST */134struct dn_queue main_q; /* main queue is after si directly */135uint32_t perturbation; /* random value */136struct fq_pie_list newflows; /* list of new queues */137struct fq_pie_list oldflows; /* list of old queues */138struct fq_pie_si_extra *si_extra; /* extra state vars*/139};140141static struct dn_alg fq_pie_desc;142143/* Default FQ-PIE parameters including PIE */144/* PIE defaults145* target=15ms, max_burst=150ms, max_ecnth=0.1,146* alpha=0.125, beta=1.25, tupdate=15ms147* FQ-148* flows=1024, limit=10240, quantum =1514149*/150struct dn_sch_fq_pie_parms151fq_pie_sysctl = {{15000 * AQM_TIME_1US, 15000 * AQM_TIME_1US,152150000 * AQM_TIME_1US, PIE_SCALE * 0.1, PIE_SCALE * 0.125,153PIE_SCALE * 1.25, PIE_CAPDROP_ENABLED | PIE_DERAND_ENABLED},1541024, 10240, 1514};155156static int157fqpie_sysctl_alpha_beta_handler(SYSCTL_HANDLER_ARGS)158{159int error;160long value;161162if (!strcmp(oidp->oid_name,"alpha"))163value = fq_pie_sysctl.pcfg.alpha;164else165value = fq_pie_sysctl.pcfg.beta;166167value = value * 1000 / PIE_SCALE;168error = sysctl_handle_long(oidp, &value, 0, req);169if (error != 0 || req->newptr == NULL)170return (error);171if (value < 1 || value > 7 * PIE_SCALE)172return (EINVAL);173value = (value * PIE_SCALE) / 1000;174if (!strcmp(oidp->oid_name,"alpha"))175fq_pie_sysctl.pcfg.alpha = value;176else177fq_pie_sysctl.pcfg.beta = value;178return (0);179}180181static int182fqpie_sysctl_target_tupdate_maxb_handler(SYSCTL_HANDLER_ARGS)183{184int error;185long value;186187if (!strcmp(oidp->oid_name,"target"))188value = fq_pie_sysctl.pcfg.qdelay_ref;189else if (!strcmp(oidp->oid_name,"tupdate"))190value = fq_pie_sysctl.pcfg.tupdate;191else192value = fq_pie_sysctl.pcfg.max_burst;193194value = value / AQM_TIME_1US;195error = sysctl_handle_long(oidp, &value, 0, req);196if (error != 0 || req->newptr == NULL)197return (error);198if (value < 1 || value > 10 * AQM_TIME_1S)199return (EINVAL);200value = value * AQM_TIME_1US;201202if (!strcmp(oidp->oid_name,"target"))203fq_pie_sysctl.pcfg.qdelay_ref = value;204else if (!strcmp(oidp->oid_name,"tupdate"))205fq_pie_sysctl.pcfg.tupdate = value;206else207fq_pie_sysctl.pcfg.max_burst = value;208return (0);209}210211static int212fqpie_sysctl_max_ecnth_handler(SYSCTL_HANDLER_ARGS)213{214int error;215long value;216217value = fq_pie_sysctl.pcfg.max_ecnth;218value = value * 1000 / PIE_SCALE;219error = sysctl_handle_long(oidp, &value, 0, req);220if (error != 0 || req->newptr == NULL)221return (error);222if (value < 1 || value > PIE_SCALE)223return (EINVAL);224value = (value * PIE_SCALE) / 1000;225fq_pie_sysctl.pcfg.max_ecnth = value;226return (0);227}228229/* define FQ- PIE sysctl variables */230SYSBEGIN(f4)231SYSCTL_DECL(_net_inet);232SYSCTL_DECL(_net_inet_ip);233SYSCTL_DECL(_net_inet_ip_dummynet);234static SYSCTL_NODE(_net_inet_ip_dummynet, OID_AUTO, fqpie,235CTLFLAG_RW | CTLFLAG_MPSAFE, 0,236"FQ_PIE");237238#ifdef SYSCTL_NODE239240SYSCTL_PROC(_net_inet_ip_dummynet_fqpie, OID_AUTO, target,241CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,242fqpie_sysctl_target_tupdate_maxb_handler, "L",243"queue target in microsecond");244245SYSCTL_PROC(_net_inet_ip_dummynet_fqpie, OID_AUTO, tupdate,246CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,247fqpie_sysctl_target_tupdate_maxb_handler, "L",248"the frequency of drop probability calculation in microsecond");249250SYSCTL_PROC(_net_inet_ip_dummynet_fqpie, OID_AUTO, max_burst,251CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,252fqpie_sysctl_target_tupdate_maxb_handler, "L",253"Burst allowance interval in microsecond");254255SYSCTL_PROC(_net_inet_ip_dummynet_fqpie, OID_AUTO, max_ecnth,256CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,257fqpie_sysctl_max_ecnth_handler, "L",258"ECN safeguard threshold scaled by 1000");259260SYSCTL_PROC(_net_inet_ip_dummynet_fqpie, OID_AUTO, alpha,261CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,262fqpie_sysctl_alpha_beta_handler, "L",263"PIE alpha scaled by 1000");264265SYSCTL_PROC(_net_inet_ip_dummynet_fqpie, OID_AUTO, beta,266CTLTYPE_LONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,267fqpie_sysctl_alpha_beta_handler, "L",268"beta scaled by 1000");269270SYSCTL_UINT(_net_inet_ip_dummynet_fqpie, OID_AUTO, quantum,271CTLFLAG_RW, &fq_pie_sysctl.quantum, 1514, "quantum for FQ_PIE");272SYSCTL_UINT(_net_inet_ip_dummynet_fqpie, OID_AUTO, flows,273CTLFLAG_RW, &fq_pie_sysctl.flows_cnt, 1024, "Number of queues for FQ_PIE");274SYSCTL_UINT(_net_inet_ip_dummynet_fqpie, OID_AUTO, limit,275CTLFLAG_RW, &fq_pie_sysctl.limit, 10240, "limit for FQ_PIE");276#endif277278/* Helper function to update queue&main-queue and scheduler statistics.279* negative len & drop -> drop280* negative len -> dequeue281* positive len -> enqueue282* positive len + drop -> drop during enqueue283*/284__inline static void285fq_update_stats(struct fq_pie_flow *q, struct fq_pie_si *si, int len,286int drop)287{288int inc = 0;289290if (len < 0)291inc = -1;292else if (len > 0)293inc = 1;294295if (drop) {296si->main_q.ni.drops ++;297q->stats.drops ++;298si->_si.ni.drops ++;299V_dn_cfg.io_pkt_drop ++;300}301302if (!drop || (drop && len < 0)) {303/* Update stats for the main queue */304si->main_q.ni.length += inc;305si->main_q.ni.len_bytes += len;306307/*update sub-queue stats */308q->stats.length += inc;309q->stats.len_bytes += len;310311/*update scheduler instance stats */312si->_si.ni.length += inc;313si->_si.ni.len_bytes += len;314}315316if (inc > 0) {317si->main_q.ni.tot_bytes += len;318si->main_q.ni.tot_pkts ++;319320q->stats.tot_bytes +=len;321q->stats.tot_pkts++;322323si->_si.ni.tot_bytes +=len;324si->_si.ni.tot_pkts ++;325}326327}328329/*330* Extract a packet from the head of sub-queue 'q'331* Return a packet or NULL if the queue is empty.332* If getts is set, also extract packet's timestamp from mtag.333*/334__inline static struct mbuf *335fq_pie_extract_head(struct fq_pie_flow *q, aqm_time_t *pkt_ts,336struct fq_pie_si *si, int getts)337{338struct mbuf *m;339340next: m = q->mq.head;341if (m == NULL)342return m;343q->mq.head = m->m_nextpkt;344345fq_update_stats(q, si, -m->m_pkthdr.len, 0);346347if (si->main_q.ni.length == 0) /* queue is now idle */348si->main_q.q_time = V_dn_cfg.curr_time;349350if (getts) {351/* extract packet timestamp*/352struct m_tag *mtag;353mtag = m_tag_locate(m, MTAG_ABI_COMPAT, DN_AQM_MTAG_TS, NULL);354if (mtag == NULL){355D("PIE timestamp mtag not found!");356*pkt_ts = 0;357} else {358*pkt_ts = *(aqm_time_t *)(mtag + 1);359m_tag_delete(m,mtag);360}361}362if (m->m_pkthdr.rcvif != NULL &&363__predict_false(m_rcvif_restore(m) == NULL)) {364m_freem(m);365goto next;366}367return m;368}369370/*371* Callout function for drop probability calculation372* This function is called over tupdate ms and takes pointer of FQ-PIE373* flow as an argument374*/375static void376fq_calculate_drop_prob(void *x)377{378struct fq_pie_flow *q = (struct fq_pie_flow *) x;379struct pie_status *pst = &q->pst;380struct dn_aqm_pie_parms *pprms;381int64_t p, prob, oldprob;382int p_isneg;383384pprms = pst->parms;385prob = pst->drop_prob;386387/* calculate current qdelay using DRE method.388* If TS is used and no data in the queue, reset current_qdelay389* as it stays at last value during dequeue process.390*/391if (pprms->flags & PIE_DEPRATEEST_ENABLED)392pst->current_qdelay = ((uint64_t)q->stats.len_bytes * pst->avg_dq_time)393>> PIE_DQ_THRESHOLD_BITS;394else395if (!q->stats.len_bytes)396pst->current_qdelay = 0;397398/* calculate drop probability */399p = (int64_t)pprms->alpha *400((int64_t)pst->current_qdelay - (int64_t)pprms->qdelay_ref);401p +=(int64_t) pprms->beta *402((int64_t)pst->current_qdelay - (int64_t)pst->qdelay_old);403404/* take absolute value so right shift result is well defined */405p_isneg = p < 0;406if (p_isneg) {407p = -p;408}409410/* We PIE_MAX_PROB shift by 12-bits to increase the division precision */411p *= (PIE_MAX_PROB << 12) / AQM_TIME_1S;412413/* auto-tune drop probability */414if (prob < (PIE_MAX_PROB / 1000000)) /* 0.000001 */415p >>= 11 + PIE_FIX_POINT_BITS + 12;416else if (prob < (PIE_MAX_PROB / 100000)) /* 0.00001 */417p >>= 9 + PIE_FIX_POINT_BITS + 12;418else if (prob < (PIE_MAX_PROB / 10000)) /* 0.0001 */419p >>= 7 + PIE_FIX_POINT_BITS + 12;420else if (prob < (PIE_MAX_PROB / 1000)) /* 0.001 */421p >>= 5 + PIE_FIX_POINT_BITS + 12;422else if (prob < (PIE_MAX_PROB / 100)) /* 0.01 */423p >>= 3 + PIE_FIX_POINT_BITS + 12;424else if (prob < (PIE_MAX_PROB / 10)) /* 0.1 */425p >>= 1 + PIE_FIX_POINT_BITS + 12;426else427p >>= PIE_FIX_POINT_BITS + 12;428429oldprob = prob;430431if (p_isneg) {432prob = prob - p;433434/* check for multiplication underflow */435if (prob > oldprob) {436prob= 0;437D("underflow");438}439} else {440/* Cap Drop adjustment */441if ((pprms->flags & PIE_CAPDROP_ENABLED) &&442prob >= PIE_MAX_PROB / 10 &&443p > PIE_MAX_PROB / 50 ) {444p = PIE_MAX_PROB / 50;445}446447prob = prob + p;448449/* check for multiplication overflow */450if (prob<oldprob) {451D("overflow");452prob= PIE_MAX_PROB;453}454}455456/*457* decay the drop probability exponentially458* and restrict it to range 0 to PIE_MAX_PROB459*/460if (prob < 0) {461prob = 0;462} else {463if (pst->current_qdelay == 0 && pst->qdelay_old == 0) {464/* 0.98 ~= 1- 1/64 */465prob = prob - (prob >> 6);466}467468if (prob > PIE_MAX_PROB) {469prob = PIE_MAX_PROB;470}471}472473pst->drop_prob = prob;474475/* store current delay value */476pst->qdelay_old = pst->current_qdelay;477478/* update burst allowance */479if ((pst->sflags & PIE_ACTIVE) && pst->burst_allowance) {480if (pst->burst_allowance > pprms->tupdate)481pst->burst_allowance -= pprms->tupdate;482else483pst->burst_allowance = 0;484}485486if (pst->sflags & PIE_ACTIVE)487callout_reset_sbt(&pst->aqm_pie_callout,488(uint64_t)pprms->tupdate * SBT_1US,4890, fq_calculate_drop_prob, q, 0);490491mtx_unlock(&pst->lock_mtx);492}493494/*495* Reset PIE variables & activate the queue496*/497__inline static void498fq_activate_pie(struct fq_pie_flow *q)499{500struct pie_status *pst = &q->pst;501struct dn_aqm_pie_parms *pprms;502503mtx_lock(&pst->lock_mtx);504pprms = pst->parms;505506pprms = pst->parms;507pst->drop_prob = 0;508pst->qdelay_old = 0;509pst->burst_allowance = pprms->max_burst;510pst->accu_prob = 0;511pst->dq_count = 0;512pst->avg_dq_time = 0;513pst->sflags = PIE_INMEASUREMENT | PIE_ACTIVE;514pst->measurement_start = AQM_UNOW;515516callout_reset_sbt(&pst->aqm_pie_callout,517(uint64_t)pprms->tupdate * SBT_1US,5180, fq_calculate_drop_prob, q, 0);519520mtx_unlock(&pst->lock_mtx);521}522523/*524* Deactivate PIE and stop probe update callout525*/526__inline static void527fq_deactivate_pie(struct pie_status *pst)528{529mtx_lock(&pst->lock_mtx);530pst->sflags &= ~(PIE_ACTIVE | PIE_INMEASUREMENT);531callout_stop(&pst->aqm_pie_callout);532//D("PIE Deactivated");533mtx_unlock(&pst->lock_mtx);534}535536/*537* Initialize PIE for sub-queue 'q'538*/539static int540pie_init(struct fq_pie_flow *q, struct fq_pie_schk *fqpie_schk)541{542struct pie_status *pst=&q->pst;543struct dn_aqm_pie_parms *pprms = pst->parms;544545int err = 0;546if (!pprms){547D("AQM_PIE is not configured");548err = EINVAL;549} else {550q->psi_extra->nr_active_q++;551552/* For speed optimization, we caculate 1/3 queue size once here */553// XXX limit divided by number of queues divided by 3 ???554pst->one_third_q_size = (fqpie_schk->cfg.limit /555fqpie_schk->cfg.flows_cnt) / 3;556557mtx_init(&pst->lock_mtx, "mtx_pie", NULL, MTX_DEF);558callout_init_mtx(&pst->aqm_pie_callout, &pst->lock_mtx,559CALLOUT_RETURNUNLOCKED);560}561562return err;563}564565/*566* callout function to destroy PIE lock, and free fq_pie flows and fq_pie si567* extra memory when number of active sub-queues reaches zero.568* 'x' is a fq_pie_flow to be destroyed569*/570static void571fqpie_callout_cleanup(void *x)572{573struct fq_pie_flow *q = x;574struct pie_status *pst = &q->pst;575struct fq_pie_si_extra *psi_extra;576577mtx_unlock(&pst->lock_mtx);578mtx_destroy(&pst->lock_mtx);579psi_extra = q->psi_extra;580581dummynet_sched_lock();582psi_extra->nr_active_q--;583584/* when all sub-queues are destroyed, free flows fq_pie extra vars memory */585if (!psi_extra->nr_active_q) {586free(psi_extra->flows, M_DUMMYNET);587free(psi_extra, M_DUMMYNET);588fq_pie_desc.ref_count--;589}590dummynet_sched_unlock();591}592593/*594* Clean up PIE status for sub-queue 'q'595* Stop callout timer and destroy mtx using fqpie_callout_cleanup() callout.596*/597static int598pie_cleanup(struct fq_pie_flow *q)599{600struct pie_status *pst = &q->pst;601602mtx_lock(&pst->lock_mtx);603callout_reset_sbt(&pst->aqm_pie_callout,604SBT_1US, 0, fqpie_callout_cleanup, q, 0);605mtx_unlock(&pst->lock_mtx);606return 0;607}608609/*610* Dequeue and return a pcaket from sub-queue 'q' or NULL if 'q' is empty.611* Also, caculate depature time or queue delay using timestamp612*/613static struct mbuf *614pie_dequeue(struct fq_pie_flow *q, struct fq_pie_si *si)615{616struct mbuf *m;617struct dn_aqm_pie_parms *pprms;618struct pie_status *pst;619aqm_time_t now;620aqm_time_t pkt_ts, dq_time;621int32_t w;622623pst = &q->pst;624pprms = q->pst.parms;625626/*we extarct packet ts only when Departure Rate Estimation dis not used*/627m = fq_pie_extract_head(q, &pkt_ts, si,628!(pprms->flags & PIE_DEPRATEEST_ENABLED));629630if (!m || !(pst->sflags & PIE_ACTIVE))631return m;632633now = AQM_UNOW;634if (pprms->flags & PIE_DEPRATEEST_ENABLED) {635/* calculate average depature time */636if(pst->sflags & PIE_INMEASUREMENT) {637pst->dq_count += m->m_pkthdr.len;638639if (pst->dq_count >= PIE_DQ_THRESHOLD) {640dq_time = now - pst->measurement_start;641642/*643* if we don't have old avg dq_time i.e PIE is (re)initialized,644* don't use weight to calculate new avg_dq_time645*/646if(pst->avg_dq_time == 0)647pst->avg_dq_time = dq_time;648else {649/*650* weight = PIE_DQ_THRESHOLD/2^6, but we scaled651* weight by 2^8. Thus, scaled652* weight = PIE_DQ_THRESHOLD /2^8653* */654w = PIE_DQ_THRESHOLD >> 8;655pst->avg_dq_time = (dq_time* w656+ (pst->avg_dq_time * ((1L << 8) - w))) >> 8;657pst->sflags &= ~PIE_INMEASUREMENT;658}659}660}661662/*663* Start new measurement cycle when the queue has664* PIE_DQ_THRESHOLD worth of bytes.665*/666if(!(pst->sflags & PIE_INMEASUREMENT) &&667q->stats.len_bytes >= PIE_DQ_THRESHOLD) {668pst->sflags |= PIE_INMEASUREMENT;669pst->measurement_start = now;670pst->dq_count = 0;671}672}673/* Optionally, use packet timestamp to estimate queue delay */674else675pst->current_qdelay = now - pkt_ts;676677return m;678}679680/*681* Enqueue a packet in q, subject to space and FQ-PIE queue management policy682* (whose parameters are in q->fs).683* Update stats for the queue and the scheduler.684* Return 0 on success, 1 on drop. The packet is consumed anyways.685*/686static int687pie_enqueue(struct fq_pie_flow *q, struct mbuf* m, struct fq_pie_si *si)688{689uint64_t len;690struct pie_status *pst;691struct dn_aqm_pie_parms *pprms;692int t;693694len = m->m_pkthdr.len;695pst = &q->pst;696pprms = pst->parms;697t = ENQUE;698699/* drop/mark the packet when PIE is active and burst time elapsed */700if (pst->sflags & PIE_ACTIVE && pst->burst_allowance == 0701&& drop_early(pst, q->stats.len_bytes) == DROP) {702/*703* if drop_prob over ECN threshold, drop the packet704* otherwise mark and enqueue it.705*/706if (pprms->flags & PIE_ECN_ENABLED && pst->drop_prob <707(pprms->max_ecnth << (PIE_PROB_BITS - PIE_FIX_POINT_BITS))708&& ecn_mark(m))709t = ENQUE;710else711t = DROP;712}713714/* Turn PIE on when 1/3 of the queue is full */715if (!(pst->sflags & PIE_ACTIVE) && q->stats.len_bytes >=716pst->one_third_q_size) {717fq_activate_pie(q);718}719720/* reset burst tolerance and optinally turn PIE off*/721if (pst->drop_prob == 0 && pst->current_qdelay < (pprms->qdelay_ref >> 1)722&& pst->qdelay_old < (pprms->qdelay_ref >> 1)) {723724pst->burst_allowance = pprms->max_burst;725if (pprms->flags & PIE_ON_OFF_MODE_ENABLED && q->stats.len_bytes<=0)726fq_deactivate_pie(pst);727}728729/* Use timestamp if Departure Rate Estimation mode is disabled */730if (t != DROP && !(pprms->flags & PIE_DEPRATEEST_ENABLED)) {731/* Add TS to mbuf as a TAG */732struct m_tag *mtag;733mtag = m_tag_locate(m, MTAG_ABI_COMPAT, DN_AQM_MTAG_TS, NULL);734if (mtag == NULL)735mtag = m_tag_alloc(MTAG_ABI_COMPAT, DN_AQM_MTAG_TS,736sizeof(aqm_time_t), M_NOWAIT);737if (mtag == NULL) {738t = DROP;739} else {740*(aqm_time_t *)(mtag + 1) = AQM_UNOW;741m_tag_prepend(m, mtag);742}743}744745if (t != DROP) {746if (m->m_pkthdr.rcvif != NULL)747m_rcvif_serialize(m);748749mq_append(&q->mq, m);750fq_update_stats(q, si, len, 0);751return 0;752} else {753fq_update_stats(q, si, len, 1);754pst->accu_prob = 0;755FREE_PKT(m);756return 1;757}758759return 0;760}761762/* Drop a packet form the head of FQ-PIE sub-queue */763static void764pie_drop_head(struct fq_pie_flow *q, struct fq_pie_si *si)765{766struct mbuf *m = q->mq.head;767768if (m == NULL)769return;770q->mq.head = m->m_nextpkt;771772fq_update_stats(q, si, -m->m_pkthdr.len, 1);773774if (si->main_q.ni.length == 0) /* queue is now idle */775si->main_q.q_time = V_dn_cfg.curr_time;776/* reset accu_prob after packet drop */777q->pst.accu_prob = 0;778779FREE_PKT(m);780}781782/*783* Classify a packet to queue number using Jenkins hash function.784* Return: queue number785* the input of the hash are protocol no, perturbation, src IP, dst IP,786* src port, dst port,787*/788static inline int789fq_pie_classify_flow(struct mbuf *m, uint16_t fcount, struct fq_pie_si *si)790{791struct ip *ip;792struct tcphdr *th;793struct udphdr *uh;794uint8_t tuple[41];795uint16_t hash=0;796797ip = (struct ip *)mtodo(m, dn_tag_get(m)->iphdr_off);798//#ifdef INET6799struct ip6_hdr *ip6;800int isip6;801isip6 = (ip->ip_v == 6);802803if(isip6) {804ip6 = (struct ip6_hdr *)ip;805*((uint8_t *) &tuple[0]) = ip6->ip6_nxt;806*((uint32_t *) &tuple[1]) = si->perturbation;807memcpy(&tuple[5], ip6->ip6_src.s6_addr, 16);808memcpy(&tuple[21], ip6->ip6_dst.s6_addr, 16);809810switch (ip6->ip6_nxt) {811case IPPROTO_TCP:812th = (struct tcphdr *)(ip6 + 1);813*((uint16_t *) &tuple[37]) = th->th_dport;814*((uint16_t *) &tuple[39]) = th->th_sport;815break;816817case IPPROTO_UDP:818uh = (struct udphdr *)(ip6 + 1);819*((uint16_t *) &tuple[37]) = uh->uh_dport;820*((uint16_t *) &tuple[39]) = uh->uh_sport;821break;822default:823memset(&tuple[37], 0, 4);824}825826hash = jenkins_hash(tuple, 41, HASHINIT) % fcount;827return hash;828}829//#endif830831/* IPv4 */832*((uint8_t *) &tuple[0]) = ip->ip_p;833*((uint32_t *) &tuple[1]) = si->perturbation;834*((uint32_t *) &tuple[5]) = ip->ip_src.s_addr;835*((uint32_t *) &tuple[9]) = ip->ip_dst.s_addr;836837switch (ip->ip_p) {838case IPPROTO_TCP:839th = (struct tcphdr *)(ip + 1);840*((uint16_t *) &tuple[13]) = th->th_dport;841*((uint16_t *) &tuple[15]) = th->th_sport;842break;843844case IPPROTO_UDP:845uh = (struct udphdr *)(ip + 1);846*((uint16_t *) &tuple[13]) = uh->uh_dport;847*((uint16_t *) &tuple[15]) = uh->uh_sport;848break;849default:850memset(&tuple[13], 0, 4);851}852hash = jenkins_hash(tuple, 17, HASHINIT) % fcount;853854return hash;855}856857/*858* Enqueue a packet into an appropriate queue according to859* FQ-CoDe; algorithm.860*/861static int862fq_pie_enqueue(struct dn_sch_inst *_si, struct dn_queue *_q,863struct mbuf *m)864{865struct fq_pie_si *si;866struct fq_pie_schk *schk;867struct dn_sch_fq_pie_parms *param;868struct dn_queue *mainq;869struct fq_pie_flow *flows;870int idx, drop, i, maxidx;871872mainq = (struct dn_queue *)(_si + 1);873si = (struct fq_pie_si *)_si;874flows = si->si_extra->flows;875schk = (struct fq_pie_schk *)(si->_si.sched+1);876param = &schk->cfg;877878/* classify a packet to queue number*/879idx = fq_pie_classify_flow(m, param->flows_cnt, si);880881/* enqueue packet into appropriate queue using PIE AQM.882* Note: 'pie_enqueue' function returns 1 only when it unable to883* add timestamp to packet (no limit check)*/884drop = pie_enqueue(&flows[idx], m, si);885886/* pie unable to timestamp a packet */887if (drop)888return 1;889890/* If the flow (sub-queue) is not active ,then add it to tail of891* new flows list, initialize and activate it.892*/893if (!flows[idx].active) {894STAILQ_INSERT_TAIL(&si->newflows, &flows[idx], flowchain);895flows[idx].deficit = param->quantum;896fq_activate_pie(&flows[idx]);897flows[idx].active = 1;898}899900/* check the limit for all queues and remove a packet from the901* largest one902*/903if (mainq->ni.length > schk->cfg.limit) {904/* find first active flow */905for (maxidx = 0; maxidx < schk->cfg.flows_cnt; maxidx++)906if (flows[maxidx].active)907break;908if (maxidx < schk->cfg.flows_cnt) {909/* find the largest sub- queue */910for (i = maxidx + 1; i < schk->cfg.flows_cnt; i++)911if (flows[i].active && flows[i].stats.length >912flows[maxidx].stats.length)913maxidx = i;914pie_drop_head(&flows[maxidx], si);915drop = 1;916}917}918919return drop;920}921922/*923* Dequeue a packet from an appropriate queue according to924* FQ-CoDel algorithm.925*/926static struct mbuf *927fq_pie_dequeue(struct dn_sch_inst *_si)928{929struct fq_pie_si *si;930struct fq_pie_schk *schk;931struct dn_sch_fq_pie_parms *param;932struct fq_pie_flow *f;933struct mbuf *mbuf;934struct fq_pie_list *fq_pie_flowlist;935936si = (struct fq_pie_si *)_si;937schk = (struct fq_pie_schk *)(si->_si.sched+1);938param = &schk->cfg;939940do {941/* select a list to start with */942if (STAILQ_EMPTY(&si->newflows))943fq_pie_flowlist = &si->oldflows;944else945fq_pie_flowlist = &si->newflows;946947/* Both new and old queue lists are empty, return NULL */948if (STAILQ_EMPTY(fq_pie_flowlist))949return NULL;950951f = STAILQ_FIRST(fq_pie_flowlist);952while (f != NULL) {953/* if there is no flow(sub-queue) deficit, increase deficit954* by quantum, move the flow to the tail of old flows list955* and try another flow.956* Otherwise, the flow will be used for dequeue.957*/958if (f->deficit < 0) {959f->deficit += param->quantum;960STAILQ_REMOVE_HEAD(fq_pie_flowlist, flowchain);961STAILQ_INSERT_TAIL(&si->oldflows, f, flowchain);962} else963break;964965f = STAILQ_FIRST(fq_pie_flowlist);966}967968/* the new flows list is empty, try old flows list */969if (STAILQ_EMPTY(fq_pie_flowlist))970continue;971972/* Dequeue a packet from the selected flow */973mbuf = pie_dequeue(f, si);974975/* pie did not return a packet */976if (!mbuf) {977/* If the selected flow belongs to new flows list, then move978* it to the tail of old flows list. Otherwise, deactivate it and979* remove it from the old list and980*/981if (fq_pie_flowlist == &si->newflows) {982STAILQ_REMOVE_HEAD(fq_pie_flowlist, flowchain);983STAILQ_INSERT_TAIL(&si->oldflows, f, flowchain);984} else {985f->active = 0;986fq_deactivate_pie(&f->pst);987STAILQ_REMOVE_HEAD(fq_pie_flowlist, flowchain);988}989/* start again */990continue;991}992993/* we have a packet to return,994* update flow deficit and return the packet*/995f->deficit -= mbuf->m_pkthdr.len;996return mbuf;997998} while (1);9991000/* unreachable point */1001return NULL;1002}10031004/*1005* Initialize fq_pie scheduler instance.1006* also, allocate memory for flows array.1007*/1008static int1009fq_pie_new_sched(struct dn_sch_inst *_si)1010{1011struct fq_pie_si *si;1012struct dn_queue *q;1013struct fq_pie_schk *schk;1014struct fq_pie_flow *flows;1015int i;10161017si = (struct fq_pie_si *)_si;1018schk = (struct fq_pie_schk *)(_si->sched+1);10191020if(si->si_extra) {1021D("si already configured!");1022return 0;1023}10241025/* init the main queue */1026q = &si->main_q;1027set_oid(&q->ni.oid, DN_QUEUE, sizeof(*q));1028q->_si = _si;1029q->fs = _si->sched->fs;10301031/* allocate memory for scheduler instance extra vars */1032si->si_extra = malloc(sizeof(struct fq_pie_si_extra),1033M_DUMMYNET, M_NOWAIT | M_ZERO);1034if (si->si_extra == NULL) {1035D("cannot allocate memory for fq_pie si extra vars");1036return ENOMEM ;1037}1038/* allocate memory for flows array */1039si->si_extra->flows = mallocarray(schk->cfg.flows_cnt,1040sizeof(struct fq_pie_flow), M_DUMMYNET, M_NOWAIT | M_ZERO);1041flows = si->si_extra->flows;1042if (flows == NULL) {1043free(si->si_extra, M_DUMMYNET);1044si->si_extra = NULL;1045D("cannot allocate memory for fq_pie flows");1046return ENOMEM ;1047}10481049/* init perturbation for this si */1050si->perturbation = random();1051si->si_extra->nr_active_q = 0;10521053/* init the old and new flows lists */1054STAILQ_INIT(&si->newflows);1055STAILQ_INIT(&si->oldflows);10561057/* init the flows (sub-queues) */1058for (i = 0; i < schk->cfg.flows_cnt; i++) {1059flows[i].pst.parms = &schk->cfg.pcfg;1060flows[i].psi_extra = si->si_extra;1061pie_init(&flows[i], schk);1062}10631064dummynet_sched_lock();1065fq_pie_desc.ref_count++;1066dummynet_sched_unlock();10671068return 0;1069}10701071/*1072* Free fq_pie scheduler instance.1073*/1074static int1075fq_pie_free_sched(struct dn_sch_inst *_si)1076{1077struct fq_pie_si *si;1078struct fq_pie_schk *schk;1079struct fq_pie_flow *flows;1080int i;10811082si = (struct fq_pie_si *)_si;1083schk = (struct fq_pie_schk *)(_si->sched+1);1084flows = si->si_extra->flows;1085for (i = 0; i < schk->cfg.flows_cnt; i++) {1086pie_cleanup(&flows[i]);1087}1088si->si_extra = NULL;1089return 0;1090}10911092/*1093* Configure FQ-PIE scheduler.1094* the configurations for the scheduler is passed fromipfw userland.1095*/1096static int1097fq_pie_config(struct dn_schk *_schk)1098{1099struct fq_pie_schk *schk;1100struct dn_extra_parms *ep;1101struct dn_sch_fq_pie_parms *fqp_cfg;11021103schk = (struct fq_pie_schk *)(_schk+1);1104ep = (struct dn_extra_parms *) _schk->cfg;11051106/* par array contains fq_pie configuration as follow1107* PIE: 0- qdelay_ref,1- tupdate, 2- max_burst1108* 3- max_ecnth, 4- alpha, 5- beta, 6- flags1109* FQ_PIE: 7- quantum, 8- limit, 9- flows1110*/1111if (ep && ep->oid.len ==sizeof(*ep) &&1112ep->oid.subtype == DN_SCH_PARAMS) {1113fqp_cfg = &schk->cfg;1114if (ep->par[0] < 0)1115fqp_cfg->pcfg.qdelay_ref = fq_pie_sysctl.pcfg.qdelay_ref;1116else1117fqp_cfg->pcfg.qdelay_ref = ep->par[0];1118if (ep->par[1] < 0)1119fqp_cfg->pcfg.tupdate = fq_pie_sysctl.pcfg.tupdate;1120else1121fqp_cfg->pcfg.tupdate = ep->par[1];1122if (ep->par[2] < 0)1123fqp_cfg->pcfg.max_burst = fq_pie_sysctl.pcfg.max_burst;1124else1125fqp_cfg->pcfg.max_burst = ep->par[2];1126if (ep->par[3] < 0)1127fqp_cfg->pcfg.max_ecnth = fq_pie_sysctl.pcfg.max_ecnth;1128else1129fqp_cfg->pcfg.max_ecnth = ep->par[3];1130if (ep->par[4] < 0)1131fqp_cfg->pcfg.alpha = fq_pie_sysctl.pcfg.alpha;1132else1133fqp_cfg->pcfg.alpha = ep->par[4];1134if (ep->par[5] < 0)1135fqp_cfg->pcfg.beta = fq_pie_sysctl.pcfg.beta;1136else1137fqp_cfg->pcfg.beta = ep->par[5];1138if (ep->par[6] < 0)1139fqp_cfg->pcfg.flags = 0;1140else1141fqp_cfg->pcfg.flags = ep->par[6];11421143/* FQ configurations */1144if (ep->par[7] < 0)1145fqp_cfg->quantum = fq_pie_sysctl.quantum;1146else1147fqp_cfg->quantum = ep->par[7];1148if (ep->par[8] < 0)1149fqp_cfg->limit = fq_pie_sysctl.limit;1150else1151fqp_cfg->limit = ep->par[8];1152if (ep->par[9] < 0)1153fqp_cfg->flows_cnt = fq_pie_sysctl.flows_cnt;1154else1155fqp_cfg->flows_cnt = ep->par[9];11561157/* Bound the configurations */1158fqp_cfg->pcfg.qdelay_ref = BOUND_VAR(fqp_cfg->pcfg.qdelay_ref,11591, 5 * AQM_TIME_1S);1160fqp_cfg->pcfg.tupdate = BOUND_VAR(fqp_cfg->pcfg.tupdate,11611, 5 * AQM_TIME_1S);1162fqp_cfg->pcfg.max_burst = BOUND_VAR(fqp_cfg->pcfg.max_burst,11630, 5 * AQM_TIME_1S);1164fqp_cfg->pcfg.max_ecnth = BOUND_VAR(fqp_cfg->pcfg.max_ecnth,11650, PIE_SCALE);1166fqp_cfg->pcfg.alpha = BOUND_VAR(fqp_cfg->pcfg.alpha, 0, 7 * PIE_SCALE);1167fqp_cfg->pcfg.beta = BOUND_VAR(fqp_cfg->pcfg.beta, 0, 7 * PIE_SCALE);11681169fqp_cfg->quantum = BOUND_VAR(fqp_cfg->quantum,1,9000);1170fqp_cfg->limit= BOUND_VAR(fqp_cfg->limit,1,20480);1171fqp_cfg->flows_cnt= BOUND_VAR(fqp_cfg->flows_cnt,1,65536);1172}1173else {1174D("Wrong parameters for fq_pie scheduler");1175return 1;1176}11771178return 0;1179}11801181/*1182* Return FQ-PIE scheduler configurations1183* the configurations for the scheduler is passed to userland.1184*/1185static int1186fq_pie_getconfig (struct dn_schk *_schk, struct dn_extra_parms *ep) {1187struct fq_pie_schk *schk = (struct fq_pie_schk *)(_schk+1);1188struct dn_sch_fq_pie_parms *fqp_cfg;11891190fqp_cfg = &schk->cfg;11911192strcpy(ep->name, fq_pie_desc.name);1193ep->par[0] = fqp_cfg->pcfg.qdelay_ref;1194ep->par[1] = fqp_cfg->pcfg.tupdate;1195ep->par[2] = fqp_cfg->pcfg.max_burst;1196ep->par[3] = fqp_cfg->pcfg.max_ecnth;1197ep->par[4] = fqp_cfg->pcfg.alpha;1198ep->par[5] = fqp_cfg->pcfg.beta;1199ep->par[6] = fqp_cfg->pcfg.flags;12001201ep->par[7] = fqp_cfg->quantum;1202ep->par[8] = fqp_cfg->limit;1203ep->par[9] = fqp_cfg->flows_cnt;12041205return 0;1206}12071208/*1209* FQ-PIE scheduler descriptor1210* contains the type of the scheduler, the name, the size of extra1211* data structures, and function pointers.1212*/1213static struct dn_alg fq_pie_desc = {1214_SI( .type = ) DN_SCHED_FQ_PIE,1215_SI( .name = ) "FQ_PIE",1216_SI( .flags = ) 0,12171218_SI( .schk_datalen = ) sizeof(struct fq_pie_schk),1219_SI( .si_datalen = ) sizeof(struct fq_pie_si) - sizeof(struct dn_sch_inst),1220_SI( .q_datalen = ) 0,12211222_SI( .enqueue = ) fq_pie_enqueue,1223_SI( .dequeue = ) fq_pie_dequeue,1224_SI( .config = ) fq_pie_config, /* new sched i.e. sched X config ...*/1225_SI( .destroy = ) NULL, /*sched x delete */1226_SI( .new_sched = ) fq_pie_new_sched, /* new schd instance */1227_SI( .free_sched = ) fq_pie_free_sched, /* delete schd instance */1228_SI( .new_fsk = ) NULL,1229_SI( .free_fsk = ) NULL,1230_SI( .new_queue = ) NULL,1231_SI( .free_queue = ) NULL,1232_SI( .getconfig = ) fq_pie_getconfig,1233_SI( .ref_count = ) 01234};12351236DECLARE_DNSCHED_MODULE(dn_fq_pie, &fq_pie_desc);123712381239