]>
git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/ip_dummynet.c
426b22d5db689c904fa26c1a9ac700a195a5686f
2 * Copyright (c) 2000-2007 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1998-2002 Luigi Rizzo, Universita` di Pisa
30 * Portions Copyright (c) 2000 Akamba Corp.
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
42 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * $FreeBSD: src/sys/netinet/ip_dummynet.c,v 1.84 2004/08/25 09:31:30 pjd Exp $
57 #define DUMMYNET_DEBUG
60 * This module implements IP dummynet, a bandwidth limiter/delay emulator
61 * used in conjunction with the ipfw package.
62 * Description of the data structures used is in ip_dummynet.h
63 * Here you mainly find the following blocks of code:
64 * + variable declarations;
65 * + heap management functions;
66 * + scheduler and dummynet functions;
67 * + configuration and initialization.
69 * NOTA BENE: critical sections are protected by the "dummynet lock".
71 * Most important Changes:
73 * 010124: Fixed WF2Q behaviour
74 * 010122: Fixed spl protection.
75 * 000601: WF2Q support
76 * 000106: large rewrite, use heaps to handle very many pipes.
77 * 980513: initial release
79 * include files marked with XXX are probably not needed
82 #include <sys/param.h>
83 #include <sys/systm.h>
84 #include <sys/malloc.h>
86 #include <sys/queue.h> /* XXX */
87 #include <sys/kernel.h>
88 #include <sys/socket.h>
89 #include <sys/socketvar.h>
91 #include <sys/sysctl.h>
93 #include <net/route.h>
94 #include <net/kpi_protocol.h>
95 #include <netinet/in.h>
96 #include <netinet/in_systm.h>
97 #include <netinet/in_var.h>
98 #include <netinet/ip.h>
99 #include <netinet/ip_fw.h>
100 #include <netinet/ip_dummynet.h>
101 #include <netinet/ip_var.h>
104 #include <netinet/if_ether.h> /* for struct arpcom */
105 #include <net/bridge.h>
109 * We keep a private variable for the simulation time, but we could
110 * probably use an existing one ("softticks" in sys/kern/kern_timer.c)
112 static dn_key curr_time
= 0 ; /* current simulation time */
114 /* this is for the timer that fires to call dummynet() - we only enable the timer when
115 there are packets to process, otherwise it's disabled */
116 static int timer_enabled
= 0;
118 static int dn_hash_size
= 64 ; /* default hash size */
120 /* statistics on number of queue searches and search steps */
121 static int searches
, search_steps
;
122 static int pipe_expire
= 1 ; /* expire queue if empty */
123 static int dn_max_ratio
= 16 ; /* max queues/buckets ratio */
125 static int red_lookup_depth
= 256; /* RED - default lookup table depth */
126 static int red_avg_pkt_size
= 512; /* RED - default medium packet size */
127 static int red_max_pkt_size
= 1500; /* RED - default max packet size */
130 * Three heaps contain queues and pipes that the scheduler handles:
132 * ready_heap contains all dn_flow_queue related to fixed-rate pipes.
134 * wfq_ready_heap contains the pipes associated with WF2Q flows
136 * extract_heap contains pipes associated with delay lines.
139 static struct dn_heap ready_heap
, extract_heap
, wfq_ready_heap
;
141 static int heap_init(struct dn_heap
*h
, int size
) ;
142 static int heap_insert (struct dn_heap
*h
, dn_key key1
, void *p
);
143 static void heap_extract(struct dn_heap
*h
, void *obj
);
145 static void transmit_event(struct dn_pipe
*pipe
);
146 static void ready_event(struct dn_flow_queue
*q
);
148 static struct dn_pipe
*all_pipes
= NULL
; /* list of all pipes */
149 static struct dn_flow_set
*all_flow_sets
= NULL
;/* list of all flow_sets */
152 SYSCTL_NODE(_net_inet_ip
, OID_AUTO
, dummynet
,
153 CTLFLAG_RW
, 0, "Dummynet");
154 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, hash_size
,
155 CTLFLAG_RW
, &dn_hash_size
, 0, "Default hash table size");
156 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, curr_time
,
157 CTLFLAG_RD
, &curr_time
, 0, "Current tick");
158 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, ready_heap
,
159 CTLFLAG_RD
, &ready_heap
.size
, 0, "Size of ready heap");
160 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, extract_heap
,
161 CTLFLAG_RD
, &extract_heap
.size
, 0, "Size of extract heap");
162 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, searches
,
163 CTLFLAG_RD
, &searches
, 0, "Number of queue searches");
164 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, search_steps
,
165 CTLFLAG_RD
, &search_steps
, 0, "Number of queue search steps");
166 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, expire
,
167 CTLFLAG_RW
, &pipe_expire
, 0, "Expire queue if empty");
168 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, max_chain_len
,
169 CTLFLAG_RW
, &dn_max_ratio
, 0,
170 "Max ratio between dynamic queues and buckets");
171 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, red_lookup_depth
,
172 CTLFLAG_RD
, &red_lookup_depth
, 0, "Depth of RED lookup table");
173 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, red_avg_pkt_size
,
174 CTLFLAG_RD
, &red_avg_pkt_size
, 0, "RED Medium packet size");
175 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, red_max_pkt_size
,
176 CTLFLAG_RD
, &red_max_pkt_size
, 0, "RED Max packet size");
179 #ifdef DUMMYNET_DEBUG
180 int dummynet_debug
= 0;
182 SYSCTL_INT(_net_inet_ip_dummynet
, OID_AUTO
, debug
, CTLFLAG_RW
, &dummynet_debug
,
183 0, "control debugging printfs");
185 #define DPRINTF(X) if (dummynet_debug) printf X
190 /* contrary to the comment above random(), it does not actually
191 * return a value [0, 2^31 - 1], which breaks plr amongst other
192 * things. Masking it should work even if the behavior of
193 * the function is fixed.
195 #define MY_RANDOM (random() & 0x7FFFFFFF)
198 lck_grp_t
*dn_mutex_grp
;
199 lck_grp_attr_t
*dn_mutex_grp_attr
;
200 lck_attr_t
*dn_mutex_attr
;
203 static int config_pipe(struct dn_pipe
*p
);
204 static int ip_dn_ctl(struct sockopt
*sopt
);
206 static void dummynet(void *);
207 static void dummynet_flush(void);
208 void dummynet_drain(void);
209 static ip_dn_io_t dummynet_io
;
210 static void dn_rule_delete(void *);
212 int if_tx_rdy(struct ifnet
*ifp
);
215 * Heap management functions.
217 * In the heap, first node is element 0. Children of i are 2i+1 and 2i+2.
218 * Some macros help finding parent/children so we can optimize them.
220 * heap_init() is called to expand the heap when needed.
221 * Increment size in blocks of 16 entries.
222 * XXX failure to allocate a new element is a pretty bad failure
223 * as we basically stall a whole queue forever!!
224 * Returns 1 on error, 0 on success
226 #define HEAP_FATHER(x) ( ( (x) - 1 ) / 2 )
227 #define HEAP_LEFT(x) ( 2*(x) + 1 )
228 #define HEAP_IS_LEFT(x) ( (x) & 1 )
229 #define HEAP_RIGHT(x) ( 2*(x) + 2 )
230 #define HEAP_SWAP(a, b, buffer) { buffer = a ; a = b ; b = buffer ; }
231 #define HEAP_INCREMENT 15
234 heap_init(struct dn_heap
*h
, int new_size
)
236 struct dn_heap_entry
*p
;
238 if (h
->size
>= new_size
) {
239 printf("dummynet: heap_init, Bogus call, have %d want %d\n",
243 new_size
= (new_size
+ HEAP_INCREMENT
) & ~HEAP_INCREMENT
;
244 p
= _MALLOC(new_size
* sizeof(*p
), M_DUMMYNET
, M_DONTWAIT
);
246 printf("dummynet: heap_init, resize %d failed\n", new_size
);
247 return 1 ; /* error */
250 bcopy(h
->p
, p
, h
->size
* sizeof(*p
) );
251 FREE(h
->p
, M_DUMMYNET
);
259 * Insert element in heap. Normally, p != NULL, we insert p in
260 * a new position and bubble up. If p == NULL, then the element is
261 * already in place, and key is the position where to start the
263 * Returns 1 on failure (cannot allocate new heap entry)
265 * If offset > 0 the position (index, int) of the element in the heap is
266 * also stored in the element itself at the given offset in bytes.
268 #define SET_OFFSET(heap, node) \
269 if (heap->offset > 0) \
270 *((int *)((char *)(heap->p[node].object) + heap->offset)) = node ;
272 * RESET_OFFSET is used for sanity checks. It sets offset to an invalid value.
274 #define RESET_OFFSET(heap, node) \
275 if (heap->offset > 0) \
276 *((int *)((char *)(heap->p[node].object) + heap->offset)) = -1 ;
278 heap_insert(struct dn_heap
*h
, dn_key key1
, void *p
)
280 int son
= h
->elements
;
282 if (p
== NULL
) /* data already there, set starting point */
284 else { /* insert new element at the end, possibly resize */
286 if (son
== h
->size
) /* need resize... */
287 if (heap_init(h
, h
->elements
+1) )
288 return 1 ; /* failure... */
289 h
->p
[son
].object
= p
;
290 h
->p
[son
].key
= key1
;
293 while (son
> 0) { /* bubble up */
294 int father
= HEAP_FATHER(son
) ;
295 struct dn_heap_entry tmp
;
297 if (DN_KEY_LT( h
->p
[father
].key
, h
->p
[son
].key
) )
298 break ; /* found right position */
299 /* son smaller than father, swap and repeat */
300 HEAP_SWAP(h
->p
[son
], h
->p
[father
], tmp
) ;
309 * remove top element from heap, or obj if obj != NULL
312 heap_extract(struct dn_heap
*h
, void *obj
)
314 int child
, father
, maxelt
= h
->elements
- 1 ;
317 printf("dummynet: warning, extract from empty heap 0x%p\n", h
);
320 father
= 0 ; /* default: move up smallest child */
321 if (obj
!= NULL
) { /* extract specific element, index is at offset */
323 panic("dummynet: heap_extract from middle not supported on this heap!!!\n");
324 father
= *((int *)((char *)obj
+ h
->offset
)) ;
325 if (father
< 0 || father
>= h
->elements
) {
326 printf("dummynet: heap_extract, father %d out of bound 0..%d\n",
327 father
, h
->elements
);
328 panic("dummynet: heap_extract");
331 RESET_OFFSET(h
, father
);
332 child
= HEAP_LEFT(father
) ; /* left child */
333 while (child
<= maxelt
) { /* valid entry */
334 if (child
!= maxelt
&& DN_KEY_LT(h
->p
[child
+1].key
, h
->p
[child
].key
) )
335 child
= child
+1 ; /* take right child, otherwise left */
336 h
->p
[father
] = h
->p
[child
] ;
337 SET_OFFSET(h
, father
);
339 child
= HEAP_LEFT(child
) ; /* left child for next loop */
342 if (father
!= maxelt
) {
344 * Fill hole with last entry and bubble up, reusing the insert code
346 h
->p
[father
] = h
->p
[maxelt
] ;
347 heap_insert(h
, father
, NULL
); /* this one cannot fail */
353 * change object position and update references
354 * XXX this one is never used!
357 heap_move(struct dn_heap
*h
, dn_key new_key
, void *object
)
361 int maxelt
= h
->elements
-1 ;
362 struct dn_heap_entry buf
;
365 panic("cannot move items on this heap");
367 i
= *((int *)((char *)object
+ h
->offset
));
368 if (DN_KEY_LT(new_key
, h
->p
[i
].key
) ) { /* must move up */
369 h
->p
[i
].key
= new_key
;
370 for (; i
>0 && DN_KEY_LT(new_key
, h
->p
[(temp
= HEAP_FATHER(i
))].key
) ;
371 i
= temp
) { /* bubble up */
372 HEAP_SWAP(h
->p
[i
], h
->p
[temp
], buf
) ;
375 } else { /* must move down */
376 h
->p
[i
].key
= new_key
;
377 while ( (temp
= HEAP_LEFT(i
)) <= maxelt
) { /* found left child */
378 if ((temp
!= maxelt
) && DN_KEY_GT(h
->p
[temp
].key
, h
->p
[temp
+1].key
))
379 temp
++ ; /* select child with min key */
380 if (DN_KEY_GT(new_key
, h
->p
[temp
].key
)) { /* go down */
381 HEAP_SWAP(h
->p
[i
], h
->p
[temp
], buf
) ;
390 #endif /* heap_move, unused */
393 * heapify() will reorganize data inside an array to maintain the
394 * heap property. It is needed when we delete a bunch of entries.
397 heapify(struct dn_heap
*h
)
401 for (i
= 0 ; i
< h
->elements
; i
++ )
402 heap_insert(h
, i
, NULL
) ;
406 * cleanup the heap and free data structure
409 heap_free(struct dn_heap
*h
)
412 FREE(h
->p
, M_DUMMYNET
);
413 bzero(h
, sizeof(*h
));
417 * --- end of heap management functions ---
421 * Return the mbuf tag holding the dummynet state. As an optimization
422 * this is assumed to be the first tag on the list. If this turns out
423 * wrong we'll need to search the list.
425 static struct dn_pkt_tag
*
426 dn_tag_get(struct mbuf
*m
)
428 struct m_tag
*mtag
= m_tag_first(m
);
429 /* KASSERT(mtag != NULL &&
430 mtag->m_tag_id == KERNEL_MODULE_TAG_ID &&
431 mtag->m_tag_type == KERNEL_TAG_TYPE_DUMMYNET,
432 ("packet on dummynet queue w/o dummynet tag!"));
434 return (struct dn_pkt_tag
*)(mtag
+1);
438 * Scheduler functions:
440 * transmit_event() is called when the delay-line needs to enter
441 * the scheduler, either because of existing pkts getting ready,
442 * or new packets entering the queue. The event handled is the delivery
443 * time of the packet.
445 * ready_event() does something similar with fixed-rate queues, and the
446 * event handled is the finish time of the head pkt.
448 * wfq_ready_event() does something similar with WF2Q queues, and the
449 * event handled is the start time of the head pkt.
451 * In all cases, we make sure that the data structures are consistent
452 * before passing pkts out, because this might trigger recursive
453 * invocations of the procedures.
456 transmit_event(struct dn_pipe
*pipe
)
459 struct dn_pkt_tag
*pkt
;
461 lck_mtx_assert(dn_mutex
, LCK_MTX_ASSERT_OWNED
);
463 while ( (m
= pipe
->head
) ) {
465 if ( !DN_KEY_LEQ(pkt
->output_time
, curr_time
) )
468 * first unlink, then call procedures, since ip_input() can invoke
469 * ip_output() and viceversa, thus causing nested calls
471 pipe
->head
= m
->m_nextpkt
;
474 /* XXX: drop the lock for now to avoid LOR's */
475 lck_mtx_unlock(dn_mutex
);
476 switch (pkt
->dn_dir
) {
478 struct route tmp_rt
= pkt
->ro
;
479 (void)ip_output(m
, NULL
, NULL
, pkt
->flags
, NULL
, NULL
);
481 rtfree(tmp_rt
.ro_rt
);
486 proto_inject(PF_INET
, m
);
492 * The bridge requires/assumes the Ethernet header is
493 * contiguous in the first mbuf header. Insure this is true.
496 if (m
->m_len
< ETHER_HDR_LEN
&&
497 (m
= m_pullup(m
, ETHER_HDR_LEN
)) == NULL
) {
498 printf("dummynet/bridge: pullup fail, dropping pkt\n");
501 m
= bdg_forward_ptr(m
, pkt
->ifp
);
503 /* somebody unloaded the bridge module. Drop pkt */
505 printf("dummynet: dropping bridged packet trapped in pipe\n");
512 printf("dummynet: bad switch %d!\n", pkt
->dn_dir
);
516 lck_mtx_lock(dn_mutex
);
518 /* if there are leftover packets, put into the heap for next event */
519 if ( (m
= pipe
->head
) ) {
521 /* XXX should check errors on heap_insert, by draining the
522 * whole pipe p and hoping in the future we are more successful
524 heap_insert(&extract_heap
, pkt
->output_time
, pipe
);
529 * the following macro computes how many ticks we have to wait
530 * before being able to transmit a packet. The credit is taken from
531 * either a pipe (WF2Q) or a flow_queue (per-flow queueing)
534 /* hz is 100, which gives a granularity of 10ms in the old timer.
535 * The timer has been changed to fire every 1ms, so the use of
536 * hz has been modified here. All instances of hz have been left
537 * in place but adjusted by a factor of 10 so that hz is functionally
540 #define SET_TICKS(_m, q, p) \
541 ((_m)->m_pkthdr.len*8*(hz*10) - (q)->numbytes + p->bandwidth - 1 ) / \
545 * extract pkt from queue, compute output time (could be now)
546 * and put into delay line (p_queue)
549 move_pkt(struct mbuf
*pkt
, struct dn_flow_queue
*q
,
550 struct dn_pipe
*p
, int len
)
552 struct dn_pkt_tag
*dt
= dn_tag_get(pkt
);
554 q
->head
= pkt
->m_nextpkt
;
556 q
->len_bytes
-= len
;
558 dt
->output_time
= curr_time
+ p
->delay
;
563 p
->tail
->m_nextpkt
= pkt
;
565 p
->tail
->m_nextpkt
= NULL
;
569 * ready_event() is invoked every time the queue must enter the
570 * scheduler, either because the first packet arrives, or because
571 * a previously scheduled event fired.
572 * On invokation, drain as many pkts as possible (could be 0) and then
573 * if there are leftover packets reinsert the pkt in the scheduler.
576 ready_event(struct dn_flow_queue
*q
)
579 struct dn_pipe
*p
= q
->fs
->pipe
;
582 lck_mtx_assert(dn_mutex
, LCK_MTX_ASSERT_OWNED
);
585 printf("dummynet: ready_event- pipe is gone\n");
588 p_was_empty
= (p
->head
== NULL
) ;
591 * schedule fixed-rate queues linked to this pipe:
592 * Account for the bw accumulated since last scheduling, then
593 * drain as many pkts as allowed by q->numbytes and move to
594 * the delay line (in p) computing output time.
595 * bandwidth==0 (no limit) means we can drain the whole queue,
596 * setting len_scaled = 0 does the job.
598 q
->numbytes
+= ( curr_time
- q
->sched_time
) * p
->bandwidth
;
599 while ( (pkt
= q
->head
) != NULL
) {
600 int len
= pkt
->m_pkthdr
.len
;
601 int len_scaled
= p
->bandwidth
? len
*8*(hz
*10) : 0 ;
602 if (len_scaled
> q
->numbytes
)
604 q
->numbytes
-= len_scaled
;
605 move_pkt(pkt
, q
, p
, len
);
608 * If we have more packets queued, schedule next ready event
609 * (can only occur when bandwidth != 0, otherwise we would have
610 * flushed the whole queue in the previous loop).
611 * To this purpose we record the current time and compute how many
612 * ticks to go for the finish time of the packet.
614 if ( (pkt
= q
->head
) != NULL
) { /* this implies bandwidth != 0 */
615 dn_key t
= SET_TICKS(pkt
, q
, p
); /* ticks i have to wait */
616 q
->sched_time
= curr_time
;
617 heap_insert(&ready_heap
, curr_time
+ t
, (void *)q
);
618 /* XXX should check errors on heap_insert, and drain the whole
619 * queue on error hoping next time we are luckier.
621 } else { /* RED needs to know when the queue becomes empty */
622 q
->q_time
= curr_time
;
626 * If the delay line was empty call transmit_event(p) now.
627 * Otherwise, the scheduler will take care of it.
634 * Called when we can transmit packets on WF2Q queues. Take pkts out of
635 * the queues at their start time, and enqueue into the delay line.
636 * Packets are drained until p->numbytes < 0. As long as
637 * len_scaled >= p->numbytes, the packet goes into the delay line
638 * with a deadline p->delay. For the last packet, if p->numbytes<0,
639 * there is an additional delay.
642 ready_event_wfq(struct dn_pipe
*p
)
644 int p_was_empty
= (p
->head
== NULL
) ;
645 struct dn_heap
*sch
= &(p
->scheduler_heap
);
646 struct dn_heap
*neh
= &(p
->not_eligible_heap
) ;
648 lck_mtx_assert(dn_mutex
, LCK_MTX_ASSERT_OWNED
);
650 if (p
->if_name
[0] == 0) /* tx clock is simulated */
651 p
->numbytes
+= ( curr_time
- p
->sched_time
) * p
->bandwidth
;
652 else { /* tx clock is for real, the ifq must be empty or this is a NOP */
653 if (p
->ifp
&& p
->ifp
->if_snd
.ifq_head
!= NULL
)
656 DPRINTF(("dummynet: pipe %d ready from %s --\n",
657 p
->pipe_nr
, p
->if_name
));
662 * While we have backlogged traffic AND credit, we need to do
663 * something on the queue.
665 while ( p
->numbytes
>=0 && (sch
->elements
>0 || neh
->elements
>0) ) {
666 if (sch
->elements
> 0) { /* have some eligible pkts to send out */
667 struct dn_flow_queue
*q
= sch
->p
[0].object
;
668 struct mbuf
*pkt
= q
->head
;
669 struct dn_flow_set
*fs
= q
->fs
;
670 u_int64_t len
= pkt
->m_pkthdr
.len
;
671 int len_scaled
= p
->bandwidth
? len
*8*(hz
*10) : 0 ;
673 heap_extract(sch
, NULL
); /* remove queue from heap */
674 p
->numbytes
-= len_scaled
;
675 move_pkt(pkt
, q
, p
, len
);
677 p
->V
+= (len
<<MY_M
) / p
->sum
; /* update V */
678 q
->S
= q
->F
; /* update start time */
679 if (q
->len
== 0) { /* Flow not backlogged any more */
681 heap_insert(&(p
->idle_heap
), q
->F
, q
);
682 } else { /* still backlogged */
684 * update F and position in backlogged queue, then
685 * put flow in not_eligible_heap (we will fix this later).
687 len
= (q
->head
)->m_pkthdr
.len
;
688 q
->F
+= (len
<<MY_M
)/(u_int64_t
) fs
->weight
;
689 if (DN_KEY_LEQ(q
->S
, p
->V
))
690 heap_insert(neh
, q
->S
, q
);
692 heap_insert(sch
, q
->F
, q
);
696 * now compute V = max(V, min(S_i)). Remember that all elements in sch
697 * have by definition S_i <= V so if sch is not empty, V is surely
698 * the max and we must not update it. Conversely, if sch is empty
699 * we only need to look at neh.
701 if (sch
->elements
== 0 && neh
->elements
> 0)
702 p
->V
= MAX64 ( p
->V
, neh
->p
[0].key
);
703 /* move from neh to sch any packets that have become eligible */
704 while (neh
->elements
> 0 && DN_KEY_LEQ(neh
->p
[0].key
, p
->V
) ) {
705 struct dn_flow_queue
*q
= neh
->p
[0].object
;
706 heap_extract(neh
, NULL
);
707 heap_insert(sch
, q
->F
, q
);
710 if (p
->if_name
[0] != '\0') {/* tx clock is from a real thing */
711 p
->numbytes
= -1 ; /* mark not ready for I/O */
715 if (sch
->elements
== 0 && neh
->elements
== 0 && p
->numbytes
>= 0
716 && p
->idle_heap
.elements
> 0) {
718 * no traffic and no events scheduled. We can get rid of idle-heap.
722 for (i
= 0 ; i
< p
->idle_heap
.elements
; i
++) {
723 struct dn_flow_queue
*q
= p
->idle_heap
.p
[i
].object
;
730 p
->idle_heap
.elements
= 0 ;
733 * If we are getting clocks from dummynet (not a real interface) and
734 * If we are under credit, schedule the next ready event.
735 * Also fix the delivery time of the last packet.
737 if (p
->if_name
[0]==0 && p
->numbytes
< 0) { /* this implies bandwidth >0 */
738 dn_key t
=0 ; /* number of ticks i have to wait */
740 if (p
->bandwidth
> 0)
741 t
= ( p
->bandwidth
-1 - p
->numbytes
) / p
->bandwidth
;
742 dn_tag_get(p
->tail
)->output_time
+= t
;
743 p
->sched_time
= curr_time
;
744 heap_insert(&wfq_ready_heap
, curr_time
+ t
, (void *)p
);
745 /* XXX should check errors on heap_insert, and drain the whole
746 * queue on error hoping next time we are luckier.
750 * If the delay line was empty call transmit_event(p) now.
751 * Otherwise, the scheduler will take care of it.
758 * This is called every 1ms. It is used to
759 * increment the current tick counter and schedule expired events.
762 dummynet(__unused
void * unused
)
764 void *p
; /* generic parameter to handler */
766 struct dn_heap
*heaps
[3];
772 heaps
[0] = &ready_heap
; /* fixed-rate queues */
773 heaps
[1] = &wfq_ready_heap
; /* wfq queues */
774 heaps
[2] = &extract_heap
; /* delay line */
776 lck_mtx_lock(dn_mutex
);
778 /* make all time measurements in milliseconds (ms) -
779 * here we convert secs and usecs to msecs (just divide the
780 * usecs and take the closest whole number).
783 curr_time
= (tv
.tv_sec
* 1000) + (tv
.tv_usec
/ 1000);
785 for (i
=0; i
< 3 ; i
++) {
787 while (h
->elements
> 0 && DN_KEY_LEQ(h
->p
[0].key
, curr_time
) ) {
788 if (h
->p
[0].key
> curr_time
)
789 printf("dummynet: warning, heap %d is %d ticks late\n",
790 i
, (int)(curr_time
- h
->p
[0].key
));
791 p
= h
->p
[0].object
; /* store a copy before heap_extract */
792 heap_extract(h
, NULL
); /* need to extract before processing */
796 struct dn_pipe
*pipe
= p
;
797 if (pipe
->if_name
[0] != '\0')
798 printf("dummynet: bad ready_event_wfq for pipe %s\n",
806 /* sweep pipes trying to expire idle flow_queues */
807 for (pe
= all_pipes
; pe
; pe
= pe
->next
)
808 if (pe
->idle_heap
.elements
> 0 &&
809 DN_KEY_LT(pe
->idle_heap
.p
[0].key
, pe
->V
) ) {
810 struct dn_flow_queue
*q
= pe
->idle_heap
.p
[0].object
;
812 heap_extract(&(pe
->idle_heap
), NULL
);
813 q
->S
= q
->F
+ 1 ; /* mark timestamp as invalid */
814 pe
->sum
-= q
->fs
->weight
;
817 /* check the heaps to see if there's still stuff in there, and
818 * only set the timer if there are packets to process
821 for (i
=0; i
< 3 ; i
++) {
823 if (h
->elements
> 0) { // set the timer
825 ts
.tv_nsec
= 1 * 1000000; // 1ms
827 bsd_timeout(dummynet
, NULL
, &ts
);
832 lck_mtx_unlock(dn_mutex
);
836 * called by an interface when tx_rdy occurs.
839 if_tx_rdy(struct ifnet
*ifp
)
843 lck_mtx_lock(dn_mutex
);
844 for (p
= all_pipes
; p
; p
= p
->next
)
849 snprintf(buf
, sizeof(buf
), "%s%d",ifp
->if_name
, ifp
->if_unit
);
850 for (p
= all_pipes
; p
; p
= p
->next
)
851 if (!strcmp(p
->if_name
, buf
) ) {
853 DPRINTF(("dummynet: ++ tx rdy from %s (now found)\n", buf
));
858 DPRINTF(("dummynet: ++ tx rdy from %s%d - qlen %d\n", ifp
->if_name
,
859 ifp
->if_unit
, ifp
->if_snd
.ifq_len
));
860 p
->numbytes
= 0 ; /* mark ready for I/O */
863 lck_mtx_lock(dn_mutex
);
869 * Unconditionally expire empty queues in case of shortage.
870 * Returns the number of queues freed.
873 expire_queues(struct dn_flow_set
*fs
)
875 struct dn_flow_queue
*q
, *prev
;
876 int i
, initial_elements
= fs
->rq_elements
;
877 struct timeval timenow
;
879 getmicrotime(&timenow
);
881 if (fs
->last_expired
== timenow
.tv_sec
)
883 fs
->last_expired
= timenow
.tv_sec
;
884 for (i
= 0 ; i
<= fs
->rq_size
; i
++) /* last one is overflow */
885 for (prev
=NULL
, q
= fs
->rq
[i
] ; q
!= NULL
; )
886 if (q
->head
!= NULL
|| q
->S
!= q
->F
+1) {
889 } else { /* entry is idle, expire it */
890 struct dn_flow_queue
*old_q
= q
;
893 prev
->next
= q
= q
->next
;
895 fs
->rq
[i
] = q
= q
->next
;
897 FREE(old_q
, M_DUMMYNET
);
899 return initial_elements
- fs
->rq_elements
;
903 * If room, create a new queue and put at head of slot i;
904 * otherwise, create or use the default queue.
906 static struct dn_flow_queue
*
907 create_queue(struct dn_flow_set
*fs
, int i
)
909 struct dn_flow_queue
*q
;
911 if (fs
->rq_elements
> fs
->rq_size
* dn_max_ratio
&&
912 expire_queues(fs
) == 0) {
914 * No way to get room, use or create overflow queue.
917 if ( fs
->rq
[i
] != NULL
)
920 q
= _MALLOC(sizeof(*q
), M_DUMMYNET
, M_DONTWAIT
| M_ZERO
);
922 printf("dummynet: sorry, cannot allocate queue for new flow\n");
927 q
->next
= fs
->rq
[i
] ;
928 q
->S
= q
->F
+ 1; /* hack - mark timestamp as invalid */
935 * Given a flow_set and a pkt in last_pkt, find a matching queue
936 * after appropriate masking. The queue is moved to front
937 * so that further searches take less time.
939 static struct dn_flow_queue
*
940 find_queue(struct dn_flow_set
*fs
, struct ipfw_flow_id
*id
)
942 int i
= 0 ; /* we need i and q for new allocations */
943 struct dn_flow_queue
*q
, *prev
;
945 if ( !(fs
->flags_fs
& DN_HAVE_FLOW_MASK
) )
948 /* first, do the masking */
949 id
->dst_ip
&= fs
->flow_mask
.dst_ip
;
950 id
->src_ip
&= fs
->flow_mask
.src_ip
;
951 id
->dst_port
&= fs
->flow_mask
.dst_port
;
952 id
->src_port
&= fs
->flow_mask
.src_port
;
953 id
->proto
&= fs
->flow_mask
.proto
;
954 id
->flags
= 0 ; /* we don't care about this one */
955 /* then, hash function */
956 i
= ( (id
->dst_ip
) & 0xffff ) ^
957 ( (id
->dst_ip
>> 15) & 0xffff ) ^
958 ( (id
->src_ip
<< 1) & 0xffff ) ^
959 ( (id
->src_ip
>> 16 ) & 0xffff ) ^
960 (id
->dst_port
<< 1) ^ (id
->src_port
) ^
962 i
= i
% fs
->rq_size
;
963 /* finally, scan the current list for a match */
965 for (prev
=NULL
, q
= fs
->rq
[i
] ; q
; ) {
967 if (id
->dst_ip
== q
->id
.dst_ip
&&
968 id
->src_ip
== q
->id
.src_ip
&&
969 id
->dst_port
== q
->id
.dst_port
&&
970 id
->src_port
== q
->id
.src_port
&&
971 id
->proto
== q
->id
.proto
&&
972 id
->flags
== q
->id
.flags
)
974 else if (pipe_expire
&& q
->head
== NULL
&& q
->S
== q
->F
+1 ) {
975 /* entry is idle and not in any heap, expire it */
976 struct dn_flow_queue
*old_q
= q
;
979 prev
->next
= q
= q
->next
;
981 fs
->rq
[i
] = q
= q
->next
;
983 FREE(old_q
, M_DUMMYNET
);
989 if (q
&& prev
!= NULL
) { /* found and not in front */
990 prev
->next
= q
->next
;
991 q
->next
= fs
->rq
[i
] ;
995 if (q
== NULL
) { /* no match, need to allocate a new entry */
996 q
= create_queue(fs
, i
);
1004 red_drops(struct dn_flow_set
*fs
, struct dn_flow_queue
*q
, int len
)
1009 * RED calculates the average queue size (avg) using a low-pass filter
1010 * with an exponential weighted (w_q) moving average:
1011 * avg <- (1-w_q) * avg + w_q * q_size
1012 * where q_size is the queue length (measured in bytes or * packets).
1014 * If q_size == 0, we compute the idle time for the link, and set
1015 * avg = (1 - w_q)^(idle/s)
1016 * where s is the time needed for transmitting a medium-sized packet.
1018 * Now, if avg < min_th the packet is enqueued.
1019 * If avg > max_th the packet is dropped. Otherwise, the packet is
1020 * dropped with probability P function of avg.
1025 /* queue in bytes or packets ? */
1026 u_int q_size
= (fs
->flags_fs
& DN_QSIZE_IS_BYTES
) ? q
->len_bytes
: q
->len
;
1028 DPRINTF(("\ndummynet: %d q: %2u ", (int) curr_time
, q_size
));
1030 /* average queue size estimation */
1033 * queue is not empty, avg <- avg + (q_size - avg) * w_q
1035 int diff
= SCALE(q_size
) - q
->avg
;
1036 int64_t v
= SCALE_MUL((int64_t) diff
, (int64_t) fs
->w_q
);
1041 * queue is empty, find for how long the queue has been
1042 * empty and use a lookup table for computing
1043 * (1 - * w_q)^(idle_time/s) where s is the time to send a
1045 * XXX check wraps...
1048 u_int t
= (curr_time
- q
->q_time
) / fs
->lookup_step
;
1050 q
->avg
= (t
< fs
->lookup_depth
) ?
1051 SCALE_MUL(q
->avg
, fs
->w_q_lookup
[t
]) : 0;
1054 DPRINTF(("dummynet: avg: %u ", SCALE_VAL(q
->avg
)));
1056 /* should i drop ? */
1058 if (q
->avg
< fs
->min_th
) {
1060 return 0; /* accept packet ; */
1062 if (q
->avg
>= fs
->max_th
) { /* average queue >= max threshold */
1063 if (fs
->flags_fs
& DN_IS_GENTLE_RED
) {
1065 * According to Gentle-RED, if avg is greater than max_th the
1066 * packet is dropped with a probability
1067 * p_b = c_3 * avg - c_4
1068 * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
1070 p_b
= SCALE_MUL((int64_t) fs
->c_3
, (int64_t) q
->avg
) - fs
->c_4
;
1073 DPRINTF(("dummynet: - drop"));
1076 } else if (q
->avg
> fs
->min_th
) {
1078 * we compute p_b using the linear dropping function p_b = c_1 *
1079 * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
1080 * max_p * min_th / (max_th - min_th)
1082 p_b
= SCALE_MUL((int64_t) fs
->c_1
, (int64_t) q
->avg
) - fs
->c_2
;
1084 if (fs
->flags_fs
& DN_QSIZE_IS_BYTES
)
1085 p_b
= (p_b
* len
) / fs
->max_pkt_size
;
1086 if (++q
->count
== 0)
1087 q
->random
= MY_RANDOM
& 0xffff;
1090 * q->count counts packets arrived since last drop, so a greater
1091 * value of q->count means a greater packet drop probability.
1093 if (SCALE_MUL(p_b
, SCALE((int64_t) q
->count
)) > q
->random
) {
1095 DPRINTF(("dummynet: - red drop"));
1096 /* after a drop we calculate a new random value */
1097 q
->random
= MY_RANDOM
& 0xffff;
1098 return 1; /* drop */
1101 /* end of RED algorithm */
1102 return 0 ; /* accept */
1106 struct dn_flow_set
*
1107 locate_flowset(int pipe_nr
, struct ip_fw
*rule
)
1109 struct dn_flow_set
*fs
;
1110 ipfw_insn
*cmd
= rule
->cmd
+ rule
->act_ofs
;
1112 if (cmd
->opcode
== O_LOG
)
1115 bcopy(& ((ipfw_insn_pipe
*)cmd
)->pipe_ptr
, &fs
, sizeof(fs
));
1120 if (cmd
->opcode
== O_QUEUE
) {
1121 for (fs
=all_flow_sets
; fs
&& fs
->fs_nr
!= pipe_nr
; fs
=fs
->next
)
1126 for (p1
= all_pipes
; p1
&& p1
->pipe_nr
!= pipe_nr
; p1
= p1
->next
)
1131 /* record for the future */
1132 bcopy(&fs
, & ((ipfw_insn_pipe
*)cmd
)->pipe_ptr
, sizeof(fs
));
1138 * dummynet hook for packets. Below 'pipe' is a pipe or a queue
1139 * depending on whether WF2Q or fixed bw is used.
1141 * pipe_nr pipe or queue the packet is destined for.
1142 * dir where shall we send the packet after dummynet.
1143 * m the mbuf with the packet
1144 * ifp the 'ifp' parameter from the caller.
1145 * NULL in ip_input, destination interface in ip_output,
1146 * real_dst in bdg_forward
1147 * ro route parameter (only used in ip_output, NULL otherwise)
1148 * dst destination address, only used by ip_output
1149 * rule matching rule, in case of multiple passes
1150 * flags flags from the caller, only used in ip_output
1154 dummynet_io(struct mbuf
*m
, int pipe_nr
, int dir
, struct ip_fw_args
*fwa
)
1156 struct dn_pkt_tag
*pkt
;
1158 struct dn_flow_set
*fs
;
1159 struct dn_pipe
*pipe
;
1160 u_int64_t len
= m
->m_pkthdr
.len
;
1161 struct dn_flow_queue
*q
= NULL
;
1167 ipfw_insn
*cmd
= fwa
->rule
->cmd
+ fwa
->rule
->act_ofs
;
1169 if (cmd
->opcode
== O_LOG
)
1171 is_pipe
= (cmd
->opcode
== O_PIPE
);
1173 is_pipe
= (fwa
->rule
->fw_flg
& IP_FW_F_COMMAND
) == IP_FW_F_PIPE
;
1178 lck_mtx_lock(dn_mutex
);
1180 /* make all time measurements in milliseconds (ms) -
1181 * here we convert secs and usecs to msecs (just divide the
1182 * usecs and take the closest whole number).
1185 curr_time
= (tv
.tv_sec
* 1000) + (tv
.tv_usec
/ 1000);
1188 * This is a dummynet rule, so we expect an O_PIPE or O_QUEUE rule.
1190 fs
= locate_flowset(pipe_nr
, fwa
->rule
);
1192 goto dropit
; /* this queue/pipe does not exist! */
1194 if (pipe
== NULL
) { /* must be a queue, try find a matching pipe */
1195 for (pipe
= all_pipes
; pipe
&& pipe
->pipe_nr
!= fs
->parent_nr
;
1201 printf("dummynet: no pipe %d for queue %d, drop pkt\n",
1202 fs
->parent_nr
, fs
->fs_nr
);
1206 q
= find_queue(fs
, &(fwa
->f_id
));
1208 goto dropit
; /* cannot allocate queue */
1210 * update statistics, then check reasons to drop pkt
1212 q
->tot_bytes
+= len
;
1214 if ( fs
->plr
&& (MY_RANDOM
< fs
->plr
) )
1215 goto dropit
; /* random pkt drop */
1216 if ( fs
->flags_fs
& DN_QSIZE_IS_BYTES
) {
1217 if (q
->len_bytes
> fs
->qsize
)
1218 goto dropit
; /* queue size overflow */
1220 if (q
->len
>= fs
->qsize
)
1221 goto dropit
; /* queue count overflow */
1223 if ( fs
->flags_fs
& DN_IS_RED
&& red_drops(fs
, q
, len
) )
1226 /* XXX expensive to zero, see if we can remove it*/
1227 mtag
= m_tag_alloc(KERNEL_MODULE_TAG_ID
, KERNEL_TAG_TYPE_DUMMYNET
,
1228 sizeof(struct dn_pkt_tag
), M_NOWAIT
);
1230 goto dropit
; /* cannot allocate packet header */
1231 m_tag_prepend(m
, mtag
); /* attach to mbuf chain */
1233 pkt
= (struct dn_pkt_tag
*)(mtag
+1);
1234 bzero(pkt
, sizeof(struct dn_pkt_tag
));
1235 /* ok, i can handle the pkt now... */
1236 /* build and enqueue packet + parameters */
1237 pkt
->rule
= fwa
->rule
;
1240 pkt
->ifp
= fwa
->oif
;
1241 if (dir
== DN_TO_IP_OUT
) {
1243 * We need to copy *ro because for ICMP pkts (and maybe others)
1244 * the caller passed a pointer into the stack; dst might also be
1245 * a pointer into *ro so it needs to be updated.
1247 lck_mtx_lock(rt_mtx
);
1248 pkt
->ro
= *(fwa
->ro
);
1250 rtref(fwa
->ro
->ro_rt
);
1251 if (fwa
->dst
== (struct sockaddr_in
*)&fwa
->ro
->ro_dst
) /* dst points into ro */
1252 fwa
->dst
= (struct sockaddr_in
*)&(pkt
->ro
.ro_dst
) ;
1253 lck_mtx_unlock(rt_mtx
);
1255 pkt
->dn_dst
= fwa
->dst
;
1256 pkt
->flags
= fwa
->flags
;
1258 if (q
->head
== NULL
)
1261 q
->tail
->m_nextpkt
= m
;
1264 q
->len_bytes
+= len
;
1266 if ( q
->head
!= m
) /* flow was not idle, we are done */
1269 * If we reach this point the flow was previously idle, so we need
1270 * to schedule it. This involves different actions for fixed-rate or
1275 * Fixed-rate queue: just insert into the ready_heap.
1278 if (pipe
->bandwidth
)
1279 t
= SET_TICKS(m
, q
, pipe
);
1280 q
->sched_time
= curr_time
;
1281 if (t
== 0) /* must process it now */
1284 heap_insert(&ready_heap
, curr_time
+ t
, q
);
1287 * WF2Q. First, compute start time S: if the flow was idle (S=F+1)
1288 * set S to the virtual time V for the controlling pipe, and update
1289 * the sum of weights for the pipe; otherwise, remove flow from
1290 * idle_heap and set S to max(F,V).
1291 * Second, compute finish time F = S + len/weight.
1292 * Third, if pipe was idle, update V=max(S, V).
1293 * Fourth, count one more backlogged flow.
1295 if (DN_KEY_GT(q
->S
, q
->F
)) { /* means timestamps are invalid */
1297 pipe
->sum
+= fs
->weight
; /* add weight of new queue */
1299 heap_extract(&(pipe
->idle_heap
), q
);
1300 q
->S
= MAX64(q
->F
, pipe
->V
) ;
1302 q
->F
= q
->S
+ ( len
<<MY_M
)/(u_int64_t
) fs
->weight
;
1304 if (pipe
->not_eligible_heap
.elements
== 0 &&
1305 pipe
->scheduler_heap
.elements
== 0)
1306 pipe
->V
= MAX64 ( q
->S
, pipe
->V
);
1309 * Look at eligibility. A flow is not eligibile if S>V (when
1310 * this happens, it means that there is some other flow already
1311 * scheduled for the same pipe, so the scheduler_heap cannot be
1312 * empty). If the flow is not eligible we just store it in the
1313 * not_eligible_heap. Otherwise, we store in the scheduler_heap
1314 * and possibly invoke ready_event_wfq() right now if there is
1316 * Note that for all flows in scheduler_heap (SCH), S_i <= V,
1317 * and for all flows in not_eligible_heap (NEH), S_i > V .
1318 * So when we need to compute max( V, min(S_i) ) forall i in SCH+NEH,
1319 * we only need to look into NEH.
1321 if (DN_KEY_GT(q
->S
, pipe
->V
) ) { /* not eligible */
1322 if (pipe
->scheduler_heap
.elements
== 0)
1323 printf("dummynet: ++ ouch! not eligible but empty scheduler!\n");
1324 heap_insert(&(pipe
->not_eligible_heap
), q
->S
, q
);
1326 heap_insert(&(pipe
->scheduler_heap
), q
->F
, q
);
1327 if (pipe
->numbytes
>= 0) { /* pipe is idle */
1328 if (pipe
->scheduler_heap
.elements
!= 1)
1329 printf("dummynet: OUCH! pipe should have been idle!\n");
1330 DPRINTF(("dummynet: waking up pipe %d at %d\n",
1331 pipe
->pipe_nr
, (int)(q
->F
>> MY_M
)));
1332 pipe
->sched_time
= curr_time
;
1333 ready_event_wfq(pipe
);
1338 /* start the timer and set global if not already set */
1339 if (!timer_enabled
) {
1341 ts
.tv_nsec
= 1 * 1000000; // 1ms
1343 bsd_timeout(dummynet
, NULL
, &ts
);
1346 lck_mtx_unlock(dn_mutex
);
1352 lck_mtx_unlock(dn_mutex
);
1354 return ( (fs
&& (fs
->flags_fs
& DN_NOERROR
)) ? 0 : ENOBUFS
);
1358 * Below, the rtfree is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
1359 * Doing this would probably save us the initial bzero of dn_pkt
1361 #define DN_FREE_PKT(_m) do { \
1362 struct m_tag *tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_DUMMYNET, NULL); \
1364 struct dn_pkt_tag *n = (struct dn_pkt_tag *)(tag+1); \
1366 rtfree(n->ro.ro_rt); \
1368 m_tag_delete(_m, tag); \
1373 * Dispose all packets and flow_queues on a flow_set.
1374 * If all=1, also remove red lookup table and other storage,
1375 * including the descriptor itself.
1376 * For the one in dn_pipe MUST also cleanup ready_heap...
1379 purge_flow_set(struct dn_flow_set
*fs
, int all
)
1381 struct dn_flow_queue
*q
, *qn
;
1384 lck_mtx_assert(dn_mutex
, LCK_MTX_ASSERT_OWNED
);
1386 for (i
= 0 ; i
<= fs
->rq_size
; i
++ ) {
1387 for (q
= fs
->rq
[i
] ; q
; q
= qn
) {
1388 struct mbuf
*m
, *mnext
;
1391 while ((m
= mnext
) != NULL
) {
1392 mnext
= m
->m_nextpkt
;
1396 FREE(q
, M_DUMMYNET
);
1400 fs
->rq_elements
= 0 ;
1402 /* RED - free lookup table */
1404 FREE(fs
->w_q_lookup
, M_DUMMYNET
);
1406 FREE(fs
->rq
, M_DUMMYNET
);
1407 /* if this fs is not part of a pipe, free it */
1408 if (fs
->pipe
&& fs
!= &(fs
->pipe
->fs
) )
1409 FREE(fs
, M_DUMMYNET
);
1414 * Dispose all packets queued on a pipe (not a flow_set).
1415 * Also free all resources associated to a pipe, which is about
1419 purge_pipe(struct dn_pipe
*pipe
)
1421 struct mbuf
*m
, *mnext
;
1423 purge_flow_set( &(pipe
->fs
), 1 );
1426 while ((m
= mnext
) != NULL
) {
1427 mnext
= m
->m_nextpkt
;
1431 heap_free( &(pipe
->scheduler_heap
) );
1432 heap_free( &(pipe
->not_eligible_heap
) );
1433 heap_free( &(pipe
->idle_heap
) );
1437 * Delete all pipes and heaps returning memory. Must also
1438 * remove references from all ipfw rules to all pipes.
1441 dummynet_flush(void)
1443 struct dn_pipe
*curr_p
, *p
;
1444 struct dn_flow_set
*fs
, *curr_fs
;
1446 lck_mtx_lock(dn_mutex
);
1448 /* remove all references to pipes ...*/
1449 flush_pipe_ptrs(NULL
);
1450 /* prevent future matches... */
1453 fs
= all_flow_sets
;
1454 all_flow_sets
= NULL
;
1455 /* and free heaps so we don't have unwanted events */
1456 heap_free(&ready_heap
);
1457 heap_free(&wfq_ready_heap
);
1458 heap_free(&extract_heap
);
1461 * Now purge all queued pkts and delete all pipes
1463 /* scan and purge all flow_sets. */
1467 purge_flow_set(curr_fs
, 1);
1473 FREE(curr_p
, M_DUMMYNET
);
1475 lck_mtx_unlock(dn_mutex
);
1479 extern struct ip_fw
*ip_fw_default_rule
;
1481 dn_rule_delete_fs(struct dn_flow_set
*fs
, void *r
)
1484 struct dn_flow_queue
*q
;
1487 for (i
= 0 ; i
<= fs
->rq_size
; i
++) /* last one is ovflow */
1488 for (q
= fs
->rq
[i
] ; q
; q
= q
->next
)
1489 for (m
= q
->head
; m
; m
= m
->m_nextpkt
) {
1490 struct dn_pkt_tag
*pkt
= dn_tag_get(m
) ;
1492 pkt
->rule
= ip_fw_default_rule
;
1496 * when a firewall rule is deleted, scan all queues and remove the flow-id
1497 * from packets matching this rule.
1500 dn_rule_delete(void *r
)
1503 struct dn_flow_set
*fs
;
1504 struct dn_pkt_tag
*pkt
;
1507 lck_mtx_lock(dn_mutex
);
1510 * If the rule references a queue (dn_flow_set), then scan
1511 * the flow set, otherwise scan pipes. Should do either, but doing
1512 * both does not harm.
1514 for ( fs
= all_flow_sets
; fs
; fs
= fs
->next
)
1515 dn_rule_delete_fs(fs
, r
);
1516 for ( p
= all_pipes
; p
; p
= p
->next
) {
1518 dn_rule_delete_fs(fs
, r
);
1519 for (m
= p
->head
; m
; m
= m
->m_nextpkt
) {
1520 pkt
= dn_tag_get(m
) ;
1522 pkt
->rule
= ip_fw_default_rule
;
1525 lck_mtx_unlock(dn_mutex
);
1529 * setup RED parameters
1532 config_red(struct dn_flow_set
*p
, struct dn_flow_set
* x
)
1537 x
->min_th
= SCALE(p
->min_th
);
1538 x
->max_th
= SCALE(p
->max_th
);
1539 x
->max_p
= p
->max_p
;
1541 x
->c_1
= p
->max_p
/ (p
->max_th
- p
->min_th
);
1542 x
->c_2
= SCALE_MUL(x
->c_1
, SCALE(p
->min_th
));
1543 if (x
->flags_fs
& DN_IS_GENTLE_RED
) {
1544 x
->c_3
= (SCALE(1) - p
->max_p
) / p
->max_th
;
1545 x
->c_4
= (SCALE(1) - 2 * p
->max_p
);
1548 /* if the lookup table already exist, free and create it again */
1549 if (x
->w_q_lookup
) {
1550 FREE(x
->w_q_lookup
, M_DUMMYNET
);
1551 x
->w_q_lookup
= NULL
;
1553 if (red_lookup_depth
== 0) {
1554 printf("\ndummynet: net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
1555 FREE(x
, M_DUMMYNET
);
1558 x
->lookup_depth
= red_lookup_depth
;
1559 x
->w_q_lookup
= (u_int
*) _MALLOC(x
->lookup_depth
* sizeof(int),
1560 M_DUMMYNET
, M_DONTWAIT
);
1561 if (x
->w_q_lookup
== NULL
) {
1562 printf("dummynet: sorry, cannot allocate red lookup table\n");
1563 FREE(x
, M_DUMMYNET
);
1567 /* fill the lookup table with (1 - w_q)^x */
1568 x
->lookup_step
= p
->lookup_step
;
1569 x
->lookup_weight
= p
->lookup_weight
;
1570 x
->w_q_lookup
[0] = SCALE(1) - x
->w_q
;
1571 for (i
= 1; i
< x
->lookup_depth
; i
++)
1572 x
->w_q_lookup
[i
] = SCALE_MUL(x
->w_q_lookup
[i
- 1], x
->lookup_weight
);
1573 if (red_avg_pkt_size
< 1)
1574 red_avg_pkt_size
= 512 ;
1575 x
->avg_pkt_size
= red_avg_pkt_size
;
1576 if (red_max_pkt_size
< 1)
1577 red_max_pkt_size
= 1500 ;
1578 x
->max_pkt_size
= red_max_pkt_size
;
1583 alloc_hash(struct dn_flow_set
*x
, struct dn_flow_set
*pfs
)
1585 if (x
->flags_fs
& DN_HAVE_FLOW_MASK
) { /* allocate some slots */
1586 int l
= pfs
->rq_size
;
1592 else if (l
> DN_MAX_HASH_SIZE
)
1593 l
= DN_MAX_HASH_SIZE
;
1595 } else /* one is enough for null mask */
1597 x
->rq
= _MALLOC((1 + x
->rq_size
) * sizeof(struct dn_flow_queue
*),
1598 M_DUMMYNET
, M_DONTWAIT
| M_ZERO
);
1599 if (x
->rq
== NULL
) {
1600 printf("dummynet: sorry, cannot allocate queue\n");
1608 set_fs_parms(struct dn_flow_set
*x
, struct dn_flow_set
*src
)
1610 x
->flags_fs
= src
->flags_fs
;
1611 x
->qsize
= src
->qsize
;
1613 x
->flow_mask
= src
->flow_mask
;
1614 if (x
->flags_fs
& DN_QSIZE_IS_BYTES
) {
1615 if (x
->qsize
> 1024*1024)
1616 x
->qsize
= 1024*1024 ;
1623 /* configuring RED */
1624 if ( x
->flags_fs
& DN_IS_RED
)
1625 config_red(src
, x
) ; /* XXX should check errors */
1629 * setup pipe or queue parameters.
1633 config_pipe(struct dn_pipe
*p
)
1636 struct dn_flow_set
*pfs
= &(p
->fs
);
1637 struct dn_flow_queue
*q
;
1640 * The config program passes parameters as follows:
1641 * bw = bits/second (0 means no limits),
1642 * delay = ms, must be translated into ticks.
1643 * qsize = slots/bytes
1645 p
->delay
= ( p
->delay
* (hz
*10) ) / 1000 ;
1646 /* We need either a pipe number or a flow_set number */
1647 if (p
->pipe_nr
== 0 && pfs
->fs_nr
== 0)
1649 if (p
->pipe_nr
!= 0 && pfs
->fs_nr
!= 0)
1651 if (p
->pipe_nr
!= 0) { /* this is a pipe */
1652 struct dn_pipe
*x
, *a
, *b
;
1654 lck_mtx_lock(dn_mutex
);
1656 for (a
= NULL
, b
= all_pipes
; b
&& b
->pipe_nr
< p
->pipe_nr
;
1657 a
= b
, b
= b
->next
) ;
1659 if (b
== NULL
|| b
->pipe_nr
!= p
->pipe_nr
) { /* new pipe */
1660 x
= _MALLOC(sizeof(struct dn_pipe
), M_DUMMYNET
, M_DONTWAIT
| M_ZERO
) ;
1662 lck_mtx_unlock(dn_mutex
);
1663 printf("dummynet: no memory for new pipe\n");
1666 x
->pipe_nr
= p
->pipe_nr
;
1668 /* idle_heap is the only one from which we extract from the middle.
1670 x
->idle_heap
.size
= x
->idle_heap
.elements
= 0 ;
1671 x
->idle_heap
.offset
=OFFSET_OF(struct dn_flow_queue
, heap_pos
);
1674 /* Flush accumulated credit for all queues */
1675 for (i
= 0; i
<= x
->fs
.rq_size
; i
++)
1676 for (q
= x
->fs
.rq
[i
]; q
; q
= q
->next
)
1680 x
->bandwidth
= p
->bandwidth
;
1681 x
->numbytes
= 0; /* just in case... */
1682 bcopy(p
->if_name
, x
->if_name
, sizeof(p
->if_name
) );
1683 x
->ifp
= NULL
; /* reset interface ptr */
1684 x
->delay
= p
->delay
;
1685 set_fs_parms(&(x
->fs
), pfs
);
1688 if ( x
->fs
.rq
== NULL
) { /* a new pipe */
1689 r
= alloc_hash(&(x
->fs
), pfs
) ;
1691 lck_mtx_unlock(dn_mutex
);
1692 FREE(x
, M_DUMMYNET
);
1701 lck_mtx_unlock(dn_mutex
);
1702 } else { /* config queue */
1703 struct dn_flow_set
*x
, *a
, *b
;
1705 lck_mtx_lock(dn_mutex
);
1706 /* locate flow_set */
1707 for (a
=NULL
, b
=all_flow_sets
; b
&& b
->fs_nr
< pfs
->fs_nr
;
1708 a
= b
, b
= b
->next
) ;
1710 if (b
== NULL
|| b
->fs_nr
!= pfs
->fs_nr
) { /* new */
1711 if (pfs
->parent_nr
== 0) { /* need link to a pipe */
1712 lck_mtx_unlock(dn_mutex
);
1715 x
= _MALLOC(sizeof(struct dn_flow_set
), M_DUMMYNET
, M_DONTWAIT
| M_ZERO
);
1717 lck_mtx_unlock(dn_mutex
);
1718 printf("dummynet: no memory for new flow_set\n");
1721 x
->fs_nr
= pfs
->fs_nr
;
1722 x
->parent_nr
= pfs
->parent_nr
;
1723 x
->weight
= pfs
->weight
;
1726 else if (x
->weight
> 100)
1729 /* Change parent pipe not allowed; must delete and recreate */
1730 if (pfs
->parent_nr
!= 0 && b
->parent_nr
!= pfs
->parent_nr
) {
1731 lck_mtx_unlock(dn_mutex
);
1736 set_fs_parms(x
, pfs
);
1738 if ( x
->rq
== NULL
) { /* a new flow_set */
1739 r
= alloc_hash(x
, pfs
) ;
1741 lck_mtx_unlock(dn_mutex
);
1742 FREE(x
, M_DUMMYNET
);
1751 lck_mtx_unlock(dn_mutex
);
1757 * Helper function to remove from a heap queues which are linked to
1758 * a flow_set about to be deleted.
1761 fs_remove_from_heap(struct dn_heap
*h
, struct dn_flow_set
*fs
)
1763 int i
= 0, found
= 0 ;
1764 for (; i
< h
->elements
;)
1765 if ( ((struct dn_flow_queue
*)h
->p
[i
].object
)->fs
== fs
) {
1767 h
->p
[i
] = h
->p
[h
->elements
] ;
1776 * helper function to remove a pipe from a heap (can be there at most once)
1779 pipe_remove_from_heap(struct dn_heap
*h
, struct dn_pipe
*p
)
1781 if (h
->elements
> 0) {
1783 for (i
=0; i
< h
->elements
; i
++ ) {
1784 if (h
->p
[i
].object
== p
) { /* found it */
1786 h
->p
[i
] = h
->p
[h
->elements
] ;
1795 * drain all queues. Called in case of severe mbuf shortage.
1798 dummynet_drain(void)
1800 struct dn_flow_set
*fs
;
1802 struct mbuf
*m
, *mnext
;
1804 lck_mtx_assert(dn_mutex
, LCK_MTX_ASSERT_OWNED
);
1806 heap_free(&ready_heap
);
1807 heap_free(&wfq_ready_heap
);
1808 heap_free(&extract_heap
);
1809 /* remove all references to this pipe from flow_sets */
1810 for (fs
= all_flow_sets
; fs
; fs
= fs
->next
)
1811 purge_flow_set(fs
, 0);
1813 for (p
= all_pipes
; p
; p
= p
->next
) {
1814 purge_flow_set(&(p
->fs
), 0);
1817 while ((m
= mnext
) != NULL
) {
1818 mnext
= m
->m_nextpkt
;
1821 p
->head
= p
->tail
= NULL
;
1826 * Fully delete a pipe or a queue, cleaning up associated info.
1829 delete_pipe(struct dn_pipe
*p
)
1831 if (p
->pipe_nr
== 0 && p
->fs
.fs_nr
== 0)
1833 if (p
->pipe_nr
!= 0 && p
->fs
.fs_nr
!= 0)
1835 if (p
->pipe_nr
!= 0) { /* this is an old-style pipe */
1836 struct dn_pipe
*a
, *b
;
1837 struct dn_flow_set
*fs
;
1839 lck_mtx_lock(dn_mutex
);
1841 for (a
= NULL
, b
= all_pipes
; b
&& b
->pipe_nr
< p
->pipe_nr
;
1842 a
= b
, b
= b
->next
) ;
1843 if (b
== NULL
|| (b
->pipe_nr
!= p
->pipe_nr
) ) {
1844 lck_mtx_unlock(dn_mutex
);
1845 return EINVAL
; /* not found */
1848 /* unlink from list of pipes */
1850 all_pipes
= b
->next
;
1853 /* remove references to this pipe from the ip_fw rules. */
1854 flush_pipe_ptrs(&(b
->fs
));
1856 /* remove all references to this pipe from flow_sets */
1857 for (fs
= all_flow_sets
; fs
; fs
= fs
->next
)
1858 if (fs
->pipe
== b
) {
1859 printf("dummynet: ++ ref to pipe %d from fs %d\n",
1860 p
->pipe_nr
, fs
->fs_nr
);
1862 purge_flow_set(fs
, 0);
1864 fs_remove_from_heap(&ready_heap
, &(b
->fs
));
1865 purge_pipe(b
); /* remove all data associated to this pipe */
1866 /* remove reference to here from extract_heap and wfq_ready_heap */
1867 pipe_remove_from_heap(&extract_heap
, b
);
1868 pipe_remove_from_heap(&wfq_ready_heap
, b
);
1869 lck_mtx_unlock(dn_mutex
);
1871 FREE(b
, M_DUMMYNET
);
1872 } else { /* this is a WF2Q queue (dn_flow_set) */
1873 struct dn_flow_set
*a
, *b
;
1875 lck_mtx_lock(dn_mutex
);
1877 for (a
= NULL
, b
= all_flow_sets
; b
&& b
->fs_nr
< p
->fs
.fs_nr
;
1878 a
= b
, b
= b
->next
) ;
1879 if (b
== NULL
|| (b
->fs_nr
!= p
->fs
.fs_nr
) ) {
1880 lck_mtx_unlock(dn_mutex
);
1881 return EINVAL
; /* not found */
1885 all_flow_sets
= b
->next
;
1888 /* remove references to this flow_set from the ip_fw rules. */
1891 if (b
->pipe
!= NULL
) {
1892 /* Update total weight on parent pipe and cleanup parent heaps */
1893 b
->pipe
->sum
-= b
->weight
* b
->backlogged
;
1894 fs_remove_from_heap(&(b
->pipe
->not_eligible_heap
), b
);
1895 fs_remove_from_heap(&(b
->pipe
->scheduler_heap
), b
);
1896 #if 1 /* XXX should i remove from idle_heap as well ? */
1897 fs_remove_from_heap(&(b
->pipe
->idle_heap
), b
);
1900 purge_flow_set(b
, 1);
1901 lck_mtx_unlock(dn_mutex
);
1907 * helper function used to copy data from kernel in DUMMYNET_GET
1910 dn_copy_set(struct dn_flow_set
*set
, char *bp
)
1913 struct dn_flow_queue
*q
, *qp
= (struct dn_flow_queue
*)bp
;
1915 lck_mtx_assert(dn_mutex
, LCK_MTX_ASSERT_OWNED
);
1917 for (i
= 0 ; i
<= set
->rq_size
; i
++)
1918 for (q
= set
->rq
[i
] ; q
; q
= q
->next
, qp
++ ) {
1919 if (q
->hash_slot
!= i
)
1920 printf("dummynet: ++ at %d: wrong slot (have %d, "
1921 "should be %d)\n", copied
, q
->hash_slot
, i
);
1923 printf("dummynet: ++ at %d: wrong fs ptr (have %p, should be %p)\n",
1926 bcopy(q
, qp
, sizeof(*q
));
1927 /* cleanup pointers */
1929 qp
->head
= qp
->tail
= NULL
;
1932 if (copied
!= set
->rq_elements
)
1933 printf("dummynet: ++ wrong count, have %d should be %d\n",
1934 copied
, set
->rq_elements
);
1941 struct dn_flow_set
*set
;
1945 lck_mtx_assert(dn_mutex
, LCK_MTX_ASSERT_OWNED
);
1948 * compute size of data structures: list of pipes and flow_sets.
1950 for (p
= all_pipes
, size
= 0 ; p
; p
= p
->next
)
1951 size
+= sizeof(*p
) +
1952 p
->fs
.rq_elements
* sizeof(struct dn_flow_queue
);
1953 for (set
= all_flow_sets
; set
; set
= set
->next
)
1954 size
+= sizeof(*set
) +
1955 set
->rq_elements
* sizeof(struct dn_flow_queue
);
1960 dummynet_get(struct sockopt
*sopt
)
1962 char *buf
, *bp
; /* bp is the "copy-pointer" */
1964 struct dn_flow_set
*set
;
1968 /* XXX lock held too long */
1969 lck_mtx_lock(dn_mutex
);
1971 * XXX: Ugly, but we need to allocate memory with M_WAITOK flag and we
1972 * cannot use this flag while holding a mutex.
1974 for (i
= 0; i
< 10; i
++) {
1975 size
= dn_calc_size();
1976 lck_mtx_unlock(dn_mutex
);
1977 buf
= _MALLOC(size
, M_TEMP
, M_WAITOK
);
1978 lck_mtx_lock(dn_mutex
);
1979 if (size
== dn_calc_size())
1985 lck_mtx_unlock(dn_mutex
);
1988 for (p
= all_pipes
, bp
= buf
; p
; p
= p
->next
) {
1989 struct dn_pipe
*pipe_bp
= (struct dn_pipe
*)bp
;
1992 * copy pipe descriptor into *bp, convert delay back to ms,
1993 * then copy the flow_set descriptor(s) one at a time.
1994 * After each flow_set, copy the queue descriptor it owns.
1996 bcopy(p
, bp
, sizeof(*p
));
1997 pipe_bp
->delay
= (pipe_bp
->delay
* 1000) / (hz
*10) ;
1999 * XXX the following is a hack based on ->next being the
2000 * first field in dn_pipe and dn_flow_set. The correct
2001 * solution would be to move the dn_flow_set to the beginning
2002 * of struct dn_pipe.
2004 pipe_bp
->next
= (struct dn_pipe
*)DN_IS_PIPE
;
2005 /* clean pointers */
2006 pipe_bp
->head
= pipe_bp
->tail
= NULL
;
2007 pipe_bp
->fs
.next
= NULL
;
2008 pipe_bp
->fs
.pipe
= NULL
;
2009 pipe_bp
->fs
.rq
= NULL
;
2012 bp
= dn_copy_set( &(p
->fs
), bp
);
2014 for (set
= all_flow_sets
; set
; set
= set
->next
) {
2015 struct dn_flow_set
*fs_bp
= (struct dn_flow_set
*)bp
;
2016 bcopy(set
, bp
, sizeof(*set
));
2017 /* XXX same hack as above */
2018 fs_bp
->next
= (struct dn_flow_set
*)DN_IS_QUEUE
;
2019 fs_bp
->pipe
= NULL
;
2022 bp
= dn_copy_set( set
, bp
);
2024 lck_mtx_unlock(dn_mutex
);
2026 error
= sooptcopyout(sopt
, buf
, size
);
2032 * Handler for the various dummynet socket options (get, flush, config, del)
2035 ip_dn_ctl(struct sockopt
*sopt
)
2038 struct dn_pipe
*p
, tmp_pipe
;
2040 /* Disallow sets in really-really secure mode. */
2041 if (sopt
->sopt_dir
== SOPT_SET
&& securelevel
>= 3)
2044 switch (sopt
->sopt_name
) {
2046 printf("dummynet: -- unknown option %d", sopt
->sopt_name
);
2049 case IP_DUMMYNET_GET
:
2050 error
= dummynet_get(sopt
);
2053 case IP_DUMMYNET_FLUSH
:
2057 case IP_DUMMYNET_CONFIGURE
:
2059 error
= sooptcopyin(sopt
, p
, sizeof(*p
), sizeof(*p
));
2062 error
= config_pipe(p
);
2065 case IP_DUMMYNET_DEL
: /* remove a pipe or queue */
2067 error
= sooptcopyin(sopt
, p
, sizeof(*p
), sizeof(*p
));
2071 error
= delete_pipe(p
);
2081 dn_mutex_grp_attr
= lck_grp_attr_alloc_init();
2082 dn_mutex_grp
= lck_grp_alloc_init("dn", dn_mutex_grp_attr
);
2083 dn_mutex_attr
= lck_attr_alloc_init();
2085 if ((dn_mutex
= lck_mtx_alloc_init(dn_mutex_grp
, dn_mutex_attr
)) == NULL
) {
2086 printf("ip_dn_init: can't alloc dn_mutex\n");
2091 all_flow_sets
= NULL
;
2092 ready_heap
.size
= ready_heap
.elements
= 0 ;
2093 ready_heap
.offset
= 0 ;
2095 wfq_ready_heap
.size
= wfq_ready_heap
.elements
= 0 ;
2096 wfq_ready_heap
.offset
= 0 ;
2098 extract_heap
.size
= extract_heap
.elements
= 0 ;
2099 extract_heap
.offset
= 0 ;
2100 ip_dn_ctl_ptr
= ip_dn_ctl
;
2101 ip_dn_io_ptr
= dummynet_io
;
2102 ip_dn_ruledel_ptr
= dn_rule_delete
;