2 * tc_util.c Misc TC utility functions.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
17 #include <sys/socket.h>
18 #include <sys/param.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
28 #include "tc_common.h"
31 #define LIBDIR "/usr/lib"
34 static struct db_names *cls_names;
36 #define NAMES_DB "/etc/iproute2/tc_cls"
38 int cls_names_init(char *path)
42 cls_names = db_names_alloc();
46 ret = db_names_load(cls_names, path ?: NAMES_DB);
47 if (ret == -ENOENT && path) {
48 fprintf(stderr, "Can't open class names file: %s\n", path);
52 db_names_free(cls_names);
59 void cls_names_uninit(void)
61 db_names_free(cls_names);
64 const char *get_tc_lib(void)
68 lib_dir = getenv("TC_LIB_DIR");
70 lib_dir = LIBDIR "/tc/";
75 int get_qdisc_handle(__u32 *h, const char *str)
81 if (strcmp(str, "none") == 0)
83 maj = strtoul(str, &p, 16);
84 if (p == str || maj >= (1 << 16))
87 if (*p != ':' && *p != 0)
94 int get_tc_classid(__u32 *h, const char *str)
100 if (strcmp(str, "root") == 0)
103 if (strcmp(str, "none") == 0)
105 maj = strtoul(str, &p, 16);
116 min = strtoul(str, &p, 16);
130 int print_tc_classid(char *buf, int blen, __u32 h)
132 SPRINT_BUF(handle) = {};
133 int hlen = SPRINT_BSIZE - 1;
136 sprintf(handle, "root");
137 else if (h == TC_H_UNSPEC)
138 snprintf(handle, hlen, "none");
139 else if (TC_H_MAJ(h) == 0)
140 snprintf(handle, hlen, ":%x", TC_H_MIN(h));
141 else if (TC_H_MIN(h) == 0)
142 snprintf(handle, hlen, "%x:", TC_H_MAJ(h) >> 16);
144 snprintf(handle, hlen, "%x:%x", TC_H_MAJ(h) >> 16, TC_H_MIN(h));
147 char clname[IDNAME_MAX] = {};
149 if (id_to_name(cls_names, h, clname))
150 snprintf(buf, blen, "%s#%s", clname, handle);
152 snprintf(buf, blen, "%s", handle);
154 snprintf(buf, blen, "%s", handle);
160 char *sprint_tc_classid(__u32 h, char *buf)
162 if (print_tc_classid(buf, SPRINT_BSIZE-1, h))
167 /* See http://physics.nist.gov/cuu/Units/binary.html */
168 static const struct rate_suffix {
175 { "mibit", 1024.*1024. },
176 { "mbit", 1000000. },
177 { "gibit", 1024.*1024.*1024. },
178 { "gbit", 1000000000. },
179 { "tibit", 1024.*1024.*1024.*1024. },
180 { "tbit", 1000000000000. },
182 { "KiBps", 8.*1024. },
184 { "MiBps", 8.*1024*1024. },
185 { "MBps", 8000000. },
186 { "GiBps", 8.*1024.*1024.*1024. },
187 { "GBps", 8000000000. },
188 { "TiBps", 8.*1024.*1024.*1024.*1024. },
189 { "TBps", 8000000000000. },
193 /* Parse a percent e.g: '30%'
194 * return: 0 = ok, -1 = error, 1 = out of range
196 int parse_percent(double *val, const char *str)
200 *val = strtod(str, &p) / 100.;
201 if (*val > 1.0 || *val < 0.0)
203 if (*p && strcmp(p, "%"))
209 static int parse_percent_rate(char *rate, size_t len,
210 const char *str, const char *dev)
214 double perc, rate_bit;
215 char *str_perc = NULL;
218 fprintf(stderr, "No device specified; specify device to rate limit by percentage\n");
222 if (read_prop(dev, "speed", &dev_mbit))
225 ret = sscanf(str, "%m[0-9.%]", &str_perc);
229 ret = parse_percent(&perc, str_perc);
231 fprintf(stderr, "Invalid rate specified; should be between [0,100]%% but is %s\n", str);
233 } else if (ret == -1) {
239 rate_bit = perc * dev_mbit * 1000 * 1000;
241 ret = snprintf(rate, len, "%lf", rate_bit);
242 if (ret <= 0 || ret >= len) {
243 fprintf(stderr, "Unable to parse calculated rate\n");
250 fprintf(stderr, "Specified rate value could not be read or is malformed\n");
256 int get_percent_rate(unsigned int *rate, const char *str, const char *dev)
260 if (parse_percent_rate(r_str, sizeof(r_str), str, dev))
263 return get_rate(rate, r_str);
266 int get_percent_rate64(__u64 *rate, const char *str, const char *dev)
270 if (parse_percent_rate(r_str, sizeof(r_str), str, dev))
273 return get_rate64(rate, r_str);
276 int get_rate(unsigned int *rate, const char *str)
279 double bps = strtod(str, &p);
280 const struct rate_suffix *s;
285 for (s = suffixes; s->name; ++s) {
286 if (strcasecmp(s->name, p) == 0) {
294 return -1; /* unknown suffix */
296 bps /= 8; /* -> bytes per second */
298 /* detect if an overflow happened */
299 if (*rate != floor(bps))
304 int get_rate64(__u64 *rate, const char *str)
307 double bps = strtod(str, &p);
308 const struct rate_suffix *s;
313 for (s = suffixes; s->name; ++s) {
314 if (strcasecmp(s->name, p) == 0) {
322 return -1; /* unknown suffix */
324 bps /= 8; /* -> bytes per second */
329 void print_rate(char *buf, int len, __u64 rate)
332 unsigned long kilo = use_iec ? 1024 : 1000;
333 const char *str = use_iec ? "i" : "";
334 static char *units[5] = {"", "K", "M", "G", "T"};
337 rate <<= 3; /* bytes/sec -> bits/sec */
339 for (i = 0; i < ARRAY_SIZE(units) - 1; i++) {
342 if (((rate % kilo) != 0) && rate < 1000*kilo)
347 snprintf(buf, len, "%.0f%s%sbit", (double)rate, units[i], str);
350 char *sprint_rate(__u64 rate, char *buf)
352 print_rate(buf, SPRINT_BSIZE-1, rate);
356 char *sprint_ticks(__u32 ticks, char *buf)
358 return sprint_time(tc_core_tick2time(ticks), buf);
361 int get_size(unsigned int *size, const char *str)
366 sz = strtod(str, &p);
371 if (strcasecmp(p, "kb") == 0 || strcasecmp(p, "k") == 0)
373 else if (strcasecmp(p, "gb") == 0 || strcasecmp(p, "g") == 0)
374 sz *= 1024*1024*1024;
375 else if (strcasecmp(p, "gbit") == 0)
376 sz *= 1024*1024*1024/8;
377 else if (strcasecmp(p, "mb") == 0 || strcasecmp(p, "m") == 0)
379 else if (strcasecmp(p, "mbit") == 0)
381 else if (strcasecmp(p, "kbit") == 0)
383 else if (strcasecmp(p, "b") != 0)
391 int get_size_and_cell(unsigned int *size, int *cell_log, char *str)
393 char *slash = strchr(str, '/');
398 if (get_size(size, str))
405 if (get_integer(&cell, slash+1, 0))
409 for (i = 0; i < 32; i++) {
410 if ((1<<i) == cell) {
420 void print_devname(enum output_type type, int ifindex)
422 const char *ifname = ll_index_to_name(ifindex);
424 if (!is_json_context())
427 print_color_string(type, COLOR_IFNAME,
428 "dev", "%s ", ifname);
431 static void print_size(char *buf, int len, __u32 sz)
435 if (sz >= 1024*1024 && fabs(1024*1024*rint(tmp/(1024*1024)) - sz) < 1024)
436 snprintf(buf, len, "%gMb", rint(tmp/(1024*1024)));
437 else if (sz >= 1024 && fabs(1024*rint(tmp/1024) - sz) < 16)
438 snprintf(buf, len, "%gKb", rint(tmp/1024));
440 snprintf(buf, len, "%ub", sz);
443 char *sprint_size(__u32 size, char *buf)
445 print_size(buf, SPRINT_BSIZE-1, size);
449 static const char *action_n2a(int action)
453 if (TC_ACT_EXT_CMP(action, TC_ACT_GOTO_CHAIN))
455 if (TC_ACT_EXT_CMP(action, TC_ACT_JUMP))
464 case TC_ACT_RECLASSIFY:
473 snprintf(buf, 64, "%d", action);
478 /* Convert action branch name into numeric format.
481 * @arg - string to parse
482 * @result - pointer to output variable
483 * @allow_num - whether @arg may be in numeric format already
485 * In error case, returns -1 and does not touch @result. Otherwise returns 0.
487 int action_a2n(char *arg, int *result, bool allow_num)
495 {"continue", TC_ACT_UNSPEC},
496 {"drop", TC_ACT_SHOT},
497 {"shot", TC_ACT_SHOT},
500 {"reclassify", TC_ACT_RECLASSIFY},
501 {"pipe", TC_ACT_PIPE},
502 {"goto", TC_ACT_GOTO_CHAIN},
503 {"jump", TC_ACT_JUMP},
504 {"trap", TC_ACT_TRAP},
508 for (iter = a2n; iter->a; iter++) {
509 if (matches(arg, iter->a) != 0)
514 if (!allow_num || sscanf(arg, "%d%c", &n, &dummy) != 1)
523 static int __parse_action_control(int *argc_p, char ***argv_p, int *result_p,
524 bool allow_num, bool ignore_a2n_miss)
527 char **argv = *argv_p;
532 if (action_a2n(*argv, &result, allow_num) == -1) {
533 if (!ignore_a2n_miss)
534 fprintf(stderr, "Bad action type %s\n", *argv);
537 if (result == TC_ACT_GOTO_CHAIN) {
541 if (matches(*argv, "chain") != 0) {
542 fprintf(stderr, "\"chain index\" expected\n");
546 if (get_u32(&chain_index, *argv, 10) ||
547 chain_index > TC_ACT_EXT_VAL_MASK) {
548 fprintf(stderr, "Illegal \"chain index\"\n");
551 result |= chain_index;
553 if (result == TC_ACT_JUMP) {
557 if (get_u32(&jump_cnt, *argv, 10) ||
558 jump_cnt > TC_ACT_EXT_VAL_MASK) {
559 fprintf(stderr, "Invalid \"jump count\" (%s)\n", *argv);
571 /* Parse action control including possible options.
574 * @argc_p - pointer to argc to parse
575 * @argv_p - pointer to argv to parse
576 * @result_p - pointer to output variable
577 * @allow_num - whether action may be in numeric format already
579 * In error case, returns -1 and does not touch @result_1p. Otherwise returns 0.
581 int parse_action_control(int *argc_p, char ***argv_p,
582 int *result_p, bool allow_num)
584 return __parse_action_control(argc_p, argv_p, result_p,
588 /* Parse action control including possible options.
591 * @argc_p - pointer to argc to parse
592 * @argv_p - pointer to argv to parse
593 * @result_p - pointer to output variable
594 * @allow_num - whether action may be in numeric format already
595 * @default_result - set as a result in case of parsing error
597 * In case there is an error during parsing, the default result is used.
599 void parse_action_control_dflt(int *argc_p, char ***argv_p,
600 int *result_p, bool allow_num,
603 if (__parse_action_control(argc_p, argv_p, result_p, allow_num, true))
604 *result_p = default_result;
607 static int parse_action_control_slash_spaces(int *argc_p, char ***argv_p,
608 int *result1_p, int *result2_p,
612 char **argv = *argv_p;
613 int result1 = -1, result2;
614 int *result_p = &result1;
621 if (strcmp(*argv, "/") != 0)
626 case 0: /* fall-through */
628 ret = parse_action_control(&argc, &argv,
629 result_p, allow_num);
639 *result1_p = result1;
641 *result2_p = result2;
647 /* Parse action control with slash including possible options.
650 * @argc_p - pointer to argc to parse
651 * @argv_p - pointer to argv to parse
652 * @result1_p - pointer to the first (before slash) output variable
653 * @result2_p - pointer to the second (after slash) output variable
654 * @allow_num - whether action may be in numeric format already
656 * In error case, returns -1 and does not touch @result*. Otherwise returns 0.
658 int parse_action_control_slash(int *argc_p, char ***argv_p,
659 int *result1_p, int *result2_p, bool allow_num)
661 int result1, result2, argc = *argc_p;
662 char **argv = *argv_p;
663 char *p = strchr(*argv, '/');
666 return parse_action_control_slash_spaces(argc_p, argv_p,
667 result1_p, result2_p,
670 if (action_a2n(*argv, &result1, allow_num)) {
676 if (action_a2n(p + 1, &result2, allow_num))
679 *result1_p = result1;
680 *result2_p = result2;
687 void print_action_control(FILE *f, const char *prefix,
688 int action, const char *suffix)
690 print_string(PRINT_FP, NULL, "%s", prefix);
691 open_json_object("control_action");
692 print_string(PRINT_ANY, "type", "%s", action_n2a(action));
693 if (TC_ACT_EXT_CMP(action, TC_ACT_GOTO_CHAIN))
694 print_uint(PRINT_ANY, "chain", " chain %u",
695 action & TC_ACT_EXT_VAL_MASK);
696 if (TC_ACT_EXT_CMP(action, TC_ACT_JUMP))
697 print_uint(PRINT_ANY, "jump", " %u",
698 action & TC_ACT_EXT_VAL_MASK);
700 print_string(PRINT_FP, NULL, "%s", suffix);
703 int get_linklayer(unsigned int *val, const char *arg)
707 if (matches(arg, "ethernet") == 0)
708 res = LINKLAYER_ETHERNET;
709 else if (matches(arg, "atm") == 0)
711 else if (matches(arg, "adsl") == 0)
714 return -1; /* Indicate error */
720 static void print_linklayer(char *buf, int len, unsigned int linklayer)
723 case LINKLAYER_UNSPEC:
724 snprintf(buf, len, "%s", "unspec");
726 case LINKLAYER_ETHERNET:
727 snprintf(buf, len, "%s", "ethernet");
730 snprintf(buf, len, "%s", "atm");
733 snprintf(buf, len, "%s", "unknown");
738 char *sprint_linklayer(unsigned int linklayer, char *buf)
740 print_linklayer(buf, SPRINT_BSIZE-1, linklayer);
744 void print_tm(FILE *f, const struct tcf_t *tm)
746 int hz = get_user_hz();
748 if (tm->install != 0) {
749 print_uint(PRINT_JSON, "installed", NULL, tm->install);
750 print_uint(PRINT_FP, NULL, " installed %u sec",
751 (unsigned int)(tm->install/hz));
753 if (tm->lastuse != 0) {
754 print_uint(PRINT_JSON, "last_used", NULL, tm->lastuse);
755 print_uint(PRINT_FP, NULL, " used %u sec",
756 (unsigned int)(tm->lastuse/hz));
758 if (tm->expires != 0) {
759 print_uint(PRINT_JSON, "expires", NULL, tm->expires);
760 print_uint(PRINT_FP, NULL, " expires %u sec",
761 (unsigned int)(tm->expires/hz));
765 static void print_tcstats_basic_hw(struct rtattr **tbs, char *prefix)
767 struct gnet_stats_basic bs_hw;
769 if (!tbs[TCA_STATS_BASIC_HW])
772 memcpy(&bs_hw, RTA_DATA(tbs[TCA_STATS_BASIC_HW]),
773 MIN(RTA_PAYLOAD(tbs[TCA_STATS_BASIC_HW]), sizeof(bs_hw)));
775 if (bs_hw.bytes == 0 && bs_hw.packets == 0)
778 if (tbs[TCA_STATS_BASIC]) {
779 struct gnet_stats_basic bs;
781 memcpy(&bs, RTA_DATA(tbs[TCA_STATS_BASIC]),
782 MIN(RTA_PAYLOAD(tbs[TCA_STATS_BASIC]),
785 if (bs.bytes >= bs_hw.bytes && bs.packets >= bs_hw.packets) {
786 print_string(PRINT_FP, NULL, "%s", _SL_);
787 print_string(PRINT_FP, NULL, "%s", prefix);
788 print_lluint(PRINT_ANY, "sw_bytes",
789 "Sent software %llu bytes",
790 bs.bytes - bs_hw.bytes);
791 print_uint(PRINT_ANY, "sw_packets", " %u pkt",
792 bs.packets - bs_hw.packets);
796 print_string(PRINT_FP, NULL, "%s", _SL_);
797 print_string(PRINT_FP, NULL, "%s", prefix);
798 print_lluint(PRINT_ANY, "hw_bytes", "Sent hardware %llu bytes",
800 print_uint(PRINT_ANY, "hw_packets", " %u pkt", bs_hw.packets);
803 void print_tcstats2_attr(FILE *fp, struct rtattr *rta, char *prefix, struct rtattr **xstats)
806 struct rtattr *tbs[TCA_STATS_MAX + 1];
808 parse_rtattr_nested(tbs, TCA_STATS_MAX, rta);
810 if (tbs[TCA_STATS_BASIC]) {
811 struct gnet_stats_basic bs = {0};
814 if (tbs[TCA_STATS_PKT64])
815 packets64 = rta_getattr_u64(tbs[TCA_STATS_PKT64]);
817 memcpy(&bs, RTA_DATA(tbs[TCA_STATS_BASIC]),
818 MIN(RTA_PAYLOAD(tbs[TCA_STATS_BASIC]), sizeof(bs)));
819 print_string(PRINT_FP, NULL, "%s", prefix);
820 print_lluint(PRINT_ANY, "bytes", "Sent %llu bytes", bs.bytes);
822 print_lluint(PRINT_ANY, "packets",
823 " %llu pkt", packets64);
825 print_uint(PRINT_ANY, "packets",
826 " %u pkt", bs.packets);
829 if (tbs[TCA_STATS_QUEUE]) {
830 struct gnet_stats_queue q = {0};
832 memcpy(&q, RTA_DATA(tbs[TCA_STATS_QUEUE]),
833 MIN(RTA_PAYLOAD(tbs[TCA_STATS_QUEUE]), sizeof(q)));
834 print_uint(PRINT_ANY, "drops", " (dropped %u", q.drops);
835 print_uint(PRINT_ANY, "overlimits", ", overlimits %u",
837 print_uint(PRINT_ANY, "requeues", " requeues %u) ", q.requeues);
840 if (tbs[TCA_STATS_BASIC_HW])
841 print_tcstats_basic_hw(tbs, prefix);
843 if (tbs[TCA_STATS_RATE_EST64]) {
844 struct gnet_stats_rate_est64 re = {0};
846 memcpy(&re, RTA_DATA(tbs[TCA_STATS_RATE_EST64]),
847 MIN(RTA_PAYLOAD(tbs[TCA_STATS_RATE_EST64]),
849 print_string(PRINT_FP, NULL, "\n%s", prefix);
850 print_lluint(PRINT_JSON, "rate", NULL, re.bps);
851 print_string(PRINT_FP, NULL, "rate %s",
852 sprint_rate(re.bps, b1));
853 print_lluint(PRINT_ANY, "pps", " %llupps", re.pps);
854 } else if (tbs[TCA_STATS_RATE_EST]) {
855 struct gnet_stats_rate_est re = {0};
857 memcpy(&re, RTA_DATA(tbs[TCA_STATS_RATE_EST]),
858 MIN(RTA_PAYLOAD(tbs[TCA_STATS_RATE_EST]), sizeof(re)));
859 print_string(PRINT_FP, NULL, "\n%s", prefix);
860 print_uint(PRINT_JSON, "rate", NULL, re.bps);
861 print_string(PRINT_FP, NULL, "rate %s",
862 sprint_rate(re.bps, b1));
863 print_uint(PRINT_ANY, "pps", " %upps", re.pps);
866 if (tbs[TCA_STATS_QUEUE]) {
867 struct gnet_stats_queue q = {0};
869 memcpy(&q, RTA_DATA(tbs[TCA_STATS_QUEUE]),
870 MIN(RTA_PAYLOAD(tbs[TCA_STATS_QUEUE]), sizeof(q)));
871 if (!tbs[TCA_STATS_RATE_EST])
872 print_string(PRINT_FP, NULL, "\n", "");
873 print_uint(PRINT_JSON, "backlog", NULL, q.backlog);
874 print_string(PRINT_FP, NULL, "%s", prefix);
875 print_string(PRINT_FP, NULL, "backlog %s",
876 sprint_size(q.backlog, b1));
877 print_uint(PRINT_ANY, "qlen", " %up", q.qlen);
878 print_uint(PRINT_FP, NULL, " requeues %u", q.requeues);
882 *xstats = tbs[TCA_STATS_APP] ? : NULL;
885 void print_tcstats_attr(FILE *fp, struct rtattr *tb[], char *prefix,
886 struct rtattr **xstats)
890 if (tb[TCA_STATS2]) {
891 print_tcstats2_attr(fp, tb[TCA_STATS2], prefix, xstats);
892 if (xstats && !*xstats)
896 /* backward compatibility */
898 struct tc_stats st = {};
900 /* handle case where kernel returns more/less than we know about */
901 memcpy(&st, RTA_DATA(tb[TCA_STATS]),
902 MIN(RTA_PAYLOAD(tb[TCA_STATS]), sizeof(st)));
905 "%sSent %llu bytes %u pkts (dropped %u, overlimits %u) ",
906 prefix, (unsigned long long)st.bytes,
907 st.packets, st.drops, st.overlimits);
909 if (st.bps || st.pps || st.qlen || st.backlog) {
910 fprintf(fp, "\n%s", prefix);
911 if (st.bps || st.pps) {
912 fprintf(fp, "rate ");
915 sprint_rate(st.bps, b1));
917 fprintf(fp, "%upps ", st.pps);
919 if (st.qlen || st.backlog) {
920 fprintf(fp, "backlog ");
923 sprint_size(st.backlog, b1));
925 fprintf(fp, "%up ", st.qlen);
931 if (tb[TCA_XSTATS] && xstats)
932 *xstats = tb[TCA_XSTATS];
935 static void print_masked_type(__u32 type_max,
936 __u32 (*rta_getattr_type)(const struct rtattr *),
937 const char *name, struct rtattr *attr,
938 struct rtattr *mask_attr, bool newline)
948 value = rta_getattr_type(attr);
949 mask = mask_attr ? rta_getattr_type(mask_attr) : type_max;
951 if (is_json_context()) {
952 sprintf(namefrm, "\n %s %%u", name);
953 print_hu(PRINT_ANY, name, namefrm,
954 rta_getattr_type(attr));
955 if (mask != type_max) {
956 char mask_name[SPRINT_BSIZE-6];
958 sprintf(mask_name, "%s_mask", name);
960 print_string(PRINT_FP, NULL, "%s ", _SL_);
961 sprintf(namefrm, " %s %%u", mask_name);
962 print_hu(PRINT_ANY, mask_name, namefrm, mask);
965 done = sprintf(out, "%u", value);
966 if (mask != type_max)
967 sprintf(out + done, "/0x%x", mask);
969 print_string(PRINT_FP, NULL, "%s ", _SL_);
970 sprintf(namefrm, " %s %%s", name);
971 print_string(PRINT_ANY, name, namefrm, out);
975 void print_masked_u32(const char *name, struct rtattr *attr,
976 struct rtattr *mask_attr, bool newline)
978 print_masked_type(UINT32_MAX, rta_getattr_u32, name, attr, mask_attr,
982 static __u32 __rta_getattr_u16_u32(const struct rtattr *attr)
984 return rta_getattr_u16(attr);
987 void print_masked_u16(const char *name, struct rtattr *attr,
988 struct rtattr *mask_attr, bool newline)
990 print_masked_type(UINT16_MAX, __rta_getattr_u16_u32, name, attr,
994 static __u32 __rta_getattr_u8_u32(const struct rtattr *attr)
996 return rta_getattr_u8(attr);
999 void print_masked_u8(const char *name, struct rtattr *attr,
1000 struct rtattr *mask_attr, bool newline)
1002 print_masked_type(UINT8_MAX, __rta_getattr_u8_u32, name, attr,
1003 mask_attr, newline);
1006 static __u32 __rta_getattr_be16_u32(const struct rtattr *attr)
1008 return rta_getattr_be16(attr);
1011 void print_masked_be16(const char *name, struct rtattr *attr,
1012 struct rtattr *mask_attr, bool newline)
1014 print_masked_type(UINT16_MAX, __rta_getattr_be16_u32, name, attr,
1015 mask_attr, newline);