xdp_redirect_kern.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Copyright (c) 2016 John Fastabend <john.r.fastabend@intel.com>
  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. * This program is distributed in the hope that it will be useful, but
  8. * WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. * General Public License for more details.
  11. */
  12. #define KBUILD_MODNAME "foo"
  13. #include <uapi/linux/bpf.h>
  14. #include <linux/in.h>
  15. #include <linux/if_ether.h>
  16. #include <linux/if_packet.h>
  17. #include <linux/if_vlan.h>
  18. #include <linux/ip.h>
  19. #include <linux/ipv6.h>
  20. #include <bpf/bpf_helpers.h>
  21. struct {
  22. __uint(type, BPF_MAP_TYPE_ARRAY);
  23. __type(key, int);
  24. __type(value, int);
  25. __uint(max_entries, 1);
  26. } tx_port SEC(".maps");
  27. /* Count RX packets, as XDP bpf_prog doesn't get direct TX-success
  28. * feedback. Redirect TX errors can be caught via a tracepoint.
  29. */
  30. struct {
  31. __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
  32. __type(key, u32);
  33. __type(value, long);
  34. __uint(max_entries, 1);
  35. } rxcnt SEC(".maps");
  36. static void swap_src_dst_mac(void *data)
  37. {
  38. unsigned short *p = data;
  39. unsigned short dst[3];
  40. dst[0] = p[0];
  41. dst[1] = p[1];
  42. dst[2] = p[2];
  43. p[0] = p[3];
  44. p[1] = p[4];
  45. p[2] = p[5];
  46. p[3] = dst[0];
  47. p[4] = dst[1];
  48. p[5] = dst[2];
  49. }
  50. SEC("xdp_redirect")
  51. int xdp_redirect_prog(struct xdp_md *ctx)
  52. {
  53. void *data_end = (void *)(long)ctx->data_end;
  54. void *data = (void *)(long)ctx->data;
  55. struct ethhdr *eth = data;
  56. int rc = XDP_DROP;
  57. int *ifindex, port = 0;
  58. long *value;
  59. u32 key = 0;
  60. u64 nh_off;
  61. nh_off = sizeof(*eth);
  62. if (data + nh_off > data_end)
  63. return rc;
  64. ifindex = bpf_map_lookup_elem(&tx_port, &port);
  65. if (!ifindex)
  66. return rc;
  67. value = bpf_map_lookup_elem(&rxcnt, &key);
  68. if (value)
  69. *value += 1;
  70. swap_src_dst_mac(data);
  71. return bpf_redirect(*ifindex, 0);
  72. }
  73. /* Redirect require an XDP bpf_prog loaded on the TX device */
  74. SEC("xdp_redirect_dummy")
  75. int xdp_redirect_dummy_prog(struct xdp_md *ctx)
  76. {
  77. return XDP_PASS;
  78. }
  79. char _license[] SEC("license") = "GPL";