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