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