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 #include "opt_inet6.h"
35 * This module implements IP dummynet, a bandwidth limiter/delay emulator
36 * used in conjunction with the ipfw package.
37 * Description of the data structures used is in ip_dummynet.h
38 * Here you mainly find the following blocks of code:
39 * + variable declarations;
40 * + heap management functions;
41 * + scheduler and dummynet functions;
42 * + configuration and initialization.
44 * NOTA BENE: critical sections are protected by the "dummynet lock".
46 * Most important Changes:
49 * 010124: Fixed WF2Q behaviour
50 * 010122: Fixed spl protection.
51 * 000601: WF2Q support
52 * 000106: large rewrite, use heaps to handle very many pipes.
53 * 980513: initial release
55 * include files marked with XXX are probably not needed
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/malloc.h>
62 #include <sys/kernel.h>
63 #include <sys/module.h>
65 #include <sys/socket.h>
66 #include <sys/socketvar.h>
68 #include <sys/sysctl.h>
70 #include <net/route.h>
71 #include <netinet/in.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/in_var.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_fw.h>
76 #include <netinet/ip_dummynet.h>
77 #include <netinet/ip_var.h>
79 #include <netinet/if_ether.h> /* for struct arpcom */
81 #include <netinet/ip6.h> /* for ip6_input, ip6_output prototypes */
82 #include <netinet6/ip6_var.h>
85 * We keep a private variable for the simulation time, but we could
86 * probably use an existing one ("softticks" in sys/kern/kern_timeout.c)
88 static dn_key curr_time = 0 ; /* current simulation time */
90 static int dn_hash_size = 64 ; /* default hash size */
92 /* statistics on number of queue searches and search steps */
93 static int searches, search_steps ;
94 static int pipe_expire = 1 ; /* expire queue if empty */
95 static int dn_max_ratio = 16 ; /* max queues/buckets ratio */
97 static int red_lookup_depth = 256; /* RED - default lookup table depth */
98 static int red_avg_pkt_size = 512; /* RED - default medium packet size */
99 static int red_max_pkt_size = 1500; /* RED - default max packet size */
102 * Three heaps contain queues and pipes that the scheduler handles:
104 * ready_heap contains all dn_flow_queue related to fixed-rate pipes.
106 * wfq_ready_heap contains the pipes associated with WF2Q flows
108 * extract_heap contains pipes associated with delay lines.
112 MALLOC_DEFINE(M_DUMMYNET, "dummynet", "dummynet heap");
114 static struct dn_heap ready_heap, extract_heap, wfq_ready_heap ;
116 static int heap_init(struct dn_heap *h, int size);
117 static int heap_insert (struct dn_heap *h, dn_key key1, void *p);
118 static void heap_extract(struct dn_heap *h, void *obj);
119 static void transmit_event(struct dn_pipe *pipe, struct mbuf **head,
121 static void ready_event(struct dn_flow_queue *q, struct mbuf **head,
123 static void ready_event_wfq(struct dn_pipe *p, struct mbuf **head,
127 #define HASH(num) ((((num) >> 8) ^ ((num) >> 4) ^ (num)) & 0x0f)
128 static struct dn_pipe_head pipehash[HASHSIZE]; /* all pipes */
129 static struct dn_flow_set_head flowsethash[HASHSIZE]; /* all flowsets */
131 static struct callout dn_timeout;
133 extern void (*bridge_dn_p)(struct mbuf *, struct ifnet *);
136 SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet,
137 CTLFLAG_RW, 0, "Dummynet");
138 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, hash_size,
139 CTLFLAG_RW, &dn_hash_size, 0, "Default hash table size");
140 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, curr_time,
141 CTLFLAG_RD, &curr_time, 0, "Current tick");
142 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, ready_heap,
143 CTLFLAG_RD, &ready_heap.size, 0, "Size of ready heap");
144 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, extract_heap,
145 CTLFLAG_RD, &extract_heap.size, 0, "Size of extract heap");
146 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, searches,
147 CTLFLAG_RD, &searches, 0, "Number of queue searches");
148 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, search_steps,
149 CTLFLAG_RD, &search_steps, 0, "Number of queue search steps");
150 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, expire,
151 CTLFLAG_RW, &pipe_expire, 0, "Expire queue if empty");
152 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, max_chain_len,
153 CTLFLAG_RW, &dn_max_ratio, 0,
154 "Max ratio between dynamic queues and buckets");
155 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
156 CTLFLAG_RD, &red_lookup_depth, 0, "Depth of RED lookup table");
157 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
158 CTLFLAG_RD, &red_avg_pkt_size, 0, "RED Medium packet size");
159 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
160 CTLFLAG_RD, &red_max_pkt_size, 0, "RED Max packet size");
163 #ifdef DUMMYNET_DEBUG
164 int dummynet_debug = 0;
166 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug, CTLFLAG_RW, &dummynet_debug,
167 0, "control debugging printfs");
169 #define DPRINTF(X) if (dummynet_debug) printf X
174 static struct mtx dummynet_mtx;
176 * NB: Recursion is needed to deal with re-entry via ICMP. That is,
177 * a packet may be dispatched via ip_input from dummynet_io and
178 * re-enter through ip_output. Yech.
180 #define DUMMYNET_LOCK_INIT() \
181 mtx_init(&dummynet_mtx, "dummynet", NULL, MTX_DEF | MTX_RECURSE)
182 #define DUMMYNET_LOCK_DESTROY() mtx_destroy(&dummynet_mtx)
183 #define DUMMYNET_LOCK() mtx_lock(&dummynet_mtx)
184 #define DUMMYNET_UNLOCK() mtx_unlock(&dummynet_mtx)
185 #define DUMMYNET_LOCK_ASSERT() do { \
186 mtx_assert(&dummynet_mtx, MA_OWNED); \
187 NET_ASSERT_GIANT(); \
190 static int config_pipe(struct dn_pipe *p);
191 static int ip_dn_ctl(struct sockopt *sopt);
193 static void dummynet(void *);
194 static void dummynet_flush(void);
195 static void dummynet_send(struct mbuf *);
196 void dummynet_drain(void);
197 static ip_dn_io_t dummynet_io;
198 static void dn_rule_delete(void *);
201 * Heap management functions.
203 * In the heap, first node is element 0. Children of i are 2i+1 and 2i+2.
204 * Some macros help finding parent/children so we can optimize them.
206 * heap_init() is called to expand the heap when needed.
207 * Increment size in blocks of 16 entries.
208 * XXX failure to allocate a new element is a pretty bad failure
209 * as we basically stall a whole queue forever!!
210 * Returns 1 on error, 0 on success
212 #define HEAP_FATHER(x) ( ( (x) - 1 ) / 2 )
213 #define HEAP_LEFT(x) ( 2*(x) + 1 )
214 #define HEAP_IS_LEFT(x) ( (x) & 1 )
215 #define HEAP_RIGHT(x) ( 2*(x) + 2 )
216 #define HEAP_SWAP(a, b, buffer) { buffer = a ; a = b ; b = buffer ; }
217 #define HEAP_INCREMENT 15
220 heap_init(struct dn_heap *h, int new_size)
222 struct dn_heap_entry *p;
224 if (h->size >= new_size ) {
225 printf("dummynet: %s, Bogus call, have %d want %d\n", __func__,
229 new_size = (new_size + HEAP_INCREMENT ) & ~HEAP_INCREMENT ;
230 p = malloc(new_size * sizeof(*p), M_DUMMYNET, M_NOWAIT);
232 printf("dummynet: %s, resize %d failed\n", __func__, new_size );
233 return 1 ; /* error */
236 bcopy(h->p, p, h->size * sizeof(*p) );
237 free(h->p, M_DUMMYNET);
245 * Insert element in heap. Normally, p != NULL, we insert p in
246 * a new position and bubble up. If p == NULL, then the element is
247 * already in place, and key is the position where to start the
249 * Returns 1 on failure (cannot allocate new heap entry)
251 * If offset > 0 the position (index, int) of the element in the heap is
252 * also stored in the element itself at the given offset in bytes.
254 #define SET_OFFSET(heap, node) \
255 if (heap->offset > 0) \
256 *((int *)((char *)(heap->p[node].object) + heap->offset)) = node ;
258 * RESET_OFFSET is used for sanity checks. It sets offset to an invalid value.
260 #define RESET_OFFSET(heap, node) \
261 if (heap->offset > 0) \
262 *((int *)((char *)(heap->p[node].object) + heap->offset)) = -1 ;
264 heap_insert(struct dn_heap *h, dn_key key1, void *p)
266 int son = h->elements ;
268 if (p == NULL) /* data already there, set starting point */
270 else { /* insert new element at the end, possibly resize */
272 if (son == h->size) /* need resize... */
273 if (heap_init(h, h->elements+1) )
274 return 1 ; /* failure... */
275 h->p[son].object = p ;
276 h->p[son].key = key1 ;
279 while (son > 0) { /* bubble up */
280 int father = HEAP_FATHER(son) ;
281 struct dn_heap_entry tmp ;
283 if (DN_KEY_LT( h->p[father].key, h->p[son].key ) )
284 break ; /* found right position */
285 /* son smaller than father, swap and repeat */
286 HEAP_SWAP(h->p[son], h->p[father], tmp) ;
295 * remove top element from heap, or obj if obj != NULL
298 heap_extract(struct dn_heap *h, void *obj)
300 int child, father, max = h->elements - 1 ;
303 printf("dummynet: warning, extract from empty heap 0x%p\n", h);
306 father = 0 ; /* default: move up smallest child */
307 if (obj != NULL) { /* extract specific element, index is at offset */
309 panic("dummynet: heap_extract from middle not supported on this heap!!!\n");
310 father = *((int *)((char *)obj + h->offset)) ;
311 if (father < 0 || father >= h->elements) {
312 printf("dummynet: heap_extract, father %d out of bound 0..%d\n",
313 father, h->elements);
314 panic("dummynet: heap_extract");
317 RESET_OFFSET(h, father);
318 child = HEAP_LEFT(father) ; /* left child */
319 while (child <= max) { /* valid entry */
320 if (child != max && DN_KEY_LT(h->p[child+1].key, h->p[child].key) )
321 child = child+1 ; /* take right child, otherwise left */
322 h->p[father] = h->p[child] ;
323 SET_OFFSET(h, father);
325 child = HEAP_LEFT(child) ; /* left child for next loop */
330 * Fill hole with last entry and bubble up, reusing the insert code
332 h->p[father] = h->p[max] ;
333 heap_insert(h, father, NULL); /* this one cannot fail */
339 * change object position and update references
340 * XXX this one is never used!
343 heap_move(struct dn_heap *h, dn_key new_key, void *object)
347 int max = h->elements-1 ;
348 struct dn_heap_entry buf ;
351 panic("cannot move items on this heap");
353 i = *((int *)((char *)object + h->offset));
354 if (DN_KEY_LT(new_key, h->p[i].key) ) { /* must move up */
355 h->p[i].key = new_key ;
356 for (; i>0 && DN_KEY_LT(new_key, h->p[(temp = HEAP_FATHER(i))].key) ;
357 i = temp ) { /* bubble up */
358 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
361 } else { /* must move down */
362 h->p[i].key = new_key ;
363 while ( (temp = HEAP_LEFT(i)) <= max ) { /* found left child */
364 if ((temp != max) && DN_KEY_GT(h->p[temp].key, h->p[temp+1].key))
365 temp++ ; /* select child with min key */
366 if (DN_KEY_GT(new_key, h->p[temp].key)) { /* go down */
367 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
376 #endif /* heap_move, unused */
379 * heapify() will reorganize data inside an array to maintain the
380 * heap property. It is needed when we delete a bunch of entries.
383 heapify(struct dn_heap *h)
387 for (i = 0 ; i < h->elements ; i++ )
388 heap_insert(h, i , NULL) ;
392 * cleanup the heap and free data structure
395 heap_free(struct dn_heap *h)
398 free(h->p, M_DUMMYNET);
399 bzero(h, sizeof(*h) );
403 * --- end of heap management functions ---
407 * Return the mbuf tag holding the dummynet state. As an optimization
408 * this is assumed to be the first tag on the list. If this turns out
409 * wrong we'll need to search the list.
411 static struct dn_pkt_tag *
412 dn_tag_get(struct mbuf *m)
414 struct m_tag *mtag = m_tag_first(m);
415 KASSERT(mtag != NULL &&
416 mtag->m_tag_cookie == MTAG_ABI_COMPAT &&
417 mtag->m_tag_id == PACKET_TAG_DUMMYNET,
418 ("packet on dummynet queue w/o dummynet tag!"));
419 return (struct dn_pkt_tag *)(mtag+1);
423 * Scheduler functions:
425 * transmit_event() is called when the delay-line needs to enter
426 * the scheduler, either because of existing pkts getting ready,
427 * or new packets entering the queue. The event handled is the delivery
428 * time of the packet.
430 * ready_event() does something similar with fixed-rate queues, and the
431 * event handled is the finish time of the head pkt.
433 * wfq_ready_event() does something similar with WF2Q queues, and the
434 * event handled is the start time of the head pkt.
436 * In all cases, we make sure that the data structures are consistent
437 * before passing pkts out, because this might trigger recursive
438 * invocations of the procedures.
441 transmit_event(struct dn_pipe *pipe, struct mbuf **head, struct mbuf **tail)
444 struct dn_pkt_tag *pkt;
446 DUMMYNET_LOCK_ASSERT();
448 while ((m = pipe->head) != NULL) {
450 if (!DN_KEY_LEQ(pkt->output_time, curr_time))
453 pipe->head = m->m_nextpkt;
455 (*tail)->m_nextpkt = m;
461 (*tail)->m_nextpkt = NULL;
463 /* If there are leftover packets, put into the heap for next event. */
464 if ((m = pipe->head) != NULL) {
467 * XXX: Should check errors on heap_insert, by draining the
468 * whole pipe p and hoping in the future we are more successful.
470 heap_insert(&extract_heap, pkt->output_time, pipe);
475 * the following macro computes how many ticks we have to wait
476 * before being able to transmit a packet. The credit is taken from
477 * either a pipe (WF2Q) or a flow_queue (per-flow queueing)
479 #define SET_TICKS(_m, q, p) \
480 ((_m)->m_pkthdr.len*8*hz - (q)->numbytes + p->bandwidth - 1 ) / \
484 * extract pkt from queue, compute output time (could be now)
485 * and put into delay line (p_queue)
488 move_pkt(struct mbuf *pkt, struct dn_flow_queue *q,
489 struct dn_pipe *p, int len)
491 struct dn_pkt_tag *dt = dn_tag_get(pkt);
493 q->head = pkt->m_nextpkt ;
495 q->len_bytes -= len ;
497 dt->output_time = curr_time + p->delay ;
502 p->tail->m_nextpkt = pkt;
504 p->tail->m_nextpkt = NULL;
508 * ready_event() is invoked every time the queue must enter the
509 * scheduler, either because the first packet arrives, or because
510 * a previously scheduled event fired.
511 * On invokation, drain as many pkts as possible (could be 0) and then
512 * if there are leftover packets reinsert the pkt in the scheduler.
515 ready_event(struct dn_flow_queue *q, struct mbuf **head, struct mbuf **tail)
518 struct dn_pipe *p = q->fs->pipe ;
521 DUMMYNET_LOCK_ASSERT();
524 printf("dummynet: ready_event- pipe is gone\n");
527 p_was_empty = (p->head == NULL) ;
530 * schedule fixed-rate queues linked to this pipe:
531 * Account for the bw accumulated since last scheduling, then
532 * drain as many pkts as allowed by q->numbytes and move to
533 * the delay line (in p) computing output time.
534 * bandwidth==0 (no limit) means we can drain the whole queue,
535 * setting len_scaled = 0 does the job.
537 q->numbytes += ( curr_time - q->sched_time ) * p->bandwidth;
538 while ( (pkt = q->head) != NULL ) {
539 int len = pkt->m_pkthdr.len;
540 int len_scaled = p->bandwidth ? len*8*hz : 0 ;
541 if (len_scaled > q->numbytes )
543 q->numbytes -= len_scaled ;
544 move_pkt(pkt, q, p, len);
547 * If we have more packets queued, schedule next ready event
548 * (can only occur when bandwidth != 0, otherwise we would have
549 * flushed the whole queue in the previous loop).
550 * To this purpose we record the current time and compute how many
551 * ticks to go for the finish time of the packet.
553 if ( (pkt = q->head) != NULL ) { /* this implies bandwidth != 0 */
554 dn_key t = SET_TICKS(pkt, q, p); /* ticks i have to wait */
555 q->sched_time = curr_time ;
556 heap_insert(&ready_heap, curr_time + t, (void *)q );
557 /* XXX should check errors on heap_insert, and drain the whole
558 * queue on error hoping next time we are luckier.
560 } else { /* RED needs to know when the queue becomes empty */
561 q->q_time = curr_time;
565 * If the delay line was empty call transmit_event() now.
566 * Otherwise, the scheduler will take care of it.
569 transmit_event(p, head, tail);
573 * Called when we can transmit packets on WF2Q queues. Take pkts out of
574 * the queues at their start time, and enqueue into the delay line.
575 * Packets are drained until p->numbytes < 0. As long as
576 * len_scaled >= p->numbytes, the packet goes into the delay line
577 * with a deadline p->delay. For the last packet, if p->numbytes<0,
578 * there is an additional delay.
581 ready_event_wfq(struct dn_pipe *p, struct mbuf **head, struct mbuf **tail)
583 int p_was_empty = (p->head == NULL) ;
584 struct dn_heap *sch = &(p->scheduler_heap);
585 struct dn_heap *neh = &(p->not_eligible_heap) ;
587 DUMMYNET_LOCK_ASSERT();
589 if (p->if_name[0] == 0) /* tx clock is simulated */
590 p->numbytes += ( curr_time - p->sched_time ) * p->bandwidth;
591 else { /* tx clock is for real, the ifq must be empty or this is a NOP */
592 if (p->ifp && p->ifp->if_snd.ifq_head != NULL)
595 DPRINTF(("dummynet: pipe %d ready from %s --\n",
596 p->pipe_nr, p->if_name));
601 * While we have backlogged traffic AND credit, we need to do
602 * something on the queue.
604 while ( p->numbytes >=0 && (sch->elements>0 || neh->elements >0) ) {
605 if (sch->elements > 0) { /* have some eligible pkts to send out */
606 struct dn_flow_queue *q = sch->p[0].object ;
607 struct mbuf *pkt = q->head;
608 struct dn_flow_set *fs = q->fs;
609 u_int64_t len = pkt->m_pkthdr.len;
610 int len_scaled = p->bandwidth ? len*8*hz : 0 ;
612 heap_extract(sch, NULL); /* remove queue from heap */
613 p->numbytes -= len_scaled ;
614 move_pkt(pkt, q, p, len);
616 p->V += (len<<MY_M) / p->sum ; /* update V */
617 q->S = q->F ; /* update start time */
618 if (q->len == 0) { /* Flow not backlogged any more */
620 heap_insert(&(p->idle_heap), q->F, q);
621 } else { /* still backlogged */
623 * update F and position in backlogged queue, then
624 * put flow in not_eligible_heap (we will fix this later).
626 len = (q->head)->m_pkthdr.len;
627 q->F += (len<<MY_M)/(u_int64_t) fs->weight ;
628 if (DN_KEY_LEQ(q->S, p->V))
629 heap_insert(neh, q->S, q);
631 heap_insert(sch, q->F, q);
635 * now compute V = max(V, min(S_i)). Remember that all elements in sch
636 * have by definition S_i <= V so if sch is not empty, V is surely
637 * the max and we must not update it. Conversely, if sch is empty
638 * we only need to look at neh.
640 if (sch->elements == 0 && neh->elements > 0)
641 p->V = MAX64 ( p->V, neh->p[0].key );
642 /* move from neh to sch any packets that have become eligible */
643 while (neh->elements > 0 && DN_KEY_LEQ(neh->p[0].key, p->V) ) {
644 struct dn_flow_queue *q = neh->p[0].object ;
645 heap_extract(neh, NULL);
646 heap_insert(sch, q->F, q);
649 if (p->if_name[0] != '\0') {/* tx clock is from a real thing */
650 p->numbytes = -1 ; /* mark not ready for I/O */
654 if (sch->elements == 0 && neh->elements == 0 && p->numbytes >= 0
655 && p->idle_heap.elements > 0) {
657 * no traffic and no events scheduled. We can get rid of idle-heap.
661 for (i = 0 ; i < p->idle_heap.elements ; i++) {
662 struct dn_flow_queue *q = p->idle_heap.p[i].object ;
669 p->idle_heap.elements = 0 ;
672 * If we are getting clocks from dummynet (not a real interface) and
673 * If we are under credit, schedule the next ready event.
674 * Also fix the delivery time of the last packet.
676 if (p->if_name[0]==0 && p->numbytes < 0) { /* this implies bandwidth >0 */
677 dn_key t=0 ; /* number of ticks i have to wait */
679 if (p->bandwidth > 0)
680 t = ( p->bandwidth -1 - p->numbytes) / p->bandwidth ;
681 dn_tag_get(p->tail)->output_time += t ;
682 p->sched_time = curr_time ;
683 heap_insert(&wfq_ready_heap, curr_time + t, (void *)p);
684 /* XXX should check errors on heap_insert, and drain the whole
685 * queue on error hoping next time we are luckier.
689 * If the delay line was empty call transmit_event() now.
690 * Otherwise, the scheduler will take care of it.
693 transmit_event(p, head, tail);
697 * This is called once per tick, or HZ times per second. It is used to
698 * increment the current tick counter and schedule expired events.
701 dummynet(void * __unused unused)
703 struct mbuf *head = NULL, *tail = NULL;
704 struct dn_pipe *pipe;
705 struct dn_heap *heaps[3];
707 void *p; /* generic parameter to handler */
710 heaps[0] = &ready_heap ; /* fixed-rate queues */
711 heaps[1] = &wfq_ready_heap ; /* wfq queues */
712 heaps[2] = &extract_heap ; /* delay line */
716 for (i=0; i < 3 ; i++) {
718 while (h->elements > 0 && DN_KEY_LEQ(h->p[0].key, curr_time) ) {
719 if (h->p[0].key > curr_time)
720 printf("dummynet: warning, heap %d is %d ticks late\n",
721 i, (int)(curr_time - h->p[0].key));
722 p = h->p[0].object ; /* store a copy before heap_extract */
723 heap_extract(h, NULL); /* need to extract before processing */
725 ready_event(p, &head, &tail);
727 struct dn_pipe *pipe = p;
728 if (pipe->if_name[0] != '\0')
729 printf("dummynet: bad ready_event_wfq for pipe %s\n",
732 ready_event_wfq(p, &head, &tail);
734 transmit_event(p, &head, &tail);
737 /* Sweep pipes trying to expire idle flow_queues. */
738 for (i = 0; i < HASHSIZE; i++)
739 SLIST_FOREACH(pipe, &pipehash[i], next)
740 if (pipe->idle_heap.elements > 0 &&
741 DN_KEY_LT(pipe->idle_heap.p[0].key, pipe->V) ) {
742 struct dn_flow_queue *q = pipe->idle_heap.p[0].object;
744 heap_extract(&(pipe->idle_heap), NULL);
745 q->S = q->F + 1; /* Mark timestamp as invalid. */
746 pipe->sum -= q->fs->weight;
754 callout_reset(&dn_timeout, 1, dummynet, NULL);
758 dummynet_send(struct mbuf *m)
760 struct dn_pkt_tag *pkt;
764 for (; m != NULL; m = n) {
768 switch (pkt->dn_dir) {
770 ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
773 ip = mtod(m, struct ip *);
774 ip->ip_len = htons(ip->ip_len);
775 ip->ip_off = htons(ip->ip_off);
784 ip6_output(m, NULL, NULL, IPV6_FORWARDING, NULL, NULL, NULL);
788 if (bridge_dn_p != NULL)
789 ((*bridge_dn_p)(m, pkt->ifp));
791 printf("dummynet: if_bridge not loaded\n");
794 case DN_TO_ETH_DEMUX:
796 * The Ethernet code assumes the Ethernet header is
797 * contiguous in the first mbuf header.
798 * Insure this is true.
800 if (m->m_len < ETHER_HDR_LEN &&
801 (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
802 printf("dummynet/ether: pullup failed, "
803 "dropping packet\n");
806 ether_demux(m->m_pkthdr.rcvif, m);
809 ether_output_frame(pkt->ifp, m);
812 printf("dummynet: bad switch %d!\n", pkt->dn_dir);
820 * Unconditionally expire empty queues in case of shortage.
821 * Returns the number of queues freed.
824 expire_queues(struct dn_flow_set *fs)
826 struct dn_flow_queue *q, *prev ;
827 int i, initial_elements = fs->rq_elements ;
829 if (fs->last_expired == time_uptime)
831 fs->last_expired = time_uptime ;
832 for (i = 0 ; i <= fs->rq_size ; i++) /* last one is overflow */
833 for (prev=NULL, q = fs->rq[i] ; q != NULL ; )
834 if (q->head != NULL || q->S != q->F+1) {
837 } else { /* entry is idle, expire it */
838 struct dn_flow_queue *old_q = q ;
841 prev->next = q = q->next ;
843 fs->rq[i] = q = q->next ;
845 free(old_q, M_DUMMYNET);
847 return initial_elements - fs->rq_elements ;
851 * If room, create a new queue and put at head of slot i;
852 * otherwise, create or use the default queue.
854 static struct dn_flow_queue *
855 create_queue(struct dn_flow_set *fs, int i)
857 struct dn_flow_queue *q ;
859 if (fs->rq_elements > fs->rq_size * dn_max_ratio &&
860 expire_queues(fs) == 0) {
862 * No way to get room, use or create overflow queue.
865 if ( fs->rq[i] != NULL )
868 q = malloc(sizeof(*q), M_DUMMYNET, M_NOWAIT | M_ZERO);
870 printf("dummynet: sorry, cannot allocate queue for new flow\n");
875 q->next = fs->rq[i] ;
876 q->S = q->F + 1; /* hack - mark timestamp as invalid */
883 * Given a flow_set and a pkt in last_pkt, find a matching queue
884 * after appropriate masking. The queue is moved to front
885 * so that further searches take less time.
887 static struct dn_flow_queue *
888 find_queue(struct dn_flow_set *fs, struct ipfw_flow_id *id)
890 int i = 0 ; /* we need i and q for new allocations */
891 struct dn_flow_queue *q, *prev;
892 int is_v6 = IS_IP6_FLOW_ID(id);
894 if ( !(fs->flags_fs & DN_HAVE_FLOW_MASK) )
897 /* first, do the masking, then hash */
898 id->dst_port &= fs->flow_mask.dst_port ;
899 id->src_port &= fs->flow_mask.src_port ;
900 id->proto &= fs->flow_mask.proto ;
901 id->flags = 0 ; /* we don't care about this one */
903 APPLY_MASK(&id->dst_ip6, &fs->flow_mask.dst_ip6);
904 APPLY_MASK(&id->src_ip6, &fs->flow_mask.src_ip6);
905 id->flow_id6 &= fs->flow_mask.flow_id6;
907 i = ((id->dst_ip6.__u6_addr.__u6_addr32[0]) & 0xffff)^
908 ((id->dst_ip6.__u6_addr.__u6_addr32[1]) & 0xffff)^
909 ((id->dst_ip6.__u6_addr.__u6_addr32[2]) & 0xffff)^
910 ((id->dst_ip6.__u6_addr.__u6_addr32[3]) & 0xffff)^
912 ((id->dst_ip6.__u6_addr.__u6_addr32[0] >> 15) & 0xffff)^
913 ((id->dst_ip6.__u6_addr.__u6_addr32[1] >> 15) & 0xffff)^
914 ((id->dst_ip6.__u6_addr.__u6_addr32[2] >> 15) & 0xffff)^
915 ((id->dst_ip6.__u6_addr.__u6_addr32[3] >> 15) & 0xffff)^
917 ((id->src_ip6.__u6_addr.__u6_addr32[0] << 1) & 0xfffff)^
918 ((id->src_ip6.__u6_addr.__u6_addr32[1] << 1) & 0xfffff)^
919 ((id->src_ip6.__u6_addr.__u6_addr32[2] << 1) & 0xfffff)^
920 ((id->src_ip6.__u6_addr.__u6_addr32[3] << 1) & 0xfffff)^
922 ((id->src_ip6.__u6_addr.__u6_addr32[0] << 16) & 0xffff)^
923 ((id->src_ip6.__u6_addr.__u6_addr32[1] << 16) & 0xffff)^
924 ((id->src_ip6.__u6_addr.__u6_addr32[2] << 16) & 0xffff)^
925 ((id->src_ip6.__u6_addr.__u6_addr32[3] << 16) & 0xffff)^
927 (id->dst_port << 1) ^ (id->src_port) ^
931 id->dst_ip &= fs->flow_mask.dst_ip ;
932 id->src_ip &= fs->flow_mask.src_ip ;
934 i = ( (id->dst_ip) & 0xffff ) ^
935 ( (id->dst_ip >> 15) & 0xffff ) ^
936 ( (id->src_ip << 1) & 0xffff ) ^
937 ( (id->src_ip >> 16 ) & 0xffff ) ^
938 (id->dst_port << 1) ^ (id->src_port) ^
941 i = i % fs->rq_size ;
942 /* finally, scan the current list for a match */
944 for (prev=NULL, q = fs->rq[i] ; q ; ) {
947 IN6_ARE_ADDR_EQUAL(&id->dst_ip6,&q->id.dst_ip6) &&
948 IN6_ARE_ADDR_EQUAL(&id->src_ip6,&q->id.src_ip6) &&
949 id->dst_port == q->id.dst_port &&
950 id->src_port == q->id.src_port &&
951 id->proto == q->id.proto &&
952 id->flags == q->id.flags &&
953 id->flow_id6 == q->id.flow_id6)
956 if (!is_v6 && id->dst_ip == q->id.dst_ip &&
957 id->src_ip == q->id.src_ip &&
958 id->dst_port == q->id.dst_port &&
959 id->src_port == q->id.src_port &&
960 id->proto == q->id.proto &&
961 id->flags == q->id.flags)
964 /* No match. Check if we can expire the entry */
965 if (pipe_expire && q->head == NULL && q->S == q->F+1 ) {
966 /* entry is idle and not in any heap, expire it */
967 struct dn_flow_queue *old_q = q ;
970 prev->next = q = q->next ;
972 fs->rq[i] = q = q->next ;
974 free(old_q, M_DUMMYNET);
980 if (q && prev != NULL) { /* found and not in front */
981 prev->next = q->next ;
982 q->next = fs->rq[i] ;
986 if (q == NULL) { /* no match, need to allocate a new entry */
987 q = create_queue(fs, i);
995 red_drops(struct dn_flow_set *fs, struct dn_flow_queue *q, int len)
1000 * RED calculates the average queue size (avg) using a low-pass filter
1001 * with an exponential weighted (w_q) moving average:
1002 * avg <- (1-w_q) * avg + w_q * q_size
1003 * where q_size is the queue length (measured in bytes or * packets).
1005 * If q_size == 0, we compute the idle time for the link, and set
1006 * avg = (1 - w_q)^(idle/s)
1007 * where s is the time needed for transmitting a medium-sized packet.
1009 * Now, if avg < min_th the packet is enqueued.
1010 * If avg > max_th the packet is dropped. Otherwise, the packet is
1011 * dropped with probability P function of avg.
1016 /* queue in bytes or packets ? */
1017 u_int q_size = (fs->flags_fs & DN_QSIZE_IS_BYTES) ? q->len_bytes : q->len;
1019 DPRINTF(("\ndummynet: %d q: %2u ", (int) curr_time, q_size));
1021 /* average queue size estimation */
1024 * queue is not empty, avg <- avg + (q_size - avg) * w_q
1026 int diff = SCALE(q_size) - q->avg;
1027 int64_t v = SCALE_MUL((int64_t) diff, (int64_t) fs->w_q);
1032 * queue is empty, find for how long the queue has been
1033 * empty and use a lookup table for computing
1034 * (1 - * w_q)^(idle_time/s) where s is the time to send a
1036 * XXX check wraps...
1039 u_int t = (curr_time - q->q_time) / fs->lookup_step;
1041 q->avg = (t < fs->lookup_depth) ?
1042 SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
1045 DPRINTF(("dummynet: avg: %u ", SCALE_VAL(q->avg)));
1047 /* should i drop ? */
1049 if (q->avg < fs->min_th) {
1051 return 0; /* accept packet ; */
1053 if (q->avg >= fs->max_th) { /* average queue >= max threshold */
1054 if (fs->flags_fs & DN_IS_GENTLE_RED) {
1056 * According to Gentle-RED, if avg is greater than max_th the
1057 * packet is dropped with a probability
1058 * p_b = c_3 * avg - c_4
1059 * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
1061 p_b = SCALE_MUL((int64_t) fs->c_3, (int64_t) q->avg) - fs->c_4;
1064 DPRINTF(("dummynet: - drop"));
1067 } else if (q->avg > fs->min_th) {
1069 * we compute p_b using the linear dropping function p_b = c_1 *
1070 * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
1071 * max_p * min_th / (max_th - min_th)
1073 p_b = SCALE_MUL((int64_t) fs->c_1, (int64_t) q->avg) - fs->c_2;
1075 if (fs->flags_fs & DN_QSIZE_IS_BYTES)
1076 p_b = (p_b * len) / fs->max_pkt_size;
1077 if (++q->count == 0)
1078 q->random = random() & 0xffff;
1081 * q->count counts packets arrived since last drop, so a greater
1082 * value of q->count means a greater packet drop probability.
1084 if (SCALE_MUL(p_b, SCALE((int64_t) q->count)) > q->random) {
1086 DPRINTF(("dummynet: - red drop"));
1087 /* after a drop we calculate a new random value */
1088 q->random = random() & 0xffff;
1089 return 1; /* drop */
1092 /* end of RED algorithm */
1093 return 0 ; /* accept */
1096 static __inline struct dn_flow_set *
1097 locate_flowset(int fs_nr)
1099 struct dn_flow_set *fs;
1101 SLIST_FOREACH(fs, &flowsethash[HASH(fs_nr)], next)
1102 if (fs->fs_nr == fs_nr)
1108 static __inline struct dn_pipe *
1109 locate_pipe(int pipe_nr)
1111 struct dn_pipe *pipe;
1113 SLIST_FOREACH(pipe, &pipehash[HASH(pipe_nr)], next)
1114 if (pipe->pipe_nr == pipe_nr)
1121 * dummynet hook for packets. Below 'pipe' is a pipe or a queue
1122 * depending on whether WF2Q or fixed bw is used.
1124 * pipe_nr pipe or queue the packet is destined for.
1125 * dir where shall we send the packet after dummynet.
1126 * m the mbuf with the packet
1127 * ifp the 'ifp' parameter from the caller.
1128 * NULL in ip_input, destination interface in ip_output,
1129 * rule matching rule, in case of multiple passes
1133 dummynet_io(struct mbuf *m, int dir, struct ip_fw_args *fwa)
1135 struct mbuf *head = NULL, *tail = NULL;
1136 struct dn_pkt_tag *pkt;
1138 struct dn_flow_set *fs = NULL;
1139 struct dn_pipe *pipe ;
1140 u_int64_t len = m->m_pkthdr.len ;
1141 struct dn_flow_queue *q = NULL ;
1143 ipfw_insn *cmd = ACTION_PTR(fwa->rule);
1145 KASSERT(m->m_nextpkt == NULL,
1146 ("dummynet_io: mbuf queue passed to dummynet"));
1148 if (cmd->opcode == O_LOG)
1150 if (cmd->opcode == O_ALTQ)
1152 if (cmd->opcode == O_TAG)
1154 is_pipe = (cmd->opcode == O_PIPE);
1158 * This is a dummynet rule, so we expect an O_PIPE or O_QUEUE rule.
1160 * XXXGL: probably the pipe->fs and fs->pipe logic here
1161 * below can be simplified.
1164 pipe = locate_pipe(fwa->cookie);
1168 fs = locate_flowset(fwa->cookie);
1171 goto dropit; /* This queue/pipe does not exist! */
1173 if (pipe == NULL) { /* Must be a queue, try find a matching pipe. */
1174 pipe = locate_pipe(fs->parent_nr);
1178 printf("dummynet: no pipe %d for queue %d, drop pkt\n",
1179 fs->parent_nr, fs->fs_nr);
1183 q = find_queue(fs, &(fwa->f_id));
1185 goto dropit ; /* cannot allocate queue */
1187 * update statistics, then check reasons to drop pkt
1189 q->tot_bytes += len ;
1191 if ( fs->plr && random() < fs->plr )
1192 goto dropit ; /* random pkt drop */
1193 if ( fs->flags_fs & DN_QSIZE_IS_BYTES) {
1194 if (q->len_bytes > fs->qsize)
1195 goto dropit ; /* queue size overflow */
1197 if (q->len >= fs->qsize)
1198 goto dropit ; /* queue count overflow */
1200 if ( fs->flags_fs & DN_IS_RED && red_drops(fs, q, len) )
1203 /* XXX expensive to zero, see if we can remove it*/
1204 mtag = m_tag_get(PACKET_TAG_DUMMYNET,
1205 sizeof(struct dn_pkt_tag), M_NOWAIT|M_ZERO);
1207 goto dropit ; /* cannot allocate packet header */
1208 m_tag_prepend(m, mtag); /* attach to mbuf chain */
1210 pkt = (struct dn_pkt_tag *)(mtag+1);
1211 /* ok, i can handle the pkt now... */
1212 /* build and enqueue packet + parameters */
1213 pkt->rule = fwa->rule ;
1216 pkt->ifp = fwa->oif;
1218 if (q->head == NULL)
1221 q->tail->m_nextpkt = m;
1224 q->len_bytes += len ;
1226 if ( q->head != m ) /* flow was not idle, we are done */
1229 * If we reach this point the flow was previously idle, so we need
1230 * to schedule it. This involves different actions for fixed-rate or
1235 * Fixed-rate queue: just insert into the ready_heap.
1238 if (pipe->bandwidth)
1239 t = SET_TICKS(m, q, pipe);
1240 q->sched_time = curr_time ;
1241 if (t == 0) /* must process it now */
1242 ready_event(q, &head, &tail);
1244 heap_insert(&ready_heap, curr_time + t , q );
1247 * WF2Q. First, compute start time S: if the flow was idle (S=F+1)
1248 * set S to the virtual time V for the controlling pipe, and update
1249 * the sum of weights for the pipe; otherwise, remove flow from
1250 * idle_heap and set S to max(F,V).
1251 * Second, compute finish time F = S + len/weight.
1252 * Third, if pipe was idle, update V=max(S, V).
1253 * Fourth, count one more backlogged flow.
1255 if (DN_KEY_GT(q->S, q->F)) { /* means timestamps are invalid */
1257 pipe->sum += fs->weight ; /* add weight of new queue */
1259 heap_extract(&(pipe->idle_heap), q);
1260 q->S = MAX64(q->F, pipe->V ) ;
1262 q->F = q->S + ( len<<MY_M )/(u_int64_t) fs->weight;
1264 if (pipe->not_eligible_heap.elements == 0 &&
1265 pipe->scheduler_heap.elements == 0)
1266 pipe->V = MAX64 ( q->S, pipe->V );
1269 * Look at eligibility. A flow is not eligibile if S>V (when
1270 * this happens, it means that there is some other flow already
1271 * scheduled for the same pipe, so the scheduler_heap cannot be
1272 * empty). If the flow is not eligible we just store it in the
1273 * not_eligible_heap. Otherwise, we store in the scheduler_heap
1274 * and possibly invoke ready_event_wfq() right now if there is
1276 * Note that for all flows in scheduler_heap (SCH), S_i <= V,
1277 * and for all flows in not_eligible_heap (NEH), S_i > V .
1278 * So when we need to compute max( V, min(S_i) ) forall i in SCH+NEH,
1279 * we only need to look into NEH.
1281 if (DN_KEY_GT(q->S, pipe->V) ) { /* not eligible */
1282 if (pipe->scheduler_heap.elements == 0)
1283 printf("dummynet: ++ ouch! not eligible but empty scheduler!\n");
1284 heap_insert(&(pipe->not_eligible_heap), q->S, q);
1286 heap_insert(&(pipe->scheduler_heap), q->F, q);
1287 if (pipe->numbytes >= 0) { /* pipe is idle */
1288 if (pipe->scheduler_heap.elements != 1)
1289 printf("dummynet: OUCH! pipe should have been idle!\n");
1290 DPRINTF(("dummynet: waking up pipe %d at %d\n",
1291 pipe->pipe_nr, (int)(q->F >> MY_M)));
1292 pipe->sched_time = curr_time ;
1293 ready_event_wfq(pipe, &head, &tail);
1300 dummynet_send(head);
1308 return ( (fs && (fs->flags_fs & DN_NOERROR)) ? 0 : ENOBUFS);
1312 * Below, the rt_unref is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
1313 * Doing this would probably save us the initial bzero of dn_pkt
1315 #define DN_FREE_PKT(_m) do { \
1320 * Dispose all packets and flow_queues on a flow_set.
1321 * If all=1, also remove red lookup table and other storage,
1322 * including the descriptor itself.
1323 * For the one in dn_pipe MUST also cleanup ready_heap...
1326 purge_flow_set(struct dn_flow_set *fs, int all)
1328 struct dn_flow_queue *q, *qn ;
1331 DUMMYNET_LOCK_ASSERT();
1333 for (i = 0 ; i <= fs->rq_size ; i++ ) {
1334 for (q = fs->rq[i] ; q ; q = qn ) {
1335 struct mbuf *m, *mnext;
1338 while ((m = mnext) != NULL) {
1339 mnext = m->m_nextpkt;
1343 free(q, M_DUMMYNET);
1347 fs->rq_elements = 0 ;
1349 /* RED - free lookup table */
1351 free(fs->w_q_lookup, M_DUMMYNET);
1353 free(fs->rq, M_DUMMYNET);
1354 /* if this fs is not part of a pipe, free it */
1355 if (fs->pipe && fs != &(fs->pipe->fs) )
1356 free(fs, M_DUMMYNET);
1361 * Dispose all packets queued on a pipe (not a flow_set).
1362 * Also free all resources associated to a pipe, which is about
1366 purge_pipe(struct dn_pipe *pipe)
1368 struct mbuf *m, *mnext;
1370 purge_flow_set( &(pipe->fs), 1 );
1373 while ((m = mnext) != NULL) {
1374 mnext = m->m_nextpkt;
1378 heap_free( &(pipe->scheduler_heap) );
1379 heap_free( &(pipe->not_eligible_heap) );
1380 heap_free( &(pipe->idle_heap) );
1384 * Delete all pipes and heaps returning memory. Must also
1385 * remove references from all ipfw rules to all pipes.
1388 dummynet_flush(void)
1390 struct dn_pipe *pipe, *pipe1;
1391 struct dn_flow_set *fs, *fs1;
1395 /* Free heaps so we don't have unwanted events. */
1396 heap_free(&ready_heap);
1397 heap_free(&wfq_ready_heap);
1398 heap_free(&extract_heap);
1401 * Now purge all queued pkts and delete all pipes.
1403 * XXXGL: can we merge the for(;;) cycles into one or not?
1405 for (i = 0; i < HASHSIZE; i++)
1406 SLIST_FOREACH_SAFE(fs, &flowsethash[i], next, fs1) {
1407 SLIST_REMOVE(&flowsethash[i], fs, dn_flow_set, next);
1408 purge_flow_set(fs, 1);
1410 for (i = 0; i < HASHSIZE; i++)
1411 SLIST_FOREACH_SAFE(pipe, &pipehash[i], next, pipe1) {
1412 SLIST_REMOVE(&pipehash[i], pipe, dn_pipe, next);
1414 free(pipe, M_DUMMYNET);
1419 extern struct ip_fw *ip_fw_default_rule ;
1421 dn_rule_delete_fs(struct dn_flow_set *fs, void *r)
1424 struct dn_flow_queue *q ;
1427 for (i = 0 ; i <= fs->rq_size ; i++) /* last one is ovflow */
1428 for (q = fs->rq[i] ; q ; q = q->next )
1429 for (m = q->head ; m ; m = m->m_nextpkt ) {
1430 struct dn_pkt_tag *pkt = dn_tag_get(m) ;
1432 pkt->rule = ip_fw_default_rule ;
1436 * when a firewall rule is deleted, scan all queues and remove the flow-id
1437 * from packets matching this rule.
1440 dn_rule_delete(void *r)
1442 struct dn_pipe *pipe;
1443 struct dn_flow_set *fs;
1444 struct dn_pkt_tag *pkt;
1450 * If the rule references a queue (dn_flow_set), then scan
1451 * the flow set, otherwise scan pipes. Should do either, but doing
1452 * both does not harm.
1454 for (i = 0; i < HASHSIZE; i++)
1455 SLIST_FOREACH(fs, &flowsethash[i], next)
1456 dn_rule_delete_fs(fs, r);
1458 for (i = 0; i < HASHSIZE; i++)
1459 SLIST_FOREACH(pipe, &pipehash[i], next) {
1461 dn_rule_delete_fs(fs, r);
1462 for (m = pipe->head ; m ; m = m->m_nextpkt ) {
1463 pkt = dn_tag_get(m);
1465 pkt->rule = ip_fw_default_rule;
1472 * setup RED parameters
1475 config_red(struct dn_flow_set *p, struct dn_flow_set * x)
1480 x->min_th = SCALE(p->min_th);
1481 x->max_th = SCALE(p->max_th);
1482 x->max_p = p->max_p;
1484 x->c_1 = p->max_p / (p->max_th - p->min_th);
1485 x->c_2 = SCALE_MUL(x->c_1, SCALE(p->min_th));
1486 if (x->flags_fs & DN_IS_GENTLE_RED) {
1487 x->c_3 = (SCALE(1) - p->max_p) / p->max_th;
1488 x->c_4 = (SCALE(1) - 2 * p->max_p);
1491 /* if the lookup table already exist, free and create it again */
1492 if (x->w_q_lookup) {
1493 free(x->w_q_lookup, M_DUMMYNET);
1494 x->w_q_lookup = NULL ;
1496 if (red_lookup_depth == 0) {
1497 printf("\ndummynet: net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
1498 free(x, M_DUMMYNET);
1501 x->lookup_depth = red_lookup_depth;
1502 x->w_q_lookup = (u_int *) malloc(x->lookup_depth * sizeof(int),
1503 M_DUMMYNET, M_NOWAIT);
1504 if (x->w_q_lookup == NULL) {
1505 printf("dummynet: sorry, cannot allocate red lookup table\n");
1506 free(x, M_DUMMYNET);
1510 /* fill the lookup table with (1 - w_q)^x */
1511 x->lookup_step = p->lookup_step ;
1512 x->lookup_weight = p->lookup_weight ;
1513 x->w_q_lookup[0] = SCALE(1) - x->w_q;
1514 for (i = 1; i < x->lookup_depth; i++)
1515 x->w_q_lookup[i] = SCALE_MUL(x->w_q_lookup[i - 1], x->lookup_weight);
1516 if (red_avg_pkt_size < 1)
1517 red_avg_pkt_size = 512 ;
1518 x->avg_pkt_size = red_avg_pkt_size ;
1519 if (red_max_pkt_size < 1)
1520 red_max_pkt_size = 1500 ;
1521 x->max_pkt_size = red_max_pkt_size ;
1526 alloc_hash(struct dn_flow_set *x, struct dn_flow_set *pfs)
1528 if (x->flags_fs & DN_HAVE_FLOW_MASK) { /* allocate some slots */
1529 int l = pfs->rq_size;
1535 else if (l > DN_MAX_HASH_SIZE)
1536 l = DN_MAX_HASH_SIZE;
1538 } else /* one is enough for null mask */
1540 x->rq = malloc((1 + x->rq_size) * sizeof(struct dn_flow_queue *),
1541 M_DUMMYNET, M_NOWAIT | M_ZERO);
1542 if (x->rq == NULL) {
1543 printf("dummynet: sorry, cannot allocate queue\n");
1551 set_fs_parms(struct dn_flow_set *x, struct dn_flow_set *src)
1553 x->flags_fs = src->flags_fs;
1554 x->qsize = src->qsize;
1556 x->flow_mask = src->flow_mask;
1557 if (x->flags_fs & DN_QSIZE_IS_BYTES) {
1558 if (x->qsize > 1024*1024)
1559 x->qsize = 1024*1024 ;
1566 /* configuring RED */
1567 if ( x->flags_fs & DN_IS_RED )
1568 config_red(src, x) ; /* XXX should check errors */
1572 * setup pipe or queue parameters.
1576 config_pipe(struct dn_pipe *p)
1578 struct dn_flow_set *pfs = &(p->fs);
1579 struct dn_flow_queue *q;
1583 * The config program passes parameters as follows:
1584 * bw = bits/second (0 means no limits),
1585 * delay = ms, must be translated into ticks.
1586 * qsize = slots/bytes
1588 p->delay = ( p->delay * hz ) / 1000 ;
1589 /* We need either a pipe number or a flow_set number */
1590 if (p->pipe_nr == 0 && pfs->fs_nr == 0)
1592 if (p->pipe_nr != 0 && pfs->fs_nr != 0)
1594 if (p->pipe_nr != 0) { /* this is a pipe */
1595 struct dn_pipe *pipe;
1598 pipe = locate_pipe(p->pipe_nr); /* locate pipe */
1600 if (pipe == NULL) { /* new pipe */
1601 pipe = malloc(sizeof(struct dn_pipe), M_DUMMYNET,
1605 printf("dummynet: no memory for new pipe\n");
1608 pipe->pipe_nr = p->pipe_nr;
1609 pipe->fs.pipe = pipe ;
1610 /* idle_heap is the only one from which we extract from the middle.
1612 pipe->idle_heap.size = pipe->idle_heap.elements = 0 ;
1613 pipe->idle_heap.offset=OFFSET_OF(struct dn_flow_queue, heap_pos);
1615 /* Flush accumulated credit for all queues */
1616 for (i = 0; i <= pipe->fs.rq_size; i++)
1617 for (q = pipe->fs.rq[i]; q; q = q->next)
1620 pipe->bandwidth = p->bandwidth ;
1621 pipe->numbytes = 0; /* just in case... */
1622 bcopy(p->if_name, pipe->if_name, sizeof(p->if_name) );
1623 pipe->ifp = NULL ; /* reset interface ptr */
1624 pipe->delay = p->delay ;
1625 set_fs_parms(&(pipe->fs), pfs);
1628 if (pipe->fs.rq == NULL) { /* a new pipe */
1629 error = alloc_hash(&(pipe->fs), pfs);
1632 free(pipe, M_DUMMYNET);
1635 SLIST_INSERT_HEAD(&pipehash[HASH(pipe->pipe_nr)], pipe, next);
1638 } else { /* config queue */
1639 struct dn_flow_set *fs;
1642 fs = locate_flowset(pfs->fs_nr); /* locate flow_set */
1644 if (fs == NULL) { /* new */
1645 if (pfs->parent_nr == 0) { /* need link to a pipe */
1649 fs = malloc(sizeof(struct dn_flow_set), M_DUMMYNET,
1653 printf("dummynet: no memory for new flow_set\n");
1656 fs->fs_nr = pfs->fs_nr;
1657 fs->parent_nr = pfs->parent_nr;
1658 fs->weight = pfs->weight;
1659 if (fs->weight == 0)
1661 else if (fs->weight > 100)
1664 /* Change parent pipe not allowed; must delete and recreate */
1665 if (pfs->parent_nr != 0 && fs->parent_nr != pfs->parent_nr) {
1670 set_fs_parms(fs, pfs);
1672 if (fs->rq == NULL) { /* a new flow_set */
1673 error = alloc_hash(fs, pfs);
1676 free(fs, M_DUMMYNET);
1679 SLIST_INSERT_HEAD(&flowsethash[HASH(fs->fs_nr)], fs, next);
1687 * Helper function to remove from a heap queues which are linked to
1688 * a flow_set about to be deleted.
1691 fs_remove_from_heap(struct dn_heap *h, struct dn_flow_set *fs)
1693 int i = 0, found = 0 ;
1694 for (; i < h->elements ;)
1695 if ( ((struct dn_flow_queue *)h->p[i].object)->fs == fs) {
1697 h->p[i] = h->p[h->elements] ;
1706 * helper function to remove a pipe from a heap (can be there at most once)
1709 pipe_remove_from_heap(struct dn_heap *h, struct dn_pipe *p)
1711 if (h->elements > 0) {
1713 for (i=0; i < h->elements ; i++ ) {
1714 if (h->p[i].object == p) { /* found it */
1716 h->p[i] = h->p[h->elements] ;
1725 * drain all queues. Called in case of severe mbuf shortage.
1730 struct dn_flow_set *fs;
1731 struct dn_pipe *pipe;
1732 struct mbuf *m, *mnext;
1735 DUMMYNET_LOCK_ASSERT();
1737 heap_free(&ready_heap);
1738 heap_free(&wfq_ready_heap);
1739 heap_free(&extract_heap);
1740 /* remove all references to this pipe from flow_sets */
1741 for (i = 0; i < HASHSIZE; i++)
1742 SLIST_FOREACH(fs, &flowsethash[i], next)
1743 purge_flow_set(fs, 0);
1745 for (i = 0; i < HASHSIZE; i++) {
1746 SLIST_FOREACH(pipe, &pipehash[i], next) {
1747 purge_flow_set(&(pipe->fs), 0);
1750 while ((m = mnext) != NULL) {
1751 mnext = m->m_nextpkt;
1754 pipe->head = pipe->tail = NULL;
1760 * Fully delete a pipe or a queue, cleaning up associated info.
1763 delete_pipe(struct dn_pipe *p)
1765 if (p->pipe_nr == 0 && p->fs.fs_nr == 0)
1767 if (p->pipe_nr != 0 && p->fs.fs_nr != 0)
1769 if (p->pipe_nr != 0) { /* this is an old-style pipe */
1770 struct dn_pipe *pipe;
1771 struct dn_flow_set *fs;
1775 pipe = locate_pipe(p->pipe_nr); /* locate pipe */
1779 return (ENOENT); /* not found */
1782 /* Unlink from list of pipes. */
1783 SLIST_REMOVE(&pipehash[HASH(pipe->pipe_nr)], pipe, dn_pipe, next);
1785 /* Remove all references to this pipe from flow_sets. */
1786 for (i = 0; i < HASHSIZE; i++)
1787 SLIST_FOREACH(fs, &flowsethash[i], next)
1788 if (fs->pipe == pipe) {
1789 printf("dummynet: ++ ref to pipe %d from fs %d\n",
1790 p->pipe_nr, fs->fs_nr);
1792 purge_flow_set(fs, 0);
1794 fs_remove_from_heap(&ready_heap, &(pipe->fs));
1795 purge_pipe(pipe); /* remove all data associated to this pipe */
1796 /* remove reference to here from extract_heap and wfq_ready_heap */
1797 pipe_remove_from_heap(&extract_heap, pipe);
1798 pipe_remove_from_heap(&wfq_ready_heap, pipe);
1801 free(pipe, M_DUMMYNET);
1802 } else { /* this is a WF2Q queue (dn_flow_set) */
1803 struct dn_flow_set *fs;
1806 fs = locate_flowset(p->fs.fs_nr); /* locate set */
1810 return (ENOENT); /* not found */
1813 /* Unlink from list of flowsets. */
1814 SLIST_REMOVE( &flowsethash[HASH(fs->fs_nr)], fs, dn_flow_set, next);
1816 if (fs->pipe != NULL) {
1817 /* Update total weight on parent pipe and cleanup parent heaps. */
1818 fs->pipe->sum -= fs->weight * fs->backlogged ;
1819 fs_remove_from_heap(&(fs->pipe->not_eligible_heap), fs);
1820 fs_remove_from_heap(&(fs->pipe->scheduler_heap), fs);
1821 #if 1 /* XXX should i remove from idle_heap as well ? */
1822 fs_remove_from_heap(&(fs->pipe->idle_heap), fs);
1825 purge_flow_set(fs, 1);
1832 * helper function used to copy data from kernel in DUMMYNET_GET
1835 dn_copy_set(struct dn_flow_set *set, char *bp)
1838 struct dn_flow_queue *q, *qp = (struct dn_flow_queue *)bp;
1840 DUMMYNET_LOCK_ASSERT();
1842 for (i = 0 ; i <= set->rq_size ; i++)
1843 for (q = set->rq[i] ; q ; q = q->next, qp++ ) {
1844 if (q->hash_slot != i)
1845 printf("dummynet: ++ at %d: wrong slot (have %d, "
1846 "should be %d)\n", copied, q->hash_slot, i);
1848 printf("dummynet: ++ at %d: wrong fs ptr (have %p, should be %p)\n",
1851 bcopy(q, qp, sizeof( *q ) );
1852 /* cleanup pointers */
1854 qp->head = qp->tail = NULL ;
1857 if (copied != set->rq_elements)
1858 printf("dummynet: ++ wrong count, have %d should be %d\n",
1859 copied, set->rq_elements);
1866 struct dn_flow_set *fs;
1867 struct dn_pipe *pipe;
1871 DUMMYNET_LOCK_ASSERT();
1873 * Compute size of data structures: list of pipes and flow_sets.
1875 for (i = 0; i < HASHSIZE; i++) {
1876 SLIST_FOREACH(pipe, &pipehash[i], next)
1877 size += sizeof(*pipe) +
1878 pipe->fs.rq_elements * sizeof(struct dn_flow_queue);
1879 SLIST_FOREACH(fs, &flowsethash[i], next)
1880 size += sizeof (*fs) +
1881 fs->rq_elements * sizeof(struct dn_flow_queue);
1887 dummynet_get(struct sockopt *sopt)
1889 char *buf, *bp ; /* bp is the "copy-pointer" */
1891 struct dn_flow_set *fs;
1892 struct dn_pipe *pipe;
1895 /* XXX lock held too long */
1898 * XXX: Ugly, but we need to allocate memory with M_WAITOK flag and we
1899 * cannot use this flag while holding a mutex.
1901 for (i = 0; i < 10; i++) {
1902 size = dn_calc_size();
1904 buf = malloc(size, M_TEMP, M_WAITOK);
1906 if (size == dn_calc_size())
1916 for (i = 0; i < HASHSIZE; i++)
1917 SLIST_FOREACH(pipe, &pipehash[i], next) {
1918 struct dn_pipe *pipe_bp = (struct dn_pipe *)bp;
1921 * Copy pipe descriptor into *bp, convert delay back to ms,
1922 * then copy the flow_set descriptor(s) one at a time.
1923 * After each flow_set, copy the queue descriptor it owns.
1925 bcopy(pipe, bp, sizeof(*pipe));
1926 pipe_bp->delay = (pipe_bp->delay * 1000) / hz;
1928 * XXX the following is a hack based on ->next being the
1929 * first field in dn_pipe and dn_flow_set. The correct
1930 * solution would be to move the dn_flow_set to the beginning
1931 * of struct dn_pipe.
1933 pipe_bp->next.sle_next = (struct dn_pipe *)DN_IS_PIPE;
1934 /* Clean pointers. */
1935 pipe_bp->head = pipe_bp->tail = NULL;
1936 pipe_bp->fs.next.sle_next = NULL;
1937 pipe_bp->fs.pipe = NULL;
1938 pipe_bp->fs.rq = NULL;
1940 bp += sizeof(*pipe) ;
1941 bp = dn_copy_set(&(pipe->fs), bp);
1944 for (i = 0; i < HASHSIZE; i++)
1945 SLIST_FOREACH(fs, &flowsethash[i], next) {
1946 struct dn_flow_set *fs_bp = (struct dn_flow_set *)bp;
1948 bcopy(fs, bp, sizeof(*fs));
1949 /* XXX same hack as above */
1950 fs_bp->next.sle_next = (struct dn_flow_set *)DN_IS_QUEUE;
1954 bp = dn_copy_set(fs, bp);
1959 error = sooptcopyout(sopt, buf, size);
1965 * Handler for the various dummynet socket options (get, flush, config, del)
1968 ip_dn_ctl(struct sockopt *sopt)
1971 struct dn_pipe *p, tmp_pipe;
1973 /* Disallow sets in really-really secure mode. */
1974 if (sopt->sopt_dir == SOPT_SET) {
1975 #if __FreeBSD_version >= 500034
1976 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
1980 if (securelevel >= 3)
1985 switch (sopt->sopt_name) {
1987 printf("dummynet: -- unknown option %d", sopt->sopt_name);
1990 case IP_DUMMYNET_GET :
1991 error = dummynet_get(sopt);
1994 case IP_DUMMYNET_FLUSH :
1998 case IP_DUMMYNET_CONFIGURE :
2000 error = sooptcopyin(sopt, p, sizeof *p, sizeof *p);
2003 error = config_pipe(p);
2006 case IP_DUMMYNET_DEL : /* remove a pipe or queue */
2008 error = sooptcopyin(sopt, p, sizeof *p, sizeof *p);
2012 error = delete_pipe(p);
2024 printf("DUMMYNET with IPv6 initialized (040826)\n");
2026 DUMMYNET_LOCK_INIT();
2028 for (i = 0; i < HASHSIZE; i++) {
2029 SLIST_INIT(&pipehash[i]);
2030 SLIST_INIT(&flowsethash[i]);
2032 ready_heap.size = ready_heap.elements = 0 ;
2033 ready_heap.offset = 0 ;
2035 wfq_ready_heap.size = wfq_ready_heap.elements = 0 ;
2036 wfq_ready_heap.offset = 0 ;
2038 extract_heap.size = extract_heap.elements = 0 ;
2039 extract_heap.offset = 0 ;
2041 ip_dn_ctl_ptr = ip_dn_ctl;
2042 ip_dn_io_ptr = dummynet_io;
2043 ip_dn_ruledel_ptr = dn_rule_delete;
2045 callout_init(&dn_timeout, NET_CALLOUT_MPSAFE);
2046 callout_reset(&dn_timeout, 1, dummynet, NULL);
2053 ip_dn_ctl_ptr = NULL;
2054 ip_dn_io_ptr = NULL;
2055 ip_dn_ruledel_ptr = NULL;
2057 callout_stop(&dn_timeout);
2060 DUMMYNET_LOCK_DESTROY();
2062 #endif /* KLD_MODULE */
2065 dummynet_modevent(module_t mod, int type, void *data)
2069 if (DUMMYNET_LOADED) {
2070 printf("DUMMYNET already loaded\n");
2077 #if !defined(KLD_MODULE)
2078 printf("dummynet statically compiled, cannot unload\n");
2091 static moduledata_t dummynet_mod = {
2096 DECLARE_MODULE(dummynet, dummynet_mod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
2097 MODULE_DEPEND(dummynet, ipfw, 2, 2, 2);
2098 MODULE_VERSION(dummynet, 1);