Skip to contentSkip to conversation

netlink: optimize the NMLSG_OK macro

PATCH In review Atlas Yu 2 participants 2 messages Sep 12, 2024

Subsystems (2)
lore
Share & tools
lore

Atlas Yu

author
#0 lore raw

PATCH 1/1 netlink: optimize the NMLSG_OK macro

When nlmsg_len >= sizeof(hdr) and nlmsg_len <= len are true, we can set up an inequation: len >= nlmsg_len >= sizeof(hdr), which makes checking len >= sizeof(hdr) useless.

gcc -O3 cannot optimize ok1 to generate the same instructions as ok2 on x86_64 (not investigated on other architectures).
int ok1(int a, int b, int c) { return a >= b && c >= b && c <= a; } int ok2(int a, int b, int c) { return c >= b && c <= a; }

---
 include/uapi/linux/netlink.h | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
include/uapi/linux/netlink.h +1 -2
index f87aaf28a649..85dcfa6b33af 100644
@@ -104,8 +104,7 @@ struct nlmsghdr {
 #define NLMSG_NEXT(nlh,len)	 ((len) -= NLMSG_ALIGN((nlh)->nlmsg_len), \
 				  (struct nlmsghdr *)(((char *)(nlh)) + \
 				  NLMSG_ALIGN((nlh)->nlmsg_len)))
-#define NLMSG_OK(nlh,len) ((len) >= (int)sizeof(struct nlmsghdr) && \
-			   (nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \
+#define NLMSG_OK(nlh,len) ((nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \
 			   (nlh)->nlmsg_len <= (len))
 #define NLMSG_PAYLOAD(nlh,len) ((nlh)->nlmsg_len - NLMSG_SPACE((len)))
 
Signature · 1 line
2.43.0
#1 lore raw

From: Atlas Yu <[email protected]>
Date: Thu, 12 Sep 2024 10:40:18 +0800

Quoted 19 lines

When nlmsg_len >= sizeof(hdr) and nlmsg_len <= len are true, we can set up an inequation: len >= nlmsg_len >= sizeof(hdr), which makes checking len >= sizeof(hdr) useless.

gcc -O3 cannot optimize ok1 to generate the same instructions as ok2 on x86_64 (not investigated on other architectures).
int ok1(int a, int b, int c) { return a >= b && c >= b && c <= a; } int ok2(int a, int b, int c) { return c >= b && c <= a; }

---
 include/uapi/linux/netlink.h | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
include/uapi/linux/netlink.h +0 -0
index f87aaf28a649..85dcfa6b33af 100644

include/uapi/linux/netlink.h struct nlmsghdr { · line 107

Quoted 6 lines
include/uapi/linux/netlink.h +1 -2
@@ -104,8 +104,7 @@ struct nlmsghdr {
 #define NLMSG_NEXT(nlh,len)	 ((len) -= NLMSG_ALIGN((nlh)->nlmsg_len), \
 				  (struct nlmsghdr *)(((char *)(nlh)) + \
 				  NLMSG_ALIGN((nlh)->nlmsg_len)))
-#define NLMSG_OK(nlh,len) ((len) >= (int)sizeof(struct nlmsghdr) && \
-			   (nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \
+#define NLMSG_OK(nlh,len) ((nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \

If len < sizeof(struct nlmsghdr)
(more specifically, offsetof(struct nlmsghdr, nlmsg_len)), you can't access nlmsg_len; it returns a garbage.

Quoted 6 lines
include/uapi/linux/netlink.h +0 -0
 			   (nlh)->nlmsg_len <= (len))
 #define NLMSG_PAYLOAD(nlh,len) ((nlh)->nlmsg_len - NLMSG_SPACE((len)))
 
Signature · 1 line
2.43.0