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