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
27 * $FreeBSD: src/sys/netinet/ip_dummynet.c,v 1.24.2.22 2003/05/13 09:31:06 maxim Exp $
28 * $DragonFly: src/sys/net/dummynet/ip_dummynet.c,v 1.46 2007/11/06 14:42:52 sephe Exp $
32 #include "opt_ipfw.h" /* for IPFW2 definition */
36 #define DPRINTF(fmt, ...) kprintf(fmt, __VA_ARGS__)
38 #define DPRINTF(fmt, ...) ((void)0)
42 * This module implements IP dummynet, a bandwidth limiter/delay emulator
43 * used in conjunction with the ipfw package.
44 * Description of the data structures used is in ip_dummynet.h
45 * Here you mainly find the following blocks of code:
46 * + variable declarations;
47 * + heap management functions;
48 * + scheduler and dummynet functions;
49 * + configuration and initialization.
51 * Most important Changes:
54 * 010124: Fixed WF2Q behaviour
55 * 010122: Fixed spl protection.
56 * 000601: WF2Q support
57 * 000106: Large rewrite, use heaps to handle very many pipes.
58 * 980513: Initial release
61 #include <sys/param.h>
62 #include <sys/kernel.h>
63 #include <sys/malloc.h>
65 #include <sys/socketvar.h>
66 #include <sys/sysctl.h>
67 #include <sys/systimer.h>
68 #include <sys/thread2.h>
70 #include <net/ethernet.h>
71 #include <net/route.h>
72 #include <net/netmsg2.h>
74 #include <netinet/in.h>
75 #include <netinet/in_var.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_var.h>
79 #include <net/ipfw/ip_fw.h>
80 #include <net/dummynet/ip_dummynet.h>
82 #ifndef DN_CALLOUT_FREQ_MAX
83 #define DN_CALLOUT_FREQ_MAX 10000
87 * The maximum/minimum hash table size for queues.
88 * These values must be a power of 2.
90 #define DN_MIN_HASH_SIZE 4
91 #define DN_MAX_HASH_SIZE 65536
94 * Some macros are used to compare key values and handle wraparounds.
95 * MAX64 returns the largest of two key values.
97 #define DN_KEY_LT(a, b) ((int64_t)((a) - (b)) < 0)
98 #define DN_KEY_LEQ(a, b) ((int64_t)((a) - (b)) <= 0)
99 #define DN_KEY_GT(a, b) ((int64_t)((a) - (b)) > 0)
100 #define DN_KEY_GEQ(a, b) ((int64_t)((a) - (b)) >= 0)
101 #define MAX64(x, y) ((((int64_t)((y) - (x))) > 0) ? (y) : (x))
103 #define DN_NR_HASH_MAX 16
104 #define DN_NR_HASH_MASK (DN_NR_HASH_MAX - 1)
105 #define DN_NR_HASH(nr) \
106 ((((nr) >> 12) ^ ((nr) >> 8) ^ ((nr) >> 4) ^ (nr)) & DN_NR_HASH_MASK)
108 MALLOC_DEFINE(M_DUMMYNET, "dummynet", "dummynet heap");
110 static dn_key curr_time = 0; /* current simulation time */
111 static int dn_hash_size = 64; /* default hash size */
112 static int pipe_expire = 1; /* expire queue if empty */
113 static int dn_max_ratio = 16; /* max queues/buckets ratio */
116 * Statistics on number of queue searches and search steps
119 static int search_steps;
124 static int red_lookup_depth = 256; /* default lookup table depth */
125 static int red_avg_pkt_size = 512; /* default medium packet size */
126 static int red_max_pkt_size = 1500;/* default max packet size */
129 * Three heaps contain queues and pipes that the scheduler handles:
131 * + ready_heap contains all dn_flow_queue related to fixed-rate pipes.
132 * + wfq_ready_heap contains the pipes associated with WF2Q flows
133 * + extract_heap contains pipes associated with delay lines.
135 static struct dn_heap ready_heap;
136 static struct dn_heap extract_heap;
137 static struct dn_heap wfq_ready_heap;
139 static struct dn_pipe_head pipe_table[DN_NR_HASH_MAX];
140 static struct dn_flowset_head flowset_table[DN_NR_HASH_MAX];
143 * Variables for dummynet systimer
145 static struct netmsg dn_netmsg;
146 static struct systimer dn_clock;
147 static int dn_hz = 1000;
148 static int dn_cpu = 0; /* TODO tunable */
150 static int sysctl_dn_hz(SYSCTL_HANDLER_ARGS);
152 SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet, CTLFLAG_RW, 0, "Dummynet");
154 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, hash_size, CTLFLAG_RW,
155 &dn_hash_size, 0, "Default hash table size");
156 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, curr_time, CTLFLAG_RD,
157 &curr_time, 0, "Current tick");
158 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, expire, CTLFLAG_RW,
159 &pipe_expire, 0, "Expire queue if empty");
160 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, max_chain_len, CTLFLAG_RW,
161 &dn_max_ratio, 0, "Max ratio between dynamic queues and buckets");
163 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, ready_heap, CTLFLAG_RD,
164 &ready_heap.size, 0, "Size of ready heap");
165 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, extract_heap, CTLFLAG_RD,
166 &extract_heap.size, 0, "Size of extract heap");
168 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, searches, CTLFLAG_RD,
169 &searches, 0, "Number of queue searches");
170 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, search_steps, CTLFLAG_RD,
171 &search_steps, 0, "Number of queue search steps");
173 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth, CTLFLAG_RD,
174 &red_lookup_depth, 0, "Depth of RED lookup table");
175 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size, CTLFLAG_RD,
176 &red_avg_pkt_size, 0, "RED Medium packet size");
177 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size, CTLFLAG_RD,
178 &red_max_pkt_size, 0, "RED Max packet size");
180 SYSCTL_PROC(_net_inet_ip_dummynet, OID_AUTO, hz, CTLTYPE_INT | CTLFLAG_RW,
181 0, 0, sysctl_dn_hz, "I", "Dummynet callout frequency");
183 static int heap_init(struct dn_heap *, int);
184 static int heap_insert(struct dn_heap *, dn_key, void *);
185 static void heap_extract(struct dn_heap *, void *);
187 static void transmit_event(struct dn_pipe *);
188 static void ready_event(struct dn_flow_queue *);
189 static void ready_event_wfq(struct dn_pipe *);
191 static int config_pipe(struct dn_ioc_pipe *);
192 static void dummynet_flush(void);
193 static void rt_unref(struct rtentry *);
195 static void dummynet_clock(systimer_t, struct intrframe *);
196 static void dummynet(struct netmsg *);
198 static struct dn_pipe *dn_find_pipe(int);
199 static struct dn_flow_set *dn_locate_flowset(int, int);
201 typedef void (*dn_pipe_iter_t)(struct dn_pipe *, void *);
202 static void dn_iterate_pipe(dn_pipe_iter_t, void *);
204 typedef void (*dn_flowset_iter_t)(struct dn_flow_set *, void *);
205 static void dn_iterate_flowset(dn_flowset_iter_t, void *);
207 static ip_dn_io_t dummynet_io;
208 static ip_dn_ruledel_t dummynet_ruledel;
209 static ip_dn_ctl_t dummynet_ctl;
212 rt_unref(struct rtentry *rt)
216 if (rt->rt_refcnt <= 0)
217 kprintf("-- warning, refcnt now %ld, decreasing\n", rt->rt_refcnt);
222 * Heap management functions.
224 * In the heap, first node is element 0. Children of i are 2i+1 and 2i+2.
225 * Some macros help finding parent/children so we can optimize them.
227 * heap_init() is called to expand the heap when needed.
228 * Increment size in blocks of 16 entries.
229 * XXX failure to allocate a new element is a pretty bad failure
230 * as we basically stall a whole queue forever!!
231 * Returns 1 on error, 0 on success
233 #define HEAP_FATHER(x) (((x) - 1) / 2)
234 #define HEAP_LEFT(x) (2*(x) + 1)
235 #define HEAP_IS_LEFT(x) ((x) & 1)
236 #define HEAP_RIGHT(x) (2*(x) + 2)
237 #define HEAP_SWAP(a, b, buffer) { buffer = a; a = b; b = buffer; }
238 #define HEAP_INCREMENT 15
241 heap_init(struct dn_heap *h, int new_size)
243 struct dn_heap_entry *p;
245 if (h->size >= new_size) {
246 kprintf("%s, Bogus call, have %d want %d\n", __func__,
251 new_size = (new_size + HEAP_INCREMENT) & ~HEAP_INCREMENT;
252 p = kmalloc(new_size * sizeof(*p), M_DUMMYNET, M_WAITOK | M_ZERO);
254 bcopy(h->p, p, h->size * sizeof(*p));
255 kfree(h->p, M_DUMMYNET);
263 * Insert element in heap. Normally, p != NULL, we insert p in
264 * a new position and bubble up. If p == NULL, then the element is
265 * already in place, and key is the position where to start the
267 * Returns 1 on failure (cannot allocate new heap entry)
269 * If offset > 0 the position (index, int) of the element in the heap is
270 * also stored in the element itself at the given offset in bytes.
272 #define SET_OFFSET(heap, node) \
273 if (heap->offset > 0) \
274 *((int *)((char *)(heap->p[node].object) + heap->offset)) = node;
277 * RESET_OFFSET is used for sanity checks. It sets offset to an invalid value.
279 #define RESET_OFFSET(heap, node) \
280 if (heap->offset > 0) \
281 *((int *)((char *)(heap->p[node].object) + heap->offset)) = -1;
284 heap_insert(struct dn_heap *h, dn_key key1, void *p)
286 int son = h->elements;
288 if (p == NULL) { /* Data already there, set starting point */
290 } else { /* Insert new element at the end, possibly resize */
292 if (son == h->size) { /* Need resize... */
293 if (heap_init(h, h->elements + 1))
294 return 1; /* Failure... */
296 h->p[son].object = p;
297 h->p[son].key = key1;
301 while (son > 0) { /* Bubble up */
302 int father = HEAP_FATHER(son);
303 struct dn_heap_entry tmp;
305 if (DN_KEY_LT(h->p[father].key, h->p[son].key))
306 break; /* Found right position */
308 /* 'son' smaller than 'father', swap and repeat */
309 HEAP_SWAP(h->p[son], h->p[father], tmp);
318 * Remove top element from heap, or obj if obj != NULL
321 heap_extract(struct dn_heap *h, void *obj)
323 int child, father, max = h->elements - 1;
326 kprintf("warning, extract from empty heap 0x%p\n", h);
330 father = 0; /* Default: move up smallest child */
331 if (obj != NULL) { /* Extract specific element, index is at offset */
333 panic("%s from middle not supported on this heap!!!\n", __func__);
335 father = *((int *)((char *)obj + h->offset));
336 if (father < 0 || father >= h->elements) {
337 panic("%s father %d out of bound 0..%d\n", __func__,
338 father, h->elements);
341 RESET_OFFSET(h, father);
343 child = HEAP_LEFT(father); /* Left child */
344 while (child <= max) { /* Valid entry */
345 if (child != max && DN_KEY_LT(h->p[child + 1].key, h->p[child].key))
346 child = child + 1; /* Take right child, otherwise left */
347 h->p[father] = h->p[child];
348 SET_OFFSET(h, father);
350 child = HEAP_LEFT(child); /* Left child for next loop */
355 * Fill hole with last entry and bubble up, reusing the insert code
357 h->p[father] = h->p[max];
358 heap_insert(h, father, NULL); /* This one cannot fail */
363 * heapify() will reorganize data inside an array to maintain the
364 * heap property. It is needed when we delete a bunch of entries.
367 heapify(struct dn_heap *h)
371 for (i = 0; i < h->elements; i++)
372 heap_insert(h, i , NULL);
376 * Cleanup the heap and free data structure
379 heap_free(struct dn_heap *h)
382 kfree(h->p, M_DUMMYNET);
383 bzero(h, sizeof(*h));
387 * --- End of heap management functions ---
391 * Scheduler functions:
393 * transmit_event() is called when the delay-line needs to enter
394 * the scheduler, either because of existing pkts getting ready,
395 * or new packets entering the queue. The event handled is the delivery
396 * time of the packet.
398 * ready_event() does something similar with fixed-rate queues, and the
399 * event handled is the finish time of the head pkt.
401 * ready_event_wfq() does something similar with WF2Q queues, and the
402 * event handled is the start time of the head pkt.
404 * In all cases, we make sure that the data structures are consistent
405 * before passing pkts out, because this might trigger recursive
406 * invocations of the procedures.
409 transmit_event(struct dn_pipe *pipe)
413 while ((pkt = TAILQ_FIRST(&pipe->p_queue)) &&
414 DN_KEY_LEQ(pkt->output_time, curr_time)) {
418 * First unlink, then call procedures, since ip_input() can invoke
419 * ip_output() and viceversa, thus causing nested calls
421 TAILQ_REMOVE(&pipe->p_queue, pkt, dn_next);
425 * 'pkt' should _not_ be touched after calling
426 * ip_output(), ip_input(), ether_demux() and ether_output_frame()
428 switch (pkt->dn_dir) {
431 * 'pkt' will be freed in ip_output, so we keep
432 * a reference of the 'rtentry' beforehand.
435 ip_output(pkt->dn_m, NULL, NULL, 0, NULL, NULL);
443 case DN_TO_ETH_DEMUX:
445 struct mbuf *m = pkt->dn_m;
446 struct ether_header *eh;
448 if (m->m_len < ETHER_HDR_LEN &&
449 (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
450 kprintf("dummynet: pullup fail, dropping pkt\n");
454 * Same as ether_input, make eh be a pointer into the mbuf
456 eh = mtod(m, struct ether_header *);
457 m_adj(m, ETHER_HDR_LEN);
458 ether_demux(NULL, eh, m);
463 ether_output_frame(pkt->ifp, pkt->dn_m);
467 kprintf("dummynet: bad switch %d!\n", pkt->dn_dir);
474 * If there are leftover packets, put into the heap for next event
476 if ((pkt = TAILQ_FIRST(&pipe->p_queue)) != NULL) {
478 * XXX should check errors on heap_insert, by draining the
479 * whole pipe and hoping in the future we are more successful
481 heap_insert(&extract_heap, pkt->output_time, pipe);
486 * The following macro computes how many ticks we have to wait
487 * before being able to transmit a packet. The credit is taken from
488 * either a pipe (WF2Q) or a flow_queue (per-flow queueing)
490 #define SET_TICKS(pkt, q, p) \
491 (pkt->dn_m->m_pkthdr.len*8*dn_hz - (q)->numbytes + p->bandwidth - 1 ) / \
495 * Extract pkt from queue, compute output time (could be now)
496 * and put into delay line (p_queue)
499 move_pkt(struct dn_pkt *pkt, struct dn_flow_queue *q,
500 struct dn_pipe *p, int len)
502 TAILQ_REMOVE(&q->queue, pkt, dn_next);
506 pkt->output_time = curr_time + p->delay;
508 TAILQ_INSERT_TAIL(&p->p_queue, pkt, dn_next);
512 * ready_event() is invoked every time the queue must enter the
513 * scheduler, either because the first packet arrives, or because
514 * a previously scheduled event fired.
515 * On invokation, drain as many pkts as possible (could be 0) and then
516 * if there are leftover packets reinsert the pkt in the scheduler.
519 ready_event(struct dn_flow_queue *q)
522 struct dn_pipe *p = q->fs->pipe;
526 kprintf("ready_event- pipe is gone\n");
529 p_was_empty = TAILQ_EMPTY(&p->p_queue);
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 = TAILQ_FIRST(&q->queue)) != NULL) {
541 int len = pkt->dn_m->m_pkthdr.len;
542 int len_scaled = p->bandwidth ? len*8*dn_hz : 0;
544 if (len_scaled > q->numbytes)
546 q->numbytes -= len_scaled;
547 move_pkt(pkt, q, p, len);
551 * If we have more packets queued, schedule next ready event
552 * (can only occur when bandwidth != 0, otherwise we would have
553 * flushed the whole queue in the previous loop).
554 * To this purpose we record the current time and compute how many
555 * ticks to go for the finish time of the packet.
557 if ((pkt = TAILQ_FIRST(&q->queue)) != NULL) {
558 /* This implies bandwidth != 0 */
559 dn_key t = SET_TICKS(pkt, q, p); /* ticks i have to wait */
561 q->sched_time = curr_time;
564 * XXX should check errors on heap_insert, and drain the whole
565 * queue on error hoping next time we are luckier.
567 heap_insert(&ready_heap, curr_time + t, q);
568 } else { /* RED needs to know when the queue becomes empty */
569 q->q_time = curr_time;
574 * If the delay line was empty call transmit_event(p) now.
575 * Otherwise, the scheduler will take care of it.
582 * Called when we can transmit packets on WF2Q queues. Take pkts out of
583 * the queues at their start time, and enqueue into the delay line.
584 * Packets are drained until p->numbytes < 0. As long as
585 * len_scaled >= p->numbytes, the packet goes into the delay line
586 * with a deadline p->delay. For the last packet, if p->numbytes < 0,
587 * there is an additional delay.
590 ready_event_wfq(struct dn_pipe *p)
592 int p_was_empty = TAILQ_EMPTY(&p->p_queue);
593 struct dn_heap *sch = &p->scheduler_heap;
594 struct dn_heap *neh = &p->not_eligible_heap;
596 p->numbytes += (curr_time - p->sched_time) * p->bandwidth;
599 * While we have backlogged traffic AND credit, we need to do
600 * something on the queue.
602 while (p->numbytes >= 0 && (sch->elements > 0 || neh->elements > 0)) {
603 if (sch->elements > 0) { /* Have some eligible pkts to send out */
604 struct dn_flow_queue *q = sch->p[0].object;
605 struct dn_pkt *pkt = TAILQ_FIRST(&q->queue);
606 struct dn_flow_set *fs = q->fs;
607 uint64_t len = pkt->dn_m->m_pkthdr.len;
608 int len_scaled = p->bandwidth ? len*8*dn_hz : 0;
610 heap_extract(sch, NULL); /* Remove queue from heap */
611 p->numbytes -= len_scaled;
612 move_pkt(pkt, q, p, len);
614 p->V += (len << MY_M) / p->sum; /* Update V */
615 q->S = q->F; /* Update start time */
617 if (q->len == 0) { /* Flow not backlogged any more */
619 heap_insert(&p->idle_heap, q->F, q);
620 } else { /* Still backlogged */
622 * Update F and position in backlogged queue, then
623 * put flow in not_eligible_heap (we will fix this later).
625 len = TAILQ_FIRST(&q->queue)->dn_m->m_pkthdr.len;
626 q->F += (len << MY_M) / (uint64_t)fs->weight;
627 if (DN_KEY_LEQ(q->S, p->V))
628 heap_insert(neh, q->S, q);
630 heap_insert(sch, q->F, q);
635 * Now compute V = max(V, min(S_i)). Remember that all elements in
636 * sch 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);
644 * Move from neh to sch any packets that have become eligible
646 while (neh->elements > 0 && DN_KEY_LEQ(neh->p[0].key, p->V)) {
647 struct dn_flow_queue *q = neh->p[0].object;
649 heap_extract(neh, NULL);
650 heap_insert(sch, q->F, q);
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;
673 * If we are getting clocks from dummynet and if we are under credit,
674 * schedule the next ready event.
675 * Also fix the delivery time of the last packet.
677 if (p->numbytes < 0) { /* This implies bandwidth>0 */
678 dn_key t = 0; /* Number of ticks i have to wait */
680 if (p->bandwidth > 0)
681 t = (p->bandwidth - 1 - p->numbytes) / p->bandwidth;
682 TAILQ_LAST(&p->p_queue, dn_pkt_queue)->output_time += t;
683 p->sched_time = curr_time;
686 * XXX should check errors on heap_insert, and drain the whole
687 * queue on error hoping next time we are luckier.
689 heap_insert(&wfq_ready_heap, curr_time + t, p);
693 * If the delay line was empty call transmit_event(p) now.
694 * Otherwise, the scheduler will take care of it.
701 dn_expire_pipe_cb(struct dn_pipe *pipe, void *dummy __unused)
703 if (pipe->idle_heap.elements > 0 &&
704 DN_KEY_LT(pipe->idle_heap.p[0].key, pipe->V)) {
705 struct dn_flow_queue *q = pipe->idle_heap.p[0].object;
707 heap_extract(&pipe->idle_heap, NULL);
708 q->S = q->F + 1; /* Mark timestamp as invalid */
709 pipe->sum -= q->fs->weight;
714 * This is called once per tick, or dn_hz times per second. It is used to
715 * increment the current tick counter and schedule expired events.
718 dummynet(struct netmsg *msg)
722 struct dn_heap *heaps[3];
725 heaps[0] = &ready_heap; /* Fixed-rate queues */
726 heaps[1] = &wfq_ready_heap; /* WF2Q queues */
727 heaps[2] = &extract_heap; /* Delay line */
732 lwkt_replymsg(&msg->nm_lmsg, 0);
735 for (i = 0; i < 3; i++) {
737 while (h->elements > 0 && DN_KEY_LEQ(h->p[0].key, curr_time)) {
738 if (h->p[0].key > curr_time) {
739 kprintf("-- dummynet: warning, heap %d is %d ticks late\n",
740 i, (int)(curr_time - h->p[0].key));
743 p = h->p[0].object; /* Store a copy before heap_extract */
744 heap_extract(h, NULL); /* Need to extract before processing */
755 /* Sweep pipes trying to expire idle flow_queues */
756 dn_iterate_pipe(dn_expire_pipe_cb, NULL);
762 * Unconditionally expire empty queues in case of shortage.
763 * Returns the number of queues freed.
766 expire_queues(struct dn_flow_set *fs)
768 struct dn_flow_queue *q, *prev;
769 int i, initial_elements = fs->rq_elements;
771 if (fs->last_expired == time_second)
774 fs->last_expired = time_second;
776 for (i = 0; i <= fs->rq_size; i++) { /* Last one is overflow */
777 for (prev = NULL, q = fs->rq[i]; q != NULL;) {
778 if (!TAILQ_EMPTY(&q->queue) || q->S != q->F + 1) {
781 } else { /* Entry is idle, expire it */
782 struct dn_flow_queue *old_q = q;
785 prev->next = q = q->next;
787 fs->rq[i] = q = q->next;
789 kfree(old_q, M_DUMMYNET);
793 return initial_elements - fs->rq_elements;
797 * If room, create a new queue and put at head of slot i;
798 * otherwise, create or use the default queue.
800 static struct dn_flow_queue *
801 create_queue(struct dn_flow_set *fs, int i)
803 struct dn_flow_queue *q;
805 if (fs->rq_elements > fs->rq_size * dn_max_ratio &&
806 expire_queues(fs) == 0) {
808 * No way to get room, use or create overflow queue.
811 if (fs->rq[i] != NULL)
815 q = kmalloc(sizeof(*q), M_DUMMYNET, M_INTWAIT | M_NULLOK | M_ZERO);
822 q->S = q->F + 1; /* hack - mark timestamp as invalid */
825 TAILQ_INIT(&q->queue);
831 * Given a flow_set and a pkt in last_pkt, find a matching queue
832 * after appropriate masking. The queue is moved to front
833 * so that further searches take less time.
835 static struct dn_flow_queue *
836 find_queue(struct dn_flow_set *fs, struct ipfw_flow_id *id)
838 struct dn_flow_queue *q, *prev;
841 if (!(fs->flags_fs & DN_HAVE_FLOW_MASK)) {
844 /* First, do the masking */
845 id->dst_ip &= fs->flow_mask.dst_ip;
846 id->src_ip &= fs->flow_mask.src_ip;
847 id->dst_port &= fs->flow_mask.dst_port;
848 id->src_port &= fs->flow_mask.src_port;
849 id->proto &= fs->flow_mask.proto;
850 id->flags = 0; /* we don't care about this one */
852 /* Then, hash function */
853 i = ((id->dst_ip) & 0xffff) ^
854 ((id->dst_ip >> 15) & 0xffff) ^
855 ((id->src_ip << 1) & 0xffff) ^
856 ((id->src_ip >> 16 ) & 0xffff) ^
857 (id->dst_port << 1) ^ (id->src_port) ^
861 /* Finally, scan the current list for a match */
863 for (prev = NULL, q = fs->rq[i]; q;) {
865 if (id->dst_ip == q->id.dst_ip &&
866 id->src_ip == q->id.src_ip &&
867 id->dst_port == q->id.dst_port &&
868 id->src_port == q->id.src_port &&
869 id->proto == q->id.proto &&
870 id->flags == q->id.flags) {
872 } else if (pipe_expire && TAILQ_EMPTY(&q->queue) &&
874 /* Entry is idle and not in any heap, expire it */
875 struct dn_flow_queue *old_q = q;
878 prev->next = q = q->next;
880 fs->rq[i] = q = q->next;
882 kfree(old_q, M_DUMMYNET);
888 if (q && prev != NULL) { /* Found and not in front */
889 prev->next = q->next;
894 if (q == NULL) { /* No match, need to allocate a new entry */
895 q = create_queue(fs, i);
903 red_drops(struct dn_flow_set *fs, struct dn_flow_queue *q, int len)
908 * RED calculates the average queue size (avg) using a low-pass filter
909 * with an exponential weighted (w_q) moving average:
910 * avg <- (1-w_q) * avg + w_q * q_size
911 * where q_size is the queue length (measured in bytes or * packets).
913 * If q_size == 0, we compute the idle time for the link, and set
914 * avg = (1 - w_q)^(idle/s)
915 * where s is the time needed for transmitting a medium-sized packet.
917 * Now, if avg < min_th the packet is enqueued.
918 * If avg > max_th the packet is dropped. Otherwise, the packet is
919 * dropped with probability P function of avg.
923 u_int q_size = (fs->flags_fs & DN_QSIZE_IS_BYTES) ? q->len_bytes : q->len;
925 DPRINTF("\n%d q: %2u ", (int)curr_time, q_size);
927 /* Average queue size estimation */
930 * Queue is not empty, avg <- avg + (q_size - avg) * w_q
932 int diff = SCALE(q_size) - q->avg;
933 int64_t v = SCALE_MUL((int64_t)diff, (int64_t)fs->w_q);
938 * Queue is empty, find for how long the queue has been
939 * empty and use a lookup table for computing
940 * (1 - * w_q)^(idle_time/s) where s is the time to send a
945 u_int t = (curr_time - q->q_time) / fs->lookup_step;
947 q->avg = (t < fs->lookup_depth) ?
948 SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
951 DPRINTF("avg: %u ", SCALE_VAL(q->avg));
955 if (q->avg < fs->min_th) {
961 if (q->avg >= fs->max_th) { /* Average queue >= Max threshold */
962 if (fs->flags_fs & DN_IS_GENTLE_RED) {
964 * According to Gentle-RED, if avg is greater than max_th the
965 * packet is dropped with a probability
966 * p_b = c_3 * avg - c_4
967 * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
969 p_b = SCALE_MUL((int64_t)fs->c_3, (int64_t)q->avg) - fs->c_4;
975 } else if (q->avg > fs->min_th) {
977 * We compute p_b using the linear dropping function p_b = c_1 *
978 * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
979 * max_p * min_th / (max_th - min_th)
981 p_b = SCALE_MUL((int64_t)fs->c_1, (int64_t)q->avg) - fs->c_2;
983 if (fs->flags_fs & DN_QSIZE_IS_BYTES)
984 p_b = (p_b * len) / fs->max_pkt_size;
986 if (++q->count == 0) {
987 q->random = krandom() & 0xffff;
990 * q->count counts packets arrived since last drop, so a greater
991 * value of q->count means a greater packet drop probability.
993 if (SCALE_MUL(p_b, SCALE((int64_t)q->count)) > q->random) {
995 DPRINTF("%s", "- red drop");
996 /* After a drop we calculate a new random value */
997 q->random = krandom() & 0xffff;
1001 /* End of RED algorithm */
1002 return 0; /* Accept */
1006 dn_iterate_pipe(dn_pipe_iter_t func, void *arg)
1010 for (i = 0; i < DN_NR_HASH_MAX; ++i) {
1011 struct dn_pipe_head *pipe_hdr = &pipe_table[i];
1012 struct dn_pipe *pipe, *pipe_next;
1014 LIST_FOREACH_MUTABLE(pipe, pipe_hdr, p_link, pipe_next)
1020 dn_iterate_flowset(dn_flowset_iter_t func, void *arg)
1024 for (i = 0; i < DN_NR_HASH_MAX; ++i) {
1025 struct dn_flowset_head *fs_hdr = &flowset_table[i];
1026 struct dn_flow_set *fs, *fs_next;
1028 LIST_FOREACH_MUTABLE(fs, fs_hdr, fs_link, fs_next)
1033 static struct dn_pipe *
1034 dn_find_pipe(int pipe_nr)
1036 struct dn_pipe_head *pipe_hdr;
1039 pipe_hdr = &pipe_table[DN_NR_HASH(pipe_nr)];
1040 LIST_FOREACH(p, pipe_hdr, p_link) {
1041 if (p->pipe_nr == pipe_nr)
1047 static struct dn_flow_set *
1048 dn_find_flowset(int fs_nr)
1050 struct dn_flowset_head *fs_hdr;
1051 struct dn_flow_set *fs;
1053 fs_hdr = &flowset_table[DN_NR_HASH(fs_nr)];
1054 LIST_FOREACH(fs, fs_hdr, fs_link) {
1055 if (fs->fs_nr == fs_nr)
1061 static struct dn_flow_set *
1062 dn_locate_flowset(int pipe_nr, int is_pipe)
1064 struct dn_flow_set *fs = NULL;
1067 fs = dn_find_flowset(pipe_nr);
1071 p = dn_find_pipe(pipe_nr);
1079 * Dummynet hook for packets. Below 'pipe' is a pipe or a queue
1080 * depending on whether WF2Q or fixed bw is used.
1082 * pipe_nr pipe or queue the packet is destined for.
1083 * dir where shall we send the packet after dummynet.
1084 * m the mbuf with the packet
1085 * fwa->oif the 'ifp' parameter from the caller.
1086 * NULL in ip_input, destination interface in ip_output
1087 * fwa->ro route parameter (only used in ip_output, NULL otherwise)
1088 * fwa->dst destination address, only used by ip_output
1089 * fwa->rule matching rule, in case of multiple passes
1090 * fwa->flags flags from the caller, only used in ip_output
1093 dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
1097 struct dn_flow_set *fs;
1098 struct dn_pipe *pipe;
1099 uint64_t len = m->m_pkthdr.len;
1100 struct dn_flow_queue *q = NULL;
1106 cmd = fwa->rule->cmd + fwa->rule->act_ofs;
1107 if (cmd->opcode == O_LOG)
1110 KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
1111 ("Rule is not PIPE or QUEUE, opcode %d\n", cmd->opcode));
1113 is_pipe = (cmd->opcode == O_PIPE);
1117 * This is a dummynet rule, so we expect a O_PIPE or O_QUEUE rule
1119 fs = dn_locate_flowset(pipe_nr, is_pipe);
1121 goto dropit; /* This queue/pipe does not exist! */
1124 if (pipe == NULL) { /* Must be a queue, try find a matching pipe */
1125 pipe = dn_find_pipe(fs->parent_nr);
1129 kprintf("No pipe %d for queue %d, drop pkt\n",
1130 fs->parent_nr, fs->fs_nr);
1135 q = find_queue(fs, &fwa->f_id);
1137 goto dropit; /* Cannot allocate queue */
1140 * Update statistics, then check reasons to drop pkt
1142 q->tot_bytes += len;
1145 if (fs->plr && krandom() < fs->plr)
1146 goto dropit; /* Random pkt drop */
1148 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1149 if (q->len_bytes > fs->qsize)
1150 goto dropit; /* Queue size overflow */
1152 if (q->len >= fs->qsize)
1153 goto dropit; /* Queue count overflow */
1156 if ((fs->flags_fs & DN_IS_RED) && red_drops(fs, q, len))
1160 * Build and enqueue packet + parameters
1162 tag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT /* XXX */);
1165 m_tag_prepend(m, tag);
1167 pkt = m_tag_data(tag);
1168 bzero(pkt, sizeof(*pkt)); /* XXX expensive to zero */
1170 pkt->rule = fwa->rule;
1174 pkt->ifp = fwa->oif;
1175 if (dir == DN_TO_IP_OUT) {
1177 * We need to copy *ro because for ICMP pkts (and maybe others)
1178 * the caller passed a pointer into the stack; dst might also be
1179 * a pointer into *ro so it needs to be updated.
1181 pkt->ro = *(fwa->ro);
1183 fwa->ro->ro_rt->rt_refcnt++;
1184 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) {
1185 /* 'dst' points into 'ro' */
1186 fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst);
1189 pkt->dn_dst = fwa->dst;
1190 pkt->flags = fwa->flags;
1192 TAILQ_INSERT_TAIL(&q->queue, pkt, dn_next);
1194 q->len_bytes += len;
1196 if (TAILQ_FIRST(&q->queue) != pkt) /* Flow was not idle, we are done */
1200 * If we reach this point the flow was previously idle, so we need
1201 * to schedule it. This involves different actions for fixed-rate
1206 * Fixed-rate queue: just insert into the ready_heap.
1210 if (pipe->bandwidth)
1211 t = SET_TICKS(pkt, q, pipe);
1213 q->sched_time = curr_time;
1214 if (t == 0) /* Must process it now */
1217 heap_insert(&ready_heap, curr_time + t, q);
1221 * First, compute start time S: if the flow was idle (S=F+1)
1222 * set S to the virtual time V for the controlling pipe, and update
1223 * the sum of weights for the pipe; otherwise, remove flow from
1224 * idle_heap and set S to max(F, V).
1225 * Second, compute finish time F = S + len/weight.
1226 * Third, if pipe was idle, update V = max(S, V).
1227 * Fourth, count one more backlogged flow.
1229 if (DN_KEY_GT(q->S, q->F)) { /* Means timestamps are invalid */
1231 pipe->sum += fs->weight; /* Add weight of new queue */
1233 heap_extract(&pipe->idle_heap, q);
1234 q->S = MAX64(q->F, pipe->V);
1236 q->F = q->S + (len << MY_M) / (uint64_t)fs->weight;
1238 if (pipe->not_eligible_heap.elements == 0 &&
1239 pipe->scheduler_heap.elements == 0)
1240 pipe->V = MAX64(q->S, pipe->V);
1245 * Look at eligibility. A flow is not eligibile if S>V (when
1246 * this happens, it means that there is some other flow already
1247 * scheduled for the same pipe, so the scheduler_heap cannot be
1248 * empty). If the flow is not eligible we just store it in the
1249 * not_eligible_heap. Otherwise, we store in the scheduler_heap
1250 * and possibly invoke ready_event_wfq() right now if there is
1252 * Note that for all flows in scheduler_heap (SCH), S_i <= V,
1253 * and for all flows in not_eligible_heap (NEH), S_i > V.
1254 * So when we need to compute max(V, min(S_i)) forall i in SCH+NEH,
1255 * we only need to look into NEH.
1257 if (DN_KEY_GT(q->S, pipe->V)) { /* Not eligible */
1258 if (pipe->scheduler_heap.elements == 0)
1259 kprintf("++ ouch! not eligible but empty scheduler!\n");
1260 heap_insert(&pipe->not_eligible_heap, q->S, q);
1262 heap_insert(&pipe->scheduler_heap, q->F, q);
1263 if (pipe->numbytes >= 0) { /* Pipe is idle */
1264 if (pipe->scheduler_heap.elements != 1)
1265 kprintf("*** OUCH! pipe should have been idle!\n");
1266 DPRINTF("Waking up pipe %d at %d\n",
1267 pipe->pipe_nr, (int)(q->F >> MY_M));
1268 pipe->sched_time = curr_time;
1269 ready_event_wfq(pipe);
1282 return ((fs && (fs->flags_fs & DN_NOERROR)) ? 0 : ENOBUFS);
1286 * Below, the rt_unref is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
1287 * Doing this would probably save us the initial bzero of dn_pkt
1289 #define DN_FREE_PKT(pkt) \
1291 rt_unref((pkt)->ro.ro_rt); \
1292 m_freem((pkt)->dn_m); \
1296 * Dispose all packets and flow_queues on a flow_set.
1297 * If all=1, also remove red lookup table and other storage,
1298 * including the descriptor itself.
1299 * For the one in dn_pipe MUST also cleanup ready_heap...
1302 purge_flow_set(struct dn_flow_set *fs, int all)
1306 for (i = 0; i <= fs->rq_size; i++) {
1307 struct dn_flow_queue *q, *qn;
1309 for (q = fs->rq[i]; q; q = qn) {
1312 while ((pkt = TAILQ_FIRST(&q->queue)) != NULL) {
1313 TAILQ_REMOVE(&q->queue, pkt, dn_next);
1318 kfree(q, M_DUMMYNET);
1322 fs->rq_elements = 0;
1325 /* RED - free lookup table */
1327 kfree(fs->w_q_lookup, M_DUMMYNET);
1330 kfree(fs->rq, M_DUMMYNET);
1332 /* If this fs is not part of a pipe, free it */
1333 if (fs->pipe && fs != &fs->pipe->fs)
1334 kfree(fs, M_DUMMYNET);
1339 * Dispose all packets queued on a pipe (not a flow_set).
1340 * Also free all resources associated to a pipe, which is about
1344 purge_pipe(struct dn_pipe *pipe)
1348 purge_flow_set(&pipe->fs, 1);
1350 while ((pkt = TAILQ_FIRST(&pipe->p_queue)) != NULL) {
1351 TAILQ_REMOVE(&pipe->p_queue, pkt, dn_next);
1355 heap_free(&pipe->scheduler_heap);
1356 heap_free(&pipe->not_eligible_heap);
1357 heap_free(&pipe->idle_heap);
1361 * Delete all pipes and heaps returning memory. Must also
1362 * remove references from all ipfw rules to all pipes.
1365 dummynet_flush(void)
1367 struct dn_pipe_head pipe_list;
1368 struct dn_flowset_head fs_list;
1370 struct dn_flow_set *fs;
1376 * Prevent future matches...
1378 LIST_INIT(&pipe_list);
1379 for (i = 0; i < DN_NR_HASH_MAX; ++i) {
1380 struct dn_pipe_head *pipe_hdr = &pipe_table[i];
1382 while ((p = LIST_FIRST(pipe_hdr)) != NULL) {
1383 LIST_REMOVE(p, p_link);
1384 LIST_INSERT_HEAD(&pipe_list, p, p_link);
1388 LIST_INIT(&fs_list);
1389 for (i = 0; i < DN_NR_HASH_MAX; ++i) {
1390 struct dn_flowset_head *fs_hdr = &flowset_table[i];
1392 while ((fs = LIST_FIRST(fs_hdr)) != NULL) {
1393 LIST_REMOVE(fs, fs_link);
1394 LIST_INSERT_HEAD(&fs_list, fs, fs_link);
1398 /* Free heaps so we don't have unwanted events */
1399 heap_free(&ready_heap);
1400 heap_free(&wfq_ready_heap);
1401 heap_free(&extract_heap);
1406 * Now purge all queued pkts and delete all pipes
1408 /* Scan and purge all flow_sets. */
1409 while ((fs = LIST_FIRST(&fs_list)) != NULL) {
1410 LIST_REMOVE(fs, fs_link);
1411 purge_flow_set(fs, 1);
1414 while ((p = LIST_FIRST(&pipe_list)) != NULL) {
1415 LIST_REMOVE(p, p_link);
1417 kfree(p, M_DUMMYNET);
1422 extern struct ip_fw *ip_fw_default_rule;
1425 dn_rule_delete_fs(struct dn_flow_set *fs, void *r)
1429 for (i = 0; i <= fs->rq_size; i++) { /* Last one is ovflow */
1430 struct dn_flow_queue *q;
1432 for (q = fs->rq[i]; q; q = q->next) {
1435 TAILQ_FOREACH(pkt, &q->queue, dn_next) {
1437 pkt->rule = ip_fw_default_rule;
1444 dn_ruledel_pipe_cb(struct dn_pipe *pipe, void *rule)
1448 dn_rule_delete_fs(&pipe->fs, rule);
1450 TAILQ_FOREACH(pkt, &pipe->p_queue, dn_next) {
1451 if (pkt->rule == rule)
1452 pkt->rule = ip_fw_default_rule;
1457 dn_ruledel_fs_cb(struct dn_flow_set *fs, void *rule)
1459 dn_rule_delete_fs(fs, rule);
1463 * When a firewall rule is deleted, scan all queues and remove the flow-id
1464 * from packets matching this rule.
1467 dummynet_ruledel(void *r)
1470 * If the rule references a queue (dn_flow_set), then scan
1471 * the flow set, otherwise scan pipes. Should do either, but doing
1472 * both does not harm.
1474 dn_iterate_flowset(dn_ruledel_fs_cb, r);
1475 dn_iterate_pipe(dn_ruledel_pipe_cb, r);
1479 * setup RED parameters
1482 config_red(const struct dn_ioc_flowset *ioc_fs, struct dn_flow_set *x)
1486 x->w_q = ioc_fs->w_q;
1487 x->min_th = SCALE(ioc_fs->min_th);
1488 x->max_th = SCALE(ioc_fs->max_th);
1489 x->max_p = ioc_fs->max_p;
1491 x->c_1 = ioc_fs->max_p / (ioc_fs->max_th - ioc_fs->min_th);
1492 x->c_2 = SCALE_MUL(x->c_1, SCALE(ioc_fs->min_th));
1493 if (x->flags_fs & DN_IS_GENTLE_RED) {
1494 x->c_3 = (SCALE(1) - ioc_fs->max_p) / ioc_fs->max_th;
1495 x->c_4 = (SCALE(1) - 2 * ioc_fs->max_p);
1498 /* If the lookup table already exist, free and create it again */
1499 if (x->w_q_lookup) {
1500 kfree(x->w_q_lookup, M_DUMMYNET);
1501 x->w_q_lookup = NULL ;
1504 if (red_lookup_depth == 0) {
1505 kprintf("net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
1506 kfree(x, M_DUMMYNET);
1509 x->lookup_depth = red_lookup_depth;
1510 x->w_q_lookup = kmalloc(x->lookup_depth * sizeof(int),
1511 M_DUMMYNET, M_WAITOK);
1513 /* Fill the lookup table with (1 - w_q)^x */
1514 x->lookup_step = ioc_fs->lookup_step;
1515 x->lookup_weight = ioc_fs->lookup_weight;
1517 x->w_q_lookup[0] = SCALE(1) - x->w_q;
1518 for (i = 1; i < x->lookup_depth; i++)
1519 x->w_q_lookup[i] = SCALE_MUL(x->w_q_lookup[i - 1], x->lookup_weight);
1521 if (red_avg_pkt_size < 1)
1522 red_avg_pkt_size = 512;
1523 x->avg_pkt_size = red_avg_pkt_size;
1525 if (red_max_pkt_size < 1)
1526 red_max_pkt_size = 1500;
1527 x->max_pkt_size = red_max_pkt_size;
1533 alloc_hash(struct dn_flow_set *x, const struct dn_ioc_flowset *ioc_fs)
1535 if (x->flags_fs & DN_HAVE_FLOW_MASK) {
1536 int l = ioc_fs->rq_size;
1538 /* Allocate some slots */
1542 if (l < DN_MIN_HASH_SIZE)
1543 l = DN_MIN_HASH_SIZE;
1544 else if (l > DN_MAX_HASH_SIZE)
1545 l = DN_MAX_HASH_SIZE;
1549 /* One is enough for null mask */
1552 x->rq = kmalloc((1 + x->rq_size) * sizeof(struct dn_flow_queue *),
1553 M_DUMMYNET, M_WAITOK | M_ZERO);
1558 set_flowid_parms(struct ipfw_flow_id *id, const struct dn_ioc_flowid *ioc_id)
1560 id->dst_ip = ioc_id->u.ip.dst_ip;
1561 id->src_ip = ioc_id->u.ip.src_ip;
1562 id->dst_port = ioc_id->u.ip.dst_port;
1563 id->src_port = ioc_id->u.ip.src_port;
1564 id->proto = ioc_id->u.ip.proto;
1565 id->flags = ioc_id->u.ip.flags;
1569 set_fs_parms(struct dn_flow_set *x, const struct dn_ioc_flowset *ioc_fs)
1571 x->flags_fs = ioc_fs->flags_fs;
1572 x->qsize = ioc_fs->qsize;
1573 x->plr = ioc_fs->plr;
1574 set_flowid_parms(&x->flow_mask, &ioc_fs->flow_mask);
1575 if (x->flags_fs & DN_QSIZE_IS_BYTES) {
1576 if (x->qsize > 1024 * 1024)
1577 x->qsize = 1024 * 1024;
1579 if (x->qsize == 0 || x->qsize > 100)
1583 /* Configuring RED */
1584 if (x->flags_fs & DN_IS_RED)
1585 config_red(ioc_fs, x); /* XXX should check errors */
1589 * setup pipe or queue parameters.
1593 config_pipe(struct dn_ioc_pipe *ioc_pipe)
1595 struct dn_ioc_flowset *ioc_fs = &ioc_pipe->fs;
1599 * The config program passes parameters as follows:
1600 * bw bits/second (0 means no limits)
1601 * delay ms (must be translated into ticks)
1602 * qsize slots or bytes
1604 ioc_pipe->delay = (ioc_pipe->delay * dn_hz) / 1000;
1607 * We need either a pipe number or a flow_set number
1609 if (ioc_pipe->pipe_nr == 0 && ioc_fs->fs_nr == 0)
1611 if (ioc_pipe->pipe_nr != 0 && ioc_fs->fs_nr != 0)
1615 * Validate pipe number
1617 if (ioc_pipe->pipe_nr > DN_PIPE_NR_MAX || ioc_pipe->pipe_nr < 0)
1623 if (ioc_pipe->pipe_nr != 0) { /* This is a pipe */
1624 struct dn_pipe *x, *p;
1627 p = dn_find_pipe(ioc_pipe->pipe_nr);
1629 if (p == NULL) { /* New pipe */
1630 x = kmalloc(sizeof(struct dn_pipe), M_DUMMYNET, M_WAITOK | M_ZERO);
1631 x->pipe_nr = ioc_pipe->pipe_nr;
1633 TAILQ_INIT(&x->p_queue);
1636 * idle_heap is the only one from which we extract from the middle.
1638 x->idle_heap.size = x->idle_heap.elements = 0;
1639 x->idle_heap.offset = __offsetof(struct dn_flow_queue, heap_pos);
1645 /* Flush accumulated credit for all queues */
1646 for (i = 0; i <= x->fs.rq_size; i++) {
1647 struct dn_flow_queue *q;
1649 for (q = x->fs.rq[i]; q; q = q->next)
1654 x->bandwidth = ioc_pipe->bandwidth;
1655 x->numbytes = 0; /* Just in case... */
1656 x->delay = ioc_pipe->delay;
1658 set_fs_parms(&x->fs, ioc_fs);
1660 if (x->fs.rq == NULL) { /* A new pipe */
1661 struct dn_pipe_head *pipe_hdr;
1663 alloc_hash(&x->fs, ioc_fs);
1665 pipe_hdr = &pipe_table[DN_NR_HASH(x->pipe_nr)];
1666 LIST_INSERT_HEAD(pipe_hdr, x, p_link);
1668 } else { /* Config flow_set */
1669 struct dn_flow_set *x, *fs;
1671 /* Locate flow_set */
1672 fs = dn_find_flowset(ioc_fs->fs_nr);
1674 if (fs == NULL) { /* New flow_set */
1675 if (ioc_fs->parent_nr == 0) /* Need link to a pipe */
1678 x = kmalloc(sizeof(struct dn_flow_set), M_DUMMYNET,
1680 x->fs_nr = ioc_fs->fs_nr;
1681 x->parent_nr = ioc_fs->parent_nr;
1682 x->weight = ioc_fs->weight;
1685 else if (x->weight > 100)
1688 /* Change parent pipe not allowed; must delete and recreate */
1689 if (ioc_fs->parent_nr != 0 && fs->parent_nr != ioc_fs->parent_nr)
1694 set_fs_parms(x, ioc_fs);
1696 if (x->rq == NULL) { /* A new flow_set */
1697 struct dn_flowset_head *fs_hdr;
1699 alloc_hash(x, ioc_fs);
1701 fs_hdr = &flowset_table[DN_NR_HASH(x->fs_nr)];
1702 LIST_INSERT_HEAD(fs_hdr, x, fs_link);
1713 * Helper function to remove from a heap queues which are linked to
1714 * a flow_set about to be deleted.
1717 fs_remove_from_heap(struct dn_heap *h, struct dn_flow_set *fs)
1719 int i = 0, found = 0;
1721 while (i < h->elements) {
1722 if (((struct dn_flow_queue *)h->p[i].object)->fs == fs) {
1724 h->p[i] = h->p[h->elements];
1735 * helper function to remove a pipe from a heap (can be there at most once)
1738 pipe_remove_from_heap(struct dn_heap *h, struct dn_pipe *p)
1740 if (h->elements > 0) {
1743 for (i = 0; i < h->elements; i++) {
1744 if (h->p[i].object == p) { /* found it */
1746 h->p[i] = h->p[h->elements];
1755 dn_unref_pipe_cb(struct dn_flow_set *fs, void *pipe0)
1757 struct dn_pipe *pipe = pipe0;
1759 if (fs->pipe == pipe) {
1760 kprintf("++ ref to pipe %d from fs %d\n",
1761 pipe->pipe_nr, fs->fs_nr);
1763 purge_flow_set(fs, 0);
1768 * Fully delete a pipe or a queue, cleaning up associated info.
1771 delete_pipe(const struct dn_ioc_pipe *ioc_pipe)
1776 if (ioc_pipe->pipe_nr == 0 && ioc_pipe->fs.fs_nr == 0)
1778 if (ioc_pipe->pipe_nr != 0 && ioc_pipe->fs.fs_nr != 0)
1781 if (ioc_pipe->pipe_nr > DN_NR_HASH_MAX || ioc_pipe->pipe_nr < 0)
1787 if (ioc_pipe->pipe_nr != 0) { /* This is an old-style pipe */
1789 p = dn_find_pipe(ioc_pipe->pipe_nr);
1791 goto back; /* Not found */
1793 /* Unlink from pipe hash table */
1794 LIST_REMOVE(p, p_link);
1796 /* Remove all references to this pipe from flow_sets */
1797 dn_iterate_flowset(dn_unref_pipe_cb, p);
1799 fs_remove_from_heap(&ready_heap, &p->fs);
1800 purge_pipe(p); /* Remove all data associated to this pipe */
1802 /* Remove reference to here from extract_heap and wfq_ready_heap */
1803 pipe_remove_from_heap(&extract_heap, p);
1804 pipe_remove_from_heap(&wfq_ready_heap, p);
1806 kfree(p, M_DUMMYNET);
1807 } else { /* This is a WF2Q queue (dn_flow_set) */
1808 struct dn_flow_set *fs;
1810 /* Locate flow_set */
1811 fs = dn_find_flowset(ioc_pipe->fs.fs_nr);
1813 goto back; /* Not found */
1815 LIST_REMOVE(fs, fs_link);
1817 if ((p = fs->pipe) != NULL) {
1818 /* Update total weight on parent pipe and cleanup parent heaps */
1819 p->sum -= fs->weight * fs->backlogged;
1820 fs_remove_from_heap(&p->not_eligible_heap, fs);
1821 fs_remove_from_heap(&p->scheduler_heap, fs);
1822 #if 1 /* XXX should i remove from idle_heap as well ? */
1823 fs_remove_from_heap(&p->idle_heap, fs);
1826 purge_flow_set(fs, 1);
1836 * helper function used to copy data from kernel in DUMMYNET_GET
1839 dn_copy_flowid(const struct ipfw_flow_id *id, struct dn_ioc_flowid *ioc_id)
1841 ioc_id->type = ETHERTYPE_IP;
1842 ioc_id->u.ip.dst_ip = id->dst_ip;
1843 ioc_id->u.ip.src_ip = id->src_ip;
1844 ioc_id->u.ip.dst_port = id->dst_port;
1845 ioc_id->u.ip.src_port = id->src_port;
1846 ioc_id->u.ip.proto = id->proto;
1847 ioc_id->u.ip.flags = id->flags;
1851 dn_copy_flowqueues(const struct dn_flow_set *fs, void *bp)
1853 const struct dn_flow_queue *q;
1854 struct dn_ioc_flowqueue *ioc_fq = bp;
1857 for (i = 0; i <= fs->rq_size; i++) {
1858 for (q = fs->rq[i]; q; q = q->next, ioc_fq++) {
1859 if (q->hash_slot != i) { /* XXX ASSERT */
1860 kprintf("++ at %d: wrong slot (have %d, "
1861 "should be %d)\n", copied, q->hash_slot, i);
1863 if (q->fs != fs) { /* XXX ASSERT */
1864 kprintf("++ at %d: wrong fs ptr (have %p, should be %p)\n",
1870 ioc_fq->len = q->len;
1871 ioc_fq->len_bytes = q->len_bytes;
1872 ioc_fq->tot_pkts = q->tot_pkts;
1873 ioc_fq->tot_bytes = q->tot_bytes;
1874 ioc_fq->drops = q->drops;
1875 ioc_fq->hash_slot = q->hash_slot;
1878 dn_copy_flowid(&q->id, &ioc_fq->id);
1882 if (copied != fs->rq_elements) { /* XXX ASSERT */
1883 kprintf("++ wrong count, have %d should be %d\n",
1884 copied, fs->rq_elements);
1890 dn_copy_flowset(const struct dn_flow_set *fs, struct dn_ioc_flowset *ioc_fs,
1893 ioc_fs->fs_type = fs_type;
1895 ioc_fs->fs_nr = fs->fs_nr;
1896 ioc_fs->flags_fs = fs->flags_fs;
1897 ioc_fs->parent_nr = fs->parent_nr;
1899 ioc_fs->weight = fs->weight;
1900 ioc_fs->qsize = fs->qsize;
1901 ioc_fs->plr = fs->plr;
1903 ioc_fs->rq_size = fs->rq_size;
1904 ioc_fs->rq_elements = fs->rq_elements;
1906 ioc_fs->w_q = fs->w_q;
1907 ioc_fs->max_th = fs->max_th;
1908 ioc_fs->min_th = fs->min_th;
1909 ioc_fs->max_p = fs->max_p;
1911 dn_copy_flowid(&fs->flow_mask, &ioc_fs->flow_mask);
1915 dn_calc_pipe_size_cb(struct dn_pipe *pipe, void *sz)
1919 *size += sizeof(struct dn_ioc_pipe) +
1920 pipe->fs.rq_elements * sizeof(struct dn_ioc_flowqueue);
1924 dn_calc_fs_size_cb(struct dn_flow_set *fs, void *sz)
1928 *size += sizeof(struct dn_ioc_flowset) +
1929 fs->rq_elements * sizeof(struct dn_ioc_flowqueue);
1933 dn_copyout_pipe_cb(struct dn_pipe *pipe, void *bp0)
1936 struct dn_ioc_pipe *ioc_pipe = (struct dn_ioc_pipe *)(*bp);
1939 * Copy flow set descriptor associated with this pipe
1941 dn_copy_flowset(&pipe->fs, &ioc_pipe->fs, DN_IS_PIPE);
1944 * Copy pipe descriptor
1946 ioc_pipe->bandwidth = pipe->bandwidth;
1947 ioc_pipe->pipe_nr = pipe->pipe_nr;
1948 ioc_pipe->V = pipe->V;
1949 /* Convert delay to milliseconds */
1950 ioc_pipe->delay = (pipe->delay * 1000) / dn_hz;
1953 * Copy flow queue descriptors
1955 *bp += sizeof(*ioc_pipe);
1956 *bp = dn_copy_flowqueues(&pipe->fs, *bp);
1960 dn_copyout_fs_cb(struct dn_flow_set *fs, void *bp0)
1963 struct dn_ioc_flowset *ioc_fs = (struct dn_ioc_flowset *)(*bp);
1966 * Copy flow set descriptor
1968 dn_copy_flowset(fs, ioc_fs, DN_IS_QUEUE);
1971 * Copy flow queue descriptors
1973 *bp += sizeof(*ioc_fs);
1974 *bp = dn_copy_flowqueues(fs, *bp);
1978 dummynet_get(struct sockopt *sopt)
1987 * Compute size of data structures: list of pipes and flow_sets.
1989 dn_iterate_pipe(dn_calc_pipe_size_cb, &size);
1990 dn_iterate_flowset(dn_calc_fs_size_cb, &size);
1993 * Copyout pipe/flow_set/flow_queue
1995 bp = buf = kmalloc(size, M_TEMP, M_WAITOK | M_ZERO);
1996 dn_iterate_pipe(dn_copyout_pipe_cb, &bp);
1997 dn_iterate_flowset(dn_copyout_fs_cb, &bp);
2001 error = sooptcopyout(sopt, buf, size);
2007 * Handler for the various dummynet socket options (get, flush, config, del)
2010 dummynet_ctl(struct sockopt *sopt)
2012 struct dn_ioc_pipe tmp_ioc_pipe;
2015 /* Disallow sets in really-really secure mode. */
2016 if (sopt->sopt_dir == SOPT_SET) {
2017 if (securelevel >= 3)
2021 switch (sopt->sopt_name) {
2022 case IP_DUMMYNET_GET:
2023 error = dummynet_get(sopt);
2026 case IP_DUMMYNET_FLUSH:
2030 case IP_DUMMYNET_CONFIGURE:
2031 error = sooptcopyin(sopt, &tmp_ioc_pipe, sizeof(tmp_ioc_pipe),
2032 sizeof(tmp_ioc_pipe));
2035 error = config_pipe(&tmp_ioc_pipe);
2038 case IP_DUMMYNET_DEL: /* Remove a pipe or flow_set */
2039 error = sooptcopyin(sopt, &tmp_ioc_pipe, sizeof(tmp_ioc_pipe),
2040 sizeof(tmp_ioc_pipe));
2043 error = delete_pipe(&tmp_ioc_pipe);
2047 kprintf("%s -- unknown option %d\n", __func__, sopt->sopt_name);
2055 dummynet_clock(systimer_t info __unused, struct intrframe *frame __unused)
2057 KASSERT(mycpu->gd_cpuid == dn_cpu,
2058 ("systimer comes on a different cpu!\n"));
2061 if (dn_netmsg.nm_lmsg.ms_flags & MSGF_DONE)
2062 lwkt_sendmsg(cpu_portfn(mycpu->gd_cpuid), &dn_netmsg.nm_lmsg);
2067 sysctl_dn_hz(SYSCTL_HANDLER_ARGS)
2072 error = sysctl_handle_int(oidp, &val, 0, req);
2073 if (error || req->newptr == NULL)
2077 else if (val > DN_CALLOUT_FREQ_MAX)
2078 val = DN_CALLOUT_FREQ_MAX;
2082 systimer_adjust_periodic(&dn_clock, val);
2089 ip_dn_register_systimer(struct netmsg *msg)
2091 systimer_init_periodic_nq(&dn_clock, dummynet_clock, NULL, dn_hz);
2092 lwkt_replymsg(&msg->nm_lmsg, 0);
2096 ip_dn_deregister_systimer(struct netmsg *msg)
2098 systimer_del(&dn_clock);
2099 lwkt_replymsg(&msg->nm_lmsg, 0);
2109 kprintf("DUMMYNET initialized (011031)\n");
2111 for (i = 0; i < DN_NR_HASH_MAX; ++i)
2112 LIST_INIT(&pipe_table[i]);
2114 for (i = 0; i < DN_NR_HASH_MAX; ++i)
2115 LIST_INIT(&flowset_table[i]);
2117 ready_heap.size = ready_heap.elements = 0;
2118 ready_heap.offset = 0;
2120 wfq_ready_heap.size = wfq_ready_heap.elements = 0;
2121 wfq_ready_heap.offset = 0;
2123 extract_heap.size = extract_heap.elements = 0;
2124 extract_heap.offset = 0;
2126 ip_dn_ctl_ptr = dummynet_ctl;
2127 ip_dn_io_ptr = dummynet_io;
2128 ip_dn_ruledel_ptr = dummynet_ruledel;
2130 netmsg_init(&dn_netmsg, &netisr_adone_rport, 0, dummynet);
2132 netmsg_init(&smsg, &curthread->td_msgport, 0, ip_dn_register_systimer);
2133 port = cpu_portfn(dn_cpu);
2134 lwkt_domsg(port, &smsg.nm_lmsg, 0);
2143 netmsg_init(&smsg, &curthread->td_msgport, 0, ip_dn_deregister_systimer);
2144 port = cpu_portfn(dn_cpu);
2145 lwkt_domsg(port, &smsg.nm_lmsg, 0);
2149 ip_dn_ctl_ptr = NULL;
2150 ip_dn_io_ptr = NULL;
2151 ip_dn_ruledel_ptr = NULL;
2153 netmsg_service_sync();
2157 dummynet_modevent(module_t mod, int type, void *data)
2162 if (DUMMYNET_LOADED) {
2164 kprintf("DUMMYNET already loaded\n");
2173 kprintf("dummynet statically compiled, cannot unload\n");
2188 static moduledata_t dummynet_mod = {
2193 DECLARE_MODULE(dummynet, dummynet_mod, SI_SUB_PROTO_END, SI_ORDER_ANY);
2194 MODULE_DEPEND(dummynet, ipfw, 1, 1, 1);
2195 MODULE_VERSION(dummynet, 1);