1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2019 Facebook
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
8 * Example program for Host Bandwidth Managment
10 * This program loads a cgroup skb BPF program to enforce cgroup output
11 * (egress) or input (ingress) bandwidth limits.
13 * USAGE: hbm [-d] [-l] [-n <id>] [-r <rate>] [-s] [-t <secs>] [-w] [-h] [prog]
15 * -d Print BPF trace debug buffer
16 * -l Also limit flows doing loopback
17 * -n <#> To create cgroup \"/hbm#\" and attach prog
19 * --no_cn Do not return cn notifications
20 * -r <rate> Rate limit in Mbps
21 * -s Get HBM stats (marked, dropped, etc.)
22 * -t <time> Exit after specified seconds (default is 0)
23 * -w Work conserving flag. cgroup can increase its bandwidth
24 * beyond the rate limit specified while there is available
25 * bandwidth. Current implementation assumes there is only
26 * NIC (eth0), but can be extended to support multiple NICs.
27 * Currrently only supported for egress.
29 * prog BPF program file name. Name defaults to hbm_out_kern.o
37 #include <sys/resource.h>
42 #include <linux/unistd.h>
44 #include <linux/bpf.h>
49 #include "bpf_rlimit.h"
50 #include "cgroup_helpers.h"
57 int minRate = 1000; /* cgroup rate limit in Mbps */
58 int rate = 1000; /* can grow if rate conserving is enabled */
63 bool work_conserving_flag;
66 static void Usage(void);
67 static void read_trace_pipe2(void);
68 static void do_error(char *msg, bool errno_flag);
70 #define DEBUGFS "/sys/kernel/debug/tracing/"
72 struct bpf_object *obj;
74 int cgroup_storage_fd;
76 static void read_trace_pipe2(void)
80 char *outFname = "hbm_out.log";
82 trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
84 printf("Error opening trace_pipe\n");
88 // Future support of ingress
90 // outFname = "hbm_in.log";
91 outf = fopen(outFname, "w");
94 printf("Error creating %s\n", outFname);
97 static char buf[4097];
100 sz = read(trace_fd, buf, sizeof(buf) - 1);
105 fprintf(outf, "%s\n", buf);
112 static void do_error(char *msg, bool errno_flag)
115 printf("ERROR: %s, errno: %d\n", msg, errno);
117 printf("ERROR: %s\n", msg);
121 static int prog_load(char *prog)
123 struct bpf_prog_load_attr prog_load_attr = {
124 .prog_type = BPF_PROG_TYPE_CGROUP_SKB,
126 .expected_attach_type = BPF_CGROUP_INET_EGRESS,
133 if (access(prog, O_RDONLY) < 0) {
134 printf("Error accessing file %s: %s\n", prog, strerror(errno));
137 if (bpf_prog_load_xattr(&prog_load_attr, &obj, &bpfprog_fd))
140 map = bpf_object__find_map_by_name(obj, "queue_stats");
141 map_fd = bpf_map__fd(map);
143 printf("Map not found: %s\n", strerror(map_fd));
149 printf("ERROR: load_bpf_file failed for: %s\n", prog);
150 printf(" Output from verifier:\n%s\n------\n", bpf_log_buf);
159 static int run_bpf_prog(char *prog, int cg_id)
165 int type = BPF_CGROUP_INET_EGRESS;
167 struct hbm_queue_stats qstats = {0};
169 sprintf(cg_dir, "/hbm%d", cg_id);
170 map_fd = prog_load(prog);
174 if (setup_cgroup_environment()) {
175 printf("ERROR: setting cgroup environment\n");
178 cg1 = create_and_get_cgroup(cg_dir);
180 printf("ERROR: create_and_get_cgroup\n");
183 if (join_cgroup(cg_dir)) {
184 printf("ERROR: join_cgroup\n");
189 qstats.stats = stats_flag ? 1 : 0;
190 qstats.loopback = loopback_flag ? 1 : 0;
191 qstats.no_cn = no_cn_flag ? 1 : 0;
192 if (bpf_map_update_elem(map_fd, &key, &qstats, BPF_ANY)) {
193 printf("ERROR: Could not update map element\n");
198 type = BPF_CGROUP_INET_INGRESS;
199 if (bpf_prog_attach(bpfprog_fd, cg1, type, 0)) {
200 printf("ERROR: bpf_prog_attach fails!\n");
201 log_err("Attaching prog");
205 if (work_conserving_flag) {
206 struct timeval t0, t_last, t_new;
208 unsigned long long last_eth_tx_bytes, new_eth_tx_bytes;
209 signed long long last_cg_tx_bytes, new_cg_tx_bytes;
210 signed long long delta_time, delta_bytes, delta_rate;
212 #define DELTA_RATE_CHECK 10000 /* in us */
213 #define RATE_THRESHOLD 9500000000 /* 9.5 Gbps */
215 bpf_map_lookup_elem(map_fd, &key, &qstats);
216 if (gettimeofday(&t0, NULL) < 0)
217 do_error("gettimeofday failed", true);
219 fin = fopen("/sys/class/net/eth0/statistics/tx_bytes", "r");
220 if (fscanf(fin, "%llu", &last_eth_tx_bytes) != 1)
221 do_error("fscanf fails", false);
223 last_cg_tx_bytes = qstats.bytes_total;
225 usleep(DELTA_RATE_CHECK);
226 if (gettimeofday(&t_new, NULL) < 0)
227 do_error("gettimeofday failed", true);
228 delta_ms = (t_new.tv_sec - t0.tv_sec) * 1000 +
229 (t_new.tv_usec - t0.tv_usec)/1000;
230 if (delta_ms > dur * 1000)
232 delta_time = (t_new.tv_sec - t_last.tv_sec) * 1000000 +
233 (t_new.tv_usec - t_last.tv_usec);
237 fin = fopen("/sys/class/net/eth0/statistics/tx_bytes",
239 if (fscanf(fin, "%llu", &new_eth_tx_bytes) != 1)
240 do_error("fscanf fails", false);
242 printf(" new_eth_tx_bytes:%llu\n",
244 bpf_map_lookup_elem(map_fd, &key, &qstats);
245 new_cg_tx_bytes = qstats.bytes_total;
246 delta_bytes = new_eth_tx_bytes - last_eth_tx_bytes;
247 last_eth_tx_bytes = new_eth_tx_bytes;
248 delta_rate = (delta_bytes * 8000000) / delta_time;
249 printf("%5d - eth_rate:%.1fGbps cg_rate:%.3fGbps",
250 delta_ms, delta_rate/1000000000.0,
252 if (delta_rate < RATE_THRESHOLD) {
253 /* can increase cgroup rate limit, but first
254 * check if we are using the current limit.
255 * Currently increasing by 6.25%, unknown
256 * if that is the optimal rate.
260 delta_bytes = new_cg_tx_bytes -
262 last_cg_tx_bytes = new_cg_tx_bytes;
263 delta_rate = (delta_bytes * 8000000) /
265 printf(" rate:%.3fGbps",
266 delta_rate/1000000000.0);
267 rate_diff100 = (((long long)rate)*1000000 -
269 (((long long) rate) * 1000000);
270 printf(" rdiff:%d", rate_diff100);
271 if (rate_diff100 <= 3) {
273 if (rate > RATE_THRESHOLD / 1000000)
274 rate = RATE_THRESHOLD / 1000000;
281 /* Need to decrease cgroup rate limit.
282 * Currently decreasing by 12.5%, unknown
291 if (bpf_map_update_elem(map_fd, &key, &qstats, BPF_ANY))
292 do_error("update map element fails", false);
298 if (stats_flag && bpf_map_lookup_elem(map_fd, &key, &qstats)) {
303 sprintf(fname, "hbm.%d.in", cg_id);
305 sprintf(fname, "hbm.%d.out", cg_id);
306 fout = fopen(fname, "w");
307 fprintf(fout, "id:%d\n", cg_id);
308 fprintf(fout, "ERROR: Could not lookup queue_stats\n");
309 } else if (stats_flag && qstats.lastPacketTime >
310 qstats.firstPacketTime) {
311 long long delta_us = (qstats.lastPacketTime -
312 qstats.firstPacketTime)/1000;
313 unsigned int rate_mbps = ((qstats.bytes_total -
314 qstats.bytes_dropped) * 8 /
316 double percent_pkts, percent_bytes;
320 static const char *returnValNames[] = {
326 #define RET_VAL_COUNT 4
328 // Future support of ingress
330 // sprintf(fname, "hbm.%d.in", cg_id);
332 sprintf(fname, "hbm.%d.out", cg_id);
333 fout = fopen(fname, "w");
334 fprintf(fout, "id:%d\n", cg_id);
335 fprintf(fout, "rate_mbps:%d\n", rate_mbps);
336 fprintf(fout, "duration:%.1f secs\n",
337 (qstats.lastPacketTime - qstats.firstPacketTime) /
339 fprintf(fout, "packets:%d\n", (int)qstats.pkts_total);
340 fprintf(fout, "bytes_MB:%d\n", (int)(qstats.bytes_total /
342 fprintf(fout, "pkts_dropped:%d\n", (int)qstats.pkts_dropped);
343 fprintf(fout, "bytes_dropped_MB:%d\n",
344 (int)(qstats.bytes_dropped /
346 // Marked Pkts and Bytes
347 percent_pkts = (qstats.pkts_marked * 100.0) /
348 (qstats.pkts_total + 1);
349 percent_bytes = (qstats.bytes_marked * 100.0) /
350 (qstats.bytes_total + 1);
351 fprintf(fout, "pkts_marked_percent:%6.2f\n", percent_pkts);
352 fprintf(fout, "bytes_marked_percent:%6.2f\n", percent_bytes);
354 // Dropped Pkts and Bytes
355 percent_pkts = (qstats.pkts_dropped * 100.0) /
356 (qstats.pkts_total + 1);
357 percent_bytes = (qstats.bytes_dropped * 100.0) /
358 (qstats.bytes_total + 1);
359 fprintf(fout, "pkts_dropped_percent:%6.2f\n", percent_pkts);
360 fprintf(fout, "bytes_dropped_percent:%6.2f\n", percent_bytes);
363 percent_pkts = (qstats.pkts_ecn_ce * 100.0) /
364 (qstats.pkts_total + 1);
365 fprintf(fout, "pkts_ecn_ce:%6.2f (%d)\n", percent_pkts,
366 (int)qstats.pkts_ecn_ce);
369 fprintf(fout, "avg cwnd:%d\n",
370 (int)(qstats.sum_cwnd / (qstats.sum_cwnd_cnt + 1)));
372 fprintf(fout, "avg rtt:%d\n",
373 (int)(qstats.sum_rtt / (qstats.pkts_total + 1)));
375 fprintf(fout, "avg credit:%d\n",
376 (int)(qstats.sum_credit /
377 (1500 * ((int)qstats.pkts_total) + 1)));
379 // Return values stats
380 for (k = 0; k < RET_VAL_COUNT; k++) {
381 percent_pkts = (qstats.returnValCount[k] * 100.0) /
382 (qstats.pkts_total + 1);
383 fprintf(fout, "%s:%6.2f (%d)\n", returnValNames[k],
384 percent_pkts, (int)qstats.returnValCount[k]);
397 cleanup_cgroup_environment();
402 static void Usage(void)
404 printf("This program loads a cgroup skb BPF program to enforce\n"
405 "cgroup output (egress) bandwidth limits.\n\n"
406 "USAGE: hbm [-o] [-d] [-l] [-n <id>] [--no_cn] [-r <rate>]\n"
407 " [-s] [-t <secs>] [-w] [-h] [prog]\n"
409 " -o indicates egress direction (default)\n"
410 " -d print BPF trace debug buffer\n"
411 " -l also limit flows using loopback\n"
412 " -n <#> to create cgroup \"/hbm#\" and attach prog\n"
413 " Default is /hbm1\n"
414 " --no_cn disable CN notifications\n"
415 " -r <rate> Rate in Mbps\n"
416 " -s Update HBM stats\n"
417 " -t <time> Exit after specified seconds (default is 0)\n"
418 " -w Work conserving flag. cgroup can increase\n"
419 " bandwidth beyond the rate limit specified\n"
420 " while there is available bandwidth. Current\n"
421 " implementation assumes there is only eth0\n"
422 " but can be extended to support multiple NICs\n"
423 " -h print this info\n"
424 " prog BPF program file name. Name defaults to\n"
425 " hbm_out_kern.o\n");
428 int main(int argc, char **argv)
430 char *prog = "hbm_out_kern.o";
433 char *optstring = "iodln:r:st:wh";
434 struct option loptions[] = {
435 {"no_cn", 0, NULL, 1},
439 while ((k = getopt_long(argc, argv, optstring, loptions, NULL)) != -1) {
450 loopback_flag = true;
453 cg_id = atoi(optarg);
456 minRate = atoi(optarg) * 1.024;
466 work_conserving_flag = true;
469 if (optopt == 'n' || optopt == 'r' || optopt == 't')
471 "Option -%c requires an argument.\n\n",
483 printf("HBM prog: %s\n", prog != NULL ? prog : "NULL");
485 return run_bpf_prog(prog, cg_id);