oops
[libnl.git] / lib / route / tc.c
1 /*
2  * lib/route/tc.c               Traffic Control
3  *
4  *      This library is free software; you can redistribute it and/or
5  *      modify it under the terms of the GNU Lesser General Public
6  *      License as published by the Free Software Foundation version 2.1
7  *      of the License.
8  *
9  * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
10  */
11
12 /**
13  * @ingroup rtnl
14  * @defgroup tc Traffic Control
15  * @brief
16  * @{
17  */
18
19 #include <netlink-local.h>
20 #include <netlink-tc.h>
21 #include <netlink/netlink.h>
22 #include <netlink/utils.h>
23 #include <netlink/route/rtnl.h>
24 #include <netlink/route/link.h>
25 #include <netlink/route/tc.h>
26
27 /** @cond SKIP */
28
29 static struct nla_policy tc_policy[TCA_MAX+1] = {
30         [TCA_KIND]      = { .type = NLA_STRING,
31                             .maxlen = TCKINDSIZ },
32         [TCA_STATS]     = { .minlen = sizeof(struct tc_stats) },
33         [TCA_STATS2]    = { .type = NLA_NESTED },
34 };
35
36 int tca_parse(struct nlattr **tb, int maxattr, struct rtnl_tca *g,
37               struct nla_policy *policy)
38 {
39         
40         if (g->tc_mask & TCA_ATTR_OPTS)
41                 return nla_parse(tb, maxattr,
42                                  (struct nlattr *) g->tc_opts->d_data,
43                                  g->tc_opts->d_size, policy);
44         else {
45                 /* Ugly but tb[] must be in a defined state even if no
46                  * attributes can be found. */
47                 memset(tb, 0, sizeof(struct nlattr *) * (maxattr + 1));
48                 return 0;
49         }
50 }
51
52 static struct nla_policy tc_stats2_policy[TCA_STATS_MAX+1] = {
53         [TCA_STATS_BASIC]    = { .minlen = sizeof(struct gnet_stats_basic) },
54         [TCA_STATS_RATE_EST] = { .minlen = sizeof(struct gnet_stats_rate_est) },
55         [TCA_STATS_QUEUE]    = { .minlen = sizeof(struct gnet_stats_queue) },
56 };
57
58 int tca_msg_parser(struct nlmsghdr *n, struct rtnl_tca *g)
59 {
60         struct nlattr *tb[TCA_MAX + 1];
61         struct tcmsg *tm;
62         int err;
63
64         err = nlmsg_parse(n, sizeof(*tm), tb, TCA_MAX, tc_policy);
65         if (err < 0)
66                 return err;
67
68         if (tb[TCA_KIND] == NULL)
69                 return nl_error(EINVAL, "Missing tca kind TLV");
70
71         nla_strlcpy(g->tc_kind, tb[TCA_KIND], TCKINDSIZ);
72
73         tm = nlmsg_data(n);
74         g->tc_family  = tm->tcm_family;
75         g->tc_ifindex = tm->tcm_ifindex;
76         g->tc_handle  = tm->tcm_handle;
77         g->tc_parent  = tm->tcm_parent;
78         g->tc_info    = tm->tcm_info;
79
80         g->tc_mask = (TCA_ATTR_FAMILY|TCA_ATTR_IFINDEX|TCA_ATTR_HANDLE|
81                 TCA_ATTR_PARENT|TCA_ATTR_INFO|TCA_ATTR_KIND);
82
83         if (tb[TCA_OPTIONS]) {
84                 g->tc_opts = nla_get_data(tb[TCA_OPTIONS]);
85                 if (!g->tc_opts)
86                         return nl_errno(ENOMEM);
87                 g->tc_mask |= TCA_ATTR_OPTS;
88         }
89         
90
91         if (tb[TCA_STATS2]) {
92                 struct nlattr *tbs[TCA_STATS_MAX + 1];
93
94                 err = nla_parse_nested(tbs, TCA_STATS_MAX, tb[TCA_STATS2],
95                                        tc_stats2_policy);
96                 if (err < 0)
97                         return err;
98
99                 if (tbs[TCA_STATS_BASIC]) {
100                         struct gnet_stats_basic *bs;
101                         
102                         bs = nla_data(tbs[TCA_STATS_BASIC]);
103                         g->tc_stats[RTNL_TC_BYTES]      = bs->bytes;
104                         g->tc_stats[RTNL_TC_PACKETS]    = bs->packets;
105                 }
106
107                 if (tbs[TCA_STATS_RATE_EST]) {
108                         struct gnet_stats_rate_est *re;
109
110                         re = nla_data(tbs[TCA_STATS_RATE_EST]);
111                         g->tc_stats[RTNL_TC_RATE_BPS]   = re->bps;
112                         g->tc_stats[RTNL_TC_RATE_PPS]   = re->pps;
113                 }
114                 
115                 if (tbs[TCA_STATS_QUEUE]) {
116                         struct gnet_stats_queue *q;
117
118                         q = nla_data(tbs[TCA_STATS_QUEUE]);
119                         g->tc_stats[RTNL_TC_QLEN]       = q->qlen;
120                         g->tc_stats[RTNL_TC_BACKLOG]    = q->backlog;
121                         g->tc_stats[RTNL_TC_DROPS]      = q->drops;
122                         g->tc_stats[RTNL_TC_REQUEUES]   = q->requeues;
123                         g->tc_stats[RTNL_TC_OVERLIMITS] = q->overlimits;
124                 }
125
126                 g->tc_mask |= TCA_ATTR_STATS;
127                 
128                 if (tbs[TCA_STATS_APP]) {
129                         g->tc_xstats = nla_get_data(tbs[TCA_STATS_APP]);
130                         if (g->tc_xstats == NULL)
131                                 return -ENOMEM;
132                 } else
133                         goto compat_xstats;
134         } else {
135                 if (tb[TCA_STATS]) {
136                         struct tc_stats *st = nla_data(tb[TCA_STATS]);
137
138                         g->tc_stats[RTNL_TC_BYTES]      = st->bytes;
139                         g->tc_stats[RTNL_TC_PACKETS]    = st->packets;
140                         g->tc_stats[RTNL_TC_RATE_BPS]   = st->bps;
141                         g->tc_stats[RTNL_TC_RATE_PPS]   = st->pps;
142                         g->tc_stats[RTNL_TC_QLEN]       = st->qlen;
143                         g->tc_stats[RTNL_TC_BACKLOG]    = st->backlog;
144                         g->tc_stats[RTNL_TC_DROPS]      = st->drops;
145                         g->tc_stats[RTNL_TC_OVERLIMITS] = st->overlimits;
146
147                         g->tc_mask |= TCA_ATTR_STATS;
148                 }
149
150 compat_xstats:
151                 if (tb[TCA_XSTATS]) {
152                         g->tc_xstats = nla_get_data(tb[TCA_XSTATS]);
153                         if (g->tc_xstats == NULL)
154                                 return -ENOMEM;
155                         g->tc_mask |= TCA_ATTR_XSTATS;
156                 }
157         }
158
159
160         return 0;
161 }
162
163 void tca_free_data(struct rtnl_tca *tca)
164 {
165         nl_data_free(tca->tc_opts);
166         nl_data_free(tca->tc_xstats);
167 }
168
169 int tca_dump_brief(struct rtnl_tca *g, const char *type,
170                    struct nl_dump_params *p, int line)
171 {
172         char handle[32], parent[32];
173         struct nl_cache *link_cache;
174         
175         link_cache = nl_cache_mngt_require("route/link");
176
177         dp_dump(p, "%s %s ", g->tc_kind, type);
178
179         if (link_cache) {
180                 char buf[32];
181                 dp_dump(p, "dev %s ",
182                         rtnl_link_i2name(link_cache, g->tc_ifindex,
183                                          buf, sizeof(buf)));
184         } else
185                 dp_dump(p, "dev %u ", g->tc_ifindex);
186         
187         dp_dump(p, "handle %s parent %s",
188                 rtnl_tc_handle2str(g->tc_handle, handle, sizeof(handle)),
189                 rtnl_tc_handle2str(g->tc_parent, parent, sizeof(parent)));
190
191         return 1;
192 }
193
194 int tca_dump_full(struct rtnl_tca *g, struct nl_dump_params *p, int line)
195 {
196         dp_dump_line(p, line++, "  ");
197         return line;
198 }
199
200 int tca_dump_stats(struct rtnl_tca *g, struct nl_dump_params *p, int line)
201 {
202         char *unit, fmt[64];
203         float res;
204         strcpy(fmt, "        %7.2f %s %10u %10u %10u %10u %10u\n");
205
206         dp_dump_line(p, line++,
207                 "    Stats:    bytes    packets      drops overlimits" \
208                 "       qlen    backlog\n");
209
210         res = nl_cancel_down_bytes(g->tc_stats[RTNL_TC_BYTES], &unit);
211         if (*unit == 'B')
212                 fmt[11] = '9';
213
214         dp_dump_line(p, line++, fmt, res, unit,
215                 g->tc_stats[RTNL_TC_PACKETS],
216                 g->tc_stats[RTNL_TC_DROPS],
217                 g->tc_stats[RTNL_TC_OVERLIMITS],
218                 g->tc_stats[RTNL_TC_QLEN],
219                 g->tc_stats[RTNL_TC_BACKLOG]);
220
221         res = nl_cancel_down_bytes(g->tc_stats[RTNL_TC_RATE_BPS], &unit);
222
223         strcpy(fmt, "        %7.2f %s/s%9u pps");
224
225         if (*unit == 'B')
226                 fmt[11] = '9';
227
228         dp_dump_line(p, line++, fmt, res, unit, g->tc_stats[RTNL_TC_RATE_PPS]);
229
230         return line;
231 }
232
233 int tca_filter(struct rtnl_tca *o, struct rtnl_tca *f)
234 {
235 #define REQ(F) (f->tc_mask & TCA_ATTR_##F)
236 #define AVAIL(F) (o->tc_mask & TCA_ATTR_##F)
237 #define _O(F, EXPR) (REQ(F) && (!AVAIL(F) || (EXPR)))
238 #define _C(F, N) (REQ(F) && (!AVAIL(F) || (o->N != f->N)))
239         if (_C(HANDLE,  tc_handle)                      ||
240             _C(PARENT,  tc_parent)                      ||
241             _C(IFINDEX, tc_ifindex)                     ||
242             _O(KIND,    strcmp(o->tc_kind, f->tc_kind)))
243                 return 0;
244 #undef REQ
245 #undef AVAIL
246 #undef _O
247 #undef _C
248
249         return 1;
250 }
251
252 void tca_set_ifindex(struct rtnl_tca *t, int ifindex)
253 {
254         t->tc_ifindex = ifindex;
255         t->tc_mask |= TCA_ATTR_IFINDEX;
256 }
257
258 int tca_get_ifindex(struct rtnl_tca *t)
259 {
260         if (t->tc_mask & TCA_ATTR_IFINDEX)
261                 return t->tc_ifindex;
262         else
263                 return RTNL_LINK_NOT_FOUND;
264 }
265
266 void tca_set_handle(struct rtnl_tca *t, uint32_t handle)
267 {
268         t->tc_handle = handle;
269         t->tc_mask |= TCA_ATTR_HANDLE;
270 }
271
272 uint32_t tca_get_handle(struct rtnl_tca *t)
273 {
274         if (t->tc_mask & TCA_ATTR_HANDLE)
275                 return t->tc_handle;
276         else
277                 return 0;
278 }
279
280 void tca_set_parent(struct rtnl_tca *t, uint32_t parent)
281 {
282         t->tc_parent = parent;
283         t->tc_mask |= TCA_ATTR_PARENT;
284 }
285
286 uint32_t tca_get_parent(struct rtnl_tca *t)
287 {
288         if (t->tc_mask & TCA_ATTR_PARENT)
289                 return t->tc_parent;
290         else
291                 return 0;
292 }
293
294 void tca_set_kind(struct rtnl_tca *t, const char *kind)
295 {
296         strncpy(t->tc_kind, kind, sizeof(t->tc_kind) - 1);
297         t->tc_mask |= TCA_ATTR_KIND;
298 }
299
300 char *tca_get_kind(struct rtnl_tca *t)
301 {
302         if (t->tc_mask & TCA_ATTR_KIND)
303                 return t->tc_kind;
304         else
305                 return NULL;
306 }
307
308 uint64_t tca_get_stat(struct rtnl_tca *t, int id)
309 {
310         if (id < 0 || id > RTNL_TC_STATS_MAX)
311                 return 0;
312
313         return t->tc_stats[id];
314 }
315
316 struct nl_msg *tca_build_msg(struct rtnl_tca *tca, int type, int flags)
317 {
318         struct nl_msg *msg;
319         struct tcmsg tchdr = {
320                 .tcm_family = AF_UNSPEC,
321                 .tcm_ifindex = tca->tc_ifindex,
322                 .tcm_handle = tca->tc_handle,
323                 .tcm_parent = tca->tc_parent,
324         };
325
326         msg = nlmsg_build_simple(type, flags);
327         if (!msg)
328                 goto nla_put_failure;
329
330         if (nlmsg_append(msg, &tchdr, sizeof(tchdr), 1) < 0)
331                 goto nla_put_failure;
332
333         if (tca->tc_mask & TCA_ATTR_KIND)
334             NLA_PUT_STRING(msg, TCA_KIND, tca->tc_kind);
335
336         return msg;
337
338 nla_put_failure:
339         nlmsg_free(msg);
340         return NULL;
341 }
342
343 /** @endcond */
344
345 /**
346  * @name Utilities
347  * @{
348  */
349
350 /**
351  * Calculate time required to transmit buffer at a specific rate
352  * @arg bufsize         Size of buffer to be transmited in bytes.
353  * @arg rate            Transmit rate in bytes per second.
354  *
355  * Calculates the number of micro seconds required to transmit a
356  * specific buffer at a specific transmit rate.
357  *
358  * @f[
359  *   txtime=\frac{bufsize}{rate}10^6
360  * @f]
361  * 
362  * @return Required transmit time in micro seconds.
363  */
364 int rtnl_tc_calc_txtime(int bufsize, int rate)
365 {
366         double tx_time_secs;
367         
368         tx_time_secs = (double) bufsize / (double) rate;
369
370         return tx_time_secs * 1000000.;
371 }
372
373 /**
374  * Calculate buffer size able to transmit in a specific time and rate.
375  * @arg txtime          Available transmit time in micro seconds.
376  * @arg rate            Transmit rate in bytes per second.
377  *
378  * Calculates the size of the buffer that can be transmitted in a
379  * specific time period at a specific transmit rate.
380  *
381  * @f[
382  *   bufsize=\frac{{txtime} \times {rate}}{10^6}
383  * @f]
384  *
385  * @return Size of buffer in bytes.
386  */
387 int rtnl_tc_calc_bufsize(int txtime, int rate)
388 {
389         double bufsize;
390
391         bufsize = (double) txtime * (double) rate;
392
393         return bufsize / 1000000.;
394 }
395
396 /**
397  * Calculate the binary logarithm for a specific cell size
398  * @arg cell_size       Size of cell, must be a power of two.
399  * @return Binary logirhtm of cell size or a negative error code.
400  */
401 int rtnl_tc_calc_cell_log(int cell_size)
402 {
403         int i;
404
405         for (i = 0; i < 32; i++)
406                 if ((1 << i) == cell_size)
407                         return i;
408
409         return nl_errno(EINVAL);
410 }
411
412
413 /** @} */
414
415 /**
416  * @name Rate Tables
417  * @{
418  */
419
420 /**
421  * Compute a transmission time lookup table
422  * @arg dst      Destination buffer of RTNL_TC_RTABLE_SIZE uint32_t[].
423  * @arg mpu      Minimal size of a packet at all times.
424  * @arg overhead Overhead to be added to each packet.
425  * @arg cell     Size of cell, i.e. size of step between entries in bytes.
426  * @arg rate     Rate in bytes per second.
427  *
428  * Computes a table of RTNL_TC_RTABLE_SIZE entries specyfing the
429  * transmission times for various packet sizes, e.g. the transmission
430  * time for a packet of size \c pktsize could be looked up:
431  * @code
432  * txtime = table[pktsize >> log2(cell)];
433  * @endcode
434  */
435 int rtnl_tc_build_rate_table(uint32_t *dst, uint8_t mpu, uint8_t overhead,
436                              int cell, int rate)
437 {
438         int i, size, cell_log;
439
440         cell_log = rtnl_tc_calc_cell_log(cell);
441         if (cell_log < 0)
442                 return cell_log;
443
444         for (i = 0; i < RTNL_TC_RTABLE_SIZE; i++) {
445                 size = (i << cell_log) + overhead;
446                 if (size < mpu)
447                         size = mpu;
448
449                 dst[i] = rtnl_tc_calc_txtime(size, rate);
450         }
451
452         return 0;
453 }
454
455 /** @} */
456
457 /**
458  * @name Traffic Control Handle Translations
459  * @{
460  */
461
462 /**
463  * Convert a traffic control handle to a character string (Reentrant).
464  * @arg handle          traffic control handle
465  * @arg buf             destination buffer
466  * @arg len             buffer length
467  *
468  * Converts a tarffic control handle to a character string in the
469  * form of \c MAJ:MIN and stores it in the specified destination buffer.
470  *
471  * @return The destination buffer or the type encoded in hexidecimal
472  *         form if no match was found.
473  */
474 char * rtnl_tc_handle2str(uint32_t handle, char *buf, size_t len)
475 {
476         if (TC_H_ROOT == handle)
477                 snprintf(buf, len, "root");
478         else if (TC_H_UNSPEC == handle)
479                 snprintf(buf, len, "none");
480         else if (0 == TC_H_MAJ(handle))
481                 snprintf(buf, len, ":%02x", TC_H_MIN(handle));
482         else if (0 == TC_H_MIN(handle))
483                 snprintf(buf, len, "%02x:", TC_H_MAJ(handle) >> 16);
484         else
485                 snprintf(buf, len, "%02x:%02x",
486                         TC_H_MAJ(handle) >> 16, TC_H_MIN(handle));
487
488         return buf;
489 }
490
491 /**
492  * Convert a charactering strint to a traffic control handle
493  * @arg name            traffic control handle as character string
494  * @arg res             destination buffer
495  *
496  * Converts the provided character string specifying a traffic
497  * control handle to the corresponding numeric value.
498  *
499  * The handle must be provided in one of the following formats:
500  *  - root
501  *  - none
502  *  - XXXX:
503  *  - :YYYY
504  *  - XXXX:YYYY
505  *  - XXXXYYYY
506  *
507  * @return 0 on success or a negative error code
508  */
509 int rtnl_tc_str2handle(const char *name, uint32_t *res)
510 {
511         char *colon, *end;
512         uint32_t h;
513
514         if (!strcasecmp(name, "root")) {
515                 *res = TC_H_ROOT;
516                 return 0;
517         }
518
519         if (!strcasecmp(name, "none")) {
520                 *res = TC_H_UNSPEC;
521                 return 0;
522         }
523
524         h = strtoul(name, &colon, 16);
525
526         if (colon == name) {
527                 /* :YYYY */
528                 h = 0;
529                 if (':' != *colon)
530                         return -EINVAL;
531         }
532
533         if (':' == *colon) {
534                 /* check if we would lose bits */
535                 if (TC_H_MAJ(h))
536                         return -ERANGE;
537                 h <<= 16;
538
539                 if ('\0' == colon[1]) {
540                         /* XXXX: */
541                         *res = h;
542                 } else {
543                         /* XXXX:YYYY */
544                         uint32_t l = strtoul(colon+1, &end, 16);
545
546                         /* check if we overlap with major part */
547                         if (TC_H_MAJ(l))
548                                 return -ERANGE;
549
550                         if ('\0' != *end)
551                                 return -EINVAL;
552
553                         *res = (h | l);
554                 }
555         } else if ('\0' == *colon) {
556                 /* XXXXYYYY */
557                 *res = h;
558         } else
559                 return -EINVAL;
560
561         return 0;
562 }
563
564 /** @} */
565
566 /** @} */