2 * Copyright (c) 1998-2002 Luigi Rizzo, Universita` di Pisa
3 * Portions Copyright (c) 2000 Akamba Corp.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
30 #define DUMMYNET_DEBUG
32 #if !defined(KLD_MODULE)
33 #include "opt_inet6.h"
37 * This module implements IP dummynet, a bandwidth limiter/delay emulator
38 * used in conjunction with the ipfw package.
39 * Description of the data structures used is in ip_dummynet.h
40 * Here you mainly find the following blocks of code:
41 * + variable declarations;
42 * + heap management functions;
43 * + scheduler and dummynet functions;
44 * + configuration and initialization.
46 * NOTA BENE: critical sections are protected by the "dummynet lock".
48 * Most important Changes:
51 * 010124: Fixed WF2Q behaviour
52 * 010122: Fixed spl protection.
53 * 000601: WF2Q support
54 * 000106: large rewrite, use heaps to handle very many pipes.
55 * 980513: initial release
57 * include files marked with XXX are probably not needed
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/malloc.h>
64 #include <sys/kernel.h>
65 #include <sys/module.h>
67 #include <sys/socket.h>
68 #include <sys/socketvar.h>
70 #include <sys/sysctl.h>
72 #include <net/route.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/in_var.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_fw.h>
78 #include <netinet/ip_dummynet.h>
79 #include <netinet/ip_var.h>
81 #include <netinet/if_ether.h> /* for struct arpcom */
83 #include <netinet/ip6.h> /* for ip6_input, ip6_output prototypes */
84 #include <netinet6/ip6_var.h>
87 * We keep a private variable for the simulation time, but we could
88 * probably use an existing one ("softticks" in sys/kern/kern_timeout.c)
90 static dn_key curr_time = 0 ; /* current simulation time */
92 static int dn_hash_size = 64 ; /* default hash size */
94 /* statistics on number of queue searches and search steps */
95 static int searches, search_steps ;
96 static int pipe_expire = 1 ; /* expire queue if empty */
97 static int dn_max_ratio = 16 ; /* max queues/buckets ratio */
99 static int red_lookup_depth = 256; /* RED - default lookup table depth */
100 static int red_avg_pkt_size = 512; /* RED - default medium packet size */
101 static int red_max_pkt_size = 1500; /* RED - default max packet size */
104 * Three heaps contain queues and pipes that the scheduler handles:
106 * ready_heap contains all dn_flow_queue related to fixed-rate pipes.
108 * wfq_ready_heap contains the pipes associated with WF2Q flows
110 * extract_heap contains pipes associated with delay lines.
114 MALLOC_DEFINE(M_DUMMYNET, "dummynet", "dummynet heap");
116 static struct dn_heap ready_heap, extract_heap, wfq_ready_heap ;
118 static int heap_init(struct dn_heap *h, int size);
119 static int heap_insert (struct dn_heap *h, dn_key key1, void *p);
120 static void heap_extract(struct dn_heap *h, void *obj);
121 static void transmit_event(struct dn_pipe *pipe, struct mbuf **head,
123 static void ready_event(struct dn_flow_queue *q, struct mbuf **head,
125 static void ready_event_wfq(struct dn_pipe *p, struct mbuf **head,
129 #define HASH(num) ((((num) >> 8) ^ ((num) >> 4) ^ (num)) & 0x0f)
130 static struct dn_pipe_head pipehash[HASHSIZE]; /* all pipes */
131 static struct dn_flow_set_head flowsethash[HASHSIZE]; /* all flowsets */
133 static struct callout dn_timeout;
135 extern void (*bridge_dn_p)(struct mbuf *, struct ifnet *);
138 SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet,
139 CTLFLAG_RW, 0, "Dummynet");
140 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, hash_size,
141 CTLFLAG_RW, &dn_hash_size, 0, "Default hash table size");
142 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, curr_time,
143 CTLFLAG_RD, &curr_time, 0, "Current tick");
144 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, ready_heap,
145 CTLFLAG_RD, &ready_heap.size, 0, "Size of ready heap");
146 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, extract_heap,
147 CTLFLAG_RD, &extract_heap.size, 0, "Size of extract heap");
148 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, searches,
149 CTLFLAG_RD, &searches, 0, "Number of queue searches");
150 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, search_steps,
151 CTLFLAG_RD, &search_steps, 0, "Number of queue search steps");
152 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, expire,
153 CTLFLAG_RW, &pipe_expire, 0, "Expire queue if empty");
154 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, max_chain_len,
155 CTLFLAG_RW, &dn_max_ratio, 0,
156 "Max ratio between dynamic queues and buckets");
157 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
158 CTLFLAG_RD, &red_lookup_depth, 0, "Depth of RED lookup table");
159 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
160 CTLFLAG_RD, &red_avg_pkt_size, 0, "RED Medium packet size");
161 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
162 CTLFLAG_RD, &red_max_pkt_size, 0, "RED Max packet size");
165 #ifdef DUMMYNET_DEBUG
166 int dummynet_debug = 0;
168 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug, CTLFLAG_RW, &dummynet_debug,
169 0, "control debugging printfs");
171 #define DPRINTF(X) if (dummynet_debug) printf X
176 static struct mtx dummynet_mtx;
178 * NB: Recursion is needed to deal with re-entry via ICMP. That is,
179 * a packet may be dispatched via ip_input from dummynet_io and
180 * re-enter through ip_output. Yech.
182 #define DUMMYNET_LOCK_INIT() \
183 mtx_init(&dummynet_mtx, "dummynet", NULL, MTX_DEF | MTX_RECURSE)
184 #define DUMMYNET_LOCK_DESTROY() mtx_destroy(&dummynet_mtx)
185 #define DUMMYNET_LOCK() mtx_lock(&dummynet_mtx)
186 #define DUMMYNET_UNLOCK() mtx_unlock(&dummynet_mtx)
187 #define DUMMYNET_LOCK_ASSERT() do { \
188 mtx_assert(&dummynet_mtx, MA_OWNED); \
189 NET_ASSERT_GIANT(); \
192 static int config_pipe(struct dn_pipe *p);
193 static int ip_dn_ctl(struct sockopt *sopt);
195 static void dummynet(void *);
196 static void dummynet_flush(void);
197 static void dummynet_send(struct mbuf *);
198 void dummynet_drain(void);
199 static ip_dn_io_t dummynet_io;
200 static void dn_rule_delete(void *);
203 * Heap management functions.
205 * In the heap, first node is element 0. Children of i are 2i+1 and 2i+2.
206 * Some macros help finding parent/children so we can optimize them.
208 * heap_init() is called to expand the heap when needed.
209 * Increment size in blocks of 16 entries.
210 * XXX failure to allocate a new element is a pretty bad failure
211 * as we basically stall a whole queue forever!!
212 * Returns 1 on error, 0 on success
214 #define HEAP_FATHER(x) ( ( (x) - 1 ) / 2 )
215 #define HEAP_LEFT(x) ( 2*(x) + 1 )
216 #define HEAP_IS_LEFT(x) ( (x) & 1 )
217 #define HEAP_RIGHT(x) ( 2*(x) + 2 )
218 #define HEAP_SWAP(a, b, buffer) { buffer = a ; a = b ; b = buffer ; }
219 #define HEAP_INCREMENT 15
222 heap_init(struct dn_heap *h, int new_size)
224 struct dn_heap_entry *p;
226 if (h->size >= new_size ) {
227 printf("dummynet: %s, Bogus call, have %d want %d\n", __func__,
231 new_size = (new_size + HEAP_INCREMENT ) & ~HEAP_INCREMENT ;
232 p = malloc(new_size * sizeof(*p), M_DUMMYNET, M_NOWAIT);
234 printf("dummynet: %s, resize %d failed\n", __func__, new_size );
235 return 1 ; /* error */
238 bcopy(h->p, p, h->size * sizeof(*p) );
239 free(h->p, M_DUMMYNET);
247 * Insert element in heap. Normally, p != NULL, we insert p in
248 * a new position and bubble up. If p == NULL, then the element is
249 * already in place, and key is the position where to start the
251 * Returns 1 on failure (cannot allocate new heap entry)
253 * If offset > 0 the position (index, int) of the element in the heap is
254 * also stored in the element itself at the given offset in bytes.
256 #define SET_OFFSET(heap, node) \
257 if (heap->offset > 0) \
258 *((int *)((char *)(heap->p[node].object) + heap->offset)) = node ;
260 * RESET_OFFSET is used for sanity checks. It sets offset to an invalid value.
262 #define RESET_OFFSET(heap, node) \
263 if (heap->offset > 0) \
264 *((int *)((char *)(heap->p[node].object) + heap->offset)) = -1 ;
266 heap_insert(struct dn_heap *h, dn_key key1, void *p)
268 int son = h->elements ;
270 if (p == NULL) /* data already there, set starting point */
272 else { /* insert new element at the end, possibly resize */
274 if (son == h->size) /* need resize... */
275 if (heap_init(h, h->elements+1) )
276 return 1 ; /* failure... */
277 h->p[son].object = p ;
278 h->p[son].key = key1 ;
281 while (son > 0) { /* bubble up */
282 int father = HEAP_FATHER(son) ;
283 struct dn_heap_entry tmp ;
285 if (DN_KEY_LT( h->p[father].key, h->p[son].key ) )
286 break ; /* found right position */
287 /* son smaller than father, swap and repeat */
288 HEAP_SWAP(h->p[son], h->p[father], tmp) ;
297 * remove top element from heap, or obj if obj != NULL
300 heap_extract(struct dn_heap *h, void *obj)
302 int child, father, max = h->elements - 1 ;
305 printf("dummynet: warning, extract from empty heap 0x%p\n", h);
308 father = 0 ; /* default: move up smallest child */
309 if (obj != NULL) { /* extract specific element, index is at offset */
311 panic("dummynet: heap_extract from middle not supported on this heap!!!\n");
312 father = *((int *)((char *)obj + h->offset)) ;
313 if (father < 0 || father >= h->elements) {
314 printf("dummynet: heap_extract, father %d out of bound 0..%d\n",
315 father, h->elements);
316 panic("dummynet: heap_extract");
319 RESET_OFFSET(h, father);
320 child = HEAP_LEFT(father) ; /* left child */
321 while (child <= max) { /* valid entry */
322 if (child != max && DN_KEY_LT(h->p[child+1].key, h->p[child].key) )
323 child = child+1 ; /* take right child, otherwise left */
324 h->p[father] = h->p[child] ;
325 SET_OFFSET(h, father);
327 child = HEAP_LEFT(child) ; /* left child for next loop */
332 * Fill hole with last entry and bubble up, reusing the insert code
334 h->p[father] = h->p[max] ;
335 heap_insert(h, father, NULL); /* this one cannot fail */
341 * change object position and update references
342 * XXX this one is never used!
345 heap_move(struct dn_heap *h, dn_key new_key, void *object)
349 int max = h->elements-1 ;
350 struct dn_heap_entry buf ;
353 panic("cannot move items on this heap");
355 i = *((int *)((char *)object + h->offset));
356 if (DN_KEY_LT(new_key, h->p[i].key) ) { /* must move up */
357 h->p[i].key = new_key ;
358 for (; i>0 && DN_KEY_LT(new_key, h->p[(temp = HEAP_FATHER(i))].key) ;
359 i = temp ) { /* bubble up */
360 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
363 } else { /* must move down */
364 h->p[i].key = new_key ;
365 while ( (temp = HEAP_LEFT(i)) <= max ) { /* found left child */
366 if ((temp != max) && DN_KEY_GT(h->p[temp].key, h->p[temp+1].key))
367 temp++ ; /* select child with min key */
368 if (DN_KEY_GT(new_key, h->p[temp].key)) { /* go down */
369 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
378 #endif /* heap_move, unused */
381 * heapify() will reorganize data inside an array to maintain the
382 * heap property. It is needed when we delete a bunch of entries.
385 heapify(struct dn_heap *h)
389 for (i = 0 ; i < h->elements ; i++ )
390 heap_insert(h, i , NULL) ;
394 * cleanup the heap and free data structure
397 heap_free(struct dn_heap *h)
400 free(h->p, M_DUMMYNET);
401 bzero(h, sizeof(*h) );
405 * --- end of heap management functions ---
409 * Return the mbuf tag holding the dummynet state. As an optimization
410 * this is assumed to be the first tag on the list. If this turns out
411 * wrong we'll need to search the list.
413 static struct dn_pkt_tag *
414 dn_tag_get(struct mbuf *m)
416 struct m_tag *mtag = m_tag_first(m);
417 KASSERT(mtag != NULL &&
418 mtag->m_tag_cookie == MTAG_ABI_COMPAT &&
419 mtag->m_tag_id == PACKET_TAG_DUMMYNET,
420 ("packet on dummynet queue w/o dummynet tag!"));
421 return (struct dn_pkt_tag *)(mtag+1);
425 * Scheduler functions:
427 * transmit_event() is called when the delay-line needs to enter
428 * the scheduler, either because of existing pkts getting ready,
429 * or new packets entering the queue. The event handled is the delivery
430 * time of the packet.
432 * ready_event() does something similar with fixed-rate queues, and the
433 * event handled is the finish time of the head pkt.
435 * wfq_ready_event() does something similar with WF2Q queues, and the
436 * event handled is the start time of the head pkt.
438 * In all cases, we make sure that the data structures are consistent
439 * before passing pkts out, because this might trigger recursive
440 * invocations of the procedures.
443 transmit_event(struct dn_pipe *pipe, struct mbuf **head, struct mbuf **tail)
446 struct dn_pkt_tag *pkt;
448 DUMMYNET_LOCK_ASSERT();
450 while ((m = pipe->head) != NULL) {
452 if (!DN_KEY_LEQ(pkt->output_time, curr_time))
455 pipe->head = m->m_nextpkt;
457 (*tail)->m_nextpkt = m;
463 (*tail)->m_nextpkt = NULL;
465 /* If there are leftover packets, put into the heap for next event. */
466 if ((m = pipe->head) != NULL) {
469 * XXX: Should check errors on heap_insert, by draining the
470 * whole pipe p and hoping in the future we are more successful.
472 heap_insert(&extract_heap, pkt->output_time, pipe);
477 * the following macro computes how many ticks we have to wait
478 * before being able to transmit a packet. The credit is taken from
479 * either a pipe (WF2Q) or a flow_queue (per-flow queueing)
481 #define SET_TICKS(_m, q, p) \
482 ((_m)->m_pkthdr.len*8*hz - (q)->numbytes + p->bandwidth - 1 ) / \
486 * extract pkt from queue, compute output time (could be now)
487 * and put into delay line (p_queue)
490 move_pkt(struct mbuf *pkt, struct dn_flow_queue *q,
491 struct dn_pipe *p, int len)
493 struct dn_pkt_tag *dt = dn_tag_get(pkt);
495 q->head = pkt->m_nextpkt ;
497 q->len_bytes -= len ;
499 dt->output_time = curr_time + p->delay ;
504 p->tail->m_nextpkt = pkt;
506 p->tail->m_nextpkt = NULL;
510 * ready_event() is invoked every time the queue must enter the
511 * scheduler, either because the first packet arrives, or because
512 * a previously scheduled event fired.
513 * On invokation, drain as many pkts as possible (could be 0) and then
514 * if there are leftover packets reinsert the pkt in the scheduler.
517 ready_event(struct dn_flow_queue *q, struct mbuf **head, struct mbuf **tail)
520 struct dn_pipe *p = q->fs->pipe ;
523 DUMMYNET_LOCK_ASSERT();
526 printf("dummynet: ready_event- pipe is gone\n");
529 p_was_empty = (p->head == NULL) ;
532 * schedule fixed-rate queues linked to this pipe:
533 * Account for the bw accumulated since last scheduling, then
534 * drain as many pkts as allowed by q->numbytes and move to
535 * the delay line (in p) computing output time.
536 * bandwidth==0 (no limit) means we can drain the whole queue,
537 * setting len_scaled = 0 does the job.
539 q->numbytes += ( curr_time - q->sched_time ) * p->bandwidth;
540 while ( (pkt = q->head) != NULL ) {
541 int len = pkt->m_pkthdr.len;
542 int len_scaled = p->bandwidth ? len*8*hz : 0 ;
543 if (len_scaled > q->numbytes )
545 q->numbytes -= len_scaled ;
546 move_pkt(pkt, q, p, len);
549 * If we have more packets queued, schedule next ready event
550 * (can only occur when bandwidth != 0, otherwise we would have
551 * flushed the whole queue in the previous loop).
552 * To this purpose we record the current time and compute how many
553 * ticks to go for the finish time of the packet.
555 if ( (pkt = q->head) != NULL ) { /* this implies bandwidth != 0 */
556 dn_key t = SET_TICKS(pkt, q, p); /* ticks i have to wait */
557 q->sched_time = curr_time ;
558 heap_insert(&ready_heap, curr_time + t, (void *)q );
559 /* XXX should check errors on heap_insert, and drain the whole
560 * queue on error hoping next time we are luckier.
562 } else { /* RED needs to know when the queue becomes empty */
563 q->q_time = curr_time;
567 * If the delay line was empty call transmit_event() now.
568 * Otherwise, the scheduler will take care of it.
571 transmit_event(p, head, tail);
575 * Called when we can transmit packets on WF2Q queues. Take pkts out of
576 * the queues at their start time, and enqueue into the delay line.
577 * Packets are drained until p->numbytes < 0. As long as
578 * len_scaled >= p->numbytes, the packet goes into the delay line
579 * with a deadline p->delay. For the last packet, if p->numbytes<0,
580 * there is an additional delay.
583 ready_event_wfq(struct dn_pipe *p, struct mbuf **head, struct mbuf **tail)
585 int p_was_empty = (p->head == NULL) ;
586 struct dn_heap *sch = &(p->scheduler_heap);
587 struct dn_heap *neh = &(p->not_eligible_heap) ;
589 DUMMYNET_LOCK_ASSERT();
591 if (p->if_name[0] == 0) /* tx clock is simulated */
592 p->numbytes += ( curr_time - p->sched_time ) * p->bandwidth;
593 else { /* tx clock is for real, the ifq must be empty or this is a NOP */
594 if (p->ifp && p->ifp->if_snd.ifq_head != NULL)
597 DPRINTF(("dummynet: pipe %d ready from %s --\n",
598 p->pipe_nr, p->if_name));
603 * While we have backlogged traffic AND credit, we need to do
604 * something on the queue.
606 while ( p->numbytes >=0 && (sch->elements>0 || neh->elements >0) ) {
607 if (sch->elements > 0) { /* have some eligible pkts to send out */
608 struct dn_flow_queue *q = sch->p[0].object ;
609 struct mbuf *pkt = q->head;
610 struct dn_flow_set *fs = q->fs;
611 u_int64_t len = pkt->m_pkthdr.len;
612 int len_scaled = p->bandwidth ? len*8*hz : 0 ;
614 heap_extract(sch, NULL); /* remove queue from heap */
615 p->numbytes -= len_scaled ;
616 move_pkt(pkt, q, p, len);
618 p->V += (len<<MY_M) / p->sum ; /* update V */
619 q->S = q->F ; /* update start time */
620 if (q->len == 0) { /* Flow not backlogged any more */
622 heap_insert(&(p->idle_heap), q->F, q);
623 } else { /* still backlogged */
625 * update F and position in backlogged queue, then
626 * put flow in not_eligible_heap (we will fix this later).
628 len = (q->head)->m_pkthdr.len;
629 q->F += (len<<MY_M)/(u_int64_t) fs->weight ;
630 if (DN_KEY_LEQ(q->S, p->V))
631 heap_insert(neh, q->S, q);
633 heap_insert(sch, q->F, q);
637 * now compute V = max(V, min(S_i)). Remember that all elements in sch
638 * have by definition S_i <= V so if sch is not empty, V is surely
639 * the max and we must not update it. Conversely, if sch is empty
640 * we only need to look at neh.
642 if (sch->elements == 0 && neh->elements > 0)
643 p->V = MAX64 ( p->V, neh->p[0].key );
644 /* move from neh to sch any packets that have become eligible */
645 while (neh->elements > 0 && DN_KEY_LEQ(neh->p[0].key, p->V) ) {
646 struct dn_flow_queue *q = neh->p[0].object ;
647 heap_extract(neh, NULL);
648 heap_insert(sch, q->F, q);
651 if (p->if_name[0] != '\0') {/* tx clock is from a real thing */
652 p->numbytes = -1 ; /* mark not ready for I/O */
656 if (sch->elements == 0 && neh->elements == 0 && p->numbytes >= 0
657 && p->idle_heap.elements > 0) {
659 * no traffic and no events scheduled. We can get rid of idle-heap.
663 for (i = 0 ; i < p->idle_heap.elements ; i++) {
664 struct dn_flow_queue *q = p->idle_heap.p[i].object ;
671 p->idle_heap.elements = 0 ;
674 * If we are getting clocks from dummynet (not a real interface) and
675 * If we are under credit, schedule the next ready event.
676 * Also fix the delivery time of the last packet.
678 if (p->if_name[0]==0 && p->numbytes < 0) { /* this implies bandwidth >0 */
679 dn_key t=0 ; /* number of ticks i have to wait */
681 if (p->bandwidth > 0)
682 t = ( p->bandwidth -1 - p->numbytes) / p->bandwidth ;
683 dn_tag_get(p->tail)->output_time += t ;
684 p->sched_time = curr_time ;
685 heap_insert(&wfq_ready_heap, curr_time + t, (void *)p);
686 /* XXX should check errors on heap_insert, and drain the whole
687 * queue on error hoping next time we are luckier.
691 * If the delay line was empty call transmit_event() now.
692 * Otherwise, the scheduler will take care of it.
695 transmit_event(p, head, tail);
699 * This is called once per tick, or HZ times per second. It is used to
700 * increment the current tick counter and schedule expired events.
703 dummynet(void * __unused unused)
705 struct mbuf *head = NULL, *tail = NULL;
706 struct dn_pipe *pipe;
707 struct dn_heap *heaps[3];
709 void *p; /* generic parameter to handler */
712 heaps[0] = &ready_heap ; /* fixed-rate queues */
713 heaps[1] = &wfq_ready_heap ; /* wfq queues */
714 heaps[2] = &extract_heap ; /* delay line */
718 for (i=0; i < 3 ; i++) {
720 while (h->elements > 0 && DN_KEY_LEQ(h->p[0].key, curr_time) ) {
721 if (h->p[0].key > curr_time)
722 printf("dummynet: warning, heap %d is %d ticks late\n",
723 i, (int)(curr_time - h->p[0].key));
724 p = h->p[0].object ; /* store a copy before heap_extract */
725 heap_extract(h, NULL); /* need to extract before processing */
727 ready_event(p, &head, &tail);
729 struct dn_pipe *pipe = p;
730 if (pipe->if_name[0] != '\0')
731 printf("dummynet: bad ready_event_wfq for pipe %s\n",
734 ready_event_wfq(p, &head, &tail);
736 transmit_event(p, &head, &tail);
739 /* Sweep pipes trying to expire idle flow_queues. */
740 for (i = 0; i < HASHSIZE; i++)
741 SLIST_FOREACH(pipe, &pipehash[i], next)
742 if (pipe->idle_heap.elements > 0 &&
743 DN_KEY_LT(pipe->idle_heap.p[0].key, pipe->V) ) {
744 struct dn_flow_queue *q = pipe->idle_heap.p[0].object;
746 heap_extract(&(pipe->idle_heap), NULL);
747 q->S = q->F + 1; /* Mark timestamp as invalid. */
748 pipe->sum -= q->fs->weight;
756 callout_reset(&dn_timeout, 1, dummynet, NULL);
760 dummynet_send(struct mbuf *m)
762 struct dn_pkt_tag *pkt;
766 for (; m != NULL; m = n) {
770 switch (pkt->dn_dir) {
772 ip_output(m, NULL, NULL, pkt->flags, NULL, NULL);
775 ip = mtod(m, struct ip *);
776 ip->ip_len = htons(ip->ip_len);
777 ip->ip_off = htons(ip->ip_off);
786 ip6_output(m, NULL, NULL, pkt->flags, NULL, NULL, NULL);
790 if (bridge_dn_p != NULL)
791 ((*bridge_dn_p)(m, pkt->ifp));
793 printf("dummynet: if_bridge not loaded\n");
796 case DN_TO_ETH_DEMUX:
798 * The Ethernet code assumes the Ethernet header is
799 * contiguous in the first mbuf header.
800 * Insure this is true.
802 if (m->m_len < ETHER_HDR_LEN &&
803 (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
804 printf("dummynet/ether: pullup failed, "
805 "dropping packet\n");
808 ether_demux(m->m_pkthdr.rcvif, m);
811 ether_output_frame(pkt->ifp, m);
814 printf("dummynet: bad switch %d!\n", pkt->dn_dir);
822 * Unconditionally expire empty queues in case of shortage.
823 * Returns the number of queues freed.
826 expire_queues(struct dn_flow_set *fs)
828 struct dn_flow_queue *q, *prev ;
829 int i, initial_elements = fs->rq_elements ;
831 if (fs->last_expired == time_uptime)
833 fs->last_expired = time_uptime ;
834 for (i = 0 ; i <= fs->rq_size ; i++) /* last one is overflow */
835 for (prev=NULL, q = fs->rq[i] ; q != NULL ; )
836 if (q->head != NULL || q->S != q->F+1) {
839 } else { /* entry is idle, expire it */
840 struct dn_flow_queue *old_q = q ;
843 prev->next = q = q->next ;
845 fs->rq[i] = q = q->next ;
847 free(old_q, M_DUMMYNET);
849 return initial_elements - fs->rq_elements ;
853 * If room, create a new queue and put at head of slot i;
854 * otherwise, create or use the default queue.
856 static struct dn_flow_queue *
857 create_queue(struct dn_flow_set *fs, int i)
859 struct dn_flow_queue *q ;
861 if (fs->rq_elements > fs->rq_size * dn_max_ratio &&
862 expire_queues(fs) == 0) {
864 * No way to get room, use or create overflow queue.
867 if ( fs->rq[i] != NULL )
870 q = malloc(sizeof(*q), M_DUMMYNET, M_NOWAIT | M_ZERO);
872 printf("dummynet: sorry, cannot allocate queue for new flow\n");
877 q->next = fs->rq[i] ;
878 q->S = q->F + 1; /* hack - mark timestamp as invalid */
885 * Given a flow_set and a pkt in last_pkt, find a matching queue
886 * after appropriate masking. The queue is moved to front
887 * so that further searches take less time.
889 static struct dn_flow_queue *
890 find_queue(struct dn_flow_set *fs, struct ipfw_flow_id *id)
892 int i = 0 ; /* we need i and q for new allocations */
893 struct dn_flow_queue *q, *prev;
894 int is_v6 = IS_IP6_FLOW_ID(id);
896 if ( !(fs->flags_fs & DN_HAVE_FLOW_MASK) )
899 /* first, do the masking, then hash */
900 id->dst_port &= fs->flow_mask.dst_port ;
901 id->src_port &= fs->flow_mask.src_port ;
902 id->proto &= fs->flow_mask.proto ;
903 id->flags = 0 ; /* we don't care about this one */
905 APPLY_MASK(&id->dst_ip6, &fs->flow_mask.dst_ip6);
906 APPLY_MASK(&id->src_ip6, &fs->flow_mask.src_ip6);
907 id->flow_id6 &= fs->flow_mask.flow_id6;
909 i = ((id->dst_ip6.__u6_addr.__u6_addr32[0]) & 0xffff)^
910 ((id->dst_ip6.__u6_addr.__u6_addr32[1]) & 0xffff)^
911 ((id->dst_ip6.__u6_addr.__u6_addr32[2]) & 0xffff)^
912 ((id->dst_ip6.__u6_addr.__u6_addr32[3]) & 0xffff)^
914 ((id->dst_ip6.__u6_addr.__u6_addr32[0] >> 15) & 0xffff)^
915 ((id->dst_ip6.__u6_addr.__u6_addr32[1] >> 15) & 0xffff)^
916 ((id->dst_ip6.__u6_addr.__u6_addr32[2] >> 15) & 0xffff)^
917 ((id->dst_ip6.__u6_addr.__u6_addr32[3] >> 15) & 0xffff)^
919 ((id->src_ip6.__u6_addr.__u6_addr32[0] << 1) & 0xfffff)^
920 ((id->src_ip6.__u6_addr.__u6_addr32[1] << 1) & 0xfffff)^
921 ((id->src_ip6.__u6_addr.__u6_addr32[2] << 1) & 0xfffff)^
922 ((id->src_ip6.__u6_addr.__u6_addr32[3] << 1) & 0xfffff)^
924 ((id->src_ip6.__u6_addr.__u6_addr32[0] << 16) & 0xffff)^
925 ((id->src_ip6.__u6_addr.__u6_addr32[1] << 16) & 0xffff)^
926 ((id->src_ip6.__u6_addr.__u6_addr32[2] << 16) & 0xffff)^
927 ((id->src_ip6.__u6_addr.__u6_addr32[3] << 16) & 0xffff)^
929 (id->dst_port << 1) ^ (id->src_port) ^
933 id->dst_ip &= fs->flow_mask.dst_ip ;
934 id->src_ip &= fs->flow_mask.src_ip ;
936 i = ( (id->dst_ip) & 0xffff ) ^
937 ( (id->dst_ip >> 15) & 0xffff ) ^
938 ( (id->src_ip << 1) & 0xffff ) ^
939 ( (id->src_ip >> 16 ) & 0xffff ) ^
940 (id->dst_port << 1) ^ (id->src_port) ^
943 i = i % fs->rq_size ;
944 /* finally, scan the current list for a match */
946 for (prev=NULL, q = fs->rq[i] ; q ; ) {
949 IN6_ARE_ADDR_EQUAL(&id->dst_ip6,&q->id.dst_ip6) &&
950 IN6_ARE_ADDR_EQUAL(&id->src_ip6,&q->id.src_ip6) &&
951 id->dst_port == q->id.dst_port &&
952 id->src_port == q->id.src_port &&
953 id->proto == q->id.proto &&
954 id->flags == q->id.flags &&
955 id->flow_id6 == q->id.flow_id6)
958 if (!is_v6 && id->dst_ip == q->id.dst_ip &&
959 id->src_ip == q->id.src_ip &&
960 id->dst_port == q->id.dst_port &&
961 id->src_port == q->id.src_port &&
962 id->proto == q->id.proto &&
963 id->flags == q->id.flags)
966 /* No match. Check if we can expire the entry */
967 if (pipe_expire && q->head == NULL && q->S == q->F+1 ) {
968 /* entry is idle and not in any heap, expire it */
969 struct dn_flow_queue *old_q = q ;
972 prev->next = q = q->next ;
974 fs->rq[i] = q = q->next ;
976 free(old_q, M_DUMMYNET);
982 if (q && prev != NULL) { /* found and not in front */
983 prev->next = q->next ;
984 q->next = fs->rq[i] ;
988 if (q == NULL) { /* no match, need to allocate a new entry */
989 q = create_queue(fs, i);
997 red_drops(struct dn_flow_set *fs, struct dn_flow_queue *q, int len)
1002 * RED calculates the average queue size (avg) using a low-pass filter
1003 * with an exponential weighted (w_q) moving average:
1004 * avg <- (1-w_q) * avg + w_q * q_size
1005 * where q_size is the queue length (measured in bytes or * packets).
1007 * If q_size == 0, we compute the idle time for the link, and set
1008 * avg = (1 - w_q)^(idle/s)
1009 * where s is the time needed for transmitting a medium-sized packet.
1011 * Now, if avg < min_th the packet is enqueued.
1012 * If avg > max_th the packet is dropped. Otherwise, the packet is
1013 * dropped with probability P function of avg.
1018 /* queue in bytes or packets ? */
1019 u_int q_size = (fs->flags_fs & DN_QSIZE_IS_BYTES) ? q->len_bytes : q->len;
1021 DPRINTF(("\ndummynet: %d q: %2u ", (int) curr_time, q_size));
1023 /* average queue size estimation */
1026 * queue is not empty, avg <- avg + (q_size - avg) * w_q
1028 int diff = SCALE(q_size) - q->avg;
1029 int64_t v = SCALE_MUL((int64_t) diff, (int64_t) fs->w_q);
1034 * queue is empty, find for how long the queue has been
1035 * empty and use a lookup table for computing
1036 * (1 - * w_q)^(idle_time/s) where s is the time to send a
1038 * XXX check wraps...
1041 u_int t = (curr_time - q->q_time) / fs->lookup_step;
1043 q->avg = (t < fs->lookup_depth) ?
1044 SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
1047 DPRINTF(("dummynet: avg: %u ", SCALE_VAL(q->avg)));
1049 /* should i drop ? */
1051 if (q->avg < fs->min_th) {
1053 return 0; /* accept packet ; */
1055 if (q->avg >= fs->max_th) { /* average queue >= max threshold */
1056 if (fs->flags_fs & DN_IS_GENTLE_RED) {
1058 * According to Gentle-RED, if avg is greater than max_th the
1059 * packet is dropped with a probability
1060 * p_b = c_3 * avg - c_4
1061 * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
1063 p_b = SCALE_MUL((int64_t) fs->c_3, (int64_t) q->avg) - fs->c_4;
1066 DPRINTF(("dummynet: - drop"));
1069 } else if (q->avg > fs->min_th) {
1071 * we compute p_b using the linear dropping function p_b = c_1 *
1072 * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
1073 * max_p * min_th / (max_th - min_th)
1075 p_b = SCALE_MUL((int64_t) fs->c_1, (int64_t) q->avg) - fs->c_2;
1077 if (fs->flags_fs & DN_QSIZE_IS_BYTES)
1078 p_b = (p_b * len) / fs->max_pkt_size;
1079 if (++q->count == 0)
1080 q->random = random() & 0xffff;
1083 * q->count counts packets arrived since last drop, so a greater
1084 * value of q->count means a greater packet drop probability.
1086 if (SCALE_MUL(p_b, SCALE((int64_t) q->count)) > q->random) {
1088 DPRINTF(("dummynet: - red drop"));
1089 /* after a drop we calculate a new random value */
1090 q->random = random() & 0xffff;
1091 return 1; /* drop */
1094 /* end of RED algorithm */
1095 return 0 ; /* accept */
1098 static __inline struct dn_flow_set *
1099 locate_flowset(int fs_nr)
1101 struct dn_flow_set *fs;
1103 SLIST_FOREACH(fs, &flowsethash[HASH(fs_nr)], next)
1104 if (fs->fs_nr == fs_nr)
1110 static __inline struct dn_pipe *
1111 locate_pipe(int pipe_nr)
1113 struct dn_pipe *pipe;
1115 SLIST_FOREACH(pipe, &pipehash[HASH(pipe_nr)], next)
1116 if (pipe->pipe_nr == pipe_nr)
1123 * dummynet hook for packets. Below 'pipe' is a pipe or a queue
1124 * depending on whether WF2Q or fixed bw is used.
1126 * pipe_nr pipe or queue the packet is destined for.
1127 * dir where shall we send the packet after dummynet.
1128 * m the mbuf with the packet
1129 * ifp the 'ifp' parameter from the caller.
1130 * NULL in ip_input, destination interface in ip_output,
1131 * rule matching rule, in case of multiple passes
1132 * flags flags from the caller, only used in ip_output
1136 dummynet_io(struct mbuf *m, int dir, struct ip_fw_args *fwa)
1138 struct mbuf *head = NULL, *tail = NULL;
1139 struct dn_pkt_tag *pkt;
1141 struct dn_flow_set *fs = NULL;
1142 struct dn_pipe *pipe ;
1143 u_int64_t len = m->m_pkthdr.len ;
1144 struct dn_flow_queue *q = NULL ;
1146 ipfw_insn *cmd = ACTION_PTR(fwa->rule);
1148 KASSERT(m->m_nextpkt == NULL,
1149 ("dummynet_io: mbuf queue passed to dummynet"));
1151 if (cmd->opcode == O_LOG)
1153 is_pipe = (cmd->opcode == O_PIPE);
1157 * This is a dummynet rule, so we expect an O_PIPE or O_QUEUE rule.
1159 * XXXGL: probably the pipe->fs and fs->pipe logic here
1160 * below can be simplified.
1163 pipe = locate_pipe(fwa->cookie);
1167 fs = locate_flowset(fwa->cookie);
1170 goto dropit; /* This queue/pipe does not exist! */
1172 if (pipe == NULL) { /* Must be a queue, try find a matching pipe. */
1173 pipe = locate_pipe(fs->parent_nr);
1177 printf("dummynet: no pipe %d for queue %d, drop pkt\n",
1178 fs->parent_nr, fs->fs_nr);
1182 q = find_queue(fs, &(fwa->f_id));
1184 goto dropit ; /* cannot allocate queue */
1186 * update statistics, then check reasons to drop pkt
1188 q->tot_bytes += len ;
1190 if ( fs->plr && random() < fs->plr )
1191 goto dropit ; /* random pkt drop */
1192 if ( fs->flags_fs & DN_QSIZE_IS_BYTES) {
1193 if (q->len_bytes > fs->qsize)
1194 goto dropit ; /* queue size overflow */
1196 if (q->len >= fs->qsize)
1197 goto dropit ; /* queue count overflow */
1199 if ( fs->flags_fs & DN_IS_RED && red_drops(fs, q, len) )
1202 /* XXX expensive to zero, see if we can remove it*/
1203 mtag = m_tag_get(PACKET_TAG_DUMMYNET,
1204 sizeof(struct dn_pkt_tag), M_NOWAIT|M_ZERO);
1206 goto dropit ; /* cannot allocate packet header */
1207 m_tag_prepend(m, mtag); /* attach to mbuf chain */
1209 pkt = (struct dn_pkt_tag *)(mtag+1);
1210 /* ok, i can handle the pkt now... */
1211 /* build and enqueue packet + parameters */
1212 pkt->rule = fwa->rule ;
1215 pkt->ifp = fwa->oif;
1216 if (dir == DN_TO_IP_OUT || dir == DN_TO_IP6_OUT)
1217 pkt->flags = fwa->flags;
1219 if (q->head == NULL)
1222 q->tail->m_nextpkt = m;
1225 q->len_bytes += len ;
1227 if ( q->head != m ) /* flow was not idle, we are done */
1230 * If we reach this point the flow was previously idle, so we need
1231 * to schedule it. This involves different actions for fixed-rate or
1236 * Fixed-rate queue: just insert into the ready_heap.
1239 if (pipe->bandwidth)
1240 t = SET_TICKS(m, q, pipe);
1241 q->sched_time = curr_time ;
1242 if (t == 0) /* must process it now */
1243 ready_event(q, &head, &tail);
1245 heap_insert(&ready_heap, curr_time + t , q );
1248 * WF2Q. First, compute start time S: if the flow was idle (S=F+1)
1249 * set S to the virtual time V for the controlling pipe, and update
1250 * the sum of weights for the pipe; otherwise, remove flow from
1251 * idle_heap and set S to max(F,V).
1252 * Second, compute finish time F = S + len/weight.
1253 * Third, if pipe was idle, update V=max(S, V).
1254 * Fourth, count one more backlogged flow.
1256 if (DN_KEY_GT(q->S, q->F)) { /* means timestamps are invalid */
1258 pipe->sum += fs->weight ; /* add weight of new queue */
1260 heap_extract(&(pipe->idle_heap), q);
1261 q->S = MAX64(q->F, pipe->V ) ;
1263 q->F = q->S + ( len<<MY_M )/(u_int64_t) fs->weight;
1265 if (pipe->not_eligible_heap.elements == 0 &&
1266 pipe->scheduler_heap.elements == 0)
1267 pipe->V = MAX64 ( q->S, pipe->V );
1270 * Look at eligibility. A flow is not eligibile if S>V (when
1271 * this happens, it means that there is some other flow already
1272 * scheduled for the same pipe, so the scheduler_heap cannot be
1273 * empty). If the flow is not eligible we just store it in the
1274 * not_eligible_heap. Otherwise, we store in the scheduler_heap
1275 * and possibly invoke ready_event_wfq() right now if there is
1277 * Note that for all flows in scheduler_heap (SCH), S_i <= V,
1278 * and for all flows in not_eligible_heap (NEH), S_i > V .
1279 * So when we need to compute max( V, min(S_i) ) forall i in SCH+NEH,
1280 * we only need to look into NEH.
1282 if (DN_KEY_GT(q->S, pipe->V) ) { /* not eligible */
1283 if (pipe->scheduler_heap.elements == 0)
1284 printf("dummynet: ++ ouch! not eligible but empty scheduler!\n");
1285 heap_insert(&(pipe->not_eligible_heap), q->S, q);
1287 heap_insert(&(pipe->scheduler_heap), q->F, q);
1288 if (pipe->numbytes >= 0) { /* pipe is idle */
1289 if (pipe->scheduler_heap.elements != 1)
1290 printf("dummynet: OUCH! pipe should have been idle!\n");
1291 DPRINTF(("dummynet: waking up pipe %d at %d\n",
1292 pipe->pipe_nr, (int)(q->F >> MY_M)));
1293 pipe->sched_time = curr_time ;
1294 ready_event_wfq(pipe, &head, &tail);
1301 dummynet_send(head);
1309 return ( (fs && (fs->flags_fs & DN_NOERROR)) ? 0 : ENOBUFS);
1313 * Below, the rt_unref is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
1314 * Doing this would probably save us the initial bzero of dn_pkt
1316 #define DN_FREE_PKT(_m) do { \
1321 * Dispose all packets and flow_queues on a flow_set.
1322 * If all=1, also remove red lookup table and other storage,
1323 * including the descriptor itself.
1324 * For the one in dn_pipe MUST also cleanup ready_heap...
1327 purge_flow_set(struct dn_flow_set *fs, int all)
1329 struct dn_flow_queue *q, *qn ;
1332 DUMMYNET_LOCK_ASSERT();
1334 for (i = 0 ; i <= fs->rq_size ; i++ ) {
1335 for (q = fs->rq[i] ; q ; q = qn ) {
1336 struct mbuf *m, *mnext;
1339 while ((m = mnext) != NULL) {
1340 mnext = m->m_nextpkt;
1344 free(q, M_DUMMYNET);
1348 fs->rq_elements = 0 ;
1350 /* RED - free lookup table */
1352 free(fs->w_q_lookup, M_DUMMYNET);
1354 free(fs->rq, M_DUMMYNET);
1355 /* if this fs is not part of a pipe, free it */
1356 if (fs->pipe && fs != &(fs->pipe->fs) )
1357 free(fs, M_DUMMYNET);
1362 * Dispose all packets queued on a pipe (not a flow_set).
1363 * Also free all resources associated to a pipe, which is about
1367 purge_pipe(struct dn_pipe *pipe)
1369 struct mbuf *m, *mnext;
1371 purge_flow_set( &(pipe->fs), 1 );
1374 while ((m = mnext) != NULL) {
1375 mnext = m->m_nextpkt;
1379 heap_free( &(pipe->scheduler_heap) );
1380 heap_free( &(pipe->not_eligible_heap) );
1381 heap_free( &(pipe->idle_heap) );
1385 * Delete all pipes and heaps returning memory. Must also
1386 * remove references from all ipfw rules to all pipes.
1389 dummynet_flush(void)
1391 struct dn_pipe *pipe, *pipe1;
1392 struct dn_flow_set *fs, *fs1;
1396 /* Free heaps so we don't have unwanted events. */
1397 heap_free(&ready_heap);
1398 heap_free(&wfq_ready_heap);
1399 heap_free(&extract_heap);
1402 * Now purge all queued pkts and delete all pipes.
1404 * XXXGL: can we merge the for(;;) cycles into one or not?
1406 for (i = 0; i < HASHSIZE; i++)
1407 SLIST_FOREACH_SAFE(fs, &flowsethash[i], next, fs1) {
1408 SLIST_REMOVE(&flowsethash[i], fs, dn_flow_set, next);
1409 purge_flow_set(fs, 1);
1411 for (i = 0; i < HASHSIZE; i++)
1412 SLIST_FOREACH_SAFE(pipe, &pipehash[i], next, pipe1) {
1413 SLIST_REMOVE(&pipehash[i], pipe, dn_pipe, next);
1415 free(pipe, M_DUMMYNET);
1420 extern struct ip_fw *ip_fw_default_rule ;
1422 dn_rule_delete_fs(struct dn_flow_set *fs, void *r)
1425 struct dn_flow_queue *q ;
1428 for (i = 0 ; i <= fs->rq_size ; i++) /* last one is ovflow */
1429 for (q = fs->rq[i] ; q ; q = q->next )
1430 for (m = q->head ; m ; m = m->m_nextpkt ) {
1431 struct dn_pkt_tag *pkt = dn_tag_get(m) ;
1433 pkt->rule = ip_fw_default_rule ;
1437 * when a firewall rule is deleted, scan all queues and remove the flow-id
1438 * from packets matching this rule.
1441 dn_rule_delete(void *r)
1443 struct dn_pipe *pipe;
1444 struct dn_flow_set *fs;
1445 struct dn_pkt_tag *pkt;
1451 * If the rule references a queue (dn_flow_set), then scan
1452 * the flow set, otherwise scan pipes. Should do either, but doing
1453 * both does not harm.
1455 for (i = 0; i < HASHSIZE; i++)
1456 SLIST_FOREACH(fs, &flowsethash[i], next)
1457 dn_rule_delete_fs(fs, r);
1459 for (i = 0; i < HASHSIZE; i++)
1460 SLIST_FOREACH(pipe, &pipehash[i], next) {
1462 dn_rule_delete_fs(fs, r);
1463 for (m = pipe->head ; m ; m = m->m_nextpkt ) {
1464 pkt = dn_tag_get(m);
1466 pkt->rule = ip_fw_default_rule;
1473 * setup RED parameters
1476 config_red(struct dn_flow_set *p, struct dn_flow_set * x)
1481 x->min_th = SCALE(p->min_th);
1482 x->max_th = SCALE(p->max_th);
1483 x->max_p = p->max_p;
1485 x->c_1 = p->max_p / (p->max_th - p->min_th);
1486 x->c_2 = SCALE_MUL(x->c_1, SCALE(p->min_th));
1487 if (x->flags_fs & DN_IS_GENTLE_RED) {
1488 x->c_3 = (SCALE(1) - p->max_p) / p->max_th;
1489 x->c_4 = (SCALE(1) - 2 * p->max_p);
1492 /* if the lookup table already exist, free and create it again */
1493 if (x->w_q_lookup) {
1494 free(x->w_q_lookup, M_DUMMYNET);
1495 x->w_q_lookup = NULL ;
1497 if (red_lookup_depth == 0) {
1498 printf("\ndummynet: net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
1499 free(x, M_DUMMYNET);
1502 x->lookup_depth = red_lookup_depth;
1503 x->w_q_lookup = (u_int *) malloc(x->lookup_depth * sizeof(int),
1504 M_DUMMYNET, M_NOWAIT);
1505 if (x->w_q_lookup == NULL) {
1506 printf("dummynet: sorry, cannot allocate red lookup table\n");
1507 free(x, M_DUMMYNET);
1511 /* fill the lookup table with (1 - w_q)^x */
1512 x->lookup_step = p->lookup_step ;
1513 x->lookup_weight = p->lookup_weight ;
1514 x->w_q_lookup[0] = SCALE(1) - x->w_q;
1515 for (i = 1; i < x->lookup_depth; i++)
1516 x->w_q_lookup[i] = SCALE_MUL(x->w_q_lookup[i - 1], x->lookup_weight);
1517 if (red_avg_pkt_size < 1)
1518 red_avg_pkt_size = 512 ;
1519 x->avg_pkt_size = red_avg_pkt_size ;
1520 if (red_max_pkt_size < 1)
1521 red_max_pkt_size = 1500 ;
1522 x->max_pkt_size = red_max_pkt_size ;
1527 alloc_hash(struct dn_flow_set *x, struct dn_flow_set *pfs)
1529 if (x->flags_fs & DN_HAVE_FLOW_MASK) { /* allocate some slots */
1530 int l = pfs->rq_size;
1536 else if (l > DN_MAX_HASH_SIZE)
1537 l = DN_MAX_HASH_SIZE;
1539 } else /* one is enough for null mask */
1541 x->rq = malloc((1 + x->rq_size) * sizeof(struct dn_flow_queue *),
1542 M_DUMMYNET, M_NOWAIT | M_ZERO);
1543 if (x->rq == NULL) {
1544 printf("dummynet: sorry, cannot allocate queue\n");
1552 set_fs_parms(struct dn_flow_set *x, struct dn_flow_set *src)
1554 x->flags_fs = src->flags_fs;
1555 x->qsize = src->qsize;
1557 x->flow_mask = src->flow_mask;
1558 if (x->flags_fs & DN_QSIZE_IS_BYTES) {
1559 if (x->qsize > 1024*1024)
1560 x->qsize = 1024*1024 ;
1567 /* configuring RED */
1568 if ( x->flags_fs & DN_IS_RED )
1569 config_red(src, x) ; /* XXX should check errors */
1573 * setup pipe or queue parameters.
1577 config_pipe(struct dn_pipe *p)
1579 struct dn_flow_set *pfs = &(p->fs);
1580 struct dn_flow_queue *q;
1584 * The config program passes parameters as follows:
1585 * bw = bits/second (0 means no limits),
1586 * delay = ms, must be translated into ticks.
1587 * qsize = slots/bytes
1589 p->delay = ( p->delay * hz ) / 1000 ;
1590 /* We need either a pipe number or a flow_set number */
1591 if (p->pipe_nr == 0 && pfs->fs_nr == 0)
1593 if (p->pipe_nr != 0 && pfs->fs_nr != 0)
1595 if (p->pipe_nr != 0) { /* this is a pipe */
1596 struct dn_pipe *pipe;
1599 pipe = locate_pipe(p->pipe_nr); /* locate pipe */
1601 if (pipe == NULL) { /* new pipe */
1602 pipe = malloc(sizeof(struct dn_pipe), M_DUMMYNET,
1606 printf("dummynet: no memory for new pipe\n");
1609 pipe->pipe_nr = p->pipe_nr;
1610 pipe->fs.pipe = pipe ;
1611 /* idle_heap is the only one from which we extract from the middle.
1613 pipe->idle_heap.size = pipe->idle_heap.elements = 0 ;
1614 pipe->idle_heap.offset=OFFSET_OF(struct dn_flow_queue, heap_pos);
1616 /* Flush accumulated credit for all queues */
1617 for (i = 0; i <= pipe->fs.rq_size; i++)
1618 for (q = pipe->fs.rq[i]; q; q = q->next)
1621 pipe->bandwidth = p->bandwidth ;
1622 pipe->numbytes = 0; /* just in case... */
1623 bcopy(p->if_name, pipe->if_name, sizeof(p->if_name) );
1624 pipe->ifp = NULL ; /* reset interface ptr */
1625 pipe->delay = p->delay ;
1626 set_fs_parms(&(pipe->fs), pfs);
1629 if (pipe->fs.rq == NULL) { /* a new pipe */
1630 error = alloc_hash(&(pipe->fs), pfs);
1633 free(pipe, M_DUMMYNET);
1636 SLIST_INSERT_HEAD(&pipehash[HASH(pipe->pipe_nr)], pipe, next);
1639 } else { /* config queue */
1640 struct dn_flow_set *fs;
1643 fs = locate_flowset(pfs->fs_nr); /* locate flow_set */
1645 if (fs == NULL) { /* new */
1646 if (pfs->parent_nr == 0) { /* need link to a pipe */
1650 fs = malloc(sizeof(struct dn_flow_set), M_DUMMYNET,
1654 printf("dummynet: no memory for new flow_set\n");
1657 fs->fs_nr = pfs->fs_nr;
1658 fs->parent_nr = pfs->parent_nr;
1659 fs->weight = pfs->weight;
1660 if (fs->weight == 0)
1662 else if (fs->weight > 100)
1665 /* Change parent pipe not allowed; must delete and recreate */
1666 if (pfs->parent_nr != 0 && fs->parent_nr != pfs->parent_nr) {
1671 set_fs_parms(fs, pfs);
1673 if (fs->rq == NULL) { /* a new flow_set */
1674 error = alloc_hash(fs, pfs);
1677 free(fs, M_DUMMYNET);
1680 SLIST_INSERT_HEAD(&flowsethash[HASH(fs->fs_nr)], fs, next);
1688 * Helper function to remove from a heap queues which are linked to
1689 * a flow_set about to be deleted.
1692 fs_remove_from_heap(struct dn_heap *h, struct dn_flow_set *fs)
1694 int i = 0, found = 0 ;
1695 for (; i < h->elements ;)
1696 if ( ((struct dn_flow_queue *)h->p[i].object)->fs == fs) {
1698 h->p[i] = h->p[h->elements] ;
1707 * helper function to remove a pipe from a heap (can be there at most once)
1710 pipe_remove_from_heap(struct dn_heap *h, struct dn_pipe *p)
1712 if (h->elements > 0) {
1714 for (i=0; i < h->elements ; i++ ) {
1715 if (h->p[i].object == p) { /* found it */
1717 h->p[i] = h->p[h->elements] ;
1726 * drain all queues. Called in case of severe mbuf shortage.
1731 struct dn_flow_set *fs;
1732 struct dn_pipe *pipe;
1733 struct mbuf *m, *mnext;
1736 DUMMYNET_LOCK_ASSERT();
1738 heap_free(&ready_heap);
1739 heap_free(&wfq_ready_heap);
1740 heap_free(&extract_heap);
1741 /* remove all references to this pipe from flow_sets */
1742 for (i = 0; i < HASHSIZE; i++)
1743 SLIST_FOREACH(fs, &flowsethash[i], next)
1744 purge_flow_set(fs, 0);
1746 for (i = 0; i < HASHSIZE; i++) {
1747 SLIST_FOREACH(pipe, &pipehash[i], next) {
1748 purge_flow_set(&(pipe->fs), 0);
1751 while ((m = mnext) != NULL) {
1752 mnext = m->m_nextpkt;
1755 pipe->head = pipe->tail = NULL;
1761 * Fully delete a pipe or a queue, cleaning up associated info.
1764 delete_pipe(struct dn_pipe *p)
1766 if (p->pipe_nr == 0 && p->fs.fs_nr == 0)
1768 if (p->pipe_nr != 0 && p->fs.fs_nr != 0)
1770 if (p->pipe_nr != 0) { /* this is an old-style pipe */
1771 struct dn_pipe *pipe;
1772 struct dn_flow_set *fs;
1776 pipe = locate_pipe(p->pipe_nr); /* locate pipe */
1780 return (ENOENT); /* not found */
1783 /* Unlink from list of pipes. */
1784 SLIST_REMOVE(&pipehash[HASH(pipe->pipe_nr)], pipe, dn_pipe, next);
1786 /* Remove all references to this pipe from flow_sets. */
1787 for (i = 0; i < HASHSIZE; i++)
1788 SLIST_FOREACH(fs, &flowsethash[i], next)
1789 if (fs->pipe == pipe) {
1790 printf("dummynet: ++ ref to pipe %d from fs %d\n",
1791 p->pipe_nr, fs->fs_nr);
1793 purge_flow_set(fs, 0);
1795 fs_remove_from_heap(&ready_heap, &(pipe->fs));
1796 purge_pipe(pipe); /* remove all data associated to this pipe */
1797 /* remove reference to here from extract_heap and wfq_ready_heap */
1798 pipe_remove_from_heap(&extract_heap, pipe);
1799 pipe_remove_from_heap(&wfq_ready_heap, pipe);
1802 free(pipe, M_DUMMYNET);
1803 } else { /* this is a WF2Q queue (dn_flow_set) */
1804 struct dn_flow_set *fs;
1807 fs = locate_flowset(p->fs.fs_nr); /* locate set */
1811 return (ENOENT); /* not found */
1814 /* Unlink from list of flowsets. */
1815 SLIST_REMOVE( &flowsethash[HASH(fs->fs_nr)], fs, dn_flow_set, next);
1817 if (fs->pipe != NULL) {
1818 /* Update total weight on parent pipe and cleanup parent heaps. */
1819 fs->pipe->sum -= fs->weight * fs->backlogged ;
1820 fs_remove_from_heap(&(fs->pipe->not_eligible_heap), fs);
1821 fs_remove_from_heap(&(fs->pipe->scheduler_heap), fs);
1822 #if 1 /* XXX should i remove from idle_heap as well ? */
1823 fs_remove_from_heap(&(fs->pipe->idle_heap), fs);
1826 purge_flow_set(fs, 1);
1833 * helper function used to copy data from kernel in DUMMYNET_GET
1836 dn_copy_set(struct dn_flow_set *set, char *bp)
1839 struct dn_flow_queue *q, *qp = (struct dn_flow_queue *)bp;
1841 DUMMYNET_LOCK_ASSERT();
1843 for (i = 0 ; i <= set->rq_size ; i++)
1844 for (q = set->rq[i] ; q ; q = q->next, qp++ ) {
1845 if (q->hash_slot != i)
1846 printf("dummynet: ++ at %d: wrong slot (have %d, "
1847 "should be %d)\n", copied, q->hash_slot, i);
1849 printf("dummynet: ++ at %d: wrong fs ptr (have %p, should be %p)\n",
1852 bcopy(q, qp, sizeof( *q ) );
1853 /* cleanup pointers */
1855 qp->head = qp->tail = NULL ;
1858 if (copied != set->rq_elements)
1859 printf("dummynet: ++ wrong count, have %d should be %d\n",
1860 copied, set->rq_elements);
1867 struct dn_flow_set *fs;
1868 struct dn_pipe *pipe;
1872 DUMMYNET_LOCK_ASSERT();
1874 * Compute size of data structures: list of pipes and flow_sets.
1876 for (i = 0; i < HASHSIZE; i++) {
1877 SLIST_FOREACH(pipe, &pipehash[i], next)
1878 size += sizeof(*pipe) +
1879 pipe->fs.rq_elements * sizeof(struct dn_flow_queue);
1880 SLIST_FOREACH(fs, &flowsethash[i], next)
1881 size += sizeof (*fs) +
1882 fs->rq_elements * sizeof(struct dn_flow_queue);
1888 dummynet_get(struct sockopt *sopt)
1890 char *buf, *bp ; /* bp is the "copy-pointer" */
1892 struct dn_flow_set *fs;
1893 struct dn_pipe *pipe;
1896 /* XXX lock held too long */
1899 * XXX: Ugly, but we need to allocate memory with M_WAITOK flag and we
1900 * cannot use this flag while holding a mutex.
1902 for (i = 0; i < 10; i++) {
1903 size = dn_calc_size();
1905 buf = malloc(size, M_TEMP, M_WAITOK);
1907 if (size == dn_calc_size())
1917 for (i = 0; i < HASHSIZE; i++)
1918 SLIST_FOREACH(pipe, &pipehash[i], next) {
1919 struct dn_pipe *pipe_bp = (struct dn_pipe *)bp;
1922 * Copy pipe descriptor into *bp, convert delay back to ms,
1923 * then copy the flow_set descriptor(s) one at a time.
1924 * After each flow_set, copy the queue descriptor it owns.
1926 bcopy(pipe, bp, sizeof(*pipe));
1927 pipe_bp->delay = (pipe_bp->delay * 1000) / hz;
1929 * XXX the following is a hack based on ->next being the
1930 * first field in dn_pipe and dn_flow_set. The correct
1931 * solution would be to move the dn_flow_set to the beginning
1932 * of struct dn_pipe.
1934 pipe_bp->next.sle_next = (struct dn_pipe *)DN_IS_PIPE;
1935 /* Clean pointers. */
1936 pipe_bp->head = pipe_bp->tail = NULL;
1937 pipe_bp->fs.next.sle_next = NULL;
1938 pipe_bp->fs.pipe = NULL;
1939 pipe_bp->fs.rq = NULL;
1941 bp += sizeof(*pipe) ;
1942 bp = dn_copy_set(&(pipe->fs), bp);
1945 for (i = 0; i < HASHSIZE; i++)
1946 SLIST_FOREACH(fs, &flowsethash[i], next) {
1947 struct dn_flow_set *fs_bp = (struct dn_flow_set *)bp;
1949 bcopy(fs, bp, sizeof(*fs));
1950 /* XXX same hack as above */
1951 fs_bp->next.sle_next = (struct dn_flow_set *)DN_IS_QUEUE;
1955 bp = dn_copy_set(fs, bp);
1960 error = sooptcopyout(sopt, buf, size);
1966 * Handler for the various dummynet socket options (get, flush, config, del)
1969 ip_dn_ctl(struct sockopt *sopt)
1972 struct dn_pipe *p, tmp_pipe;
1974 /* Disallow sets in really-really secure mode. */
1975 if (sopt->sopt_dir == SOPT_SET) {
1976 #if __FreeBSD_version >= 500034
1977 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
1981 if (securelevel >= 3)
1986 switch (sopt->sopt_name) {
1988 printf("dummynet: -- unknown option %d", sopt->sopt_name);
1991 case IP_DUMMYNET_GET :
1992 error = dummynet_get(sopt);
1995 case IP_DUMMYNET_FLUSH :
1999 case IP_DUMMYNET_CONFIGURE :
2001 error = sooptcopyin(sopt, p, sizeof *p, sizeof *p);
2004 error = config_pipe(p);
2007 case IP_DUMMYNET_DEL : /* remove a pipe or queue */
2009 error = sooptcopyin(sopt, p, sizeof *p, sizeof *p);
2013 error = delete_pipe(p);
2025 printf("DUMMYNET with IPv6 initialized (040826)\n");
2027 DUMMYNET_LOCK_INIT();
2029 for (i = 0; i < HASHSIZE; i++) {
2030 SLIST_INIT(&pipehash[i]);
2031 SLIST_INIT(&flowsethash[i]);
2033 ready_heap.size = ready_heap.elements = 0 ;
2034 ready_heap.offset = 0 ;
2036 wfq_ready_heap.size = wfq_ready_heap.elements = 0 ;
2037 wfq_ready_heap.offset = 0 ;
2039 extract_heap.size = extract_heap.elements = 0 ;
2040 extract_heap.offset = 0 ;
2042 ip_dn_ctl_ptr = ip_dn_ctl;
2043 ip_dn_io_ptr = dummynet_io;
2044 ip_dn_ruledel_ptr = dn_rule_delete;
2046 callout_init(&dn_timeout, NET_CALLOUT_MPSAFE);
2047 callout_reset(&dn_timeout, 1, dummynet, NULL);
2054 ip_dn_ctl_ptr = NULL;
2055 ip_dn_io_ptr = NULL;
2056 ip_dn_ruledel_ptr = NULL;
2058 callout_stop(&dn_timeout);
2061 DUMMYNET_LOCK_DESTROY();
2063 #endif /* KLD_MODULE */
2066 dummynet_modevent(module_t mod, int type, void *data)
2070 if (DUMMYNET_LOADED) {
2071 printf("DUMMYNET already loaded\n");
2078 #if !defined(KLD_MODULE)
2079 printf("dummynet statically compiled, cannot unload\n");
2092 static moduledata_t dummynet_mod = {
2097 DECLARE_MODULE(dummynet, dummynet_mod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
2098 MODULE_DEPEND(dummynet, ipfw, 2, 2, 2);
2099 MODULE_VERSION(dummynet, 1);