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