Sync with the new ipfw3 version.
[ipfw.git] / ipfw / dummynet.c
1 /*
2  * Copyright (c) 2002-2003,2010 Luigi Rizzo
3  *
4  * Redistribution and use in source forms, with and without modification,
5  * are permitted provided that this entire comment appears intact.
6  *
7  * Redistribution in binary form may occur without any restrictions.
8  * Obviously, it would be nice if you gave credit where credit is due
9  * but requiring it would be too onerous.
10  *
11  * This software is provided ``AS IS'' without any warranties of any kind.
12  *
13  * $FreeBSD: user/luigi/ipfw3-head/sbin/ipfw/dummynet.c 203321 2010-01-31 21:39:25Z luigi $
14  *
15  * dummynet support
16  */
17
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 /* XXX there are several sysctl leftover here */
21 #include <sys/sysctl.h>
22
23 #include "ipfw2.h"
24
25 #include <ctype.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <libutil.h>
29 #include <netdb.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sysexits.h>
34
35 #include <net/if.h>
36 #include <netinet/in.h>
37 #include <netinet/ip_fw.h>
38 #include <netinet/ip_dummynet.h>
39 #include <arpa/inet.h>  /* inet_ntoa */
40
41
42 static struct _s_x dummynet_params[] = {
43         { "plr",                TOK_PLR },
44         { "noerror",            TOK_NOERROR },
45         { "buckets",            TOK_BUCKETS },
46         { "dst-ip",             TOK_DSTIP },
47         { "src-ip",             TOK_SRCIP },
48         { "dst-port",           TOK_DSTPORT },
49         { "src-port",           TOK_SRCPORT },
50         { "proto",              TOK_PROTO },
51         { "weight",             TOK_WEIGHT },
52         { "lmax",               TOK_LMAX },
53         { "maxlen",             TOK_LMAX },
54         { "all",                TOK_ALL },
55         { "mask",               TOK_MASK }, /* alias for both */
56         { "sched_mask",         TOK_SCHED_MASK },
57         { "flow_mask",          TOK_FLOW_MASK },
58         { "droptail",           TOK_DROPTAIL },
59         { "red",                TOK_RED },
60         { "gred",               TOK_GRED },
61         { "bw",                 TOK_BW },
62         { "bandwidth",          TOK_BW },
63         { "delay",              TOK_DELAY },
64         { "link",               TOK_LINK },
65         { "pipe",               TOK_PIPE },
66         { "queue",              TOK_QUEUE },
67         { "flowset",            TOK_FLOWSET },
68         { "sched",              TOK_SCHED },
69         { "pri",                TOK_PRI },
70         { "priority",           TOK_PRI },
71         { "type",               TOK_TYPE },
72         { "flow-id",            TOK_FLOWID},
73         { "dst-ipv6",           TOK_DSTIP6},
74         { "dst-ip6",            TOK_DSTIP6},
75         { "src-ipv6",           TOK_SRCIP6},
76         { "src-ip6",            TOK_SRCIP6},
77         { "profile",            TOK_PROFILE},
78         { "burst",              TOK_BURST},
79         { "dummynet-params",    TOK_NULL },
80         { NULL, 0 }     /* terminator */
81 };
82
83 #define O_NEXT(p, len) ((void *)((char *)p + len))
84
85 static void
86 oid_fill(struct dn_id *oid, int len, int type, uintptr_t id)
87 {
88         oid->len = len;
89         oid->type = type;
90         oid->subtype = 0;
91         oid->id = id;
92 }
93
94 /* make room in the buffer and move the pointer forward */
95 static void *
96 o_next(struct dn_id **o, int len, int type)
97 {
98         struct dn_id *ret = *o;
99         oid_fill(ret, len, type, 0);
100         *o = O_NEXT(*o, len);
101         return ret;
102 }
103
104 #if 0
105 static int
106 sort_q(void *arg, const void *pa, const void *pb)
107 {
108         int rev = (co.do_sort < 0);
109         int field = rev ? -co.do_sort : co.do_sort;
110         long long res = 0;
111         const struct dn_flow_queue *a = pa;
112         const struct dn_flow_queue *b = pb;
113
114         switch (field) {
115         case 1: /* pkts */
116                 res = a->len - b->len;
117                 break;
118         case 2: /* bytes */
119                 res = a->len_bytes - b->len_bytes;
120                 break;
121
122         case 3: /* tot pkts */
123                 res = a->tot_pkts - b->tot_pkts;
124                 break;
125
126         case 4: /* tot bytes */
127                 res = a->tot_bytes - b->tot_bytes;
128                 break;
129         }
130         if (res < 0)
131                 res = -1;
132         if (res > 0)
133                 res = 1;
134         return (int)(rev ? res : -res);
135 }
136 #endif
137
138 /* print a mask and header for the subsequent list of flows */
139 static void
140 print_mask(struct ipfw_flow_id *id)
141 {
142         if (!IS_IP6_FLOW_ID(id)) {
143                 printf("    "
144                     "mask: %s 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
145                     id->extra ? "queue," : "",
146                     id->proto,
147                     id->src_ip, id->src_port,
148                     id->dst_ip, id->dst_port);
149
150                 printf("BKT Prot ___Source IP/port____ "
151                     "____Dest. IP/port____ "
152                     "Tot_pkt/bytes Pkt/Byte Drp\n");
153         } else {
154                 char buf[255];
155                 printf("\n        mask: %sproto: 0x%02x, flow_id: 0x%08x,  ",
156                     id->extra ? "queue," : "",
157                     id->proto, id->flow_id6);
158                 inet_ntop(AF_INET6, &(id->src_ip6), buf, sizeof(buf));
159                 printf("%s/0x%04x -> ", buf, id->src_port);
160                 inet_ntop(AF_INET6, &(id->dst_ip6), buf, sizeof(buf));
161                 printf("%s/0x%04x\n", buf, id->dst_port);
162
163                 printf("BKT ___Prot___ _flow-id_ "
164                     "______________Source IPv6/port_______________ "
165                     "_______________Dest. IPv6/port_______________ "
166                     "Tot_pkt/bytes Pkt/Byte Drp\n");
167         }
168 }
169
170 static void
171 list_flow(struct dn_flow *ni)
172 {
173         char buff[255];
174         struct protoent *pe = NULL;
175         struct in_addr ina;
176         struct ipfw_flow_id *id = &ni->fid;
177
178         pe = getprotobynumber(id->proto);
179                 /* XXX: Should check for IPv4 flows */
180         printf("%3u%c", (ni->oid.id) & 0xff,
181                 id->extra ? '*' : ' ');
182         if (!IS_IP6_FLOW_ID(id)) {
183                 if (pe)
184                         printf("%-4s ", pe->p_name);
185                 else
186                         printf("%4u ", id->proto);
187                 ina.s_addr = htonl(id->src_ip);
188                 printf("%15s/%-5d ",
189                     inet_ntoa(ina), id->src_port);
190                 ina.s_addr = htonl(id->dst_ip);
191                 printf("%15s/%-5d ",
192                     inet_ntoa(ina), id->dst_port);
193         } else {
194                 /* Print IPv6 flows */
195                 if (pe != NULL)
196                         printf("%9s ", pe->p_name);
197                 else
198                         printf("%9u ", id->proto);
199                 printf("%7d  %39s/%-5d ", id->flow_id6,
200                     inet_ntop(AF_INET6, &(id->src_ip6), buff, sizeof(buff)),
201                     id->src_port);
202                 printf(" %39s/%-5d ",
203                     inet_ntop(AF_INET6, &(id->dst_ip6), buff, sizeof(buff)),
204                     id->dst_port);
205         }
206
207         /* Tcc relies on msvcrt.dll for printf, and
208          * it does not support ANSI %llu syntax
209          */
210 #ifndef TCC
211         printf("%4llu %8llu %2u %4u %3u\n",
212             align_uint64(&ni->tot_pkts),
213             align_uint64(&ni->tot_bytes),
214             ni->length, ni->len_bytes, ni->drops);
215 #else
216         /* XXX This should be printed correctly, but for some
217          * weird reason, it is not. Making a printf for each
218          * value is a workaround, until we don't undestand what's wrong
219          */
220         /*printf("%4I64u %8I64u %2u %4u %3u\n",
221             align_uint64(&ni->tot_pkts),
222             align_uint64(&ni->tot_bytes),
223             ni->length, ni->len_bytes, ni->drops);*/
224         
225         printf("%4I64u ",align_uint64(&ni->tot_pkts));
226         printf("%8I64u ",align_uint64(&ni->tot_bytes));
227         printf("%2u ",ni->length);
228         printf("%4u ",ni->len_bytes);
229         printf("%3u\n",ni->drops);
230 #endif
231 }
232
233 static void
234 print_flowset_parms(struct dn_fs *fs, char *prefix)
235 {
236         int l;
237         char qs[30];
238         char plr[30];
239         char red[90];   /* Display RED parameters */
240
241         l = fs->qsize;
242         if (fs->flags & DN_QSIZE_BYTES) {
243                 if (l >= 8192)
244                         sprintf(qs, "%d KB", l / 1024);
245                 else
246                         sprintf(qs, "%d B", l);
247         } else
248                 sprintf(qs, "%3d sl.", l);
249         if (fs->plr)
250                 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
251         else
252                 plr[0] = '\0';
253
254         if (fs->flags & DN_IS_RED)      /* RED parameters */
255                 sprintf(red,
256                     "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
257                     (fs->flags & DN_IS_GENTLE_RED) ? 'G' : ' ',
258                     1.0 * fs->w_q / (double)(1 << SCALE_RED),
259                     fs->min_th,
260                     fs->max_th,
261                     1.0 * fs->max_p / (double)(1 << SCALE_RED));
262         else
263                 sprintf(red, "droptail");
264
265         if (prefix[0]) {
266             printf("%s %s%s %d queues (%d buckets) %s\n",
267                 prefix, qs, plr, fs->oid.id, fs->buckets, red);
268             prefix[0] = '\0';
269         } else {
270             printf("q%05d %s%s %d flows (%d buckets) sched %d "
271                         "weight %d lmax %d pri %d %s\n",
272                 fs->fs_nr, qs, plr, fs->oid.id, fs->buckets,
273                 fs->sched_nr, fs->par[0], fs->par[1], fs->par[2], red);
274             if (fs->flags & DN_HAVE_MASK)
275                 print_mask(&fs->flow_mask);
276         }
277 }
278
279 static void
280 print_extra_delay_parms(struct dn_profile *p)
281 {
282         double loss;
283         if (p->samples_no <= 0)
284                 return;
285
286         loss = p->loss_level;
287         loss /= p->samples_no;
288         printf("\t profile: name \"%s\" loss %f samples %d\n",
289                 p->name, loss, p->samples_no);
290 }
291
292 static void
293 flush_buf(char *buf)
294 {
295         if (buf[0])
296                 printf("%s\n", buf);
297         buf[0] = '\0';
298 }
299         
300 /*
301  * generic list routine. We expect objects in a specific order, i.e.
302  * PIPES AND SCHEDULERS:
303  *      link; scheduler; internal flowset if any; instances
304  * we can tell a pipe from the number.
305  *
306  * FLOWSETS:
307  *      flowset; queues;
308  * link i (int queue); scheduler i; si(i) { flowsets() : queues }
309  */
310 static void
311 list_pipes(struct dn_id *oid, struct dn_id *end)
312 {
313     char buf[160];      /* pending buffer */
314     buf[0] = '\0';
315         
316     for (; oid != end; oid = O_NEXT(oid, oid->len)) {
317         if (oid->len < sizeof(*oid))
318                 errx(1, "invalid oid len %d\n", oid->len);
319
320         switch (oid->type) {
321         default:
322             flush_buf(buf);
323             printf("unrecognized object %d size %d\n", oid->type, oid->len);
324             break;
325         case DN_TEXT: /* list of attached flowsets */
326             {
327                 int i, l;
328                 struct {
329                         struct dn_id id;
330                         uint32_t p[0];
331                 } *d = (void *)oid;
332                 l = (oid->len - sizeof(*oid))/sizeof(d->p[0]);
333                 if (l == 0)
334                     break;
335                 printf("   Children flowsets: ");
336                 for (i = 0; i < l; i++)
337                         printf("%u ", d->p[i]);
338                 printf("\n");
339                 break;
340             }
341         case DN_CMD_GET:
342             if (co.verbose)
343                 printf("answer for cmd %d, len %d\n", oid->type, oid->id);
344             break;
345         case DN_SCH: {
346             struct dn_sch *s = (struct dn_sch *)oid;
347             flush_buf(buf);
348             printf(" sched %d type %s flags 0x%x %d buckets %d active\n",
349                         s->sched_nr,
350                         s->name, s->flags, s->buckets, s->oid.id);
351             if (s->flags & DN_HAVE_MASK)
352                         print_mask(&s->sched_mask);
353             }
354             break;
355
356         case DN_FLOW:
357             list_flow((struct dn_flow *)oid);
358             break;
359
360         case DN_LINK: {
361             struct dn_link *p = (struct dn_link *)oid;
362             double b = p->bandwidth;
363             char bwbuf[30];
364             char burst[5 + 7];
365
366             /* This starts a new object so flush buffer */
367             flush_buf(buf);
368             /* data rate */
369             if (b == 0)
370                 sprintf(bwbuf, "unlimited     ");
371             else if (b >= 1000000)
372                 sprintf(bwbuf, "%7.3f Mbit/s", b/1000000);
373             else if (b >= 1000)
374                 sprintf(bwbuf, "%7.3f Kbit/s", b/1000);
375             else
376                 sprintf(bwbuf, "%7.3f bit/s ", b);
377
378             if (humanize_number(burst, sizeof(burst), p->burst,
379                     "", HN_AUTOSCALE, 0) < 0 || co.verbose)
380                 sprintf(burst, "%d", (int)p->burst);
381             sprintf(buf, "%05d: %s %4d ms burst %s",
382                 p->link_nr % DN_MAX_ID, bwbuf, p->delay, burst);
383             }
384             break;
385
386         case DN_FS:
387             print_flowset_parms((struct dn_fs *)oid, buf);
388             break;
389         case DN_PROFILE:
390             flush_buf(buf);
391             print_extra_delay_parms((struct dn_profile *)oid);
392         }
393         flush_buf(buf); // XXX does it really go here ?
394         }
395 }
396
397 /*
398  * Delete pipe, queue or scheduler i
399  */
400 int
401 ipfw_delete_pipe(int do_pipe, int i)
402 {
403         struct {
404                 struct dn_id oid;
405                 uintptr_t a[1]; /* add more if we want a list */
406         } cmd;
407         oid_fill((void *)&cmd, sizeof(cmd), DN_CMD_DELETE, DN_API_VERSION);
408         cmd.oid.subtype = (do_pipe == 1) ? DN_LINK :
409                 ( (do_pipe == 2) ? DN_FS : DN_SCH);
410         cmd.a[0] = i;
411         i = do_cmd(IP_DUMMYNET3, &cmd, cmd.oid.len);
412         if (i) {
413                 i = 1;
414                 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", i);
415         }
416         return i;
417 }
418
419 /*
420  * Code to parse delay profiles.
421  *
422  * Some link types introduce extra delays in the transmission
423  * of a packet, e.g. because of MAC level framing, contention on
424  * the use of the channel, MAC level retransmissions and so on.
425  * From our point of view, the channel is effectively unavailable
426  * for this extra time, which is constant or variable depending
427  * on the link type. Additionally, packets may be dropped after this
428  * time (e.g. on a wireless link after too many retransmissions).
429  * We can model the additional delay with an empirical curve
430  * that represents its distribution.
431  *
432  *      cumulative probability
433  *      1.0 ^
434  *          |
435  *      L   +-- loss-level          x
436  *          |                 ******
437  *          |                *
438  *          |           *****
439  *          |          *
440  *          |        **
441  *          |       *                         
442  *          +-------*------------------->
443  *                      delay
444  *
445  * The empirical curve may have both vertical and horizontal lines.
446  * Vertical lines represent constant delay for a range of
447  * probabilities; horizontal lines correspond to a discontinuty
448  * in the delay distribution: the link will use the largest delay
449  * for a given probability.
450  * 
451  * To pass the curve to dummynet, we must store the parameters
452  * in a file as described below, and issue the command
453  *
454  *      ipfw pipe <n> config ... bw XXX profile <filename> ...
455  *
456  * The file format is the following, with whitespace acting as
457  * a separator and '#' indicating the beginning a comment:
458  *
459  *      samples N
460  *              the number of samples used in the internal
461  *              representation (2..1024; default 100);
462  *
463  *      loss-level L 
464  *              The probability above which packets are lost.
465  *               (0.0 <= L <= 1.0, default 1.0 i.e. no loss);
466  *
467  *      name identifier
468  *              Optional a name (listed by "ipfw pipe show")
469  *              to identify the distribution;
470  *
471  *      "delay prob" | "prob delay"
472  *              One of these two lines is mandatory and defines
473  *              the format of the following lines with data points.
474  *
475  *      XXX YYY
476  *              2 or more lines representing points in the curve,
477  *              with either delay or probability first, according
478  *              to the chosen format.
479  *              The unit for delay is milliseconds.
480  *
481  * Data points does not need to be ordered or equal to the number
482  * specified in the "samples" line. ipfw will sort and interpolate
483  * the curve as needed.
484  *
485  * Example of a profile file:
486  
487         name    bla_bla_bla
488         samples 100
489         loss-level    0.86
490         prob    delay
491         0       200     # minimum overhead is 200ms
492         0.5     200
493         0.5     300
494         0.8     1000
495         0.9     1300
496         1       1300
497  
498  * Internally, we will convert the curve to a fixed number of
499  * samples, and when it is time to transmit a packet we will
500  * model the extra delay as extra bits in the packet.
501  *
502  */
503
504 #define ED_MAX_LINE_LEN 256+ED_MAX_NAME_LEN
505 #define ED_TOK_SAMPLES  "samples"
506 #define ED_TOK_LOSS     "loss-level"
507 #define ED_TOK_NAME     "name"
508 #define ED_TOK_DELAY    "delay"
509 #define ED_TOK_PROB     "prob"
510 #define ED_TOK_BW       "bw"
511 #define ED_SEPARATORS   " \t\n"
512 #define ED_MIN_SAMPLES_NO       2
513
514 /*
515  * returns 1 if s is a non-negative number, with at least one '.'
516  */
517 static int
518 is_valid_number(const char *s)
519 {
520         int i, dots_found = 0;
521         int len = strlen(s);
522
523         for (i = 0; i<len; ++i)
524                 if (!isdigit(s[i]) && (s[i] !='.' || ++dots_found > 1))
525                         return 0;
526         return 1;
527 }
528
529 /*
530  * Take as input a string describing a bandwidth value
531  * and return the numeric bandwidth value.
532  * set clocking interface or bandwidth value
533  */
534 static void
535 read_bandwidth(char *arg, int *bandwidth, char *if_name, int namelen)
536 {
537         if (*bandwidth != -1)
538                 warnx("duplicate token, override bandwidth value!");
539
540         if (arg[0] >= 'a' && arg[0] <= 'z') {
541                 if (!if_name) {
542                         errx(1, "no if support");
543                 }
544                 if (namelen >= IFNAMSIZ)
545                         warn("interface name truncated");
546                 namelen--;
547                 /* interface name */
548                 strncpy(if_name, arg, namelen);
549                 if_name[namelen] = '\0';
550                 *bandwidth = 0;
551         } else {        /* read bandwidth value */
552                 int bw;
553                 char *end = NULL;
554
555                 bw = strtoul(arg, &end, 0);
556                 if (*end == 'K' || *end == 'k') {
557                         end++;
558                         bw *= 1000;
559                 } else if (*end == 'M' || *end == 'm') {
560                         end++;
561                         bw *= 1000000;
562                 }
563                 if ((*end == 'B' &&
564                         _substrcmp2(end, "Bi", "Bit/s") != 0) ||
565                     _substrcmp2(end, "by", "bytes") == 0)
566                         bw *= 8;
567
568                 if (bw < 0)
569                         errx(EX_DATAERR, "bandwidth too large");
570
571                 *bandwidth = bw;
572                 if (if_name)
573                         if_name[0] = '\0';
574         }
575 }
576
577 struct point {
578         double prob;
579         double delay;
580 };
581
582 static int
583 compare_points(const void *vp1, const void *vp2)
584 {
585         const struct point *p1 = vp1;
586         const struct point *p2 = vp2;
587         double res = 0;
588
589         res = p1->prob - p2->prob;
590         if (res == 0)
591                 res = p1->delay - p2->delay;
592         if (res < 0)
593                 return -1;
594         else if (res > 0)
595                 return 1;
596         else
597                 return 0;
598 }
599
600 #define ED_EFMT(s) EX_DATAERR,"error in %s at line %d: "#s,filename,lineno
601
602 static void
603 load_extra_delays(const char *filename, struct dn_profile *p,
604         struct dn_link *link)
605 {
606         char    line[ED_MAX_LINE_LEN];
607         FILE    *f;
608         int     lineno = 0;
609         int     i;
610
611         int     samples = -1;
612         double  loss = -1.0;
613         char    profile_name[ED_MAX_NAME_LEN];
614         int     delay_first = -1;
615         int     do_points = 0;
616         struct point    points[ED_MAX_SAMPLES_NO];
617         int     points_no = 0;
618
619         /* XXX link never NULL? */
620         p->link_nr = link->link_nr;
621
622         profile_name[0] = '\0';
623         f = fopen(filename, "r");
624         if (f == NULL)
625                 err(EX_UNAVAILABLE, "fopen: %s", filename);
626
627         while (fgets(line, ED_MAX_LINE_LEN, f)) {         /* read commands */
628                 char *s, *cur = line, *name = NULL, *arg = NULL;
629
630                 ++lineno;
631
632                 /* parse the line */
633                 while (cur) {
634                         s = strsep(&cur, ED_SEPARATORS);
635                         if (s == NULL || *s == '#')
636                                 break;
637                         if (*s == '\0')
638                                 continue;
639                         if (arg)
640                                 errx(ED_EFMT("too many arguments"));
641                         if (name == NULL)
642                                 name = s;
643                         else
644                                 arg = s;
645                 }
646                 if (name == NULL)       /* empty line */
647                         continue;
648                 if (arg == NULL)
649                         errx(ED_EFMT("missing arg for %s"), name);
650
651                 if (!strcasecmp(name, ED_TOK_SAMPLES)) {
652                     if (samples > 0)
653                         errx(ED_EFMT("duplicate ``samples'' line"));
654                     if (atoi(arg) <=0)
655                         errx(ED_EFMT("invalid number of samples"));
656                     samples = atoi(arg);
657                     if (samples>ED_MAX_SAMPLES_NO)
658                             errx(ED_EFMT("too many samples, maximum is %d"),
659                                 ED_MAX_SAMPLES_NO);
660                     do_points = 0;
661                 } else if (!strcasecmp(name, ED_TOK_BW)) {
662                     char buf[IFNAMSIZ];
663                     read_bandwidth(arg, &link->bandwidth, buf, sizeof(buf));
664                 } else if (!strcasecmp(name, ED_TOK_LOSS)) {
665                     if (loss != -1.0)
666                         errx(ED_EFMT("duplicated token: %s"), name);
667                     if (!is_valid_number(arg))
668                         errx(ED_EFMT("invalid %s"), arg);
669                     loss = atof(arg);
670                     if (loss > 1)
671                         errx(ED_EFMT("%s greater than 1.0"), name);
672                     do_points = 0;
673                 } else if (!strcasecmp(name, ED_TOK_NAME)) {
674                     if (profile_name[0] != '\0')
675                         errx(ED_EFMT("duplicated token: %s"), name);
676                     strncpy(profile_name, arg, sizeof(profile_name) - 1);
677                     profile_name[sizeof(profile_name)-1] = '\0';
678                     do_points = 0;
679                 } else if (!strcasecmp(name, ED_TOK_DELAY)) {
680                     if (do_points)
681                         errx(ED_EFMT("duplicated token: %s"), name);
682                     delay_first = 1;
683                     do_points = 1;
684                 } else if (!strcasecmp(name, ED_TOK_PROB)) {
685                     if (do_points)
686                         errx(ED_EFMT("duplicated token: %s"), name);
687                     delay_first = 0;
688                     do_points = 1;
689                 } else if (do_points) {
690                     if (!is_valid_number(name) || !is_valid_number(arg))
691                         errx(ED_EFMT("invalid point found"));
692                     if (delay_first) {
693                         points[points_no].delay = atof(name);
694                         points[points_no].prob = atof(arg);
695                     } else {
696                         points[points_no].delay = atof(arg);
697                         points[points_no].prob = atof(name);
698                     }
699                     if (points[points_no].prob > 1.0)
700                         errx(ED_EFMT("probability greater than 1.0"));
701                     ++points_no;
702                 } else {
703                     errx(ED_EFMT("unrecognised command '%s'"), name);
704                 }
705         }
706
707         fclose (f);
708
709         if (samples == -1) {
710             warnx("'%s' not found, assuming 100", ED_TOK_SAMPLES);
711             samples = 100;
712         }
713
714         if (loss == -1.0) {
715             warnx("'%s' not found, assuming no loss", ED_TOK_LOSS);
716             loss = 1;
717         }
718
719         /* make sure that there are enough points. */
720         if (points_no < ED_MIN_SAMPLES_NO)
721             errx(ED_EFMT("too few samples, need at least %d"),
722                 ED_MIN_SAMPLES_NO);
723
724         qsort(points, points_no, sizeof(struct point), compare_points);
725
726         /* interpolation */
727         for (i = 0; i<points_no-1; ++i) {
728             double y1 = points[i].prob * samples;
729             double x1 = points[i].delay;
730             double y2 = points[i+1].prob * samples;
731             double x2 = points[i+1].delay;
732
733             int ix = y1;
734             int stop = y2;
735
736             if (x1 == x2) {
737                 for (; ix<stop; ++ix)
738                     p->samples[ix] = x1;
739             } else {
740                 double m = (y2-y1)/(x2-x1);
741                 double c = y1 - m*x1;
742                 for (; ix<stop ; ++ix)
743                     p->samples[ix] = (ix - c)/m;
744             }
745         }
746         p->samples_no = samples;
747         p->loss_level = loss * samples;
748         strncpy(p->name, profile_name, sizeof(p->name));
749 }
750
751 /*
752  * configuration of pipes, schedulers, flowsets.
753  * When we configure a new scheduler, an empty pipe is created, so:
754  * 
755  * do_pipe = 1 -> "pipe N config ..." only for backward compatibility
756  *      sched N+Delta type fifo sched_mask ...
757  *      pipe N+Delta <parameters>
758  *      flowset N+Delta pipe N+Delta (no parameters)
759  *      sched N type wf2q+ sched_mask ...
760  *      pipe N <parameters>
761  *
762  * do_pipe = 2 -> flowset N config
763  *      flowset N parameters
764  *
765  * do_pipe = 3 -> sched N config
766  *      sched N parameters (default no pipe)
767  *      optional Pipe N config ...
768  * pipe ==>
769  */
770 void
771 ipfw_config_pipe(int ac, char **av)
772 {
773         int i, j;
774         char *end;
775         void *par = NULL;
776         struct dn_id *buf, *base;
777         struct dn_sch *sch = NULL;
778         struct dn_link *p = NULL;
779         struct dn_fs *fs = NULL;
780         struct dn_profile *pf = NULL;
781         struct ipfw_flow_id *mask = NULL;
782         int lmax;
783         uint32_t _foo = 0, *flags = &_foo , *buckets = &_foo;
784
785         /*
786          * allocate space for 1 header,
787          * 1 scheduler, 1 link, 1 flowset, 1 profile
788          */
789         lmax = sizeof(struct dn_id);    /* command header */
790         lmax += sizeof(struct dn_sch) + sizeof(struct dn_link) +
791                 sizeof(struct dn_fs) + sizeof(struct dn_profile);
792
793         av++; ac--;
794         /* Pipe number */
795         if (ac && isdigit(**av)) {
796                 i = atoi(*av); av++; ac--;
797         } else
798                 i = -1;
799         if (i <= 0)
800                 errx(EX_USAGE, "need a pipe/flowset/sched number");
801         base = buf = safe_calloc(1, lmax);
802         /* all commands start with a 'CONFIGURE' and a version */
803         o_next(&buf, sizeof(struct dn_id), DN_CMD_CONFIG);
804         base->id = DN_API_VERSION;
805
806         switch (co.do_pipe) {
807         case 1: /* "pipe N config ..." */
808                 /* Allocate space for the WF2Q+ scheduler, its link
809                  * and the FIFO flowset. Set the number, but leave
810                  * the scheduler subtype and other parameters to 0
811                  * so the kernel will use appropriate defaults.
812                  * XXX todo: add a flag to record if a parameter
813                  * is actually configured.
814                  * If we do a 'pipe config' mask -> sched_mask.
815                  * The FIFO scheduler and link are derived from the
816                  * WF2Q+ one in the kernel.
817                  */
818                 sch = o_next(&buf, sizeof(*sch), DN_SCH);
819                 p = o_next(&buf, sizeof(*p), DN_LINK);
820                 fs = o_next(&buf, sizeof(*fs), DN_FS);
821
822                 sch->sched_nr = i;
823                 sch->oid.subtype = 0;   /* defaults to WF2Q+ */
824                 mask = &sch->sched_mask;
825                 flags = &sch->flags;
826                 buckets = &sch->buckets;
827                 *flags |= DN_PIPE_CMD;
828
829                 p->link_nr = i;
830
831                 /* This flowset is only for the FIFO scheduler */
832                 fs->fs_nr = i + 2*DN_MAX_ID;
833                 fs->sched_nr = i + DN_MAX_ID;
834                 break;
835
836         case 2: /* "queue N config ... " */
837                 fs = o_next(&buf, sizeof(*fs), DN_FS);
838                 fs->fs_nr = i;
839                 mask = &fs->flow_mask;
840                 flags = &fs->flags;
841                 buckets = &fs->buckets;
842                 break;
843
844         case 3: /* "sched N config ..." */
845                 sch = o_next(&buf, sizeof(*sch), DN_SCH);
846                 fs = o_next(&buf, sizeof(*fs), DN_FS);
847                 sch->sched_nr = i;
848                 mask = &sch->sched_mask;
849                 flags = &sch->flags;
850                 buckets = &sch->buckets;
851                 /* fs is used only with !MULTIQUEUE schedulers */
852                 fs->fs_nr = i + DN_MAX_ID;
853                 fs->sched_nr = i;
854                 break;
855         }
856         /* set to -1 those fields for which we want to reuse existing
857          * values from the kernel.
858          * Also, *_nr and subtype = 0 mean reuse the value from the kernel.
859          * XXX todo: support reuse of the mask.
860          */
861         if (p)
862                 p->bandwidth = -1;
863         for (j = 0; j < sizeof(fs->par)/sizeof(fs->par[0]); j++)
864                 fs->par[j] = -1;
865         while (ac > 0) {
866                 double d;
867                 int tok = match_token(dummynet_params, *av);
868                 ac--; av++;
869
870                 switch(tok) {
871                 case TOK_NOERROR:
872                         NEED(fs, "noerror is only for pipes");
873                         fs->flags |= DN_NOERROR;
874                         break;
875
876                 case TOK_PLR:
877                         NEED(fs, "plr is only for pipes");
878                         NEED1("plr needs argument 0..1\n");
879                         d = strtod(av[0], NULL);
880                         if (d > 1)
881                                 d = 1;
882                         else if (d < 0)
883                                 d = 0;
884                         fs->plr = (int)(d*0x7fffffff);
885                         ac--; av++;
886                         break;
887
888                 case TOK_QUEUE:
889                         NEED(fs, "queue is only for pipes or flowsets");
890                         NEED1("queue needs queue size\n");
891                         end = NULL;
892                         fs->qsize = strtoul(av[0], &end, 0);
893                         if (*end == 'K' || *end == 'k') {
894                                 fs->flags |= DN_QSIZE_BYTES;
895                                 fs->qsize *= 1024;
896                         } else if (*end == 'B' ||
897                             _substrcmp2(end, "by", "bytes") == 0) {
898                                 fs->flags |= DN_QSIZE_BYTES;
899                         }
900                         ac--; av++;
901                         break;
902
903                 case TOK_BUCKETS:
904                         NEED(fs, "buckets is only for pipes or flowsets");
905                         NEED1("buckets needs argument\n");
906                         *buckets = strtoul(av[0], NULL, 0);
907                         ac--; av++;
908                         break;
909
910                 case TOK_FLOW_MASK:
911                 case TOK_SCHED_MASK:
912                 case TOK_MASK:
913                         NEED(mask, "tok_mask");
914                         NEED1("mask needs mask specifier\n");
915                         /*
916                          * per-flow queue, mask is dst_ip, dst_port,
917                          * src_ip, src_port, proto measured in bits
918                          */
919                         par = NULL;
920
921                         bzero(mask, sizeof(*mask));
922                         end = NULL;
923
924                         while (ac >= 1) {
925                             uint32_t *p32 = NULL;
926                             uint16_t *p16 = NULL;
927                             uint32_t *p20 = NULL;
928                             struct in6_addr *pa6 = NULL;
929                             uint32_t a;
930
931                             tok = match_token(dummynet_params, *av);
932                             ac--; av++;
933                             switch(tok) {
934                             case TOK_ALL:
935                                     /*
936                                      * special case, all bits significant
937                                      * except 'extra' (the queue number)
938                                      */
939                                     mask->dst_ip = ~0;
940                                     mask->src_ip = ~0;
941                                     mask->dst_port = ~0;
942                                     mask->src_port = ~0;
943                                     mask->proto = ~0;
944                                     n2mask(&mask->dst_ip6, 128);
945                                     n2mask(&mask->src_ip6, 128);
946                                     mask->flow_id6 = ~0;
947                                     *flags |= DN_HAVE_MASK;
948                                     goto end_mask;
949
950                             case TOK_QUEUE:
951                                     mask->extra = ~0;
952                                     *flags |= DN_HAVE_MASK;
953                                     goto end_mask;
954
955                             case TOK_DSTIP:
956                                     mask->addr_type = 4;
957                                     p32 = &mask->dst_ip;
958                                     break;
959
960                             case TOK_SRCIP:
961                                     mask->addr_type = 4;
962                                     p32 = &mask->src_ip;
963                                     break;
964
965                             case TOK_DSTIP6:
966                                     mask->addr_type = 6;
967                                     pa6 = &mask->dst_ip6;
968                                     break;
969                             
970                             case TOK_SRCIP6:
971                                     mask->addr_type = 6;
972                                     pa6 = &mask->src_ip6;
973                                     break;
974
975                             case TOK_FLOWID:
976                                     mask->addr_type = 6;
977                                     p20 = &mask->flow_id6;
978                                     break;
979
980                             case TOK_DSTPORT:
981                                     p16 = &mask->dst_port;
982                                     break;
983
984                             case TOK_SRCPORT:
985                                     p16 = &mask->src_port;
986                                     break;
987
988                             case TOK_PROTO:
989                                     break;
990
991                             default:
992                                     ac++; av--; /* backtrack */
993                                     goto end_mask;
994                             }
995                             if (ac < 1)
996                                     errx(EX_USAGE, "mask: value missing");
997                             if (*av[0] == '/') {
998                                     a = strtoul(av[0]+1, &end, 0);
999                                     if (pa6 == NULL)
1000                                             a = (a == 32) ? ~0 : (1 << a) - 1;
1001                             } else
1002                                     a = strtoul(av[0], &end, 0);
1003                             if (p32 != NULL)
1004                                     *p32 = a;
1005                             else if (p16 != NULL) {
1006                                     if (a > 0xFFFF)
1007                                             errx(EX_DATAERR,
1008                                                 "port mask must be 16 bit");
1009                                     *p16 = (uint16_t)a;
1010                             } else if (p20 != NULL) {
1011                                     if (a > 0xfffff)
1012                                         errx(EX_DATAERR,
1013                                             "flow_id mask must be 20 bit");
1014                                     *p20 = (uint32_t)a;
1015                             } else if (pa6 != NULL) {
1016                                     if (a > 128)
1017                                         errx(EX_DATAERR,
1018                                             "in6addr invalid mask len");
1019                                     else
1020                                         n2mask(pa6, a);
1021                             } else {
1022                                     if (a > 0xFF)
1023                                             errx(EX_DATAERR,
1024                                                 "proto mask must be 8 bit");
1025                                     mask->proto = (uint8_t)a;
1026                             }
1027                             if (a != 0)
1028                                     *flags |= DN_HAVE_MASK;
1029                             ac--; av++;
1030                         } /* end while, config masks */
1031 end_mask:
1032                         break;
1033
1034                 case TOK_RED:
1035                 case TOK_GRED:
1036                         NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
1037                         fs->flags |= DN_IS_RED;
1038                         if (tok == TOK_GRED)
1039                                 fs->flags |= DN_IS_GENTLE_RED;
1040                         /*
1041                          * the format for parameters is w_q/min_th/max_th/max_p
1042                          */
1043                         if ((end = strsep(&av[0], "/"))) {
1044                             double w_q = strtod(end, NULL);
1045                             if (w_q > 1 || w_q <= 0)
1046                                 errx(EX_DATAERR, "0 < w_q <= 1");
1047                             fs->w_q = (int) (w_q * (1 << SCALE_RED));
1048                         }
1049                         if ((end = strsep(&av[0], "/"))) {
1050                             fs->min_th = strtoul(end, &end, 0);
1051                             if (*end == 'K' || *end == 'k')
1052                                 fs->min_th *= 1024;
1053                         }
1054                         if ((end = strsep(&av[0], "/"))) {
1055                             fs->max_th = strtoul(end, &end, 0);
1056                             if (*end == 'K' || *end == 'k')
1057                                 fs->max_th *= 1024;
1058                         }
1059                         if ((end = strsep(&av[0], "/"))) {
1060                             double max_p = strtod(end, NULL);
1061                             if (max_p > 1 || max_p <= 0)
1062                                 errx(EX_DATAERR, "0 < max_p <= 1");
1063                             fs->max_p = (int)(max_p * (1 << SCALE_RED));
1064                         }
1065                         ac--; av++;
1066                         break;
1067
1068                 case TOK_DROPTAIL:
1069                         NEED(fs, "droptail is only for flowsets");
1070                         fs->flags &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1071                         break;
1072
1073                 case TOK_BW:
1074                         NEED(p, "bw is only for links");
1075                         NEED1("bw needs bandwidth or interface\n");
1076                         read_bandwidth(av[0], &p->bandwidth, NULL, 0);
1077                         ac--; av++;
1078                         break;
1079
1080                 case TOK_DELAY:
1081                         NEED(p, "delay is only for links");
1082                         NEED1("delay needs argument 0..10000ms\n");
1083                         p->delay = strtoul(av[0], NULL, 0);
1084                         ac--; av++;
1085                         break;
1086
1087                 case TOK_TYPE: {
1088                         int l;
1089                         NEED(sch, "type is only for schedulers");
1090                         NEED1("type needs a string");
1091                         l = strlen(av[0]);
1092                         if (l == 0 || l > 15)
1093                                 errx(1, "type %s too long\n", av[0]);
1094                         strcpy(sch->name, av[0]);
1095                         sch->oid.subtype = 0; /* use string */
1096                         ac--; av++;
1097                         break;
1098                     }
1099
1100                 case TOK_WEIGHT:
1101                         NEED(fs, "weight is only for flowsets");
1102                         NEED1("weight needs argument\n");
1103                         fs->par[0] = strtol(av[0], &end, 0);
1104                         ac--; av++;
1105                         break;
1106
1107                 case TOK_LMAX:
1108                         NEED(fs, "lmax is only for flowsets");
1109                         NEED1("lmax needs argument\n");
1110                         fs->par[1] = strtol(av[0], &end, 0);
1111                         ac--; av++;
1112                         break;
1113
1114                 case TOK_PRI:
1115                         NEED(fs, "priority is only for flowsets");
1116                         NEED1("priority needs argument\n");
1117                         fs->par[2] = strtol(av[0], &end, 0);
1118                         ac--; av++;
1119                         break;
1120
1121                 case TOK_SCHED:
1122                 case TOK_PIPE:
1123                         NEED(fs, "pipe/sched");
1124                         NEED1("pipe/link/sched needs number\n");
1125                         fs->sched_nr = strtoul(av[0], &end, 0);
1126                         ac--; av++;
1127                         break;
1128
1129                 case TOK_PROFILE:
1130                         NEED((!pf), "profile already set");
1131                         NEED(p, "profile");
1132                     {
1133                         NEED1("extra delay needs the file name\n");
1134                         pf = o_next(&buf, sizeof(*pf), DN_PROFILE);
1135                         load_extra_delays(av[0], pf, p); //XXX can't fail?
1136                         --ac; ++av;
1137                     }
1138                         break;
1139
1140                 case TOK_BURST:
1141                         NEED(p, "burst");
1142                         NEED1("burst needs argument\n");
1143                         errno = 0;
1144                         if (expand_number(av[0], (int64_t *)&p->burst) < 0)
1145                                 if (errno != ERANGE)
1146                                         errx(EX_DATAERR,
1147                                             "burst: invalid argument");
1148                         if (errno || p->burst > (1ULL << 48) - 1)
1149                                 errx(EX_DATAERR,
1150                                     "burst: out of range (0..2^48-1)");
1151                         ac--; av++;
1152                         break;
1153
1154                 default:
1155                         errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
1156                 }
1157         }
1158
1159         /* check validity of parameters */
1160         if (p) {
1161                 if (p->delay > 10000)
1162                         errx(EX_DATAERR, "delay must be < 10000");
1163                 if (p->bandwidth == -1)
1164                         p->bandwidth = 0;
1165         }
1166         if (fs) {
1167                 /* XXX accept a 0 scheduler to keep the default */
1168     if (fs->flags & DN_QSIZE_BYTES) {
1169         size_t len;
1170                 long limit;
1171
1172                 len = sizeof(limit);
1173                 if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
1174                         &limit, &len, NULL, 0) == -1)
1175                         limit = 1024*1024;
1176                 if (fs->qsize > limit)
1177                         errx(EX_DATAERR, "queue size must be < %ldB", limit);
1178             } else {
1179                 size_t len;
1180                 long limit;
1181
1182                 len = sizeof(limit);
1183                 if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
1184                         &limit, &len, NULL, 0) == -1)
1185                         limit = 100;
1186                 if (fs->qsize > limit)
1187                         errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
1188             }
1189
1190             if (fs->flags & DN_IS_RED) {
1191                 size_t len;
1192                 int lookup_depth, avg_pkt_size;
1193                 double w_q;
1194
1195                 if (fs->min_th >= fs->max_th)
1196                     errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1197                         fs->min_th, fs->max_th);
1198                 if (fs->max_th == 0)
1199                     errx(EX_DATAERR, "max_th must be > 0");
1200
1201                 len = sizeof(int);
1202                 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1203                         &lookup_depth, &len, NULL, 0) == -1)
1204                         lookup_depth = 256;
1205                 if (lookup_depth == 0)
1206                     errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
1207                         " must be greater than zero");
1208
1209                 len = sizeof(int);
1210                 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
1211                         &avg_pkt_size, &len, NULL, 0) == -1)
1212                         avg_pkt_size = 512;
1213
1214                 if (avg_pkt_size == 0)
1215                         errx(EX_DATAERR,
1216                             "net.inet.ip.dummynet.red_avg_pkt_size must"
1217                             " be greater than zero");
1218
1219                 /*
1220                  * Ticks needed for sending a medium-sized packet.
1221                  * Unfortunately, when we are configuring a WF2Q+ queue, we
1222                  * do not have bandwidth information, because that is stored
1223                  * in the parent pipe, and also we have multiple queues
1224                  * competing for it. So we set s=0, which is not very
1225                  * correct. But on the other hand, why do we want RED with
1226                  * WF2Q+ ?
1227                  */
1228 #if 0
1229                 if (p.bandwidth==0) /* this is a WF2Q+ queue */
1230                         s = 0;
1231                 else
1232                         s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
1233 #endif
1234                 /*
1235                  * max idle time (in ticks) before avg queue size becomes 0.
1236                  * NOTA:  (3/w_q) is approx the value x so that
1237                  * (1-w_q)^x < 10^-3.
1238                  */
1239                 w_q = ((double)fs->w_q) / (1 << SCALE_RED);
1240 #if 0 // go in kernel
1241                 idle = s * 3. / w_q;
1242                 fs->lookup_step = (int)idle / lookup_depth;
1243                 if (!fs->lookup_step)
1244                         fs->lookup_step = 1;
1245                 weight = 1 - w_q;
1246                 for (t = fs->lookup_step; t > 1; --t)
1247                         weight *= 1 - w_q;
1248                 fs->lookup_weight = (int)(weight * (1 << SCALE_RED));
1249 #endif
1250             }
1251         }
1252
1253         i = do_cmd(IP_DUMMYNET3, base, (char *)buf - (char *)base);
1254
1255         if (i)
1256                 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
1257 }
1258
1259 void
1260 dummynet_flush(void)
1261 {
1262         struct dn_id oid;
1263         oid_fill(&oid, sizeof(oid), DN_CMD_FLUSH, DN_API_VERSION);
1264         do_cmd(IP_DUMMYNET3, &oid, oid.len);
1265 }
1266
1267 /* Parse input for 'ipfw [pipe|sched|queue] show [range list]'
1268  * Returns the number of ranges, and possibly stores them
1269  * in the array v of size len.
1270  */
1271 static int
1272 parse_range(int ac, char *av[], uint32_t *v, int len)
1273 {
1274         int n = 0;
1275         char *endptr, *s;
1276         uint32_t base[2];
1277
1278         if (v == NULL || len < 2) {
1279                 v = base;
1280                 len = 2;
1281         }
1282
1283         for (s = *av; s != NULL; av++, ac--) {
1284                 v[0] = strtoul(s, &endptr, 10);
1285                 v[1] = (*endptr != '-') ? v[0] :
1286                          strtoul(endptr+1, &endptr, 10);
1287                 if (*endptr == '\0') { /* prepare for next round */
1288                         s = (ac > 0) ? *(av+1) : NULL;
1289                 } else {
1290                         if (*endptr != ',') {
1291                                 warn("invalid number: %s", s);
1292                                 s = ++endptr;
1293                                 continue;
1294                         }
1295                         /* continue processing from here */
1296                         s = ++endptr;
1297                         ac++;
1298                         av--;
1299                 }
1300                 if (v[1] < v[0] ||
1301                         v[1] < 0 || v[1] >= DN_MAX_ID-1 ||
1302                         v[0] < 0 || v[1] >= DN_MAX_ID-1) {
1303                         continue; /* invalid entry */
1304                 }
1305                 n++;
1306                 /* translate if 'pipe list' */
1307                 if (co.do_pipe == 1) {
1308                         v[0] += DN_MAX_ID;
1309                         v[1] += DN_MAX_ID;
1310                 }
1311                 v = (n*2 < len) ? v + 2 : base;
1312         }
1313         return n;
1314 }
1315
1316 /* main entry point for dummynet list functions. co.do_pipe indicates
1317  * which function we want to support.
1318  * av may contain filtering arguments, either individual entries
1319  * or ranges, or lists (space or commas are valid separators).
1320  * Format for a range can be n1-n2 or n3 n4 n5 ...
1321  * In a range n1 must be <= n2, otherwise the range is ignored.
1322  * A number 'n4' is translate in a range 'n4-n4'
1323  * All number must be > 0 and < DN_MAX_ID-1
1324  */
1325 void
1326 dummynet_list(int ac, char *av[], int show_counters)
1327 {
1328         struct dn_id *oid, *x = NULL;
1329         int ret, i, l;
1330         int n;          /* # of ranges */
1331         int buflen;
1332         int max_size;   /* largest obj passed up */
1333
1334         ac--;
1335         av++;           /* skip 'list' | 'show' word */
1336
1337         n = parse_range(ac, av, NULL, 0);       /* Count # of ranges. */
1338
1339         /* Allocate space to store ranges */
1340         l = sizeof(*oid) + sizeof(uint32_t) * n * 2;
1341         oid = safe_calloc(1, l);
1342         oid_fill(oid, l, DN_CMD_GET, DN_API_VERSION);
1343
1344         if (n > 0)      /* store ranges in idx */
1345                 parse_range(ac, av, (uint32_t *)(oid + 1), n*2);
1346         /*
1347          * Compute the size of the largest object returned. If the
1348          * response leaves at least this much spare space in the
1349          * buffer, then surely the response is complete; otherwise
1350          * there might be a risk of truncation and we will need to
1351          * retry with a larger buffer.
1352          * XXX don't bother with smaller structs.
1353          */
1354         max_size = sizeof(struct dn_fs);
1355         if (max_size < sizeof(struct dn_sch))
1356                 max_size = sizeof(struct dn_sch);
1357         if (max_size < sizeof(struct dn_flow))
1358                 max_size = sizeof(struct dn_flow);
1359
1360         switch (co.do_pipe) {
1361         case 1:
1362                 oid->subtype = DN_LINK; /* list pipe */
1363                 break;
1364         case 2:
1365                 oid->subtype = DN_FS;   /* list queue */
1366                 break;
1367         case 3:
1368                 oid->subtype = DN_SCH;  /* list sched */
1369                 break;
1370         }
1371
1372         /*
1373          * Ask the kernel an estimate of the required space (result
1374          * in oid.id), unless we are requesting a subset of objects,
1375          * in which case the kernel does not give an exact answer.
1376          * In any case, space might grow in the meantime due to the
1377          * creation of new queues, so we must be prepared to retry.
1378          */
1379         if (n > 0) {
1380                 buflen = 4*1024;
1381         } else {
1382                 ret = do_cmd(-IP_DUMMYNET3, oid, (uintptr_t)&l);
1383                 if (ret != 0 || oid->id <= sizeof(*oid))
1384                         goto done; 
1385                 buflen = oid->id + max_size;
1386                 oid->len = sizeof(*oid); /* restore */
1387         }
1388         /* Try a few times, until the buffer fits */
1389         for (i = 0; i < 20; i++) {
1390                 l = buflen;
1391                 x = safe_realloc(x, l);
1392                 bcopy(oid, x, oid->len);
1393                 ret = do_cmd(-IP_DUMMYNET3, x, (uintptr_t)&l);
1394                 if (ret != 0 || x->id <= sizeof(*oid))
1395                         goto done; /* no response */
1396                 if (l + max_size <= buflen)
1397                         break; /* ok */
1398                 buflen *= 2;     /* double for next attempt */
1399         }
1400         list_pipes(x, O_NEXT(x, l));
1401 done:
1402         if (x)
1403                 free(x);
1404         free(oid);
1405 }