xref: /linux/net/sched/em_cmp.c (revision 127fa2ae9e2b1f9b9d876dfaa39fe3640cec5764)
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 
8 #include <linux/module.h>
9 #include <linux/types.h>
10 #include <linux/kernel.h>
11 #include <linux/skbuff.h>
12 #include <linux/tc_ematch/tc_em_cmp.h>
13 #include <linux/unaligned.h>
14 #include <net/pkt_cls.h>
15 
16 static inline int cmp_needs_transformation(struct tcf_em_cmp *cmp)
17 {
18 	return unlikely(cmp->flags & TCF_EM_CMP_TRANS);
19 }
20 
21 static int em_cmp_match(struct sk_buff *skb, struct tcf_ematch *em,
22 			struct tcf_pkt_info *info)
23 {
24 	struct tcf_em_cmp *cmp = (struct tcf_em_cmp *) em->data;
25 	unsigned char *ptr = tcf_get_base_ptr(skb, cmp->layer);
26 	u32 val = 0;
27 
28 	if (!ptr)
29 		return 0;
30 	ptr += cmp->off;
31 	if (!tcf_valid_offset(skb, ptr, cmp->align))
32 		return 0;
33 
34 	switch (cmp->align) {
35 	case TCF_EM_ALIGN_U8:
36 		val = *ptr;
37 		break;
38 
39 	case TCF_EM_ALIGN_U16:
40 		val = get_unaligned_be16(ptr);
41 
42 		if (cmp_needs_transformation(cmp))
43 			val = be16_to_cpu(val);
44 		break;
45 
46 	case TCF_EM_ALIGN_U32:
47 		/* Worth checking boundaries? The branching seems
48 		 * to get worse. Visit again.
49 		 */
50 		val = get_unaligned_be32(ptr);
51 
52 		if (cmp_needs_transformation(cmp))
53 			val = be32_to_cpu(val);
54 		break;
55 
56 	default:
57 		return 0;
58 	}
59 
60 	if (cmp->mask)
61 		val &= cmp->mask;
62 
63 	switch (cmp->opnd) {
64 	case TCF_EM_OPND_EQ:
65 		return val == cmp->val;
66 	case TCF_EM_OPND_LT:
67 		return val < cmp->val;
68 	case TCF_EM_OPND_GT:
69 		return val > cmp->val;
70 	}
71 
72 	return 0;
73 }
74 
75 static struct tcf_ematch_ops em_cmp_ops = {
76 	.kind	  = TCF_EM_CMP,
77 	.datalen  = sizeof(struct tcf_em_cmp),
78 	.match	  = em_cmp_match,
79 	.owner	  = THIS_MODULE,
80 	.link	  = LIST_HEAD_INIT(em_cmp_ops.link)
81 };
82 
83 static int __init init_em_cmp(void)
84 {
85 	return tcf_em_register(&em_cmp_ops);
86 }
87 
88 static void __exit exit_em_cmp(void)
89 {
90 	tcf_em_unregister(&em_cmp_ops);
91 }
92 
93 MODULE_DESCRIPTION("ematch classifier for basic data types(8/16/32 bit) against skb data");
94 MODULE_LICENSE("GPL");
95 
96 module_init(init_em_cmp);
97 module_exit(exit_em_cmp);
98 
99 MODULE_ALIAS_TCF_EMATCH(TCF_EM_CMP);
100