Merge from vendor branch SENDMAIL:
[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.41 2007/11/03 13:14:29 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       10000
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_ioc_pipe *);
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     p->numbytes += (curr_time - p->sched_time) * p->bandwidth;
561
562     /*
563      * While we have backlogged traffic AND credit, we need to do
564      * something on the queue.
565      */
566     while (p->numbytes >= 0 && (sch->elements > 0 || neh->elements > 0)) {
567         if (sch->elements > 0) { /* Have some eligible pkts to send out */
568             struct dn_flow_queue *q = sch->p[0].object;
569             struct dn_pkt *pkt = q->head;
570             struct dn_flow_set *fs = q->fs;
571             uint64_t len = pkt->dn_m->m_pkthdr.len;
572             int len_scaled = p->bandwidth ? len*8*dn_hz : 0;
573
574             heap_extract(sch, NULL);    /* Remove queue from heap */
575             p->numbytes -= len_scaled;
576             move_pkt(pkt, q, p, len);
577
578             p->V += (len << MY_M) / p->sum;     /* Update V */
579             q->S = q->F;                        /* Update start time */
580
581             if (q->len == 0) {  /* Flow not backlogged any more */
582                 fs->backlogged--;
583                 heap_insert(&p->idle_heap, q->F, q);
584             } else {            /* Still backlogged */
585                 /*
586                  * Update F and position in backlogged queue, then
587                  * put flow in not_eligible_heap (we will fix this later).
588                  */
589                 len = q->head->dn_m->m_pkthdr.len;
590                 q->F += (len << MY_M) / (uint64_t)fs->weight;
591                 if (DN_KEY_LEQ(q->S, p->V))
592                     heap_insert(neh, q->S, q);
593                 else
594                     heap_insert(sch, q->F, q);
595             }
596         }
597
598         /*
599          * Now compute V = max(V, min(S_i)).  Remember that all elements in
600          * sch have by definition S_i <= V so if sch is not empty, V is surely
601          * the max and we must not update it.  Conversely, if sch is empty
602          * we only need to look at neh.
603          */
604         if (sch->elements == 0 && neh->elements > 0)
605             p->V = MAX64(p->V, neh->p[0].key);
606
607         /*
608          * Move from neh to sch any packets that have become eligible
609          */
610         while (neh->elements > 0 && DN_KEY_LEQ(neh->p[0].key, p->V)) {
611             struct dn_flow_queue *q = neh->p[0].object;
612
613             heap_extract(neh, NULL);
614             heap_insert(sch, q->F, q);
615         }
616     }
617
618     if (sch->elements == 0 && neh->elements == 0 && p->numbytes >= 0 &&
619         p->idle_heap.elements > 0) {
620         /*
621          * No traffic and no events scheduled.  We can get rid of idle-heap.
622          */
623         int i;
624
625         for (i = 0; i < p->idle_heap.elements; i++) {
626             struct dn_flow_queue *q = p->idle_heap.p[i].object;
627
628             q->F = 0;
629             q->S = q->F + 1;
630         }
631         p->sum = 0;
632         p->V = 0;
633         p->idle_heap.elements = 0;
634     }
635
636     /*
637      * If we are getting clocks from dummynet and if we are under credit,
638      * schedule the next ready event.
639      * Also fix the delivery time of the last packet.
640      */
641     if (p->numbytes < 0) { /* This implies bandwidth>0 */
642         dn_key t = 0; /* Number of ticks i have to wait */
643
644         if (p->bandwidth > 0)
645             t = (p->bandwidth - 1 - p->numbytes) / p->bandwidth;
646         p->tail->output_time += t;
647         p->sched_time = curr_time;
648
649         /*
650          * XXX should check errors on heap_insert, and drain the whole
651          * queue on error hoping next time we are luckier.
652          */
653         heap_insert(&wfq_ready_heap, curr_time + t, p);
654     }
655
656     /*
657      * If the delay line was empty call transmit_event(p) now.
658      * Otherwise, the scheduler will take care of it.
659      */
660     if (p_was_empty)
661         transmit_event(p);
662 }
663
664 /*
665  * This is called once per tick, or dn_hz times per second.  It is used to
666  * increment the current tick counter and schedule expired events.
667  */
668 static void
669 dummynet(struct netmsg *msg)
670 {
671     void *p;
672     struct dn_heap *h;
673     struct dn_heap *heaps[3];
674     int i;
675     struct dn_pipe *pe;
676
677     heaps[0] = &ready_heap;             /* Fixed-rate queues */
678     heaps[1] = &wfq_ready_heap;         /* WF2Q queues */
679     heaps[2] = &extract_heap;           /* Delay line */
680
681     crit_enter();
682
683     /* Reply ASAP */
684     lwkt_replymsg(&msg->nm_lmsg, 0);
685
686     curr_time++;
687     for (i = 0; i < 3; i++) {
688         h = heaps[i];
689         while (h->elements > 0 && DN_KEY_LEQ(h->p[0].key, curr_time)) {
690             DDB(if (h->p[0].key > curr_time)
691                 kprintf("-- dummynet: warning, heap %d is %d ticks late\n",
692                     i, (int)(curr_time - h->p[0].key));)
693
694             p = h->p[0].object;         /* Store a copy before heap_extract */
695             heap_extract(h, NULL);      /* Need to extract before processing */
696
697             if (i == 0)
698                 ready_event(p);
699             else if (i == 1)
700                 ready_event_wfq(p);
701             else
702                 transmit_event(p);
703         }
704     }
705
706     /*
707      * Sweep pipes trying to expire idle flow_queues
708      */
709     for (pe = all_pipes; pe; pe = pe->next) {
710         if (pe->idle_heap.elements > 0 &&
711             DN_KEY_LT(pe->idle_heap.p[0].key, pe->V)) {
712             struct dn_flow_queue *q = pe->idle_heap.p[0].object;
713
714             heap_extract(&pe->idle_heap, NULL);
715             q->S = q->F + 1; /* Mark timestamp as invalid */
716             pe->sum -= q->fs->weight;
717         }
718     }
719
720     crit_exit();
721 }
722
723 /*
724  * Unconditionally expire empty queues in case of shortage.
725  * Returns the number of queues freed.
726  */
727 static int
728 expire_queues(struct dn_flow_set *fs)
729 {
730     struct dn_flow_queue *q, *prev;
731     int i, initial_elements = fs->rq_elements;
732
733     if (fs->last_expired == time_second)
734         return 0;
735
736     fs->last_expired = time_second;
737
738     for (i = 0; i <= fs->rq_size; i++) { /* Last one is overflow */
739         for (prev = NULL, q = fs->rq[i]; q != NULL;) {
740             if (q->head != NULL || q->S != q->F + 1) {
741                 prev = q;
742                 q = q->next;
743             } else {    /* Entry is idle, expire it */
744                 struct dn_flow_queue *old_q = q;
745
746                 if (prev != NULL)
747                     prev->next = q = q->next;
748                 else
749                     fs->rq[i] = q = q->next;
750                 fs->rq_elements-- ;
751                 kfree(old_q, M_DUMMYNET);
752             }
753         }
754     }
755     return initial_elements - fs->rq_elements;
756 }
757
758 /*
759  * If room, create a new queue and put at head of slot i;
760  * otherwise, create or use the default queue.
761  */
762 static struct dn_flow_queue *
763 create_queue(struct dn_flow_set *fs, int i)
764 {
765     struct dn_flow_queue *q;
766
767     if (fs->rq_elements > fs->rq_size * dn_max_ratio &&
768         expire_queues(fs) == 0) {
769         /*
770          * No way to get room, use or create overflow queue.
771          */
772         i = fs->rq_size;
773         if (fs->rq[i] != NULL)
774             return fs->rq[i];
775     }
776
777     q = kmalloc(sizeof(*q), M_DUMMYNET, M_INTWAIT | M_NULLOK | M_ZERO);
778     if (q == NULL)
779         return NULL;
780
781     q->fs = fs;
782     q->hash_slot = i;
783     q->next = fs->rq[i];
784     q->S = q->F + 1;   /* hack - mark timestamp as invalid */
785     fs->rq[i] = q;
786     fs->rq_elements++;
787
788     return q;
789 }
790
791 /*
792  * Given a flow_set and a pkt in last_pkt, find a matching queue
793  * after appropriate masking. The queue is moved to front
794  * so that further searches take less time.
795  */
796 static struct dn_flow_queue *
797 find_queue(struct dn_flow_set *fs, struct ipfw_flow_id *id)
798 {
799     struct dn_flow_queue *q, *prev;
800     int i = 0;
801
802     if (!(fs->flags_fs & DN_HAVE_FLOW_MASK)) {
803         q = fs->rq[0];
804     } else {
805         /* First, do the masking */
806         id->dst_ip &= fs->flow_mask.dst_ip;
807         id->src_ip &= fs->flow_mask.src_ip;
808         id->dst_port &= fs->flow_mask.dst_port;
809         id->src_port &= fs->flow_mask.src_port;
810         id->proto &= fs->flow_mask.proto;
811         id->flags = 0; /* we don't care about this one */
812
813         /* Then, hash function */
814         i = ((id->dst_ip) & 0xffff) ^
815             ((id->dst_ip >> 15) & 0xffff) ^
816             ((id->src_ip << 1) & 0xffff) ^
817             ((id->src_ip >> 16 ) & 0xffff) ^
818             (id->dst_port << 1) ^ (id->src_port) ^
819             (id->proto);
820         i = i % fs->rq_size;
821
822         /* Finally, scan the current list for a match */
823         searches++;
824         for (prev = NULL, q = fs->rq[i]; q;) {
825             search_steps++;
826             if (id->dst_ip == q->id.dst_ip &&
827                 id->src_ip == q->id.src_ip &&
828                 id->dst_port == q->id.dst_port &&
829                 id->src_port == q->id.src_port &&
830                 id->proto == q->id.proto &&
831                 id->flags == q->id.flags) {
832                 break; /* Found */
833             } else if (pipe_expire && q->head == NULL && q->S == q->F + 1) {
834                 /* Entry is idle and not in any heap, expire it */
835                 struct dn_flow_queue *old_q = q;
836
837                 if (prev != NULL)
838                     prev->next = q = q->next;
839                 else
840                     fs->rq[i] = q = q->next;
841                 fs->rq_elements--;
842                 kfree(old_q, M_DUMMYNET);
843                 continue;
844             }
845             prev = q;
846             q = q->next;
847         }
848         if (q && prev != NULL) { /* Found and not in front */
849             prev->next = q->next;
850             q->next = fs->rq[i];
851             fs->rq[i] = q;
852         }
853     }
854     if (q == NULL) {    /* No match, need to allocate a new entry */
855         q = create_queue(fs, i);
856         if (q != NULL)
857             q->id = *id;
858     }
859     return q;
860 }
861
862 static int
863 red_drops(struct dn_flow_set *fs, struct dn_flow_queue *q, int len)
864 {
865     /*
866      * RED algorithm
867      *
868      * RED calculates the average queue size (avg) using a low-pass filter
869      * with an exponential weighted (w_q) moving average:
870      *  avg  <-  (1-w_q) * avg + w_q * q_size
871      * where q_size is the queue length (measured in bytes or * packets).
872      *
873      * If q_size == 0, we compute the idle time for the link, and set
874      *  avg = (1 - w_q)^(idle/s)
875      * where s is the time needed for transmitting a medium-sized packet.
876      *
877      * Now, if avg < min_th the packet is enqueued.
878      * If avg > max_th the packet is dropped. Otherwise, the packet is
879      * dropped with probability P function of avg.
880      */
881
882     int64_t p_b = 0;
883     u_int q_size = (fs->flags_fs & DN_QSIZE_IS_BYTES) ? q->len_bytes : q->len;
884
885     DEB(kprintf("\n%d q: %2u ", (int) curr_time, q_size);)
886
887     /* Average queue size estimation */
888     if (q_size != 0) {
889         /*
890          * Queue is not empty, avg <- avg + (q_size - avg) * w_q
891          */
892         int diff = SCALE(q_size) - q->avg;
893         int64_t v = SCALE_MUL((int64_t)diff, (int64_t)fs->w_q);
894
895         q->avg += (int)v;
896     } else {
897         /*
898          * Queue is empty, find for how long the queue has been
899          * empty and use a lookup table for computing
900          * (1 - * w_q)^(idle_time/s) where s is the time to send a
901          * (small) packet.
902          * XXX check wraps...
903          */
904         if (q->avg) {
905             u_int t = (curr_time - q->q_time) / fs->lookup_step;
906
907             q->avg = (t < fs->lookup_depth) ?
908                      SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
909         }
910     }
911     DEB(kprintf("avg: %u ", SCALE_VAL(q->avg));)
912
913     /* Should i drop? */
914
915     if (q->avg < fs->min_th) {
916         /* Accept packet */
917         q->count = -1;
918         return 0;
919     }
920
921     if (q->avg >= fs->max_th) { /* Average queue >=  Max threshold */
922         if (fs->flags_fs & DN_IS_GENTLE_RED) {
923             /*
924              * According to Gentle-RED, if avg is greater than max_th the
925              * packet is dropped with a probability
926              *  p_b = c_3 * avg - c_4
927              * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
928              */
929             p_b = SCALE_MUL((int64_t)fs->c_3, (int64_t)q->avg) - fs->c_4;
930         } else {
931             q->count = -1;
932             kprintf("- drop\n");
933             return 1;
934         }
935     } else if (q->avg > fs->min_th) {
936         /*
937          * We compute p_b using the linear dropping function p_b = c_1 *
938          * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
939          * max_p * min_th / (max_th - min_th)
940          */
941         p_b = SCALE_MUL((int64_t)fs->c_1, (int64_t)q->avg) - fs->c_2;
942     }
943     if (fs->flags_fs & DN_QSIZE_IS_BYTES)
944         p_b = (p_b * len) / fs->max_pkt_size;
945
946     if (++q->count == 0) {
947         q->random = krandom() & 0xffff;
948     } else {
949         /*
950          * q->count counts packets arrived since last drop, so a greater
951          * value of q->count means a greater packet drop probability.
952          */
953         if (SCALE_MUL(p_b, SCALE((int64_t)q->count)) > q->random) {
954             q->count = 0;
955             DEB(kprintf("- red drop");)
956             /* After a drop we calculate a new random value */
957             q->random = krandom() & 0xffff;
958             return 1;    /* Drop */
959         }
960     }
961     /* End of RED algorithm */
962     return 0; /* Accept */
963 }
964
965 static __inline struct dn_flow_set *
966 locate_flowset(int pipe_nr, struct ip_fw *rule)
967 {
968     ipfw_insn *cmd = rule->cmd + rule->act_ofs;
969     struct dn_flow_set *fs;
970
971     if (cmd->opcode == O_LOG)
972         cmd += F_LEN(cmd);
973
974     fs = ((ipfw_insn_pipe *)cmd)->pipe_ptr;
975     if (fs != NULL)
976         return fs;
977
978     if (cmd->opcode == O_QUEUE) {
979         for (fs = all_flow_sets; fs && fs->fs_nr != pipe_nr; fs = fs->next)
980             ;   /* EMPTY */
981     } else {
982         struct dn_pipe *p;
983
984         for (p = all_pipes; p && p->pipe_nr != pipe_nr; p = p->next)
985             ;   /* EMPTY */
986         if (p != NULL)
987             fs = &p->fs;
988     }
989
990     /* record for the future */
991     ((ipfw_insn_pipe *)cmd)->pipe_ptr = fs;
992     return fs;
993 }
994
995 /*
996  * Dummynet hook for packets.  Below 'pipe' is a pipe or a queue
997  * depending on whether WF2Q or fixed bw is used.
998  *
999  * pipe_nr      pipe or queue the packet is destined for.
1000  * dir          where shall we send the packet after dummynet.
1001  * m            the mbuf with the packet
1002  * fwa->oif     the 'ifp' parameter from the caller.
1003  *              NULL in ip_input, destination interface in ip_output
1004  * fwa->ro      route parameter (only used in ip_output, NULL otherwise)
1005  * fwa->dst     destination address, only used by ip_output
1006  * fwa->rule    matching rule, in case of multiple passes
1007  * fwa->flags   flags from the caller, only used in ip_output
1008  */
1009 static int
1010 dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
1011 {
1012     struct dn_pkt *pkt;
1013     struct m_tag *tag;
1014     struct dn_flow_set *fs;
1015     struct dn_pipe *pipe;
1016     uint64_t len = m->m_pkthdr.len;
1017     struct dn_flow_queue *q = NULL;
1018     int is_pipe;
1019     ipfw_insn *cmd;
1020
1021     crit_enter();
1022
1023     cmd = fwa->rule->cmd + fwa->rule->act_ofs;
1024     if (cmd->opcode == O_LOG)
1025         cmd += F_LEN(cmd);
1026
1027     KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
1028             ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
1029
1030     is_pipe = (cmd->opcode == O_PIPE);
1031     pipe_nr &= 0xffff;
1032
1033     /*
1034      * This is a dummynet rule, so we expect a O_PIPE or O_QUEUE rule
1035      */
1036     fs = locate_flowset(pipe_nr, fwa->rule);
1037     if (fs == NULL)
1038         goto dropit;    /* This queue/pipe does not exist! */
1039
1040     pipe = fs->pipe;
1041     if (pipe == NULL) { /* Must be a queue, try find a matching pipe */
1042         for (pipe = all_pipes; pipe && pipe->pipe_nr != fs->parent_nr;
1043              pipe = pipe->next)
1044             ;   /* EMPTY */
1045         if (pipe != NULL) {
1046             fs->pipe = pipe;
1047         } else {
1048             kprintf("No pipe %d for queue %d, drop pkt\n",
1049                     fs->parent_nr, fs->fs_nr);
1050             goto dropit;
1051         }
1052     }
1053
1054     q = find_queue(fs, &fwa->f_id);
1055     if (q == NULL)
1056         goto dropit;    /* Cannot allocate queue */
1057
1058     /*
1059      * Update statistics, then check reasons to drop pkt
1060      */
1061     q->tot_bytes += len;
1062     q->tot_pkts++;
1063
1064     if (fs->plr && krandom() < fs->plr)
1065         goto dropit;    /* Random pkt drop */
1066
1067     if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1068         if (q->len_bytes > fs->qsize)
1069             goto dropit;        /* Queue size overflow */
1070     } else {
1071         if (q->len >= fs->qsize)
1072             goto dropit;        /* Queue count overflow */
1073     }
1074
1075     if ((fs->flags_fs & DN_IS_RED) && red_drops(fs, q, len))
1076         goto dropit;
1077
1078     /*
1079      * Build and enqueue packet + parameters
1080      */
1081     tag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT /* XXX */);
1082     if (tag == NULL)
1083         goto dropit;
1084     m_tag_prepend(m, tag);
1085
1086     pkt = m_tag_data(tag);
1087     bzero(pkt, sizeof(*pkt)); /* XXX expensive to zero */
1088
1089     pkt->rule = fwa->rule;
1090     pkt->dn_next = NULL;
1091     pkt->dn_m = m;
1092     pkt->dn_dir = dir;
1093
1094     pkt->ifp = fwa->oif;
1095     if (dir == DN_TO_IP_OUT) {
1096         /*
1097          * We need to copy *ro because for ICMP pkts (and maybe others)
1098          * the caller passed a pointer into the stack; dst might also be
1099          * a pointer into *ro so it needs to be updated.
1100          */
1101         pkt->ro = *(fwa->ro);
1102         if (fwa->ro->ro_rt)
1103             fwa->ro->ro_rt->rt_refcnt++;
1104         if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) {
1105             /* 'dst' points into 'ro' */
1106             fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst);
1107         }
1108
1109         pkt->dn_dst = fwa->dst;
1110         pkt->flags = fwa->flags;
1111     }
1112     if (q->head == NULL)
1113         q->head = pkt;
1114     else
1115         q->tail->dn_next = pkt;
1116     q->tail = pkt;
1117     q->len++;
1118     q->len_bytes += len;
1119
1120     if (q->head != pkt) /* Flow was not idle, we are done */
1121         goto done;
1122
1123     /*
1124      * If we reach this point the flow was previously idle, so we need
1125      * to schedule it.  This involves different actions for fixed-rate
1126      * or WF2Q queues.
1127      */
1128     if (is_pipe) {
1129         /*
1130          * Fixed-rate queue: just insert into the ready_heap.
1131          */
1132         dn_key t = 0;
1133
1134         if (pipe->bandwidth)
1135             t = SET_TICKS(pkt, q, pipe);
1136
1137         q->sched_time = curr_time;
1138         if (t == 0)     /* Must process it now */
1139             ready_event(q);
1140         else
1141             heap_insert(&ready_heap, curr_time + t, q);
1142     } else {
1143         /*
1144          * WF2Q:
1145          * First, compute start time S: if the flow was idle (S=F+1)
1146          * set S to the virtual time V for the controlling pipe, and update
1147          * the sum of weights for the pipe; otherwise, remove flow from
1148          * idle_heap and set S to max(F, V).
1149          * Second, compute finish time F = S + len/weight.
1150          * Third, if pipe was idle, update V = max(S, V).
1151          * Fourth, count one more backlogged flow.
1152          */
1153         if (DN_KEY_GT(q->S, q->F)) { /* Means timestamps are invalid */
1154             q->S = pipe->V;
1155             pipe->sum += fs->weight; /* Add weight of new queue */
1156         } else {
1157             heap_extract(&pipe->idle_heap, q);
1158             q->S = MAX64(q->F, pipe->V);
1159         }
1160         q->F = q->S + (len << MY_M) / (uint64_t)fs->weight;
1161
1162         if (pipe->not_eligible_heap.elements == 0 &&
1163             pipe->scheduler_heap.elements == 0)
1164             pipe->V = MAX64(q->S, pipe->V);
1165
1166         fs->backlogged++;
1167
1168         /*
1169          * Look at eligibility.  A flow is not eligibile if S>V (when
1170          * this happens, it means that there is some other flow already
1171          * scheduled for the same pipe, so the scheduler_heap cannot be
1172          * empty).  If the flow is not eligible we just store it in the
1173          * not_eligible_heap.  Otherwise, we store in the scheduler_heap
1174          * and possibly invoke ready_event_wfq() right now if there is
1175          * leftover credit.
1176          * Note that for all flows in scheduler_heap (SCH), S_i <= V,
1177          * and for all flows in not_eligible_heap (NEH), S_i > V.
1178          * So when we need to compute max(V, min(S_i)) forall i in SCH+NEH,
1179          * we only need to look into NEH.
1180          */
1181         if (DN_KEY_GT(q->S, pipe->V)) { /* Not eligible */
1182             if (pipe->scheduler_heap.elements == 0)
1183                 kprintf("++ ouch! not eligible but empty scheduler!\n");
1184             heap_insert(&pipe->not_eligible_heap, q->S, q);
1185         } else {
1186             heap_insert(&pipe->scheduler_heap, q->F, q);
1187             if (pipe->numbytes >= 0) {  /* Pipe is idle */
1188                 if (pipe->scheduler_heap.elements != 1)
1189                     kprintf("*** OUCH! pipe should have been idle!\n");
1190                 DEB(kprintf("Waking up pipe %d at %d\n",
1191                         pipe->pipe_nr, (int)(q->F >> MY_M)); )
1192                 pipe->sched_time = curr_time;
1193                 ready_event_wfq(pipe);
1194             }
1195         }
1196     }
1197 done:
1198     crit_exit();
1199     return 0;
1200
1201 dropit:
1202     crit_exit();
1203     if (q)
1204         q->drops++;
1205     m_freem(m);
1206     return ((fs && (fs->flags_fs & DN_NOERROR)) ? 0 : ENOBUFS);
1207 }
1208
1209 /*
1210  * Below, the rt_unref is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
1211  * Doing this would probably save us the initial bzero of dn_pkt
1212  */
1213 #define DN_FREE_PKT(pkt)        {               \
1214         struct dn_pkt *n = pkt;                 \
1215         pkt = n->dn_next;                       \
1216         rt_unref (n->ro.ro_rt);                 \
1217         m_freem(n->dn_m);       }
1218
1219 /*
1220  * Dispose all packets and flow_queues on a flow_set.
1221  * If all=1, also remove red lookup table and other storage,
1222  * including the descriptor itself.
1223  * For the one in dn_pipe MUST also cleanup ready_heap...
1224  */
1225 static void
1226 purge_flow_set(struct dn_flow_set *fs, int all)
1227 {
1228     int i;
1229
1230     for (i = 0; i <= fs->rq_size; i++) {
1231         struct dn_flow_queue *q, *qn;
1232
1233         for (q = fs->rq[i]; q; q = qn) {
1234             struct dn_pkt *pkt;
1235
1236             for (pkt = q->head; pkt;)
1237                 DN_FREE_PKT(pkt);
1238
1239             qn = q->next;
1240             kfree(q, M_DUMMYNET);
1241         }
1242         fs->rq[i] = NULL;
1243     }
1244     fs->rq_elements = 0;
1245
1246     if (all) {
1247         /* RED - free lookup table */
1248         if (fs->w_q_lookup)
1249             kfree(fs->w_q_lookup, M_DUMMYNET);
1250
1251         if (fs->rq)
1252             kfree(fs->rq, M_DUMMYNET);
1253
1254         /* If this fs is not part of a pipe, free it */
1255         if (fs->pipe && fs != &fs->pipe->fs)
1256             kfree(fs, M_DUMMYNET);
1257     }
1258 }
1259
1260 /*
1261  * Dispose all packets queued on a pipe (not a flow_set).
1262  * Also free all resources associated to a pipe, which is about
1263  * to be deleted.
1264  */
1265 static void
1266 purge_pipe(struct dn_pipe *pipe)
1267 {
1268     struct dn_pkt *pkt;
1269
1270     purge_flow_set(&pipe->fs, 1);
1271
1272     for (pkt = pipe->head; pkt;)
1273         DN_FREE_PKT(pkt);
1274
1275     heap_free(&pipe->scheduler_heap);
1276     heap_free(&pipe->not_eligible_heap);
1277     heap_free(&pipe->idle_heap);
1278 }
1279
1280 /*
1281  * Delete all pipes and heaps returning memory. Must also
1282  * remove references from all ipfw rules to all pipes.
1283  */
1284 static void
1285 dummynet_flush(void)
1286 {
1287     struct dn_pipe *p;
1288     struct dn_flow_set *fs;
1289
1290     crit_enter();
1291
1292     /* Remove all references to pipes ... */
1293     flush_pipe_ptrs(NULL);
1294
1295     /* Prevent future matches... */
1296     p = all_pipes;
1297     all_pipes = NULL;
1298     fs = all_flow_sets;
1299     all_flow_sets = NULL;
1300
1301     /* Free heaps so we don't have unwanted events */
1302     heap_free(&ready_heap);
1303     heap_free(&wfq_ready_heap);
1304     heap_free(&extract_heap);
1305
1306     crit_exit();
1307
1308     /*
1309      * Now purge all queued pkts and delete all pipes
1310      */
1311     /* Scan and purge all flow_sets. */
1312     while (fs != NULL) {
1313         struct dn_flow_set *curr_fs = fs;
1314
1315         fs = curr_fs->next;
1316         purge_flow_set(curr_fs, 1);
1317     }
1318     while (p != NULL) {
1319         struct dn_pipe *curr_p = p;
1320
1321         p = curr_p->next;
1322         purge_pipe(curr_p);
1323         kfree(curr_p, M_DUMMYNET);
1324     }
1325 }
1326
1327
1328 extern struct ip_fw *ip_fw_default_rule;
1329
1330 static void
1331 dn_rule_delete_fs(struct dn_flow_set *fs, void *r)
1332 {
1333     int i;
1334
1335     for (i = 0; i <= fs->rq_size; i++) { /* Last one is ovflow */
1336         struct dn_flow_queue *q;
1337
1338         for (q = fs->rq[i]; q; q = q->next) {
1339             struct dn_pkt *pkt;
1340
1341             for (pkt = q->head; pkt; pkt = pkt->dn_next) {
1342                 if (pkt->rule == r)
1343                     pkt->rule = ip_fw_default_rule;
1344             }
1345         }
1346     }
1347 }
1348
1349 /*
1350  * When a firewall rule is deleted, scan all queues and remove the flow-id
1351  * from packets matching this rule.
1352  */
1353 void
1354 dn_rule_delete(void *r)
1355 {
1356     struct dn_pipe *p;
1357     struct dn_flow_set *fs;
1358
1359     /*
1360      * If the rule references a queue (dn_flow_set), then scan
1361      * the flow set, otherwise scan pipes. Should do either, but doing
1362      * both does not harm.
1363      */
1364
1365     for (fs = all_flow_sets; fs; fs = fs->next)
1366         dn_rule_delete_fs(fs, r);
1367
1368     for (p = all_pipes; p; p = p->next) {
1369         struct dn_pkt *pkt;
1370
1371         fs = &p->fs;
1372         dn_rule_delete_fs(fs, r);
1373
1374         for (pkt = p->head; pkt; pkt = pkt->dn_next) {
1375             if (pkt->rule == r)
1376                 pkt->rule = ip_fw_default_rule;
1377         }
1378     }
1379 }
1380
1381 /*
1382  * setup RED parameters
1383  */
1384 static int
1385 config_red(const struct dn_ioc_flowset *ioc_fs, struct dn_flow_set *x)
1386 {
1387     int i;
1388
1389     x->w_q = ioc_fs->w_q;
1390     x->min_th = SCALE(ioc_fs->min_th);
1391     x->max_th = SCALE(ioc_fs->max_th);
1392     x->max_p = ioc_fs->max_p;
1393
1394     x->c_1 = ioc_fs->max_p / (ioc_fs->max_th - ioc_fs->min_th);
1395     x->c_2 = SCALE_MUL(x->c_1, SCALE(ioc_fs->min_th));
1396     if (x->flags_fs & DN_IS_GENTLE_RED) {
1397         x->c_3 = (SCALE(1) - ioc_fs->max_p) / ioc_fs->max_th;
1398         x->c_4 = (SCALE(1) - 2 * ioc_fs->max_p);
1399     }
1400
1401     /* If the lookup table already exist, free and create it again */
1402     if (x->w_q_lookup) {
1403         kfree(x->w_q_lookup, M_DUMMYNET);
1404         x->w_q_lookup = NULL ;
1405     }
1406
1407     if (red_lookup_depth == 0) {
1408         kprintf("net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
1409         kfree(x, M_DUMMYNET);
1410         return EINVAL;
1411     }
1412     x->lookup_depth = red_lookup_depth;
1413     x->w_q_lookup = kmalloc(x->lookup_depth * sizeof(int),
1414                             M_DUMMYNET, M_WAITOK);
1415
1416     /* Fill the lookup table with (1 - w_q)^x */
1417     x->lookup_step = ioc_fs->lookup_step;
1418     x->lookup_weight = ioc_fs->lookup_weight;
1419
1420     x->w_q_lookup[0] = SCALE(1) - x->w_q;
1421     for (i = 1; i < x->lookup_depth; i++)
1422         x->w_q_lookup[i] = SCALE_MUL(x->w_q_lookup[i - 1], x->lookup_weight);
1423
1424     if (red_avg_pkt_size < 1)
1425         red_avg_pkt_size = 512;
1426     x->avg_pkt_size = red_avg_pkt_size;
1427
1428     if (red_max_pkt_size < 1)
1429         red_max_pkt_size = 1500;
1430     x->max_pkt_size = red_max_pkt_size;
1431
1432     return 0;
1433 }
1434
1435 static void
1436 alloc_hash(struct dn_flow_set *x, const struct dn_ioc_flowset *ioc_fs)
1437 {
1438     if (x->flags_fs & DN_HAVE_FLOW_MASK) {
1439         int l = ioc_fs->rq_size;
1440
1441         /* Allocate some slots */
1442         if (l == 0)
1443             l = dn_hash_size;
1444
1445         if (l < DN_MIN_HASH_SIZE)
1446             l = DN_MIN_HASH_SIZE;
1447         else if (l > DN_MAX_HASH_SIZE)
1448             l = DN_MAX_HASH_SIZE;
1449
1450         x->rq_size = l;
1451     } else {
1452         /* One is enough for null mask */
1453         x->rq_size = 1;
1454     }
1455     x->rq = kmalloc((1 + x->rq_size) * sizeof(struct dn_flow_queue *),
1456                     M_DUMMYNET, M_WAITOK | M_ZERO);
1457     x->rq_elements = 0;
1458 }
1459
1460 static void
1461 set_flowid_parms(struct ipfw_flow_id *id, const struct dn_ioc_flowid *ioc_id)
1462 {
1463     id->dst_ip = ioc_id->u.ip.dst_ip;
1464     id->src_ip = ioc_id->u.ip.src_ip;
1465     id->dst_port = ioc_id->u.ip.dst_port;
1466     id->src_port = ioc_id->u.ip.src_port;
1467     id->proto = ioc_id->u.ip.proto;
1468     id->flags = ioc_id->u.ip.flags;
1469 }
1470
1471 static void
1472 set_fs_parms(struct dn_flow_set *x, const struct dn_ioc_flowset *ioc_fs)
1473 {
1474     x->flags_fs = ioc_fs->flags_fs;
1475     x->qsize = ioc_fs->qsize;
1476     x->plr = ioc_fs->plr;
1477     set_flowid_parms(&x->flow_mask, &ioc_fs->flow_mask);
1478     if (x->flags_fs & DN_QSIZE_IS_BYTES) {
1479         if (x->qsize > 1024 * 1024)
1480             x->qsize = 1024 * 1024;
1481     } else {
1482         if (x->qsize == 0 || x->qsize > 100)
1483             x->qsize = 50;
1484     }
1485
1486     /* Configuring RED */
1487     if (x->flags_fs & DN_IS_RED)
1488         config_red(ioc_fs, x);  /* XXX should check errors */
1489 }
1490
1491 /*
1492  * setup pipe or queue parameters.
1493  */
1494
1495 static int
1496 config_pipe(struct dn_ioc_pipe *ioc_pipe)
1497 {
1498     struct dn_ioc_flowset *ioc_fs = &ioc_pipe->fs;
1499     int error;
1500
1501     /*
1502      * The config program passes parameters as follows:
1503      * bw       bits/second (0 means no limits)
1504      * delay    ms (must be translated into ticks)
1505      * qsize    slots or bytes
1506      */
1507     ioc_pipe->delay = (ioc_pipe->delay * dn_hz) / 1000;
1508
1509     /*
1510      * We need either a pipe number or a flow_set number
1511      */
1512     if (ioc_pipe->pipe_nr == 0 && ioc_fs->fs_nr == 0)
1513         return EINVAL;
1514     if (ioc_pipe->pipe_nr != 0 && ioc_fs->fs_nr != 0)
1515         return EINVAL;
1516
1517     crit_enter();
1518
1519     error = EINVAL;
1520     if (ioc_pipe->pipe_nr != 0) {       /* This is a pipe */
1521         struct dn_pipe *x, *a, *b;
1522
1523         /* Locate pipe */
1524         for (a = NULL, b = all_pipes; b && b->pipe_nr < ioc_pipe->pipe_nr;
1525              a = b, b = b->next)
1526             ;   /* EMPTY */
1527
1528         if (b == NULL || b->pipe_nr != ioc_pipe->pipe_nr) { /* New pipe */
1529             x = kmalloc(sizeof(struct dn_pipe), M_DUMMYNET, M_WAITOK | M_ZERO);
1530             x->pipe_nr = ioc_pipe->pipe_nr;
1531             x->fs.pipe = x;
1532
1533             /*
1534              * idle_heap is the only one from which we extract from the middle.
1535              */
1536             x->idle_heap.size = x->idle_heap.elements = 0;
1537             x->idle_heap.offset = __offsetof(struct dn_flow_queue, heap_pos);
1538         } else {
1539             int i;
1540
1541             x = b;
1542
1543             /* Flush accumulated credit for all queues */
1544             for (i = 0; i <= x->fs.rq_size; i++) {
1545                 struct dn_flow_queue *q;
1546
1547                 for (q = x->fs.rq[i]; q; q = q->next)
1548                     q->numbytes = 0;
1549             }
1550         }
1551
1552         x->bandwidth = ioc_pipe->bandwidth;
1553         x->numbytes = 0; /* Just in case... */
1554         x->delay = ioc_pipe->delay;
1555
1556         set_fs_parms(&x->fs, ioc_fs);
1557
1558         if (x->fs.rq == NULL) { /* A new pipe */
1559             alloc_hash(&x->fs, ioc_fs);
1560
1561             x->next = b;
1562             if (a == NULL)
1563                 all_pipes = x;
1564             else
1565                 a->next = x;
1566         }
1567     } else {    /* Config flow_set */
1568         struct dn_flow_set *x, *a, *b;
1569
1570         /* Locate flow_set */
1571         for (a = NULL, b = all_flow_sets; b && b->fs_nr < ioc_fs->fs_nr;
1572              a = b, b = b->next)
1573             ;   /* EMPTY */
1574
1575         if (b == NULL || b->fs_nr != ioc_fs->fs_nr) { /* New flow_set */
1576             if (ioc_fs->parent_nr == 0) /* Need link to a pipe */
1577                 goto back;
1578
1579             x = kmalloc(sizeof(struct dn_flow_set), M_DUMMYNET,
1580                         M_WAITOK | M_ZERO);
1581             x->fs_nr = ioc_fs->fs_nr;
1582             x->parent_nr = ioc_fs->parent_nr;
1583             x->weight = ioc_fs->weight;
1584             if (x->weight == 0)
1585                 x->weight = 1;
1586             else if (x->weight > 100)
1587                 x->weight = 100;
1588         } else {
1589             /* Change parent pipe not allowed; must delete and recreate */
1590             if (ioc_fs->parent_nr != 0 && b->parent_nr != ioc_fs->parent_nr)
1591                 goto back;
1592             x = b;
1593         }
1594
1595         set_fs_parms(x, ioc_fs);
1596
1597         if (x->rq == NULL) {    /* A new flow_set */
1598             alloc_hash(x, ioc_fs);
1599
1600             x->next = b;
1601             if (a == NULL)
1602                 all_flow_sets = x;
1603             else
1604                 a->next = x;
1605         }
1606     }
1607     error = 0;
1608
1609 back:
1610     crit_exit();
1611     return error;
1612 }
1613
1614 /*
1615  * Helper function to remove from a heap queues which are linked to
1616  * a flow_set about to be deleted.
1617  */
1618 static void
1619 fs_remove_from_heap(struct dn_heap *h, struct dn_flow_set *fs)
1620 {
1621     int i = 0, found = 0;
1622
1623     while (i < h->elements) {
1624         if (((struct dn_flow_queue *)h->p[i].object)->fs == fs) {
1625             h->elements--;
1626             h->p[i] = h->p[h->elements];
1627             found++;
1628         } else {
1629             i++;
1630         }
1631     }
1632     if (found)
1633         heapify(h);
1634 }
1635
1636 /*
1637  * helper function to remove a pipe from a heap (can be there at most once)
1638  */
1639 static void
1640 pipe_remove_from_heap(struct dn_heap *h, struct dn_pipe *p)
1641 {
1642     if (h->elements > 0) {
1643         int i;
1644
1645         for (i = 0; i < h->elements; i++) {
1646             if (h->p[i].object == p) { /* found it */
1647                 h->elements--;
1648                 h->p[i] = h->p[h->elements];
1649                 heapify(h);
1650                 break;
1651             }
1652         }
1653     }
1654 }
1655
1656 /*
1657  * drain all queues. Called in case of severe mbuf shortage.
1658  */
1659 void
1660 dummynet_drain(void)
1661 {
1662     struct dn_flow_set *fs;
1663     struct dn_pipe *p;
1664     struct dn_pkt *pkt;
1665
1666     heap_free(&ready_heap);
1667     heap_free(&wfq_ready_heap);
1668     heap_free(&extract_heap);
1669
1670     /* remove all references to this pipe from flow_sets */
1671     for (fs = all_flow_sets; fs; fs= fs->next)
1672         purge_flow_set(fs, 0);
1673
1674     for (p = all_pipes; p; p= p->next) {
1675         purge_flow_set(&p->fs, 0);
1676         for (pkt = p->head; pkt ;)
1677             DN_FREE_PKT(pkt);
1678         p->head = p->tail = NULL;
1679     }
1680 }
1681
1682 /*
1683  * Fully delete a pipe or a queue, cleaning up associated info.
1684  */
1685 static int
1686 delete_pipe(const struct dn_ioc_pipe *ioc_pipe)
1687 {
1688     int error;
1689
1690     if (ioc_pipe->pipe_nr == 0 && ioc_pipe->fs.fs_nr == 0)
1691         return EINVAL;
1692     if (ioc_pipe->pipe_nr != 0 && ioc_pipe->fs.fs_nr != 0)
1693         return EINVAL;
1694
1695     crit_enter();
1696
1697     error = EINVAL;
1698     if (ioc_pipe->pipe_nr != 0) {       /* This is an old-style pipe */
1699         struct dn_pipe *a, *b;
1700         struct dn_flow_set *fs;
1701
1702         /* Locate pipe */
1703         for (a = NULL, b = all_pipes; b && b->pipe_nr < ioc_pipe->pipe_nr;
1704              a = b, b = b->next)
1705             ;   /* EMPTY */
1706         if (b == NULL || b->pipe_nr != ioc_pipe->pipe_nr)
1707             goto back; /* Not found */
1708
1709         /* Unlink from list of pipes */
1710         if (a == NULL)
1711             all_pipes = b->next;
1712         else
1713             a->next = b->next;
1714
1715         /* Remove references to this pipe from the ip_fw rules. */
1716         flush_pipe_ptrs(&b->fs);
1717
1718         /* Remove all references to this pipe from flow_sets */
1719         for (fs = all_flow_sets; fs; fs = fs->next) {
1720             if (fs->pipe == b) {
1721                 kprintf("++ ref to pipe %d from fs %d\n",
1722                         ioc_pipe->pipe_nr, fs->fs_nr);
1723                 fs->pipe = NULL;
1724                 purge_flow_set(fs, 0);
1725             }
1726         }
1727         fs_remove_from_heap(&ready_heap, &b->fs);
1728         purge_pipe(b);  /* Remove all data associated to this pipe */
1729
1730         /* Remove reference to here from extract_heap and wfq_ready_heap */
1731         pipe_remove_from_heap(&extract_heap, b);
1732         pipe_remove_from_heap(&wfq_ready_heap, b);
1733
1734         kfree(b, M_DUMMYNET);
1735     } else {    /* This is a WF2Q queue (dn_flow_set) */
1736         struct dn_flow_set *a, *b;
1737
1738         /* Locate flow_set */
1739         for (a = NULL, b = all_flow_sets; b && b->fs_nr < ioc_pipe->fs.fs_nr;
1740              a = b, b = b->next)
1741             ;   /* EMPTY */
1742         if (b == NULL || b->fs_nr != ioc_pipe->fs.fs_nr)
1743             goto back; /* Not found */
1744
1745         if (a == NULL)
1746             all_flow_sets = b->next;
1747         else
1748             a->next = b->next;
1749
1750         /* Remove references to this flow_set from the ip_fw rules. */
1751         flush_pipe_ptrs(b);
1752
1753         if (b->pipe != NULL) {
1754             /* Update total weight on parent pipe and cleanup parent heaps */
1755             b->pipe->sum -= b->weight * b->backlogged;
1756             fs_remove_from_heap(&b->pipe->not_eligible_heap, b);
1757             fs_remove_from_heap(&b->pipe->scheduler_heap, b);
1758 #if 1   /* XXX should i remove from idle_heap as well ? */
1759             fs_remove_from_heap(&b->pipe->idle_heap, b);
1760 #endif
1761         }
1762         purge_flow_set(b, 1);
1763     }
1764     error = 0;
1765
1766 back:
1767     crit_exit();
1768     return error;
1769 }
1770
1771 /*
1772  * helper function used to copy data from kernel in DUMMYNET_GET
1773  */
1774 static void
1775 dn_copy_flowid(const struct ipfw_flow_id *id, struct dn_ioc_flowid *ioc_id)
1776 {
1777     ioc_id->type = ETHERTYPE_IP;
1778     ioc_id->u.ip.dst_ip = id->dst_ip;
1779     ioc_id->u.ip.src_ip = id->src_ip;
1780     ioc_id->u.ip.dst_port = id->dst_port;
1781     ioc_id->u.ip.src_port = id->src_port;
1782     ioc_id->u.ip.proto = id->proto;
1783     ioc_id->u.ip.flags = id->flags;
1784 }
1785
1786 static void *
1787 dn_copy_flowqueues(const struct dn_flow_set *fs, void *bp)
1788 {
1789     const struct dn_flow_queue *q;
1790     struct dn_ioc_flowqueue *ioc_fq = bp;
1791     int i, copied = 0;
1792
1793     for (i = 0; i <= fs->rq_size; i++) {
1794         for (q = fs->rq[i]; q; q = q->next, ioc_fq++) {
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             if (q->fs != fs) {          /* XXX ASSERT */
1800                 kprintf("++ at %d: wrong fs ptr (have %p, should be %p)\n",
1801                         i, q->fs, fs);
1802             }
1803
1804             copied++;
1805
1806             ioc_fq->len = q->len;
1807             ioc_fq->len_bytes = q->len_bytes;
1808             ioc_fq->tot_pkts = q->tot_pkts;
1809             ioc_fq->tot_bytes = q->tot_bytes;
1810             ioc_fq->drops = q->drops;
1811             ioc_fq->hash_slot = q->hash_slot;
1812             ioc_fq->S = q->S;
1813             ioc_fq->F = q->F;
1814             dn_copy_flowid(&q->id, &ioc_fq->id);
1815         }
1816     }
1817
1818     if (copied != fs->rq_elements) {    /* XXX ASSERT */
1819         kprintf("++ wrong count, have %d should be %d\n",
1820                 copied, fs->rq_elements);
1821     }
1822     return ioc_fq;
1823 }
1824
1825 static void
1826 dn_copy_flowset(const struct dn_flow_set *fs, struct dn_ioc_flowset *ioc_fs,
1827                 u_short fs_type)
1828 {
1829     ioc_fs->fs_type = fs_type;
1830
1831     ioc_fs->fs_nr = fs->fs_nr;
1832     ioc_fs->flags_fs = fs->flags_fs;
1833     ioc_fs->parent_nr = fs->parent_nr;
1834
1835     ioc_fs->weight = fs->weight;
1836     ioc_fs->qsize = fs->qsize;
1837     ioc_fs->plr = fs->plr;
1838
1839     ioc_fs->rq_size = fs->rq_size;
1840     ioc_fs->rq_elements = fs->rq_elements;
1841
1842     ioc_fs->w_q = fs->w_q;
1843     ioc_fs->max_th = fs->max_th;
1844     ioc_fs->min_th = fs->min_th;
1845     ioc_fs->max_p = fs->max_p;
1846
1847     dn_copy_flowid(&fs->flow_mask, &ioc_fs->flow_mask);
1848 }
1849
1850 static int
1851 dummynet_get(struct sockopt *sopt)
1852 {
1853     struct dn_flow_set *fs;
1854     struct dn_pipe *pipe;
1855     char *buf, *bp;
1856     size_t size = 0;
1857     int error = 0;
1858
1859     crit_enter();
1860
1861     /*
1862      * Compute size of data structures: list of pipes and flow_sets.
1863      */
1864     for (pipe = all_pipes; pipe; pipe = pipe->next) {
1865         size += sizeof(struct dn_ioc_pipe) +
1866             pipe->fs.rq_elements * sizeof(struct dn_ioc_flowqueue);
1867     }
1868
1869     for (fs = all_flow_sets; fs; fs = fs->next) {
1870         size += sizeof(struct dn_ioc_flowset) +
1871             fs->rq_elements * sizeof(struct dn_ioc_flowqueue);
1872     }
1873
1874     bp = buf = kmalloc(size, M_TEMP, M_WAITOK | M_ZERO);
1875
1876     for (pipe = all_pipes; pipe; pipe = pipe->next) {
1877         struct dn_ioc_pipe *ioc_pipe = (struct dn_ioc_pipe *)bp;
1878
1879         /*
1880          * Copy flow set descriptor associated with this pipe
1881          */
1882         dn_copy_flowset(&pipe->fs, &ioc_pipe->fs, DN_IS_PIPE);
1883
1884         /*
1885          * Copy pipe descriptor
1886          */
1887         ioc_pipe->bandwidth = pipe->bandwidth;
1888         ioc_pipe->pipe_nr = pipe->pipe_nr;
1889         ioc_pipe->V = pipe->V;
1890         /* Convert delay to milliseconds */
1891         ioc_pipe->delay = (pipe->delay * 1000) / dn_hz;
1892
1893         /*
1894          * Copy flow queue descriptors
1895          */
1896         bp += sizeof(*ioc_pipe);
1897         bp = dn_copy_flowqueues(&pipe->fs, bp);
1898     }
1899
1900     for (fs = all_flow_sets; fs; fs = fs->next) {
1901         struct dn_ioc_flowset *ioc_fs = (struct dn_ioc_flowset *)bp;
1902
1903         /*
1904          * Copy flow set descriptor
1905          */
1906         dn_copy_flowset(fs, ioc_fs, DN_IS_QUEUE);
1907
1908         /*
1909          * Copy flow queue descriptors
1910          */
1911         bp += sizeof(*ioc_fs);
1912         bp = dn_copy_flowqueues(fs, bp);
1913     }
1914
1915     crit_exit();
1916
1917     error = sooptcopyout(sopt, buf, size);
1918     kfree(buf, M_TEMP);
1919     return error;
1920 }
1921
1922 /*
1923  * Handler for the various dummynet socket options (get, flush, config, del)
1924  */
1925 static int
1926 ip_dn_ctl(struct sockopt *sopt)
1927 {
1928     struct dn_ioc_pipe tmp_ioc_pipe;
1929     int error = 0;
1930
1931     /* Disallow sets in really-really secure mode. */
1932     if (sopt->sopt_dir == SOPT_SET) {
1933         if (securelevel >= 3)
1934             return EPERM;
1935     }
1936
1937     switch (sopt->sopt_name) {
1938     case IP_DUMMYNET_GET:
1939         error = dummynet_get(sopt);
1940         break;
1941
1942     case IP_DUMMYNET_FLUSH:
1943         dummynet_flush();
1944         break;
1945
1946     case IP_DUMMYNET_CONFIGURE:
1947         error = sooptcopyin(sopt, &tmp_ioc_pipe, sizeof(tmp_ioc_pipe),
1948                             sizeof(tmp_ioc_pipe));
1949         if (error)
1950             break;
1951         error = config_pipe(&tmp_ioc_pipe);
1952         break;
1953
1954     case IP_DUMMYNET_DEL:       /* Remove a pipe or flow_set */
1955         error = sooptcopyin(sopt, &tmp_ioc_pipe, sizeof(tmp_ioc_pipe),
1956                             sizeof(tmp_ioc_pipe));
1957         if (error)
1958             break;
1959         error = delete_pipe(&tmp_ioc_pipe);
1960         break;
1961
1962     default:
1963         kprintf("%s -- unknown option %d\n", __func__, sopt->sopt_name);
1964         error = EINVAL;
1965         break;
1966     }
1967     return error;
1968 }
1969
1970 static void
1971 dummynet_clock(systimer_t info __unused, struct intrframe *frame __unused)
1972 {
1973     KASSERT(mycpu->gd_cpuid == dn_cpu,
1974             ("systimer comes on a different cpu!\n"));
1975
1976     crit_enter();
1977     if (dn_netmsg.nm_lmsg.ms_flags & MSGF_DONE)
1978         lwkt_sendmsg(cpu_portfn(mycpu->gd_cpuid), &dn_netmsg.nm_lmsg);
1979     crit_exit();
1980 }
1981
1982 static int
1983 sysctl_dn_hz(SYSCTL_HANDLER_ARGS)
1984 {
1985     int error, val;
1986
1987     val = dn_hz;
1988     error = sysctl_handle_int(oidp, &val, 0, req);
1989     if (error || req->newptr == NULL)
1990         return error;
1991     if (val <= 0)
1992         return EINVAL;
1993     else if (val > DUMMYNET_CALLOUT_FREQ_MAX)
1994         val = DUMMYNET_CALLOUT_FREQ_MAX;
1995
1996     crit_enter();
1997     dn_hz = val;
1998     systimer_adjust_periodic(&dn_clock, val);
1999     crit_exit();
2000
2001     return 0;
2002 }
2003
2004 static void
2005 ip_dn_register_systimer(struct netmsg *msg)
2006 {
2007     systimer_init_periodic_nq(&dn_clock, dummynet_clock, NULL, dn_hz);
2008     lwkt_replymsg(&msg->nm_lmsg, 0);
2009 }
2010
2011 static void
2012 ip_dn_deregister_systimer(struct netmsg *msg)
2013 {
2014     systimer_del(&dn_clock);
2015     lwkt_replymsg(&msg->nm_lmsg, 0);
2016 }
2017
2018 static void
2019 ip_dn_init(void)
2020 {
2021     struct netmsg smsg;
2022     lwkt_port_t port;
2023
2024     kprintf("DUMMYNET initialized (011031)\n");
2025
2026     all_pipes = NULL;
2027     all_flow_sets = NULL;
2028
2029     ready_heap.size = ready_heap.elements = 0;
2030     ready_heap.offset = 0;
2031
2032     wfq_ready_heap.size = wfq_ready_heap.elements = 0;
2033     wfq_ready_heap.offset = 0;
2034
2035     extract_heap.size = extract_heap.elements = 0;
2036     extract_heap.offset = 0;
2037
2038     ip_dn_ctl_ptr = ip_dn_ctl;
2039     ip_dn_io_ptr = dummynet_io;
2040     ip_dn_ruledel_ptr = dn_rule_delete;
2041
2042     netmsg_init(&dn_netmsg, &netisr_adone_rport, 0, dummynet);
2043
2044     netmsg_init(&smsg, &curthread->td_msgport, 0, ip_dn_register_systimer);
2045     port = cpu_portfn(dn_cpu);
2046     lwkt_domsg(port, &smsg.nm_lmsg, 0);
2047 }
2048
2049 static void
2050 ip_dn_stop(void)
2051 {
2052     struct netmsg smsg;
2053     lwkt_port_t port;
2054
2055     netmsg_init(&smsg, &curthread->td_msgport, 0, ip_dn_deregister_systimer);
2056     port = cpu_portfn(dn_cpu);
2057     lwkt_domsg(port, &smsg.nm_lmsg, 0);
2058
2059     dummynet_flush();
2060
2061     ip_dn_ctl_ptr = NULL;
2062     ip_dn_io_ptr = NULL;
2063     ip_dn_ruledel_ptr = NULL;
2064
2065     netmsg_service_sync();
2066 }
2067
2068 static int
2069 dummynet_modevent(module_t mod, int type, void *data)
2070 {
2071     switch (type) {
2072     case MOD_LOAD:
2073         crit_enter();
2074         if (DUMMYNET_LOADED) {
2075             crit_exit();
2076             kprintf("DUMMYNET already loaded\n");
2077             return EEXIST;
2078         }
2079         ip_dn_init();
2080         crit_exit();
2081         break;
2082     
2083     case MOD_UNLOAD:
2084 #ifndef KLD_MODULE
2085         kprintf("dummynet statically compiled, cannot unload\n");
2086         return EINVAL ;
2087 #else
2088         crit_enter();
2089         ip_dn_stop();
2090         crit_exit();
2091 #endif
2092         break;
2093
2094     default:
2095         break;
2096     }
2097     return 0;
2098 }
2099
2100 static moduledata_t dummynet_mod = {
2101     "dummynet",
2102     dummynet_modevent,
2103     NULL
2104 };
2105 DECLARE_MODULE(dummynet, dummynet_mod, SI_SUB_PROTO_END, SI_ORDER_ANY);
2106 MODULE_DEPEND(dummynet, ipfw, 1, 1, 1);
2107 MODULE_VERSION(dummynet, 1);