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