]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/ip_dummynet.c
xnu-1456.1.26.tar.gz
[apple/xnu.git] / bsd / netinet / ip_dummynet.c
1 /*
2 * Copyright (c) 2000-2008 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_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 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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1998-2002 Luigi Rizzo, Universita` di Pisa
30 * Portions Copyright (c) 2000 Akamba Corp.
31 * All rights reserved
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
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.
41 *
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
52 * SUCH DAMAGE.
53 *
54 * $FreeBSD: src/sys/netinet/ip_dummynet.c,v 1.84 2004/08/25 09:31:30 pjd Exp $
55 */
56
57 #define DUMMYNET_DEBUG
58
59 /*
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.
68 *
69 * NOTA BENE: critical sections are protected by the "dummynet lock".
70 *
71 * Most important Changes:
72 *
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
78 *
79 * include files marked with XXX are probably not needed
80 */
81
82 #include <sys/param.h>
83 #include <sys/systm.h>
84 #include <sys/malloc.h>
85 #include <sys/mbuf.h>
86 #include <sys/queue.h> /* XXX */
87 #include <sys/kernel.h>
88 #include <sys/socket.h>
89 #include <sys/socketvar.h>
90 #include <sys/time.h>
91 #include <sys/sysctl.h>
92 #include <net/if.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>
102
103 #if BRIDGE
104 #include <netinet/if_ether.h> /* for struct arpcom */
105 #include <net/bridge.h>
106 #endif
107
108 /*
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)
111 */
112 static dn_key curr_time = 0 ; /* current simulation time */
113
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;
117
118 static int dn_hash_size = 64 ; /* default hash size */
119
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 */
124
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 */
128
129 /*
130 * Three heaps contain queues and pipes that the scheduler handles:
131 *
132 * ready_heap contains all dn_flow_queue related to fixed-rate pipes.
133 *
134 * wfq_ready_heap contains the pipes associated with WF2Q flows
135 *
136 * extract_heap contains pipes associated with delay lines.
137 *
138 */
139 static struct dn_heap ready_heap, extract_heap, wfq_ready_heap ;
140
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);
144
145
146 static void transmit_event(struct dn_pipe *pipe, struct mbuf **head,
147 struct mbuf **tail);
148 static void ready_event(struct dn_flow_queue *q, struct mbuf **head,
149 struct mbuf **tail);
150 static void ready_event_wfq(struct dn_pipe *p, struct mbuf **head,
151 struct mbuf **tail);
152
153 /*
154 * Packets are retrieved from queues in Dummynet in chains instead of
155 * packet-by-packet. The entire list of packets is first dequeued and
156 * sent out by the following function.
157 */
158 static void dummynet_send(struct mbuf *m);
159
160 /* Flag to signify the existance of a dequeued packet chain */
161 static int serialize = 0;
162
163 #define HASHSIZE 16
164 #define HASH(num) ((((num) >> 8) ^ ((num) >> 4) ^ (num)) & 0x0f)
165 static struct dn_pipe_head pipehash[HASHSIZE]; /* all pipes */
166 static struct dn_flow_set_head flowsethash[HASHSIZE]; /* all flowsets */
167
168
169 #ifdef SYSCTL_NODE
170 SYSCTL_NODE(_net_inet_ip, OID_AUTO, dummynet,
171 CTLFLAG_RW, 0, "Dummynet");
172 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, hash_size,
173 CTLFLAG_RW, &dn_hash_size, 0, "Default hash table size");
174 SYSCTL_QUAD(_net_inet_ip_dummynet, OID_AUTO, curr_time,
175 CTLFLAG_RD, &curr_time, "Current tick");
176 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, ready_heap,
177 CTLFLAG_RD, &ready_heap.size, 0, "Size of ready heap");
178 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, extract_heap,
179 CTLFLAG_RD, &extract_heap.size, 0, "Size of extract heap");
180 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, searches,
181 CTLFLAG_RD, &searches, 0, "Number of queue searches");
182 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, search_steps,
183 CTLFLAG_RD, &search_steps, 0, "Number of queue search steps");
184 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, expire,
185 CTLFLAG_RW, &pipe_expire, 0, "Expire queue if empty");
186 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, max_chain_len,
187 CTLFLAG_RW, &dn_max_ratio, 0,
188 "Max ratio between dynamic queues and buckets");
189 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_lookup_depth,
190 CTLFLAG_RD, &red_lookup_depth, 0, "Depth of RED lookup table");
191 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_avg_pkt_size,
192 CTLFLAG_RD, &red_avg_pkt_size, 0, "RED Medium packet size");
193 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, red_max_pkt_size,
194 CTLFLAG_RD, &red_max_pkt_size, 0, "RED Max packet size");
195 #endif
196
197 #ifdef DUMMYNET_DEBUG
198 int dummynet_debug = 0;
199 #ifdef SYSCTL_NODE
200 SYSCTL_INT(_net_inet_ip_dummynet, OID_AUTO, debug, CTLFLAG_RW, &dummynet_debug,
201 0, "control debugging printfs");
202 #endif
203 #define DPRINTF(X) if (dummynet_debug) printf X
204 #else
205 #define DPRINTF(X)
206 #endif
207
208 /* contrary to the comment above random(), it does not actually
209 * return a value [0, 2^31 - 1], which breaks plr amongst other
210 * things. Masking it should work even if the behavior of
211 * the function is fixed.
212 */
213 #define MY_RANDOM (random() & 0x7FFFFFFF)
214
215 /* dummynet lock */
216 static lck_grp_t *dn_mutex_grp;
217 static lck_grp_attr_t *dn_mutex_grp_attr;
218 static lck_attr_t *dn_mutex_attr;
219 static lck_mtx_t *dn_mutex;
220
221 static int config_pipe(struct dn_pipe *p);
222 static int ip_dn_ctl(struct sockopt *sopt);
223
224 static void dummynet(void *);
225 static void dummynet_flush(void);
226 void dummynet_drain(void);
227 static ip_dn_io_t dummynet_io;
228 static void dn_rule_delete(void *);
229
230 int if_tx_rdy(struct ifnet *ifp);
231
232 static void cp_flow_set_to_64_user(struct dn_flow_set *set, struct dn_flow_set_64 *fs_bp);
233 static void cp_queue_to_64_user( struct dn_flow_queue *q, struct dn_flow_queue_64 *qp);
234 static char *cp_pipe_to_64_user(struct dn_pipe *p, struct dn_pipe_64 *pipe_bp);
235 static char* dn_copy_set_64(struct dn_flow_set *set, char *bp);
236 static int cp_pipe_from_user_64( struct sockopt *sopt, struct dn_pipe *p );
237
238 static void cp_flow_set_to_32_user(struct dn_flow_set *set, struct dn_flow_set_32 *fs_bp);
239 static void cp_queue_to_32_user( struct dn_flow_queue *q, struct dn_flow_queue_32 *qp);
240 static char *cp_pipe_to_32_user(struct dn_pipe *p, struct dn_pipe_32 *pipe_bp);
241 static char* dn_copy_set_32(struct dn_flow_set *set, char *bp);
242 static int cp_pipe_from_user_32( struct sockopt *sopt, struct dn_pipe *p );
243
244
245 /*
246 * Heap management functions.
247 *
248 * In the heap, first node is element 0. Children of i are 2i+1 and 2i+2.
249 * Some macros help finding parent/children so we can optimize them.
250 *
251 * heap_init() is called to expand the heap when needed.
252 * Increment size in blocks of 16 entries.
253 * XXX failure to allocate a new element is a pretty bad failure
254 * as we basically stall a whole queue forever!!
255 * Returns 1 on error, 0 on success
256 */
257 #define HEAP_FATHER(x) ( ( (x) - 1 ) / 2 )
258 #define HEAP_LEFT(x) ( 2*(x) + 1 )
259 #define HEAP_IS_LEFT(x) ( (x) & 1 )
260 #define HEAP_RIGHT(x) ( 2*(x) + 2 )
261 #define HEAP_SWAP(a, b, buffer) { buffer = a ; a = b ; b = buffer ; }
262 #define HEAP_INCREMENT 15
263
264
265 int cp_pipe_from_user_32( struct sockopt *sopt, struct dn_pipe *p )
266 {
267 struct dn_pipe_32 user_pipe_32;
268 int error=0;
269
270 error = sooptcopyin(sopt, &user_pipe_32, sizeof(struct dn_pipe_32), sizeof(struct dn_pipe_32));
271 if ( !error ){
272 p->pipe_nr = user_pipe_32.pipe_nr;
273 p->bandwidth = user_pipe_32.bandwidth;
274 p->delay = user_pipe_32.delay;
275 p->V = user_pipe_32.V;
276 p->sum = user_pipe_32.sum;
277 p->numbytes = user_pipe_32.numbytes;
278 p->sched_time = user_pipe_32.sched_time;
279 bcopy( user_pipe_32.if_name, p->if_name, IFNAMSIZ);
280 p->ready = user_pipe_32.ready;
281
282 p->fs.fs_nr = user_pipe_32.fs.fs_nr;
283 p->fs.flags_fs = user_pipe_32.fs.flags_fs;
284 p->fs.parent_nr = user_pipe_32.fs.parent_nr;
285 p->fs.weight = user_pipe_32.fs.weight;
286 p->fs.qsize = user_pipe_32.fs.qsize;
287 p->fs.plr = user_pipe_32.fs.plr;
288 p->fs.flow_mask = user_pipe_32.fs.flow_mask;
289 p->fs.rq_size = user_pipe_32.fs.rq_size;
290 p->fs.rq_elements = user_pipe_32.fs.rq_elements;
291 p->fs.last_expired = user_pipe_32.fs.last_expired;
292 p->fs.backlogged = user_pipe_32.fs.backlogged;
293 p->fs.w_q = user_pipe_32.fs.w_q;
294 p->fs.max_th = user_pipe_32.fs.max_th;
295 p->fs.min_th = user_pipe_32.fs.min_th;
296 p->fs.max_p = user_pipe_32.fs.max_p;
297 p->fs.c_1 = user_pipe_32.fs.c_1;
298 p->fs.c_2 = user_pipe_32.fs.c_2;
299 p->fs.c_3 = user_pipe_32.fs.c_3;
300 p->fs.c_4 = user_pipe_32.fs.c_4;
301 p->fs.lookup_depth = user_pipe_32.fs.lookup_depth;
302 p->fs.lookup_step = user_pipe_32.fs.lookup_step;
303 p->fs.lookup_weight = user_pipe_32.fs.lookup_weight;
304 p->fs.avg_pkt_size = user_pipe_32.fs.avg_pkt_size;
305 p->fs.max_pkt_size = user_pipe_32.fs.max_pkt_size;
306 }
307 return error;
308 }
309
310
311 int cp_pipe_from_user_64( struct sockopt *sopt, struct dn_pipe *p )
312 {
313 struct dn_pipe_64 user_pipe_64;
314 int error=0;
315
316 error = sooptcopyin(sopt, &user_pipe_64, sizeof(struct dn_pipe_64), sizeof(struct dn_pipe_64));
317 if ( !error ){
318 p->pipe_nr = user_pipe_64.pipe_nr;
319 p->bandwidth = user_pipe_64.bandwidth;
320 p->delay = user_pipe_64.delay;
321 p->V = user_pipe_64.V;
322 p->sum = user_pipe_64.sum;
323 p->numbytes = user_pipe_64.numbytes;
324 p->sched_time = user_pipe_64.sched_time;
325 bcopy( user_pipe_64.if_name, p->if_name, IFNAMSIZ);
326 p->ready = user_pipe_64.ready;
327
328 p->fs.fs_nr = user_pipe_64.fs.fs_nr;
329 p->fs.flags_fs = user_pipe_64.fs.flags_fs;
330 p->fs.parent_nr = user_pipe_64.fs.parent_nr;
331 p->fs.weight = user_pipe_64.fs.weight;
332 p->fs.qsize = user_pipe_64.fs.qsize;
333 p->fs.plr = user_pipe_64.fs.plr;
334 p->fs.flow_mask = user_pipe_64.fs.flow_mask;
335 p->fs.rq_size = user_pipe_64.fs.rq_size;
336 p->fs.rq_elements = user_pipe_64.fs.rq_elements;
337 p->fs.last_expired = user_pipe_64.fs.last_expired;
338 p->fs.backlogged = user_pipe_64.fs.backlogged;
339 p->fs.w_q = user_pipe_64.fs.w_q;
340 p->fs.max_th = user_pipe_64.fs.max_th;
341 p->fs.min_th = user_pipe_64.fs.min_th;
342 p->fs.max_p = user_pipe_64.fs.max_p;
343 p->fs.c_1 = user_pipe_64.fs.c_1;
344 p->fs.c_2 = user_pipe_64.fs.c_2;
345 p->fs.c_3 = user_pipe_64.fs.c_3;
346 p->fs.c_4 = user_pipe_64.fs.c_4;
347 p->fs.lookup_depth = user_pipe_64.fs.lookup_depth;
348 p->fs.lookup_step = user_pipe_64.fs.lookup_step;
349 p->fs.lookup_weight = user_pipe_64.fs.lookup_weight;
350 p->fs.avg_pkt_size = user_pipe_64.fs.avg_pkt_size;
351 p->fs.max_pkt_size = user_pipe_64.fs.max_pkt_size;
352 }
353 return error;
354 }
355
356 static void
357 cp_flow_set_to_32_user(struct dn_flow_set *set, struct dn_flow_set_32 *fs_bp)
358 {
359 fs_bp->fs_nr = set->fs_nr;
360 fs_bp->flags_fs = set->flags_fs ;
361 fs_bp->parent_nr = set->parent_nr ;
362 fs_bp->weight = set->weight ;
363 fs_bp->qsize = set->qsize ;
364 fs_bp->plr = set->plr ;
365 fs_bp->flow_mask = set->flow_mask ;
366 fs_bp->rq_size = set->rq_size ;
367 fs_bp->rq_elements = set->rq_elements ;
368 fs_bp->last_expired = set->last_expired ;
369 fs_bp->backlogged = set->backlogged ;
370 fs_bp->w_q = set->w_q ;
371 fs_bp->max_th = set->max_th ;
372 fs_bp->min_th = set->min_th ;
373 fs_bp->max_p = set->max_p ;
374 fs_bp->c_1 = set->c_1 ;
375 fs_bp->c_2 = set->c_2 ;
376 fs_bp->c_3 = set->c_3 ;
377 fs_bp->c_4 = set->c_4 ;
378 fs_bp->w_q_lookup = CAST_DOWN_EXPLICIT(user32_addr_t, set->w_q_lookup) ;
379 fs_bp->lookup_depth = set->lookup_depth ;
380 fs_bp->lookup_step = set->lookup_step ;
381 fs_bp->lookup_weight = set->lookup_weight ;
382 fs_bp->avg_pkt_size = set->avg_pkt_size ;
383 fs_bp->max_pkt_size = set->max_pkt_size ;
384 }
385
386 static void
387 cp_flow_set_to_64_user(struct dn_flow_set *set, struct dn_flow_set_64 *fs_bp)
388 {
389 fs_bp->fs_nr = set->fs_nr;
390 fs_bp->flags_fs = set->flags_fs ;
391 fs_bp->parent_nr = set->parent_nr ;
392 fs_bp->weight = set->weight ;
393 fs_bp->qsize = set->qsize ;
394 fs_bp->plr = set->plr ;
395 fs_bp->flow_mask = set->flow_mask ;
396 fs_bp->rq_size = set->rq_size ;
397 fs_bp->rq_elements = set->rq_elements ;
398 fs_bp->last_expired = set->last_expired ;
399 fs_bp->backlogged = set->backlogged ;
400 fs_bp->w_q = set->w_q ;
401 fs_bp->max_th = set->max_th ;
402 fs_bp->min_th = set->min_th ;
403 fs_bp->max_p = set->max_p ;
404 fs_bp->c_1 = set->c_1 ;
405 fs_bp->c_2 = set->c_2 ;
406 fs_bp->c_3 = set->c_3 ;
407 fs_bp->c_4 = set->c_4 ;
408 fs_bp->w_q_lookup = CAST_DOWN(user64_addr_t, set->w_q_lookup) ;
409 fs_bp->lookup_depth = set->lookup_depth ;
410 fs_bp->lookup_step = set->lookup_step ;
411 fs_bp->lookup_weight = set->lookup_weight ;
412 fs_bp->avg_pkt_size = set->avg_pkt_size ;
413 fs_bp->max_pkt_size = set->max_pkt_size ;
414 }
415
416 static
417 void cp_queue_to_32_user( struct dn_flow_queue *q, struct dn_flow_queue_32 *qp)
418 {
419 qp->id = q->id;
420 qp->len = q->len;
421 qp->len_bytes = q->len_bytes;
422 qp->numbytes = q->numbytes;
423 qp->tot_pkts = q->tot_pkts;
424 qp->tot_bytes = q->tot_bytes;
425 qp->drops = q->drops;
426 qp->hash_slot = q->hash_slot;
427 qp->avg = q->avg;
428 qp->count = q->count;
429 qp->random = q->random;
430 qp->q_time = q->q_time;
431 qp->heap_pos = q->heap_pos;
432 qp->sched_time = q->sched_time;
433 qp->S = q->S;
434 qp->F = q->F;
435 }
436
437 static
438 void cp_queue_to_64_user( struct dn_flow_queue *q, struct dn_flow_queue_64 *qp)
439 {
440 qp->id = q->id;
441 qp->len = q->len;
442 qp->len_bytes = q->len_bytes;
443 qp->numbytes = q->numbytes;
444 qp->tot_pkts = q->tot_pkts;
445 qp->tot_bytes = q->tot_bytes;
446 qp->drops = q->drops;
447 qp->hash_slot = q->hash_slot;
448 qp->avg = q->avg;
449 qp->count = q->count;
450 qp->random = q->random;
451 qp->q_time = q->q_time;
452 qp->heap_pos = q->heap_pos;
453 qp->sched_time = q->sched_time;
454 qp->S = q->S;
455 qp->F = q->F;
456 }
457
458 static
459 char *cp_pipe_to_32_user(struct dn_pipe *p, struct dn_pipe_32 *pipe_bp)
460 {
461 char *bp;
462
463 pipe_bp->pipe_nr = p->pipe_nr;
464 pipe_bp->bandwidth = p->bandwidth;
465 bcopy( &(p->scheduler_heap), &(pipe_bp->scheduler_heap), sizeof(struct dn_heap_32));
466 pipe_bp->scheduler_heap.p = CAST_DOWN_EXPLICIT(user32_addr_t, pipe_bp->scheduler_heap.p);
467 bcopy( &(p->not_eligible_heap), &(pipe_bp->not_eligible_heap), sizeof(struct dn_heap_32));
468 pipe_bp->not_eligible_heap.p = CAST_DOWN_EXPLICIT(user32_addr_t, pipe_bp->not_eligible_heap.p);
469 bcopy( &(p->idle_heap), &(pipe_bp->idle_heap), sizeof(struct dn_heap_32));
470 pipe_bp->idle_heap.p = CAST_DOWN_EXPLICIT(user32_addr_t, pipe_bp->idle_heap.p);
471 pipe_bp->V = p->V;
472 pipe_bp->sum = p->sum;
473 pipe_bp->numbytes = p->numbytes;
474 pipe_bp->sched_time = p->sched_time;
475 bcopy( p->if_name, pipe_bp->if_name, IFNAMSIZ);
476 pipe_bp->ifp = CAST_DOWN_EXPLICIT(user32_addr_t, p->ifp);
477 pipe_bp->ready = p->ready;
478
479 cp_flow_set_to_32_user( &(p->fs), &(pipe_bp->fs));
480
481 pipe_bp->delay = (pipe_bp->delay * 1000) / (hz*10) ;
482 /*
483 * XXX the following is a hack based on ->next being the
484 * first field in dn_pipe and dn_flow_set. The correct
485 * solution would be to move the dn_flow_set to the beginning
486 * of struct dn_pipe.
487 */
488 pipe_bp->next = CAST_DOWN_EXPLICIT( user32_addr_t, DN_IS_PIPE );
489 /* clean pointers */
490 pipe_bp->head = pipe_bp->tail = (user32_addr_t) 0 ;
491 pipe_bp->fs.next = (user32_addr_t)0 ;
492 pipe_bp->fs.pipe = (user32_addr_t)0 ;
493 pipe_bp->fs.rq = (user32_addr_t)0 ;
494 bp = ((char *)pipe_bp) + sizeof(struct dn_pipe_32);
495 return( dn_copy_set_32( &(p->fs), bp) );
496 }
497
498 static
499 char *cp_pipe_to_64_user(struct dn_pipe *p, struct dn_pipe_64 *pipe_bp)
500 {
501 char *bp;
502
503 pipe_bp->pipe_nr = p->pipe_nr;
504 pipe_bp->bandwidth = p->bandwidth;
505 bcopy( &(p->scheduler_heap), &(pipe_bp->scheduler_heap), sizeof(struct dn_heap_64));
506 pipe_bp->scheduler_heap.p = CAST_DOWN(user64_addr_t, pipe_bp->scheduler_heap.p);
507 bcopy( &(p->not_eligible_heap), &(pipe_bp->not_eligible_heap), sizeof(struct dn_heap_64));
508 pipe_bp->not_eligible_heap.p = CAST_DOWN(user64_addr_t, pipe_bp->not_eligible_heap.p);
509 bcopy( &(p->idle_heap), &(pipe_bp->idle_heap), sizeof(struct dn_heap_64));
510 pipe_bp->idle_heap.p = CAST_DOWN(user64_addr_t, pipe_bp->idle_heap.p);
511 pipe_bp->V = p->V;
512 pipe_bp->sum = p->sum;
513 pipe_bp->numbytes = p->numbytes;
514 pipe_bp->sched_time = p->sched_time;
515 bcopy( p->if_name, pipe_bp->if_name, IFNAMSIZ);
516 pipe_bp->ifp = CAST_DOWN(user64_addr_t, p->ifp);
517 pipe_bp->ready = p->ready;
518
519 cp_flow_set_to_64_user( &(p->fs), &(pipe_bp->fs));
520
521 pipe_bp->delay = (pipe_bp->delay * 1000) / (hz*10) ;
522 /*
523 * XXX the following is a hack based on ->next being the
524 * first field in dn_pipe and dn_flow_set. The correct
525 * solution would be to move the dn_flow_set to the beginning
526 * of struct dn_pipe.
527 */
528 pipe_bp->next = CAST_DOWN( user64_addr_t, DN_IS_PIPE );
529 /* clean pointers */
530 pipe_bp->head = pipe_bp->tail = USER_ADDR_NULL ;
531 pipe_bp->fs.next = USER_ADDR_NULL ;
532 pipe_bp->fs.pipe = USER_ADDR_NULL ;
533 pipe_bp->fs.rq = USER_ADDR_NULL ;
534 bp = ((char *)pipe_bp) + sizeof(struct dn_pipe_64);
535 return( dn_copy_set_64( &(p->fs), bp) );
536 }
537
538 static int
539 heap_init(struct dn_heap *h, int new_size)
540 {
541 struct dn_heap_entry *p;
542
543 if (h->size >= new_size ) {
544 printf("dummynet: heap_init, Bogus call, have %d want %d\n",
545 h->size, new_size);
546 return 0 ;
547 }
548 new_size = (new_size + HEAP_INCREMENT ) & ~HEAP_INCREMENT ;
549 p = _MALLOC(new_size * sizeof(*p), M_DUMMYNET, M_DONTWAIT );
550 if (p == NULL) {
551 printf("dummynet: heap_init, resize %d failed\n", new_size );
552 return 1 ; /* error */
553 }
554 if (h->size > 0) {
555 bcopy(h->p, p, h->size * sizeof(*p) );
556 FREE(h->p, M_DUMMYNET);
557 }
558 h->p = p ;
559 h->size = new_size ;
560 return 0 ;
561 }
562
563 /*
564 * Insert element in heap. Normally, p != NULL, we insert p in
565 * a new position and bubble up. If p == NULL, then the element is
566 * already in place, and key is the position where to start the
567 * bubble-up.
568 * Returns 1 on failure (cannot allocate new heap entry)
569 *
570 * If offset > 0 the position (index, int) of the element in the heap is
571 * also stored in the element itself at the given offset in bytes.
572 */
573 #define SET_OFFSET(heap, node) \
574 if (heap->offset > 0) \
575 *((int *)((char *)(heap->p[node].object) + heap->offset)) = node ;
576 /*
577 * RESET_OFFSET is used for sanity checks. It sets offset to an invalid value.
578 */
579 #define RESET_OFFSET(heap, node) \
580 if (heap->offset > 0) \
581 *((int *)((char *)(heap->p[node].object) + heap->offset)) = -1 ;
582 static int
583 heap_insert(struct dn_heap *h, dn_key key1, void *p)
584 {
585 int son = h->elements ;
586
587 if (p == NULL) /* data already there, set starting point */
588 son = key1 ;
589 else { /* insert new element at the end, possibly resize */
590 son = h->elements ;
591 if (son == h->size) /* need resize... */
592 if (heap_init(h, h->elements+1) )
593 return 1 ; /* failure... */
594 h->p[son].object = p ;
595 h->p[son].key = key1 ;
596 h->elements++ ;
597 }
598 while (son > 0) { /* bubble up */
599 int father = HEAP_FATHER(son) ;
600 struct dn_heap_entry tmp ;
601
602 if (DN_KEY_LT( h->p[father].key, h->p[son].key ) )
603 break ; /* found right position */
604 /* son smaller than father, swap and repeat */
605 HEAP_SWAP(h->p[son], h->p[father], tmp) ;
606 SET_OFFSET(h, son);
607 son = father ;
608 }
609 SET_OFFSET(h, son);
610 return 0 ;
611 }
612
613 /*
614 * remove top element from heap, or obj if obj != NULL
615 */
616 static void
617 heap_extract(struct dn_heap *h, void *obj)
618 {
619 int child, father, maxelt = h->elements - 1 ;
620
621 if (maxelt < 0) {
622 printf("dummynet: warning, extract from empty heap 0x%p\n", h);
623 return ;
624 }
625 father = 0 ; /* default: move up smallest child */
626 if (obj != NULL) { /* extract specific element, index is at offset */
627 if (h->offset <= 0)
628 panic("dummynet: heap_extract from middle not supported on this heap!!!\n");
629 father = *((int *)((char *)obj + h->offset)) ;
630 if (father < 0 || father >= h->elements) {
631 printf("dummynet: heap_extract, father %d out of bound 0..%d\n",
632 father, h->elements);
633 panic("dummynet: heap_extract");
634 }
635 }
636 RESET_OFFSET(h, father);
637 child = HEAP_LEFT(father) ; /* left child */
638 while (child <= maxelt) { /* valid entry */
639 if (child != maxelt && DN_KEY_LT(h->p[child+1].key, h->p[child].key) )
640 child = child+1 ; /* take right child, otherwise left */
641 h->p[father] = h->p[child] ;
642 SET_OFFSET(h, father);
643 father = child ;
644 child = HEAP_LEFT(child) ; /* left child for next loop */
645 }
646 h->elements-- ;
647 if (father != maxelt) {
648 /*
649 * Fill hole with last entry and bubble up, reusing the insert code
650 */
651 h->p[father] = h->p[maxelt] ;
652 heap_insert(h, father, NULL); /* this one cannot fail */
653 }
654 }
655
656 #if 0
657 /*
658 * change object position and update references
659 * XXX this one is never used!
660 */
661 static void
662 heap_move(struct dn_heap *h, dn_key new_key, void *object)
663 {
664 int temp;
665 int i ;
666 int maxelt = h->elements-1 ;
667 struct dn_heap_entry buf ;
668
669 if (h->offset <= 0)
670 panic("cannot move items on this heap");
671
672 i = *((int *)((char *)object + h->offset));
673 if (DN_KEY_LT(new_key, h->p[i].key) ) { /* must move up */
674 h->p[i].key = new_key ;
675 for (; i>0 && DN_KEY_LT(new_key, h->p[(temp = HEAP_FATHER(i))].key) ;
676 i = temp ) { /* bubble up */
677 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
678 SET_OFFSET(h, i);
679 }
680 } else { /* must move down */
681 h->p[i].key = new_key ;
682 while ( (temp = HEAP_LEFT(i)) <= maxelt ) { /* found left child */
683 if ((temp != maxelt) && DN_KEY_GT(h->p[temp].key, h->p[temp+1].key))
684 temp++ ; /* select child with min key */
685 if (DN_KEY_GT(new_key, h->p[temp].key)) { /* go down */
686 HEAP_SWAP(h->p[i], h->p[temp], buf) ;
687 SET_OFFSET(h, i);
688 } else
689 break ;
690 i = temp ;
691 }
692 }
693 SET_OFFSET(h, i);
694 }
695 #endif /* heap_move, unused */
696
697 /*
698 * heapify() will reorganize data inside an array to maintain the
699 * heap property. It is needed when we delete a bunch of entries.
700 */
701 static void
702 heapify(struct dn_heap *h)
703 {
704 int i ;
705
706 for (i = 0 ; i < h->elements ; i++ )
707 heap_insert(h, i , NULL) ;
708 }
709
710 /*
711 * cleanup the heap and free data structure
712 */
713 static void
714 heap_free(struct dn_heap *h)
715 {
716 if (h->size >0 )
717 FREE(h->p, M_DUMMYNET);
718 bzero(h, sizeof(*h));
719 }
720
721 /*
722 * --- end of heap management functions ---
723 */
724
725 /*
726 * Return the mbuf tag holding the dummynet state. As an optimization
727 * this is assumed to be the first tag on the list. If this turns out
728 * wrong we'll need to search the list.
729 */
730 static struct dn_pkt_tag *
731 dn_tag_get(struct mbuf *m)
732 {
733 struct m_tag *mtag = m_tag_first(m);
734 /* KASSERT(mtag != NULL &&
735 mtag->m_tag_id == KERNEL_MODULE_TAG_ID &&
736 mtag->m_tag_type == KERNEL_TAG_TYPE_DUMMYNET,
737 ("packet on dummynet queue w/o dummynet tag!"));
738 */
739 return (struct dn_pkt_tag *)(mtag+1);
740 }
741
742 /*
743 * Scheduler functions:
744 *
745 * transmit_event() is called when the delay-line needs to enter
746 * the scheduler, either because of existing pkts getting ready,
747 * or new packets entering the queue. The event handled is the delivery
748 * time of the packet.
749 *
750 * ready_event() does something similar with fixed-rate queues, and the
751 * event handled is the finish time of the head pkt.
752 *
753 * wfq_ready_event() does something similar with WF2Q queues, and the
754 * event handled is the start time of the head pkt.
755 *
756 * In all cases, we make sure that the data structures are consistent
757 * before passing pkts out, because this might trigger recursive
758 * invocations of the procedures.
759 */
760 static void
761 transmit_event(struct dn_pipe *pipe, struct mbuf **head, struct mbuf **tail)
762 {
763 struct mbuf *m ;
764 struct dn_pkt_tag *pkt ;
765
766 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
767
768 /* Extract packets only if no pending chain is being currently processed */
769 if (serialize == 0) {
770 while ((m = pipe->head) != NULL) {
771 pkt = dn_tag_get(m);
772 if (!DN_KEY_LEQ(pkt->output_time, curr_time))
773 break;
774
775 pipe->head = m->m_nextpkt;
776 if (*tail != NULL)
777 (*tail)->m_nextpkt = m;
778 else
779 *head = m;
780 *tail = m;
781 }
782 if (*tail != NULL)
783 (*tail)->m_nextpkt = NULL;
784 }
785
786 /* if there are leftover packets, put the pipe into the heap for next ready event */
787 if ((m = pipe->head) != NULL) {
788 pkt = dn_tag_get(m);
789 /* XXX should check errors on heap_insert, by draining the
790 * whole pipe p and hoping in the future we are more successful
791 */
792 heap_insert(&extract_heap, pkt->output_time, pipe);
793 }
794 }
795
796 /*
797 * the following macro computes how many ticks we have to wait
798 * before being able to transmit a packet. The credit is taken from
799 * either a pipe (WF2Q) or a flow_queue (per-flow queueing)
800 */
801
802 /* hz is 100, which gives a granularity of 10ms in the old timer.
803 * The timer has been changed to fire every 1ms, so the use of
804 * hz has been modified here. All instances of hz have been left
805 * in place but adjusted by a factor of 10 so that hz is functionally
806 * equal to 1000.
807 */
808 #define SET_TICKS(_m, q, p) \
809 ((_m)->m_pkthdr.len*8*(hz*10) - (q)->numbytes + p->bandwidth - 1 ) / \
810 p->bandwidth ;
811
812 /*
813 * extract pkt from queue, compute output time (could be now)
814 * and put into delay line (p_queue)
815 */
816 static void
817 move_pkt(struct mbuf *pkt, struct dn_flow_queue *q,
818 struct dn_pipe *p, int len)
819 {
820 struct dn_pkt_tag *dt = dn_tag_get(pkt);
821
822 q->head = pkt->m_nextpkt ;
823 q->len-- ;
824 q->len_bytes -= len ;
825
826 dt->output_time = curr_time + p->delay ;
827
828 if (p->head == NULL)
829 p->head = pkt;
830 else
831 p->tail->m_nextpkt = pkt;
832 p->tail = pkt;
833 p->tail->m_nextpkt = NULL;
834 }
835
836 /*
837 * ready_event() is invoked every time the queue must enter the
838 * scheduler, either because the first packet arrives, or because
839 * a previously scheduled event fired.
840 * On invokation, drain as many pkts as possible (could be 0) and then
841 * if there are leftover packets reinsert the pkt in the scheduler.
842 */
843 static void
844 ready_event(struct dn_flow_queue *q, struct mbuf **head, struct mbuf **tail)
845 {
846 struct mbuf *pkt;
847 struct dn_pipe *p = q->fs->pipe ;
848 int p_was_empty ;
849
850 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
851
852 if (p == NULL) {
853 printf("dummynet: ready_event pipe is gone\n");
854 return ;
855 }
856 p_was_empty = (p->head == NULL) ;
857
858 /*
859 * schedule fixed-rate queues linked to this pipe:
860 * Account for the bw accumulated since last scheduling, then
861 * drain as many pkts as allowed by q->numbytes and move to
862 * the delay line (in p) computing output time.
863 * bandwidth==0 (no limit) means we can drain the whole queue,
864 * setting len_scaled = 0 does the job.
865 */
866 q->numbytes += ( curr_time - q->sched_time ) * p->bandwidth;
867 while ( (pkt = q->head) != NULL ) {
868 int len = pkt->m_pkthdr.len;
869 int len_scaled = p->bandwidth ? len*8*(hz*10) : 0 ;
870 if (len_scaled > q->numbytes )
871 break ;
872 q->numbytes -= len_scaled ;
873 move_pkt(pkt, q, p, len);
874 }
875 /*
876 * If we have more packets queued, schedule next ready event
877 * (can only occur when bandwidth != 0, otherwise we would have
878 * flushed the whole queue in the previous loop).
879 * To this purpose we record the current time and compute how many
880 * ticks to go for the finish time of the packet.
881 */
882 if ( (pkt = q->head) != NULL ) { /* this implies bandwidth != 0 */
883 dn_key t = SET_TICKS(pkt, q, p); /* ticks i have to wait */
884 q->sched_time = curr_time ;
885 heap_insert(&ready_heap, curr_time + t, (void *)q );
886 /* XXX should check errors on heap_insert, and drain the whole
887 * queue on error hoping next time we are luckier.
888 */
889 } else { /* RED needs to know when the queue becomes empty */
890 q->q_time = curr_time;
891 q->numbytes = 0;
892 }
893 /*
894 * If the delay line was empty call transmit_event(p) now.
895 * Otherwise, the scheduler will take care of it.
896 */
897 if (p_was_empty)
898 transmit_event(p, head, tail);
899 }
900
901 /*
902 * Called when we can transmit packets on WF2Q queues. Take pkts out of
903 * the queues at their start time, and enqueue into the delay line.
904 * Packets are drained until p->numbytes < 0. As long as
905 * len_scaled >= p->numbytes, the packet goes into the delay line
906 * with a deadline p->delay. For the last packet, if p->numbytes<0,
907 * there is an additional delay.
908 */
909 static void
910 ready_event_wfq(struct dn_pipe *p, struct mbuf **head, struct mbuf **tail)
911 {
912 int p_was_empty = (p->head == NULL) ;
913 struct dn_heap *sch = &(p->scheduler_heap);
914 struct dn_heap *neh = &(p->not_eligible_heap) ;
915 int64_t p_numbytes = p->numbytes;
916
917 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
918
919 if (p->if_name[0] == 0) /* tx clock is simulated */
920 p_numbytes += ( curr_time - p->sched_time ) * p->bandwidth;
921 else { /* tx clock is for real, the ifq must be empty or this is a NOP */
922 if (p->ifp && p->ifp->if_snd.ifq_head != NULL)
923 return ;
924 else {
925 DPRINTF(("dummynet: pipe %d ready from %s --\n",
926 p->pipe_nr, p->if_name));
927 }
928 }
929
930 /*
931 * While we have backlogged traffic AND credit, we need to do
932 * something on the queue.
933 */
934 while ( p_numbytes >=0 && (sch->elements>0 || neh->elements >0) ) {
935 if (sch->elements > 0) { /* have some eligible pkts to send out */
936 struct dn_flow_queue *q = sch->p[0].object ;
937 struct mbuf *pkt = q->head;
938 struct dn_flow_set *fs = q->fs;
939 u_int64_t len = pkt->m_pkthdr.len;
940 int len_scaled = p->bandwidth ? len*8*(hz*10) : 0 ;
941
942 heap_extract(sch, NULL); /* remove queue from heap */
943 p_numbytes -= len_scaled ;
944 move_pkt(pkt, q, p, len);
945
946 p->V += (len<<MY_M) / p->sum ; /* update V */
947 q->S = q->F ; /* update start time */
948 if (q->len == 0) { /* Flow not backlogged any more */
949 fs->backlogged-- ;
950 heap_insert(&(p->idle_heap), q->F, q);
951 } else { /* still backlogged */
952 /*
953 * update F and position in backlogged queue, then
954 * put flow in not_eligible_heap (we will fix this later).
955 */
956 len = (q->head)->m_pkthdr.len;
957 q->F += (len<<MY_M)/(u_int64_t) fs->weight ;
958 if (DN_KEY_LEQ(q->S, p->V))
959 heap_insert(neh, q->S, q);
960 else
961 heap_insert(sch, q->F, q);
962 }
963 }
964 /*
965 * now compute V = max(V, min(S_i)). Remember that all elements in sch
966 * have by definition S_i <= V so if sch is not empty, V is surely
967 * the max and we must not update it. Conversely, if sch is empty
968 * we only need to look at neh.
969 */
970 if (sch->elements == 0 && neh->elements > 0)
971 p->V = MAX64 ( p->V, neh->p[0].key );
972 /* move from neh to sch any packets that have become eligible */
973 while (neh->elements > 0 && DN_KEY_LEQ(neh->p[0].key, p->V) ) {
974 struct dn_flow_queue *q = neh->p[0].object ;
975 heap_extract(neh, NULL);
976 heap_insert(sch, q->F, q);
977 }
978
979 if (p->if_name[0] != '\0') {/* tx clock is from a real thing */
980 p_numbytes = -1 ; /* mark not ready for I/O */
981 break ;
982 }
983 }
984 if (sch->elements == 0 && neh->elements == 0 && p_numbytes >= 0
985 && p->idle_heap.elements > 0) {
986 /*
987 * no traffic and no events scheduled. We can get rid of idle-heap.
988 */
989 int i ;
990
991 for (i = 0 ; i < p->idle_heap.elements ; i++) {
992 struct dn_flow_queue *q = p->idle_heap.p[i].object ;
993
994 q->F = 0 ;
995 q->S = q->F + 1 ;
996 }
997 p->sum = 0 ;
998 p->V = 0 ;
999 p->idle_heap.elements = 0 ;
1000 }
1001 /*
1002 * If we are getting clocks from dummynet (not a real interface) and
1003 * If we are under credit, schedule the next ready event.
1004 * Also fix the delivery time of the last packet.
1005 */
1006 if (p->if_name[0]==0 && p_numbytes < 0) { /* this implies bandwidth >0 */
1007 dn_key t=0 ; /* number of ticks i have to wait */
1008
1009 if (p->bandwidth > 0)
1010 t = ( p->bandwidth -1 - p_numbytes) / p->bandwidth ;
1011 dn_tag_get(p->tail)->output_time += t ;
1012 p->sched_time = curr_time ;
1013 heap_insert(&wfq_ready_heap, curr_time + t, (void *)p);
1014 /* XXX should check errors on heap_insert, and drain the whole
1015 * queue on error hoping next time we are luckier.
1016 */
1017 }
1018
1019 /* Fit (adjust if necessary) 64bit result into 32bit variable. */
1020 if (p_numbytes > INT_MAX)
1021 p->numbytes = INT_MAX;
1022 else if (p_numbytes < INT_MIN)
1023 p->numbytes = INT_MIN;
1024 else
1025 p->numbytes = p_numbytes;
1026
1027 /*
1028 * If the delay line was empty call transmit_event(p) now.
1029 * Otherwise, the scheduler will take care of it.
1030 */
1031 if (p_was_empty)
1032 transmit_event(p, head, tail);
1033
1034 }
1035
1036 /*
1037 * This is called every 1ms. It is used to
1038 * increment the current tick counter and schedule expired events.
1039 */
1040 static void
1041 dummynet(__unused void * unused)
1042 {
1043 void *p ; /* generic parameter to handler */
1044 struct dn_heap *h ;
1045 struct dn_heap *heaps[3];
1046 struct mbuf *head = NULL, *tail = NULL;
1047 int i;
1048 struct dn_pipe *pe ;
1049 struct timespec ts;
1050 struct timeval tv;
1051
1052 heaps[0] = &ready_heap ; /* fixed-rate queues */
1053 heaps[1] = &wfq_ready_heap ; /* wfq queues */
1054 heaps[2] = &extract_heap ; /* delay line */
1055
1056 lck_mtx_lock(dn_mutex);
1057
1058 /* make all time measurements in milliseconds (ms) -
1059 * here we convert secs and usecs to msecs (just divide the
1060 * usecs and take the closest whole number).
1061 */
1062 microuptime(&tv);
1063 curr_time = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
1064
1065 for (i=0; i < 3 ; i++) {
1066 h = heaps[i];
1067 while (h->elements > 0 && DN_KEY_LEQ(h->p[0].key, curr_time) ) {
1068 if (h->p[0].key > curr_time)
1069 printf("dummynet: warning, heap %d is %d ticks late\n",
1070 i, (int)(curr_time - h->p[0].key));
1071 p = h->p[0].object ; /* store a copy before heap_extract */
1072 heap_extract(h, NULL); /* need to extract before processing */
1073 if (i == 0)
1074 ready_event(p, &head, &tail) ;
1075 else if (i == 1) {
1076 struct dn_pipe *pipe = p;
1077 if (pipe->if_name[0] != '\0')
1078 printf("dummynet: bad ready_event_wfq for pipe %s\n",
1079 pipe->if_name);
1080 else
1081 ready_event_wfq(p, &head, &tail) ;
1082 } else {
1083 transmit_event(p, &head, &tail);
1084 }
1085 }
1086 }
1087 /* sweep pipes trying to expire idle flow_queues */
1088 for (i = 0; i < HASHSIZE; i++)
1089 SLIST_FOREACH(pe, &pipehash[i], next)
1090 if (pe->idle_heap.elements > 0 &&
1091 DN_KEY_LT(pe->idle_heap.p[0].key, pe->V) ) {
1092 struct dn_flow_queue *q = pe->idle_heap.p[0].object ;
1093
1094 heap_extract(&(pe->idle_heap), NULL);
1095 q->S = q->F + 1 ; /* mark timestamp as invalid */
1096 pe->sum -= q->fs->weight ;
1097 }
1098
1099 /* check the heaps to see if there's still stuff in there, and
1100 * only set the timer if there are packets to process
1101 */
1102 timer_enabled = 0;
1103 for (i=0; i < 3 ; i++) {
1104 h = heaps[i];
1105 if (h->elements > 0) { // set the timer
1106 ts.tv_sec = 0;
1107 ts.tv_nsec = 1 * 1000000; // 1ms
1108 timer_enabled = 1;
1109 bsd_timeout(dummynet, NULL, &ts);
1110 break;
1111 }
1112 }
1113
1114 /*
1115 * If a packet chain has been dequeued, set serialize=1 so that new
1116 * packets don't get dispatched out of turn
1117 */
1118 if (head != NULL)
1119 serialize = 1;
1120
1121 lck_mtx_unlock(dn_mutex);
1122
1123 /* Send out the de-queued list of ready-to-send packets */
1124 if (head != NULL) {
1125 dummynet_send(head);
1126 lck_mtx_lock(dn_mutex);
1127 serialize = 0;
1128 lck_mtx_unlock(dn_mutex);
1129 }
1130 }
1131
1132
1133 static void
1134 dummynet_send(struct mbuf *m)
1135 {
1136 struct dn_pkt_tag *pkt;
1137 struct mbuf *n;
1138
1139 for (; m != NULL; m = n) {
1140 n = m->m_nextpkt;
1141 m->m_nextpkt = NULL;
1142 pkt = dn_tag_get(m);
1143
1144 switch (pkt->dn_dir) {
1145 case DN_TO_IP_OUT: {
1146 struct route tmp_rt = pkt->ro;
1147 (void)ip_output(m, NULL, &tmp_rt, pkt->flags, NULL, NULL);
1148 if (tmp_rt.ro_rt) {
1149 rtfree(tmp_rt.ro_rt);
1150 tmp_rt.ro_rt = NULL;
1151 }
1152 break ;
1153 }
1154 case DN_TO_IP_IN :
1155 proto_inject(PF_INET, m);
1156 break ;
1157
1158 #if BRIDGE
1159 case DN_TO_BDG_FWD :
1160 /*
1161 * The bridge requires/assumes the Ethernet header is
1162 * contiguous in the first mbuf header. Insure this is true.
1163 */
1164 if (BDG_LOADED) {
1165 if (m->m_len < ETHER_HDR_LEN &&
1166 (m = m_pullup(m, ETHER_HDR_LEN)) == NULL) {
1167 printf("dummynet/bridge: pullup fail, dropping pkt\n");
1168 break;
1169 }
1170 m = bdg_forward_ptr(m, pkt->ifp);
1171 } else {
1172 /* somebody unloaded the bridge module. Drop pkt */
1173 /* XXX rate limit */
1174 printf("dummynet: dropping bridged packet trapped in pipe\n");
1175 }
1176 if (m)
1177 m_freem(m);
1178 break;
1179 #endif
1180 default:
1181 printf("dummynet: bad switch %d!\n", pkt->dn_dir);
1182 m_freem(m);
1183 break ;
1184 }
1185 }
1186 }
1187
1188
1189
1190 /*
1191 * called by an interface when tx_rdy occurs.
1192 */
1193 int
1194 if_tx_rdy(struct ifnet *ifp)
1195 {
1196 struct dn_pipe *p;
1197 struct mbuf *head = NULL, *tail = NULL;
1198 int i;
1199
1200 lck_mtx_lock(dn_mutex);
1201
1202 for (i = 0; i < HASHSIZE; i++)
1203 SLIST_FOREACH(p, &pipehash[i], next)
1204 if (p->ifp == ifp)
1205 break ;
1206 if (p == NULL) {
1207 char buf[32];
1208 snprintf(buf, sizeof(buf), "%s%d",ifp->if_name, ifp->if_unit);
1209 for (i = 0; i < HASHSIZE; i++)
1210 SLIST_FOREACH(p, &pipehash[i], next)
1211 if (!strcmp(p->if_name, buf) ) {
1212 p->ifp = ifp ;
1213 DPRINTF(("dummynet: ++ tx rdy from %s (now found)\n", buf));
1214 break ;
1215 }
1216 }
1217 if (p != NULL) {
1218 DPRINTF(("dummynet: ++ tx rdy from %s%d - qlen %d\n", ifp->if_name,
1219 ifp->if_unit, ifp->if_snd.ifq_len));
1220 p->numbytes = 0 ; /* mark ready for I/O */
1221 ready_event_wfq(p, &head, &tail);
1222 }
1223 lck_mtx_unlock(dn_mutex);
1224
1225
1226 /* Send out the de-queued list of ready-to-send packets */
1227 if (head != NULL)
1228 dummynet_send(head);
1229
1230 return 0;
1231 }
1232
1233 /*
1234 * Unconditionally expire empty queues in case of shortage.
1235 * Returns the number of queues freed.
1236 */
1237 static int
1238 expire_queues(struct dn_flow_set *fs)
1239 {
1240 struct dn_flow_queue *q, *prev ;
1241 int i, initial_elements = fs->rq_elements ;
1242 struct timeval timenow;
1243
1244 getmicrotime(&timenow);
1245
1246 if (fs->last_expired == timenow.tv_sec)
1247 return 0 ;
1248 fs->last_expired = timenow.tv_sec ;
1249 for (i = 0 ; i <= fs->rq_size ; i++) /* last one is overflow */
1250 for (prev=NULL, q = fs->rq[i] ; q != NULL ; )
1251 if (q->head != NULL || q->S != q->F+1) {
1252 prev = q ;
1253 q = q->next ;
1254 } else { /* entry is idle, expire it */
1255 struct dn_flow_queue *old_q = q ;
1256
1257 if (prev != NULL)
1258 prev->next = q = q->next ;
1259 else
1260 fs->rq[i] = q = q->next ;
1261 fs->rq_elements-- ;
1262 FREE(old_q, M_DUMMYNET);
1263 }
1264 return initial_elements - fs->rq_elements ;
1265 }
1266
1267 /*
1268 * If room, create a new queue and put at head of slot i;
1269 * otherwise, create or use the default queue.
1270 */
1271 static struct dn_flow_queue *
1272 create_queue(struct dn_flow_set *fs, int i)
1273 {
1274 struct dn_flow_queue *q ;
1275
1276 if (fs->rq_elements > fs->rq_size * dn_max_ratio &&
1277 expire_queues(fs) == 0) {
1278 /*
1279 * No way to get room, use or create overflow queue.
1280 */
1281 i = fs->rq_size ;
1282 if ( fs->rq[i] != NULL )
1283 return fs->rq[i] ;
1284 }
1285 q = _MALLOC(sizeof(*q), M_DUMMYNET, M_DONTWAIT | M_ZERO);
1286 if (q == NULL) {
1287 printf("dummynet: sorry, cannot allocate queue for new flow\n");
1288 return NULL ;
1289 }
1290 q->fs = fs ;
1291 q->hash_slot = i ;
1292 q->next = fs->rq[i] ;
1293 q->S = q->F + 1; /* hack - mark timestamp as invalid */
1294 fs->rq[i] = q ;
1295 fs->rq_elements++ ;
1296 return q ;
1297 }
1298
1299 /*
1300 * Given a flow_set and a pkt in last_pkt, find a matching queue
1301 * after appropriate masking. The queue is moved to front
1302 * so that further searches take less time.
1303 */
1304 static struct dn_flow_queue *
1305 find_queue(struct dn_flow_set *fs, struct ipfw_flow_id *id)
1306 {
1307 int i = 0 ; /* we need i and q for new allocations */
1308 struct dn_flow_queue *q, *prev;
1309
1310 if ( !(fs->flags_fs & DN_HAVE_FLOW_MASK) )
1311 q = fs->rq[0] ;
1312 else {
1313 /* first, do the masking */
1314 id->dst_ip &= fs->flow_mask.dst_ip ;
1315 id->src_ip &= fs->flow_mask.src_ip ;
1316 id->dst_port &= fs->flow_mask.dst_port ;
1317 id->src_port &= fs->flow_mask.src_port ;
1318 id->proto &= fs->flow_mask.proto ;
1319 id->flags = 0 ; /* we don't care about this one */
1320 /* then, hash function */
1321 i = ( (id->dst_ip) & 0xffff ) ^
1322 ( (id->dst_ip >> 15) & 0xffff ) ^
1323 ( (id->src_ip << 1) & 0xffff ) ^
1324 ( (id->src_ip >> 16 ) & 0xffff ) ^
1325 (id->dst_port << 1) ^ (id->src_port) ^
1326 (id->proto );
1327 i = i % fs->rq_size ;
1328 /* finally, scan the current list for a match */
1329 searches++ ;
1330 for (prev=NULL, q = fs->rq[i] ; q ; ) {
1331 search_steps++;
1332 if (id->dst_ip == q->id.dst_ip &&
1333 id->src_ip == q->id.src_ip &&
1334 id->dst_port == q->id.dst_port &&
1335 id->src_port == q->id.src_port &&
1336 id->proto == q->id.proto &&
1337 id->flags == q->id.flags)
1338 break ; /* found */
1339 else if (pipe_expire && q->head == NULL && q->S == q->F+1 ) {
1340 /* entry is idle and not in any heap, expire it */
1341 struct dn_flow_queue *old_q = q ;
1342
1343 if (prev != NULL)
1344 prev->next = q = q->next ;
1345 else
1346 fs->rq[i] = q = q->next ;
1347 fs->rq_elements-- ;
1348 FREE(old_q, M_DUMMYNET);
1349 continue ;
1350 }
1351 prev = q ;
1352 q = q->next ;
1353 }
1354 if (q && prev != NULL) { /* found and not in front */
1355 prev->next = q->next ;
1356 q->next = fs->rq[i] ;
1357 fs->rq[i] = q ;
1358 }
1359 }
1360 if (q == NULL) { /* no match, need to allocate a new entry */
1361 q = create_queue(fs, i);
1362 if (q != NULL)
1363 q->id = *id ;
1364 }
1365 return q ;
1366 }
1367
1368 static int
1369 red_drops(struct dn_flow_set *fs, struct dn_flow_queue *q, int len)
1370 {
1371 /*
1372 * RED algorithm
1373 *
1374 * RED calculates the average queue size (avg) using a low-pass filter
1375 * with an exponential weighted (w_q) moving average:
1376 * avg <- (1-w_q) * avg + w_q * q_size
1377 * where q_size is the queue length (measured in bytes or * packets).
1378 *
1379 * If q_size == 0, we compute the idle time for the link, and set
1380 * avg = (1 - w_q)^(idle/s)
1381 * where s is the time needed for transmitting a medium-sized packet.
1382 *
1383 * Now, if avg < min_th the packet is enqueued.
1384 * If avg > max_th the packet is dropped. Otherwise, the packet is
1385 * dropped with probability P function of avg.
1386 *
1387 */
1388
1389 int64_t p_b = 0;
1390 /* queue in bytes or packets ? */
1391 u_int q_size = (fs->flags_fs & DN_QSIZE_IS_BYTES) ? q->len_bytes : q->len;
1392
1393 DPRINTF(("\ndummynet: %d q: %2u ", (int) curr_time, q_size));
1394
1395 /* average queue size estimation */
1396 if (q_size != 0) {
1397 /*
1398 * queue is not empty, avg <- avg + (q_size - avg) * w_q
1399 */
1400 int diff = SCALE(q_size) - q->avg;
1401 int64_t v = SCALE_MUL((int64_t) diff, (int64_t) fs->w_q);
1402
1403 q->avg += (int) v;
1404 } else {
1405 /*
1406 * queue is empty, find for how long the queue has been
1407 * empty and use a lookup table for computing
1408 * (1 - * w_q)^(idle_time/s) where s is the time to send a
1409 * (small) packet.
1410 * XXX check wraps...
1411 */
1412 if (q->avg) {
1413 u_int t = (curr_time - q->q_time) / fs->lookup_step;
1414
1415 q->avg = (t < fs->lookup_depth) ?
1416 SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
1417 }
1418 }
1419 DPRINTF(("dummynet: avg: %u ", SCALE_VAL(q->avg)));
1420
1421 /* should i drop ? */
1422
1423 if (q->avg < fs->min_th) {
1424 q->count = -1;
1425 return 0; /* accept packet ; */
1426 }
1427 if (q->avg >= fs->max_th) { /* average queue >= max threshold */
1428 if (fs->flags_fs & DN_IS_GENTLE_RED) {
1429 /*
1430 * According to Gentle-RED, if avg is greater than max_th the
1431 * packet is dropped with a probability
1432 * p_b = c_3 * avg - c_4
1433 * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
1434 */
1435 p_b = SCALE_MUL((int64_t) fs->c_3, (int64_t) q->avg) - fs->c_4;
1436 } else {
1437 q->count = -1;
1438 DPRINTF(("dummynet: - drop"));
1439 return 1 ;
1440 }
1441 } else if (q->avg > fs->min_th) {
1442 /*
1443 * we compute p_b using the linear dropping function p_b = c_1 *
1444 * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
1445 * max_p * min_th / (max_th - min_th)
1446 */
1447 p_b = SCALE_MUL((int64_t) fs->c_1, (int64_t) q->avg) - fs->c_2;
1448 }
1449 if (fs->flags_fs & DN_QSIZE_IS_BYTES)
1450 p_b = (p_b * len) / fs->max_pkt_size;
1451 if (++q->count == 0)
1452 q->random = MY_RANDOM & 0xffff;
1453 else {
1454 /*
1455 * q->count counts packets arrived since last drop, so a greater
1456 * value of q->count means a greater packet drop probability.
1457 */
1458 if (SCALE_MUL(p_b, SCALE((int64_t) q->count)) > q->random) {
1459 q->count = 0;
1460 DPRINTF(("dummynet: - red drop"));
1461 /* after a drop we calculate a new random value */
1462 q->random = MY_RANDOM & 0xffff;
1463 return 1; /* drop */
1464 }
1465 }
1466 /* end of RED algorithm */
1467 return 0 ; /* accept */
1468 }
1469
1470 static __inline
1471 struct dn_flow_set *
1472 locate_flowset(int fs_nr)
1473 {
1474 struct dn_flow_set *fs;
1475 SLIST_FOREACH(fs, &flowsethash[HASH(fs_nr)], next)
1476 if (fs->fs_nr == fs_nr)
1477 return fs ;
1478
1479 return (NULL);
1480 }
1481
1482 static __inline struct dn_pipe *
1483 locate_pipe(int pipe_nr)
1484 {
1485 struct dn_pipe *pipe;
1486
1487 SLIST_FOREACH(pipe, &pipehash[HASH(pipe_nr)], next)
1488 if (pipe->pipe_nr == pipe_nr)
1489 return (pipe);
1490
1491 return (NULL);
1492 }
1493
1494
1495
1496 /*
1497 * dummynet hook for packets. Below 'pipe' is a pipe or a queue
1498 * depending on whether WF2Q or fixed bw is used.
1499 *
1500 * pipe_nr pipe or queue the packet is destined for.
1501 * dir where shall we send the packet after dummynet.
1502 * m the mbuf with the packet
1503 * ifp the 'ifp' parameter from the caller.
1504 * NULL in ip_input, destination interface in ip_output,
1505 * real_dst in bdg_forward
1506 * ro route parameter (only used in ip_output, NULL otherwise)
1507 * dst destination address, only used by ip_output
1508 * rule matching rule, in case of multiple passes
1509 * flags flags from the caller, only used in ip_output
1510 *
1511 */
1512 static int
1513 dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
1514 {
1515 struct mbuf *head = NULL, *tail = NULL;
1516 struct dn_pkt_tag *pkt;
1517 struct m_tag *mtag;
1518 struct dn_flow_set *fs = NULL;
1519 struct dn_pipe *pipe ;
1520 u_int64_t len = m->m_pkthdr.len ;
1521 struct dn_flow_queue *q = NULL ;
1522 int is_pipe;
1523 struct timespec ts;
1524 struct timeval tv;
1525
1526 #if IPFW2
1527 ipfw_insn *cmd = fwa->rule->cmd + fwa->rule->act_ofs;
1528
1529 if (cmd->opcode == O_LOG)
1530 cmd += F_LEN(cmd);
1531 is_pipe = (cmd->opcode == O_PIPE);
1532 #else
1533 is_pipe = (fwa->rule->fw_flg & IP_FW_F_COMMAND) == IP_FW_F_PIPE;
1534 #endif
1535
1536 pipe_nr &= 0xffff ;
1537
1538 lck_mtx_lock(dn_mutex);
1539
1540 /* make all time measurements in milliseconds (ms) -
1541 * here we convert secs and usecs to msecs (just divide the
1542 * usecs and take the closest whole number).
1543 */
1544 microuptime(&tv);
1545 curr_time = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
1546
1547 /*
1548 * This is a dummynet rule, so we expect an O_PIPE or O_QUEUE rule.
1549 */
1550 if (is_pipe) {
1551 pipe = locate_pipe(pipe_nr);
1552 if (pipe != NULL)
1553 fs = &(pipe->fs);
1554 } else
1555 fs = locate_flowset(pipe_nr);
1556
1557
1558 if (fs == NULL){
1559 goto dropit ; /* this queue/pipe does not exist! */
1560 }
1561 pipe = fs->pipe ;
1562 if (pipe == NULL) { /* must be a queue, try find a matching pipe */
1563 pipe = locate_pipe(fs->parent_nr);
1564
1565 if (pipe != NULL)
1566 fs->pipe = pipe ;
1567 else {
1568 printf("dummynet: no pipe %d for queue %d, drop pkt\n",
1569 fs->parent_nr, fs->fs_nr);
1570 goto dropit ;
1571 }
1572 }
1573 q = find_queue(fs, &(fwa->f_id));
1574 if ( q == NULL )
1575 goto dropit ; /* cannot allocate queue */
1576 /*
1577 * update statistics, then check reasons to drop pkt
1578 */
1579 q->tot_bytes += len ;
1580 q->tot_pkts++ ;
1581 if ( fs->plr && (MY_RANDOM < fs->plr) )
1582 goto dropit ; /* random pkt drop */
1583 if ( fs->flags_fs & DN_QSIZE_IS_BYTES) {
1584 if (q->len_bytes > fs->qsize)
1585 goto dropit ; /* queue size overflow */
1586 } else {
1587 if (q->len >= fs->qsize)
1588 goto dropit ; /* queue count overflow */
1589 }
1590 if ( fs->flags_fs & DN_IS_RED && red_drops(fs, q, len) )
1591 goto dropit ;
1592
1593 /* XXX expensive to zero, see if we can remove it*/
1594 mtag = m_tag_alloc(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_DUMMYNET,
1595 sizeof(struct dn_pkt_tag), M_NOWAIT);
1596 if ( mtag == NULL )
1597 goto dropit ; /* cannot allocate packet header */
1598 m_tag_prepend(m, mtag); /* attach to mbuf chain */
1599
1600 pkt = (struct dn_pkt_tag *)(mtag+1);
1601 bzero(pkt, sizeof(struct dn_pkt_tag));
1602 /* ok, i can handle the pkt now... */
1603 /* build and enqueue packet + parameters */
1604 pkt->rule = fwa->rule ;
1605 pkt->dn_dir = dir ;
1606
1607 pkt->ifp = fwa->oif;
1608 if (dir == DN_TO_IP_OUT) {
1609 /*
1610 * We need to copy *ro because for ICMP pkts (and maybe others)
1611 * the caller passed a pointer into the stack; dst might also be
1612 * a pointer into *ro so it needs to be updated.
1613 */
1614 pkt->ro = *(fwa->ro);
1615 if (fwa->ro->ro_rt)
1616 RT_ADDREF(fwa->ro->ro_rt);
1617
1618 if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) /* dst points into ro */
1619 fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst) ;
1620
1621 pkt->dn_dst = fwa->dst;
1622 pkt->flags = fwa->flags;
1623 if (fwa->ipoa != NULL)
1624 pkt->ipoa = *(fwa->ipoa);
1625 }
1626 if (q->head == NULL)
1627 q->head = m;
1628 else
1629 q->tail->m_nextpkt = m;
1630 q->tail = m;
1631 q->len++;
1632 q->len_bytes += len ;
1633
1634 if ( q->head != m ) /* flow was not idle, we are done */
1635 goto done;
1636 /*
1637 * If we reach this point the flow was previously idle, so we need
1638 * to schedule it. This involves different actions for fixed-rate or
1639 * WF2Q queues.
1640 */
1641 if (is_pipe) {
1642 /*
1643 * Fixed-rate queue: just insert into the ready_heap.
1644 */
1645 dn_key t = 0 ;
1646 if (pipe->bandwidth)
1647 t = SET_TICKS(m, q, pipe);
1648 q->sched_time = curr_time ;
1649 if (t == 0) /* must process it now */
1650 ready_event( q , &head, &tail );
1651 else
1652 heap_insert(&ready_heap, curr_time + t , q );
1653 } else {
1654 /*
1655 * WF2Q. First, compute start time S: if the flow was idle (S=F+1)
1656 * set S to the virtual time V for the controlling pipe, and update
1657 * the sum of weights for the pipe; otherwise, remove flow from
1658 * idle_heap and set S to max(F,V).
1659 * Second, compute finish time F = S + len/weight.
1660 * Third, if pipe was idle, update V=max(S, V).
1661 * Fourth, count one more backlogged flow.
1662 */
1663 if (DN_KEY_GT(q->S, q->F)) { /* means timestamps are invalid */
1664 q->S = pipe->V ;
1665 pipe->sum += fs->weight ; /* add weight of new queue */
1666 } else {
1667 heap_extract(&(pipe->idle_heap), q);
1668 q->S = MAX64(q->F, pipe->V ) ;
1669 }
1670 q->F = q->S + ( len<<MY_M )/(u_int64_t) fs->weight;
1671
1672 if (pipe->not_eligible_heap.elements == 0 &&
1673 pipe->scheduler_heap.elements == 0)
1674 pipe->V = MAX64 ( q->S, pipe->V );
1675 fs->backlogged++ ;
1676 /*
1677 * Look at eligibility. A flow is not eligibile if S>V (when
1678 * this happens, it means that there is some other flow already
1679 * scheduled for the same pipe, so the scheduler_heap cannot be
1680 * empty). If the flow is not eligible we just store it in the
1681 * not_eligible_heap. Otherwise, we store in the scheduler_heap
1682 * and possibly invoke ready_event_wfq() right now if there is
1683 * leftover credit.
1684 * Note that for all flows in scheduler_heap (SCH), S_i <= V,
1685 * and for all flows in not_eligible_heap (NEH), S_i > V .
1686 * So when we need to compute max( V, min(S_i) ) forall i in SCH+NEH,
1687 * we only need to look into NEH.
1688 */
1689 if (DN_KEY_GT(q->S, pipe->V) ) { /* not eligible */
1690 if (pipe->scheduler_heap.elements == 0)
1691 printf("dummynet: ++ ouch! not eligible but empty scheduler!\n");
1692 heap_insert(&(pipe->not_eligible_heap), q->S, q);
1693 } else {
1694 heap_insert(&(pipe->scheduler_heap), q->F, q);
1695 if (pipe->numbytes >= 0) { /* pipe is idle */
1696 if (pipe->scheduler_heap.elements != 1)
1697 printf("dummynet: OUCH! pipe should have been idle!\n");
1698 DPRINTF(("dummynet: waking up pipe %d at %d\n",
1699 pipe->pipe_nr, (int)(q->F >> MY_M)));
1700 pipe->sched_time = curr_time ;
1701 ready_event_wfq(pipe, &head, &tail);
1702 }
1703 }
1704 }
1705 done:
1706 /* start the timer and set global if not already set */
1707 if (!timer_enabled) {
1708 ts.tv_sec = 0;
1709 ts.tv_nsec = 1 * 1000000; // 1ms
1710 timer_enabled = 1;
1711 bsd_timeout(dummynet, NULL, &ts);
1712 }
1713
1714 lck_mtx_unlock(dn_mutex);
1715 if (head != NULL)
1716 dummynet_send(head);
1717
1718 return 0;
1719
1720 dropit:
1721 if (q)
1722 q->drops++ ;
1723 lck_mtx_unlock(dn_mutex);
1724 m_freem(m);
1725 return ( (fs && (fs->flags_fs & DN_NOERROR)) ? 0 : ENOBUFS);
1726 }
1727
1728 /*
1729 * Below, the rtfree is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
1730 * Doing this would probably save us the initial bzero of dn_pkt
1731 */
1732 #define DN_FREE_PKT(_m) do { \
1733 struct m_tag *tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_DUMMYNET, NULL); \
1734 if (tag) { \
1735 struct dn_pkt_tag *n = (struct dn_pkt_tag *)(tag+1); \
1736 if (n->ro.ro_rt != NULL) { \
1737 rtfree(n->ro.ro_rt); \
1738 n->ro.ro_rt = NULL; \
1739 } \
1740 } \
1741 m_tag_delete(_m, tag); \
1742 m_freem(_m); \
1743 } while (0)
1744
1745 /*
1746 * Dispose all packets and flow_queues on a flow_set.
1747 * If all=1, also remove red lookup table and other storage,
1748 * including the descriptor itself.
1749 * For the one in dn_pipe MUST also cleanup ready_heap...
1750 */
1751 static void
1752 purge_flow_set(struct dn_flow_set *fs, int all)
1753 {
1754 struct dn_flow_queue *q, *qn ;
1755 int i ;
1756
1757 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
1758
1759 for (i = 0 ; i <= fs->rq_size ; i++ ) {
1760 for (q = fs->rq[i] ; q ; q = qn ) {
1761 struct mbuf *m, *mnext;
1762
1763 mnext = q->head;
1764 while ((m = mnext) != NULL) {
1765 mnext = m->m_nextpkt;
1766 DN_FREE_PKT(m);
1767 }
1768 qn = q->next ;
1769 FREE(q, M_DUMMYNET);
1770 }
1771 fs->rq[i] = NULL ;
1772 }
1773 fs->rq_elements = 0 ;
1774 if (all) {
1775 /* RED - free lookup table */
1776 if (fs->w_q_lookup)
1777 FREE(fs->w_q_lookup, M_DUMMYNET);
1778 if (fs->rq)
1779 FREE(fs->rq, M_DUMMYNET);
1780 /* if this fs is not part of a pipe, free it */
1781 if (fs->pipe && fs != &(fs->pipe->fs) )
1782 FREE(fs, M_DUMMYNET);
1783 }
1784 }
1785
1786 /*
1787 * Dispose all packets queued on a pipe (not a flow_set).
1788 * Also free all resources associated to a pipe, which is about
1789 * to be deleted.
1790 */
1791 static void
1792 purge_pipe(struct dn_pipe *pipe)
1793 {
1794 struct mbuf *m, *mnext;
1795
1796 purge_flow_set( &(pipe->fs), 1 );
1797
1798 mnext = pipe->head;
1799 while ((m = mnext) != NULL) {
1800 mnext = m->m_nextpkt;
1801 DN_FREE_PKT(m);
1802 }
1803
1804 heap_free( &(pipe->scheduler_heap) );
1805 heap_free( &(pipe->not_eligible_heap) );
1806 heap_free( &(pipe->idle_heap) );
1807 }
1808
1809 /*
1810 * Delete all pipes and heaps returning memory. Must also
1811 * remove references from all ipfw rules to all pipes.
1812 */
1813 static void
1814 dummynet_flush(void)
1815 {
1816 struct dn_pipe *pipe, *pipe1;
1817 struct dn_flow_set *fs, *fs1;
1818 int i;
1819
1820 lck_mtx_lock(dn_mutex);
1821
1822 /* remove all references to pipes ...*/
1823 flush_pipe_ptrs(NULL);
1824
1825 /* Free heaps so we don't have unwanted events. */
1826 heap_free(&ready_heap);
1827 heap_free(&wfq_ready_heap);
1828 heap_free(&extract_heap);
1829
1830 /*
1831 * Now purge all queued pkts and delete all pipes.
1832 *
1833 * XXXGL: can we merge the for(;;) cycles into one or not?
1834 */
1835 for (i = 0; i < HASHSIZE; i++)
1836 SLIST_FOREACH_SAFE(fs, &flowsethash[i], next, fs1) {
1837 SLIST_REMOVE(&flowsethash[i], fs, dn_flow_set, next);
1838 purge_flow_set(fs, 1);
1839 }
1840 for (i = 0; i < HASHSIZE; i++)
1841 SLIST_FOREACH_SAFE(pipe, &pipehash[i], next, pipe1) {
1842 SLIST_REMOVE(&pipehash[i], pipe, dn_pipe, next);
1843 purge_pipe(pipe);
1844 FREE(pipe, M_DUMMYNET);
1845 }
1846 lck_mtx_unlock(dn_mutex);
1847 }
1848
1849
1850 extern struct ip_fw *ip_fw_default_rule ;
1851 static void
1852 dn_rule_delete_fs(struct dn_flow_set *fs, void *r)
1853 {
1854 int i ;
1855 struct dn_flow_queue *q ;
1856 struct mbuf *m ;
1857
1858 for (i = 0 ; i <= fs->rq_size ; i++) /* last one is ovflow */
1859 for (q = fs->rq[i] ; q ; q = q->next )
1860 for (m = q->head ; m ; m = m->m_nextpkt ) {
1861 struct dn_pkt_tag *pkt = dn_tag_get(m) ;
1862 if (pkt->rule == r)
1863 pkt->rule = ip_fw_default_rule ;
1864 }
1865 }
1866 /*
1867 * when a firewall rule is deleted, scan all queues and remove the flow-id
1868 * from packets matching this rule.
1869 */
1870 void
1871 dn_rule_delete(void *r)
1872 {
1873 struct dn_pipe *p ;
1874 struct dn_flow_set *fs ;
1875 struct dn_pkt_tag *pkt ;
1876 struct mbuf *m ;
1877 int i;
1878
1879 lck_mtx_lock(dn_mutex);
1880
1881 /*
1882 * If the rule references a queue (dn_flow_set), then scan
1883 * the flow set, otherwise scan pipes. Should do either, but doing
1884 * both does not harm.
1885 */
1886 for (i = 0; i < HASHSIZE; i++)
1887 SLIST_FOREACH(fs, &flowsethash[i], next)
1888 dn_rule_delete_fs(fs, r);
1889
1890 for (i = 0; i < HASHSIZE; i++)
1891 SLIST_FOREACH(p, &pipehash[i], next) {
1892 fs = &(p->fs);
1893 dn_rule_delete_fs(fs, r);
1894 for (m = p->head ; m ; m = m->m_nextpkt ) {
1895 pkt = dn_tag_get(m);
1896 if (pkt->rule == r)
1897 pkt->rule = ip_fw_default_rule;
1898 }
1899 }
1900 lck_mtx_unlock(dn_mutex);
1901 }
1902
1903 /*
1904 * setup RED parameters
1905 */
1906 static int
1907 config_red(struct dn_flow_set *p, struct dn_flow_set * x)
1908 {
1909 int i;
1910
1911 x->w_q = p->w_q;
1912 x->min_th = SCALE(p->min_th);
1913 x->max_th = SCALE(p->max_th);
1914 x->max_p = p->max_p;
1915
1916 x->c_1 = p->max_p / (p->max_th - p->min_th);
1917 x->c_2 = SCALE_MUL(x->c_1, SCALE(p->min_th));
1918 if (x->flags_fs & DN_IS_GENTLE_RED) {
1919 x->c_3 = (SCALE(1) - p->max_p) / p->max_th;
1920 x->c_4 = (SCALE(1) - 2 * p->max_p);
1921 }
1922
1923 /* if the lookup table already exist, free and create it again */
1924 if (x->w_q_lookup) {
1925 FREE(x->w_q_lookup, M_DUMMYNET);
1926 x->w_q_lookup = NULL ;
1927 }
1928 if (red_lookup_depth == 0) {
1929 printf("\ndummynet: net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
1930 FREE(x, M_DUMMYNET);
1931 return EINVAL;
1932 }
1933 x->lookup_depth = red_lookup_depth;
1934 x->w_q_lookup = (u_int *) _MALLOC(x->lookup_depth * sizeof(int),
1935 M_DUMMYNET, M_DONTWAIT);
1936 if (x->w_q_lookup == NULL) {
1937 printf("dummynet: sorry, cannot allocate red lookup table\n");
1938 FREE(x, M_DUMMYNET);
1939 return ENOSPC;
1940 }
1941
1942 /* fill the lookup table with (1 - w_q)^x */
1943 x->lookup_step = p->lookup_step ;
1944 x->lookup_weight = p->lookup_weight ;
1945 x->w_q_lookup[0] = SCALE(1) - x->w_q;
1946 for (i = 1; i < x->lookup_depth; i++)
1947 x->w_q_lookup[i] = SCALE_MUL(x->w_q_lookup[i - 1], x->lookup_weight);
1948 if (red_avg_pkt_size < 1)
1949 red_avg_pkt_size = 512 ;
1950 x->avg_pkt_size = red_avg_pkt_size ;
1951 if (red_max_pkt_size < 1)
1952 red_max_pkt_size = 1500 ;
1953 x->max_pkt_size = red_max_pkt_size ;
1954 return 0 ;
1955 }
1956
1957 static int
1958 alloc_hash(struct dn_flow_set *x, struct dn_flow_set *pfs)
1959 {
1960 if (x->flags_fs & DN_HAVE_FLOW_MASK) { /* allocate some slots */
1961 int l = pfs->rq_size;
1962
1963 if (l == 0)
1964 l = dn_hash_size;
1965 if (l < 4)
1966 l = 4;
1967 else if (l > DN_MAX_HASH_SIZE)
1968 l = DN_MAX_HASH_SIZE;
1969 x->rq_size = l;
1970 } else /* one is enough for null mask */
1971 x->rq_size = 1;
1972 x->rq = _MALLOC((1 + x->rq_size) * sizeof(struct dn_flow_queue *),
1973 M_DUMMYNET, M_DONTWAIT | M_ZERO);
1974 if (x->rq == NULL) {
1975 printf("dummynet: sorry, cannot allocate queue\n");
1976 return ENOSPC;
1977 }
1978 x->rq_elements = 0;
1979 return 0 ;
1980 }
1981
1982 static void
1983 set_fs_parms(struct dn_flow_set *x, struct dn_flow_set *src)
1984 {
1985 x->flags_fs = src->flags_fs;
1986 x->qsize = src->qsize;
1987 x->plr = src->plr;
1988 x->flow_mask = src->flow_mask;
1989 if (x->flags_fs & DN_QSIZE_IS_BYTES) {
1990 if (x->qsize > 1024*1024)
1991 x->qsize = 1024*1024 ;
1992 } else {
1993 if (x->qsize == 0)
1994 x->qsize = 50 ;
1995 if (x->qsize > 100)
1996 x->qsize = 50 ;
1997 }
1998 /* configuring RED */
1999 if ( x->flags_fs & DN_IS_RED )
2000 config_red(src, x) ; /* XXX should check errors */
2001 }
2002
2003 /*
2004 * setup pipe or queue parameters.
2005 */
2006
2007 static int
2008 config_pipe(struct dn_pipe *p)
2009 {
2010 int i, r;
2011 struct dn_flow_set *pfs = &(p->fs);
2012 struct dn_flow_queue *q;
2013
2014 /*
2015 * The config program passes parameters as follows:
2016 * bw = bits/second (0 means no limits),
2017 * delay = ms, must be translated into ticks.
2018 * qsize = slots/bytes
2019 */
2020 p->delay = ( p->delay * (hz*10) ) / 1000 ;
2021 /* We need either a pipe number or a flow_set number */
2022 if (p->pipe_nr == 0 && pfs->fs_nr == 0)
2023 return EINVAL ;
2024 if (p->pipe_nr != 0 && pfs->fs_nr != 0)
2025 return EINVAL ;
2026 if (p->pipe_nr != 0) { /* this is a pipe */
2027 struct dn_pipe *x, *b;
2028
2029 lck_mtx_lock(dn_mutex);
2030
2031 /* locate pipe */
2032 b = locate_pipe(p->pipe_nr);
2033
2034 if (b == NULL || b->pipe_nr != p->pipe_nr) { /* new pipe */
2035 x = _MALLOC(sizeof(struct dn_pipe), M_DUMMYNET, M_DONTWAIT | M_ZERO) ;
2036 if (x == NULL) {
2037 lck_mtx_unlock(dn_mutex);
2038 printf("dummynet: no memory for new pipe\n");
2039 return ENOSPC;
2040 }
2041 x->pipe_nr = p->pipe_nr;
2042 x->fs.pipe = x ;
2043 /* idle_heap is the only one from which we extract from the middle.
2044 */
2045 x->idle_heap.size = x->idle_heap.elements = 0 ;
2046 x->idle_heap.offset=offsetof(struct dn_flow_queue, heap_pos);
2047 } else {
2048 x = b;
2049 /* Flush accumulated credit for all queues */
2050 for (i = 0; i <= x->fs.rq_size; i++)
2051 for (q = x->fs.rq[i]; q; q = q->next)
2052 q->numbytes = 0;
2053 }
2054
2055 x->bandwidth = p->bandwidth ;
2056 x->numbytes = 0; /* just in case... */
2057 bcopy(p->if_name, x->if_name, sizeof(p->if_name) );
2058 x->ifp = NULL ; /* reset interface ptr */
2059 x->delay = p->delay ;
2060 set_fs_parms(&(x->fs), pfs);
2061
2062
2063 if ( x->fs.rq == NULL ) { /* a new pipe */
2064 r = alloc_hash(&(x->fs), pfs) ;
2065 if (r) {
2066 lck_mtx_unlock(dn_mutex);
2067 FREE(x, M_DUMMYNET);
2068 return r ;
2069 }
2070 SLIST_INSERT_HEAD(&pipehash[HASH(x->pipe_nr)],
2071 x, next);
2072 }
2073 lck_mtx_unlock(dn_mutex);
2074 } else { /* config queue */
2075 struct dn_flow_set *x, *b ;
2076
2077 lck_mtx_lock(dn_mutex);
2078 /* locate flow_set */
2079 b = locate_flowset(pfs->fs_nr);
2080
2081 if (b == NULL || b->fs_nr != pfs->fs_nr) { /* new */
2082 if (pfs->parent_nr == 0) { /* need link to a pipe */
2083 lck_mtx_unlock(dn_mutex);
2084 return EINVAL ;
2085 }
2086 x = _MALLOC(sizeof(struct dn_flow_set), M_DUMMYNET, M_DONTWAIT | M_ZERO);
2087 if (x == NULL) {
2088 lck_mtx_unlock(dn_mutex);
2089 printf("dummynet: no memory for new flow_set\n");
2090 return ENOSPC;
2091 }
2092 x->fs_nr = pfs->fs_nr;
2093 x->parent_nr = pfs->parent_nr;
2094 x->weight = pfs->weight ;
2095 if (x->weight == 0)
2096 x->weight = 1 ;
2097 else if (x->weight > 100)
2098 x->weight = 100 ;
2099 } else {
2100 /* Change parent pipe not allowed; must delete and recreate */
2101 if (pfs->parent_nr != 0 && b->parent_nr != pfs->parent_nr) {
2102 lck_mtx_unlock(dn_mutex);
2103 return EINVAL ;
2104 }
2105 x = b;
2106 }
2107 set_fs_parms(x, pfs);
2108
2109 if ( x->rq == NULL ) { /* a new flow_set */
2110 r = alloc_hash(x, pfs) ;
2111 if (r) {
2112 lck_mtx_unlock(dn_mutex);
2113 FREE(x, M_DUMMYNET);
2114 return r ;
2115 }
2116 SLIST_INSERT_HEAD(&flowsethash[HASH(x->fs_nr)],
2117 x, next);
2118 }
2119 lck_mtx_unlock(dn_mutex);
2120 }
2121 return 0 ;
2122 }
2123
2124 /*
2125 * Helper function to remove from a heap queues which are linked to
2126 * a flow_set about to be deleted.
2127 */
2128 static void
2129 fs_remove_from_heap(struct dn_heap *h, struct dn_flow_set *fs)
2130 {
2131 int i = 0, found = 0 ;
2132 for (; i < h->elements ;)
2133 if ( ((struct dn_flow_queue *)h->p[i].object)->fs == fs) {
2134 h->elements-- ;
2135 h->p[i] = h->p[h->elements] ;
2136 found++ ;
2137 } else
2138 i++ ;
2139 if (found)
2140 heapify(h);
2141 }
2142
2143 /*
2144 * helper function to remove a pipe from a heap (can be there at most once)
2145 */
2146 static void
2147 pipe_remove_from_heap(struct dn_heap *h, struct dn_pipe *p)
2148 {
2149 if (h->elements > 0) {
2150 int i = 0 ;
2151 for (i=0; i < h->elements ; i++ ) {
2152 if (h->p[i].object == p) { /* found it */
2153 h->elements-- ;
2154 h->p[i] = h->p[h->elements] ;
2155 heapify(h);
2156 break ;
2157 }
2158 }
2159 }
2160 }
2161
2162 /*
2163 * drain all queues. Called in case of severe mbuf shortage.
2164 */
2165 void
2166 dummynet_drain(void)
2167 {
2168 struct dn_flow_set *fs;
2169 struct dn_pipe *p;
2170 struct mbuf *m, *mnext;
2171 int i;
2172
2173 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
2174
2175 heap_free(&ready_heap);
2176 heap_free(&wfq_ready_heap);
2177 heap_free(&extract_heap);
2178 /* remove all references to this pipe from flow_sets */
2179 for (i = 0; i < HASHSIZE; i++)
2180 SLIST_FOREACH(fs, &flowsethash[i], next)
2181 purge_flow_set(fs, 0);
2182
2183 for (i = 0; i < HASHSIZE; i++)
2184 SLIST_FOREACH(p, &pipehash[i], next) {
2185 purge_flow_set(&(p->fs), 0);
2186
2187 mnext = p->head;
2188 while ((m = mnext) != NULL) {
2189 mnext = m->m_nextpkt;
2190 DN_FREE_PKT(m);
2191 }
2192 p->head = p->tail = NULL ;
2193 }
2194 }
2195
2196 /*
2197 * Fully delete a pipe or a queue, cleaning up associated info.
2198 */
2199 static int
2200 delete_pipe(struct dn_pipe *p)
2201 {
2202 if (p->pipe_nr == 0 && p->fs.fs_nr == 0)
2203 return EINVAL ;
2204 if (p->pipe_nr != 0 && p->fs.fs_nr != 0)
2205 return EINVAL ;
2206 if (p->pipe_nr != 0) { /* this is an old-style pipe */
2207 struct dn_pipe *b;
2208 struct dn_flow_set *fs;
2209 int i;
2210
2211 lck_mtx_lock(dn_mutex);
2212 /* locate pipe */
2213 b = locate_pipe(p->pipe_nr);
2214 if(b == NULL){
2215 lck_mtx_unlock(dn_mutex);
2216 return EINVAL ; /* not found */
2217 }
2218
2219 /* Unlink from list of pipes. */
2220 SLIST_REMOVE(&pipehash[HASH(b->pipe_nr)], b, dn_pipe, next);
2221
2222 /* remove references to this pipe from the ip_fw rules. */
2223 flush_pipe_ptrs(&(b->fs));
2224
2225 /* Remove all references to this pipe from flow_sets. */
2226 for (i = 0; i < HASHSIZE; i++)
2227 SLIST_FOREACH(fs, &flowsethash[i], next)
2228 if (fs->pipe == b) {
2229 printf("dummynet: ++ ref to pipe %d from fs %d\n",
2230 p->pipe_nr, fs->fs_nr);
2231 fs->pipe = NULL ;
2232 purge_flow_set(fs, 0);
2233 }
2234 fs_remove_from_heap(&ready_heap, &(b->fs));
2235
2236 purge_pipe(b); /* remove all data associated to this pipe */
2237 /* remove reference to here from extract_heap and wfq_ready_heap */
2238 pipe_remove_from_heap(&extract_heap, b);
2239 pipe_remove_from_heap(&wfq_ready_heap, b);
2240 lck_mtx_unlock(dn_mutex);
2241
2242 FREE(b, M_DUMMYNET);
2243 } else { /* this is a WF2Q queue (dn_flow_set) */
2244 struct dn_flow_set *b;
2245
2246 lck_mtx_lock(dn_mutex);
2247 /* locate set */
2248 b = locate_flowset(p->fs.fs_nr);
2249 if (b == NULL) {
2250 lck_mtx_unlock(dn_mutex);
2251 return EINVAL ; /* not found */
2252 }
2253
2254 /* remove references to this flow_set from the ip_fw rules. */
2255 flush_pipe_ptrs(b);
2256
2257 /* Unlink from list of flowsets. */
2258 SLIST_REMOVE( &flowsethash[HASH(b->fs_nr)], b, dn_flow_set, next);
2259
2260 if (b->pipe != NULL) {
2261 /* Update total weight on parent pipe and cleanup parent heaps */
2262 b->pipe->sum -= b->weight * b->backlogged ;
2263 fs_remove_from_heap(&(b->pipe->not_eligible_heap), b);
2264 fs_remove_from_heap(&(b->pipe->scheduler_heap), b);
2265 #if 1 /* XXX should i remove from idle_heap as well ? */
2266 fs_remove_from_heap(&(b->pipe->idle_heap), b);
2267 #endif
2268 }
2269 purge_flow_set(b, 1);
2270 lck_mtx_unlock(dn_mutex);
2271 }
2272 return 0 ;
2273 }
2274
2275 /*
2276 * helper function used to copy data from kernel in DUMMYNET_GET
2277 */
2278 static
2279 char* dn_copy_set_32(struct dn_flow_set *set, char *bp)
2280 {
2281 int i, copied = 0 ;
2282 struct dn_flow_queue *q;
2283 struct dn_flow_queue_32 *qp = (struct dn_flow_queue_32 *)bp;
2284
2285 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
2286
2287 for (i = 0 ; i <= set->rq_size ; i++)
2288 for (q = set->rq[i] ; q ; q = q->next, qp++ ) {
2289 if (q->hash_slot != i)
2290 printf("dummynet: ++ at %d: wrong slot (have %d, "
2291 "should be %d)\n", copied, q->hash_slot, i);
2292 if (q->fs != set)
2293 printf("dummynet: ++ at %d: wrong fs ptr (have %p, should be %p)\n",
2294 i, q->fs, set);
2295 copied++ ;
2296 cp_queue_to_32_user( q, qp );
2297 /* cleanup pointers */
2298 qp->next = (user32_addr_t)0 ;
2299 qp->head = qp->tail = (user32_addr_t)0 ;
2300 qp->fs = (user32_addr_t)0 ;
2301 }
2302 if (copied != set->rq_elements)
2303 printf("dummynet: ++ wrong count, have %d should be %d\n",
2304 copied, set->rq_elements);
2305 return (char *)qp ;
2306 }
2307
2308 static
2309 char* dn_copy_set_64(struct dn_flow_set *set, char *bp)
2310 {
2311 int i, copied = 0 ;
2312 struct dn_flow_queue *q;
2313 struct dn_flow_queue_64 *qp = (struct dn_flow_queue_64 *)bp;
2314
2315 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
2316
2317 for (i = 0 ; i <= set->rq_size ; i++)
2318 for (q = set->rq[i] ; q ; q = q->next, qp++ ) {
2319 if (q->hash_slot != i)
2320 printf("dummynet: ++ at %d: wrong slot (have %d, "
2321 "should be %d)\n", copied, q->hash_slot, i);
2322 if (q->fs != set)
2323 printf("dummynet: ++ at %d: wrong fs ptr (have %p, should be %p)\n",
2324 i, q->fs, set);
2325 copied++ ;
2326 //bcopy(q, qp, sizeof(*q));
2327 cp_queue_to_64_user( q, qp );
2328 /* cleanup pointers */
2329 qp->next = USER_ADDR_NULL ;
2330 qp->head = qp->tail = USER_ADDR_NULL ;
2331 qp->fs = USER_ADDR_NULL ;
2332 }
2333 if (copied != set->rq_elements)
2334 printf("dummynet: ++ wrong count, have %d should be %d\n",
2335 copied, set->rq_elements);
2336 return (char *)qp ;
2337 }
2338
2339 static size_t
2340 dn_calc_size(int is64user)
2341 {
2342 struct dn_flow_set *set ;
2343 struct dn_pipe *p ;
2344 size_t size = 0 ;
2345 size_t pipesize;
2346 size_t queuesize;
2347 size_t setsize;
2348 int i;
2349
2350 lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
2351 if ( is64user ){
2352 pipesize = sizeof(struct dn_pipe_64);
2353 queuesize = sizeof(struct dn_flow_queue_64);
2354 setsize = sizeof(struct dn_flow_set_64);
2355 }
2356 else {
2357 pipesize = sizeof(struct dn_pipe_32);
2358 queuesize = sizeof( struct dn_flow_queue_32 );
2359 setsize = sizeof(struct dn_flow_set_32);
2360 }
2361 /*
2362 * compute size of data structures: list of pipes and flow_sets.
2363 */
2364 for (i = 0; i < HASHSIZE; i++) {
2365 SLIST_FOREACH(p, &pipehash[i], next)
2366 size += sizeof(*p) +
2367 p->fs.rq_elements * sizeof(struct dn_flow_queue);
2368 SLIST_FOREACH(set, &flowsethash[i], next)
2369 size += sizeof (*set) +
2370 set->rq_elements * sizeof(struct dn_flow_queue);
2371 }
2372 return size;
2373 }
2374
2375 static int
2376 dummynet_get(struct sockopt *sopt)
2377 {
2378 char *buf, *bp=NULL; /* bp is the "copy-pointer" */
2379 size_t size ;
2380 struct dn_flow_set *set ;
2381 struct dn_pipe *p ;
2382 int error=0, i ;
2383 int is64user = 0;
2384
2385 /* XXX lock held too long */
2386 lck_mtx_lock(dn_mutex);
2387 /*
2388 * XXX: Ugly, but we need to allocate memory with M_WAITOK flag and we
2389 * cannot use this flag while holding a mutex.
2390 */
2391 if (proc_is64bit(sopt->sopt_p))
2392 is64user = 1;
2393 for (i = 0; i < 10; i++) {
2394 size = dn_calc_size(is64user);
2395 lck_mtx_unlock(dn_mutex);
2396 buf = _MALLOC(size, M_TEMP, M_WAITOK);
2397 if (buf == NULL)
2398 return ENOBUFS;
2399 lck_mtx_lock(dn_mutex);
2400 if (size == dn_calc_size(is64user))
2401 break;
2402 FREE(buf, M_TEMP);
2403 buf = NULL;
2404 }
2405 if (buf == NULL) {
2406 lck_mtx_unlock(dn_mutex);
2407 return ENOBUFS ;
2408 }
2409
2410
2411 bp = buf;
2412 for (i = 0; i < HASHSIZE; i++)
2413 SLIST_FOREACH(p, &pipehash[i], next) {
2414 /*
2415 * copy pipe descriptor into *bp, convert delay back to ms,
2416 * then copy the flow_set descriptor(s) one at a time.
2417 * After each flow_set, copy the queue descriptor it owns.
2418 */
2419 if ( is64user ){
2420 bp = cp_pipe_to_64_user(p, (struct dn_pipe_64 *)bp);
2421 }
2422 else{
2423 bp = cp_pipe_to_32_user(p, (struct dn_pipe_32 *)bp);
2424 }
2425 }
2426 for (i = 0; i < HASHSIZE; i++)
2427 SLIST_FOREACH(set, &flowsethash[i], next) {
2428 struct dn_flow_set_64 *fs_bp = (struct dn_flow_set_64 *)bp ;
2429 cp_flow_set_to_64_user(set, fs_bp);
2430 /* XXX same hack as above */
2431 fs_bp->next = CAST_DOWN(user64_addr_t, DN_IS_QUEUE);
2432 fs_bp->pipe = USER_ADDR_NULL;
2433 fs_bp->rq = USER_ADDR_NULL ;
2434 bp += sizeof(struct dn_flow_set_64);
2435 bp = dn_copy_set_64( set, bp );
2436 }
2437 lck_mtx_unlock(dn_mutex);
2438
2439 error = sooptcopyout(sopt, buf, size);
2440 FREE(buf, M_TEMP);
2441 return error ;
2442 }
2443
2444 /*
2445 * Handler for the various dummynet socket options (get, flush, config, del)
2446 */
2447 static int
2448 ip_dn_ctl(struct sockopt *sopt)
2449 {
2450 int error = 0 ;
2451 struct dn_pipe *p, tmp_pipe;
2452
2453 /* Disallow sets in really-really secure mode. */
2454 if (sopt->sopt_dir == SOPT_SET && securelevel >= 3)
2455 return (EPERM);
2456
2457 switch (sopt->sopt_name) {
2458 default :
2459 printf("dummynet: -- unknown option %d", sopt->sopt_name);
2460 return EINVAL ;
2461
2462 case IP_DUMMYNET_GET :
2463 error = dummynet_get(sopt);
2464 break ;
2465
2466 case IP_DUMMYNET_FLUSH :
2467 dummynet_flush() ;
2468 break ;
2469
2470 case IP_DUMMYNET_CONFIGURE :
2471 p = &tmp_pipe ;
2472 if (proc_is64bit(sopt->sopt_p))
2473 error = cp_pipe_from_user_64( sopt, p );
2474 else
2475 error = cp_pipe_from_user_32( sopt, p );
2476
2477 if (error)
2478 break ;
2479 error = config_pipe(p);
2480 break ;
2481
2482 case IP_DUMMYNET_DEL : /* remove a pipe or queue */
2483 p = &tmp_pipe ;
2484 if (proc_is64bit(sopt->sopt_p))
2485 error = cp_pipe_from_user_64( sopt, p );
2486 else
2487 error = cp_pipe_from_user_32( sopt, p );
2488 if (error)
2489 break ;
2490
2491 error = delete_pipe(p);
2492 break ;
2493 }
2494 return error ;
2495 }
2496
2497 void
2498 ip_dn_init(void)
2499 {
2500 /* setup locks */
2501 dn_mutex_grp_attr = lck_grp_attr_alloc_init();
2502 dn_mutex_grp = lck_grp_alloc_init("dn", dn_mutex_grp_attr);
2503 dn_mutex_attr = lck_attr_alloc_init();
2504
2505 if ((dn_mutex = lck_mtx_alloc_init(dn_mutex_grp, dn_mutex_attr)) == NULL) {
2506 printf("ip_dn_init: can't alloc dn_mutex\n");
2507 return;
2508 }
2509
2510 ready_heap.size = ready_heap.elements = 0 ;
2511 ready_heap.offset = 0 ;
2512
2513 wfq_ready_heap.size = wfq_ready_heap.elements = 0 ;
2514 wfq_ready_heap.offset = 0 ;
2515
2516 extract_heap.size = extract_heap.elements = 0 ;
2517 extract_heap.offset = 0 ;
2518 ip_dn_ctl_ptr = ip_dn_ctl;
2519 ip_dn_io_ptr = dummynet_io;
2520 ip_dn_ruledel_ptr = dn_rule_delete;
2521 }