tcp_cong_kern.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 "bpftool cgroup attach $cg sock_ops $prog" 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/bpf_helpers.h>
  19. #include <bpf/bpf_endian.h>
  20. #define DEBUG 1
  21. SEC("sockops")
  22. int bpf_cong(struct bpf_sock_ops *skops)
  23. {
  24. char cong[] = "dctcp";
  25. int rv = 0;
  26. int op;
  27. /* For testing purposes, only execute rest of BPF program
  28. * if neither port numberis 55601
  29. */
  30. if (bpf_ntohl(skops->remote_port) != 55601 &&
  31. skops->local_port != 55601) {
  32. skops->reply = -1;
  33. return 1;
  34. }
  35. op = (int) skops->op;
  36. #ifdef DEBUG
  37. bpf_printk("BPF command: %d\n", op);
  38. #endif
  39. /* Check if both hosts are in the same datacenter. For this
  40. * example they are if the 1st 5.5 bytes in the IPv6 address
  41. * are the same.
  42. */
  43. if (skops->family == AF_INET6 &&
  44. skops->local_ip6[0] == skops->remote_ip6[0] &&
  45. (bpf_ntohl(skops->local_ip6[1]) & 0xfff00000) ==
  46. (bpf_ntohl(skops->remote_ip6[1]) & 0xfff00000)) {
  47. switch (op) {
  48. case BPF_SOCK_OPS_NEEDS_ECN:
  49. rv = 1;
  50. break;
  51. case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
  52. rv = bpf_setsockopt(skops, SOL_TCP, TCP_CONGESTION,
  53. cong, sizeof(cong));
  54. break;
  55. case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB:
  56. rv = bpf_setsockopt(skops, SOL_TCP, TCP_CONGESTION,
  57. cong, sizeof(cong));
  58. break;
  59. default:
  60. rv = -1;
  61. }
  62. } else {
  63. rv = -1;
  64. }
  65. #ifdef DEBUG
  66. bpf_printk("Returning %d\n", rv);
  67. #endif
  68. skops->reply = rv;
  69. return 1;
  70. }
  71. char _license[] SEC("license") = "GPL";