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