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