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