The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netinet/ip_dummynet.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1998-2002 Luigi Rizzo, Universita` di Pisa
    3  * Portions Copyright (c) 2000 Akamba Corp.
    4  * All rights reserved
    5  *
    6  * Redistribution and use in source and binary forms, with or without
    7  * modification, are permitted provided that the following conditions
    8  * are met:
    9  * 1. Redistributions of source code must retain the above copyright
   10  *    notice, this list of conditions and the following disclaimer.
   11  * 2. Redistributions in binary form must reproduce the above copyright
   12  *    notice, this list of conditions and the following disclaimer in the
   13  *    documentation and/or other materials provided with the distribution.
   14  *
   15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   25  * SUCH DAMAGE.
   26  *
   27  * $FreeBSD$
   28  */
   29 
   30 #define DUMMYNET_DEBUG
   31 
   32 /*
   33  * This module implements IP dummynet, a bandwidth limiter/delay emulator
   34  * used in conjunction with the ipfw package.
   35  * Description of the data structures used is in ip_dummynet.h
   36  * Here you mainly find the following blocks of code:
   37  *  + variable declarations;
   38  *  + heap management functions;
   39  *  + scheduler and dummynet functions;
   40  *  + configuration and initialization.
   41  *
   42  * NOTA BENE: critical sections are protected by the "dummynet lock".
   43  *
   44  * Most important Changes:
   45  *
   46  * 011004: KLDable
   47  * 010124: Fixed WF2Q behaviour
   48  * 010122: Fixed spl protection.
   49  * 000601: WF2Q support
   50  * 000106: large rewrite, use heaps to handle very many pipes.
   51  * 980513:      initial release
   52  *
   53  * include files marked with XXX are probably not needed
   54  */
   55 
   56 #include <sys/param.h>
   57 #include <sys/systm.h>
   58 #include <sys/malloc.h>
   59 #include <sys/mbuf.h>
   60 #include <sys/kernel.h>
   61 #include <sys/module.h>
   62 #include <sys/proc.h>
   63 #include <sys/socket.h>
   64 #include <sys/socketvar.h>
   65 #include <sys/time.h>
   66 #include <sys/sysctl.h>
   67 #include <net/if.h>
   68 #include <net/route.h>
   69 #include <netinet/in.h>
   70 #include <netinet/in_systm.h>
   71 #include <netinet/in_var.h>
   72 #include <netinet/ip.h>
   73 #include <netinet/ip_fw.h>
   74 #include <netinet/ip_dummynet.h>
   75 #include <netinet/ip_var.h>
   76 
   77 #include <netinet/if_ether.h> /* for struct arpcom */
   78 #include <net/bridge.h>
   79 
   80 /*
   81  * We keep a private variable for the simulation time, but we could
   82  * probably use an existing one ("softticks" in sys/kern/kern_timeout.c)
   83  */
   84 static dn_key curr_time = 0 ; /* current simulation time */
   85 
   86 static int dn_hash_size = 64 ;  /* default hash size */
   87 
   88 /* statistics on number of queue searches and search steps */
   89 static int searches, search_steps ;
   90 static int pipe_expire = 1 ;   /* expire queue if empty */
   91 static int dn_max_ratio = 16 ; /* max queues/buckets ratio */
   92 
   93 static int red_lookup_depth = 256;      /* RED - default lookup table depth */
   94 static int red_avg_pkt_size = 512;      /* RED - default medium packet size */
   95 static int red_max_pkt_size = 1500;     /* RED - default max packet size */
   96 
   97 /*
   98  * Three heaps contain queues and pipes that the scheduler handles:
   99  *
  100  * ready_heap contains all dn_flow_queue related to fixed-rate pipes.
  101  *
  102  * wfq_ready_heap contains the pipes associated with WF2Q flows
  103  *
  104  * extract_heap contains pipes associated with delay lines.
  105  *
  106  */
  107 
  108 MALLOC_DEFINE(M_DUMMYNET, "dummynet", "dummynet heap");
  109 
  110 static struct dn_heap ready_heap, extract_heap, wfq_ready_heap ;
  111 
  112 static int heap_init(struct dn_heap *h, int size) ;
  113 static int heap_insert (struct dn_heap *h, dn_key key1, void *p);
  114 static void heap_extract(struct dn_heap *h, void *obj);
  115 
  116 static void transmit_event(struct dn_pipe *pipe);
  117 static void ready_event(struct dn_flow_queue *q);
  118 
  119 static struct dn_pipe *all_pipes = NULL ;       /* list of all pipes */
  120 static struct dn_flow_set *all_flow_sets = NULL ;/* list of all flow_sets */
  121 
  122 static struct callout dn_timeout;
  123 
  124 extern  void (*bridge_dn_p)(struct mbuf *, struct ifnet *);
  125 
  126 #ifdef SYSCTL_NODE
  127 SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet,
  128                 CTLFLAG_RW, 0, "Dummynet");
  129 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, hash_size,
  130             CTLFLAG_RW, &dn_hash_size, 0, "Default hash table size");
  131 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, curr_time,
  132             CTLFLAG_RD, &curr_time, 0, "Current tick");
  133 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, ready_heap,
  134             CTLFLAG_RD, &ready_heap.size, 0, "Size of ready heap");
  135 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, extract_heap,
  136             CTLFLAG_RD, &extract_heap.size, 0, "Size of extract heap");
  137 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, searches,
  138             CTLFLAG_RD, &searches, 0, "Number of queue searches");
  139 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, search_steps,
  140             CTLFLAG_RD, &search_steps, 0, "Number of queue search steps");
  141 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, expire,
  142             CTLFLAG_RW, &pipe_expire, 0, "Expire queue if empty");
  143 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, max_chain_len,
  144             CTLFLAG_RW, &dn_max_ratio, 0,
  145         "Max ratio between dynamic queues and buckets");
  146 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
  147         CTLFLAG_RD, &red_lookup_depth, 0, "Depth of RED lookup table");
  148 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
  149         CTLFLAG_RD, &red_avg_pkt_size, 0, "RED Medium packet size");
  150 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
  151         CTLFLAG_RD, &red_max_pkt_size, 0, "RED Max packet size");
  152 #endif
  153 
  154 #ifdef DUMMYNET_DEBUG
  155 int     dummynet_debug = 0;
  156 #ifdef SYSCTL_NODE
  157 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug, CTLFLAG_RW, &dummynet_debug,
  158             0, "control debugging printfs");
  159 #endif
  160 #define DPRINTF(X)      if (dummynet_debug) printf X
  161 #else
  162 #define DPRINTF(X)
  163 #endif
  164 
  165 static struct mtx dummynet_mtx;
  166 /*
  167  * NB: Recursion is needed to deal with re-entry via ICMP.  That is,
  168  *     a packet may be dispatched via ip_input from dummynet_io and
  169  *     re-enter through ip_output.  Yech.
  170  */
  171 #define DUMMYNET_LOCK_INIT() \
  172         mtx_init(&dummynet_mtx, "dummynet", NULL, MTX_DEF | MTX_RECURSE)
  173 #define DUMMYNET_LOCK_DESTROY() mtx_destroy(&dummynet_mtx)
  174 #define DUMMYNET_LOCK()         mtx_lock(&dummynet_mtx)
  175 #define DUMMYNET_UNLOCK()       mtx_unlock(&dummynet_mtx)
  176 #define DUMMYNET_LOCK_ASSERT()  do {                            \
  177         mtx_assert(&dummynet_mtx, MA_OWNED);                    \
  178         NET_ASSERT_GIANT();                                     \
  179 } while (0)
  180 
  181 static int config_pipe(struct dn_pipe *p);
  182 static int ip_dn_ctl(struct sockopt *sopt);
  183 
  184 static void dummynet(void *);
  185 static void dummynet_flush(void);
  186 void dummynet_drain(void);
  187 static ip_dn_io_t dummynet_io;
  188 static void dn_rule_delete(void *);
  189 
  190 int if_tx_rdy(struct ifnet *ifp);
  191 
  192 /*
  193  * Heap management functions.
  194  *
  195  * In the heap, first node is element 0. Children of i are 2i+1 and 2i+2.
  196  * Some macros help finding parent/children so we can optimize them.
  197  *
  198  * heap_init() is called to expand the heap when needed.
  199  * Increment size in blocks of 16 entries.
  200  * XXX failure to allocate a new element is a pretty bad failure
  201  * as we basically stall a whole queue forever!!
  202  * Returns 1 on error, 0 on success
  203  */
  204 #define HEAP_FATHER(x) ( ( (x) - 1 ) / 2 )
  205 #define HEAP_LEFT(x) ( 2*(x) + 1 )
  206 #define HEAP_IS_LEFT(x) ( (x) & 1 )
  207 #define HEAP_RIGHT(x) ( 2*(x) + 2 )
  208 #define HEAP_SWAP(a, b, buffer) { buffer = a ; a = b ; b = buffer ; }
  209 #define HEAP_INCREMENT  15
  210 
  211 static int
  212 heap_init(struct dn_heap *h, int new_size)
  213 {
  214     struct dn_heap_entry *p;
  215 
  216     if (h->size >= new_size ) {
  217         printf("dummynet: %s, Bogus call, have %d want %d\n", __func__,
  218                 h->size, new_size);
  219         return 0 ;
  220     }
  221     new_size = (new_size + HEAP_INCREMENT ) & ~HEAP_INCREMENT ;
  222     p = malloc(new_size * sizeof(*p), M_DUMMYNET, M_NOWAIT);
  223     if (p == NULL) {
  224         printf("dummynet: %s, resize %d failed\n", __func__, new_size );
  225         return 1 ; /* error */
  226     }
  227     if (h->size > 0) {
  228         bcopy(h->p, p, h->size * sizeof(*p) );
  229         free(h->p, M_DUMMYNET);
  230     }
  231     h->p = p ;
  232     h->size = new_size ;
  233     return 0 ;
  234 }
  235 
  236 /*
  237  * Insert element in heap. Normally, p != NULL, we insert p in
  238  * a new position and bubble up. If p == NULL, then the element is
  239  * already in place, and key is the position where to start the
  240  * bubble-up.
  241  * Returns 1 on failure (cannot allocate new heap entry)
  242  *
  243  * If offset > 0 the position (index, int) of the element in the heap is
  244  * also stored in the element itself at the given offset in bytes.
  245  */
  246 #define SET_OFFSET(heap, node) \
  247     if (heap->offset > 0) \
  248             *((int *)((char *)(heap->p[node].object) + heap->offset)) = node ;
  249 /*
  250  * RESET_OFFSET is used for sanity checks. It sets offset to an invalid value.
  251  */
  252 #define RESET_OFFSET(heap, node) \
  253     if (heap->offset > 0) \
  254             *((int *)((char *)(heap->p[node].object) + heap->offset)) = -1 ;
  255 static int
  256 heap_insert(struct dn_heap *h, dn_key key1, void *p)
  257 {
  258     int son = h->elements ;
  259 
  260     if (p == NULL)      /* data already there, set starting point */
  261         son = key1 ;
  262     else {              /* insert new element at the end, possibly resize */
  263         son = h->elements ;
  264         if (son == h->size) /* need resize... */
  265             if (heap_init(h, h->elements+1) )
  266                 return 1 ; /* failure... */
  267         h->p[son].object = p ;
  268         h->p[son].key = key1 ;
  269         h->elements++ ;
  270     }
  271     while (son > 0) {                           /* bubble up */
  272         int father = HEAP_FATHER(son) ;
  273         struct dn_heap_entry tmp  ;
  274 
  275         if (DN_KEY_LT( h->p[father].key, h->p[son].key ) )
  276             break ; /* found right position */
  277         /* son smaller than father, swap and repeat */
  278         HEAP_SWAP(h->p[son], h->p[father], tmp) ;
  279         SET_OFFSET(h, son);
  280         son = father ;
  281     }
  282     SET_OFFSET(h, son);
  283     return 0 ;
  284 }
  285 
  286 /*
  287  * remove top element from heap, or obj if obj != NULL
  288  */
  289 static void
  290 heap_extract(struct dn_heap *h, void *obj)
  291 {
  292     int child, father, max = h->elements - 1 ;
  293 
  294     if (max < 0) {
  295         printf("dummynet: warning, extract from empty heap 0x%p\n", h);
  296         return ;
  297     }
  298     father = 0 ; /* default: move up smallest child */
  299     if (obj != NULL) { /* extract specific element, index is at offset */
  300         if (h->offset <= 0)
  301             panic("dummynet: heap_extract from middle not supported on this heap!!!\n");
  302         father = *((int *)((char *)obj + h->offset)) ;
  303         if (father < 0 || father >= h->elements) {
  304             printf("dummynet: heap_extract, father %d out of bound 0..%d\n",
  305                 father, h->elements);
  306             panic("dummynet: heap_extract");
  307         }
  308     }
  309     RESET_OFFSET(h, father);
  310     child = HEAP_LEFT(father) ;         /* left child */
  311     while (child <= max) {              /* valid entry */
  312         if (child != max && DN_KEY_LT(h->p[child+1].key, h->p[child].key) )
  313             child = child+1 ;           /* take right child, otherwise left */
  314         h->p[father] = h->p[child] ;
  315         SET_OFFSET(h, father);
  316         father = child ;
  317         child = HEAP_LEFT(child) ;   /* left child for next loop */
  318     }
  319     h->elements-- ;
  320     if (father != max) {
  321         /*
  322          * Fill hole with last entry and bubble up, reusing the insert code
  323          */
  324         h->p[father] = h->p[max] ;
  325         heap_insert(h, father, NULL); /* this one cannot fail */
  326     }
  327 }
  328 
  329 #if 0
  330 /*
  331  * change object position and update references
  332  * XXX this one is never used!
  333  */
  334 static void
  335 heap_move(struct dn_heap *h, dn_key new_key, void *object)
  336 {
  337     int temp;
  338     int i ;
  339     int max = h->elements-1 ;
  340     struct dn_heap_entry buf ;
  341 
  342     if (h->offset <= 0)
  343         panic("cannot move items on this heap");
  344 
  345     i = *((int *)((char *)object + h->offset));
  346     if (DN_KEY_LT(new_key, h->p[i].key) ) { /* must move up */
  347         h->p[i].key = new_key ;
  348         for (; i>0 && DN_KEY_LT(new_key, h->p[(temp = HEAP_FATHER(i))].key) ;
  349                  i = temp ) { /* bubble up */
  350             HEAP_SWAP(h->p[i], h->p[temp], buf) ;
  351             SET_OFFSET(h, i);
  352         }
  353     } else {            /* must move down */
  354         h->p[i].key = new_key ;
  355         while ( (temp = HEAP_LEFT(i)) <= max ) { /* found left child */
  356             if ((temp != max) && DN_KEY_GT(h->p[temp].key, h->p[temp+1].key))
  357                 temp++ ; /* select child with min key */
  358             if (DN_KEY_GT(new_key, h->p[temp].key)) { /* go down */
  359                 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
  360                 SET_OFFSET(h, i);
  361             } else
  362                 break ;
  363             i = temp ;
  364         }
  365     }
  366     SET_OFFSET(h, i);
  367 }
  368 #endif /* heap_move, unused */
  369 
  370 /*
  371  * heapify() will reorganize data inside an array to maintain the
  372  * heap property. It is needed when we delete a bunch of entries.
  373  */
  374 static void
  375 heapify(struct dn_heap *h)
  376 {
  377     int i ;
  378 
  379     for (i = 0 ; i < h->elements ; i++ )
  380         heap_insert(h, i , NULL) ;
  381 }
  382 
  383 /*
  384  * cleanup the heap and free data structure
  385  */
  386 static void
  387 heap_free(struct dn_heap *h)
  388 {
  389     if (h->size >0 )
  390         free(h->p, M_DUMMYNET);
  391     bzero(h, sizeof(*h) );
  392 }
  393 
  394 /*
  395  * --- end of heap management functions ---
  396  */
  397 
  398 /*
  399  * Return the mbuf tag holding the dummynet state.  As an optimization
  400  * this is assumed to be the first tag on the list.  If this turns out
  401  * wrong we'll need to search the list.
  402  */
  403 static struct dn_pkt_tag *
  404 dn_tag_get(struct mbuf *m)
  405 {
  406     struct m_tag *mtag = m_tag_first(m);
  407     KASSERT(mtag != NULL &&
  408             mtag->m_tag_cookie == MTAG_ABI_COMPAT &&
  409             mtag->m_tag_id == PACKET_TAG_DUMMYNET,
  410             ("packet on dummynet queue w/o dummynet tag!"));
  411     return (struct dn_pkt_tag *)(mtag+1);
  412 }
  413 
  414 /*
  415  * Scheduler functions:
  416  *
  417  * transmit_event() is called when the delay-line needs to enter
  418  * the scheduler, either because of existing pkts getting ready,
  419  * or new packets entering the queue. The event handled is the delivery
  420  * time of the packet.
  421  *
  422  * ready_event() does something similar with fixed-rate queues, and the
  423  * event handled is the finish time of the head pkt.
  424  *
  425  * wfq_ready_event() does something similar with WF2Q queues, and the
  426  * event handled is the start time of the head pkt.
  427  *
  428  * In all cases, we make sure that the data structures are consistent
  429  * before passing pkts out, because this might trigger recursive
  430  * invocations of the procedures.
  431  */
  432 static void
  433 transmit_event(struct dn_pipe *pipe)
  434 {
  435     struct mbuf *m ;
  436     struct dn_pkt_tag *pkt ;
  437     struct ip *ip;
  438 
  439     DUMMYNET_LOCK_ASSERT();
  440 
  441     while ( (m = pipe->head) ) {
  442         pkt = dn_tag_get(m);
  443         if ( !DN_KEY_LEQ(pkt->output_time, curr_time) )
  444             break;
  445         /*
  446          * first unlink, then call procedures, since ip_input() can invoke
  447          * ip_output() and viceversa, thus causing nested calls
  448          */
  449         pipe->head = m->m_nextpkt ;
  450         m->m_nextpkt = NULL;
  451 
  452         /* XXX: drop the lock for now to avoid LOR's */
  453         DUMMYNET_UNLOCK();
  454         switch (pkt->dn_dir) {
  455         case DN_TO_IP_OUT:
  456             (void)ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
  457             break ;
  458 
  459         case DN_TO_IP_IN :
  460             ip = mtod(m, struct ip *);
  461             ip->ip_len = htons(ip->ip_len);
  462             ip->ip_off = htons(ip->ip_off);
  463             ip_input(m) ;
  464             break ;
  465 
  466         case DN_TO_BDG_FWD :
  467             /*
  468              * The bridge requires/assumes the Ethernet header is
  469              * contiguous in the first mbuf header.  Insure this is true.
  470              */
  471             if (BDG_LOADED) {
  472                 if (m->m_len < ETHER_HDR_LEN &&
  473                     (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
  474                     printf("dummynet/bridge: pullup fail, dropping pkt\n");
  475                     break;
  476                 }
  477                 m = bdg_forward_ptr(m, pkt->ifp);
  478             } else {
  479                 /* somebody unloaded the bridge module. Drop pkt */
  480                 /* XXX rate limit */
  481                 printf("dummynet: dropping bridged packet trapped in pipe\n");
  482             }
  483             if (m)
  484                 m_freem(m);
  485             break;
  486 
  487         case DN_TO_ETH_DEMUX:
  488             /*
  489              * The Ethernet code assumes the Ethernet header is
  490              * contiguous in the first mbuf header.  Insure this is true.
  491              */
  492             if (m->m_len < ETHER_HDR_LEN &&
  493                 (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
  494                 printf("dummynet/ether: pullup fail, dropping pkt\n");
  495                 break;
  496             }
  497             ether_demux(m->m_pkthdr.rcvif, m); /* which consumes the mbuf */
  498             break ;
  499 
  500         case DN_TO_ETH_OUT:
  501             ether_output_frame(pkt->ifp, m);
  502             break;
  503 
  504         case DN_TO_IFB_FWD:
  505             if (bridge_dn_p != NULL)
  506                 ((*bridge_dn_p)(m, pkt->ifp));
  507             else
  508                 printf("dummynet: if_bridge not loaded\n");
  509 
  510             break;
  511 
  512         default:
  513             printf("dummynet: bad switch %d!\n", pkt->dn_dir);
  514             m_freem(m);
  515             break ;
  516         }
  517         DUMMYNET_LOCK();
  518     }
  519     /* if there are leftover packets, put into the heap for next event */
  520     if ( (m = pipe->head) ) {
  521         pkt = dn_tag_get(m) ;
  522         /* XXX should check errors on heap_insert, by draining the
  523          * whole pipe p and hoping in the future we are more successful
  524          */
  525         heap_insert(&extract_heap, pkt->output_time, pipe ) ;
  526     }
  527 }
  528 
  529 /*
  530  * the following macro computes how many ticks we have to wait
  531  * before being able to transmit a packet. The credit is taken from
  532  * either a pipe (WF2Q) or a flow_queue (per-flow queueing)
  533  */
  534 #define SET_TICKS(_m, q, p)     \
  535     ((_m)->m_pkthdr.len*8*hz - (q)->numbytes + p->bandwidth - 1 ) / \
  536             p->bandwidth ;
  537 
  538 /*
  539  * extract pkt from queue, compute output time (could be now)
  540  * and put into delay line (p_queue)
  541  */
  542 static void
  543 move_pkt(struct mbuf *pkt, struct dn_flow_queue *q,
  544         struct dn_pipe *p, int len)
  545 {
  546     struct dn_pkt_tag *dt = dn_tag_get(pkt);
  547 
  548     q->head = pkt->m_nextpkt ;
  549     q->len-- ;
  550     q->len_bytes -= len ;
  551 
  552     dt->output_time = curr_time + p->delay ;
  553 
  554     if (p->head == NULL)
  555         p->head = pkt;
  556     else
  557         p->tail->m_nextpkt = pkt;
  558     p->tail = pkt;
  559     p->tail->m_nextpkt = NULL;
  560 }
  561 
  562 /*
  563  * ready_event() is invoked every time the queue must enter the
  564  * scheduler, either because the first packet arrives, or because
  565  * a previously scheduled event fired.
  566  * On invokation, drain as many pkts as possible (could be 0) and then
  567  * if there are leftover packets reinsert the pkt in the scheduler.
  568  */
  569 static void
  570 ready_event(struct dn_flow_queue *q)
  571 {
  572     struct mbuf *pkt;
  573     struct dn_pipe *p = q->fs->pipe ;
  574     int p_was_empty ;
  575 
  576     DUMMYNET_LOCK_ASSERT();
  577 
  578     if (p == NULL) {
  579         printf("dummynet: ready_event- pipe is gone\n");
  580         return ;
  581     }
  582     p_was_empty = (p->head == NULL) ;
  583 
  584     /*
  585      * schedule fixed-rate queues linked to this pipe:
  586      * Account for the bw accumulated since last scheduling, then
  587      * drain as many pkts as allowed by q->numbytes and move to
  588      * the delay line (in p) computing output time.
  589      * bandwidth==0 (no limit) means we can drain the whole queue,
  590      * setting len_scaled = 0 does the job.
  591      */
  592     q->numbytes += ( curr_time - q->sched_time ) * p->bandwidth;
  593     while ( (pkt = q->head) != NULL ) {
  594         int len = pkt->m_pkthdr.len;
  595         int len_scaled = p->bandwidth ? len*8*hz : 0 ;
  596         if (len_scaled > q->numbytes )
  597             break ;
  598         q->numbytes -= len_scaled ;
  599         move_pkt(pkt, q, p, len);
  600     }
  601     /*
  602      * If we have more packets queued, schedule next ready event
  603      * (can only occur when bandwidth != 0, otherwise we would have
  604      * flushed the whole queue in the previous loop).
  605      * To this purpose we record the current time and compute how many
  606      * ticks to go for the finish time of the packet.
  607      */
  608     if ( (pkt = q->head) != NULL ) { /* this implies bandwidth != 0 */
  609         dn_key t = SET_TICKS(pkt, q, p); /* ticks i have to wait */
  610         q->sched_time = curr_time ;
  611         heap_insert(&ready_heap, curr_time + t, (void *)q );
  612         /* XXX should check errors on heap_insert, and drain the whole
  613          * queue on error hoping next time we are luckier.
  614          */
  615     } else {    /* RED needs to know when the queue becomes empty */
  616         q->q_time = curr_time;
  617         q->numbytes = 0;
  618     }
  619     /*
  620      * If the delay line was empty call transmit_event(p) now.
  621      * Otherwise, the scheduler will take care of it.
  622      */
  623     if (p_was_empty)
  624         transmit_event(p);
  625 }
  626 
  627 /*
  628  * Called when we can transmit packets on WF2Q queues. Take pkts out of
  629  * the queues at their start time, and enqueue into the delay line.
  630  * Packets are drained until p->numbytes < 0. As long as
  631  * len_scaled >= p->numbytes, the packet goes into the delay line
  632  * with a deadline p->delay. For the last packet, if p->numbytes<0,
  633  * there is an additional delay.
  634  */
  635 static void
  636 ready_event_wfq(struct dn_pipe *p)
  637 {
  638     int p_was_empty = (p->head == NULL) ;
  639     struct dn_heap *sch = &(p->scheduler_heap);
  640     struct dn_heap *neh = &(p->not_eligible_heap) ;
  641 
  642     DUMMYNET_LOCK_ASSERT();
  643 
  644     if (p->if_name[0] == 0) /* tx clock is simulated */
  645         p->numbytes += ( curr_time - p->sched_time ) * p->bandwidth;
  646     else { /* tx clock is for real, the ifq must be empty or this is a NOP */
  647         if (p->ifp && p->ifp->if_snd.ifq_head != NULL)
  648             return ;
  649         else {
  650             DPRINTF(("dummynet: pipe %d ready from %s --\n",
  651                 p->pipe_nr, p->if_name));
  652         }
  653     }
  654 
  655     /*
  656      * While we have backlogged traffic AND credit, we need to do
  657      * something on the queue.
  658      */
  659     while ( p->numbytes >=0 && (sch->elements>0 || neh->elements >0) ) {
  660         if (sch->elements > 0) { /* have some eligible pkts to send out */
  661             struct dn_flow_queue *q = sch->p[0].object ;
  662             struct mbuf *pkt = q->head;
  663             struct dn_flow_set *fs = q->fs;
  664             u_int64_t len = pkt->m_pkthdr.len;
  665             int len_scaled = p->bandwidth ? len*8*hz : 0 ;
  666 
  667             heap_extract(sch, NULL); /* remove queue from heap */
  668             p->numbytes -= len_scaled ;
  669             move_pkt(pkt, q, p, len);
  670 
  671             p->V += (len<<MY_M) / p->sum ; /* update V */
  672             q->S = q->F ; /* update start time */
  673             if (q->len == 0) { /* Flow not backlogged any more */
  674                 fs->backlogged-- ;
  675                 heap_insert(&(p->idle_heap), q->F, q);
  676             } else { /* still backlogged */
  677                 /*
  678                  * update F and position in backlogged queue, then
  679                  * put flow in not_eligible_heap (we will fix this later).
  680                  */
  681                 len = (q->head)->m_pkthdr.len;
  682                 q->F += (len<<MY_M)/(u_int64_t) fs->weight ;
  683                 if (DN_KEY_LEQ(q->S, p->V))
  684                     heap_insert(neh, q->S, q);
  685                 else
  686                     heap_insert(sch, q->F, q);
  687             }
  688         }
  689         /*
  690          * now compute V = max(V, min(S_i)). Remember that all elements in sch
  691          * have by definition S_i <= V so if sch is not empty, V is surely
  692          * the max and we must not update it. Conversely, if sch is empty
  693          * we only need to look at neh.
  694          */
  695         if (sch->elements == 0 && neh->elements > 0)
  696             p->V = MAX64 ( p->V, neh->p[0].key );
  697         /* move from neh to sch any packets that have become eligible */
  698         while (neh->elements > 0 && DN_KEY_LEQ(neh->p[0].key, p->V) ) {
  699             struct dn_flow_queue *q = neh->p[0].object ;
  700             heap_extract(neh, NULL);
  701             heap_insert(sch, q->F, q);
  702         }
  703 
  704         if (p->if_name[0] != '\0') {/* tx clock is from a real thing */
  705             p->numbytes = -1 ; /* mark not ready for I/O */
  706             break ;
  707         }
  708     }
  709     if (sch->elements == 0 && neh->elements == 0 && p->numbytes >= 0
  710             && p->idle_heap.elements > 0) {
  711         /*
  712          * no traffic and no events scheduled. We can get rid of idle-heap.
  713          */
  714         int i ;
  715 
  716         for (i = 0 ; i < p->idle_heap.elements ; i++) {
  717             struct dn_flow_queue *q = p->idle_heap.p[i].object ;
  718 
  719             q->F = 0 ;
  720             q->S = q->F + 1 ;
  721         }
  722         p->sum = 0 ;
  723         p->V = 0 ;
  724         p->idle_heap.elements = 0 ;
  725     }
  726     /*
  727      * If we are getting clocks from dummynet (not a real interface) and
  728      * If we are under credit, schedule the next ready event.
  729      * Also fix the delivery time of the last packet.
  730      */
  731     if (p->if_name[0]==0 && p->numbytes < 0) { /* this implies bandwidth >0 */
  732         dn_key t=0 ; /* number of ticks i have to wait */
  733 
  734         if (p->bandwidth > 0)
  735             t = ( p->bandwidth -1 - p->numbytes) / p->bandwidth ;
  736         dn_tag_get(p->tail)->output_time += t ;
  737         p->sched_time = curr_time ;
  738         heap_insert(&wfq_ready_heap, curr_time + t, (void *)p);
  739         /* XXX should check errors on heap_insert, and drain the whole
  740          * queue on error hoping next time we are luckier.
  741          */
  742     }
  743     /*
  744      * If the delay line was empty call transmit_event(p) now.
  745      * Otherwise, the scheduler will take care of it.
  746      */
  747     if (p_was_empty)
  748         transmit_event(p);
  749 }
  750 
  751 /*
  752  * This is called once per tick, or HZ times per second. It is used to
  753  * increment the current tick counter and schedule expired events.
  754  */
  755 static void
  756 dummynet(void * __unused unused)
  757 {
  758     void *p ; /* generic parameter to handler */
  759     struct dn_heap *h ;
  760     struct dn_heap *heaps[3];
  761     int i;
  762     struct dn_pipe *pe ;
  763 
  764     heaps[0] = &ready_heap ;            /* fixed-rate queues */
  765     heaps[1] = &wfq_ready_heap ;        /* wfq queues */
  766     heaps[2] = &extract_heap ;          /* delay line */
  767 
  768     DUMMYNET_LOCK();
  769     curr_time++ ;
  770     for (i=0; i < 3 ; i++) {
  771         h = heaps[i];
  772         while (h->elements > 0 && DN_KEY_LEQ(h->p[0].key, curr_time) ) {
  773             if (h->p[0].key > curr_time)
  774                 printf("dummynet: warning, heap %d is %d ticks late\n",
  775                     i, (int)(curr_time - h->p[0].key));
  776             p = h->p[0].object ; /* store a copy before heap_extract */
  777             heap_extract(h, NULL); /* need to extract before processing */
  778             if (i == 0)
  779                 ready_event(p) ;
  780             else if (i == 1) {
  781                 struct dn_pipe *pipe = p;
  782                 if (pipe->if_name[0] != '\0')
  783                     printf("dummynet: bad ready_event_wfq for pipe %s\n",
  784                         pipe->if_name);
  785                 else
  786                     ready_event_wfq(p) ;
  787             } else
  788                 transmit_event(p);
  789         }
  790     }
  791     /* sweep pipes trying to expire idle flow_queues */
  792     for (pe = all_pipes; pe ; pe = pe->next )
  793         if (pe->idle_heap.elements > 0 &&
  794                 DN_KEY_LT(pe->idle_heap.p[0].key, pe->V) ) {
  795             struct dn_flow_queue *q = pe->idle_heap.p[0].object ;
  796 
  797             heap_extract(&(pe->idle_heap), NULL);
  798             q->S = q->F + 1 ; /* mark timestamp as invalid */
  799             pe->sum -= q->fs->weight ;
  800         }
  801     DUMMYNET_UNLOCK();
  802 
  803     callout_reset(&dn_timeout, 1, dummynet, NULL);
  804 }
  805 
  806 /*
  807  * called by an interface when tx_rdy occurs.
  808  */
  809 int
  810 if_tx_rdy(struct ifnet *ifp)
  811 {
  812     struct dn_pipe *p;
  813 
  814     DUMMYNET_LOCK();
  815     for (p = all_pipes; p ; p = p->next )
  816         if (p->ifp == ifp)
  817             break ;
  818     if (p == NULL) {
  819         for (p = all_pipes; p ; p = p->next )
  820             if (!strcmp(p->if_name, ifp->if_xname) ) {
  821                 p->ifp = ifp ;
  822                 DPRINTF(("dummynet: ++ tx rdy from %s (now found)\n",
  823                         ifp->if_xname));
  824                 break ;
  825             }
  826     }
  827     if (p != NULL) {
  828         DPRINTF(("dummynet: ++ tx rdy from %s - qlen %d\n", ifp->if_xname,
  829                 ifp->if_snd.ifq_len));
  830         p->numbytes = 0 ; /* mark ready for I/O */
  831         ready_event_wfq(p);
  832     }
  833     DUMMYNET_UNLOCK();
  834 
  835     return 0;
  836 }
  837 
  838 /*
  839  * Unconditionally expire empty queues in case of shortage.
  840  * Returns the number of queues freed.
  841  */
  842 static int
  843 expire_queues(struct dn_flow_set *fs)
  844 {
  845     struct dn_flow_queue *q, *prev ;
  846     int i, initial_elements = fs->rq_elements ;
  847 
  848     if (fs->last_expired == time_second)
  849         return 0 ;
  850     fs->last_expired = time_second ;
  851     for (i = 0 ; i <= fs->rq_size ; i++) /* last one is overflow */
  852         for (prev=NULL, q = fs->rq[i] ; q != NULL ; )
  853             if (q->head != NULL || q->S != q->F+1) {
  854                 prev = q ;
  855                 q = q->next ;
  856             } else { /* entry is idle, expire it */
  857                 struct dn_flow_queue *old_q = q ;
  858 
  859                 if (prev != NULL)
  860                     prev->next = q = q->next ;
  861                 else
  862                     fs->rq[i] = q = q->next ;
  863                 fs->rq_elements-- ;
  864                 free(old_q, M_DUMMYNET);
  865             }
  866     return initial_elements - fs->rq_elements ;
  867 }
  868 
  869 /*
  870  * If room, create a new queue and put at head of slot i;
  871  * otherwise, create or use the default queue.
  872  */
  873 static struct dn_flow_queue *
  874 create_queue(struct dn_flow_set *fs, int i)
  875 {
  876     struct dn_flow_queue *q ;
  877 
  878     if (fs->rq_elements > fs->rq_size * dn_max_ratio &&
  879             expire_queues(fs) == 0) {
  880         /*
  881          * No way to get room, use or create overflow queue.
  882          */
  883         i = fs->rq_size ;
  884         if ( fs->rq[i] != NULL )
  885             return fs->rq[i] ;
  886     }
  887     q = malloc(sizeof(*q), M_DUMMYNET, M_NOWAIT | M_ZERO);
  888     if (q == NULL) {
  889         printf("dummynet: sorry, cannot allocate queue for new flow\n");
  890         return NULL ;
  891     }
  892     q->fs = fs ;
  893     q->hash_slot = i ;
  894     q->next = fs->rq[i] ;
  895     q->S = q->F + 1;   /* hack - mark timestamp as invalid */
  896     fs->rq[i] = q ;
  897     fs->rq_elements++ ;
  898     return q ;
  899 }
  900 
  901 /*
  902  * Given a flow_set and a pkt in last_pkt, find a matching queue
  903  * after appropriate masking. The queue is moved to front
  904  * so that further searches take less time.
  905  */
  906 static struct dn_flow_queue *
  907 find_queue(struct dn_flow_set *fs, struct ipfw_flow_id *id)
  908 {
  909     int i = 0 ; /* we need i and q for new allocations */
  910     struct dn_flow_queue *q, *prev;
  911 
  912     if ( !(fs->flags_fs & DN_HAVE_FLOW_MASK) )
  913         q = fs->rq[0] ;
  914     else {
  915         /* first, do the masking */
  916         id->dst_ip &= fs->flow_mask.dst_ip ;
  917         id->src_ip &= fs->flow_mask.src_ip ;
  918         id->dst_port &= fs->flow_mask.dst_port ;
  919         id->src_port &= fs->flow_mask.src_port ;
  920         id->proto &= fs->flow_mask.proto ;
  921         id->flags = 0 ; /* we don't care about this one */
  922         /* then, hash function */
  923         i = ( (id->dst_ip) & 0xffff ) ^
  924             ( (id->dst_ip >> 15) & 0xffff ) ^
  925             ( (id->src_ip << 1) & 0xffff ) ^
  926             ( (id->src_ip >> 16 ) & 0xffff ) ^
  927             (id->dst_port << 1) ^ (id->src_port) ^
  928             (id->proto );
  929         i = i % fs->rq_size ;
  930         /* finally, scan the current list for a match */
  931         searches++ ;
  932         for (prev=NULL, q = fs->rq[i] ; q ; ) {
  933             search_steps++;
  934             if (id->dst_ip == q->id.dst_ip &&
  935                     id->src_ip == q->id.src_ip &&
  936                     id->dst_port == q->id.dst_port &&
  937                     id->src_port == q->id.src_port &&
  938                     id->proto == q->id.proto &&
  939                     id->flags == q->id.flags)
  940                 break ; /* found */
  941             else if (pipe_expire && q->head == NULL && q->S == q->F+1 ) {
  942                 /* entry is idle and not in any heap, expire it */
  943                 struct dn_flow_queue *old_q = q ;
  944 
  945                 if (prev != NULL)
  946                     prev->next = q = q->next ;
  947                 else
  948                     fs->rq[i] = q = q->next ;
  949                 fs->rq_elements-- ;
  950                 free(old_q, M_DUMMYNET);
  951                 continue ;
  952             }
  953             prev = q ;
  954             q = q->next ;
  955         }
  956         if (q && prev != NULL) { /* found and not in front */
  957             prev->next = q->next ;
  958             q->next = fs->rq[i] ;
  959             fs->rq[i] = q ;
  960         }
  961     }
  962     if (q == NULL) { /* no match, need to allocate a new entry */
  963         q = create_queue(fs, i);
  964         if (q != NULL)
  965         q->id = *id ;
  966     }
  967     return q ;
  968 }
  969 
  970 static int
  971 red_drops(struct dn_flow_set *fs, struct dn_flow_queue *q, int len)
  972 {
  973     /*
  974      * RED algorithm
  975      *
  976      * RED calculates the average queue size (avg) using a low-pass filter
  977      * with an exponential weighted (w_q) moving average:
  978      *  avg  <-  (1-w_q) * avg + w_q * q_size
  979      * where q_size is the queue length (measured in bytes or * packets).
  980      *
  981      * If q_size == 0, we compute the idle time for the link, and set
  982      *  avg = (1 - w_q)^(idle/s)
  983      * where s is the time needed for transmitting a medium-sized packet.
  984      *
  985      * Now, if avg < min_th the packet is enqueued.
  986      * If avg > max_th the packet is dropped. Otherwise, the packet is
  987      * dropped with probability P function of avg.
  988      *
  989      */
  990 
  991     int64_t p_b = 0;
  992     /* queue in bytes or packets ? */
  993     u_int q_size = (fs->flags_fs & DN_QSIZE_IS_BYTES) ? q->len_bytes : q->len;
  994 
  995     DPRINTF(("\ndummynet: %d q: %2u ", (int) curr_time, q_size));
  996 
  997     /* average queue size estimation */
  998     if (q_size != 0) {
  999         /*
 1000          * queue is not empty, avg <- avg + (q_size - avg) * w_q
 1001          */
 1002         int diff = SCALE(q_size) - q->avg;
 1003         int64_t v = SCALE_MUL((int64_t) diff, (int64_t) fs->w_q);
 1004 
 1005         q->avg += (int) v;
 1006     } else {
 1007         /*
 1008          * queue is empty, find for how long the queue has been
 1009          * empty and use a lookup table for computing
 1010          * (1 - * w_q)^(idle_time/s) where s is the time to send a
 1011          * (small) packet.
 1012          * XXX check wraps...
 1013          */
 1014         if (q->avg) {
 1015             u_int t = (curr_time - q->q_time) / fs->lookup_step;
 1016 
 1017             q->avg = (t < fs->lookup_depth) ?
 1018                     SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
 1019         }
 1020     }
 1021     DPRINTF(("dummynet: avg: %u ", SCALE_VAL(q->avg)));
 1022 
 1023     /* should i drop ? */
 1024 
 1025     if (q->avg < fs->min_th) {
 1026         q->count = -1;
 1027         return 0; /* accept packet ; */
 1028     }
 1029     if (q->avg >= fs->max_th) { /* average queue >=  max threshold */
 1030         if (fs->flags_fs & DN_IS_GENTLE_RED) {
 1031             /*
 1032              * According to Gentle-RED, if avg is greater than max_th the
 1033              * packet is dropped with a probability
 1034              *  p_b = c_3 * avg - c_4
 1035              * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
 1036              */
 1037             p_b = SCALE_MUL((int64_t) fs->c_3, (int64_t) q->avg) - fs->c_4;
 1038         } else {
 1039             q->count = -1;
 1040             DPRINTF(("dummynet: - drop"));
 1041             return 1 ;
 1042         }
 1043     } else if (q->avg > fs->min_th) {
 1044         /*
 1045          * we compute p_b using the linear dropping function p_b = c_1 *
 1046          * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
 1047          * max_p * min_th / (max_th - min_th)
 1048          */
 1049         p_b = SCALE_MUL((int64_t) fs->c_1, (int64_t) q->avg) - fs->c_2;
 1050     }
 1051     if (fs->flags_fs & DN_QSIZE_IS_BYTES)
 1052         p_b = (p_b * len) / fs->max_pkt_size;
 1053     if (++q->count == 0)
 1054         q->random = random() & 0xffff;
 1055     else {
 1056         /*
 1057          * q->count counts packets arrived since last drop, so a greater
 1058          * value of q->count means a greater packet drop probability.
 1059          */
 1060         if (SCALE_MUL(p_b, SCALE((int64_t) q->count)) > q->random) {
 1061             q->count = 0;
 1062             DPRINTF(("dummynet: - red drop"));
 1063             /* after a drop we calculate a new random value */
 1064             q->random = random() & 0xffff;
 1065             return 1;    /* drop */
 1066         }
 1067     }
 1068     /* end of RED algorithm */
 1069     return 0 ; /* accept */
 1070 }
 1071 
 1072 static __inline
 1073 struct dn_flow_set *
 1074 locate_flowset(int pipe_nr, struct ip_fw *rule)
 1075 {
 1076 #if IPFW2
 1077     struct dn_flow_set *fs;
 1078     ipfw_insn *cmd = rule->cmd + rule->act_ofs;
 1079 
 1080     if (cmd->opcode == O_LOG)
 1081         cmd += F_LEN(cmd);
 1082 #ifdef __i386__
 1083     fs = ((ipfw_insn_pipe *)cmd)->pipe_ptr;
 1084 #else
 1085     bcopy(& ((ipfw_insn_pipe *)cmd)->pipe_ptr, &fs, sizeof(fs));
 1086 #endif
 1087 
 1088     if (fs != NULL)
 1089         return fs;
 1090 
 1091     if (cmd->opcode == O_QUEUE)
 1092 #else /* !IPFW2 */
 1093     struct dn_flow_set *fs = NULL ;
 1094 
 1095     if ( (rule->fw_flg & IP_FW_F_COMMAND) == IP_FW_F_QUEUE )
 1096 #endif /* !IPFW2 */
 1097         for (fs=all_flow_sets; fs && fs->fs_nr != pipe_nr; fs=fs->next)
 1098             ;
 1099     else {
 1100         struct dn_pipe *p1;
 1101         for (p1 = all_pipes; p1 && p1->pipe_nr != pipe_nr; p1 = p1->next)
 1102             ;
 1103         if (p1 != NULL)
 1104             fs = &(p1->fs) ;
 1105     }
 1106     /* record for the future */
 1107 #if IPFW2
 1108 #ifdef __i386__
 1109     ((ipfw_insn_pipe *)cmd)->pipe_ptr = fs;
 1110 #else
 1111     bcopy(&fs, & ((ipfw_insn_pipe *)cmd)->pipe_ptr, sizeof(fs));
 1112 #endif
 1113 #else
 1114     if (fs != NULL)
 1115         rule->pipe_ptr = fs;
 1116 #endif
 1117     return fs ;
 1118 }
 1119 
 1120 /*
 1121  * dummynet hook for packets. Below 'pipe' is a pipe or a queue
 1122  * depending on whether WF2Q or fixed bw is used.
 1123  *
 1124  * pipe_nr      pipe or queue the packet is destined for.
 1125  * dir          where shall we send the packet after dummynet.
 1126  * m            the mbuf with the packet
 1127  * ifp          the 'ifp' parameter from the caller.
 1128  *              NULL in ip_input, destination interface in ip_output,
 1129  *              real_dst in bdg_forward
 1130  * rule         matching rule, in case of multiple passes
 1131  *
 1132  */
 1133 static int
 1134 dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
 1135 {
 1136     struct dn_pkt_tag *pkt;
 1137     struct m_tag *mtag;
 1138     struct dn_flow_set *fs;
 1139     struct dn_pipe *pipe ;
 1140     u_int64_t len = m->m_pkthdr.len ;
 1141     struct dn_flow_queue *q = NULL ;
 1142     int is_pipe;
 1143 #if IPFW2
 1144     ipfw_insn *cmd = fwa->rule->cmd + fwa->rule->act_ofs;
 1145 #endif
 1146 
 1147     KASSERT(m->m_nextpkt == NULL,
 1148         ("dummynet_io: mbuf queue passed to dummynet"));
 1149 
 1150 #if IPFW2
 1151     if (cmd->opcode == O_LOG)
 1152         cmd += F_LEN(cmd);
 1153     is_pipe = (cmd->opcode == O_PIPE);
 1154 #else
 1155     is_pipe = (fwa->rule->fw_flg & IP_FW_F_COMMAND) == IP_FW_F_PIPE;
 1156 #endif
 1157 
 1158     pipe_nr &= 0xffff ;
 1159 
 1160     DUMMYNET_LOCK();
 1161     /*
 1162      * This is a dummynet rule, so we expect an O_PIPE or O_QUEUE rule.
 1163      */
 1164     fs = locate_flowset(pipe_nr, fwa->rule);
 1165     if (fs == NULL)
 1166         goto dropit ;   /* this queue/pipe does not exist! */
 1167     pipe = fs->pipe ;
 1168     if (pipe == NULL) { /* must be a queue, try find a matching pipe */
 1169         for (pipe = all_pipes; pipe && pipe->pipe_nr != fs->parent_nr;
 1170                  pipe = pipe->next)
 1171             ;
 1172         if (pipe != NULL)
 1173             fs->pipe = pipe ;
 1174         else {
 1175             printf("dummynet: no pipe %d for queue %d, drop pkt\n",
 1176                 fs->parent_nr, fs->fs_nr);
 1177             goto dropit ;
 1178         }
 1179     }
 1180     q = find_queue(fs, &(fwa->f_id));
 1181     if ( q == NULL )
 1182         goto dropit ;           /* cannot allocate queue                */
 1183     /*
 1184      * update statistics, then check reasons to drop pkt
 1185      */
 1186     q->tot_bytes += len ;
 1187     q->tot_pkts++ ;
 1188     if ( fs->plr && random() < fs->plr )
 1189         goto dropit ;           /* random pkt drop                      */
 1190     if ( fs->flags_fs & DN_QSIZE_IS_BYTES) {
 1191         if (q->len_bytes > fs->qsize)
 1192             goto dropit ;       /* queue size overflow                  */
 1193     } else {
 1194         if (q->len >= fs->qsize)
 1195             goto dropit ;       /* queue count overflow                 */
 1196     }
 1197     if ( fs->flags_fs & DN_IS_RED && red_drops(fs, q, len) )
 1198         goto dropit ;
 1199 
 1200     /* XXX expensive to zero, see if we can remove it*/
 1201     mtag = m_tag_get(PACKET_TAG_DUMMYNET,
 1202                 sizeof(struct dn_pkt_tag), M_NOWAIT|M_ZERO);
 1203     if ( mtag == NULL )
 1204         goto dropit ;           /* cannot allocate packet header        */
 1205     m_tag_prepend(m, mtag);     /* attach to mbuf chain */
 1206 
 1207     pkt = (struct dn_pkt_tag *)(mtag+1);
 1208     /* ok, i can handle the pkt now... */
 1209     /* build and enqueue packet + parameters */
 1210     pkt->rule = fwa->rule ;
 1211     pkt->dn_dir = dir ;
 1212 
 1213     pkt->ifp = fwa->oif;
 1214     if (q->head == NULL)
 1215         q->head = m;
 1216     else
 1217         q->tail->m_nextpkt = m;
 1218     q->tail = m;
 1219     q->len++;
 1220     q->len_bytes += len ;
 1221 
 1222     if ( q->head != m )         /* flow was not idle, we are done */
 1223         goto done;
 1224     /*
 1225      * If we reach this point the flow was previously idle, so we need
 1226      * to schedule it. This involves different actions for fixed-rate or
 1227      * WF2Q queues.
 1228      */
 1229     if (is_pipe) {
 1230         /*
 1231          * Fixed-rate queue: just insert into the ready_heap.
 1232          */
 1233         dn_key t = 0 ;
 1234         if (pipe->bandwidth)
 1235             t = SET_TICKS(m, q, pipe);
 1236         q->sched_time = curr_time ;
 1237         if (t == 0)     /* must process it now */
 1238             ready_event( q );
 1239         else
 1240             heap_insert(&ready_heap, curr_time + t , q );
 1241     } else {
 1242         /*
 1243          * WF2Q. First, compute start time S: if the flow was idle (S=F+1)
 1244          * set S to the virtual time V for the controlling pipe, and update
 1245          * the sum of weights for the pipe; otherwise, remove flow from
 1246          * idle_heap and set S to max(F,V).
 1247          * Second, compute finish time F = S + len/weight.
 1248          * Third, if pipe was idle, update V=max(S, V).
 1249          * Fourth, count one more backlogged flow.
 1250          */
 1251         if (DN_KEY_GT(q->S, q->F)) { /* means timestamps are invalid */
 1252             q->S = pipe->V ;
 1253             pipe->sum += fs->weight ; /* add weight of new queue */
 1254         } else {
 1255             heap_extract(&(pipe->idle_heap), q);
 1256             q->S = MAX64(q->F, pipe->V ) ;
 1257         }
 1258         q->F = q->S + ( len<<MY_M )/(u_int64_t) fs->weight;
 1259 
 1260         if (pipe->not_eligible_heap.elements == 0 &&
 1261                 pipe->scheduler_heap.elements == 0)
 1262             pipe->V = MAX64 ( q->S, pipe->V );
 1263         fs->backlogged++ ;
 1264         /*
 1265          * Look at eligibility. A flow is not eligibile if S>V (when
 1266          * this happens, it means that there is some other flow already
 1267          * scheduled for the same pipe, so the scheduler_heap cannot be
 1268          * empty). If the flow is not eligible we just store it in the
 1269          * not_eligible_heap. Otherwise, we store in the scheduler_heap
 1270          * and possibly invoke ready_event_wfq() right now if there is
 1271          * leftover credit.
 1272          * Note that for all flows in scheduler_heap (SCH), S_i <= V,
 1273          * and for all flows in not_eligible_heap (NEH), S_i > V .
 1274          * So when we need to compute max( V, min(S_i) ) forall i in SCH+NEH,
 1275          * we only need to look into NEH.
 1276          */
 1277         if (DN_KEY_GT(q->S, pipe->V) ) { /* not eligible */
 1278             if (pipe->scheduler_heap.elements == 0)
 1279                 printf("dummynet: ++ ouch! not eligible but empty scheduler!\n");
 1280             heap_insert(&(pipe->not_eligible_heap), q->S, q);
 1281         } else {
 1282             heap_insert(&(pipe->scheduler_heap), q->F, q);
 1283             if (pipe->numbytes >= 0) { /* pipe is idle */
 1284                 if (pipe->scheduler_heap.elements != 1)
 1285                     printf("dummynet: OUCH! pipe should have been idle!\n");
 1286                 DPRINTF(("dummynet: waking up pipe %d at %d\n",
 1287                         pipe->pipe_nr, (int)(q->F >> MY_M)));
 1288                 pipe->sched_time = curr_time ;
 1289                 ready_event_wfq(pipe);
 1290             }
 1291         }
 1292     }
 1293 done:
 1294     DUMMYNET_UNLOCK();
 1295     return 0;
 1296 
 1297 dropit:
 1298     if (q)
 1299         q->drops++ ;
 1300     DUMMYNET_UNLOCK();
 1301     m_freem(m);
 1302     return ( (fs && (fs->flags_fs & DN_NOERROR)) ? 0 : ENOBUFS);
 1303 }
 1304 
 1305 /*
 1306  * Below, the rt_unref is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
 1307  * Doing this would probably save us the initial bzero of dn_pkt
 1308  */
 1309 #define DN_FREE_PKT(_m) do {                            \
 1310         m_freem(_m);                                    \
 1311 } while (0)
 1312 
 1313 /*
 1314  * Dispose all packets and flow_queues on a flow_set.
 1315  * If all=1, also remove red lookup table and other storage,
 1316  * including the descriptor itself.
 1317  * For the one in dn_pipe MUST also cleanup ready_heap...
 1318  */
 1319 static void
 1320 purge_flow_set(struct dn_flow_set *fs, int all)
 1321 {
 1322     struct dn_flow_queue *q, *qn ;
 1323     int i ;
 1324 
 1325     DUMMYNET_LOCK_ASSERT();
 1326 
 1327     for (i = 0 ; i <= fs->rq_size ; i++ ) {
 1328         for (q = fs->rq[i] ; q ; q = qn ) {
 1329             struct mbuf *m, *mnext;
 1330 
 1331             mnext = q->head;
 1332             while ((m = mnext) != NULL) {
 1333                 mnext = m->m_nextpkt;
 1334                 DN_FREE_PKT(m);
 1335             }
 1336             qn = q->next ;
 1337             free(q, M_DUMMYNET);
 1338         }
 1339         fs->rq[i] = NULL ;
 1340     }
 1341     fs->rq_elements = 0 ;
 1342     if (all) {
 1343         /* RED - free lookup table */
 1344         if (fs->w_q_lookup)
 1345             free(fs->w_q_lookup, M_DUMMYNET);
 1346         if (fs->rq)
 1347             free(fs->rq, M_DUMMYNET);
 1348         /* if this fs is not part of a pipe, free it */
 1349         if (fs->pipe && fs != &(fs->pipe->fs) )
 1350             free(fs, M_DUMMYNET);
 1351     }
 1352 }
 1353 
 1354 /*
 1355  * Dispose all packets queued on a pipe (not a flow_set).
 1356  * Also free all resources associated to a pipe, which is about
 1357  * to be deleted.
 1358  */
 1359 static void
 1360 purge_pipe(struct dn_pipe *pipe)
 1361 {
 1362     struct mbuf *m, *mnext;
 1363 
 1364     purge_flow_set( &(pipe->fs), 1 );
 1365 
 1366     mnext = pipe->head;
 1367     while ((m = mnext) != NULL) {
 1368         mnext = m->m_nextpkt;
 1369         DN_FREE_PKT(m);
 1370     }
 1371 
 1372     heap_free( &(pipe->scheduler_heap) );
 1373     heap_free( &(pipe->not_eligible_heap) );
 1374     heap_free( &(pipe->idle_heap) );
 1375 }
 1376 
 1377 /*
 1378  * Delete all pipes and heaps returning memory. Must also
 1379  * remove references from all ipfw rules to all pipes.
 1380  */
 1381 static void
 1382 dummynet_flush()
 1383 {
 1384     struct dn_pipe *curr_p, *p ;
 1385     struct dn_flow_set *fs, *curr_fs;
 1386 
 1387     DUMMYNET_LOCK();
 1388     /* remove all references to pipes ...*/
 1389     flush_pipe_ptrs(NULL);
 1390     /* prevent future matches... */
 1391     p = all_pipes ;
 1392     all_pipes = NULL ;
 1393     fs = all_flow_sets ;
 1394     all_flow_sets = NULL ;
 1395     /* and free heaps so we don't have unwanted events */
 1396     heap_free(&ready_heap);
 1397     heap_free(&wfq_ready_heap);
 1398     heap_free(&extract_heap);
 1399 
 1400     /*
 1401      * Now purge all queued pkts and delete all pipes
 1402      */
 1403     /* scan and purge all flow_sets. */
 1404     for ( ; fs ; ) {
 1405         curr_fs = fs ;
 1406         fs = fs->next ;
 1407         purge_flow_set(curr_fs, 1);
 1408     }
 1409     for ( ; p ; ) {
 1410         purge_pipe(p);
 1411         curr_p = p ;
 1412         p = p->next ;
 1413         free(curr_p, M_DUMMYNET);
 1414     }
 1415     DUMMYNET_UNLOCK();
 1416 }
 1417 
 1418 
 1419 extern struct ip_fw *ip_fw_default_rule ;
 1420 static void
 1421 dn_rule_delete_fs(struct dn_flow_set *fs, void *r)
 1422 {
 1423     int i ;
 1424     struct dn_flow_queue *q ;
 1425     struct mbuf *m ;
 1426 
 1427     for (i = 0 ; i <= fs->rq_size ; i++) /* last one is ovflow */
 1428         for (q = fs->rq[i] ; q ; q = q->next )
 1429             for (m = q->head ; m ; m = m->m_nextpkt ) {
 1430                 struct dn_pkt_tag *pkt = dn_tag_get(m) ;
 1431                 if (pkt->rule == r)
 1432                     pkt->rule = ip_fw_default_rule ;
 1433             }
 1434 }
 1435 /*
 1436  * when a firewall rule is deleted, scan all queues and remove the flow-id
 1437  * from packets matching this rule.
 1438  */
 1439 void
 1440 dn_rule_delete(void *r)
 1441 {
 1442     struct dn_pipe *p ;
 1443     struct dn_flow_set *fs ;
 1444     struct dn_pkt_tag *pkt ;
 1445     struct mbuf *m ;
 1446 
 1447     DUMMYNET_LOCK();
 1448     /*
 1449      * If the rule references a queue (dn_flow_set), then scan
 1450      * the flow set, otherwise scan pipes. Should do either, but doing
 1451      * both does not harm.
 1452      */
 1453     for ( fs = all_flow_sets ; fs ; fs = fs->next )
 1454         dn_rule_delete_fs(fs, r);
 1455     for ( p = all_pipes ; p ; p = p->next ) {
 1456         fs = &(p->fs) ;
 1457         dn_rule_delete_fs(fs, r);
 1458         for (m = p->head ; m ; m = m->m_nextpkt ) {
 1459             pkt = dn_tag_get(m) ;
 1460             if (pkt->rule == r)
 1461                 pkt->rule = ip_fw_default_rule ;
 1462         }
 1463     }
 1464     DUMMYNET_UNLOCK();
 1465 }
 1466 
 1467 /*
 1468  * setup RED parameters
 1469  */
 1470 static int
 1471 config_red(struct dn_flow_set *p, struct dn_flow_set * x)
 1472 {
 1473     int i;
 1474 
 1475     x->w_q = p->w_q;
 1476     x->min_th = SCALE(p->min_th);
 1477     x->max_th = SCALE(p->max_th);
 1478     x->max_p = p->max_p;
 1479 
 1480     x->c_1 = p->max_p / (p->max_th - p->min_th);
 1481     x->c_2 = SCALE_MUL(x->c_1, SCALE(p->min_th));
 1482     if (x->flags_fs & DN_IS_GENTLE_RED) {
 1483         x->c_3 = (SCALE(1) - p->max_p) / p->max_th;
 1484         x->c_4 = (SCALE(1) - 2 * p->max_p);
 1485     }
 1486 
 1487     /* if the lookup table already exist, free and create it again */
 1488     if (x->w_q_lookup) {
 1489         free(x->w_q_lookup, M_DUMMYNET);
 1490         x->w_q_lookup = NULL ;
 1491     }
 1492     if (red_lookup_depth == 0) {
 1493         printf("\ndummynet: net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
 1494         free(x, M_DUMMYNET);
 1495         return EINVAL;
 1496     }
 1497     x->lookup_depth = red_lookup_depth;
 1498     x->w_q_lookup = (u_int *) malloc(x->lookup_depth * sizeof(int),
 1499             M_DUMMYNET, M_NOWAIT);
 1500     if (x->w_q_lookup == NULL) {
 1501         printf("dummynet: sorry, cannot allocate red lookup table\n");
 1502         free(x, M_DUMMYNET);
 1503         return ENOSPC;
 1504     }
 1505 
 1506     /* fill the lookup table with (1 - w_q)^x */
 1507     x->lookup_step = p->lookup_step ;
 1508     x->lookup_weight = p->lookup_weight ;
 1509     x->w_q_lookup[0] = SCALE(1) - x->w_q;
 1510     for (i = 1; i < x->lookup_depth; i++)
 1511         x->w_q_lookup[i] = SCALE_MUL(x->w_q_lookup[i - 1], x->lookup_weight);
 1512     if (red_avg_pkt_size < 1)
 1513         red_avg_pkt_size = 512 ;
 1514     x->avg_pkt_size = red_avg_pkt_size ;
 1515     if (red_max_pkt_size < 1)
 1516         red_max_pkt_size = 1500 ;
 1517     x->max_pkt_size = red_max_pkt_size ;
 1518     return 0 ;
 1519 }
 1520 
 1521 static int
 1522 alloc_hash(struct dn_flow_set *x, struct dn_flow_set *pfs)
 1523 {
 1524     if (x->flags_fs & DN_HAVE_FLOW_MASK) {     /* allocate some slots */
 1525         int l = pfs->rq_size;
 1526 
 1527         if (l == 0)
 1528             l = dn_hash_size;
 1529         if (l < 4)
 1530             l = 4;
 1531         else if (l > DN_MAX_HASH_SIZE)
 1532             l = DN_MAX_HASH_SIZE;
 1533         x->rq_size = l;
 1534     } else                  /* one is enough for null mask */
 1535         x->rq_size = 1;
 1536     x->rq = malloc((1 + x->rq_size) * sizeof(struct dn_flow_queue *),
 1537             M_DUMMYNET, M_NOWAIT | M_ZERO);
 1538     if (x->rq == NULL) {
 1539         printf("dummynet: sorry, cannot allocate queue\n");
 1540         return ENOSPC;
 1541     }
 1542     x->rq_elements = 0;
 1543     return 0 ;
 1544 }
 1545 
 1546 static void
 1547 set_fs_parms(struct dn_flow_set *x, struct dn_flow_set *src)
 1548 {
 1549     x->flags_fs = src->flags_fs;
 1550     x->qsize = src->qsize;
 1551     x->plr = src->plr;
 1552     x->flow_mask = src->flow_mask;
 1553     if (x->flags_fs & DN_QSIZE_IS_BYTES) {
 1554         if (x->qsize > 1024*1024)
 1555             x->qsize = 1024*1024 ;
 1556     } else {
 1557         if (x->qsize == 0)
 1558             x->qsize = 50 ;
 1559         if (x->qsize > 100)
 1560             x->qsize = 50 ;
 1561     }
 1562     /* configuring RED */
 1563     if ( x->flags_fs & DN_IS_RED )
 1564         config_red(src, x) ;    /* XXX should check errors */
 1565 }
 1566 
 1567 /*
 1568  * setup pipe or queue parameters.
 1569  */
 1570 
 1571 static int
 1572 config_pipe(struct dn_pipe *p)
 1573 {
 1574     int i, r;
 1575     struct dn_flow_set *pfs = &(p->fs);
 1576     struct dn_flow_queue *q;
 1577 
 1578     /*
 1579      * The config program passes parameters as follows:
 1580      * bw = bits/second (0 means no limits),
 1581      * delay = ms, must be translated into ticks.
 1582      * qsize = slots/bytes
 1583      */
 1584     p->delay = ( p->delay * hz ) / 1000 ;
 1585     /* We need either a pipe number or a flow_set number */
 1586     if (p->pipe_nr == 0 && pfs->fs_nr == 0)
 1587         return EINVAL ;
 1588     if (p->pipe_nr != 0 && pfs->fs_nr != 0)
 1589         return EINVAL ;
 1590     if (p->pipe_nr != 0) { /* this is a pipe */
 1591         struct dn_pipe *x, *a, *b;
 1592 
 1593         DUMMYNET_LOCK();
 1594         /* locate pipe */
 1595         for (a = NULL , b = all_pipes ; b && b->pipe_nr < p->pipe_nr ;
 1596                  a = b , b = b->next) ;
 1597 
 1598         if (b == NULL || b->pipe_nr != p->pipe_nr) { /* new pipe */
 1599             x = malloc(sizeof(struct dn_pipe), M_DUMMYNET, M_NOWAIT | M_ZERO);
 1600             if (x == NULL) {
 1601                 DUMMYNET_UNLOCK();
 1602                 printf("dummynet: no memory for new pipe\n");
 1603                 return ENOSPC;
 1604             }
 1605             x->pipe_nr = p->pipe_nr;
 1606             x->fs.pipe = x ;
 1607             /* idle_heap is the only one from which we extract from the middle.
 1608              */
 1609             x->idle_heap.size = x->idle_heap.elements = 0 ;
 1610             x->idle_heap.offset=OFFSET_OF(struct dn_flow_queue, heap_pos);
 1611         } else {
 1612             x = b;
 1613             /* Flush accumulated credit for all queues */
 1614             for (i = 0; i <= x->fs.rq_size; i++)
 1615                 for (q = x->fs.rq[i]; q; q = q->next)
 1616                     q->numbytes = 0;
 1617         }
 1618 
 1619         x->bandwidth = p->bandwidth ;
 1620         x->numbytes = 0; /* just in case... */
 1621         bcopy(p->if_name, x->if_name, sizeof(p->if_name) );
 1622         x->ifp = NULL ; /* reset interface ptr */
 1623         x->delay = p->delay ;
 1624         set_fs_parms(&(x->fs), pfs);
 1625 
 1626 
 1627         if ( x->fs.rq == NULL ) { /* a new pipe */
 1628             r = alloc_hash(&(x->fs), pfs) ;
 1629             if (r) {
 1630                 DUMMYNET_UNLOCK();
 1631                 free(x, M_DUMMYNET);
 1632                 return r ;
 1633             }
 1634             x->next = b ;
 1635             if (a == NULL)
 1636                 all_pipes = x ;
 1637             else
 1638                 a->next = x ;
 1639         }
 1640         DUMMYNET_UNLOCK();
 1641     } else { /* config queue */
 1642         struct dn_flow_set *x, *a, *b ;
 1643 
 1644         DUMMYNET_LOCK();
 1645         /* locate flow_set */
 1646         for (a=NULL, b=all_flow_sets ; b && b->fs_nr < pfs->fs_nr ;
 1647                  a = b , b = b->next) ;
 1648 
 1649         if (b == NULL || b->fs_nr != pfs->fs_nr) { /* new  */
 1650             if (pfs->parent_nr == 0) {  /* need link to a pipe */
 1651                 DUMMYNET_UNLOCK();
 1652                 return EINVAL ;
 1653             }
 1654             x = malloc(sizeof(struct dn_flow_set), M_DUMMYNET, M_NOWAIT|M_ZERO);
 1655             if (x == NULL) {
 1656                 DUMMYNET_UNLOCK();
 1657                 printf("dummynet: no memory for new flow_set\n");
 1658                 return ENOSPC;
 1659             }
 1660             x->fs_nr = pfs->fs_nr;
 1661             x->parent_nr = pfs->parent_nr;
 1662             x->weight = pfs->weight ;
 1663             if (x->weight == 0)
 1664                 x->weight = 1 ;
 1665             else if (x->weight > 100)
 1666                 x->weight = 100 ;
 1667         } else {
 1668             /* Change parent pipe not allowed; must delete and recreate */
 1669             if (pfs->parent_nr != 0 && b->parent_nr != pfs->parent_nr) {
 1670                 DUMMYNET_UNLOCK();
 1671                 return EINVAL ;
 1672             }
 1673             x = b;
 1674         }
 1675         set_fs_parms(x, pfs);
 1676 
 1677         if ( x->rq == NULL ) { /* a new flow_set */
 1678             r = alloc_hash(x, pfs) ;
 1679             if (r) {
 1680                 DUMMYNET_UNLOCK();
 1681                 free(x, M_DUMMYNET);
 1682                 return r ;
 1683             }
 1684             x->next = b;
 1685             if (a == NULL)
 1686                 all_flow_sets = x;
 1687             else
 1688                 a->next = x;
 1689         }
 1690         DUMMYNET_UNLOCK();
 1691     }
 1692     return 0 ;
 1693 }
 1694 
 1695 /*
 1696  * Helper function to remove from a heap queues which are linked to
 1697  * a flow_set about to be deleted.
 1698  */
 1699 static void
 1700 fs_remove_from_heap(struct dn_heap *h, struct dn_flow_set *fs)
 1701 {
 1702     int i = 0, found = 0 ;
 1703     for (; i < h->elements ;)
 1704         if ( ((struct dn_flow_queue *)h->p[i].object)->fs == fs) {
 1705             h->elements-- ;
 1706             h->p[i] = h->p[h->elements] ;
 1707             found++ ;
 1708         } else
 1709             i++ ;
 1710     if (found)
 1711         heapify(h);
 1712 }
 1713 
 1714 /*
 1715  * helper function to remove a pipe from a heap (can be there at most once)
 1716  */
 1717 static void
 1718 pipe_remove_from_heap(struct dn_heap *h, struct dn_pipe *p)
 1719 {
 1720     if (h->elements > 0) {
 1721         int i = 0 ;
 1722         for (i=0; i < h->elements ; i++ ) {
 1723             if (h->p[i].object == p) { /* found it */
 1724                 h->elements-- ;
 1725                 h->p[i] = h->p[h->elements] ;
 1726                 heapify(h);
 1727                 break ;
 1728             }
 1729         }
 1730     }
 1731 }
 1732 
 1733 /*
 1734  * drain all queues. Called in case of severe mbuf shortage.
 1735  */
 1736 void
 1737 dummynet_drain()
 1738 {
 1739     struct dn_flow_set *fs;
 1740     struct dn_pipe *p;
 1741     struct mbuf *m, *mnext;
 1742 
 1743     DUMMYNET_LOCK_ASSERT();
 1744 
 1745     heap_free(&ready_heap);
 1746     heap_free(&wfq_ready_heap);
 1747     heap_free(&extract_heap);
 1748     /* remove all references to this pipe from flow_sets */
 1749     for (fs = all_flow_sets; fs; fs= fs->next )
 1750         purge_flow_set(fs, 0);
 1751 
 1752     for (p = all_pipes; p; p= p->next ) {
 1753         purge_flow_set(&(p->fs), 0);
 1754 
 1755         mnext = p->head;
 1756         while ((m = mnext) != NULL) {
 1757             mnext = m->m_nextpkt;
 1758             DN_FREE_PKT(m);
 1759         }
 1760         p->head = p->tail = NULL ;
 1761     }
 1762 }
 1763 
 1764 /*
 1765  * Fully delete a pipe or a queue, cleaning up associated info.
 1766  */
 1767 static int
 1768 delete_pipe(struct dn_pipe *p)
 1769 {
 1770     if (p->pipe_nr == 0 && p->fs.fs_nr == 0)
 1771         return EINVAL ;
 1772     if (p->pipe_nr != 0 && p->fs.fs_nr != 0)
 1773         return EINVAL ;
 1774     if (p->pipe_nr != 0) { /* this is an old-style pipe */
 1775         struct dn_pipe *a, *b;
 1776         struct dn_flow_set *fs;
 1777 
 1778         DUMMYNET_LOCK();
 1779         /* locate pipe */
 1780         for (a = NULL , b = all_pipes ; b && b->pipe_nr < p->pipe_nr ;
 1781                  a = b , b = b->next) ;
 1782         if (b == NULL || (b->pipe_nr != p->pipe_nr) ) {
 1783             DUMMYNET_UNLOCK();
 1784             return EINVAL ; /* not found */
 1785         }
 1786 
 1787         /* unlink from list of pipes */
 1788         if (a == NULL)
 1789             all_pipes = b->next ;
 1790         else
 1791             a->next = b->next ;
 1792         /* remove references to this pipe from the ip_fw rules. */
 1793         flush_pipe_ptrs(&(b->fs));
 1794 
 1795         /* remove all references to this pipe from flow_sets */
 1796         for (fs = all_flow_sets; fs; fs= fs->next )
 1797             if (fs->pipe == b) {
 1798                 printf("dummynet: ++ ref to pipe %d from fs %d\n",
 1799                         p->pipe_nr, fs->fs_nr);
 1800                 fs->pipe = NULL ;
 1801                 purge_flow_set(fs, 0);
 1802             }
 1803         fs_remove_from_heap(&ready_heap, &(b->fs));
 1804         purge_pipe(b);  /* remove all data associated to this pipe */
 1805         /* remove reference to here from extract_heap and wfq_ready_heap */
 1806         pipe_remove_from_heap(&extract_heap, b);
 1807         pipe_remove_from_heap(&wfq_ready_heap, b);
 1808         DUMMYNET_UNLOCK();
 1809 
 1810         free(b, M_DUMMYNET);
 1811     } else { /* this is a WF2Q queue (dn_flow_set) */
 1812         struct dn_flow_set *a, *b;
 1813 
 1814         DUMMYNET_LOCK();
 1815         /* locate set */
 1816         for (a = NULL, b = all_flow_sets ; b && b->fs_nr < p->fs.fs_nr ;
 1817                  a = b , b = b->next) ;
 1818         if (b == NULL || (b->fs_nr != p->fs.fs_nr) ) {
 1819             DUMMYNET_UNLOCK();
 1820             return EINVAL ; /* not found */
 1821         }
 1822 
 1823         if (a == NULL)
 1824             all_flow_sets = b->next ;
 1825         else
 1826             a->next = b->next ;
 1827         /* remove references to this flow_set from the ip_fw rules. */
 1828         flush_pipe_ptrs(b);
 1829 
 1830         if (b->pipe != NULL) {
 1831             /* Update total weight on parent pipe and cleanup parent heaps */
 1832             b->pipe->sum -= b->weight * b->backlogged ;
 1833             fs_remove_from_heap(&(b->pipe->not_eligible_heap), b);
 1834             fs_remove_from_heap(&(b->pipe->scheduler_heap), b);
 1835 #if 1   /* XXX should i remove from idle_heap as well ? */
 1836             fs_remove_from_heap(&(b->pipe->idle_heap), b);
 1837 #endif
 1838         }
 1839         purge_flow_set(b, 1);
 1840         DUMMYNET_UNLOCK();
 1841     }
 1842     return 0 ;
 1843 }
 1844 
 1845 /*
 1846  * helper function used to copy data from kernel in DUMMYNET_GET
 1847  */
 1848 static char *
 1849 dn_copy_set(struct dn_flow_set *set, char *bp)
 1850 {
 1851     int i, copied = 0 ;
 1852     struct dn_flow_queue *q, *qp = (struct dn_flow_queue *)bp;
 1853 
 1854     DUMMYNET_LOCK_ASSERT();
 1855 
 1856     for (i = 0 ; i <= set->rq_size ; i++)
 1857         for (q = set->rq[i] ; q ; q = q->next, qp++ ) {
 1858             if (q->hash_slot != i)
 1859                 printf("dummynet: ++ at %d: wrong slot (have %d, "
 1860                     "should be %d)\n", copied, q->hash_slot, i);
 1861             if (q->fs != set)
 1862                 printf("dummynet: ++ at %d: wrong fs ptr (have %p, should be %p)\n",
 1863                         i, q->fs, set);
 1864             copied++ ;
 1865             bcopy(q, qp, sizeof( *q ) );
 1866             /* cleanup pointers */
 1867             qp->next = NULL ;
 1868             qp->head = qp->tail = NULL ;
 1869             qp->fs = NULL ;
 1870         }
 1871     if (copied != set->rq_elements)
 1872         printf("dummynet: ++ wrong count, have %d should be %d\n",
 1873             copied, set->rq_elements);
 1874     return (char *)qp ;
 1875 }
 1876 
 1877 static size_t
 1878 dn_calc_size(void)
 1879 {
 1880     struct dn_flow_set *set ;
 1881     struct dn_pipe *p ;
 1882     size_t size ;
 1883 
 1884     DUMMYNET_LOCK_ASSERT();
 1885     /*
 1886      * compute size of data structures: list of pipes and flow_sets.
 1887      */
 1888     for (p = all_pipes, size = 0 ; p ; p = p->next )
 1889         size += sizeof( *p ) +
 1890             p->fs.rq_elements * sizeof(struct dn_flow_queue);
 1891     for (set = all_flow_sets ; set ; set = set->next )
 1892         size += sizeof ( *set ) +
 1893             set->rq_elements * sizeof(struct dn_flow_queue);
 1894     return size ;
 1895 }
 1896 
 1897 static int
 1898 dummynet_get(struct sockopt *sopt)
 1899 {
 1900     char *buf, *bp ; /* bp is the "copy-pointer" */
 1901     size_t size ;
 1902     struct dn_flow_set *set ;
 1903     struct dn_pipe *p ;
 1904     int error=0, i ;
 1905 
 1906     /* XXX lock held too long */
 1907     DUMMYNET_LOCK();
 1908     /*
 1909      * XXX: Ugly, but we need to allocate memory with M_WAITOK flag and we
 1910      *      cannot use this flag while holding a mutex.
 1911      */
 1912     for (i = 0; i < 10; i++) {
 1913         size = dn_calc_size();
 1914         DUMMYNET_UNLOCK();
 1915         buf = malloc(size, M_TEMP, M_WAITOK);
 1916         DUMMYNET_LOCK();
 1917         if (size == dn_calc_size())
 1918                 break;
 1919         free(buf, M_TEMP);
 1920         buf = NULL;
 1921     }
 1922     if (buf == NULL) {
 1923         DUMMYNET_UNLOCK();
 1924         return ENOBUFS ;
 1925     }
 1926     for (p = all_pipes, bp = buf ; p ; p = p->next ) {
 1927         struct dn_pipe *pipe_bp = (struct dn_pipe *)bp ;
 1928 
 1929         /*
 1930          * copy pipe descriptor into *bp, convert delay back to ms,
 1931          * then copy the flow_set descriptor(s) one at a time.
 1932          * After each flow_set, copy the queue descriptor it owns.
 1933          */
 1934         bcopy(p, bp, sizeof( *p ) );
 1935         pipe_bp->delay = (pipe_bp->delay * 1000) / hz ;
 1936         /*
 1937          * XXX the following is a hack based on ->next being the
 1938          * first field in dn_pipe and dn_flow_set. The correct
 1939          * solution would be to move the dn_flow_set to the beginning
 1940          * of struct dn_pipe.
 1941          */
 1942         pipe_bp->next = (struct dn_pipe *)DN_IS_PIPE ;
 1943         /* clean pointers */
 1944         pipe_bp->head = pipe_bp->tail = NULL ;
 1945         pipe_bp->fs.next = NULL ;
 1946         pipe_bp->fs.pipe = NULL ;
 1947         pipe_bp->fs.rq = NULL ;
 1948 
 1949         bp += sizeof( *p ) ;
 1950         bp = dn_copy_set( &(p->fs), bp );
 1951     }
 1952     for (set = all_flow_sets ; set ; set = set->next ) {
 1953         struct dn_flow_set *fs_bp = (struct dn_flow_set *)bp ;
 1954         bcopy(set, bp, sizeof( *set ) );
 1955         /* XXX same hack as above */
 1956         fs_bp->next = (struct dn_flow_set *)DN_IS_QUEUE ;
 1957         fs_bp->pipe = NULL ;
 1958         fs_bp->rq = NULL ;
 1959         bp += sizeof( *set ) ;
 1960         bp = dn_copy_set( set, bp );
 1961     }
 1962     DUMMYNET_UNLOCK();
 1963 
 1964     error = sooptcopyout(sopt, buf, size);
 1965     free(buf, M_TEMP);
 1966     return error ;
 1967 }
 1968 
 1969 /*
 1970  * Handler for the various dummynet socket options (get, flush, config, del)
 1971  */
 1972 static int
 1973 ip_dn_ctl(struct sockopt *sopt)
 1974 {
 1975     int error = 0 ;
 1976     struct dn_pipe *p, tmp_pipe;
 1977 
 1978     /* Disallow sets in really-really secure mode. */
 1979     if (sopt->sopt_dir == SOPT_SET) {
 1980 #if __FreeBSD_version >= 500034
 1981         error =  securelevel_ge(sopt->sopt_td->td_ucred, 3);
 1982         if (error)
 1983             return (error);
 1984 #else
 1985         if (securelevel >= 3)
 1986             return (EPERM);
 1987 #endif
 1988     }
 1989 
 1990     switch (sopt->sopt_name) {
 1991     default :
 1992         printf("dummynet: -- unknown option %d", sopt->sopt_name);
 1993         return EINVAL ;
 1994 
 1995     case IP_DUMMYNET_GET :
 1996         error = dummynet_get(sopt);
 1997         break ;
 1998 
 1999     case IP_DUMMYNET_FLUSH :
 2000         dummynet_flush() ;
 2001         break ;
 2002 
 2003     case IP_DUMMYNET_CONFIGURE :
 2004         p = &tmp_pipe ;
 2005         error = sooptcopyin(sopt, p, sizeof *p, sizeof *p);
 2006         if (error)
 2007             break ;
 2008         error = config_pipe(p);
 2009         break ;
 2010 
 2011     case IP_DUMMYNET_DEL :      /* remove a pipe or queue */
 2012         p = &tmp_pipe ;
 2013         error = sooptcopyin(sopt, p, sizeof *p, sizeof *p);
 2014         if (error)
 2015             break ;
 2016 
 2017         error = delete_pipe(p);
 2018         break ;
 2019     }
 2020     return error ;
 2021 }
 2022 
 2023 static void
 2024 ip_dn_init(void)
 2025 {
 2026     if (bootverbose)
 2027             printf("DUMMYNET initialized (011031)\n");
 2028 
 2029     DUMMYNET_LOCK_INIT();
 2030 
 2031     all_pipes = NULL ;
 2032     all_flow_sets = NULL ;
 2033     ready_heap.size = ready_heap.elements = 0 ;
 2034     ready_heap.offset = 0 ;
 2035 
 2036     wfq_ready_heap.size = wfq_ready_heap.elements = 0 ;
 2037     wfq_ready_heap.offset = 0 ;
 2038 
 2039     extract_heap.size = extract_heap.elements = 0 ;
 2040     extract_heap.offset = 0 ;
 2041 
 2042     ip_dn_ctl_ptr = ip_dn_ctl;
 2043     ip_dn_io_ptr = dummynet_io;
 2044     ip_dn_ruledel_ptr = dn_rule_delete;
 2045 
 2046     callout_init(&dn_timeout, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
 2047     callout_reset(&dn_timeout, 1, dummynet, NULL);
 2048 }
 2049 
 2050 #ifdef KLD_MODULE
 2051 static void
 2052 ip_dn_destroy(void)
 2053 {
 2054     ip_dn_ctl_ptr = NULL;
 2055     ip_dn_io_ptr = NULL;
 2056     ip_dn_ruledel_ptr = NULL;
 2057 
 2058     callout_stop(&dn_timeout);
 2059     dummynet_flush();
 2060 
 2061     DUMMYNET_LOCK_DESTROY();
 2062 }
 2063 #endif /* KLD_MODULE */
 2064 
 2065 static int
 2066 dummynet_modevent(module_t mod, int type, void *data)
 2067 {
 2068         switch (type) {
 2069         case MOD_LOAD:
 2070                 if (DUMMYNET_LOADED) {
 2071                     printf("DUMMYNET already loaded\n");
 2072                     return EEXIST ;
 2073                 }
 2074                 ip_dn_init();
 2075                 break;
 2076 
 2077         case MOD_UNLOAD:
 2078 #if !defined(KLD_MODULE)
 2079                 printf("dummynet statically compiled, cannot unload\n");
 2080                 return EINVAL ;
 2081 #else
 2082                 ip_dn_destroy();
 2083 #endif
 2084                 break ;
 2085         default:
 2086                 return EOPNOTSUPP;
 2087                 break ;
 2088         }
 2089         return 0 ;
 2090 }
 2091 
 2092 static moduledata_t dummynet_mod = {
 2093         "dummynet",
 2094         dummynet_modevent,
 2095         NULL
 2096 };
 2097 DECLARE_MODULE(dummynet, dummynet_mod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
 2098 MODULE_DEPEND(dummynet, ipfw, 2, 2, 2);
 2099 MODULE_VERSION(dummynet, 1);

Cache object: c825e9a55599c30af9725551f96fd448


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.