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

Cache object: 5136a327fd4b0113de846b2110680462


[ 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.