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