xdp1_kern.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* Copyright (c) 2016 PLUMgrid
  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. #define KBUILD_MODNAME "foo"
  8. #include <uapi/linux/bpf.h>
  9. #include <linux/in.h>
  10. #include <linux/if_ether.h>
  11. #include <linux/if_packet.h>
  12. #include <linux/if_vlan.h>
  13. #include <linux/ip.h>
  14. #include <linux/ipv6.h>
  15. #include <bpf/bpf_helpers.h>
  16. struct {
  17. __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
  18. __type(key, u32);
  19. __type(value, long);
  20. __uint(max_entries, 256);
  21. } rxcnt SEC(".maps");
  22. static int parse_ipv4(void *data, u64 nh_off, void *data_end)
  23. {
  24. struct iphdr *iph = data + nh_off;
  25. if (iph + 1 > data_end)
  26. return 0;
  27. return iph->protocol;
  28. }
  29. static int parse_ipv6(void *data, u64 nh_off, void *data_end)
  30. {
  31. struct ipv6hdr *ip6h = data + nh_off;
  32. if (ip6h + 1 > data_end)
  33. return 0;
  34. return ip6h->nexthdr;
  35. }
  36. SEC("xdp1")
  37. int xdp_prog1(struct xdp_md *ctx)
  38. {
  39. void *data_end = (void *)(long)ctx->data_end;
  40. void *data = (void *)(long)ctx->data;
  41. struct ethhdr *eth = data;
  42. int rc = XDP_DROP;
  43. long *value;
  44. u16 h_proto;
  45. u64 nh_off;
  46. u32 ipproto;
  47. nh_off = sizeof(*eth);
  48. if (data + nh_off > data_end)
  49. return rc;
  50. h_proto = eth->h_proto;
  51. if (h_proto == htons(ETH_P_8021Q) || h_proto == htons(ETH_P_8021AD)) {
  52. struct vlan_hdr *vhdr;
  53. vhdr = data + nh_off;
  54. nh_off += sizeof(struct vlan_hdr);
  55. if (data + nh_off > data_end)
  56. return rc;
  57. h_proto = vhdr->h_vlan_encapsulated_proto;
  58. }
  59. if (h_proto == htons(ETH_P_8021Q) || h_proto == htons(ETH_P_8021AD)) {
  60. struct vlan_hdr *vhdr;
  61. vhdr = data + nh_off;
  62. nh_off += sizeof(struct vlan_hdr);
  63. if (data + nh_off > data_end)
  64. return rc;
  65. h_proto = vhdr->h_vlan_encapsulated_proto;
  66. }
  67. if (h_proto == htons(ETH_P_IP))
  68. ipproto = parse_ipv4(data, nh_off, data_end);
  69. else if (h_proto == htons(ETH_P_IPV6))
  70. ipproto = parse_ipv6(data, nh_off, data_end);
  71. else
  72. ipproto = 0;
  73. value = bpf_map_lookup_elem(&rxcnt, &ipproto);
  74. if (value)
  75. *value += 1;
  76. return rc;
  77. }
  78. char _license[] SEC("license") = "GPL";