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