]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/ip_dummynet.c
e6cbb972203e82111e14d5b67818ba269a65dd21
[apple/xnu.git] / bsd / netinet / ip_dummynet.c
1 /*
2 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_OSREFERENCE_HEADER_START@
5 *
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
10 * License may not be used to create, or enable the creation or
11 * redistribution of, unlawful or unlicensed copies of an Apple operating
12 * system, or to circumvent, violate, or enable the circumvention or
13 * violation of, any terms of an Apple operating system software license
14 * agreement.
15 *
16 * Please obtain a copy of the License at
17 * http://www.opensource.apple.com/apsl/ and read it before using this
18 * file.
19 *
20 * The Original Code and all software distributed under the License are
21 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
22 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
23 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
25 * Please see the License for the specific language governing rights and
26 * limitations under the License.
27 *
28 * @APPLE_LICENSE_OSREFERENCE_HEADER_END@
29 */
30 /*
31 * Copyright (c) 1998-2002 Luigi Rizzo, Universita` di Pisa
32 * Portions Copyright (c) 2000 Akamba Corp.
33 * All rights reserved
34 *
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
37 * are met:
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 * notice, this list of conditions and the following disclaimer in the
42 * documentation and/or other materials provided with the distribution.
43 *
44 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
45 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
47 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
48 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
49 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
50 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
52 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
53 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * SUCH DAMAGE.
55 *
56 * $FreeBSD: src/sys/netinet/ip_dummynet.c,v 1.84 2004/08/25 09:31:30 pjd Exp $
57 */
58
59 #define DUMMYNET_DEBUG
60
61 /*
62 * This module implements IP dummynet, a bandwidth limiter/delay emulator
63 * used in conjunction with the ipfw package.
64 * Description of the data structures used is in ip_dummynet.h
65 * Here you mainly find the following blocks of code:
66 * + variable declarations;
67 * + heap management functions;
68 * + scheduler and dummynet functions;
69 * + configuration and initialization.
70 *
71 * NOTA BENE: critical sections are protected by the "dummynet lock".
72 *
73 * Most important Changes:
74 *
75 * 010124: Fixed WF2Q behaviour
76 * 010122: Fixed spl protection.
77 * 000601: WF2Q support
78 * 000106: large rewrite, use heaps to handle very many pipes.
79 * 980513: initial release
80 *
81 * include files marked with XXX are probably not needed
82 */
83
84 #include <sys/param.h>
85 #include <sys/systm.h>
86 #include <sys/malloc.h>
87 #include <sys/mbuf.h>
88 #include <sys/queue.h> /* XXX */
89 #include <sys/kernel.h>
90 #include <sys/socket.h>
91 #include <sys/socketvar.h>
92 #include <sys/time.h>
93 #include <sys/sysctl.h>
94 #include <net/if.h>
95 #include <net/route.h>
96 #include <net/kpi_protocol.h>
97 #include <netinet/in.h>
98 #include <netinet/in_systm.h>
99 #include <netinet/in_var.h>
100 #include <netinet/ip.h>
101 #include <netinet/ip_fw.h>
102 #include <netinet/ip_dummynet.h>
103 #include <netinet/ip_var.h>
104
105 #if BRIDGE
106 #include <netinet/if_ether.h> /* for struct arpcom */
107 #include <net/bridge.h>
108 #endif
109
110 /*
111 * We keep a private variable for the simulation time, but we could
112 * probably use an existing one ("softticks" in sys/kern/kern_timer.c)
113 */
114 static dn_key curr_time = 0 ; /* current simulation time */
115
116 static int dn_hash_size = 64 ; /* default hash size */
117
118 /* statistics on number of queue searches and search steps */
119 static int searches, search_steps ;
120 static int pipe_expire = 1 ; /* expire queue if empty */
121 static int dn_max_ratio = 16 ; /* max queues/buckets ratio */
122
123 static int red_lookup_depth = 256; /* RED - default lookup table depth */
124 static int red_avg_pkt_size = 512; /* RED - default medium packet size */
125 static int red_max_pkt_size = 1500; /* RED - default max packet size */
126
127 /*
128 * Three heaps contain queues and pipes that the scheduler handles:
129 *
130 * ready_heap contains all dn_flow_queue related to fixed-rate pipes.
131 *
132 * wfq_ready_heap contains the pipes associated with WF2Q flows
133 *
134 * extract_heap contains pipes associated with delay lines.
135 *
136 */
137 static struct dn_heap ready_heap, extract_heap, wfq_ready_heap ;
138
139 static int heap_init(struct dn_heap *h, int size) ;
140 static int heap_insert (struct dn_heap *h, dn_key key1, void *p);
141 static void heap_extract(struct dn_heap *h, void *obj);
142
143 static void transmit_event(struct dn_pipe *pipe);
144 static void ready_event(struct dn_flow_queue *q);
145
146 static struct dn_pipe *all_pipes = NULL ; /* list of all pipes */
147 static struct dn_flow_set *all_flow_sets = NULL ;/* list of all flow_sets */
148
149 #ifdef SYSCTL_NODE
150 SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet,
151 CTLFLAG_RW, 0, "Dummynet");
152 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, hash_size,
153 CTLFLAG_RW, &dn_hash_size, 0, "Default hash table size");
154 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, curr_time,
155 CTLFLAG_RD, &curr_time, 0, "Current tick");
156 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, ready_heap,
157 CTLFLAG_RD, &ready_heap.size, 0, "Size of ready heap");
158 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, extract_heap,
159 CTLFLAG_RD, &extract_heap.size, 0, "Size of extract heap");
160 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, searches,
161 CTLFLAG_RD, &searches, 0, "Number of queue searches");
162 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, search_steps,
163 CTLFLAG_RD, &search_steps, 0, "Number of queue search steps");
164 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, expire,
165 CTLFLAG_RW, &pipe_expire, 0, "Expire queue if empty");
166 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, max_chain_len,
167 CTLFLAG_RW, &dn_max_ratio, 0,
168 "Max ratio between dynamic queues and buckets");
169 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
170 CTLFLAG_RD, &red_lookup_depth, 0, "Depth of RED lookup table");
171 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
172 CTLFLAG_RD, &red_avg_pkt_size, 0, "RED Medium packet size");
173 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
174 CTLFLAG_RD, &red_max_pkt_size, 0, "RED Max packet size");
175 #endif
176
177 #ifdef DUMMYNET_DEBUG
178 int dummynet_debug = 0;
179 #ifdef SYSCTL_NODE
180 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug, CTLFLAG_RW, &dummynet_debug,
181 0, "control debugging printfs");
182 #endif
183 #define DPRINTF(X) if (dummynet_debug) printf X
184 #else
185 #define DPRINTF(X)
186 #endif
187
188 /* dummynet lock */
189 lck_grp_t *dn_mutex_grp;
190 lck_grp_attr_t *dn_mutex_grp_attr;
191 lck_attr_t *dn_mutex_attr;
192 lck_mtx_t *dn_mutex;
193
194 static int config_pipe(struct dn_pipe *p);
195 static int ip_dn_ctl(struct sockopt *sopt);
196
197 static void dummynet(void *);
198 static void dummynet_flush(void);
199 void dummynet_drain(void);
200 static ip_dn_io_t dummynet_io;
201 static void dn_rule_delete(void *);
202
203 int if_tx_rdy(struct ifnet *ifp);
204
205 extern lck_mtx_t *rt_mtx; /* route global lock */
206
207 /*
208 * Heap management functions.
209 *
210 * In the heap, first node is element 0. Children of i are 2i+1 and 2i+2.
211 * Some macros help finding parent/children so we can optimize them.
212 *
213 * heap_init() is called to expand the heap when needed.
214 * Increment size in blocks of 16 entries.
215 * XXX failure to allocate a new element is a pretty bad failure
216 * as we basically stall a whole queue forever!!
217 * Returns 1 on error, 0 on success
218 */
219 #define HEAP_FATHER(x) ( ( (x) - 1 ) / 2 )
220 #define HEAP_LEFT(x) ( 2*(x) + 1 )
221 #define HEAP_IS_LEFT(x) ( (x) & 1 )
222 #define HEAP_RIGHT(x) ( 2*(x) + 2 )
223 #define HEAP_SWAP(a, b, buffer) { buffer = a ; a = b ; b = buffer ; }
224 #define HEAP_INCREMENT 15
225
226 static int
227 heap_init(struct dn_heap *h, int new_size)
228 {
229 struct dn_heap_entry *p;
230
231 if (h->size >= new_size ) {
232 printf("dummynet: heap_init, Bogus call, have %d want %d\n",
233 h->size, new_size);
234 return 0 ;
235 }
236 new_size = (new_size + HEAP_INCREMENT ) & ~HEAP_INCREMENT ;
237 p = _MALLOC(new_size * sizeof(*p), M_DUMMYNET, M_DONTWAIT );
238 if (p == NULL) {
239 printf("dummynet: heap_init, resize %d failed\n", new_size );
240 return 1 ; /* error */
241 }
242 if (h->size > 0) {
243 bcopy(h->p, p, h->size * sizeof(*p) );
244 FREE(h->p, M_DUMMYNET);
245 }
246 h->p = p ;
247 h->size = new_size ;
248 return 0 ;
249 }
250
251 /*
252 * Insert element in heap. Normally, p != NULL, we insert p in
253 * a new position and bubble up. If p == NULL, then the element is
254 * already in place, and key is the position where to start the
255 * bubble-up.
256 * Returns 1 on failure (cannot allocate new heap entry)
257 *
258 * If offset > 0 the position (index, int) of the element in the heap is
259 * also stored in the element itself at the given offset in bytes.
260 */
261 #define SET_OFFSET(heap, node) \
262 if (heap->offset > 0) \
263 *((int *)((char *)(heap->p[node].object) + heap->offset)) = node ;
264 /*
265 * RESET_OFFSET is used for sanity checks. It sets offset to an invalid value.
266 */
267 #define RESET_OFFSET(heap, node) \
268 if (heap->offset > 0) \
269 *((int *)((char *)(heap->p[node].object) + heap->offset)) = -1 ;
270 static int
271 heap_insert(struct dn_heap *h, dn_key key1, void *p)
272 {
273 int son = h->elements ;
274
275 if (p == NULL) /* data already there, set starting point */
276 son = key1 ;
277 else { /* insert new element at the end, possibly resize */
278 son = h->elements ;
279 if (son == h->size) /* need resize... */
280 if (heap_init(h, h->elements+1) )
281 return 1 ; /* failure... */
282 h->p[son].object = p ;
283 h->p[son].key = key1 ;
284 h->elements++ ;
285 }
286 while (son > 0) { /* bubble up */
287 int father = HEAP_FATHER(son) ;
288 struct dn_heap_entry tmp ;
289
290 if (DN_KEY_LT( h->p[father].key, h->p[son].key ) )
291 break ; /* found right position */
292 /* son smaller than father, swap and repeat */
293 HEAP_SWAP(h->p[son], h->p[father], tmp) ;
294 SET_OFFSET(h, son);
295 son = father ;
296 }
297 SET_OFFSET(h, son);
298 return 0 ;
299 }
300
301 /*
302 * remove top element from heap, or obj if obj != NULL
303 */
304 static void
305 heap_extract(struct dn_heap *h, void *obj)
306 {
307 int child, father, max = h->elements - 1 ;
308
309 if (max < 0) {
310 printf("dummynet: warning, extract from empty heap 0x%p\n", h);
311 return ;
312 }
313 father = 0 ; /* default: move up smallest child */
314 if (obj != NULL) { /* extract specific element, index is at offset */
315 if (h->offset <= 0)
316 panic("dummynet: heap_extract from middle not supported on this heap!!!\n");
317 father = *((int *)((char *)obj + h->offset)) ;
318 if (father < 0 || father >= h->elements) {
319 printf("dummynet: heap_extract, father %d out of bound 0..%d\n",
320 father, h->elements);
321 panic("dummynet: heap_extract");
322 }
323 }
324 RESET_OFFSET(h, father);
325 child = HEAP_LEFT(father) ; /* left child */
326 while (child <= max) { /* valid entry */
327 if (child != max && DN_KEY_LT(h->p[child+1].key, h->p[child].key) )
328 child = child+1 ; /* take right child, otherwise left */
329 h->p[father] = h->p[child] ;
330 SET_OFFSET(h, father);
331 father = child ;
332 child = HEAP_LEFT(child) ; /* left child for next loop */
333 }
334 h->elements-- ;
335 if (father != max) {
336 /*
337 * Fill hole with last entry and bubble up, reusing the insert code
338 */
339 h->p[father] = h->p[max] ;
340 heap_insert(h, father, NULL); /* this one cannot fail */
341 }
342 }
343
344 #if 0
345 /*
346 * change object position and update references
347 * XXX this one is never used!
348 */
349 static void
350 heap_move(struct dn_heap *h, dn_key new_key, void *object)
351 {
352 int temp;
353 int i ;
354 int max = h->elements-1 ;
355 struct dn_heap_entry buf ;
356
357 if (h->offset <= 0)
358 panic("cannot move items on this heap");
359
360 i = *((int *)((char *)object + h->offset));
361 if (DN_KEY_LT(new_key, h->p[i].key) ) { /* must move up */
362 h->p[i].key = new_key ;
363 for (; i>0 && DN_KEY_LT(new_key, h->p[(temp = HEAP_FATHER(i))].key) ;
364 i = temp ) { /* bubble up */
365 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
366 SET_OFFSET(h, i);
367 }
368 } else { /* must move down */
369 h->p[i].key = new_key ;
370 while ( (temp = HEAP_LEFT(i)) <= max ) { /* found left child */
371 if ((temp != max) && DN_KEY_GT(h->p[temp].key, h->p[temp+1].key))
372 temp++ ; /* select child with min key */
373 if (DN_KEY_GT(new_key, h->p[temp].key)) { /* go down */
374 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
375 SET_OFFSET(h, i);
376 } else
377 break ;
378 i = temp ;
379 }
380 }
381 SET_OFFSET(h, i);
382 }
383 #endif /* heap_move, unused */
384
385 /*
386 * heapify() will reorganize data inside an array to maintain the
387 * heap property. It is needed when we delete a bunch of entries.
388 */
389 static void
390 heapify(struct dn_heap *h)
391 {
392 int i ;
393
394 for (i = 0 ; i < h->elements ; i++ )
395 heap_insert(h, i , NULL) ;
396 }
397
398 /*
399 * cleanup the heap and free data structure
400 */
401 static void
402 heap_free(struct dn_heap *h)
403 {
404 if (h->size >0 )
405 FREE(h->p, M_DUMMYNET);
406 bzero(h, sizeof(*h) );
407 }
408
409 /*
410 * --- end of heap management functions ---
411 */
412
413 /*
414 * Return the mbuf tag holding the dummynet state. As an optimization
415 * this is assumed to be the first tag on the list. If this turns out
416 * wrong we'll need to search the list.
417 */
418 static struct dn_pkt_tag *
419 dn_tag_get(struct mbuf *m)
420 {
421 struct m_tag *mtag = m_tag_first(m);
422 /* KASSERT(mtag != NULL &&
423 mtag->m_tag_id == KERNEL_MODULE_TAG_ID &&
424 mtag->m_tag_type == KERNEL_TAG_TYPE_DUMMYNET,
425 ("packet on dummynet queue w/o dummynet tag!"));
426 */
427 return (struct dn_pkt_tag *)(mtag+1);
428 }
429
430 /*
431 * Scheduler functions:
432 *
433 * transmit_event() is called when the delay-line needs to enter
434 * the scheduler, either because of existing pkts getting ready,
435 * or new packets entering the queue. The event handled is the delivery
436 * time of the packet.
437 *
438 * ready_event() does something similar with fixed-rate queues, and the
439 * event handled is the finish time of the head pkt.
440 *
441 * wfq_ready_event() does something similar with WF2Q queues, and the
442 * event handled is the start time of the head pkt.
443 *
444 * In all cases, we make sure that the data structures are consistent
445 * before passing pkts out, because this might trigger recursive
446 * invocations of the procedures.
447 */
448 static void
449 transmit_event(struct dn_pipe *pipe)
450 {
451 struct mbuf *m ;
452 struct dn_pkt_tag *pkt ;
453 struct ip *ip;
454
455 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
456
457 while ( (m = pipe->head) ) {
458 pkt = dn_tag_get(m);
459 if ( !DN_KEY_LEQ(pkt->output_time, curr_time) )
460 break;
461 /*
462 * first unlink, then call procedures, since ip_input() can invoke
463 * ip_output() and viceversa, thus causing nested calls
464 */
465 pipe->head = m->m_nextpkt ;
466 m->m_nextpkt = NULL;
467
468 /* XXX: drop the lock for now to avoid LOR's */
469 lck_mtx_unlock(dn_mutex);
470 switch (pkt->dn_dir) {
471 case DN_TO_IP_OUT: {
472 struct route tmp_rt = pkt->ro;
473 (void)ip_output(m, NULL, NULL, pkt->flags, NULL);
474 if (tmp_rt.ro_rt) {
475 rtfree(tmp_rt.ro_rt);
476 }
477 break ;
478 }
479 case DN_TO_IP_IN :
480 ip = mtod(m, struct ip *);
481 ip->ip_len = htons(ip->ip_len);
482 ip->ip_off = htons(ip->ip_off);
483 proto_inject(PF_INET, m);
484 break ;
485
486 #if BRIDGE
487 case DN_TO_BDG_FWD :
488 /*
489 * The bridge requires/assumes the Ethernet header is
490 * contiguous in the first mbuf header. Insure this is true.
491 */
492 if (BDG_LOADED) {
493 if (m->m_len < ETHER_HDR_LEN &&
494 (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
495 printf("dummynet/bridge: pullup fail, dropping pkt\n");
496 break;
497 }
498 m = bdg_forward_ptr(m, pkt->ifp);
499 } else {
500 /* somebody unloaded the bridge module. Drop pkt */
501 /* XXX rate limit */
502 printf("dummynet: dropping bridged packet trapped in pipe\n");
503 }
504 if (m)
505 m_freem(m);
506 break;
507 #endif
508 default:
509 printf("dummynet: bad switch %d!\n", pkt->dn_dir);
510 m_freem(m);
511 break ;
512 }
513 lck_mtx_lock(dn_mutex);
514 }
515 /* if there are leftover packets, put into the heap for next event */
516 if ( (m = pipe->head) ) {
517 pkt = dn_tag_get(m);
518 /* XXX should check errors on heap_insert, by draining the
519 * whole pipe p and hoping in the future we are more successful
520 */
521 heap_insert(&extract_heap, pkt->output_time, pipe);
522 }
523 }
524
525 /*
526 * the following macro computes how many ticks we have to wait
527 * before being able to transmit a packet. The credit is taken from
528 * either a pipe (WF2Q) or a flow_queue (per-flow queueing)
529 */
530 #define SET_TICKS(_m, q, p) \
531 ((_m)->m_pkthdr.len*8*hz - (q)->numbytes + p->bandwidth - 1 ) / \
532 p->bandwidth ;
533
534 /*
535 * extract pkt from queue, compute output time (could be now)
536 * and put into delay line (p_queue)
537 */
538 static void
539 move_pkt(struct mbuf *pkt, struct dn_flow_queue *q,
540 struct dn_pipe *p, int len)
541 {
542 struct dn_pkt_tag *dt = dn_tag_get(pkt);
543
544 q->head = pkt->m_nextpkt ;
545 q->len-- ;
546 q->len_bytes -= len ;
547
548 dt->output_time = curr_time + p->delay ;
549
550 if (p->head == NULL)
551 p->head = pkt;
552 else
553 p->tail->m_nextpkt = pkt;
554 p->tail = pkt;
555 p->tail->m_nextpkt = NULL;
556 }
557
558 /*
559 * ready_event() is invoked every time the queue must enter the
560 * scheduler, either because the first packet arrives, or because
561 * a previously scheduled event fired.
562 * On invokation, drain as many pkts as possible (could be 0) and then
563 * if there are leftover packets reinsert the pkt in the scheduler.
564 */
565 static void
566 ready_event(struct dn_flow_queue *q)
567 {
568 struct mbuf *pkt;
569 struct dn_pipe *p = q->fs->pipe ;
570 int p_was_empty ;
571
572 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
573
574 if (p == NULL) {
575 printf("dummynet: ready_event- pipe is gone\n");
576 return ;
577 }
578 p_was_empty = (p->head == NULL) ;
579
580 /*
581 * schedule fixed-rate queues linked to this pipe:
582 * Account for the bw accumulated since last scheduling, then
583 * drain as many pkts as allowed by q->numbytes and move to
584 * the delay line (in p) computing output time.
585 * bandwidth==0 (no limit) means we can drain the whole queue,
586 * setting len_scaled = 0 does the job.
587 */
588 q->numbytes += ( curr_time - q->sched_time ) * p->bandwidth;
589 while ( (pkt = q->head) != NULL ) {
590 int len = pkt->m_pkthdr.len;
591 int len_scaled = p->bandwidth ? len*8*hz : 0 ;
592 if (len_scaled > q->numbytes )
593 break ;
594 q->numbytes -= len_scaled ;
595 move_pkt(pkt, q, p, len);
596 }
597 /*
598 * If we have more packets queued, schedule next ready event
599 * (can only occur when bandwidth != 0, otherwise we would have
600 * flushed the whole queue in the previous loop).
601 * To this purpose we record the current time and compute how many
602 * ticks to go for the finish time of the packet.
603 */
604 if ( (pkt = q->head) != NULL ) { /* this implies bandwidth != 0 */
605 dn_key t = SET_TICKS(pkt, q, p); /* ticks i have to wait */
606 q->sched_time = curr_time ;
607 heap_insert(&ready_heap, curr_time + t, (void *)q );
608 /* XXX should check errors on heap_insert, and drain the whole
609 * queue on error hoping next time we are luckier.
610 */
611 } else { /* RED needs to know when the queue becomes empty */
612 q->q_time = curr_time;
613 q->numbytes = 0;
614 }
615 /*
616 * If the delay line was empty call transmit_event(p) now.
617 * Otherwise, the scheduler will take care of it.
618 */
619 if (p_was_empty)
620 transmit_event(p);
621 }
622
623 /*
624 * Called when we can transmit packets on WF2Q queues. Take pkts out of
625 * the queues at their start time, and enqueue into the delay line.
626 * Packets are drained until p->numbytes < 0. As long as
627 * len_scaled >= p->numbytes, the packet goes into the delay line
628 * with a deadline p->delay. For the last packet, if p->numbytes<0,
629 * there is an additional delay.
630 */
631 static void
632 ready_event_wfq(struct dn_pipe *p)
633 {
634 int p_was_empty = (p->head == NULL) ;
635 struct dn_heap *sch = &(p->scheduler_heap);
636 struct dn_heap *neh = &(p->not_eligible_heap) ;
637
638 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
639
640 if (p->if_name[0] == 0) /* tx clock is simulated */
641 p->numbytes += ( curr_time - p->sched_time ) * p->bandwidth;
642 else { /* tx clock is for real, the ifq must be empty or this is a NOP */
643 if (p->ifp && p->ifp->if_snd.ifq_head != NULL)
644 return ;
645 else {
646 DPRINTF(("dummynet: pipe %d ready from %s --\n",
647 p->pipe_nr, p->if_name));
648 }
649 }
650
651 /*
652 * While we have backlogged traffic AND credit, we need to do
653 * something on the queue.
654 */
655 while ( p->numbytes >=0 && (sch->elements>0 || neh->elements >0) ) {
656 if (sch->elements > 0) { /* have some eligible pkts to send out */
657 struct dn_flow_queue *q = sch->p[0].object ;
658 struct mbuf *pkt = q->head;
659 struct dn_flow_set *fs = q->fs;
660 u_int64_t len = pkt->m_pkthdr.len;
661 int len_scaled = p->bandwidth ? len*8*hz : 0 ;
662
663 heap_extract(sch, NULL); /* remove queue from heap */
664 p->numbytes -= len_scaled ;
665 move_pkt(pkt, q, p, len);
666
667 p->V += (len<<MY_M) / p->sum ; /* update V */
668 q->S = q->F ; /* update start time */
669 if (q->len == 0) { /* Flow not backlogged any more */
670 fs->backlogged-- ;
671 heap_insert(&(p->idle_heap), q->F, q);
672 } else { /* still backlogged */
673 /*
674 * update F and position in backlogged queue, then
675 * put flow in not_eligible_heap (we will fix this later).
676 */
677 len = (q->head)->m_pkthdr.len;
678 q->F += (len<<MY_M)/(u_int64_t) fs->weight ;
679 if (DN_KEY_LEQ(q->S, p->V))
680 heap_insert(neh, q->S, q);
681 else
682 heap_insert(sch, q->F, q);
683 }
684 }
685 /*
686 * now compute V = max(V, min(S_i)). Remember that all elements in sch
687 * have by definition S_i <= V so if sch is not empty, V is surely
688 * the max and we must not update it. Conversely, if sch is empty
689 * we only need to look at neh.
690 */
691 if (sch->elements == 0 && neh->elements > 0)
692 p->V = MAX64 ( p->V, neh->p[0].key );
693 /* move from neh to sch any packets that have become eligible */
694 while (neh->elements > 0 && DN_KEY_LEQ(neh->p[0].key, p->V) ) {
695 struct dn_flow_queue *q = neh->p[0].object ;
696 heap_extract(neh, NULL);
697 heap_insert(sch, q->F, q);
698 }
699
700 if (p->if_name[0] != '\0') {/* tx clock is from a real thing */
701 p->numbytes = -1 ; /* mark not ready for I/O */
702 break ;
703 }
704 }
705 if (sch->elements == 0 && neh->elements == 0 && p->numbytes >= 0
706 && p->idle_heap.elements > 0) {
707 /*
708 * no traffic and no events scheduled. We can get rid of idle-heap.
709 */
710 int i ;
711
712 for (i = 0 ; i < p->idle_heap.elements ; i++) {
713 struct dn_flow_queue *q = p->idle_heap.p[i].object ;
714
715 q->F = 0 ;
716 q->S = q->F + 1 ;
717 }
718 p->sum = 0 ;
719 p->V = 0 ;
720 p->idle_heap.elements = 0 ;
721 }
722 /*
723 * If we are getting clocks from dummynet (not a real interface) and
724 * If we are under credit, schedule the next ready event.
725 * Also fix the delivery time of the last packet.
726 */
727 if (p->if_name[0]==0 && p->numbytes < 0) { /* this implies bandwidth >0 */
728 dn_key t=0 ; /* number of ticks i have to wait */
729
730 if (p->bandwidth > 0)
731 t = ( p->bandwidth -1 - p->numbytes) / p->bandwidth ;
732 dn_tag_get(p->tail)->output_time += t ;
733 p->sched_time = curr_time ;
734 heap_insert(&wfq_ready_heap, curr_time + t, (void *)p);
735 /* XXX should check errors on heap_insert, and drain the whole
736 * queue on error hoping next time we are luckier.
737 */
738 }
739 /*
740 * If the delay line was empty call transmit_event(p) now.
741 * Otherwise, the scheduler will take care of it.
742 */
743 if (p_was_empty)
744 transmit_event(p);
745 }
746
747 /*
748 * This is called once per tick, or HZ times per second. It is used to
749 * increment the current tick counter and schedule expired events.
750 */
751 static void
752 dummynet(void * __unused unused)
753 {
754 void *p ; /* generic parameter to handler */
755 struct dn_heap *h ;
756 struct dn_heap *heaps[3];
757 int i;
758 struct dn_pipe *pe ;
759
760 heaps[0] = &ready_heap ; /* fixed-rate queues */
761 heaps[1] = &wfq_ready_heap ; /* wfq queues */
762 heaps[2] = &extract_heap ; /* delay line */
763
764 lck_mtx_lock(dn_mutex);
765
766 curr_time++ ;
767 for (i=0; i < 3 ; i++) {
768 h = heaps[i];
769 while (h->elements > 0 && DN_KEY_LEQ(h->p[0].key, curr_time) ) {
770 if (h->p[0].key > curr_time)
771 printf("dummynet: warning, heap %d is %d ticks late\n",
772 i, (int)(curr_time - h->p[0].key));
773 p = h->p[0].object ; /* store a copy before heap_extract */
774 heap_extract(h, NULL); /* need to extract before processing */
775 if (i == 0)
776 ready_event(p) ;
777 else if (i == 1) {
778 struct dn_pipe *pipe = p;
779 if (pipe->if_name[0] != '\0')
780 printf("dummynet: bad ready_event_wfq for pipe %s\n",
781 pipe->if_name);
782 else
783 ready_event_wfq(p) ;
784 } else
785 transmit_event(p);
786 }
787 }
788 /* sweep pipes trying to expire idle flow_queues */
789 for (pe = all_pipes; pe ; pe = pe->next )
790 if (pe->idle_heap.elements > 0 &&
791 DN_KEY_LT(pe->idle_heap.p[0].key, pe->V) ) {
792 struct dn_flow_queue *q = pe->idle_heap.p[0].object ;
793
794 heap_extract(&(pe->idle_heap), NULL);
795 q->S = q->F + 1 ; /* mark timestamp as invalid */
796 pe->sum -= q->fs->weight ;
797 }
798
799 lck_mtx_unlock(dn_mutex);
800
801 timeout(dummynet, NULL, 1);
802 }
803
804 /*
805 * called by an interface when tx_rdy occurs.
806 */
807 int
808 if_tx_rdy(struct ifnet *ifp)
809 {
810 struct dn_pipe *p;
811
812 lck_mtx_lock(dn_mutex);
813 for (p = all_pipes; p ; p = p->next )
814 if (p->ifp == ifp)
815 break ;
816 if (p == NULL) {
817 char buf[32];
818 sprintf(buf, "%s%d",ifp->if_name, ifp->if_unit);
819 for (p = all_pipes; p ; p = p->next )
820 if (!strcmp(p->if_name, buf) ) {
821 p->ifp = ifp ;
822 DPRINTF(("dummynet: ++ tx rdy from %s (now found)\n", buf));
823 break ;
824 }
825 }
826 if (p != NULL) {
827 DPRINTF(("dummynet: ++ tx rdy from %s%d - qlen %d\n", ifp->if_name,
828 ifp->if_unit, ifp->if_snd.ifq_len));
829 p->numbytes = 0 ; /* mark ready for I/O */
830 ready_event_wfq(p);
831 }
832 lck_mtx_lock(dn_mutex);
833
834 return 0;
835 }
836
837 /*
838 * Unconditionally expire empty queues in case of shortage.
839 * Returns the number of queues freed.
840 */
841 static int
842 expire_queues(struct dn_flow_set *fs)
843 {
844 struct dn_flow_queue *q, *prev ;
845 int i, initial_elements = fs->rq_elements ;
846 struct timeval timenow;
847
848 getmicrotime(&timenow);
849
850 if (fs->last_expired == timenow.tv_sec)
851 return 0 ;
852 fs->last_expired = timenow.tv_sec ;
853 for (i = 0 ; i <= fs->rq_size ; i++) /* last one is overflow */
854 for (prev=NULL, q = fs->rq[i] ; q != NULL ; )
855 if (q->head != NULL || q->S != q->F+1) {
856 prev = q ;
857 q = q->next ;
858 } else { /* entry is idle, expire it */
859 struct dn_flow_queue *old_q = q ;
860
861 if (prev != NULL)
862 prev->next = q = q->next ;
863 else
864 fs->rq[i] = q = q->next ;
865 fs->rq_elements-- ;
866 FREE(old_q, M_DUMMYNET);
867 }
868 return initial_elements - fs->rq_elements ;
869 }
870
871 /*
872 * If room, create a new queue and put at head of slot i;
873 * otherwise, create or use the default queue.
874 */
875 static struct dn_flow_queue *
876 create_queue(struct dn_flow_set *fs, int i)
877 {
878 struct dn_flow_queue *q ;
879
880 if (fs->rq_elements > fs->rq_size * dn_max_ratio &&
881 expire_queues(fs) == 0) {
882 /*
883 * No way to get room, use or create overflow queue.
884 */
885 i = fs->rq_size ;
886 if ( fs->rq[i] != NULL )
887 return fs->rq[i] ;
888 }
889 q = _MALLOC(sizeof(*q), M_DUMMYNET, M_DONTWAIT | M_ZERO);
890 if (q == NULL) {
891 printf("dummynet: sorry, cannot allocate queue for new flow\n");
892 return NULL ;
893 }
894 q->fs = fs ;
895 q->hash_slot = i ;
896 q->next = fs->rq[i] ;
897 q->S = q->F + 1; /* hack - mark timestamp as invalid */
898 fs->rq[i] = q ;
899 fs->rq_elements++ ;
900 return q ;
901 }
902
903 /*
904 * Given a flow_set and a pkt in last_pkt, find a matching queue
905 * after appropriate masking. The queue is moved to front
906 * so that further searches take less time.
907 */
908 static struct dn_flow_queue *
909 find_queue(struct dn_flow_set *fs, struct ipfw_flow_id *id)
910 {
911 int i = 0 ; /* we need i and q for new allocations */
912 struct dn_flow_queue *q, *prev;
913
914 if ( !(fs->flags_fs & DN_HAVE_FLOW_MASK) )
915 q = fs->rq[0] ;
916 else {
917 /* first, do the masking */
918 id->dst_ip &= fs->flow_mask.dst_ip ;
919 id->src_ip &= fs->flow_mask.src_ip ;
920 id->dst_port &= fs->flow_mask.dst_port ;
921 id->src_port &= fs->flow_mask.src_port ;
922 id->proto &= fs->flow_mask.proto ;
923 id->flags = 0 ; /* we don't care about this one */
924 /* then, hash function */
925 i = ( (id->dst_ip) & 0xffff ) ^
926 ( (id->dst_ip >> 15) & 0xffff ) ^
927 ( (id->src_ip << 1) & 0xffff ) ^
928 ( (id->src_ip >> 16 ) & 0xffff ) ^
929 (id->dst_port << 1) ^ (id->src_port) ^
930 (id->proto );
931 i = i % fs->rq_size ;
932 /* finally, scan the current list for a match */
933 searches++ ;
934 for (prev=NULL, q = fs->rq[i] ; q ; ) {
935 search_steps++;
936 if (id->dst_ip == q->id.dst_ip &&
937 id->src_ip == q->id.src_ip &&
938 id->dst_port == q->id.dst_port &&
939 id->src_port == q->id.src_port &&
940 id->proto == q->id.proto &&
941 id->flags == q->id.flags)
942 break ; /* found */
943 else if (pipe_expire && q->head == NULL && q->S == q->F+1 ) {
944 /* entry is idle and not in any heap, expire it */
945 struct dn_flow_queue *old_q = q ;
946
947 if (prev != NULL)
948 prev->next = q = q->next ;
949 else
950 fs->rq[i] = q = q->next ;
951 fs->rq_elements-- ;
952 FREE(old_q, M_DUMMYNET);
953 continue ;
954 }
955 prev = q ;
956 q = q->next ;
957 }
958 if (q && prev != NULL) { /* found and not in front */
959 prev->next = q->next ;
960 q->next = fs->rq[i] ;
961 fs->rq[i] = q ;
962 }
963 }
964 if (q == NULL) { /* no match, need to allocate a new entry */
965 q = create_queue(fs, i);
966 if (q != NULL)
967 q->id = *id ;
968 }
969 return q ;
970 }
971
972 static int
973 red_drops(struct dn_flow_set *fs, struct dn_flow_queue *q, int len)
974 {
975 /*
976 * RED algorithm
977 *
978 * RED calculates the average queue size (avg) using a low-pass filter
979 * with an exponential weighted (w_q) moving average:
980 * avg <- (1-w_q) * avg + w_q * q_size
981 * where q_size is the queue length (measured in bytes or * packets).
982 *
983 * If q_size == 0, we compute the idle time for the link, and set
984 * avg = (1 - w_q)^(idle/s)
985 * where s is the time needed for transmitting a medium-sized packet.
986 *
987 * Now, if avg < min_th the packet is enqueued.
988 * If avg > max_th the packet is dropped. Otherwise, the packet is
989 * dropped with probability P function of avg.
990 *
991 */
992
993 int64_t p_b = 0;
994 /* queue in bytes or packets ? */
995 u_int q_size = (fs->flags_fs & DN_QSIZE_IS_BYTES) ? q->len_bytes : q->len;
996
997 DPRINTF(("\ndummynet: %d q: %2u ", (int) curr_time, q_size));
998
999 /* average queue size estimation */
1000 if (q_size != 0) {
1001 /*
1002 * queue is not empty, avg <- avg + (q_size - avg) * w_q
1003 */
1004 int diff = SCALE(q_size) - q->avg;
1005 int64_t v = SCALE_MUL((int64_t) diff, (int64_t) fs->w_q);
1006
1007 q->avg += (int) v;
1008 } else {
1009 /*
1010 * queue is empty, find for how long the queue has been
1011 * empty and use a lookup table for computing
1012 * (1 - * w_q)^(idle_time/s) where s is the time to send a
1013 * (small) packet.
1014 * XXX check wraps...
1015 */
1016 if (q->avg) {
1017 u_int t = (curr_time - q->q_time) / fs->lookup_step;
1018
1019 q->avg = (t < fs->lookup_depth) ?
1020 SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
1021 }
1022 }
1023 DPRINTF(("dummynet: avg: %u ", SCALE_VAL(q->avg)));
1024
1025 /* should i drop ? */
1026
1027 if (q->avg < fs->min_th) {
1028 q->count = -1;
1029 return 0; /* accept packet ; */
1030 }
1031 if (q->avg >= fs->max_th) { /* average queue >= max threshold */
1032 if (fs->flags_fs & DN_IS_GENTLE_RED) {
1033 /*
1034 * According to Gentle-RED, if avg is greater than max_th the
1035 * packet is dropped with a probability
1036 * p_b = c_3 * avg - c_4
1037 * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
1038 */
1039 p_b = SCALE_MUL((int64_t) fs->c_3, (int64_t) q->avg) - fs->c_4;
1040 } else {
1041 q->count = -1;
1042 DPRINTF(("dummynet: - drop"));
1043 return 1 ;
1044 }
1045 } else if (q->avg > fs->min_th) {
1046 /*
1047 * we compute p_b using the linear dropping function p_b = c_1 *
1048 * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
1049 * max_p * min_th / (max_th - min_th)
1050 */
1051 p_b = SCALE_MUL((int64_t) fs->c_1, (int64_t) q->avg) - fs->c_2;
1052 }
1053 if (fs->flags_fs & DN_QSIZE_IS_BYTES)
1054 p_b = (p_b * len) / fs->max_pkt_size;
1055 if (++q->count == 0)
1056 q->random = random() & 0xffff;
1057 else {
1058 /*
1059 * q->count counts packets arrived since last drop, so a greater
1060 * value of q->count means a greater packet drop probability.
1061 */
1062 if (SCALE_MUL(p_b, SCALE((int64_t) q->count)) > q->random) {
1063 q->count = 0;
1064 DPRINTF(("dummynet: - red drop"));
1065 /* after a drop we calculate a new random value */
1066 q->random = random() & 0xffff;
1067 return 1; /* drop */
1068 }
1069 }
1070 /* end of RED algorithm */
1071 return 0 ; /* accept */
1072 }
1073
1074 static __inline
1075 struct dn_flow_set *
1076 locate_flowset(int pipe_nr, struct ip_fw *rule)
1077 {
1078 struct dn_flow_set *fs;
1079 ipfw_insn *cmd = rule->cmd + rule->act_ofs;
1080
1081 if (cmd->opcode == O_LOG)
1082 cmd += F_LEN(cmd);
1083
1084 bcopy(& ((ipfw_insn_pipe *)cmd)->pipe_ptr, &fs, sizeof(fs));
1085
1086 if (fs != NULL)
1087 return fs;
1088
1089 if (cmd->opcode == O_QUEUE) {
1090 for (fs=all_flow_sets; fs && fs->fs_nr != pipe_nr; fs=fs->next)
1091 ;
1092 }
1093 else {
1094 struct dn_pipe *p1;
1095 for (p1 = all_pipes; p1 && p1->pipe_nr != pipe_nr; p1 = p1->next)
1096 ;
1097 if (p1 != NULL)
1098 fs = &(p1->fs) ;
1099 }
1100 /* record for the future */
1101 bcopy(&fs, & ((ipfw_insn_pipe *)cmd)->pipe_ptr, sizeof(fs));
1102
1103 return fs ;
1104 }
1105
1106 /*
1107 * dummynet hook for packets. Below 'pipe' is a pipe or a queue
1108 * depending on whether WF2Q or fixed bw is used.
1109 *
1110 * pipe_nr pipe or queue the packet is destined for.
1111 * dir where shall we send the packet after dummynet.
1112 * m the mbuf with the packet
1113 * ifp the 'ifp' parameter from the caller.
1114 * NULL in ip_input, destination interface in ip_output,
1115 * real_dst in bdg_forward
1116 * ro route parameter (only used in ip_output, NULL otherwise)
1117 * dst destination address, only used by ip_output
1118 * rule matching rule, in case of multiple passes
1119 * flags flags from the caller, only used in ip_output
1120 *
1121 */
1122 static int
1123 dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
1124 {
1125 struct dn_pkt_tag *pkt;
1126 struct m_tag *mtag;
1127 struct dn_flow_set *fs;
1128 struct dn_pipe *pipe ;
1129 u_int64_t len = m->m_pkthdr.len ;
1130 struct dn_flow_queue *q = NULL ;
1131 int is_pipe;
1132
1133 #if IPFW2
1134 ipfw_insn *cmd = fwa->rule->cmd + fwa->rule->act_ofs;
1135
1136 if (cmd->opcode == O_LOG)
1137 cmd += F_LEN(cmd);
1138 is_pipe = (cmd->opcode == O_PIPE);
1139 #else
1140 is_pipe = (fwa->rule->fw_flg & IP_FW_F_COMMAND) == IP_FW_F_PIPE;
1141 #endif
1142
1143 pipe_nr &= 0xffff ;
1144
1145 lck_mtx_lock(dn_mutex);
1146
1147 /*
1148 * This is a dummynet rule, so we expect an O_PIPE or O_QUEUE rule.
1149 */
1150 fs = locate_flowset(pipe_nr, fwa->rule);
1151 if (fs == NULL)
1152 goto dropit ; /* this queue/pipe does not exist! */
1153 pipe = fs->pipe ;
1154 if (pipe == NULL) { /* must be a queue, try find a matching pipe */
1155 for (pipe = all_pipes; pipe && pipe->pipe_nr != fs->parent_nr;
1156 pipe = pipe->next)
1157 ;
1158 if (pipe != NULL)
1159 fs->pipe = pipe ;
1160 else {
1161 printf("dummynet: no pipe %d for queue %d, drop pkt\n",
1162 fs->parent_nr, fs->fs_nr);
1163 goto dropit ;
1164 }
1165 }
1166 q = find_queue(fs, &(fwa->f_id));
1167 if ( q == NULL )
1168 goto dropit ; /* cannot allocate queue */
1169 /*
1170 * update statistics, then check reasons to drop pkt
1171 */
1172 q->tot_bytes += len ;
1173 q->tot_pkts++ ;
1174 if ( fs->plr && random() < fs->plr )
1175 goto dropit ; /* random pkt drop */
1176 if ( fs->flags_fs & DN_QSIZE_IS_BYTES) {
1177 if (q->len_bytes > fs->qsize)
1178 goto dropit ; /* queue size overflow */
1179 } else {
1180 if (q->len >= fs->qsize)
1181 goto dropit ; /* queue count overflow */
1182 }
1183 if ( fs->flags_fs & DN_IS_RED && red_drops(fs, q, len) )
1184 goto dropit ;
1185
1186 /* XXX expensive to zero, see if we can remove it*/
1187 mtag = m_tag_alloc(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_DUMMYNET,
1188 sizeof(struct dn_pkt_tag), M_NOWAIT);
1189 if ( mtag == NULL )
1190 goto dropit ; /* cannot allocate packet header */
1191 m_tag_prepend(m, mtag); /* attach to mbuf chain */
1192
1193 pkt = (struct dn_pkt_tag *)(mtag+1);
1194 bzero(pkt, sizeof(struct dn_pkt_tag));
1195 /* ok, i can handle the pkt now... */
1196 /* build and enqueue packet + parameters */
1197 pkt->rule = fwa->rule ;
1198 pkt->dn_dir = dir ;
1199
1200 pkt->ifp = fwa->oif;
1201 if (dir == DN_TO_IP_OUT) {
1202 /*
1203 * We need to copy *ro because for ICMP pkts (and maybe others)
1204 * the caller passed a pointer into the stack; dst might also be
1205 * a pointer into *ro so it needs to be updated.
1206 */
1207 lck_mtx_lock(rt_mtx);
1208 pkt->ro = *(fwa->ro);
1209 if (fwa->ro->ro_rt)
1210 fwa->ro->ro_rt->rt_refcnt++ ;
1211 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) /* dst points into ro */
1212 fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst) ;
1213 lck_mtx_unlock(rt_mtx);
1214
1215 pkt->dn_dst = fwa->dst;
1216 pkt->flags = fwa->flags;
1217 }
1218 if (q->head == NULL)
1219 q->head = m;
1220 else
1221 q->tail->m_nextpkt = m;
1222 q->tail = m;
1223 q->len++;
1224 q->len_bytes += len ;
1225
1226 if ( q->head != m ) /* flow was not idle, we are done */
1227 goto done;
1228 /*
1229 * If we reach this point the flow was previously idle, so we need
1230 * to schedule it. This involves different actions for fixed-rate or
1231 * WF2Q queues.
1232 */
1233 if (is_pipe) {
1234 /*
1235 * Fixed-rate queue: just insert into the ready_heap.
1236 */
1237 dn_key t = 0 ;
1238 if (pipe->bandwidth)
1239 t = SET_TICKS(m, q, pipe);
1240 q->sched_time = curr_time ;
1241 if (t == 0) /* must process it now */
1242 ready_event( q );
1243 else
1244 heap_insert(&ready_heap, curr_time + t , q );
1245 } else {
1246 /*
1247 * WF2Q. First, compute start time S: if the flow was idle (S=F+1)
1248 * set S to the virtual time V for the controlling pipe, and update
1249 * the sum of weights for the pipe; otherwise, remove flow from
1250 * idle_heap and set S to max(F,V).
1251 * Second, compute finish time F = S + len/weight.
1252 * Third, if pipe was idle, update V=max(S, V).
1253 * Fourth, count one more backlogged flow.
1254 */
1255 if (DN_KEY_GT(q->S, q->F)) { /* means timestamps are invalid */
1256 q->S = pipe->V ;
1257 pipe->sum += fs->weight ; /* add weight of new queue */
1258 } else {
1259 heap_extract(&(pipe->idle_heap), q);
1260 q->S = MAX64(q->F, pipe->V ) ;
1261 }
1262 q->F = q->S + ( len<<MY_M )/(u_int64_t) fs->weight;
1263
1264 if (pipe->not_eligible_heap.elements == 0 &&
1265 pipe->scheduler_heap.elements == 0)
1266 pipe->V = MAX64 ( q->S, pipe->V );
1267 fs->backlogged++ ;
1268 /*
1269 * Look at eligibility. A flow is not eligibile if S>V (when
1270 * this happens, it means that there is some other flow already
1271 * scheduled for the same pipe, so the scheduler_heap cannot be
1272 * empty). If the flow is not eligible we just store it in the
1273 * not_eligible_heap. Otherwise, we store in the scheduler_heap
1274 * and possibly invoke ready_event_wfq() right now if there is
1275 * leftover credit.
1276 * Note that for all flows in scheduler_heap (SCH), S_i <= V,
1277 * and for all flows in not_eligible_heap (NEH), S_i > V .
1278 * So when we need to compute max( V, min(S_i) ) forall i in SCH+NEH,
1279 * we only need to look into NEH.
1280 */
1281 if (DN_KEY_GT(q->S, pipe->V) ) { /* not eligible */
1282 if (pipe->scheduler_heap.elements == 0)
1283 printf("dummynet: ++ ouch! not eligible but empty scheduler!\n");
1284 heap_insert(&(pipe->not_eligible_heap), q->S, q);
1285 } else {
1286 heap_insert(&(pipe->scheduler_heap), q->F, q);
1287 if (pipe->numbytes >= 0) { /* pipe is idle */
1288 if (pipe->scheduler_heap.elements != 1)
1289 printf("dummynet: OUCH! pipe should have been idle!\n");
1290 DPRINTF(("dummynet: waking up pipe %d at %d\n",
1291 pipe->pipe_nr, (int)(q->F >> MY_M)));
1292 pipe->sched_time = curr_time ;
1293 ready_event_wfq(pipe);
1294 }
1295 }
1296 }
1297 done:
1298 lck_mtx_unlock(dn_mutex);
1299 return 0;
1300
1301 dropit:
1302 if (q)
1303 q->drops++ ;
1304 lck_mtx_unlock(dn_mutex);
1305 m_freem(m);
1306 return ( (fs && (fs->flags_fs & DN_NOERROR)) ? 0 : ENOBUFS);
1307 }
1308
1309 /*
1310 * Below, the rtfree is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
1311 * Doing this would probably save us the initial bzero of dn_pkt
1312 */
1313 #define DN_FREE_PKT(_m) do { \
1314 struct m_tag *tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_DUMMYNET, NULL); \
1315 if (tag) { \
1316 struct dn_pkt_tag *n = (struct dn_pkt_tag *)(tag+1); \
1317 if (n->ro.ro_rt) \
1318 rtfree(n->ro.ro_rt); \
1319 } \
1320 m_tag_delete(_m, tag); \
1321 m_freem(_m); \
1322 } while (0)
1323
1324 /*
1325 * Dispose all packets and flow_queues on a flow_set.
1326 * If all=1, also remove red lookup table and other storage,
1327 * including the descriptor itself.
1328 * For the one in dn_pipe MUST also cleanup ready_heap...
1329 */
1330 static void
1331 purge_flow_set(struct dn_flow_set *fs, int all)
1332 {
1333 struct dn_flow_queue *q, *qn ;
1334 int i ;
1335
1336 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
1337
1338 for (i = 0 ; i <= fs->rq_size ; i++ ) {
1339 for (q = fs->rq[i] ; q ; q = qn ) {
1340 struct mbuf *m, *mnext;
1341
1342 mnext = q->head;
1343 while ((m = mnext) != NULL) {
1344 mnext = m->m_nextpkt;
1345 DN_FREE_PKT(m);
1346 }
1347 qn = q->next ;
1348 FREE(q, M_DUMMYNET);
1349 }
1350 fs->rq[i] = NULL ;
1351 }
1352 fs->rq_elements = 0 ;
1353 if (all) {
1354 /* RED - free lookup table */
1355 if (fs->w_q_lookup)
1356 FREE(fs->w_q_lookup, M_DUMMYNET);
1357 if (fs->rq)
1358 FREE(fs->rq, M_DUMMYNET);
1359 /* if this fs is not part of a pipe, free it */
1360 if (fs->pipe && fs != &(fs->pipe->fs) )
1361 FREE(fs, M_DUMMYNET);
1362 }
1363 }
1364
1365 /*
1366 * Dispose all packets queued on a pipe (not a flow_set).
1367 * Also free all resources associated to a pipe, which is about
1368 * to be deleted.
1369 */
1370 static void
1371 purge_pipe(struct dn_pipe *pipe)
1372 {
1373 struct mbuf *m, *mnext;
1374
1375 purge_flow_set( &(pipe->fs), 1 );
1376
1377 mnext = pipe->head;
1378 while ((m = mnext) != NULL) {
1379 mnext = m->m_nextpkt;
1380 DN_FREE_PKT(m);
1381 }
1382
1383 heap_free( &(pipe->scheduler_heap) );
1384 heap_free( &(pipe->not_eligible_heap) );
1385 heap_free( &(pipe->idle_heap) );
1386 }
1387
1388 /*
1389 * Delete all pipes and heaps returning memory. Must also
1390 * remove references from all ipfw rules to all pipes.
1391 */
1392 static void
1393 dummynet_flush()
1394 {
1395 struct dn_pipe *curr_p, *p ;
1396 struct dn_flow_set *fs, *curr_fs;
1397
1398 lck_mtx_lock(dn_mutex);
1399
1400 /* remove all references to pipes ...*/
1401 flush_pipe_ptrs(NULL);
1402 /* prevent future matches... */
1403 p = all_pipes ;
1404 all_pipes = NULL ;
1405 fs = all_flow_sets ;
1406 all_flow_sets = NULL ;
1407 /* and free heaps so we don't have unwanted events */
1408 heap_free(&ready_heap);
1409 heap_free(&wfq_ready_heap);
1410 heap_free(&extract_heap);
1411
1412 /*
1413 * Now purge all queued pkts and delete all pipes
1414 */
1415 /* scan and purge all flow_sets. */
1416 for ( ; fs ; ) {
1417 curr_fs = fs ;
1418 fs = fs->next ;
1419 purge_flow_set(curr_fs, 1);
1420 }
1421 for ( ; p ; ) {
1422 purge_pipe(p);
1423 curr_p = p ;
1424 p = p->next ;
1425 FREE(curr_p, M_DUMMYNET);
1426 }
1427 lck_mtx_unlock(dn_mutex);
1428 }
1429
1430
1431 extern struct ip_fw *ip_fw_default_rule ;
1432 static void
1433 dn_rule_delete_fs(struct dn_flow_set *fs, void *r)
1434 {
1435 int i ;
1436 struct dn_flow_queue *q ;
1437 struct mbuf *m ;
1438
1439 for (i = 0 ; i <= fs->rq_size ; i++) /* last one is ovflow */
1440 for (q = fs->rq[i] ; q ; q = q->next )
1441 for (m = q->head ; m ; m = m->m_nextpkt ) {
1442 struct dn_pkt_tag *pkt = dn_tag_get(m) ;
1443 if (pkt->rule == r)
1444 pkt->rule = ip_fw_default_rule ;
1445 }
1446 }
1447 /*
1448 * when a firewall rule is deleted, scan all queues and remove the flow-id
1449 * from packets matching this rule.
1450 */
1451 void
1452 dn_rule_delete(void *r)
1453 {
1454 struct dn_pipe *p ;
1455 struct dn_flow_set *fs ;
1456 struct dn_pkt_tag *pkt ;
1457 struct mbuf *m ;
1458
1459 lck_mtx_lock(dn_mutex);
1460
1461 /*
1462 * If the rule references a queue (dn_flow_set), then scan
1463 * the flow set, otherwise scan pipes. Should do either, but doing
1464 * both does not harm.
1465 */
1466 for ( fs = all_flow_sets ; fs ; fs = fs->next )
1467 dn_rule_delete_fs(fs, r);
1468 for ( p = all_pipes ; p ; p = p->next ) {
1469 fs = &(p->fs) ;
1470 dn_rule_delete_fs(fs, r);
1471 for (m = p->head ; m ; m = m->m_nextpkt ) {
1472 pkt = dn_tag_get(m) ;
1473 if (pkt->rule == r)
1474 pkt->rule = ip_fw_default_rule ;
1475 }
1476 }
1477 lck_mtx_unlock(dn_mutex);
1478 }
1479
1480 /*
1481 * setup RED parameters
1482 */
1483 static int
1484 config_red(struct dn_flow_set *p, struct dn_flow_set * x)
1485 {
1486 int i;
1487
1488 x->w_q = p->w_q;
1489 x->min_th = SCALE(p->min_th);
1490 x->max_th = SCALE(p->max_th);
1491 x->max_p = p->max_p;
1492
1493 x->c_1 = p->max_p / (p->max_th - p->min_th);
1494 x->c_2 = SCALE_MUL(x->c_1, SCALE(p->min_th));
1495 if (x->flags_fs & DN_IS_GENTLE_RED) {
1496 x->c_3 = (SCALE(1) - p->max_p) / p->max_th;
1497 x->c_4 = (SCALE(1) - 2 * p->max_p);
1498 }
1499
1500 /* if the lookup table already exist, free and create it again */
1501 if (x->w_q_lookup) {
1502 FREE(x->w_q_lookup, M_DUMMYNET);
1503 x->w_q_lookup = NULL ;
1504 }
1505 if (red_lookup_depth == 0) {
1506 printf("\ndummynet: net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
1507 FREE(x, M_DUMMYNET);
1508 return EINVAL;
1509 }
1510 x->lookup_depth = red_lookup_depth;
1511 x->w_q_lookup = (u_int *) _MALLOC(x->lookup_depth * sizeof(int),
1512 M_DUMMYNET, M_DONTWAIT);
1513 if (x->w_q_lookup == NULL) {
1514 printf("dummynet: sorry, cannot allocate red lookup table\n");
1515 FREE(x, M_DUMMYNET);
1516 return ENOSPC;
1517 }
1518
1519 /* fill the lookup table with (1 - w_q)^x */
1520 x->lookup_step = p->lookup_step ;
1521 x->lookup_weight = p->lookup_weight ;
1522 x->w_q_lookup[0] = SCALE(1) - x->w_q;
1523 for (i = 1; i < x->lookup_depth; i++)
1524 x->w_q_lookup[i] = SCALE_MUL(x->w_q_lookup[i - 1], x->lookup_weight);
1525 if (red_avg_pkt_size < 1)
1526 red_avg_pkt_size = 512 ;
1527 x->avg_pkt_size = red_avg_pkt_size ;
1528 if (red_max_pkt_size < 1)
1529 red_max_pkt_size = 1500 ;
1530 x->max_pkt_size = red_max_pkt_size ;
1531 return 0 ;
1532 }
1533
1534 static int
1535 alloc_hash(struct dn_flow_set *x, struct dn_flow_set *pfs)
1536 {
1537 if (x->flags_fs & DN_HAVE_FLOW_MASK) { /* allocate some slots */
1538 int l = pfs->rq_size;
1539
1540 if (l == 0)
1541 l = dn_hash_size;
1542 if (l < 4)
1543 l = 4;
1544 else if (l > DN_MAX_HASH_SIZE)
1545 l = DN_MAX_HASH_SIZE;
1546 x->rq_size = l;
1547 } else /* one is enough for null mask */
1548 x->rq_size = 1;
1549 x->rq = _MALLOC((1 + x->rq_size) * sizeof(struct dn_flow_queue *),
1550 M_DUMMYNET, M_DONTWAIT | M_ZERO);
1551 if (x->rq == NULL) {
1552 printf("dummynet: sorry, cannot allocate queue\n");
1553 return ENOSPC;
1554 }
1555 x->rq_elements = 0;
1556 return 0 ;
1557 }
1558
1559 static void
1560 set_fs_parms(struct dn_flow_set *x, struct dn_flow_set *src)
1561 {
1562 x->flags_fs = src->flags_fs;
1563 x->qsize = src->qsize;
1564 x->plr = src->plr;
1565 x->flow_mask = src->flow_mask;
1566 if (x->flags_fs & DN_QSIZE_IS_BYTES) {
1567 if (x->qsize > 1024*1024)
1568 x->qsize = 1024*1024 ;
1569 } else {
1570 if (x->qsize == 0)
1571 x->qsize = 50 ;
1572 if (x->qsize > 100)
1573 x->qsize = 50 ;
1574 }
1575 /* configuring RED */
1576 if ( x->flags_fs & DN_IS_RED )
1577 config_red(src, x) ; /* XXX should check errors */
1578 }
1579
1580 /*
1581 * setup pipe or queue parameters.
1582 */
1583
1584 static int
1585 config_pipe(struct dn_pipe *p)
1586 {
1587 int i, r;
1588 struct dn_flow_set *pfs = &(p->fs);
1589 struct dn_flow_queue *q;
1590
1591 /*
1592 * The config program passes parameters as follows:
1593 * bw = bits/second (0 means no limits),
1594 * delay = ms, must be translated into ticks.
1595 * qsize = slots/bytes
1596 */
1597 p->delay = ( p->delay * hz ) / 1000 ;
1598 /* We need either a pipe number or a flow_set number */
1599 if (p->pipe_nr == 0 && pfs->fs_nr == 0)
1600 return EINVAL ;
1601 if (p->pipe_nr != 0 && pfs->fs_nr != 0)
1602 return EINVAL ;
1603 if (p->pipe_nr != 0) { /* this is a pipe */
1604 struct dn_pipe *x, *a, *b;
1605
1606 lck_mtx_lock(dn_mutex);
1607 /* locate pipe */
1608 for (a = NULL , b = all_pipes ; b && b->pipe_nr < p->pipe_nr ;
1609 a = b , b = b->next) ;
1610
1611 if (b == NULL || b->pipe_nr != p->pipe_nr) { /* new pipe */
1612 x = _MALLOC(sizeof(struct dn_pipe), M_DUMMYNET, M_DONTWAIT | M_ZERO) ;
1613 if (x == NULL) {
1614 lck_mtx_unlock(dn_mutex);
1615 printf("dummynet: no memory for new pipe\n");
1616 return ENOSPC;
1617 }
1618 x->pipe_nr = p->pipe_nr;
1619 x->fs.pipe = x ;
1620 /* idle_heap is the only one from which we extract from the middle.
1621 */
1622 x->idle_heap.size = x->idle_heap.elements = 0 ;
1623 x->idle_heap.offset=OFFSET_OF(struct dn_flow_queue, heap_pos);
1624 } else {
1625 x = b;
1626 /* Flush accumulated credit for all queues */
1627 for (i = 0; i <= x->fs.rq_size; i++)
1628 for (q = x->fs.rq[i]; q; q = q->next)
1629 q->numbytes = 0;
1630 }
1631
1632 x->bandwidth = p->bandwidth ;
1633 x->numbytes = 0; /* just in case... */
1634 bcopy(p->if_name, x->if_name, sizeof(p->if_name) );
1635 x->ifp = NULL ; /* reset interface ptr */
1636 x->delay = p->delay ;
1637 set_fs_parms(&(x->fs), pfs);
1638
1639
1640 if ( x->fs.rq == NULL ) { /* a new pipe */
1641 r = alloc_hash(&(x->fs), pfs) ;
1642 if (r) {
1643 lck_mtx_unlock(dn_mutex);
1644 FREE(x, M_DUMMYNET);
1645 return r ;
1646 }
1647 x->next = b ;
1648 if (a == NULL)
1649 all_pipes = x ;
1650 else
1651 a->next = x ;
1652 }
1653 lck_mtx_unlock(dn_mutex);
1654 } else { /* config queue */
1655 struct dn_flow_set *x, *a, *b ;
1656
1657 lck_mtx_lock(dn_mutex);
1658 /* locate flow_set */
1659 for (a=NULL, b=all_flow_sets ; b && b->fs_nr < pfs->fs_nr ;
1660 a = b , b = b->next) ;
1661
1662 if (b == NULL || b->fs_nr != pfs->fs_nr) { /* new */
1663 if (pfs->parent_nr == 0) { /* need link to a pipe */
1664 lck_mtx_unlock(dn_mutex);
1665 return EINVAL ;
1666 }
1667 x = _MALLOC(sizeof(struct dn_flow_set), M_DUMMYNET, M_DONTWAIT | M_ZERO);
1668 if (x == NULL) {
1669 lck_mtx_unlock(dn_mutex);
1670 printf("dummynet: no memory for new flow_set\n");
1671 return ENOSPC;
1672 }
1673 x->fs_nr = pfs->fs_nr;
1674 x->parent_nr = pfs->parent_nr;
1675 x->weight = pfs->weight ;
1676 if (x->weight == 0)
1677 x->weight = 1 ;
1678 else if (x->weight > 100)
1679 x->weight = 100 ;
1680 } else {
1681 /* Change parent pipe not allowed; must delete and recreate */
1682 if (pfs->parent_nr != 0 && b->parent_nr != pfs->parent_nr) {
1683 lck_mtx_unlock(dn_mutex);
1684 return EINVAL ;
1685 }
1686 x = b;
1687 }
1688 set_fs_parms(x, pfs);
1689
1690 if ( x->rq == NULL ) { /* a new flow_set */
1691 r = alloc_hash(x, pfs) ;
1692 if (r) {
1693 lck_mtx_unlock(dn_mutex);
1694 FREE(x, M_DUMMYNET);
1695 return r ;
1696 }
1697 x->next = b;
1698 if (a == NULL)
1699 all_flow_sets = x;
1700 else
1701 a->next = x;
1702 }
1703 lck_mtx_unlock(dn_mutex);
1704 }
1705 return 0 ;
1706 }
1707
1708 /*
1709 * Helper function to remove from a heap queues which are linked to
1710 * a flow_set about to be deleted.
1711 */
1712 static void
1713 fs_remove_from_heap(struct dn_heap *h, struct dn_flow_set *fs)
1714 {
1715 int i = 0, found = 0 ;
1716 for (; i < h->elements ;)
1717 if ( ((struct dn_flow_queue *)h->p[i].object)->fs == fs) {
1718 h->elements-- ;
1719 h->p[i] = h->p[h->elements] ;
1720 found++ ;
1721 } else
1722 i++ ;
1723 if (found)
1724 heapify(h);
1725 }
1726
1727 /*
1728 * helper function to remove a pipe from a heap (can be there at most once)
1729 */
1730 static void
1731 pipe_remove_from_heap(struct dn_heap *h, struct dn_pipe *p)
1732 {
1733 if (h->elements > 0) {
1734 int i = 0 ;
1735 for (i=0; i < h->elements ; i++ ) {
1736 if (h->p[i].object == p) { /* found it */
1737 h->elements-- ;
1738 h->p[i] = h->p[h->elements] ;
1739 heapify(h);
1740 break ;
1741 }
1742 }
1743 }
1744 }
1745
1746 /*
1747 * drain all queues. Called in case of severe mbuf shortage.
1748 */
1749 void
1750 dummynet_drain()
1751 {
1752 struct dn_flow_set *fs;
1753 struct dn_pipe *p;
1754 struct mbuf *m, *mnext;
1755
1756 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
1757
1758 heap_free(&ready_heap);
1759 heap_free(&wfq_ready_heap);
1760 heap_free(&extract_heap);
1761 /* remove all references to this pipe from flow_sets */
1762 for (fs = all_flow_sets; fs; fs= fs->next )
1763 purge_flow_set(fs, 0);
1764
1765 for (p = all_pipes; p; p= p->next ) {
1766 purge_flow_set(&(p->fs), 0);
1767
1768 mnext = p->head;
1769 while ((m = mnext) != NULL) {
1770 mnext = m->m_nextpkt;
1771 DN_FREE_PKT(m);
1772 }
1773 p->head = p->tail = NULL ;
1774 }
1775 }
1776
1777 /*
1778 * Fully delete a pipe or a queue, cleaning up associated info.
1779 */
1780 static int
1781 delete_pipe(struct dn_pipe *p)
1782 {
1783 if (p->pipe_nr == 0 && p->fs.fs_nr == 0)
1784 return EINVAL ;
1785 if (p->pipe_nr != 0 && p->fs.fs_nr != 0)
1786 return EINVAL ;
1787 if (p->pipe_nr != 0) { /* this is an old-style pipe */
1788 struct dn_pipe *a, *b;
1789 struct dn_flow_set *fs;
1790
1791 lck_mtx_lock(dn_mutex);
1792 /* locate pipe */
1793 for (a = NULL , b = all_pipes ; b && b->pipe_nr < p->pipe_nr ;
1794 a = b , b = b->next) ;
1795 if (b == NULL || (b->pipe_nr != p->pipe_nr) ) {
1796 lck_mtx_unlock(dn_mutex);
1797 return EINVAL ; /* not found */
1798 }
1799
1800 /* unlink from list of pipes */
1801 if (a == NULL)
1802 all_pipes = b->next ;
1803 else
1804 a->next = b->next ;
1805 /* remove references to this pipe from the ip_fw rules. */
1806 flush_pipe_ptrs(&(b->fs));
1807
1808 /* remove all references to this pipe from flow_sets */
1809 for (fs = all_flow_sets; fs; fs= fs->next )
1810 if (fs->pipe == b) {
1811 printf("dummynet: ++ ref to pipe %d from fs %d\n",
1812 p->pipe_nr, fs->fs_nr);
1813 fs->pipe = NULL ;
1814 purge_flow_set(fs, 0);
1815 }
1816 fs_remove_from_heap(&ready_heap, &(b->fs));
1817 purge_pipe(b); /* remove all data associated to this pipe */
1818 /* remove reference to here from extract_heap and wfq_ready_heap */
1819 pipe_remove_from_heap(&extract_heap, b);
1820 pipe_remove_from_heap(&wfq_ready_heap, b);
1821 lck_mtx_unlock(dn_mutex);
1822
1823 FREE(b, M_DUMMYNET);
1824 } else { /* this is a WF2Q queue (dn_flow_set) */
1825 struct dn_flow_set *a, *b;
1826
1827 lck_mtx_lock(dn_mutex);
1828 /* locate set */
1829 for (a = NULL, b = all_flow_sets ; b && b->fs_nr < p->fs.fs_nr ;
1830 a = b , b = b->next) ;
1831 if (b == NULL || (b->fs_nr != p->fs.fs_nr) ) {
1832 lck_mtx_unlock(dn_mutex);
1833 return EINVAL ; /* not found */
1834 }
1835
1836 if (a == NULL)
1837 all_flow_sets = b->next ;
1838 else
1839 a->next = b->next ;
1840 /* remove references to this flow_set from the ip_fw rules. */
1841 flush_pipe_ptrs(b);
1842
1843 if (b->pipe != NULL) {
1844 /* Update total weight on parent pipe and cleanup parent heaps */
1845 b->pipe->sum -= b->weight * b->backlogged ;
1846 fs_remove_from_heap(&(b->pipe->not_eligible_heap), b);
1847 fs_remove_from_heap(&(b->pipe->scheduler_heap), b);
1848 #if 1 /* XXX should i remove from idle_heap as well ? */
1849 fs_remove_from_heap(&(b->pipe->idle_heap), b);
1850 #endif
1851 }
1852 purge_flow_set(b, 1);
1853 lck_mtx_unlock(dn_mutex);
1854 }
1855 return 0 ;
1856 }
1857
1858 /*
1859 * helper function used to copy data from kernel in DUMMYNET_GET
1860 */
1861 static char *
1862 dn_copy_set(struct dn_flow_set *set, char *bp)
1863 {
1864 int i, copied = 0 ;
1865 struct dn_flow_queue *q, *qp = (struct dn_flow_queue *)bp;
1866
1867 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
1868
1869 for (i = 0 ; i <= set->rq_size ; i++)
1870 for (q = set->rq[i] ; q ; q = q->next, qp++ ) {
1871 if (q->hash_slot != i)
1872 printf("dummynet: ++ at %d: wrong slot (have %d, "
1873 "should be %d)\n", copied, q->hash_slot, i);
1874 if (q->fs != set)
1875 printf("dummynet: ++ at %d: wrong fs ptr (have %p, should be %p)\n",
1876 i, q->fs, set);
1877 copied++ ;
1878 bcopy(q, qp, sizeof( *q ) );
1879 /* cleanup pointers */
1880 qp->next = NULL ;
1881 qp->head = qp->tail = NULL ;
1882 qp->fs = NULL ;
1883 }
1884 if (copied != set->rq_elements)
1885 printf("dummynet: ++ wrong count, have %d should be %d\n",
1886 copied, set->rq_elements);
1887 return (char *)qp ;
1888 }
1889
1890 static size_t
1891 dn_calc_size(void)
1892 {
1893 struct dn_flow_set *set ;
1894 struct dn_pipe *p ;
1895 size_t size ;
1896
1897 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
1898
1899 /*
1900 * compute size of data structures: list of pipes and flow_sets.
1901 */
1902 for (p = all_pipes, size = 0 ; p ; p = p->next )
1903 size += sizeof( *p ) +
1904 p->fs.rq_elements * sizeof(struct dn_flow_queue);
1905 for (set = all_flow_sets ; set ; set = set->next )
1906 size += sizeof ( *set ) +
1907 set->rq_elements * sizeof(struct dn_flow_queue);
1908 return size ;
1909 }
1910
1911 static int
1912 dummynet_get(struct sockopt *sopt)
1913 {
1914 char *buf, *bp ; /* bp is the "copy-pointer" */
1915 size_t size ;
1916 struct dn_flow_set *set ;
1917 struct dn_pipe *p ;
1918 int error=0, i ;
1919
1920 /* XXX lock held too long */
1921 lck_mtx_lock(dn_mutex);
1922 /*
1923 * XXX: Ugly, but we need to allocate memory with M_WAITOK flag and we
1924 * cannot use this flag while holding a mutex.
1925 */
1926 for (i = 0; i < 10; i++) {
1927 size = dn_calc_size();
1928 lck_mtx_unlock(dn_mutex);
1929 buf = _MALLOC(size, M_TEMP, M_WAITOK);
1930 lck_mtx_lock(dn_mutex);
1931 if (size == dn_calc_size())
1932 break;
1933 FREE(buf, M_TEMP);
1934 buf = NULL;
1935 }
1936 if (buf == NULL) {
1937 lck_mtx_unlock(dn_mutex);
1938 return ENOBUFS ;
1939 }
1940 for (p = all_pipes, bp = buf ; p ; p = p->next ) {
1941 struct dn_pipe *pipe_bp = (struct dn_pipe *)bp ;
1942
1943 /*
1944 * copy pipe descriptor into *bp, convert delay back to ms,
1945 * then copy the flow_set descriptor(s) one at a time.
1946 * After each flow_set, copy the queue descriptor it owns.
1947 */
1948 bcopy(p, bp, sizeof( *p ) );
1949 pipe_bp->delay = (pipe_bp->delay * 1000) / hz ;
1950 /*
1951 * XXX the following is a hack based on ->next being the
1952 * first field in dn_pipe and dn_flow_set. The correct
1953 * solution would be to move the dn_flow_set to the beginning
1954 * of struct dn_pipe.
1955 */
1956 pipe_bp->next = (struct dn_pipe *)DN_IS_PIPE ;
1957 /* clean pointers */
1958 pipe_bp->head = pipe_bp->tail = NULL ;
1959 pipe_bp->fs.next = NULL ;
1960 pipe_bp->fs.pipe = NULL ;
1961 pipe_bp->fs.rq = NULL ;
1962
1963 bp += sizeof( *p ) ;
1964 bp = dn_copy_set( &(p->fs), bp );
1965 }
1966 for (set = all_flow_sets ; set ; set = set->next ) {
1967 struct dn_flow_set *fs_bp = (struct dn_flow_set *)bp ;
1968 bcopy(set, bp, sizeof( *set ) );
1969 /* XXX same hack as above */
1970 fs_bp->next = (struct dn_flow_set *)DN_IS_QUEUE ;
1971 fs_bp->pipe = NULL ;
1972 fs_bp->rq = NULL ;
1973 bp += sizeof( *set ) ;
1974 bp = dn_copy_set( set, bp );
1975 }
1976 lck_mtx_unlock(dn_mutex);
1977
1978 error = sooptcopyout(sopt, buf, size);
1979 FREE(buf, M_TEMP);
1980 return error ;
1981 }
1982
1983 /*
1984 * Handler for the various dummynet socket options (get, flush, config, del)
1985 */
1986 static int
1987 ip_dn_ctl(struct sockopt *sopt)
1988 {
1989 int error = 0 ;
1990 struct dn_pipe *p, tmp_pipe;
1991
1992 /* Disallow sets in really-really secure mode. */
1993 if (sopt->sopt_dir == SOPT_SET && securelevel >= 3)
1994 return (EPERM);
1995
1996 switch (sopt->sopt_name) {
1997 default :
1998 printf("dummynet: -- unknown option %d", sopt->sopt_name);
1999 return EINVAL ;
2000
2001 case IP_DUMMYNET_GET :
2002 error = dummynet_get(sopt);
2003 break ;
2004
2005 case IP_DUMMYNET_FLUSH :
2006 dummynet_flush() ;
2007 break ;
2008
2009 case IP_DUMMYNET_CONFIGURE :
2010 p = &tmp_pipe ;
2011 error = sooptcopyin(sopt, p, sizeof *p, sizeof *p);
2012 if (error)
2013 break ;
2014 error = config_pipe(p);
2015 break ;
2016
2017 case IP_DUMMYNET_DEL : /* remove a pipe or queue */
2018 p = &tmp_pipe ;
2019 error = sooptcopyin(sopt, p, sizeof *p, sizeof *p);
2020 if (error)
2021 break ;
2022
2023 error = delete_pipe(p);
2024 break ;
2025 }
2026 return error ;
2027 }
2028
2029 void
2030 ip_dn_init(void)
2031 {
2032 /* setup locks */
2033 dn_mutex_grp_attr = lck_grp_attr_alloc_init();
2034 dn_mutex_grp = lck_grp_alloc_init("dn", dn_mutex_grp_attr);
2035 dn_mutex_attr = lck_attr_alloc_init();
2036 lck_attr_setdefault(dn_mutex_attr);
2037
2038 if ((dn_mutex = lck_mtx_alloc_init(dn_mutex_grp, dn_mutex_attr)) == NULL) {
2039 printf("ip_dn_init: can't alloc dn_mutex\n");
2040 return;
2041 }
2042
2043 all_pipes = NULL ;
2044 all_flow_sets = NULL ;
2045 ready_heap.size = ready_heap.elements = 0 ;
2046 ready_heap.offset = 0 ;
2047
2048 wfq_ready_heap.size = wfq_ready_heap.elements = 0 ;
2049 wfq_ready_heap.offset = 0 ;
2050
2051 extract_heap.size = extract_heap.elements = 0 ;
2052 extract_heap.offset = 0 ;
2053 ip_dn_ctl_ptr = ip_dn_ctl;
2054 ip_dn_io_ptr = dummynet_io;
2055 ip_dn_ruledel_ptr = dn_rule_delete;
2056
2057 timeout(dummynet, NULL, 1);
2058 }