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