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>
43 #include <linux/compiler.h>
45 #include <linux/bpf.h>
49 #include "bpf_rlimit.h"
50 #include "cgroup_helpers.h"
53 #include <bpf/libbpf.h>
56 int minRate = 1000; /* cgroup rate limit in Mbps */
57 int rate = 1000; /* can grow if rate conserving is enabled */
62 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 static struct bpf_program *bpf_prog;
73 static struct bpf_object *obj;
74 static int queue_stats_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 obj = bpf_object__open_file(prog, NULL);
124 if (libbpf_get_error(obj)) {
125 printf("ERROR: opening BPF object file failed\n");
129 /* load BPF program */
130 if (bpf_object__load(obj)) {
131 printf("ERROR: loading BPF object file failed\n");
135 bpf_prog = bpf_object__find_program_by_title(obj, "cgroup_skb/egress");
137 printf("ERROR: finding a prog in obj file failed\n");
141 queue_stats_fd = bpf_object__find_map_fd_by_name(obj, "queue_stats");
142 if (queue_stats_fd < 0) {
143 printf("ERROR: finding a map in obj file failed\n");
150 bpf_object__close(obj);
154 static int run_bpf_prog(char *prog, int cg_id)
156 struct hbm_queue_stats qstats = {0};
157 char cg_dir[100], cg_pin_path[100];
158 struct bpf_link *link = NULL;
163 sprintf(cg_dir, "/hbm%d", cg_id);
164 rc = prog_load(prog);
168 if (setup_cgroup_environment()) {
169 printf("ERROR: setting cgroup environment\n");
172 cg1 = create_and_get_cgroup(cg_dir);
174 printf("ERROR: create_and_get_cgroup\n");
177 if (join_cgroup(cg_dir)) {
178 printf("ERROR: join_cgroup\n");
183 qstats.stats = stats_flag ? 1 : 0;
184 qstats.loopback = loopback_flag ? 1 : 0;
185 qstats.no_cn = no_cn_flag ? 1 : 0;
186 if (bpf_map_update_elem(queue_stats_fd, &key, &qstats, BPF_ANY)) {
187 printf("ERROR: Could not update map element\n");
192 bpf_program__set_expected_attach_type(bpf_prog, BPF_CGROUP_INET_INGRESS);
194 link = bpf_program__attach_cgroup(bpf_prog, cg1);
195 if (libbpf_get_error(link)) {
196 fprintf(stderr, "ERROR: bpf_program__attach_cgroup failed\n");
200 sprintf(cg_pin_path, "/sys/fs/bpf/hbm%d", cg_id);
201 rc = bpf_link__pin(link, cg_pin_path);
203 printf("ERROR: bpf_link__pin failed: %d\n", rc);
207 if (work_conserving_flag) {
208 struct timeval t0, t_last, t_new;
210 unsigned long long last_eth_tx_bytes, new_eth_tx_bytes;
211 signed long long last_cg_tx_bytes, new_cg_tx_bytes;
212 signed long long delta_time, delta_bytes, delta_rate;
214 #define DELTA_RATE_CHECK 10000 /* in us */
215 #define RATE_THRESHOLD 9500000000 /* 9.5 Gbps */
217 bpf_map_lookup_elem(queue_stats_fd, &key, &qstats);
218 if (gettimeofday(&t0, NULL) < 0)
219 do_error("gettimeofday failed", true);
221 fin = fopen("/sys/class/net/eth0/statistics/tx_bytes", "r");
222 if (fscanf(fin, "%llu", &last_eth_tx_bytes) != 1)
223 do_error("fscanf fails", false);
225 last_cg_tx_bytes = qstats.bytes_total;
227 usleep(DELTA_RATE_CHECK);
228 if (gettimeofday(&t_new, NULL) < 0)
229 do_error("gettimeofday failed", true);
230 delta_ms = (t_new.tv_sec - t0.tv_sec) * 1000 +
231 (t_new.tv_usec - t0.tv_usec)/1000;
232 if (delta_ms > dur * 1000)
234 delta_time = (t_new.tv_sec - t_last.tv_sec) * 1000000 +
235 (t_new.tv_usec - t_last.tv_usec);
239 fin = fopen("/sys/class/net/eth0/statistics/tx_bytes",
241 if (fscanf(fin, "%llu", &new_eth_tx_bytes) != 1)
242 do_error("fscanf fails", false);
244 printf(" new_eth_tx_bytes:%llu\n",
246 bpf_map_lookup_elem(queue_stats_fd, &key, &qstats);
247 new_cg_tx_bytes = qstats.bytes_total;
248 delta_bytes = new_eth_tx_bytes - last_eth_tx_bytes;
249 last_eth_tx_bytes = new_eth_tx_bytes;
250 delta_rate = (delta_bytes * 8000000) / delta_time;
251 printf("%5d - eth_rate:%.1fGbps cg_rate:%.3fGbps",
252 delta_ms, delta_rate/1000000000.0,
254 if (delta_rate < RATE_THRESHOLD) {
255 /* can increase cgroup rate limit, but first
256 * check if we are using the current limit.
257 * Currently increasing by 6.25%, unknown
258 * if that is the optimal rate.
262 delta_bytes = new_cg_tx_bytes -
264 last_cg_tx_bytes = new_cg_tx_bytes;
265 delta_rate = (delta_bytes * 8000000) /
267 printf(" rate:%.3fGbps",
268 delta_rate/1000000000.0);
269 rate_diff100 = (((long long)rate)*1000000 -
271 (((long long) rate) * 1000000);
272 printf(" rdiff:%d", rate_diff100);
273 if (rate_diff100 <= 3) {
275 if (rate > RATE_THRESHOLD / 1000000)
276 rate = RATE_THRESHOLD / 1000000;
283 /* Need to decrease cgroup rate limit.
284 * Currently decreasing by 12.5%, unknown
293 if (bpf_map_update_elem(queue_stats_fd, &key, &qstats, BPF_ANY))
294 do_error("update map element fails", false);
300 if (stats_flag && bpf_map_lookup_elem(queue_stats_fd, &key, &qstats)) {
305 sprintf(fname, "hbm.%d.in", cg_id);
307 sprintf(fname, "hbm.%d.out", cg_id);
308 fout = fopen(fname, "w");
309 fprintf(fout, "id:%d\n", cg_id);
310 fprintf(fout, "ERROR: Could not lookup queue_stats\n");
311 } else if (stats_flag && qstats.lastPacketTime >
312 qstats.firstPacketTime) {
313 long long delta_us = (qstats.lastPacketTime -
314 qstats.firstPacketTime)/1000;
315 unsigned int rate_mbps = ((qstats.bytes_total -
316 qstats.bytes_dropped) * 8 /
318 double percent_pkts, percent_bytes;
322 static const char *returnValNames[] = {
328 #define RET_VAL_COUNT 4
330 // Future support of ingress
332 // sprintf(fname, "hbm.%d.in", cg_id);
334 sprintf(fname, "hbm.%d.out", cg_id);
335 fout = fopen(fname, "w");
336 fprintf(fout, "id:%d\n", cg_id);
337 fprintf(fout, "rate_mbps:%d\n", rate_mbps);
338 fprintf(fout, "duration:%.1f secs\n",
339 (qstats.lastPacketTime - qstats.firstPacketTime) /
341 fprintf(fout, "packets:%d\n", (int)qstats.pkts_total);
342 fprintf(fout, "bytes_MB:%d\n", (int)(qstats.bytes_total /
344 fprintf(fout, "pkts_dropped:%d\n", (int)qstats.pkts_dropped);
345 fprintf(fout, "bytes_dropped_MB:%d\n",
346 (int)(qstats.bytes_dropped /
348 // Marked Pkts and Bytes
349 percent_pkts = (qstats.pkts_marked * 100.0) /
350 (qstats.pkts_total + 1);
351 percent_bytes = (qstats.bytes_marked * 100.0) /
352 (qstats.bytes_total + 1);
353 fprintf(fout, "pkts_marked_percent:%6.2f\n", percent_pkts);
354 fprintf(fout, "bytes_marked_percent:%6.2f\n", percent_bytes);
356 // Dropped Pkts and Bytes
357 percent_pkts = (qstats.pkts_dropped * 100.0) /
358 (qstats.pkts_total + 1);
359 percent_bytes = (qstats.bytes_dropped * 100.0) /
360 (qstats.bytes_total + 1);
361 fprintf(fout, "pkts_dropped_percent:%6.2f\n", percent_pkts);
362 fprintf(fout, "bytes_dropped_percent:%6.2f\n", percent_bytes);
365 percent_pkts = (qstats.pkts_ecn_ce * 100.0) /
366 (qstats.pkts_total + 1);
367 fprintf(fout, "pkts_ecn_ce:%6.2f (%d)\n", percent_pkts,
368 (int)qstats.pkts_ecn_ce);
371 fprintf(fout, "avg cwnd:%d\n",
372 (int)(qstats.sum_cwnd / (qstats.sum_cwnd_cnt + 1)));
374 fprintf(fout, "avg rtt:%d\n",
375 (int)(qstats.sum_rtt / (qstats.pkts_total + 1)));
378 fprintf(fout, "avg credit_ms:%.03f\n",
380 (qstats.pkts_total + 1.0)) / 1000000.0);
382 fprintf(fout, "avg credit:%d\n",
383 (int)(qstats.sum_credit /
384 (1500 * ((int)qstats.pkts_total ) + 1)));
386 // Return values stats
387 for (k = 0; k < RET_VAL_COUNT; k++) {
388 percent_pkts = (qstats.returnValCount[k] * 100.0) /
389 (qstats.pkts_total + 1);
390 fprintf(fout, "%s:%6.2f (%d)\n", returnValNames[k],
391 percent_pkts, (int)qstats.returnValCount[k]);
404 bpf_link__destroy(link);
405 bpf_object__close(obj);
411 cleanup_cgroup_environment();
415 static void Usage(void)
417 printf("This program loads a cgroup skb BPF program to enforce\n"
418 "cgroup output (egress) bandwidth limits.\n\n"
419 "USAGE: hbm [-o] [-d] [-l] [-n <id>] [--no_cn] [-r <rate>]\n"
420 " [-s] [-t <secs>] [-w] [-h] [prog]\n"
422 " -o indicates egress direction (default)\n"
423 " -d print BPF trace debug buffer\n"
424 " --edt use fq's Earliest Departure Time\n"
425 " -l also limit flows using loopback\n"
426 " -n <#> to create cgroup \"/hbm#\" and attach prog\n"
427 " Default is /hbm1\n"
428 " --no_cn disable CN notifications\n"
429 " -r <rate> Rate in Mbps\n"
430 " -s Update HBM stats\n"
431 " -t <time> Exit after specified seconds (default is 0)\n"
432 " -w Work conserving flag. cgroup can increase\n"
433 " bandwidth beyond the rate limit specified\n"
434 " while there is available bandwidth. Current\n"
435 " implementation assumes there is only eth0\n"
436 " but can be extended to support multiple NICs\n"
437 " -h print this info\n"
438 " prog BPF program file name. Name defaults to\n"
439 " hbm_out_kern.o\n");
442 int main(int argc, char **argv)
444 char *prog = "hbm_out_kern.o";
447 char *optstring = "iodln:r:st:wh";
448 struct option loptions[] = {
449 {"no_cn", 0, NULL, 1},
454 while ((k = getopt_long(argc, argv, optstring, loptions, NULL)) != -1) {
460 prog = "hbm_edt_kern.o";
469 loopback_flag = true;
472 cg_id = atoi(optarg);
475 minRate = atoi(optarg) * 1.024;
485 work_conserving_flag = true;
488 if (optopt == 'n' || optopt == 'r' || optopt == 't')
490 "Option -%c requires an argument.\n\n",
502 printf("HBM prog: %s\n", prog != NULL ? prog : "NULL");
504 return run_bpf_prog(prog, cg_id);