tcp_cong_kern.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. return -1;
  39. op = (int) skops->op;
  40. #ifdef DEBUG
  41. bpf_printk("BPF command: %d\n", op);
  42. #endif
  43. /* Check if both hosts are in the same datacenter. For this
  44. * example they are if the 1st 5.5 bytes in the IPv6 address
  45. * are the same.
  46. */
  47. if (skops->family == AF_INET6 &&
  48. skops->local_ip6[0] == skops->remote_ip6[0] &&
  49. (bpf_ntohl(skops->local_ip6[1]) & 0xfff00000) ==
  50. (bpf_ntohl(skops->remote_ip6[1]) & 0xfff00000)) {
  51. switch (op) {
  52. case BPF_SOCK_OPS_NEEDS_ECN:
  53. rv = 1;
  54. break;
  55. case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
  56. rv = bpf_setsockopt(skops, SOL_TCP, TCP_CONGESTION,
  57. cong, sizeof(cong));
  58. break;
  59. case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB:
  60. rv = bpf_setsockopt(skops, SOL_TCP, TCP_CONGESTION,
  61. cong, sizeof(cong));
  62. break;
  63. default:
  64. rv = -1;
  65. }
  66. } else {
  67. rv = -1;
  68. }
  69. #ifdef DEBUG
  70. bpf_printk("Returning %d\n", rv);
  71. #endif
  72. skops->reply = rv;
  73. return 1;
  74. }
  75. char _license[] SEC("license") = "GPL";