tcp_cong_kern.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* Copyright (c) 2017 Facebook
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of version 2 of the GNU General Public
  5. * License as published by the Free Software Foundation.
  6. *
  7. * BPF program to set congestion control to dctcp when both hosts are
  8. * in the same datacenter (as deteremined by IPv6 prefix).
  9. *
  10. * Use load_sock_ops to load this BPF program.
  11. */
  12. #include <uapi/linux/bpf.h>
  13. #include <uapi/linux/tcp.h>
  14. #include <uapi/linux/if_ether.h>
  15. #include <uapi/linux/if_packet.h>
  16. #include <uapi/linux/ip.h>
  17. #include <linux/socket.h>
  18. #include "bpf_helpers.h"
  19. #include "bpf_endian.h"
  20. #define DEBUG 1
  21. #define bpf_printk(fmt, ...) \
  22. ({ \
  23. char ____fmt[] = fmt; \
  24. bpf_trace_printk(____fmt, sizeof(____fmt), \
  25. ##__VA_ARGS__); \
  26. })
  27. SEC("sockops")
  28. int bpf_cong(struct bpf_sock_ops *skops)
  29. {
  30. char cong[] = "dctcp";
  31. int rv = 0;
  32. int op;
  33. /* For testing purposes, only execute rest of BPF program
  34. * if neither port numberis 55601
  35. */
  36. if (bpf_ntohl(skops->remote_port) != 55601 &&
  37. skops->local_port != 55601) {
  38. skops->reply = -1;
  39. return 1;
  40. }
  41. op = (int) skops->op;
  42. #ifdef DEBUG
  43. bpf_printk("BPF command: %d\n", op);
  44. #endif
  45. /* Check if both hosts are in the same datacenter. For this
  46. * example they are if the 1st 5.5 bytes in the IPv6 address
  47. * are the same.
  48. */
  49. if (skops->family == AF_INET6 &&
  50. skops->local_ip6[0] == skops->remote_ip6[0] &&
  51. (bpf_ntohl(skops->local_ip6[1]) & 0xfff00000) ==
  52. (bpf_ntohl(skops->remote_ip6[1]) & 0xfff00000)) {
  53. switch (op) {
  54. case BPF_SOCK_OPS_NEEDS_ECN:
  55. rv = 1;
  56. break;
  57. case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
  58. rv = bpf_setsockopt(skops, SOL_TCP, TCP_CONGESTION,
  59. cong, sizeof(cong));
  60. break;
  61. case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB:
  62. rv = bpf_setsockopt(skops, SOL_TCP, TCP_CONGESTION,
  63. cong, sizeof(cong));
  64. break;
  65. default:
  66. rv = -1;
  67. }
  68. } else {
  69. rv = -1;
  70. }
  71. #ifdef DEBUG
  72. bpf_printk("Returning %d\n", rv);
  73. #endif
  74. skops->reply = rv;
  75. return 1;
  76. }
  77. char _license[] SEC("license") = "GPL";