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