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