2 * Copyright (c) 2002-2003,2010 Luigi Rizzo
4 * Redistribution and use in source forms, with and without modification,
5 * are permitted provided that this entire comment appears intact.
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.
11 * This software is provided ``AS IS'' without any warranties of any kind.
13 * $FreeBSD: head/sbin/ipfw/dummynet.c 206843 2010-04-19 15:11:45Z luigi $
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 /* XXX there are several sysctl leftover here */
21 #include <sys/sysctl.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 */
42 static struct _s_x dummynet_params[] = {
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 },
53 { "maxlen", TOK_LMAX },
55 { "mask", TOK_MASK }, /* alias for both */
56 { "sched_mask", TOK_SCHED_MASK },
57 { "flow_mask", TOK_FLOW_MASK },
58 { "droptail", TOK_DROPTAIL },
62 { "bandwidth", TOK_BW },
63 { "delay", TOK_DELAY },
66 { "queue", TOK_QUEUE },
67 { "flowset", TOK_FLOWSET },
68 { "sched", TOK_SCHED },
70 { "priority", TOK_PRI },
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 */
83 #define O_NEXT(p, len) ((void *)((char *)p + len))
86 oid_fill(struct dn_id *oid, int len, int type, uintptr_t id)
94 /* make room in the buffer and move the pointer forward */
96 o_next(struct dn_id **o, int len, int type)
98 struct dn_id *ret = *o;
99 oid_fill(ret, len, type, 0);
100 *o = O_NEXT(*o, len);
104 /* handle variable lenght structures moving back the pointer and fixing lenght */
106 o_compact(struct dn_id **o, int len, int real_length, int type)
108 struct dn_id *ret = *o;
110 ret = O_NEXT(*o, -len);
111 oid_fill(ret, real_length, type, 0);
112 *o = O_NEXT(ret, real_length);
118 sort_q(void *arg, const void *pa, const void *pb)
120 int rev = (co.do_sort < 0);
121 int field = rev ? -co.do_sort : co.do_sort;
123 const struct dn_flow_queue *a = pa;
124 const struct dn_flow_queue *b = pb;
128 res = a->len - b->len;
131 res = a->len_bytes - b->len_bytes;
134 case 3: /* tot pkts */
135 res = a->tot_pkts - b->tot_pkts;
138 case 4: /* tot bytes */
139 res = a->tot_bytes - b->tot_bytes;
146 return (int)(rev ? res : -res);
150 /* print a mask and header for the subsequent list of flows */
152 print_mask(struct ipfw_flow_id *id)
154 if (!IS_IP6_FLOW_ID(id)) {
156 "mask: %s 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
157 id->extra ? "queue," : "",
159 id->src_ip, id->src_port,
160 id->dst_ip, id->dst_port);
163 printf("\n mask: %sproto: 0x%02x, flow_id: 0x%08x, ",
164 id->extra ? "queue," : "",
165 id->proto, id->flow_id6);
166 inet_ntop(AF_INET6, &(id->src_ip6), buf, sizeof(buf));
167 printf("%s/0x%04x -> ", buf, id->src_port);
168 inet_ntop(AF_INET6, &(id->dst_ip6), buf, sizeof(buf));
169 printf("%s/0x%04x\n", buf, id->dst_port);
174 print_header(struct ipfw_flow_id *id)
176 if (!IS_IP6_FLOW_ID(id))
177 printf("BKT Prot ___Source IP/port____ "
178 "____Dest. IP/port____ "
179 "Tot_pkt/bytes Pkt/Byte Drp\n");
181 printf("BKT ___Prot___ _flow-id_ "
182 "______________Source IPv6/port_______________ "
183 "_______________Dest. IPv6/port_______________ "
184 "Tot_pkt/bytes Pkt/Byte Drp\n");
188 list_flow(struct dn_flow *ni, int *print)
191 struct protoent *pe = NULL;
193 struct ipfw_flow_id *id = &ni->fid;
196 print_header(&ni->fid);
199 pe = getprotobynumber(id->proto);
200 /* XXX: Should check for IPv4 flows */
201 printf("%3u%c", (ni->oid.id) & 0xff,
202 id->extra ? '*' : ' ');
203 if (!IS_IP6_FLOW_ID(id)) {
205 printf("%-4s ", pe->p_name);
207 printf("%4u ", id->proto);
208 ina.s_addr = htonl(id->src_ip);
210 inet_ntoa(ina), id->src_port);
211 ina.s_addr = htonl(id->dst_ip);
213 inet_ntoa(ina), id->dst_port);
215 /* Print IPv6 flows */
217 printf("%9s ", pe->p_name);
219 printf("%9u ", id->proto);
220 printf("%7d %39s/%-5d ", id->flow_id6,
221 inet_ntop(AF_INET6, &(id->src_ip6), buff, sizeof(buff)),
223 printf(" %39s/%-5d ",
224 inet_ntop(AF_INET6, &(id->dst_ip6), buff, sizeof(buff)),
227 pr_u64(&ni->tot_pkts, 4);
228 pr_u64(&ni->tot_bytes, 8);
229 printf("%2u %4u %3u\n",
230 ni->length, ni->len_bytes, ni->drops);
234 print_flowset_parms(struct dn_fs *fs, char *prefix)
239 char red[90]; /* Display RED parameters */
242 if (fs->flags & DN_QSIZE_BYTES) {
244 sprintf(qs, "%d KB", l / 1024);
246 sprintf(qs, "%d B", l);
248 sprintf(qs, "%3d sl.", l);
250 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
254 if (fs->flags & DN_IS_RED) /* RED parameters */
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),
261 1.0 * fs->max_p / (double)(1 << SCALE_RED));
263 sprintf(red, "droptail");
266 printf("%s %s%s %d queues (%d buckets) %s\n",
267 prefix, qs, plr, fs->oid.id, fs->buckets, red);
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);
280 print_extra_delay_parms(struct dn_profile *p)
283 if (p->samples_no <= 0)
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);
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.
308 * link i (int queue); scheduler i; si(i) { flowsets() : queues }
311 list_pipes(struct dn_id *oid, struct dn_id *end)
313 char buf[160]; /* pending buffer */
314 int toPrint = 1; /* print header */
317 for (; oid != end; oid = O_NEXT(oid, oid->len)) {
318 if (oid->len < sizeof(*oid))
319 errx(1, "invalid oid len %d\n", oid->len);
324 printf("unrecognized object %d size %d\n", oid->type, oid->len);
326 case DN_TEXT: /* list of attached flowsets */
333 l = (oid->len - sizeof(*oid))/sizeof(d->p[0]);
336 printf(" Children flowsets: ");
337 for (i = 0; i < l; i++)
338 printf("%u ", d->p[i]);
344 printf("answer for cmd %d, len %d\n", oid->type, oid->id);
347 struct dn_sch *s = (struct dn_sch *)oid;
349 printf(" sched %d type %s flags 0x%x %d buckets %d active\n",
351 s->name, s->flags, s->buckets, s->oid.id);
352 if (s->flags & DN_HAVE_MASK)
353 print_mask(&s->sched_mask);
358 list_flow((struct dn_flow *)oid, &toPrint);
362 struct dn_link *p = (struct dn_link *)oid;
363 double b = p->bandwidth;
367 /* This starts a new object so flush buffer */
371 sprintf(bwbuf, "unlimited ");
372 else if (b >= 1000000)
373 sprintf(bwbuf, "%7.3f Mbit/s", b/1000000);
375 sprintf(bwbuf, "%7.3f Kbit/s", b/1000);
377 sprintf(bwbuf, "%7.3f bit/s ", b);
379 if (humanize_number(burst, sizeof(burst), p->burst,
380 "", HN_AUTOSCALE, 0) < 0 || co.verbose)
381 sprintf(burst, "%d", (int)p->burst);
382 sprintf(buf, "%05d: %s %4d ms burst %s",
383 p->link_nr % DN_MAX_ID, bwbuf, p->delay, burst);
388 print_flowset_parms((struct dn_fs *)oid, buf);
392 print_extra_delay_parms((struct dn_profile *)oid);
394 flush_buf(buf); // XXX does it really go here ?
399 * Delete pipe, queue or scheduler i
402 ipfw_delete_pipe(int do_pipe, int i)
406 uintptr_t a[1]; /* add more if we want a list */
408 oid_fill((void *)&cmd, sizeof(cmd), DN_CMD_DELETE, DN_API_VERSION);
409 cmd.oid.subtype = (do_pipe == 1) ? DN_LINK :
410 ( (do_pipe == 2) ? DN_FS : DN_SCH);
412 i = do_cmd(IP_DUMMYNET3, &cmd, cmd.oid.len);
415 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", i);
421 * Code to parse delay profiles.
423 * Some link types introduce extra delays in the transmission
424 * of a packet, e.g. because of MAC level framing, contention on
425 * the use of the channel, MAC level retransmissions and so on.
426 * From our point of view, the channel is effectively unavailable
427 * for this extra time, which is constant or variable depending
428 * on the link type. Additionally, packets may be dropped after this
429 * time (e.g. on a wireless link after too many retransmissions).
430 * We can model the additional delay with an empirical curve
431 * that represents its distribution.
433 * cumulative probability
443 * +-------*------------------->
446 * The empirical curve may have both vertical and horizontal lines.
447 * Vertical lines represent constant delay for a range of
448 * probabilities; horizontal lines correspond to a discontinuty
449 * in the delay distribution: the link will use the largest delay
450 * for a given probability.
452 * To pass the curve to dummynet, we must store the parameters
453 * in a file as described below, and issue the command
455 * ipfw pipe <n> config ... bw XXX profile <filename> ...
457 * The file format is the following, with whitespace acting as
458 * a separator and '#' indicating the beginning a comment:
461 * the number of samples used in the internal
462 * representation (2..1024; default 100);
465 * The probability above which packets are lost.
466 * (0.0 <= L <= 1.0, default 1.0 i.e. no loss);
469 * Optional a name (listed by "ipfw pipe show")
470 * to identify the distribution;
472 * "delay prob" | "prob delay"
473 * One of these two lines is mandatory and defines
474 * the format of the following lines with data points.
477 * 2 or more lines representing points in the curve,
478 * with either delay or probability first, according
479 * to the chosen format.
480 * The unit for delay is milliseconds.
482 * Data points does not need to be ordered or equal to the number
483 * specified in the "samples" line. ipfw will sort and interpolate
484 * the curve as needed.
486 * Example of a profile file:
492 0 200 # minimum overhead is 200ms
499 * Internally, we will convert the curve to a fixed number of
500 * samples, and when it is time to transmit a packet we will
501 * model the extra delay as extra bits in the packet.
505 #define ED_MAX_LINE_LEN 256+ED_MAX_NAME_LEN
506 #define ED_TOK_SAMPLES "samples"
507 #define ED_TOK_LOSS "loss-level"
508 #define ED_TOK_NAME "name"
509 #define ED_TOK_DELAY "delay"
510 #define ED_TOK_PROB "prob"
511 #define ED_TOK_BW "bw"
512 #define ED_SEPARATORS " \t\n"
513 #define ED_MIN_SAMPLES_NO 2
516 * returns 1 if s is a non-negative number, with at least one '.'
519 is_valid_number(const char *s)
521 int i, dots_found = 0;
524 for (i = 0; i<len; ++i)
525 if (!isdigit(s[i]) && (s[i] !='.' || ++dots_found > 1))
531 * Take as input a string describing a bandwidth value
532 * and return the numeric bandwidth value.
533 * set clocking interface or bandwidth value
536 read_bandwidth(char *arg, int *bandwidth, char *if_name, int namelen)
538 if (*bandwidth != -1)
539 warnx("duplicate token, override bandwidth value!");
541 if (arg[0] >= 'a' && arg[0] <= 'z') {
543 errx(1, "no if support");
545 if (namelen >= IFNAMSIZ)
546 warn("interface name truncated");
549 strncpy(if_name, arg, namelen);
550 if_name[namelen] = '\0';
552 } else { /* read bandwidth value */
556 bw = strtoul(arg, &end, 0);
557 if (*end == 'K' || *end == 'k') {
560 } else if (*end == 'M' || *end == 'm') {
565 _substrcmp2(end, "Bi", "Bit/s") != 0) ||
566 _substrcmp2(end, "by", "bytes") == 0)
570 errx(EX_DATAERR, "bandwidth too large");
584 compare_points(const void *vp1, const void *vp2)
586 const struct point *p1 = vp1;
587 const struct point *p2 = vp2;
590 res = p1->prob - p2->prob;
592 res = p1->delay - p2->delay;
601 #define ED_EFMT(s) EX_DATAERR,"error in %s at line %d: "#s,filename,lineno
604 * Interpolate a set of proability-value tuples.
606 * This function takes as input a tuple of values <prob, value>
607 * and samples the interpolated curve described from the tuples.
609 * The user defined points are stored in the ponts structure.
610 * The number of points is stored in points_no.
611 * The user defined sampling value is stored in samples_no.
612 * The resulting samples are in the "samples" pointer.
614 * We assume that The last point for the '1' value of the
615 * probability should be defined. (XXX add checks for this)
617 * The input data are points and points_no.
618 * The output data are s (the array of s_no samples)
619 * and s_no (the number of samples)
623 interpolate_samples(struct point *p, int points_no,
624 int *samples, int samples_no, const char *filename)
626 double dy; /* delta on the y axis */
627 double y; /* current value of y */
628 double x; /* current value of x */
629 double m; /* the y slope */
630 int i; /* samples index */
631 int curr; /* points current index */
633 /* make sure that there are enough points. */
634 /* XXX Duplicated should be removed */
636 errx(EX_DATAERR, "%s too few samples, need at least %d",
639 qsort(p, points_no, sizeof(struct point), compare_points);
644 for (i=0, curr = 0; i < samples_no; i++, y+=dy) {
645 /* This statment move the curr pointer to the next point
646 * skipping the points with the same x value. We are
647 * guaranteed to exit from the loop because the
648 * last possible value of y is stricly less than 1
649 * and the last possible value of the y points is 1 */
650 while ( y >= p[curr+1].prob ) curr++;
652 /* compute the slope of the curve */
653 m = (p[curr+1].delay - p[curr].delay) / (p[curr+1].prob - p[curr].prob);
654 /* compute the x value starting from the current point */
655 x = p[curr].delay + (y - p[curr].prob) * m;
659 /* add the last sample */
660 samples[i] = p[curr+1].delay;
664 * p is the link (old pipe)
668 load_extra_delays(const char *filename, struct dn_profile *p,
669 struct dn_link *link)
671 char line[ED_MAX_LINE_LEN];
677 char profile_name[ED_MAX_NAME_LEN];
678 int delay_first = -1;
680 struct point points[ED_MAX_SAMPLES_NO];
683 /* XXX link never NULL? */
684 p->link_nr = link->link_nr;
686 profile_name[0] = '\0';
688 f = fopen(filename, "r");
690 err(EX_UNAVAILABLE, "fopen: %s", filename);
692 while (fgets(line, ED_MAX_LINE_LEN, f)) { /* read commands */
693 char *s, *cur = line, *name = NULL, *arg = NULL;
699 s = strsep(&cur, ED_SEPARATORS);
700 if (s == NULL || *s == '#')
705 errx(ED_EFMT("too many arguments"));
712 if ((name == NULL) || (*name == '#')) /* empty line */
715 if (!strcasecmp(name, ED_TOK_SAMPLES)) {
717 errx(ED_EFMT("duplicate ``samples'' line"));
719 errx(ED_EFMT("invalid number of samples"));
721 if (samples>=ED_MAX_SAMPLES_NO-1)
722 errx(ED_EFMT("too many samples, maximum is %d"),
723 ED_MAX_SAMPLES_NO-1);
725 } else if (!strcasecmp(name, ED_TOK_BW)) {
727 read_bandwidth(arg, &link->bandwidth, buf, sizeof(buf));
728 p->bandwidth = link->bandwidth;
729 } else if (!strcasecmp(name, ED_TOK_LOSS)) {
731 errx(ED_EFMT("duplicated token: %s"), name);
732 if (!is_valid_number(arg))
733 errx(ED_EFMT("invalid %s"), arg);
736 errx(ED_EFMT("%s greater than 1.0"), name);
738 } else if (!strcasecmp(name, ED_TOK_NAME)) {
739 if (profile_name[0] != '\0')
740 errx(ED_EFMT("duplicated token: %s"), name);
741 strncpy(profile_name, arg, sizeof(profile_name) - 1);
742 profile_name[sizeof(profile_name)-1] = '\0';
744 } else if (!strcasecmp(name, ED_TOK_DELAY)) {
746 errx(ED_EFMT("duplicated token: %s"), name);
749 } else if (!strcasecmp(name, ED_TOK_PROB)) {
751 errx(ED_EFMT("duplicated token: %s"), name);
754 } else if (do_points) {
755 if (!is_valid_number(name) || !is_valid_number(arg))
756 errx(ED_EFMT("invalid point found"));
758 points[points_no].delay = atof(name);
759 points[points_no].prob = atof(arg);
761 points[points_no].delay = atof(arg);
762 points[points_no].prob = atof(name);
764 if (points[points_no].prob > 1.0)
765 errx(ED_EFMT("probability greater than 1.0"));
768 errx(ED_EFMT("unrecognised command '%s'"), name);
775 warnx("'%s' not found, assuming 100", ED_TOK_SAMPLES);
780 warnx("'%s' not found, assuming no loss", ED_TOK_LOSS);
784 interpolate_samples(points, points_no, p->samples, samples, filename);
786 p->samples_no = samples++;
787 p->loss_level = loss * samples;
788 strncpy(p->name, profile_name, sizeof(p->name));
792 * configuration of pipes, schedulers, flowsets.
793 * When we configure a new scheduler, an empty pipe is created, so:
795 * do_pipe = 1 -> "pipe N config ..." only for backward compatibility
796 * sched N+Delta type fifo sched_mask ...
797 * pipe N+Delta <parameters>
798 * flowset N+Delta pipe N+Delta (no parameters)
799 * sched N type wf2q+ sched_mask ...
800 * pipe N <parameters>
802 * do_pipe = 2 -> flowset N config
803 * flowset N parameters
805 * do_pipe = 3 -> sched N config
806 * sched N parameters (default no pipe)
807 * optional Pipe N config ...
811 ipfw_config_pipe(int ac, char **av)
816 struct dn_id *buf, *base;
817 struct dn_sch *sch = NULL;
818 struct dn_link *p = NULL;
819 struct dn_fs *fs = NULL;
820 struct dn_profile *pf = NULL;
821 struct ipfw_flow_id *mask = NULL;
823 uint32_t _foo = 0, *flags = &_foo , *buckets = &_foo;
824 size_t max_pf_size = sizeof(struct dn_profile) + ED_MAX_SAMPLES_NO * sizeof(int);
827 * allocate space for 1 header,
828 * 1 scheduler, 1 link, 1 flowset, 1 profile
830 lmax = sizeof(struct dn_id); /* command header */
831 lmax += sizeof(struct dn_sch) + sizeof(struct dn_link) +
832 sizeof(struct dn_fs);
837 if (ac && isdigit(**av)) {
838 i = atoi(*av); av++; ac--;
842 errx(EX_USAGE, "need a pipe/flowset/sched number");
843 base = buf = safe_calloc(1, lmax);
844 /* all commands start with a 'CONFIGURE' and a version */
845 o_next(&buf, sizeof(struct dn_id), DN_CMD_CONFIG);
846 base->id = DN_API_VERSION;
848 switch (co.do_pipe) {
849 case 1: /* "pipe N config ..." */
850 /* Allocate space for the WF2Q+ scheduler, its link
851 * and the FIFO flowset. Set the number, but leave
852 * the scheduler subtype and other parameters to 0
853 * so the kernel will use appropriate defaults.
854 * XXX todo: add a flag to record if a parameter
855 * is actually configured.
856 * If we do a 'pipe config' mask -> sched_mask.
857 * The FIFO scheduler and link are derived from the
858 * WF2Q+ one in the kernel.
860 sch = o_next(&buf, sizeof(*sch), DN_SCH);
861 p = o_next(&buf, sizeof(*p), DN_LINK);
862 fs = o_next(&buf, sizeof(*fs), DN_FS);
865 sch->oid.subtype = 0; /* defaults to WF2Q+ */
866 mask = &sch->sched_mask;
868 buckets = &sch->buckets;
869 *flags |= DN_PIPE_CMD;
873 /* This flowset is only for the FIFO scheduler */
874 fs->fs_nr = i + 2*DN_MAX_ID;
875 fs->sched_nr = i + DN_MAX_ID;
878 case 2: /* "queue N config ... " */
879 fs = o_next(&buf, sizeof(*fs), DN_FS);
881 mask = &fs->flow_mask;
883 buckets = &fs->buckets;
886 case 3: /* "sched N config ..." */
887 sch = o_next(&buf, sizeof(*sch), DN_SCH);
888 fs = o_next(&buf, sizeof(*fs), DN_FS);
890 mask = &sch->sched_mask;
892 buckets = &sch->buckets;
893 /* fs is used only with !MULTIQUEUE schedulers */
894 fs->fs_nr = i + DN_MAX_ID;
898 /* set to -1 those fields for which we want to reuse existing
899 * values from the kernel.
900 * Also, *_nr and subtype = 0 mean reuse the value from the kernel.
901 * XXX todo: support reuse of the mask.
905 for (j = 0; j < sizeof(fs->par)/sizeof(fs->par[0]); j++)
909 int tok = match_token(dummynet_params, *av);
914 NEED(fs, "noerror is only for pipes");
915 fs->flags |= DN_NOERROR;
919 NEED(fs, "plr is only for pipes");
920 NEED1("plr needs argument 0..1\n");
921 d = strtod(av[0], NULL);
926 fs->plr = (int)(d*0x7fffffff);
931 NEED(fs, "queue is only for pipes or flowsets");
932 NEED1("queue needs queue size\n");
934 fs->qsize = strtoul(av[0], &end, 0);
935 if (*end == 'K' || *end == 'k') {
936 fs->flags |= DN_QSIZE_BYTES;
938 } else if (*end == 'B' ||
939 _substrcmp2(end, "by", "bytes") == 0) {
940 fs->flags |= DN_QSIZE_BYTES;
946 NEED(fs, "buckets is only for pipes or flowsets");
947 NEED1("buckets needs argument\n");
948 *buckets = strtoul(av[0], NULL, 0);
955 NEED(mask, "tok_mask");
956 NEED1("mask needs mask specifier\n");
958 * per-flow queue, mask is dst_ip, dst_port,
959 * src_ip, src_port, proto measured in bits
963 bzero(mask, sizeof(*mask));
967 uint32_t *p32 = NULL;
968 uint16_t *p16 = NULL;
969 uint32_t *p20 = NULL;
970 struct in6_addr *pa6 = NULL;
973 tok = match_token(dummynet_params, *av);
978 * special case, all bits significant
979 * except 'extra' (the queue number)
986 n2mask(&mask->dst_ip6, 128);
987 n2mask(&mask->src_ip6, 128);
989 *flags |= DN_HAVE_MASK;
994 *flags |= DN_HAVE_MASK;
1003 mask->addr_type = 4;
1004 p32 = &mask->src_ip;
1008 mask->addr_type = 6;
1009 pa6 = &mask->dst_ip6;
1013 mask->addr_type = 6;
1014 pa6 = &mask->src_ip6;
1018 mask->addr_type = 6;
1019 p20 = &mask->flow_id6;
1023 p16 = &mask->dst_port;
1027 p16 = &mask->src_port;
1034 ac++; av--; /* backtrack */
1038 errx(EX_USAGE, "mask: value missing");
1039 if (*av[0] == '/') {
1040 a = strtoul(av[0]+1, &end, 0);
1042 a = (a == 32) ? ~0 : (1 << a) - 1;
1044 a = strtoul(av[0], &end, 0);
1047 else if (p16 != NULL) {
1050 "port mask must be 16 bit");
1052 } else if (p20 != NULL) {
1055 "flow_id mask must be 20 bit");
1057 } else if (pa6 != NULL) {
1060 "in6addr invalid mask len");
1066 "proto mask must be 8 bit");
1067 mask->proto = (uint8_t)a;
1070 *flags |= DN_HAVE_MASK;
1072 } /* end while, config masks */
1078 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
1079 fs->flags |= DN_IS_RED;
1080 if (tok == TOK_GRED)
1081 fs->flags |= DN_IS_GENTLE_RED;
1083 * the format for parameters is w_q/min_th/max_th/max_p
1085 if ((end = strsep(&av[0], "/"))) {
1086 double w_q = strtod(end, NULL);
1087 if (w_q > 1 || w_q <= 0)
1088 errx(EX_DATAERR, "0 < w_q <= 1");
1089 fs->w_q = (int) (w_q * (1 << SCALE_RED));
1091 if ((end = strsep(&av[0], "/"))) {
1092 fs->min_th = strtoul(end, &end, 0);
1093 if (*end == 'K' || *end == 'k')
1096 if ((end = strsep(&av[0], "/"))) {
1097 fs->max_th = strtoul(end, &end, 0);
1098 if (*end == 'K' || *end == 'k')
1101 if ((end = strsep(&av[0], "/"))) {
1102 double max_p = strtod(end, NULL);
1103 if (max_p > 1 || max_p <= 0)
1104 errx(EX_DATAERR, "0 < max_p <= 1");
1105 fs->max_p = (int)(max_p * (1 << SCALE_RED));
1111 NEED(fs, "droptail is only for flowsets");
1112 fs->flags &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1116 NEED(p, "bw is only for links");
1117 NEED1("bw needs bandwidth or interface\n");
1118 read_bandwidth(av[0], &p->bandwidth, NULL, 0);
1123 NEED(p, "delay is only for links");
1124 NEED1("delay needs argument 0..10000ms\n");
1125 p->delay = strtoul(av[0], NULL, 0);
1131 NEED(sch, "type is only for schedulers");
1132 NEED1("type needs a string");
1134 if (l == 0 || l > 15)
1135 errx(1, "type %s too long\n", av[0]);
1136 strcpy(sch->name, av[0]);
1137 sch->oid.subtype = 0; /* use string */
1143 NEED(fs, "weight is only for flowsets");
1144 NEED1("weight needs argument\n");
1145 fs->par[0] = strtol(av[0], &end, 0);
1150 NEED(fs, "lmax is only for flowsets");
1151 NEED1("lmax needs argument\n");
1152 fs->par[1] = strtol(av[0], &end, 0);
1157 NEED(fs, "priority is only for flowsets");
1158 NEED1("priority needs argument\n");
1159 fs->par[2] = strtol(av[0], &end, 0);
1165 NEED(fs, "pipe/sched");
1166 NEED1("pipe/link/sched needs number\n");
1167 fs->sched_nr = strtoul(av[0], &end, 0);
1175 NEED((!pf), "profile already set");
1177 NEED1("extra delay needs the file name\n");
1179 /* load the profile structure using the DN_API */
1180 pf = o_next(&buf, max_pf_size, DN_PROFILE);
1181 load_extra_delays(av[0], pf, p); //XXX can't fail?
1183 /* compact the dn_id structure */
1184 real_length = sizeof(struct dn_profile) +
1185 pf->samples_no * sizeof(int);
1186 o_compact(&buf, max_pf_size, real_length, DN_PROFILE);
1193 NEED1("burst needs argument\n");
1195 if (expand_number(av[0], (int64_t *)&p->burst) < 0)
1196 if (errno != ERANGE)
1198 "burst: invalid argument");
1199 if (errno || p->burst > (1ULL << 48) - 1)
1201 "burst: out of range (0..2^48-1)");
1206 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
1210 /* check validity of parameters */
1212 if (p->delay > 10000)
1213 errx(EX_DATAERR, "delay must be < 10000");
1214 if (p->bandwidth == -1)
1218 /* XXX accept a 0 scheduler to keep the default */
1219 if (fs->flags & DN_QSIZE_BYTES) {
1223 len = sizeof(limit);
1224 if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
1225 &limit, &len, NULL, 0) == -1)
1227 if (fs->qsize > limit)
1228 errx(EX_DATAERR, "queue size must be < %ldB", limit);
1233 len = sizeof(limit);
1234 if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
1235 &limit, &len, NULL, 0) == -1)
1237 if (fs->qsize > limit)
1238 errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
1241 if (fs->flags & DN_IS_RED) {
1243 int lookup_depth, avg_pkt_size;
1246 if (fs->min_th >= fs->max_th)
1247 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1248 fs->min_th, fs->max_th);
1249 if (fs->max_th == 0)
1250 errx(EX_DATAERR, "max_th must be > 0");
1253 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1254 &lookup_depth, &len, NULL, 0) == -1)
1256 if (lookup_depth == 0)
1257 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
1258 " must be greater than zero");
1261 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
1262 &avg_pkt_size, &len, NULL, 0) == -1)
1265 if (avg_pkt_size == 0)
1267 "net.inet.ip.dummynet.red_avg_pkt_size must"
1268 " be greater than zero");
1271 * Ticks needed for sending a medium-sized packet.
1272 * Unfortunately, when we are configuring a WF2Q+ queue, we
1273 * do not have bandwidth information, because that is stored
1274 * in the parent pipe, and also we have multiple queues
1275 * competing for it. So we set s=0, which is not very
1276 * correct. But on the other hand, why do we want RED with
1280 if (p.bandwidth==0) /* this is a WF2Q+ queue */
1283 s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
1286 * max idle time (in ticks) before avg queue size becomes 0.
1287 * NOTA: (3/w_q) is approx the value x so that
1288 * (1-w_q)^x < 10^-3.
1290 w_q = ((double)fs->w_q) / (1 << SCALE_RED);
1291 #if 0 // go in kernel
1292 idle = s * 3. / w_q;
1293 fs->lookup_step = (int)idle / lookup_depth;
1294 if (!fs->lookup_step)
1295 fs->lookup_step = 1;
1297 for (t = fs->lookup_step; t > 1; --t)
1299 fs->lookup_weight = (int)(weight * (1 << SCALE_RED));
1304 i = do_cmd(IP_DUMMYNET3, base, (char *)buf - (char *)base);
1307 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
1311 dummynet_flush(void)
1314 oid_fill(&oid, sizeof(oid), DN_CMD_FLUSH, DN_API_VERSION);
1315 do_cmd(IP_DUMMYNET3, &oid, oid.len);
1318 /* Parse input for 'ipfw [pipe|sched|queue] show [range list]'
1319 * Returns the number of ranges, and possibly stores them
1320 * in the array v of size len.
1323 parse_range(int ac, char *av[], uint32_t *v, int len)
1329 if (v == NULL || len < 2) {
1334 for (s = *av; s != NULL; av++, ac--) {
1335 v[0] = strtoul(s, &endptr, 10);
1336 v[1] = (*endptr != '-') ? v[0] :
1337 strtoul(endptr+1, &endptr, 10);
1338 if (*endptr == '\0') { /* prepare for next round */
1339 s = (ac > 0) ? *(av+1) : NULL;
1341 if (*endptr != ',') {
1342 warn("invalid number: %s", s);
1346 /* continue processing from here */
1352 v[1] < 0 || v[1] >= DN_MAX_ID-1 ||
1353 v[0] < 0 || v[1] >= DN_MAX_ID-1) {
1354 continue; /* invalid entry */
1357 /* translate if 'pipe list' */
1358 if (co.do_pipe == 1) {
1362 v = (n*2 < len) ? v + 2 : base;
1367 /* main entry point for dummynet list functions. co.do_pipe indicates
1368 * which function we want to support.
1369 * av may contain filtering arguments, either individual entries
1370 * or ranges, or lists (space or commas are valid separators).
1371 * Format for a range can be n1-n2 or n3 n4 n5 ...
1372 * In a range n1 must be <= n2, otherwise the range is ignored.
1373 * A number 'n4' is translate in a range 'n4-n4'
1374 * All number must be > 0 and < DN_MAX_ID-1
1377 dummynet_list(int ac, char *av[], int show_counters)
1379 struct dn_id *oid, *x = NULL;
1381 int n; /* # of ranges */
1383 int max_size; /* largest obj passed up */
1386 av++; /* skip 'list' | 'show' word */
1388 n = parse_range(ac, av, NULL, 0); /* Count # of ranges. */
1390 /* Allocate space to store ranges */
1391 l = sizeof(*oid) + sizeof(uint32_t) * n * 2;
1392 oid = safe_calloc(1, l);
1393 oid_fill(oid, l, DN_CMD_GET, DN_API_VERSION);
1395 if (n > 0) /* store ranges in idx */
1396 parse_range(ac, av, (uint32_t *)(oid + 1), n*2);
1398 * Compute the size of the largest object returned. If the
1399 * response leaves at least this much spare space in the
1400 * buffer, then surely the response is complete; otherwise
1401 * there might be a risk of truncation and we will need to
1402 * retry with a larger buffer.
1403 * XXX don't bother with smaller structs.
1405 max_size = sizeof(struct dn_fs);
1406 if (max_size < sizeof(struct dn_sch))
1407 max_size = sizeof(struct dn_sch);
1408 if (max_size < sizeof(struct dn_flow))
1409 max_size = sizeof(struct dn_flow);
1411 switch (co.do_pipe) {
1413 oid->subtype = DN_LINK; /* list pipe */
1416 oid->subtype = DN_FS; /* list queue */
1419 oid->subtype = DN_SCH; /* list sched */
1424 * Ask the kernel an estimate of the required space (result
1425 * in oid.id), unless we are requesting a subset of objects,
1426 * in which case the kernel does not give an exact answer.
1427 * In any case, space might grow in the meantime due to the
1428 * creation of new queues, so we must be prepared to retry.
1433 ret = do_cmd(-IP_DUMMYNET3, oid, (uintptr_t)&l);
1434 if (ret != 0 || oid->id <= sizeof(*oid))
1436 buflen = oid->id + max_size;
1437 oid->len = sizeof(*oid); /* restore */
1439 /* Try a few times, until the buffer fits */
1440 for (i = 0; i < 20; i++) {
1442 x = safe_realloc(x, l);
1443 bcopy(oid, x, oid->len);
1444 ret = do_cmd(-IP_DUMMYNET3, x, (uintptr_t)&l);
1445 if (ret != 0 || x->id <= sizeof(*oid))
1446 goto done; /* no response */
1447 if (l + max_size <= buflen)
1449 buflen *= 2; /* double for next attempt */
1451 list_pipes(x, O_NEXT(x, l));