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

Cache object: 1240f9eeffb22b3eb4f019c327b9426c


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