em_cmp.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * net/sched/em_cmp.c Simple packet data comparison ematch
  4. *
  5. * Authors: Thomas Graf <tgraf@suug.ch>
  6. */
  7. #include <linux/module.h>
  8. #include <linux/types.h>
  9. #include <linux/kernel.h>
  10. #include <linux/skbuff.h>
  11. #include <linux/tc_ematch/tc_em_cmp.h>
  12. #include <linux/unaligned.h>
  13. #include <net/pkt_cls.h>
  14. static inline int cmp_needs_transformation(struct tcf_em_cmp *cmp)
  15. {
  16. return unlikely(cmp->flags & TCF_EM_CMP_TRANS);
  17. }
  18. static int em_cmp_match(struct sk_buff *skb, struct tcf_ematch *em,
  19. struct tcf_pkt_info *info)
  20. {
  21. struct tcf_em_cmp *cmp = (struct tcf_em_cmp *) em->data;
  22. unsigned char *ptr = tcf_get_base_ptr(skb, cmp->layer);
  23. u32 val = 0;
  24. if (!ptr)
  25. return 0;
  26. ptr += cmp->off;
  27. if (!tcf_valid_offset(skb, ptr, cmp->align))
  28. return 0;
  29. switch (cmp->align) {
  30. case TCF_EM_ALIGN_U8:
  31. val = *ptr;
  32. break;
  33. case TCF_EM_ALIGN_U16:
  34. val = get_unaligned_be16(ptr);
  35. if (cmp_needs_transformation(cmp))
  36. val = be16_to_cpu(val);
  37. break;
  38. case TCF_EM_ALIGN_U32:
  39. /* Worth checking boundaries? The branching seems
  40. * to get worse. Visit again.
  41. */
  42. val = get_unaligned_be32(ptr);
  43. if (cmp_needs_transformation(cmp))
  44. val = be32_to_cpu(val);
  45. break;
  46. default:
  47. return 0;
  48. }
  49. if (cmp->mask)
  50. val &= cmp->mask;
  51. switch (cmp->opnd) {
  52. case TCF_EM_OPND_EQ:
  53. return val == cmp->val;
  54. case TCF_EM_OPND_LT:
  55. return val < cmp->val;
  56. case TCF_EM_OPND_GT:
  57. return val > cmp->val;
  58. }
  59. return 0;
  60. }
  61. static struct tcf_ematch_ops em_cmp_ops = {
  62. .kind = TCF_EM_CMP,
  63. .datalen = sizeof(struct tcf_em_cmp),
  64. .match = em_cmp_match,
  65. .owner = THIS_MODULE,
  66. .link = LIST_HEAD_INIT(em_cmp_ops.link)
  67. };
  68. static int __init init_em_cmp(void)
  69. {
  70. return tcf_em_register(&em_cmp_ops);
  71. }
  72. static void __exit exit_em_cmp(void)
  73. {
  74. tcf_em_unregister(&em_cmp_ops);
  75. }
  76. MODULE_DESCRIPTION("ematch classifier for basic data types(8/16/32 bit) against skb data");
  77. MODULE_LICENSE("GPL");
  78. module_init(init_em_cmp);
  79. module_exit(exit_em_cmp);
  80. MODULE_ALIAS_TCF_EMATCH(TCF_EM_CMP);