hbm.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. // SPDX-License-Identifier: GPL-2.0
  2. /* Copyright (c) 2019 Facebook
  3. *
  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.
  7. *
  8. * Example program for Host Bandwidth Managment
  9. *
  10. * This program loads a cgroup skb BPF program to enforce cgroup output
  11. * (egress) or input (ingress) bandwidth limits.
  12. *
  13. * USAGE: hbm [-d] [-l] [-n <id>] [-r <rate>] [-s] [-t <secs>] [-w] [-h] [prog]
  14. * Where:
  15. * -d Print BPF trace debug buffer
  16. * -l Also limit flows doing loopback
  17. * -n <#> To create cgroup \"/hbm#\" and attach prog
  18. * Default is /hbm1
  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.
  28. * -h Print this info
  29. * prog BPF program file name. Name defaults to hbm_out_kern.o
  30. */
  31. #define _GNU_SOURCE
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <assert.h>
  35. #include <sys/time.h>
  36. #include <unistd.h>
  37. #include <errno.h>
  38. #include <fcntl.h>
  39. #include <linux/unistd.h>
  40. #include <linux/compiler.h>
  41. #include <linux/bpf.h>
  42. #include <bpf/bpf.h>
  43. #include <getopt.h>
  44. #include "cgroup_helpers.h"
  45. #include "hbm.h"
  46. #include "bpf_util.h"
  47. #include <bpf/libbpf.h>
  48. bool outFlag = true;
  49. int minRate = 1000; /* cgroup rate limit in Mbps */
  50. int rate = 1000; /* can grow if rate conserving is enabled */
  51. int dur = 1;
  52. bool stats_flag;
  53. bool loopback_flag;
  54. bool debugFlag;
  55. bool work_conserving_flag;
  56. bool no_cn_flag;
  57. bool edt_flag;
  58. static void Usage(void);
  59. static void read_trace_pipe2(void);
  60. static void do_error(char *msg, bool errno_flag);
  61. #define DEBUGFS "/sys/kernel/debug/tracing/"
  62. static struct bpf_program *bpf_prog;
  63. static struct bpf_object *obj;
  64. static int queue_stats_fd;
  65. static void read_trace_pipe2(void)
  66. {
  67. int trace_fd;
  68. FILE *outf;
  69. char *outFname = "hbm_out.log";
  70. trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
  71. if (trace_fd < 0) {
  72. printf("Error opening trace_pipe\n");
  73. return;
  74. }
  75. // Future support of ingress
  76. // if (!outFlag)
  77. // outFname = "hbm_in.log";
  78. outf = fopen(outFname, "w");
  79. if (outf == NULL)
  80. printf("Error creating %s\n", outFname);
  81. while (1) {
  82. static char buf[4097];
  83. ssize_t sz;
  84. sz = read(trace_fd, buf, sizeof(buf) - 1);
  85. if (sz > 0) {
  86. buf[sz] = 0;
  87. puts(buf);
  88. if (outf != NULL) {
  89. fprintf(outf, "%s\n", buf);
  90. fflush(outf);
  91. }
  92. }
  93. }
  94. }
  95. static void do_error(char *msg, bool errno_flag)
  96. {
  97. if (errno_flag)
  98. printf("ERROR: %s, errno: %d\n", msg, errno);
  99. else
  100. printf("ERROR: %s\n", msg);
  101. exit(1);
  102. }
  103. static int prog_load(char *prog)
  104. {
  105. struct bpf_program *pos;
  106. const char *sec_name;
  107. obj = bpf_object__open_file(prog, NULL);
  108. if (libbpf_get_error(obj)) {
  109. printf("ERROR: opening BPF object file failed\n");
  110. return 1;
  111. }
  112. /* load BPF program */
  113. if (bpf_object__load(obj)) {
  114. printf("ERROR: loading BPF object file failed\n");
  115. goto err;
  116. }
  117. bpf_object__for_each_program(pos, obj) {
  118. sec_name = bpf_program__section_name(pos);
  119. if (sec_name && !strcmp(sec_name, "cgroup_skb/egress")) {
  120. bpf_prog = pos;
  121. break;
  122. }
  123. }
  124. if (!bpf_prog) {
  125. printf("ERROR: finding a prog in obj file failed\n");
  126. goto err;
  127. }
  128. queue_stats_fd = bpf_object__find_map_fd_by_name(obj, "queue_stats");
  129. if (queue_stats_fd < 0) {
  130. printf("ERROR: finding a map in obj file failed\n");
  131. goto err;
  132. }
  133. return 0;
  134. err:
  135. bpf_object__close(obj);
  136. return 1;
  137. }
  138. static int run_bpf_prog(char *prog, int cg_id)
  139. {
  140. struct hbm_queue_stats qstats = {0};
  141. char cg_dir[100], cg_pin_path[100];
  142. struct bpf_link *link = NULL;
  143. int key = 0;
  144. int cg1 = 0;
  145. int rc = 0;
  146. sprintf(cg_dir, "/hbm%d", cg_id);
  147. rc = prog_load(prog);
  148. if (rc != 0)
  149. return rc;
  150. if (setup_cgroup_environment()) {
  151. printf("ERROR: setting cgroup environment\n");
  152. goto err;
  153. }
  154. cg1 = create_and_get_cgroup(cg_dir);
  155. if (!cg1) {
  156. printf("ERROR: create_and_get_cgroup\n");
  157. goto err;
  158. }
  159. if (join_cgroup(cg_dir)) {
  160. printf("ERROR: join_cgroup\n");
  161. goto err;
  162. }
  163. qstats.rate = rate;
  164. qstats.stats = stats_flag ? 1 : 0;
  165. qstats.loopback = loopback_flag ? 1 : 0;
  166. qstats.no_cn = no_cn_flag ? 1 : 0;
  167. if (bpf_map_update_elem(queue_stats_fd, &key, &qstats, BPF_ANY)) {
  168. printf("ERROR: Could not update map element\n");
  169. goto err;
  170. }
  171. if (!outFlag)
  172. bpf_program__set_expected_attach_type(bpf_prog, BPF_CGROUP_INET_INGRESS);
  173. link = bpf_program__attach_cgroup(bpf_prog, cg1);
  174. if (libbpf_get_error(link)) {
  175. fprintf(stderr, "ERROR: bpf_program__attach_cgroup failed\n");
  176. goto err;
  177. }
  178. sprintf(cg_pin_path, "/sys/fs/bpf/hbm%d", cg_id);
  179. rc = bpf_link__pin(link, cg_pin_path);
  180. if (rc < 0) {
  181. printf("ERROR: bpf_link__pin failed: %d\n", rc);
  182. goto err;
  183. }
  184. if (work_conserving_flag) {
  185. struct timeval t0, t_last, t_new;
  186. FILE *fin;
  187. unsigned long long last_eth_tx_bytes, new_eth_tx_bytes;
  188. signed long long last_cg_tx_bytes, new_cg_tx_bytes;
  189. signed long long delta_time, delta_bytes, delta_rate;
  190. int delta_ms;
  191. #define DELTA_RATE_CHECK 10000 /* in us */
  192. #define RATE_THRESHOLD 9500000000 /* 9.5 Gbps */
  193. bpf_map_lookup_elem(queue_stats_fd, &key, &qstats);
  194. if (gettimeofday(&t0, NULL) < 0)
  195. do_error("gettimeofday failed", true);
  196. t_last = t0;
  197. fin = fopen("/sys/class/net/eth0/statistics/tx_bytes", "r");
  198. if (fscanf(fin, "%llu", &last_eth_tx_bytes) != 1)
  199. do_error("fscanf fails", false);
  200. fclose(fin);
  201. last_cg_tx_bytes = qstats.bytes_total;
  202. while (true) {
  203. usleep(DELTA_RATE_CHECK);
  204. if (gettimeofday(&t_new, NULL) < 0)
  205. do_error("gettimeofday failed", true);
  206. delta_ms = (t_new.tv_sec - t0.tv_sec) * 1000 +
  207. (t_new.tv_usec - t0.tv_usec)/1000;
  208. if (delta_ms > dur * 1000)
  209. break;
  210. delta_time = (t_new.tv_sec - t_last.tv_sec) * 1000000 +
  211. (t_new.tv_usec - t_last.tv_usec);
  212. if (delta_time == 0)
  213. continue;
  214. t_last = t_new;
  215. fin = fopen("/sys/class/net/eth0/statistics/tx_bytes",
  216. "r");
  217. if (fscanf(fin, "%llu", &new_eth_tx_bytes) != 1)
  218. do_error("fscanf fails", false);
  219. fclose(fin);
  220. printf(" new_eth_tx_bytes:%llu\n",
  221. new_eth_tx_bytes);
  222. bpf_map_lookup_elem(queue_stats_fd, &key, &qstats);
  223. new_cg_tx_bytes = qstats.bytes_total;
  224. delta_bytes = new_eth_tx_bytes - last_eth_tx_bytes;
  225. last_eth_tx_bytes = new_eth_tx_bytes;
  226. delta_rate = (delta_bytes * 8000000) / delta_time;
  227. printf("%5d - eth_rate:%.1fGbps cg_rate:%.3fGbps",
  228. delta_ms, delta_rate/1000000000.0,
  229. rate/1000.0);
  230. if (delta_rate < RATE_THRESHOLD) {
  231. /* can increase cgroup rate limit, but first
  232. * check if we are using the current limit.
  233. * Currently increasing by 6.25%, unknown
  234. * if that is the optimal rate.
  235. */
  236. int rate_diff100;
  237. delta_bytes = new_cg_tx_bytes -
  238. last_cg_tx_bytes;
  239. last_cg_tx_bytes = new_cg_tx_bytes;
  240. delta_rate = (delta_bytes * 8000000) /
  241. delta_time;
  242. printf(" rate:%.3fGbps",
  243. delta_rate/1000000000.0);
  244. rate_diff100 = (((long long)rate)*1000000 -
  245. delta_rate) * 100 /
  246. (((long long) rate) * 1000000);
  247. printf(" rdiff:%d", rate_diff100);
  248. if (rate_diff100 <= 3) {
  249. rate += (rate >> 4);
  250. if (rate > RATE_THRESHOLD / 1000000)
  251. rate = RATE_THRESHOLD / 1000000;
  252. qstats.rate = rate;
  253. printf(" INC\n");
  254. } else {
  255. printf("\n");
  256. }
  257. } else {
  258. /* Need to decrease cgroup rate limit.
  259. * Currently decreasing by 12.5%, unknown
  260. * if that is optimal
  261. */
  262. printf(" DEC\n");
  263. rate -= (rate >> 3);
  264. if (rate < minRate)
  265. rate = minRate;
  266. qstats.rate = rate;
  267. }
  268. if (bpf_map_update_elem(queue_stats_fd, &key, &qstats, BPF_ANY))
  269. do_error("update map element fails", false);
  270. }
  271. } else {
  272. sleep(dur);
  273. }
  274. // Get stats!
  275. if (stats_flag && bpf_map_lookup_elem(queue_stats_fd, &key, &qstats)) {
  276. char fname[100];
  277. FILE *fout;
  278. if (!outFlag)
  279. sprintf(fname, "hbm.%d.in", cg_id);
  280. else
  281. sprintf(fname, "hbm.%d.out", cg_id);
  282. fout = fopen(fname, "w");
  283. fprintf(fout, "id:%d\n", cg_id);
  284. fprintf(fout, "ERROR: Could not lookup queue_stats\n");
  285. fclose(fout);
  286. } else if (stats_flag && qstats.lastPacketTime >
  287. qstats.firstPacketTime) {
  288. long long delta_us = (qstats.lastPacketTime -
  289. qstats.firstPacketTime)/1000;
  290. unsigned int rate_mbps = ((qstats.bytes_total -
  291. qstats.bytes_dropped) * 8 /
  292. delta_us);
  293. double percent_pkts, percent_bytes;
  294. char fname[100];
  295. FILE *fout;
  296. int k;
  297. static const char *returnValNames[] = {
  298. "DROP_PKT",
  299. "ALLOW_PKT",
  300. "DROP_PKT_CWR",
  301. "ALLOW_PKT_CWR"
  302. };
  303. #define RET_VAL_COUNT 4
  304. // Future support of ingress
  305. // if (!outFlag)
  306. // sprintf(fname, "hbm.%d.in", cg_id);
  307. // else
  308. sprintf(fname, "hbm.%d.out", cg_id);
  309. fout = fopen(fname, "w");
  310. fprintf(fout, "id:%d\n", cg_id);
  311. fprintf(fout, "rate_mbps:%d\n", rate_mbps);
  312. fprintf(fout, "duration:%.1f secs\n",
  313. (qstats.lastPacketTime - qstats.firstPacketTime) /
  314. 1000000000.0);
  315. fprintf(fout, "packets:%d\n", (int)qstats.pkts_total);
  316. fprintf(fout, "bytes_MB:%d\n", (int)(qstats.bytes_total /
  317. 1000000));
  318. fprintf(fout, "pkts_dropped:%d\n", (int)qstats.pkts_dropped);
  319. fprintf(fout, "bytes_dropped_MB:%d\n",
  320. (int)(qstats.bytes_dropped /
  321. 1000000));
  322. // Marked Pkts and Bytes
  323. percent_pkts = (qstats.pkts_marked * 100.0) /
  324. (qstats.pkts_total + 1);
  325. percent_bytes = (qstats.bytes_marked * 100.0) /
  326. (qstats.bytes_total + 1);
  327. fprintf(fout, "pkts_marked_percent:%6.2f\n", percent_pkts);
  328. fprintf(fout, "bytes_marked_percent:%6.2f\n", percent_bytes);
  329. // Dropped Pkts and Bytes
  330. percent_pkts = (qstats.pkts_dropped * 100.0) /
  331. (qstats.pkts_total + 1);
  332. percent_bytes = (qstats.bytes_dropped * 100.0) /
  333. (qstats.bytes_total + 1);
  334. fprintf(fout, "pkts_dropped_percent:%6.2f\n", percent_pkts);
  335. fprintf(fout, "bytes_dropped_percent:%6.2f\n", percent_bytes);
  336. // ECN CE markings
  337. percent_pkts = (qstats.pkts_ecn_ce * 100.0) /
  338. (qstats.pkts_total + 1);
  339. fprintf(fout, "pkts_ecn_ce:%6.2f (%d)\n", percent_pkts,
  340. (int)qstats.pkts_ecn_ce);
  341. // Average cwnd
  342. fprintf(fout, "avg cwnd:%d\n",
  343. (int)(qstats.sum_cwnd / (qstats.sum_cwnd_cnt + 1)));
  344. // Average rtt
  345. fprintf(fout, "avg rtt:%d\n",
  346. (int)(qstats.sum_rtt / (qstats.pkts_total + 1)));
  347. // Average credit
  348. if (edt_flag)
  349. fprintf(fout, "avg credit_ms:%.03f\n",
  350. (qstats.sum_credit /
  351. (qstats.pkts_total + 1.0)) / 1000000.0);
  352. else
  353. fprintf(fout, "avg credit:%d\n",
  354. (int)(qstats.sum_credit /
  355. (1500 * ((int)qstats.pkts_total ) + 1)));
  356. // Return values stats
  357. for (k = 0; k < RET_VAL_COUNT; k++) {
  358. percent_pkts = (qstats.returnValCount[k] * 100.0) /
  359. (qstats.pkts_total + 1);
  360. fprintf(fout, "%s:%6.2f (%d)\n", returnValNames[k],
  361. percent_pkts, (int)qstats.returnValCount[k]);
  362. }
  363. fclose(fout);
  364. }
  365. if (debugFlag)
  366. read_trace_pipe2();
  367. goto cleanup;
  368. err:
  369. rc = 1;
  370. cleanup:
  371. bpf_link__destroy(link);
  372. bpf_object__close(obj);
  373. if (cg1 != -1)
  374. close(cg1);
  375. if (rc != 0)
  376. cleanup_cgroup_environment();
  377. return rc;
  378. }
  379. static void Usage(void)
  380. {
  381. printf("This program loads a cgroup skb BPF program to enforce\n"
  382. "cgroup output (egress) bandwidth limits.\n\n"
  383. "USAGE: hbm [-o] [-d] [-l] [-n <id>] [--no_cn] [-r <rate>]\n"
  384. " [-s] [-t <secs>] [-w] [-h] [prog]\n"
  385. " Where:\n"
  386. " -o indicates egress direction (default)\n"
  387. " -d print BPF trace debug buffer\n"
  388. " --edt use fq's Earliest Departure Time\n"
  389. " -l also limit flows using loopback\n"
  390. " -n <#> to create cgroup \"/hbm#\" and attach prog\n"
  391. " Default is /hbm1\n"
  392. " --no_cn disable CN notifications\n"
  393. " -r <rate> Rate in Mbps\n"
  394. " -s Update HBM stats\n"
  395. " -t <time> Exit after specified seconds (default is 0)\n"
  396. " -w Work conserving flag. cgroup can increase\n"
  397. " bandwidth beyond the rate limit specified\n"
  398. " while there is available bandwidth. Current\n"
  399. " implementation assumes there is only eth0\n"
  400. " but can be extended to support multiple NICs\n"
  401. " -h print this info\n"
  402. " prog BPF program file name. Name defaults to\n"
  403. " hbm_out_kern.o\n");
  404. }
  405. int main(int argc, char **argv)
  406. {
  407. char *prog = "hbm_out_kern.o";
  408. int k;
  409. int cg_id = 1;
  410. char *optstring = "iodln:r:st:wh";
  411. struct option loptions[] = {
  412. {"no_cn", 0, NULL, 1},
  413. {"edt", 0, NULL, 2},
  414. {NULL, 0, NULL, 0}
  415. };
  416. while ((k = getopt_long(argc, argv, optstring, loptions, NULL)) != -1) {
  417. switch (k) {
  418. case 1:
  419. no_cn_flag = true;
  420. break;
  421. case 2:
  422. prog = "hbm_edt_kern.o";
  423. edt_flag = true;
  424. break;
  425. case'o':
  426. break;
  427. case 'd':
  428. debugFlag = true;
  429. break;
  430. case 'l':
  431. loopback_flag = true;
  432. break;
  433. case 'n':
  434. cg_id = atoi(optarg);
  435. break;
  436. case 'r':
  437. minRate = atoi(optarg) * 1.024;
  438. rate = minRate;
  439. break;
  440. case 's':
  441. stats_flag = true;
  442. break;
  443. case 't':
  444. dur = atoi(optarg);
  445. break;
  446. case 'w':
  447. work_conserving_flag = true;
  448. break;
  449. case '?':
  450. if (optopt == 'n' || optopt == 'r' || optopt == 't')
  451. fprintf(stderr,
  452. "Option -%c requires an argument.\n\n",
  453. optopt);
  454. case 'h':
  455. __fallthrough;
  456. default:
  457. Usage();
  458. return 0;
  459. }
  460. }
  461. if (optind < argc)
  462. prog = argv[optind];
  463. printf("HBM prog: %s\n", prog != NULL ? prog : "NULL");
  464. /* Use libbpf 1.0 API mode */
  465. libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
  466. return run_bpf_prog(prog, cg_id);
  467. }