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