xref: /freebsd/sbin/ipfw/dummynet.c (revision 04fcf30961266cd77139b40774cb0d6ef6eb2be5)
1 /*-
2  * Codel/FQ_Codel and PIE/FQ_PIE Code:
3  * Copyright (C) 2016 Centre for Advanced Internet Architectures,
4  *  Swinburne University of Technology, Melbourne, Australia.
5  * Portions of this code were made possible in part by a gift from
6  *  The Comcast Innovation Fund.
7  * Implemented by Rasool Al-Saadi <ralsaadi@swin.edu.au>
8  *
9  * Copyright (c) 2002-2003,2010 Luigi Rizzo
10  *
11  * Redistribution and use in source forms, with and without modification,
12  * are permitted provided that this entire comment appears intact.
13  *
14  * Redistribution in binary form may occur without any restrictions.
15  * Obviously, it would be nice if you gave credit where credit is due
16  * but requiring it would be too onerous.
17  *
18  * This software is provided ``AS IS'' without any warranties of any kind.
19  *
20  * dummynet support
21  */
22 
23 #define NEW_AQM
24 #include <sys/limits.h>
25 #include <sys/param.h>
26 #include <sys/socket.h>
27 /* XXX there are several sysctl leftover here */
28 #include <sys/sysctl.h>
29 
30 #include "ipfw2.h"
31 
32 #ifdef NEW_AQM
33 #include <stdint.h>
34 #endif
35 
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <libutil.h>
40 #include <netdb.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <sysexits.h>
45 
46 #include <net/if.h>
47 #include <netinet/in.h>
48 #include <netinet/ip_fw.h>
49 #include <netinet/ip_dummynet.h>
50 #include <arpa/inet.h>	/* inet_ntoa */
51 
52 
53 static struct _s_x dummynet_params[] = {
54 	{ "plr",		TOK_PLR },
55 	{ "noerror",		TOK_NOERROR },
56 	{ "buckets",		TOK_BUCKETS },
57 	{ "dst-ip",		TOK_DSTIP },
58 	{ "src-ip",		TOK_SRCIP },
59 	{ "dst-port",		TOK_DSTPORT },
60 	{ "src-port",		TOK_SRCPORT },
61 	{ "proto",		TOK_PROTO },
62 	{ "weight",		TOK_WEIGHT },
63 	{ "lmax",		TOK_LMAX },
64 	{ "maxlen",		TOK_LMAX },
65 	{ "all",		TOK_ALL },
66 	{ "mask",		TOK_MASK }, /* alias for both */
67 	{ "sched_mask",		TOK_SCHED_MASK },
68 	{ "flow_mask",		TOK_FLOW_MASK },
69 	{ "droptail",		TOK_DROPTAIL },
70 	{ "ecn",		TOK_ECN },
71 	{ "red",		TOK_RED },
72 	{ "gred",		TOK_GRED },
73 #ifdef NEW_AQM
74 	{ "codel",		TOK_CODEL}, /* Codel AQM */
75 	{ "fq_codel",	TOK_FQ_CODEL}, /* FQ-Codel  */
76 	{ "pie",		TOK_PIE}, /* PIE AQM */
77 	{ "fq_pie",		TOK_FQ_PIE}, /* FQ-PIE */
78 #endif
79 	{ "bw",			TOK_BW },
80 	{ "bandwidth",		TOK_BW },
81 	{ "delay",		TOK_DELAY },
82 	{ "link",		TOK_LINK },
83 	{ "pipe",		TOK_PIPE },
84 	{ "queue",		TOK_QUEUE },
85 	{ "flowset",		TOK_FLOWSET },
86 	{ "sched",		TOK_SCHED },
87 	{ "pri",		TOK_PRI },
88 	{ "priority",		TOK_PRI },
89 	{ "type",		TOK_TYPE },
90 	{ "flow-id",		TOK_FLOWID},
91 	{ "dst-ipv6",		TOK_DSTIP6},
92 	{ "dst-ip6",		TOK_DSTIP6},
93 	{ "src-ipv6",		TOK_SRCIP6},
94 	{ "src-ip6",		TOK_SRCIP6},
95 	{ "profile",		TOK_PROFILE},
96 	{ "burst",		TOK_BURST},
97 	{ "dummynet-params",	TOK_NULL },
98 	{ NULL, 0 }	/* terminator */
99 };
100 
101 #ifdef NEW_AQM
102 /* AQM/extra sched parameters  tokens*/
103 static struct _s_x aqm_params[] = {
104 	{ "target",		TOK_TARGET},
105 	{ "interval",		TOK_INTERVAL},
106 	{ "limit",		TOK_LIMIT},
107 	{ "flows",		TOK_FLOWS},
108 	{ "quantum",		TOK_QUANTUM},
109 	{ "ecn",		TOK_ECN},
110 	{ "noecn",		TOK_NO_ECN},
111 	{ "tupdate",		TOK_TUPDATE},
112 	{ "max_burst",		TOK_MAX_BURST},
113 	{ "max_ecnth",	TOK_MAX_ECNTH},
114 	{ "alpha",		TOK_ALPHA},
115 	{ "beta",		TOK_BETA},
116 	{ "capdrop",	TOK_CAPDROP},
117 	{ "nocapdrop",	TOK_NO_CAPDROP},
118 	{ "onoff",	TOK_ONOFF},
119 	{ "dre",	TOK_DRE},
120 	{ "ts",	TOK_TS},
121 	{ "derand",	TOK_DERAND},
122 	{ "noderand",	TOK_NO_DERAND},
123 	{ NULL, 0 }	/* terminator */
124 };
125 #endif
126 
127 #define O_NEXT(p, len) ((void *)((char *)p + len))
128 
129 static void
oid_fill(struct dn_id * oid,int len,int type,uintptr_t id)130 oid_fill(struct dn_id *oid, int len, int type, uintptr_t id)
131 {
132 	oid->len = len;
133 	oid->type = type;
134 	oid->subtype = 0;
135 	oid->id = id;
136 }
137 
138 /* make room in the buffer and move the pointer forward */
139 static void *
o_next(struct dn_id ** o,int len,int type)140 o_next(struct dn_id **o, int len, int type)
141 {
142 	struct dn_id *ret = *o;
143 	oid_fill(ret, len, type, 0);
144 	*o = O_NEXT(*o, len);
145 	return ret;
146 }
147 
148 #ifdef NEW_AQM
149 
150 /* Codel flags */
151 enum {
152 	CODEL_ECN_ENABLED = 1
153 };
154 
155 /* PIE flags, from PIE kernel module */
156 enum {
157 	PIE_ECN_ENABLED = 1,
158 	PIE_CAPDROP_ENABLED = 2,
159 	PIE_ON_OFF_MODE_ENABLED = 4,
160 	PIE_DEPRATEEST_ENABLED = 8,
161 	PIE_DERAND_ENABLED = 16
162 };
163 
164 #define PIE_FIX_POINT_BITS 13
165 #define PIE_SCALE (1L<<PIE_FIX_POINT_BITS)
166 
167 /* integer to time */
168 static void
us_to_time(int t,char * strt)169 us_to_time(int t, char *strt)
170 {
171 	if (t < 0)
172 		strt[0]='\0';
173 	else if ( t==0 )
174 		sprintf(strt,"%d", t);
175 	else if (t< 1000)
176 		sprintf(strt,"%dus", t);
177 	else if (t < 1000000)
178 		sprintf(strt,"%gms", (float) t / 1000);
179 	else
180 		sprintf(strt,"%gfs", (float) t / 1000000);
181 }
182 
183 /*
184  * returns -1 if s is not a valid time, otherwise, return time in us
185  */
186 static long
time_to_us(const char * s)187 time_to_us(const char *s)
188 {
189 	int i, dots = 0;
190 	int len = strlen(s);
191 	char strt[16]="", stru[16]="";
192 
193 	if (len>15)
194 		return -1;
195 	for (i = 0; i<len && (isdigit(s[i]) || s[i]=='.') ; i++)
196 		if (s[i]=='.') {
197 			if (dots)
198 				return -1;
199 			else
200 				dots++;
201 		}
202 
203 	if (!i)
204 		return -1;
205 	strncpy(strt, s, i);
206 	if (i<len)
207 		strcpy(stru, s+i);
208 	else
209 		strcpy(stru, "ms");
210 
211 	if (!strcasecmp(stru, "us"))
212 		return atol(strt);
213 	if (!strcasecmp(stru, "ms"))
214 		return (strtod(strt, NULL) * 1000);
215 	if (!strcasecmp(stru, "s"))
216 		return (strtod(strt, NULL)*1000000);
217 
218 	return -1;
219 }
220 
221 
222 /* Get AQM or scheduler extra parameters  */
223 static void
get_extra_parms(uint32_t nr,char * out,int subtype)224 get_extra_parms(uint32_t nr, char *out, int subtype)
225 {
226 	struct dn_extra_parms *ep;
227 	int ret;
228 	char strt1[15], strt2[15], strt3[15];
229 	u_int l;
230 
231 	/* prepare the request */
232 	l = sizeof(struct dn_extra_parms);
233 	ep = safe_calloc(1, l);
234 	memset(ep, 0, sizeof(*ep));
235 	*out = '\0';
236 
237 	oid_fill(&ep->oid, l, DN_CMD_GET, DN_API_VERSION);
238 	ep->oid.len = l;
239 	ep->oid.subtype = subtype;
240 	ep->nr = nr;
241 
242 	ret = do_cmd(-IP_DUMMYNET3, ep, (uintptr_t)&l);
243 	if (ret) {
244 		free(ep);
245 		errx(EX_DATAERR, "Error getting extra parameters\n");
246 	}
247 
248 	switch (subtype) {
249 	case DN_AQM_PARAMS:
250 		if( !strcasecmp(ep->name, "codel")) {
251 			us_to_time(ep->par[0], strt1);
252 			us_to_time(ep->par[1], strt2);
253 			l = sprintf(out, " AQM CoDel target %s interval %s",
254 				strt1, strt2);
255 			if (ep->par[2] & CODEL_ECN_ENABLED)
256 				l = sprintf(out + l, " ECN");
257 			else
258 				l += sprintf(out + l, " NoECN");
259 		} else if( !strcasecmp(ep->name, "pie")) {
260 			us_to_time(ep->par[0], strt1);
261 			us_to_time(ep->par[1], strt2);
262 			us_to_time(ep->par[2], strt3);
263 			l = sprintf(out, " AQM type PIE target %s tupdate %s alpha "
264 					"%g beta %g max_burst %s max_ecnth %.3g",
265 					strt1,
266 					strt2,
267 					ep->par[4] / (float) PIE_SCALE,
268 					ep->par[5] / (float) PIE_SCALE,
269 					strt3,
270 					ep->par[3] / (float) PIE_SCALE
271 				);
272 
273 			if (ep->par[6] & PIE_ECN_ENABLED)
274 				l += sprintf(out + l, " ECN");
275 			else
276 				l += sprintf(out + l, " NoECN");
277 			if (ep->par[6] & PIE_CAPDROP_ENABLED)
278 				l += sprintf(out + l, " CapDrop");
279 			else
280 				l += sprintf(out + l, " NoCapDrop");
281 			if (ep->par[6] & PIE_ON_OFF_MODE_ENABLED)
282 				l += sprintf(out + l, " OnOff");
283 			if (ep->par[6] & PIE_DEPRATEEST_ENABLED)
284 				l += sprintf(out + l, " DRE");
285 			else
286 				l += sprintf(out + l, " TS");
287 			if (ep->par[6] & PIE_DERAND_ENABLED)
288 				l += sprintf(out + l, " Derand");
289 			else
290 				l += sprintf(out + l, " NoDerand");
291 		}
292 		break;
293 
294 	case	DN_SCH_PARAMS:
295 		if (!strcasecmp(ep->name,"FQ_CODEL")) {
296 			us_to_time(ep->par[0], strt1);
297 			us_to_time(ep->par[1], strt2);
298 			l = sprintf(out," FQ_CODEL target %s interval %s"
299 				" quantum %jd limit %jd flows %jd",
300 				strt1, strt2,
301 				(intmax_t) ep->par[3],
302 				(intmax_t) ep->par[4],
303 				(intmax_t) ep->par[5]
304 				);
305 			if (ep->par[2] & CODEL_ECN_ENABLED)
306 				l += sprintf(out + l, " ECN");
307 			else
308 				l += sprintf(out + l, " NoECN");
309 			l += sprintf(out + l, "\n");
310 		} else 	if (!strcasecmp(ep->name,"FQ_PIE")) {
311 			us_to_time(ep->par[0], strt1);
312 			us_to_time(ep->par[1], strt2);
313 			us_to_time(ep->par[2], strt3);
314 			l = sprintf(out, "  FQ_PIE target %s tupdate %s alpha "
315 				"%g beta %g max_burst %s max_ecnth %.3g"
316 				" quantum %jd limit %jd flows %jd",
317 				strt1,
318 				strt2,
319 				ep->par[4] / (float) PIE_SCALE,
320 				ep->par[5] / (float) PIE_SCALE,
321 				strt3,
322 				ep->par[3] / (float) PIE_SCALE,
323 				(intmax_t) ep->par[7],
324 				(intmax_t) ep->par[8],
325 				(intmax_t) ep->par[9]
326 			);
327 
328 			if (ep->par[6] & PIE_ECN_ENABLED)
329 				l += sprintf(out + l, " ECN");
330 			else
331 				l += sprintf(out + l, " NoECN");
332 			if (ep->par[6] & PIE_CAPDROP_ENABLED)
333 				l += sprintf(out + l, " CapDrop");
334 			else
335 				l += sprintf(out + l, " NoCapDrop");
336 			if (ep->par[6] & PIE_ON_OFF_MODE_ENABLED)
337 				l += sprintf(out + l, " OnOff");
338 			if (ep->par[6] & PIE_DEPRATEEST_ENABLED)
339 				l += sprintf(out + l, " DRE");
340 			else
341 				l += sprintf(out + l, " TS");
342 			if (ep->par[6] & PIE_DERAND_ENABLED)
343 				l += sprintf(out + l, " Derand");
344 			else
345 				l += sprintf(out + l, " NoDerand");
346 			l += sprintf(out + l, "\n");
347 		}
348 		break;
349 	}
350 
351 	free(ep);
352 }
353 #endif
354 
355 
356 #if 0
357 static int
358 sort_q(void *arg, const void *pa, const void *pb)
359 {
360 	int rev = (co.do_sort < 0);
361 	int field = rev ? -co.do_sort : co.do_sort;
362 	long long res = 0;
363 	const struct dn_flow_queue *a = pa;
364 	const struct dn_flow_queue *b = pb;
365 
366 	switch (field) {
367 	case 1: /* pkts */
368 		res = a->len - b->len;
369 		break;
370 	case 2: /* bytes */
371 		res = a->len_bytes - b->len_bytes;
372 		break;
373 
374 	case 3: /* tot pkts */
375 		res = a->tot_pkts - b->tot_pkts;
376 		break;
377 
378 	case 4: /* tot bytes */
379 		res = a->tot_bytes - b->tot_bytes;
380 		break;
381 	}
382 	if (res < 0)
383 		res = -1;
384 	if (res > 0)
385 		res = 1;
386 	return (int)(rev ? res : -res);
387 }
388 #endif
389 
390 /* print a mask and header for the subsequent list of flows */
391 static void
print_mask(struct ipfw_flow_id * id)392 print_mask(struct ipfw_flow_id *id)
393 {
394 	if (!IS_IP6_FLOW_ID(id)) {
395 		printf("    "
396 		    "mask: %s 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
397 		    id->extra ? "queue," : "",
398 		    id->proto,
399 		    id->src_ip, id->src_port,
400 		    id->dst_ip, id->dst_port);
401 	} else {
402 		char buf[255];
403 		printf("\n        mask: %sproto: 0x%02x, flow_id: 0x%08x,  ",
404 		    id->extra ? "queue," : "",
405 		    id->proto, id->flow_id6);
406 		inet_ntop(AF_INET6, &(id->src_ip6), buf, sizeof(buf));
407 		printf("%s/0x%04x -> ", buf, id->src_port);
408 		inet_ntop(AF_INET6, &(id->dst_ip6), buf, sizeof(buf));
409 		printf("%s/0x%04x\n", buf, id->dst_port);
410 	}
411 }
412 
413 static void
print_header(struct ipfw_flow_id * id)414 print_header(struct ipfw_flow_id *id)
415 {
416 	if (!IS_IP6_FLOW_ID(id))
417 		printf("BKT Prot ___Source IP/port____ "
418 		    "____Dest. IP/port____ "
419 		    "Tot_pkt/bytes Pkt/Byte Drp\n");
420 	else
421 		printf("BKT ___Prot___ _flow-id_ "
422 		    "______________Source IPv6/port_______________ "
423 		    "_______________Dest. IPv6/port_______________ "
424 		    "Tot_pkt/bytes Pkt/Byte Drp\n");
425 }
426 
427 static void
list_flow(struct buf_pr * bp,struct dn_flow * ni)428 list_flow(struct buf_pr *bp, struct dn_flow *ni)
429 {
430 	char buff[255];
431 	struct protoent *pe = NULL;
432 	struct in_addr ina;
433 	struct ipfw_flow_id *id = &ni->fid;
434 
435 	pe = getprotobynumber(id->proto);
436 		/* XXX: Should check for IPv4 flows */
437 	bprintf(bp, "%3u%c", (ni->oid.id) & 0xff,
438 		id->extra ? '*' : ' ');
439 	if (!IS_IP6_FLOW_ID(id)) {
440 		if (pe)
441 			bprintf(bp, "%-4s ", pe->p_name);
442 		else
443 			bprintf(bp, "%4u ", id->proto);
444 		ina.s_addr = htonl(id->src_ip);
445 		bprintf(bp, "%15s/%-5d ",
446 		    inet_ntoa(ina), id->src_port);
447 		ina.s_addr = htonl(id->dst_ip);
448 		bprintf(bp, "%15s/%-5d ",
449 		    inet_ntoa(ina), id->dst_port);
450 	} else {
451 		/* Print IPv6 flows */
452 		if (pe != NULL)
453 			bprintf(bp, "%9s ", pe->p_name);
454 		else
455 			bprintf(bp, "%9u ", id->proto);
456 		bprintf(bp, "%7d  %39s/%-5d ", id->flow_id6,
457 		    inet_ntop(AF_INET6, &(id->src_ip6), buff, sizeof(buff)),
458 		    id->src_port);
459 		bprintf(bp, " %39s/%-5d ",
460 		    inet_ntop(AF_INET6, &(id->dst_ip6), buff, sizeof(buff)),
461 		    id->dst_port);
462 	}
463 	pr_u64(bp, &ni->tot_pkts, 4);
464 	pr_u64(bp, &ni->tot_bytes, 8);
465 	bprintf(bp, "%2u %4u %3u",
466 	    ni->length, ni->len_bytes, ni->drops);
467 }
468 
469 static void
print_flowset_parms(struct dn_fs * fs,char * prefix)470 print_flowset_parms(struct dn_fs *fs, char *prefix)
471 {
472 	int l;
473 	char qs[30];
474 	char plr[40];
475 	char red[200];	/* Display RED parameters */
476 
477 	l = fs->qsize;
478 	if (fs->flags & DN_QSIZE_BYTES) {
479 		if (l >= 8192)
480 			sprintf(qs, "%d KB", l / 1024);
481 		else
482 			sprintf(qs, "%d B", l);
483 	} else
484 		sprintf(qs, "%3d sl.", l);
485 	if (fs->plr[0] || fs->plr[1]) {
486 		if (fs->plr[1] == 0)
487 			sprintf(plr, "plr %f",
488 				1.0 * fs->plr[0] / (double)(0x7fffffff));
489 		else
490 			sprintf(plr, "plr %f,%f,%f,%f",
491 				1.0 * fs->plr[0] / (double)(0x7fffffff),
492 				1.0 * fs->plr[1] / (double)(0x7fffffff),
493 				1.0 * fs->plr[2] / (double)(0x7fffffff),
494 				1.0 * fs->plr[3] / (double)(0x7fffffff));
495 	} else
496 		plr[0] = '\0';
497 
498 	if (fs->flags & DN_IS_RED) {	/* RED parameters */
499 		sprintf(red,
500 		    "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
501 		    (fs->flags & DN_IS_GENTLE_RED) ? 'G' : ' ',
502 		    1.0 * fs->w_q / (double)(1 << SCALE_RED),
503 		    fs->min_th,
504 		    fs->max_th,
505 		    1.0 * fs->max_p / (double)(1 << SCALE_RED));
506 		if (fs->flags & DN_IS_ECN)
507 			strlcat(red, " (ecn)", sizeof(red));
508 #ifdef NEW_AQM
509 	/* get AQM parameters */
510 	} else if (fs->flags & DN_IS_AQM) {
511 			get_extra_parms(fs->fs_nr, red, DN_AQM_PARAMS);
512 #endif
513 	} else
514 		sprintf(red, "droptail");
515 
516 	if (prefix[0]) {
517 	    printf("%s %s%s %d queues (%d buckets) %s\n",
518 		prefix, qs, plr, fs->oid.id, fs->buckets, red);
519 	    prefix[0] = '\0';
520 	} else {
521 	    printf("q%05d %s%s %d flows (%d buckets) sched %d "
522 			"weight %d lmax %d pri %d %s\n",
523 		fs->fs_nr, qs, plr, fs->oid.id, fs->buckets,
524 		fs->sched_nr, fs->par[0], fs->par[1], fs->par[2], red);
525 	    if (fs->flags & DN_HAVE_MASK)
526 		print_mask(&fs->flow_mask);
527 	}
528 }
529 
530 static void
print_extra_delay_parms(struct dn_profile * p)531 print_extra_delay_parms(struct dn_profile *p)
532 {
533 	double loss;
534 	if (p->samples_no <= 0)
535 		return;
536 
537 	loss = p->loss_level;
538 	loss /= p->samples_no;
539 	printf("\t profile: name \"%s\" loss %f samples %d\n",
540 		p->name, loss, p->samples_no);
541 }
542 
543 static void
flush_buf(char * buf)544 flush_buf(char *buf)
545 {
546 	if (buf[0])
547 		printf("%s\n", buf);
548 	buf[0] = '\0';
549 }
550 
551 /*
552  * generic list routine. We expect objects in a specific order, i.e.
553  * PIPES AND SCHEDULERS:
554  *	link; scheduler; internal flowset if any; instances
555  * we can tell a pipe from the number.
556  *
557  * FLOWSETS:
558  *	flowset; queues;
559  * link i (int queue); scheduler i; si(i) { flowsets() : queues }
560  */
561 static void
list_pipes(struct dn_id * oid,struct dn_id * end)562 list_pipes(struct dn_id *oid, struct dn_id *end)
563 {
564     char buf[160];	/* pending buffer */
565     int toPrint = 1;	/* print header */
566     struct buf_pr bp;
567 
568     buf[0] = '\0';
569     bp_alloc(&bp, 4096);
570     for (; oid != end; oid = O_NEXT(oid, oid->len)) {
571 	if (oid->len < sizeof(*oid))
572 		errx(1, "invalid oid len %d\n", oid->len);
573 
574 	switch (oid->type) {
575 	default:
576 	    flush_buf(buf);
577 	    printf("unrecognized object %d size %d\n", oid->type, oid->len);
578 	    break;
579 	case DN_TEXT: /* list of attached flowsets */
580 	    {
581 		int i, l;
582 		struct {
583 			struct dn_id id;
584 			uint32_t p[0];
585 		} *d = (void *)oid;
586 		l = (oid->len - sizeof(*oid))/sizeof(d->p[0]);
587 		if (l == 0)
588 		    break;
589 		printf("   Children flowsets: ");
590 		for (i = 0; i < l; i++)
591 			printf("%u ", d->p[i]);
592 		printf("\n");
593 		break;
594 	    }
595 	case DN_CMD_GET:
596 	    if (g_co.verbose)
597 		printf("answer for cmd %d, len %d\n", oid->type, oid->id);
598 	    break;
599 	case DN_SCH: {
600 	    struct dn_sch *s = (struct dn_sch *)oid;
601 	    flush_buf(buf);
602 	    printf(" sched %d type %s flags 0x%x %d buckets %d active\n",
603 			s->sched_nr,
604 			s->name, s->flags, s->buckets, s->oid.id);
605 #ifdef NEW_AQM
606 		char parms[200];
607 		get_extra_parms(s->sched_nr, parms, DN_SCH_PARAMS);
608 		printf("%s",parms);
609 #endif
610 	    if (s->flags & DN_HAVE_MASK)
611 		print_mask(&s->sched_mask);
612 	    }
613 	    break;
614 
615 	case DN_FLOW:
616 	    if (toPrint != 0) {
617 		    print_header(&((struct dn_flow *)oid)->fid);
618 		    toPrint = 0;
619 	    }
620 	    list_flow(&bp, (struct dn_flow *)oid);
621 	    printf("%s\n", bp.buf);
622 	    bp_flush(&bp);
623 	    break;
624 
625 	case DN_LINK: {
626 	    struct dn_link *p = (struct dn_link *)oid;
627 	    double b = p->bandwidth;
628 	    char bwbuf[30];
629 	    char burst[5 + 7];
630 
631 	    /* This starts a new object so flush buffer */
632 	    flush_buf(buf);
633 	    /* data rate */
634 	    if (b == 0)
635 		sprintf(bwbuf, "unlimited     ");
636 	    else if (b >= 1000000000)
637 		sprintf(bwbuf, "%7.3f Gbit/s", b/1000000000);
638 	    else if (b >= 1000000)
639 		sprintf(bwbuf, "%7.3f Mbit/s", b/1000000);
640 	    else if (b >= 1000)
641 		sprintf(bwbuf, "%7.3f Kbit/s", b/1000);
642 	    else
643 		sprintf(bwbuf, "%7.3f bit/s ", b);
644 
645 	    if (humanize_number(burst, sizeof(burst), p->burst,
646 		    "", HN_AUTOSCALE, 0) < 0 || g_co.verbose)
647 		sprintf(burst, "%d", (int)p->burst);
648 	    sprintf(buf, "%05d: %s %4d ms burst %s",
649 		p->link_nr % DN_MAX_ID, bwbuf, p->delay, burst);
650 	    }
651 	    break;
652 
653 	case DN_FS:
654 	    print_flowset_parms((struct dn_fs *)oid, buf);
655 	    break;
656 	case DN_PROFILE:
657 	    flush_buf(buf);
658 	    print_extra_delay_parms((struct dn_profile *)oid);
659 	}
660 	flush_buf(buf); // XXX does it really go here ?
661     }
662 
663     bp_free(&bp);
664 }
665 
666 /*
667  * Delete pipe, queue or scheduler i
668  */
669 int
ipfw_delete_pipe(int do_pipe,int i)670 ipfw_delete_pipe(int do_pipe, int i)
671 {
672 	struct {
673 		struct dn_id oid;
674 		uintptr_t a[1];	/* add more if we want a list */
675 	} cmd;
676 	oid_fill((void *)&cmd, sizeof(cmd), DN_CMD_DELETE, DN_API_VERSION);
677 	cmd.oid.subtype = (do_pipe == 1) ? DN_LINK :
678 		( (do_pipe == 2) ? DN_FS : DN_SCH);
679 	cmd.a[0] = i;
680 	i = do_cmd(IP_DUMMYNET3, &cmd, cmd.oid.len);
681 	if (i) {
682 		i = 1;
683 		warn("rule %u: setsockopt(IP_DUMMYNET3)", i);
684 	}
685 	return i;
686 }
687 
688 /*
689  * Code to parse delay profiles.
690  *
691  * Some link types introduce extra delays in the transmission
692  * of a packet, e.g. because of MAC level framing, contention on
693  * the use of the channel, MAC level retransmissions and so on.
694  * From our point of view, the channel is effectively unavailable
695  * for this extra time, which is constant or variable depending
696  * on the link type. Additionally, packets may be dropped after this
697  * time (e.g. on a wireless link after too many retransmissions).
698  * We can model the additional delay with an empirical curve
699  * that represents its distribution.
700  *
701  *      cumulative probability
702  *      1.0 ^
703  *          |
704  *      L   +-- loss-level          x
705  *          |                 ******
706  *          |                *
707  *          |           *****
708  *          |          *
709  *          |        **
710  *          |       *
711  *          +-------*------------------->
712  *                      delay
713  *
714  * The empirical curve may have both vertical and horizontal lines.
715  * Vertical lines represent constant delay for a range of
716  * probabilities; horizontal lines correspond to a discontinuty
717  * in the delay distribution: the link will use the largest delay
718  * for a given probability.
719  *
720  * To pass the curve to dummynet, we must store the parameters
721  * in a file as described below, and issue the command
722  *
723  *      ipfw pipe <n> config ... bw XXX profile <filename> ...
724  *
725  * The file format is the following, with whitespace acting as
726  * a separator and '#' indicating the beginning a comment:
727  *
728  *	samples N
729  *		the number of samples used in the internal
730  *		representation (2..1024; default 100);
731  *
732  *	loss-level L
733  *		The probability above which packets are lost.
734  *	       (0.0 <= L <= 1.0, default 1.0 i.e. no loss);
735  *
736  *	name identifier
737  *		Optional a name (listed by "ipfw pipe show")
738  *		to identify the distribution;
739  *
740  *	"delay prob" | "prob delay"
741  *		One of these two lines is mandatory and defines
742  *		the format of the following lines with data points.
743  *
744  *	XXX YYY
745  *		2 or more lines representing points in the curve,
746  *		with either delay or probability first, according
747  *		to the chosen format.
748  *		The unit for delay is milliseconds.
749  *
750  * Data points does not need to be ordered or equal to the number
751  * specified in the "samples" line. ipfw will sort and interpolate
752  * the curve as needed.
753  *
754  * Example of a profile file:
755 
756 	name    bla_bla_bla
757 	samples 100
758 	loss-level    0.86
759 	prob    delay
760 	0       200	# minimum overhead is 200ms
761 	0.5     200
762 	0.5     300
763 	0.8     1000
764 	0.9     1300
765 	1       1300
766 
767  * Internally, we will convert the curve to a fixed number of
768  * samples, and when it is time to transmit a packet we will
769  * model the extra delay as extra bits in the packet.
770  *
771  */
772 
773 #define ED_MAX_LINE_LEN	256+ED_MAX_NAME_LEN
774 #define ED_TOK_SAMPLES	"samples"
775 #define ED_TOK_LOSS	"loss-level"
776 #define ED_TOK_NAME	"name"
777 #define ED_TOK_DELAY	"delay"
778 #define ED_TOK_PROB	"prob"
779 #define ED_TOK_BW	"bw"
780 #define ED_SEPARATORS	" \t\n"
781 #define ED_MIN_SAMPLES_NO	2
782 
783 /*
784  * returns 1 if s is a non-negative number, with at least one '.'
785  */
786 static int
is_valid_number(const char * s)787 is_valid_number(const char *s)
788 {
789 	int i, dots_found = 0;
790 	int len = strlen(s);
791 
792 	for (i = 0; i<len; ++i)
793 		if (!isdigit(s[i]) && (s[i] !='.' || ++dots_found > 1))
794 			return 0;
795 	return 1;
796 }
797 
798 /*
799  * Take as input a string describing a bandwidth value
800  * and return the numeric bandwidth value.
801  * set clocking interface or bandwidth value
802  */
803 static void
read_bandwidth(char * arg,uint32_t * bandwidth,char * if_name,int namelen)804 read_bandwidth(char *arg, uint32_t *bandwidth, char *if_name, int namelen)
805 {
806 	if (*bandwidth != (uint32_t)-1)
807 		warnx("duplicate token, override bandwidth value!");
808 
809 	if (arg[0] >= 'a' && arg[0] <= 'z') {
810 		if (!if_name) {
811 			errx(1, "no if support");
812 		}
813 		if (namelen >= IFNAMSIZ)
814 			warn("interface name truncated");
815 		namelen--;
816 		/* interface name */
817 		strlcpy(if_name, arg, namelen);
818 		*bandwidth = 0;
819 	} else {	/* read bandwidth value */
820 		uint64_t bw;
821 		char *end = NULL;
822 
823 		bw = strtoul(arg, &end, 0);
824 		if (*end == 'K' || *end == 'k') {
825 			end++;
826 			bw *= 1000;
827 		} else if (*end == 'M' || *end == 'm') {
828 			end++;
829 			bw *= 1000000;
830 		} else if (*end == 'G' || *end == 'g') {
831 			end++;
832 			bw *= 1000000000;
833 		}
834 		if ((*end == 'B' &&
835 			_substrcmp2(end, "Bi", "Bit/s") != 0) ||
836 		    _substrcmp2(end, "by", "bytes") == 0)
837 			bw *= 8;
838 
839 		if (bw > UINT_MAX)
840 			errx(EX_DATAERR, "bandwidth too large");
841 
842 		*bandwidth = (uint32_t)bw;
843 		if (if_name)
844 			if_name[0] = '\0';
845 	}
846 }
847 
848 struct point {
849 	double prob;
850 	double delay;
851 };
852 
853 static int
compare_points(const void * vp1,const void * vp2)854 compare_points(const void *vp1, const void *vp2)
855 {
856 	const struct point *p1 = vp1;
857 	const struct point *p2 = vp2;
858 	double res = 0;
859 
860 	res = p1->prob - p2->prob;
861 	if (res == 0)
862 		res = p1->delay - p2->delay;
863 	if (res < 0)
864 		return -1;
865 	else if (res > 0)
866 		return 1;
867 	else
868 		return 0;
869 }
870 
871 #define ED_EFMT(s) EX_DATAERR,"error in %s at line %d: "#s,filename,lineno
872 
873 static void
load_extra_delays(const char * filename,struct dn_profile * p,struct dn_link * link)874 load_extra_delays(const char *filename, struct dn_profile *p,
875 	struct dn_link *link)
876 {
877 	char    line[ED_MAX_LINE_LEN];
878 	FILE    *f;
879 	int     lineno = 0;
880 	int     i;
881 
882 	int     samples = -1;
883 	double  loss = -1.0;
884 	char    profile_name[ED_MAX_NAME_LEN];
885 	int     delay_first = -1;
886 	int     do_points = 0;
887 	struct point    points[ED_MAX_SAMPLES_NO];
888 	int     points_no = 0;
889 
890 	/* XXX link never NULL? */
891 	p->link_nr = link->link_nr;
892 
893 	profile_name[0] = '\0';
894 	f = fopen(filename, "r");
895 	if (f == NULL)
896 		err(EX_UNAVAILABLE, "fopen: %s", filename);
897 
898 	while (fgets(line, ED_MAX_LINE_LEN, f)) {	 /* read commands */
899 		char *s, *cur = line, *name = NULL, *arg = NULL;
900 
901 		++lineno;
902 
903 		/* parse the line */
904 		while (cur) {
905 			s = strsep(&cur, ED_SEPARATORS);
906 			if (s == NULL || *s == '#')
907 				break;
908 			if (*s == '\0')
909 				continue;
910 			if (arg)
911 				errx(ED_EFMT("too many arguments"));
912 			if (name == NULL)
913 				name = s;
914 			else
915 				arg = s;
916 		}
917 		if (name == NULL)	/* empty line */
918 			continue;
919 		if (arg == NULL)
920 			errx(ED_EFMT("missing arg for %s"), name);
921 
922 		if (!strcasecmp(name, ED_TOK_SAMPLES)) {
923 		    if (samples > 0)
924 			errx(ED_EFMT("duplicate ``samples'' line"));
925 		    if (atoi(arg) <=0)
926 			errx(ED_EFMT("invalid number of samples"));
927 		    samples = atoi(arg);
928 		    if (samples>ED_MAX_SAMPLES_NO)
929 			    errx(ED_EFMT("too many samples, maximum is %d"),
930 				ED_MAX_SAMPLES_NO);
931 		    do_points = 0;
932 		} else if (!strcasecmp(name, ED_TOK_BW)) {
933 		    char buf[IFNAMSIZ];
934 		    read_bandwidth(arg, &link->bandwidth, buf, sizeof(buf));
935 		} else if (!strcasecmp(name, ED_TOK_LOSS)) {
936 		    if (loss != -1.0)
937 			errx(ED_EFMT("duplicated token: %s"), name);
938 		    if (!is_valid_number(arg))
939 			errx(ED_EFMT("invalid %s"), arg);
940 		    loss = atof(arg);
941 		    if (loss > 1)
942 			errx(ED_EFMT("%s greater than 1.0"), name);
943 		    do_points = 0;
944 		} else if (!strcasecmp(name, ED_TOK_NAME)) {
945 		    if (profile_name[0] != '\0')
946 			errx(ED_EFMT("duplicated token: %s"), name);
947 		    strlcpy(profile_name, arg, sizeof(profile_name));
948 		    do_points = 0;
949 		} else if (!strcasecmp(name, ED_TOK_DELAY)) {
950 		    if (do_points)
951 			errx(ED_EFMT("duplicated token: %s"), name);
952 		    delay_first = 1;
953 		    do_points = 1;
954 		} else if (!strcasecmp(name, ED_TOK_PROB)) {
955 		    if (do_points)
956 			errx(ED_EFMT("duplicated token: %s"), name);
957 		    delay_first = 0;
958 		    do_points = 1;
959 		} else if (do_points) {
960 		    if (!is_valid_number(name) || !is_valid_number(arg))
961 			errx(ED_EFMT("invalid point found"));
962 		    if (points_no >= ED_MAX_SAMPLES_NO)
963 			errx(ED_EFMT("too many samples, maximum is %d"),
964 			    ED_MAX_SAMPLES_NO);
965 		    if (delay_first) {
966 			points[points_no].delay = atof(name);
967 			points[points_no].prob = atof(arg);
968 		    } else {
969 			points[points_no].delay = atof(arg);
970 			points[points_no].prob = atof(name);
971 		    }
972 		    if (points[points_no].prob > 1.0)
973 			errx(ED_EFMT("probability greater than 1.0"));
974 		    ++points_no;
975 		} else {
976 		    errx(ED_EFMT("unrecognised command '%s'"), name);
977 		}
978 	}
979 
980 	fclose (f);
981 
982 	if (samples == -1) {
983 	    warnx("'%s' not found, assuming 100", ED_TOK_SAMPLES);
984 	    samples = 100;
985 	}
986 
987 	if (loss == -1.0) {
988 	    warnx("'%s' not found, assuming no loss", ED_TOK_LOSS);
989 	    loss = 1;
990 	}
991 
992 	/* make sure that there are enough points. */
993 	if (points_no < ED_MIN_SAMPLES_NO)
994 	    errx(ED_EFMT("too few samples, need at least %d"),
995 		ED_MIN_SAMPLES_NO);
996 
997 	qsort(points, points_no, sizeof(struct point), compare_points);
998 
999 	/* interpolation */
1000 	for (i = 0; i<points_no-1; ++i) {
1001 	    double y1 = points[i].prob * samples;
1002 	    double x1 = points[i].delay;
1003 	    double y2 = points[i+1].prob * samples;
1004 	    double x2 = points[i+1].delay;
1005 
1006 	    int ix = y1;
1007 	    int stop = y2;
1008 
1009 	    if (x1 == x2) {
1010 		for (; ix<stop; ++ix)
1011 		    p->samples[ix] = x1;
1012 	    } else {
1013 		double m = (y2-y1)/(x2-x1);
1014 		double c = y1 - m*x1;
1015 		for (; ix<stop ; ++ix)
1016 		    p->samples[ix] = (ix - c)/m;
1017 	    }
1018 	}
1019 	p->samples_no = samples;
1020 	p->loss_level = loss * samples;
1021 	strlcpy(p->name, profile_name, sizeof(p->name));
1022 }
1023 
1024 #ifdef NEW_AQM
1025 
1026 /* Parse AQM/extra scheduler parameters */
1027 static int
process_extra_parms(int * ac,char ** av,struct dn_extra_parms * ep,uint16_t type)1028 process_extra_parms(int *ac, char **av, struct dn_extra_parms *ep,
1029 	uint16_t type)
1030 {
1031 	int i;
1032 
1033 	/* use kernel defaults */
1034 	for (i=0; i<DN_MAX_EXTRA_PARM; i++)
1035 		ep->par[i] = -1;
1036 
1037 	switch(type) {
1038 	case TOK_CODEL:
1039 	case TOK_FQ_CODEL:
1040 	/* Codel
1041 	 * 0- target, 1- interval, 2- flags,
1042 	 * FQ_CODEL
1043 	 * 3- quantum, 4- limit, 5- flows
1044 	 */
1045 		if (type==TOK_CODEL)
1046 			ep->par[2] = 0;
1047 		else
1048 			ep->par[2] = CODEL_ECN_ENABLED;
1049 
1050 		while (*ac > 0) {
1051 			int tok = match_token(aqm_params, *av);
1052 			(*ac)--; av++;
1053 			switch(tok) {
1054 			case TOK_TARGET:
1055 				if (*ac <= 0 || time_to_us(av[0]) < 0)
1056 					errx(EX_DATAERR, "target needs time\n");
1057 
1058 				ep->par[0] = time_to_us(av[0]);
1059 				(*ac)--; av++;
1060 				break;
1061 
1062 			case TOK_INTERVAL:
1063 				if (*ac <= 0 || time_to_us(av[0]) < 0)
1064 					errx(EX_DATAERR, "interval needs time\n");
1065 
1066 				ep->par[1] = time_to_us(av[0]);
1067 				(*ac)--; av++;
1068 				break;
1069 
1070 			case TOK_ECN:
1071 				ep->par[2] = CODEL_ECN_ENABLED;
1072 				break;
1073 			case TOK_NO_ECN:
1074 				ep->par[2] &= ~CODEL_ECN_ENABLED;
1075 				break;
1076 			/* Config fq_codel parameters */
1077 			case TOK_QUANTUM:
1078 				if (type != TOK_FQ_CODEL)
1079 					errx(EX_DATAERR, "quantum is not for codel\n");
1080 				if (*ac <= 0 || !is_valid_number(av[0]))
1081 					errx(EX_DATAERR, "quantum needs number\n");
1082 
1083 				ep->par[3]= atoi(av[0]);
1084 				(*ac)--; av++;
1085 				break;
1086 
1087 			case TOK_LIMIT:
1088 				if (type != TOK_FQ_CODEL)
1089 					errx(EX_DATAERR, "limit is not for codel, use queue instead\n");
1090 				if (*ac <= 0 || !is_valid_number(av[0]))
1091 					errx(EX_DATAERR, "limit needs number\n");
1092 
1093 				ep->par[4] = atoi(av[0]);
1094 				(*ac)--; av++;
1095 				break;
1096 
1097 			case TOK_FLOWS:
1098 				if (type != TOK_FQ_CODEL)
1099 					errx(EX_DATAERR, "flows is not for codel\n");
1100 				if (*ac <= 0 || !is_valid_number(av[0]))
1101 					errx(EX_DATAERR, "flows needs number\n");
1102 
1103 				ep->par[5] = atoi(av[0]);
1104 				(*ac)--; av++;
1105 				break;
1106 
1107 			default:
1108 				printf("%s is Invalid parameter\n", av[-1]);
1109 			}
1110 		}
1111 		break;
1112 	case TOK_PIE:
1113 	case TOK_FQ_PIE:
1114 		/* PIE
1115 		 * 0- target , 1- tupdate, 2- max_burst,
1116 		 * 3- max_ecnth, 4- alpha,
1117 		 * 5- beta, 6- flags
1118 		 * FQ_CODEL
1119 		 * 7- quantum, 8- limit, 9- flows
1120 		 */
1121 
1122 		if ( type == TOK_PIE)
1123 			ep->par[6] = PIE_CAPDROP_ENABLED | PIE_DEPRATEEST_ENABLED
1124 				| PIE_DERAND_ENABLED;
1125 		else
1126 			/* for FQ-PIE, use TS mode */
1127 			ep->par[6] = PIE_CAPDROP_ENABLED |  PIE_DERAND_ENABLED
1128 				| PIE_ECN_ENABLED;
1129 
1130 		while (*ac > 0) {
1131 			int tok = match_token(aqm_params, *av);
1132 			(*ac)--; av++;
1133 			switch(tok) {
1134 			case TOK_TARGET:
1135 				if (*ac <= 0 || time_to_us(av[0]) < 0)
1136 					errx(EX_DATAERR, "target needs time\n");
1137 
1138 				ep->par[0] = time_to_us(av[0]);
1139 				(*ac)--; av++;
1140 				break;
1141 
1142 			case TOK_TUPDATE:
1143 				if (*ac <= 0 || time_to_us(av[0]) < 0)
1144 					errx(EX_DATAERR, "tupdate needs time\n");
1145 
1146 				ep->par[1] = time_to_us(av[0]);
1147 				(*ac)--; av++;
1148 				break;
1149 
1150 			case TOK_MAX_BURST:
1151 				if (*ac <= 0 || time_to_us(av[0]) < 0)
1152 					errx(EX_DATAERR, "max_burst needs time\n");
1153 
1154 				ep->par[2] = time_to_us(av[0]);
1155 				(*ac)--; av++;
1156 				break;
1157 
1158 			case TOK_MAX_ECNTH:
1159 				if (*ac <= 0 || !is_valid_number(av[0]))
1160 					errx(EX_DATAERR, "max_ecnth needs number\n");
1161 
1162 				ep->par[3] = atof(av[0]) * PIE_SCALE;
1163 				(*ac)--; av++;
1164 				break;
1165 
1166 			case TOK_ALPHA:
1167 				if (*ac <= 0 || !is_valid_number(av[0]))
1168 					errx(EX_DATAERR, "alpha needs number\n");
1169 
1170 				ep->par[4] = atof(av[0]) * PIE_SCALE;
1171 				(*ac)--; av++;
1172 				break;
1173 
1174 			case TOK_BETA:
1175 				if (*ac <= 0 || !is_valid_number(av[0]))
1176 					errx(EX_DATAERR, "beta needs number\n");
1177 
1178 				ep->par[5] = atof(av[0]) * PIE_SCALE;
1179 				(*ac)--; av++;
1180 				break;
1181 
1182 			case TOK_ECN:
1183 				ep->par[6] |= PIE_ECN_ENABLED;
1184 				break;
1185 			case TOK_NO_ECN:
1186 				ep->par[6] &= ~PIE_ECN_ENABLED;
1187 				break;
1188 
1189 			case TOK_CAPDROP:
1190 				ep->par[6] |= PIE_CAPDROP_ENABLED;
1191 				break;
1192 			case TOK_NO_CAPDROP:
1193 				ep->par[6] &= ~PIE_CAPDROP_ENABLED;
1194 				break;
1195 
1196 			case TOK_ONOFF:
1197 				ep->par[6] |= PIE_ON_OFF_MODE_ENABLED;
1198 				break;
1199 
1200 			case TOK_DRE:
1201 				ep->par[6] |= PIE_DEPRATEEST_ENABLED;
1202 				break;
1203 
1204 			case TOK_TS:
1205 				ep->par[6] &= ~PIE_DEPRATEEST_ENABLED;
1206 				break;
1207 
1208 			case TOK_DERAND:
1209 				ep->par[6] |= PIE_DERAND_ENABLED;
1210 				break;
1211 			case TOK_NO_DERAND:
1212 				ep->par[6] &= ~PIE_DERAND_ENABLED;
1213 				break;
1214 
1215 			/* Config fq_pie parameters */
1216 			case TOK_QUANTUM:
1217 				if (type != TOK_FQ_PIE)
1218 					errx(EX_DATAERR, "quantum is not for pie\n");
1219 				if (*ac <= 0 || !is_valid_number(av[0]))
1220 					errx(EX_DATAERR, "quantum needs number\n");
1221 
1222 				ep->par[7]= atoi(av[0]);
1223 				(*ac)--; av++;
1224 				break;
1225 
1226 			case TOK_LIMIT:
1227 				if (type != TOK_FQ_PIE)
1228 					errx(EX_DATAERR, "limit is not for pie, use queue instead\n");
1229 				if (*ac <= 0 || !is_valid_number(av[0]))
1230 					errx(EX_DATAERR, "limit needs number\n");
1231 
1232 				ep->par[8] = atoi(av[0]);
1233 				(*ac)--; av++;
1234 				break;
1235 
1236 			case TOK_FLOWS:
1237 				if (type != TOK_FQ_PIE)
1238 					errx(EX_DATAERR, "flows is not for pie\n");
1239 				if (*ac <= 0 || !is_valid_number(av[0]))
1240 					errx(EX_DATAERR, "flows needs number\n");
1241 
1242 				ep->par[9] = atoi(av[0]);
1243 				(*ac)--; av++;
1244 				break;
1245 
1246 
1247 			default:
1248 				printf("%s is invalid parameter\n", av[-1]);
1249 			}
1250 		}
1251 		break;
1252 	}
1253 
1254 	return 0;
1255 }
1256 
1257 #endif
1258 
1259 
1260 /*
1261  * configuration of pipes, schedulers, flowsets.
1262  * When we configure a new scheduler, an empty pipe is created, so:
1263  *
1264  * do_pipe = 1 -> "pipe N config ..." only for backward compatibility
1265  *	sched N+Delta type fifo sched_mask ...
1266  *	pipe N+Delta <parameters>
1267  *	flowset N+Delta pipe N+Delta (no parameters)
1268  *	sched N type wf2q+ sched_mask ...
1269  *	pipe N <parameters>
1270  *
1271  * do_pipe = 2 -> flowset N config
1272  *	flowset N parameters
1273  *
1274  * do_pipe = 3 -> sched N config
1275  *	sched N parameters (default no pipe)
1276  *	optional Pipe N config ...
1277  * pipe ==>
1278  */
1279 void
ipfw_config_pipe(int ac,char ** av)1280 ipfw_config_pipe(int ac, char **av)
1281 {
1282 	int i;
1283 	u_int j;
1284 	char *end;
1285 	struct dn_id *buf, *base;
1286 	struct dn_sch *sch = NULL;
1287 	struct dn_link *p = NULL;
1288 	struct dn_fs *fs = NULL;
1289 	struct dn_profile *pf = NULL;
1290 	struct ipfw_flow_id *mask = NULL;
1291 #ifdef NEW_AQM
1292 	struct dn_extra_parms *aqm_extra = NULL;
1293 	struct dn_extra_parms *sch_extra = NULL;
1294 	int lmax_extra;
1295 #endif
1296 
1297 	int lmax;
1298 	uint32_t _foo = 0, *flags = &_foo , *buckets = &_foo;
1299 
1300 	/*
1301 	 * allocate space for 1 header,
1302 	 * 1 scheduler, 1 link, 1 flowset, 1 profile
1303 	 */
1304 	lmax = sizeof(struct dn_id);	/* command header */
1305 	lmax += sizeof(struct dn_sch) + sizeof(struct dn_link) +
1306 		sizeof(struct dn_fs) + sizeof(struct dn_profile);
1307 
1308 #ifdef NEW_AQM
1309 	/* Extra Params */
1310 	lmax_extra = sizeof(struct dn_extra_parms);
1311 	/* two lmax_extra because one for AQM params and another
1312 	 * sch params
1313 	 */
1314 	lmax += lmax_extra*2;
1315 #endif
1316 
1317 	av++; ac--;
1318 	/* Pipe number */
1319 	if (ac && isdigit(**av)) {
1320 		i = atoi(*av); av++; ac--;
1321 	} else
1322 		i = -1;
1323 	if (i <= 0)
1324 		errx(EX_USAGE, "need a pipe/flowset/sched number");
1325 	base = buf = safe_calloc(1, lmax);
1326 	/* all commands start with a 'CONFIGURE' and a version */
1327 	o_next(&buf, sizeof(struct dn_id), DN_CMD_CONFIG);
1328 	base->id = DN_API_VERSION;
1329 
1330 	switch (g_co.do_pipe) {
1331 	case 1: /* "pipe N config ..." */
1332 		/* Allocate space for the WF2Q+ scheduler, its link
1333 		 * and the FIFO flowset. Set the number, but leave
1334 		 * the scheduler subtype and other parameters to 0
1335 		 * so the kernel will use appropriate defaults.
1336 		 * XXX todo: add a flag to record if a parameter
1337 		 * is actually configured.
1338 		 * If we do a 'pipe config' mask -> sched_mask.
1339 		 * The FIFO scheduler and link are derived from the
1340 		 * WF2Q+ one in the kernel.
1341 		 */
1342 #ifdef NEW_AQM
1343 		sch_extra = o_next(&buf, lmax_extra, DN_TEXT);
1344 		sch_extra ->oid.subtype = 0; /* don't configure scheduler */
1345 #endif
1346 		sch = o_next(&buf, sizeof(*sch), DN_SCH);
1347 		p = o_next(&buf, sizeof(*p), DN_LINK);
1348 #ifdef NEW_AQM
1349 		aqm_extra = o_next(&buf, lmax_extra, DN_TEXT);
1350 		aqm_extra ->oid.subtype = 0; /* don't configure AQM */
1351 #endif
1352 		fs = o_next(&buf, sizeof(*fs), DN_FS);
1353 
1354 		sch->sched_nr = i;
1355 		sch->oid.subtype = 0;	/* defaults to WF2Q+ */
1356 		mask = &sch->sched_mask;
1357 		flags = &sch->flags;
1358 		buckets = &sch->buckets;
1359 		*flags |= DN_PIPE_CMD;
1360 
1361 		p->link_nr = i;
1362 
1363 		/* This flowset is only for the FIFO scheduler */
1364 		fs->fs_nr = i + 2*DN_MAX_ID;
1365 		fs->sched_nr = i + DN_MAX_ID;
1366 		break;
1367 
1368 	case 2: /* "queue N config ... " */
1369 #ifdef NEW_AQM
1370 		aqm_extra = o_next(&buf, lmax_extra, DN_TEXT);
1371 		aqm_extra ->oid.subtype = 0;
1372 #endif
1373 		fs = o_next(&buf, sizeof(*fs), DN_FS);
1374 		fs->fs_nr = i;
1375 		mask = &fs->flow_mask;
1376 		flags = &fs->flags;
1377 		buckets = &fs->buckets;
1378 		break;
1379 
1380 	case 3: /* "sched N config ..." */
1381 #ifdef NEW_AQM
1382 		sch_extra = o_next(&buf, lmax_extra, DN_TEXT);
1383 		sch_extra ->oid.subtype = 0;
1384 #endif
1385 		sch = o_next(&buf, sizeof(*sch), DN_SCH);
1386 #ifdef NEW_AQM
1387 		aqm_extra = o_next(&buf, lmax_extra, DN_TEXT);
1388 		aqm_extra ->oid.subtype = 0;
1389 #endif
1390 		fs = o_next(&buf, sizeof(*fs), DN_FS);
1391 		sch->sched_nr = i;
1392 		mask = &sch->sched_mask;
1393 		flags = &sch->flags;
1394 		buckets = &sch->buckets;
1395 		/* fs is used only with !MULTIQUEUE schedulers */
1396 		fs->fs_nr = i + DN_MAX_ID;
1397 		fs->sched_nr = i;
1398 		break;
1399 	}
1400 	/* set to -1 those fields for which we want to reuse existing
1401 	 * values from the kernel.
1402 	 * Also, *_nr and subtype = 0 mean reuse the value from the kernel.
1403 	 * XXX todo: support reuse of the mask.
1404 	 */
1405 	if (p)
1406 		p->bandwidth = -1;
1407 	for (j = 0; j < nitems(fs->par); j++)
1408 		fs->par[j] = -1;
1409 	while (ac > 0) {
1410 		double d;
1411 		int tok = match_token(dummynet_params, *av);
1412 		ac--; av++;
1413 
1414 		switch(tok) {
1415 		case TOK_NOERROR:
1416 			NEED(fs, "noerror is only for pipes");
1417 			fs->flags |= DN_NOERROR;
1418 			break;
1419 
1420 		case TOK_PLR:
1421 			NEED(fs, "plr is only for pipes");
1422 			NEED1("plr needs one or four arguments 0..1\n");
1423 			if ((end = strsep(&av[0], ","))) {
1424 				d = strtod(end, NULL);
1425 				d = (d < 0) ? 0 : (d <= 1) ? d : 1;
1426 				fs->plr[0] = (int)(d*0x7fffffff);
1427 			}
1428 			if ((end = strsep(&av[0], ","))) {
1429 				d = strtod(end, NULL);
1430 				d = (d < 0) ? 0 : (d <= 1) ? d : 1;
1431 				fs->plr[1] = (int)(d*0x7fffffff);
1432 			}
1433 			if ((end = strsep(&av[0], ","))) {
1434 				d = strtod(end, NULL);
1435 				d = (d < 0) ? 0 : (d <= 1) ? d : 1;
1436 				fs->plr[2] = (int)(d*0x7fffffff);
1437 			}
1438 			if ((end = strsep(&av[0], ","))) {
1439 				d = strtod(end, NULL);
1440 				d = (d < 0) ? 0 : (d <= 1) ? d : 1;
1441 				fs->plr[3] = (int)(d*0x7fffffff);
1442 			}
1443 			ac--; av++;
1444 			break;
1445 
1446 		case TOK_QUEUE:
1447 			NEED(fs, "queue is only for pipes or flowsets");
1448 			NEED1("queue needs queue size\n");
1449 			end = NULL;
1450 			fs->qsize = strtoul(av[0], &end, 0);
1451 			if (*end == 'K' || *end == 'k') {
1452 				fs->flags |= DN_QSIZE_BYTES;
1453 				fs->qsize *= 1024;
1454 			} else if (*end == 'B' ||
1455 			    _substrcmp2(end, "by", "bytes") == 0) {
1456 				fs->flags |= DN_QSIZE_BYTES;
1457 			}
1458 			ac--; av++;
1459 			break;
1460 
1461 		case TOK_BUCKETS:
1462 			NEED(fs, "buckets is only for pipes or flowsets");
1463 			NEED1("buckets needs argument\n");
1464 			*buckets = strtoul(av[0], NULL, 0);
1465 			ac--; av++;
1466 			break;
1467 
1468 		case TOK_FLOW_MASK:
1469 		case TOK_SCHED_MASK:
1470 		case TOK_MASK:
1471 			NEED(mask, "tok_mask");
1472 			NEED1("mask needs mask specifier\n");
1473 			/*
1474 			 * per-flow queue, mask is dst_ip, dst_port,
1475 			 * src_ip, src_port, proto measured in bits
1476 			 */
1477 
1478 			bzero(mask, sizeof(*mask));
1479 			end = NULL;
1480 
1481 			while (ac >= 1) {
1482 			    uint32_t *p32 = NULL;
1483 			    uint16_t *p16 = NULL;
1484 			    uint32_t *p20 = NULL;
1485 			    struct in6_addr *pa6 = NULL;
1486 			    uint32_t a;
1487 
1488 			    tok = match_token(dummynet_params, *av);
1489 			    ac--; av++;
1490 			    switch(tok) {
1491 			    case TOK_ALL:
1492 				    /*
1493 				     * special case, all bits significant
1494 				     * except 'extra' (the queue number)
1495 				     */
1496 				    mask->dst_ip = ~0;
1497 				    mask->src_ip = ~0;
1498 				    mask->dst_port = ~0;
1499 				    mask->src_port = ~0;
1500 				    mask->proto = ~0;
1501 				    n2mask(&mask->dst_ip6, 128);
1502 				    n2mask(&mask->src_ip6, 128);
1503 				    mask->flow_id6 = ~0;
1504 				    *flags |= DN_HAVE_MASK;
1505 				    goto end_mask;
1506 
1507 			    case TOK_QUEUE:
1508 				    mask->extra = ~0;
1509 				    *flags |= DN_HAVE_MASK;
1510 				    goto end_mask;
1511 
1512 			    case TOK_DSTIP:
1513 				    mask->addr_type = 4;
1514 				    p32 = &mask->dst_ip;
1515 				    break;
1516 
1517 			    case TOK_SRCIP:
1518 				    mask->addr_type = 4;
1519 				    p32 = &mask->src_ip;
1520 				    break;
1521 
1522 			    case TOK_DSTIP6:
1523 				    mask->addr_type = 6;
1524 				    pa6 = &mask->dst_ip6;
1525 				    break;
1526 
1527 			    case TOK_SRCIP6:
1528 				    mask->addr_type = 6;
1529 				    pa6 = &mask->src_ip6;
1530 				    break;
1531 
1532 			    case TOK_FLOWID:
1533 				    mask->addr_type = 6;
1534 				    p20 = &mask->flow_id6;
1535 				    break;
1536 
1537 			    case TOK_DSTPORT:
1538 				    p16 = &mask->dst_port;
1539 				    break;
1540 
1541 			    case TOK_SRCPORT:
1542 				    p16 = &mask->src_port;
1543 				    break;
1544 
1545 			    case TOK_PROTO:
1546 				    break;
1547 
1548 			    default:
1549 				    ac++; av--; /* backtrack */
1550 				    goto end_mask;
1551 			    }
1552 			    if (ac < 1)
1553 				    errx(EX_USAGE, "mask: value missing");
1554 			    if (*av[0] == '/') {
1555 				    a = strtoul(av[0]+1, &end, 0);
1556 				    if (pa6 == NULL)
1557 					    a = (a == 32) ? ~0 : (1 << a) - 1;
1558 			    } else
1559 				    a = strtoul(av[0], &end, 0);
1560 			    if (p32 != NULL)
1561 				    *p32 = a;
1562 			    else if (p16 != NULL) {
1563 				    if (a > 0xFFFF)
1564 					    errx(EX_DATAERR,
1565 						"port mask must be 16 bit");
1566 				    *p16 = (uint16_t)a;
1567 			    } else if (p20 != NULL) {
1568 				    if (a > 0xfffff)
1569 					errx(EX_DATAERR,
1570 					    "flow_id mask must be 20 bit");
1571 				    *p20 = (uint32_t)a;
1572 			    } else if (pa6 != NULL) {
1573 				    if (a > 128)
1574 					errx(EX_DATAERR,
1575 					    "in6addr invalid mask len");
1576 				    else
1577 					n2mask(pa6, a);
1578 			    } else {
1579 				    if (a > 0xFF)
1580 					    errx(EX_DATAERR,
1581 						"proto mask must be 8 bit");
1582 				    mask->proto = (uint8_t)a;
1583 			    }
1584 			    if (a != 0)
1585 				    *flags |= DN_HAVE_MASK;
1586 			    ac--; av++;
1587 			} /* end while, config masks */
1588 end_mask:
1589 			break;
1590 #ifdef NEW_AQM
1591 		case TOK_CODEL:
1592 		case TOK_PIE:
1593 			NEED(fs, "codel/pie is only for flowsets");
1594 
1595 			fs->flags &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1596 			fs->flags |= DN_IS_AQM;
1597 
1598 			strlcpy(aqm_extra->name, av[-1],
1599 			    sizeof(aqm_extra->name));
1600 			aqm_extra->oid.subtype = DN_AQM_PARAMS;
1601 
1602 			process_extra_parms(&ac, av, aqm_extra, tok);
1603 			break;
1604 
1605 		case TOK_FQ_CODEL:
1606 		case TOK_FQ_PIE:
1607 			if (!strcmp(av[-1],"type"))
1608 				errx(EX_DATAERR, "use type before fq_codel/fq_pie");
1609 
1610 			NEED(sch, "fq_codel/fq_pie is only for schd");
1611 			strlcpy(sch_extra->name, av[-1],
1612 			    sizeof(sch_extra->name));
1613 			sch_extra->oid.subtype = DN_SCH_PARAMS;
1614 			process_extra_parms(&ac, av, sch_extra, tok);
1615 			break;
1616 #endif
1617 		case TOK_RED:
1618 		case TOK_GRED:
1619 			NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
1620 			fs->flags |= DN_IS_RED;
1621 			if (tok == TOK_GRED)
1622 				fs->flags |= DN_IS_GENTLE_RED;
1623 			/*
1624 			 * the format for parameters is w_q/min_th/max_th/max_p
1625 			 */
1626 			if ((end = strsep(&av[0], "/"))) {
1627 			    double w_q = strtod(end, NULL);
1628 			    if (w_q > 1 || w_q <= 0)
1629 				errx(EX_DATAERR, "0 < w_q <= 1");
1630 			    fs->w_q = (int) (w_q * (1 << SCALE_RED));
1631 			}
1632 			if ((end = strsep(&av[0], "/"))) {
1633 			    fs->min_th = strtoul(end, &end, 0);
1634 			    if (*end == 'K' || *end == 'k')
1635 				fs->min_th *= 1024;
1636 			}
1637 			if ((end = strsep(&av[0], "/"))) {
1638 			    fs->max_th = strtoul(end, &end, 0);
1639 			    if (*end == 'K' || *end == 'k')
1640 				fs->max_th *= 1024;
1641 			}
1642 			if ((end = strsep(&av[0], "/"))) {
1643 			    double max_p = strtod(end, NULL);
1644 			    if (max_p > 1 || max_p < 0)
1645 				errx(EX_DATAERR, "0 <= max_p <= 1");
1646 			    fs->max_p = (int)(max_p * (1 << SCALE_RED));
1647 			}
1648 			ac--; av++;
1649 			break;
1650 
1651 		case TOK_ECN:
1652 			fs->flags |= DN_IS_ECN;
1653 			break;
1654 
1655 		case TOK_DROPTAIL:
1656 			NEED(fs, "droptail is only for flowsets");
1657 			fs->flags &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1658 			break;
1659 
1660 		case TOK_BW:
1661 			NEED(p, "bw is only for links");
1662 			NEED1("bw needs bandwidth or interface\n");
1663 			read_bandwidth(av[0], &p->bandwidth, NULL, 0);
1664 			ac--; av++;
1665 			break;
1666 
1667 		case TOK_DELAY:
1668 			NEED(p, "delay is only for links");
1669 			NEED1("delay needs argument 0..10000ms\n");
1670 			p->delay = strtoul(av[0], NULL, 0);
1671 			ac--; av++;
1672 			break;
1673 
1674 		case TOK_TYPE: {
1675 			int l;
1676 			NEED(sch, "type is only for schedulers");
1677 			NEED1("type needs a string");
1678 			l = strlen(av[0]);
1679 			if (l == 0 || l > 15)
1680 				errx(1, "type %s too long\n", av[0]);
1681 			strlcpy(sch->name, av[0], sizeof(sch->name));
1682 			sch->oid.subtype = 0; /* use string */
1683 #ifdef NEW_AQM
1684 			/* if fq_codel is selected, consider all tokens after it
1685 			 * as parameters
1686 			 */
1687 			if (!strcasecmp(av[0],"fq_codel") || !strcasecmp(av[0],"fq_pie")){
1688 				strlcpy(sch_extra->name, av[0],
1689 				    sizeof(sch_extra->name));
1690 				sch_extra->oid.subtype = DN_SCH_PARAMS;
1691 				process_extra_parms(&ac, av, sch_extra, tok);
1692 			} else {
1693 				ac--;av++;
1694 			}
1695 #else
1696 			ac--;av++;
1697 #endif
1698 			break;
1699 		    }
1700 
1701 		case TOK_WEIGHT:
1702 			NEED(fs, "weight is only for flowsets");
1703 			NEED1("weight needs argument\n");
1704 			fs->par[0] = strtol(av[0], &end, 0);
1705 			ac--; av++;
1706 			break;
1707 
1708 		case TOK_LMAX:
1709 			NEED(fs, "lmax is only for flowsets");
1710 			NEED1("lmax needs argument\n");
1711 			fs->par[1] = strtol(av[0], &end, 0);
1712 			ac--; av++;
1713 			break;
1714 
1715 		case TOK_PRI:
1716 			NEED(fs, "priority is only for flowsets");
1717 			NEED1("priority needs argument\n");
1718 			fs->par[2] = strtol(av[0], &end, 0);
1719 			ac--; av++;
1720 			break;
1721 
1722 		case TOK_SCHED:
1723 		case TOK_PIPE:
1724 			NEED(fs, "pipe/sched");
1725 			NEED1("pipe/link/sched needs number\n");
1726 			fs->sched_nr = strtoul(av[0], &end, 0);
1727 			ac--; av++;
1728 			break;
1729 
1730 		case TOK_PROFILE:
1731 			NEED((!pf), "profile already set");
1732 			NEED(p, "profile");
1733 		    {
1734 			NEED1("extra delay needs the file name\n");
1735 			pf = o_next(&buf, sizeof(*pf), DN_PROFILE);
1736 			load_extra_delays(av[0], pf, p); //XXX can't fail?
1737 			--ac; ++av;
1738 		    }
1739 			break;
1740 
1741 		case TOK_BURST:
1742 			NEED(p, "burst");
1743 			NEED1("burst needs argument\n");
1744 			errno = 0;
1745 			if (expand_number(av[0], &p->burst) < 0)
1746 				if (errno != ERANGE)
1747 					errx(EX_DATAERR,
1748 					    "burst: invalid argument");
1749 			if (errno || p->burst > (1ULL << 48) - 1)
1750 				errx(EX_DATAERR,
1751 				    "burst: out of range (0..2^48-1)");
1752 			ac--; av++;
1753 			break;
1754 
1755 		default:
1756 			errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
1757 		}
1758 	}
1759 
1760 	/* check validity of parameters */
1761 	if (p) {
1762 		if (p->delay > 10000)
1763 			errx(EX_DATAERR, "delay must be < 10000");
1764 		if (p->bandwidth == (uint32_t)-1)
1765 			p->bandwidth = 0;
1766 	}
1767 	if (fs) {
1768 		/* XXX accept a 0 scheduler to keep the default */
1769 	    if (fs->flags & DN_QSIZE_BYTES) {
1770 		size_t len;
1771 		long limit;
1772 
1773 		len = sizeof(limit);
1774 		if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
1775 			&limit, &len, NULL, 0) == -1)
1776 			limit = 1024*1024;
1777 		if (fs->qsize > limit)
1778 			errx(EX_DATAERR, "queue size must be < %ldB", limit);
1779 	    } else {
1780 		size_t len;
1781 		long limit;
1782 
1783 		len = sizeof(limit);
1784 		if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
1785 			&limit, &len, NULL, 0) == -1)
1786 			limit = 100;
1787 		if (fs->qsize > limit)
1788 			errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
1789 	    }
1790 
1791 #ifdef NEW_AQM
1792 		if ((fs->flags & DN_IS_ECN) && !((fs->flags & DN_IS_RED)||
1793 			(fs->flags & DN_IS_AQM)))
1794 			errx(EX_USAGE, "ECN can be used with red/gred/"
1795 				"codel/fq_codel only!");
1796 #else
1797 	    if ((fs->flags & DN_IS_ECN) && !(fs->flags & DN_IS_RED))
1798 		errx(EX_USAGE, "enable red/gred for ECN");
1799 
1800 #endif
1801 
1802 	    if (fs->flags & DN_IS_RED) {
1803 		size_t len;
1804 		int lookup_depth, avg_pkt_size;
1805 
1806 		if (!(fs->flags & DN_IS_ECN) && (fs->min_th >= fs->max_th))
1807 		    errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1808 			fs->min_th, fs->max_th);
1809 		else if ((fs->flags & DN_IS_ECN) && (fs->min_th > fs->max_th))
1810 		    errx(EX_DATAERR, "min_th %d must be =< than max_th %d",
1811 			fs->min_th, fs->max_th);
1812 
1813 		if (fs->max_th == 0)
1814 		    errx(EX_DATAERR, "max_th must be > 0");
1815 
1816 		len = sizeof(int);
1817 		if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1818 			&lookup_depth, &len, NULL, 0) == -1)
1819 			lookup_depth = 256;
1820 		if (lookup_depth == 0)
1821 		    errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
1822 			" must be greater than zero");
1823 
1824 		len = sizeof(int);
1825 		if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
1826 			&avg_pkt_size, &len, NULL, 0) == -1)
1827 			avg_pkt_size = 512;
1828 
1829 		if (avg_pkt_size == 0)
1830 			errx(EX_DATAERR,
1831 			    "net.inet.ip.dummynet.red_avg_pkt_size must"
1832 			    " be greater than zero");
1833 
1834 #if 0 /* the following computation is now done in the kernel */
1835 		/*
1836 		 * Ticks needed for sending a medium-sized packet.
1837 		 * Unfortunately, when we are configuring a WF2Q+ queue, we
1838 		 * do not have bandwidth information, because that is stored
1839 		 * in the parent pipe, and also we have multiple queues
1840 		 * competing for it. So we set s=0, which is not very
1841 		 * correct. But on the other hand, why do we want RED with
1842 		 * WF2Q+ ?
1843 		 */
1844 		if (p.bandwidth==0) /* this is a WF2Q+ queue */
1845 			s = 0;
1846 		else
1847 			s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
1848 		/*
1849 		 * max idle time (in ticks) before avg queue size becomes 0.
1850 		 * NOTA:  (3/w_q) is approx the value x so that
1851 		 * (1-w_q)^x < 10^-3.
1852 		 */
1853 		w_q = ((double)fs->w_q) / (1 << SCALE_RED);
1854 		idle = s * 3. / w_q;
1855 		fs->lookup_step = (int)idle / lookup_depth;
1856 		if (!fs->lookup_step)
1857 			fs->lookup_step = 1;
1858 		weight = 1 - w_q;
1859 		for (t = fs->lookup_step; t > 1; --t)
1860 			weight *= 1 - w_q;
1861 		fs->lookup_weight = (int)(weight * (1 << SCALE_RED));
1862 #endif /* code moved in the kernel */
1863 	    }
1864 	}
1865 
1866 	i = do_cmd(IP_DUMMYNET3, base, (char *)buf - (char *)base);
1867 
1868 	if (i)
1869 		err(1, "setsockopt(%s)", "IP_DUMMYNET3");
1870 }
1871 
1872 void
dummynet_flush(void)1873 dummynet_flush(void)
1874 {
1875 	struct dn_id oid;
1876 	oid_fill(&oid, sizeof(oid), DN_CMD_FLUSH, DN_API_VERSION);
1877 	do_cmd(IP_DUMMYNET3, &oid, oid.len);
1878 }
1879 
1880 /* Parse input for 'ipfw [pipe|sched|queue] show [range list]'
1881  * Returns the number of ranges, and possibly stores them
1882  * in the array v of size len.
1883  */
1884 static int
parse_range(int ac,char * av[],uint32_t * v,int len)1885 parse_range(int ac, char *av[], uint32_t *v, int len)
1886 {
1887 	int n = 0;
1888 	char *endptr, *s;
1889 	uint32_t base[2];
1890 
1891 	if (v == NULL || len < 2) {
1892 		v = base;
1893 		len = 2;
1894 	}
1895 
1896 	for (s = *av; s != NULL; av++, ac--) {
1897 		v[0] = strtoul(s, &endptr, 10);
1898 		v[1] = (*endptr != '-') ? v[0] :
1899 			 strtoul(endptr+1, &endptr, 10);
1900 		if (*endptr == '\0') { /* prepare for next round */
1901 			s = (ac > 0) ? *(av+1) : NULL;
1902 		} else {
1903 			if (*endptr != ',') {
1904 				warn("invalid number: %s", s);
1905 				s = ++endptr;
1906 				continue;
1907 			}
1908 			/* continue processing from here */
1909 			s = ++endptr;
1910 			ac++;
1911 			av--;
1912 		}
1913 		if (v[1] < v[0] ||
1914 			v[0] >= DN_MAX_ID-1 ||
1915 			v[1] >= DN_MAX_ID-1) {
1916 			continue; /* invalid entry */
1917 		}
1918 		n++;
1919 		/* translate if 'pipe list' */
1920 		if (g_co.do_pipe == 1) {
1921 			v[0] += DN_MAX_ID;
1922 			v[1] += DN_MAX_ID;
1923 		}
1924 		v = (n*2 < len) ? v + 2 : base;
1925 	}
1926 	return n;
1927 }
1928 
1929 /* main entry point for dummynet list functions. co.do_pipe indicates
1930  * which function we want to support.
1931  * av may contain filtering arguments, either individual entries
1932  * or ranges, or lists (space or commas are valid separators).
1933  * Format for a range can be n1-n2 or n3 n4 n5 ...
1934  * In a range n1 must be <= n2, otherwise the range is ignored.
1935  * A number 'n4' is translate in a range 'n4-n4'
1936  * All number must be > 0 and < DN_MAX_ID-1
1937  */
1938 void
dummynet_list(int ac,char * av[],int show_counters)1939 dummynet_list(int ac, char *av[], int show_counters)
1940 {
1941 	struct dn_id *oid, *x = NULL;
1942 	int ret, i;
1943 	int n; 		/* # of ranges */
1944 	u_int buflen, l;
1945 	u_int max_size;	/* largest obj passed up */
1946 
1947 	(void)show_counters;	// XXX unused, but we should use it.
1948 	ac--;
1949 	av++; 		/* skip 'list' | 'show' word */
1950 
1951 	n = parse_range(ac, av, NULL, 0);	/* Count # of ranges. */
1952 
1953 	/* Allocate space to store ranges */
1954 	l = sizeof(*oid) + sizeof(uint32_t) * n * 2;
1955 	oid = safe_calloc(1, l);
1956 	oid_fill(oid, l, DN_CMD_GET, DN_API_VERSION);
1957 
1958 	if (n > 0)	/* store ranges in idx */
1959 		parse_range(ac, av, (uint32_t *)(oid + 1), n*2);
1960 	/*
1961 	 * Compute the size of the largest object returned. If the
1962 	 * response leaves at least this much spare space in the
1963 	 * buffer, then surely the response is complete; otherwise
1964 	 * there might be a risk of truncation and we will need to
1965 	 * retry with a larger buffer.
1966 	 * XXX don't bother with smaller structs.
1967 	 */
1968 	max_size = sizeof(struct dn_fs);
1969 	if (max_size < sizeof(struct dn_sch))
1970 		max_size = sizeof(struct dn_sch);
1971 	if (max_size < sizeof(struct dn_flow))
1972 		max_size = sizeof(struct dn_flow);
1973 
1974 	switch (g_co.do_pipe) {
1975 	case 1:
1976 		oid->subtype = DN_LINK;	/* list pipe */
1977 		break;
1978 	case 2:
1979 		oid->subtype = DN_FS;	/* list queue */
1980 		break;
1981 	case 3:
1982 		oid->subtype = DN_SCH;	/* list sched */
1983 		break;
1984 	}
1985 
1986 	/*
1987 	 * Ask the kernel an estimate of the required space (result
1988 	 * in oid.id), unless we are requesting a subset of objects,
1989 	 * in which case the kernel does not give an exact answer.
1990 	 * In any case, space might grow in the meantime due to the
1991 	 * creation of new queues, so we must be prepared to retry.
1992 	 */
1993 	if (n > 0) {
1994 		buflen = 4*1024;
1995 	} else {
1996 		ret = do_cmd(-IP_DUMMYNET3, oid, (uintptr_t)&l);
1997 		if (ret != 0 || oid->id <= sizeof(*oid))
1998 			goto done;
1999 		buflen = oid->id + max_size;
2000 		oid->len = sizeof(*oid); /* restore */
2001 	}
2002 	/* Try a few times, until the buffer fits */
2003 	for (i = 0; i < 20; i++) {
2004 		l = buflen;
2005 		x = safe_realloc(x, l);
2006 		bcopy(oid, x, oid->len);
2007 		ret = do_cmd(-IP_DUMMYNET3, x, (uintptr_t)&l);
2008 		if (ret != 0 || x->id <= sizeof(*oid))
2009 			goto done; /* no response */
2010 		if (l + max_size <= buflen)
2011 			break; /* ok */
2012 		buflen *= 2;	 /* double for next attempt */
2013 	}
2014 	list_pipes(x, O_NEXT(x, l));
2015 done:
2016 	if (x)
2017 		free(x);
2018 	free(oid);
2019 }
2020