xdp_redirect_map_kern.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* Copyright (c) 2017 Covalent IO, Inc. http://covalent.io
  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_DEVMAP);
  23. __uint(key_size, sizeof(int));
  24. __uint(value_size, sizeof(int));
  25. __uint(max_entries, 100);
  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_map")
  51. int xdp_redirect_map_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 vport, port = 0, m = 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. /* constant virtual port */
  65. vport = 0;
  66. /* count packet in global counter */
  67. value = bpf_map_lookup_elem(&rxcnt, &key);
  68. if (value)
  69. *value += 1;
  70. swap_src_dst_mac(data);
  71. /* send packet out physical port */
  72. return bpf_redirect_map(&tx_port, vport, 0);
  73. }
  74. /* Redirect require an XDP bpf_prog loaded on the TX device */
  75. SEC("xdp_redirect_dummy")
  76. int xdp_redirect_dummy_prog(struct xdp_md *ctx)
  77. {
  78. return XDP_PASS;
  79. }
  80. char _license[] SEC("license") = "GPL";