Skip to contentSkip to conversation

Add skb + xdp dynptrs

PATCH Superseded Joanne Koong 1 participant 5 messages Aug 22, 2022

Subsystems (8)

v3 of 13 Superseded Latest is v13 →

lore
Share & tools
lore
#0 lore raw

v3 cover Add skb + xdp dynptrs

This patchset is the 2nd in the dynptr series. The 1st can be found here [0].

This patchset adds skb and xdp type dynptrs, which have two main benefits for packet parsing:
* allowing operations on sizes that are not statically known at compile-time (eg variable-sized accesses).
* more ergonomic and less brittle iteration through data (eg does not need manual if checking for being within bounds of data_end)

When comparing the differences in runtime for packet parsing without dynptrs vs. with dynptrs for the more simple cases, there is no noticeable difference. For the more complex cases where lengths are non-statically known at compile time, there can be a significant speed-up when using dynptrs (eg a 2x speed up for cls redirection). Patch 3 contains more details as well as examples of how to use skb and xdp dynptrs.

[0] https://lore.kernel.org/bpf/[email protected]/

--
Changelog:

v2 = https://lore.kernel.org/bpf/[email protected]/
v2 -> v3
* Fix kernel test robot build test errors

v1 = https://lore.kernel.org/bpf/[email protected]/
v1 -> v2
* Return data slices to rd-only skb dynptrs (Martin)
* bpf_dynptr_write allows writes to frags for skb dynptrs, but always invalidates associated data slices (Martin)
* Use switch casing instead of ifs (Andrii)
* Use 0xFD for experimental kind number in the selftest (Zvi)
* Put selftest conversions w/ dynptrs into new files (Alexei)
* Add new selftest "test_cls_redirect_dynptr.c"

Joanne Koong (3):
bpf: Add skb dynptrs
bpf: Add xdp dynptrs
selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

 include/linux/bpf.h                           |  14 +-
 include/linux/filter.h                        |   7 +
 include/uapi/linux/bpf.h                      |  59 +-
 kernel/bpf/helpers.c                          |  93 +-
 kernel/bpf/verifier.c                         | 105 +-
 net/core/filter.c                             |  99 +-
 tools/include/uapi/linux/bpf.h                |  59 +-
 .../selftests/bpf/prog_tests/cls_redirect.c   |  25 +
 .../testing/selftests/bpf/prog_tests/dynptr.c | 132 ++-
 .../selftests/bpf/prog_tests/l4lb_all.c       |   2 +
 .../bpf/prog_tests/parse_tcp_hdr_opt.c        |  85 ++
 .../selftests/bpf/prog_tests/xdp_attach.c     |   9 +-
 .../testing/selftests/bpf/progs/dynptr_fail.c | 111 ++
 .../selftests/bpf/progs/dynptr_success.c      |  29 +
 .../bpf/progs/test_cls_redirect_dynptr.c      | 968 ++++++++++++++++++
 .../bpf/progs/test_l4lb_noinline_dynptr.c     | 468 +++++++++
 .../bpf/progs/test_parse_tcp_hdr_opt.c        | 119 +++
 .../bpf/progs/test_parse_tcp_hdr_opt_dynptr.c | 110 ++
 .../selftests/bpf/progs/test_xdp_dynptr.c     | 240 +++++
 .../selftests/bpf/test_tcp_hdr_options.h      |   1 +
 20 files changed, 2649 insertions(+), 86 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/parse_tcp_hdr_opt.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_cls_redirect_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_xdp_dynptr.c
Signature · 1 line
2.30.2
#1 lore raw

PATCH v3 1/3 bpf: Add skb dynptrs

Add skb dynptrs, which are dynptrs whose underlying pointer points to a skb. The dynptr acts on skb data. skb dynptrs have two main benefits. One is that they allow operations on sizes that are not statically known at compile-time (eg variable-sized accesses). Another is that parsing the packet data through dynptrs (instead of through direct access of skb->data and skb->data_end) can be more ergonomic and less brittle (eg does not need manual if checking for being within bounds of data_end).

For bpf prog types that don't support writes on skb data, the dynptr is read-only. For reads and writes through the bpf_dynptr_read() and bpf_dynptr_write() interfaces, this supports reading and writing into data in the non-linear paged buffers. For data slices (through the bpf_dynptr_data() interface), if the data is in a paged buffer, the user must first call bpf_skb_pull_data() to pull the data into the linear portion. The returned data slice from a call to bpf_dynptr_data() is of reg type PTR_TO_PACKET | PTR_MAYBE_NULL.

Any bpf_dynptr_write() automatically invalidates any prior data slices to the skb dynptr. This is because a bpf_dynptr_write() may be writing to data in a paged buffer, so it will need to pull the buffer first into the head. The reason it needs to be pulled instead of writing directly to the paged buffers is because they may be cloned (only the head of the skb is by default uncloned). As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head (the verifier has no way of differentiating whether the write is to the head or paged buffers during program load time). Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well. Whenever such a helper call is made, the verifier marks any PTR_TO_PACKET reg type (which includes skb dynptr slices since they are PTR_TO_PACKETs) as unknown. The stack trace for this is check_helper_call() -> clear_all_pkt_pointers() -> __clear_all_pkt_pointers() -> mark_reg_unknown()

For examples of how skb dynptrs can be used, please see the attached selftests.

---
 include/linux/bpf.h            |  8 ++-
 include/linux/filter.h         |  4 ++
 include/uapi/linux/bpf.h       | 40 ++++++++++++--
 kernel/bpf/helpers.c           | 81 +++++++++++++++++++++++++---
 kernel/bpf/verifier.c          | 99 ++++++++++++++++++++++++++++------
 net/core/filter.c              | 53 ++++++++++++++++--
 tools/include/uapi/linux/bpf.h | 40 ++++++++++++--
 7 files changed, 289 insertions(+), 36 deletions(-)
include/linux/bpf.h +7 -1
index 39bd36359c1e..a1fdc4d350c0 100644
@@ -407,11 +407,14 @@ enum bpf_type_flag {
 	/* Size is known at compile time. */
 	MEM_FIXED_SIZE		= BIT(10 + BPF_BASE_TYPE_BITS),
 
+	/* DYNPTR points to sk_buff */
+	DYNPTR_TYPE_SKB		= BIT(11 + BPF_BASE_TYPE_BITS),
+
 	__BPF_TYPE_FLAG_MAX,
 	__BPF_TYPE_LAST_FLAG	= __BPF_TYPE_FLAG_MAX - 1,
 };
 
-#define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF)
+#define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB)
 
 /* Max number of base types. */
 #define BPF_BASE_TYPE_LIMIT	(1UL << BPF_BASE_TYPE_BITS)
@@ -2570,12 +2573,15 @@ enum bpf_dynptr_type {
 	BPF_DYNPTR_TYPE_LOCAL,
 	/* Underlying data is a ringbuf record */
 	BPF_DYNPTR_TYPE_RINGBUF,
+	/* Underlying data is a sk_buff */
+	BPF_DYNPTR_TYPE_SKB,
 };
 
 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
 		     enum bpf_dynptr_type type, u32 offset, u32 size);
 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr);
 int bpf_dynptr_check_size(u32 size);
+void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr);
 
 #ifdef CONFIG_BPF_LSM
 void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype);
include/linux/filter.h +4 -0
index a5f21dc3c432..649063d9cbfd 100644
@@ -1532,4 +1532,8 @@ static __always_inline int __bpf_xdp_redirect_map(struct bpf_map *map, u32 ifind
 	return XDP_REDIRECT;
 }
 
+int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len);
+int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
+			  u32 len, u64 flags);
+
 #endif /* __LINUX_FILTER_H__ */
include/uapi/linux/bpf.h +37 -3
index 934a2a8beb87..320e6b95d95c 100644
@@ -5253,11 +5253,22 @@ union bpf_attr {
  *	Description
  *		Write *len* bytes from *src* into *dst*, starting from *offset*
  *		into *dst*.
- *		*flags* is currently unused.
+ *
+ *		*flags* must be 0 except for skb-type dynptrs.
+ *
+ *		For skb-type dynptrs:
+ *		    *  All data slices of the dynptr are automatically
+ *		       invalidated after **bpf_dynptr_write**\ (). If you wish to
+ *		       avoid this, please perform the write using direct data slices
+ *		       instead.
+ *
+ *		    *  For *flags*, please see the flags accepted by
+ *		       **bpf_skb_store_bytes**\ ().
  *	Return
  *		0 on success, -E2BIG if *offset* + *len* exceeds the length
  *		of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst*
- *		is a read-only dynptr or if *flags* is not 0.
+ *		is a read-only dynptr or if *flags* is not correct. For skb-type dynptrs,
+ *		other errors correspond to errors returned by **bpf_skb_store_bytes**\ ().
  *
  * void *bpf_dynptr_data(struct bpf_dynptr *ptr, u32 offset, u32 len)
  *	Description
@@ -5265,10 +5276,20 @@ union bpf_attr {
  *
  *		*len* must be a statically known value. The returned data slice
  *		is invalidated whenever the dynptr is invalidated.
+ *
+ *		For skb-type dynptrs:
+ *		    * If *offset* + *len* extends into the skb's paged buffers,
+ *		      the user should manually pull the skb with **bpf_skb_pull_data**\ ()
+ *		      and try again.
+ *
+ *		    * The data slice is automatically invalidated anytime
+ *		      **bpf_dynptr_write**\ () or a helper call that changes
+ *		      the underlying packet buffer (eg **bpf_skb_pull_data**\ ())
+ *		      is called.
  *	Return
  *		Pointer to the underlying dynptr data, NULL if the dynptr is
  *		read-only, if the dynptr is invalid, or if the offset and length
- *		is out of bounds.
+ *		is out of bounds or in a paged buffer for skb-type dynptrs.
  *
  * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
  *	Description
@@ -5355,6 +5376,18 @@ union bpf_attr {
  *	Return
  *		Current *ktime*.
  *
+ * long bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags, struct bpf_dynptr *ptr)
+ *	Description
+ *		Get a dynptr to the data in *skb*. *skb* must be the BPF program
+ *		context. Depending on program type, the dynptr may be read-only.
+ *
+ *		Calls that change the *skb*'s underlying packet buffer
+ *		(eg **bpf_skb_pull_data**\ ()) do not invalidate the dynptr, but
+ *		they do invalidate any data slices associated with the dynptr.
+ *
+ *		*flags* is currently unused, it must be 0 for now.
+ *	Return
+ *		0 on success or -EINVAL if flags is not 0.
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -5566,6 +5599,7 @@ union bpf_attr {
 	FN(tcp_raw_check_syncookie_ipv4),	\
 	FN(tcp_raw_check_syncookie_ipv6),	\
 	FN(ktime_get_tai_ns),		\
+	FN(dynptr_from_skb),		\
 	/* */
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/helpers.c +73 -8

133 lines not on this page · raw message

kernel/bpf/verifier.c +82 -17

151 lines not on this page · raw message

net/core/filter.c +49 -4

107 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +37 -3
index 1d6085e15fc8..3f1800a2b77c 100644
@@ -5253,11 +5253,22 @@ union bpf_attr {
  *	Description
  *		Write *len* bytes from *src* into *dst*, starting from *offset*
  *		into *dst*.
- *		*flags* is currently unused.
+ *
+ *		*flags* must be 0 except for skb-type dynptrs.
+ *
+ *		For skb-type dynptrs:
+ *		    *  All data slices of the dynptr are automatically
+ *		       invalidated after **bpf_dynptr_write**\ (). If you wish to
+ *		       avoid this, please perform the write using direct data slices
+ *		       instead.
+ *
+ *		    *  For *flags*, please see the flags accepted by
+ *		       **bpf_skb_store_bytes**\ ().
  *	Return
  *		0 on success, -E2BIG if *offset* + *len* exceeds the length
  *		of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst*
- *		is a read-only dynptr or if *flags* is not 0.
+ *		is a read-only dynptr or if *flags* is not correct. For skb-type dynptrs,
+ *		other errors correspond to errors returned by **bpf_skb_store_bytes**\ ().
  *
  * void *bpf_dynptr_data(struct bpf_dynptr *ptr, u32 offset, u32 len)
  *	Description
@@ -5265,10 +5276,20 @@ union bpf_attr {
  *
  *		*len* must be a statically known value. The returned data slice
  *		is invalidated whenever the dynptr is invalidated.
+ *
+ *		For skb-type dynptrs:
+ *		    * If *offset* + *len* extends into the skb's paged buffers,
+ *		      the user should manually pull the skb with **bpf_skb_pull_data**\ ()
+ *		      and try again.
+ *
+ *		    * The data slice is automatically invalidated anytime
+ *		      **bpf_dynptr_write**\ () or a helper call that changes
+ *		      the underlying packet buffer (eg **bpf_skb_pull_data**\ ())
+ *		      is called.
  *	Return
  *		Pointer to the underlying dynptr data, NULL if the dynptr is
  *		read-only, if the dynptr is invalid, or if the offset and length
- *		is out of bounds.
+ *		is out of bounds or in a paged buffer for skb-type dynptrs.
  *
  * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
  *	Description
@@ -5355,6 +5376,18 @@ union bpf_attr {
  *	Return
  *		Current *ktime*.
  *
+ * long bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags, struct bpf_dynptr *ptr)
+ *	Description
+ *		Get a dynptr to the data in *skb*. *skb* must be the BPF program
+ *		context. Depending on program type, the dynptr may be read-only.
+ *
+ *		Calls that change the *skb*'s underlying packet buffer
+ *		(eg **bpf_skb_pull_data**\ ()) do not invalidate the dynptr, but
+ *		they do invalidate any data slices associated with the dynptr.
+ *
+ *		*flags* is currently unused, it must be 0 for now.
+ *	Return
+ *		0 on success or -EINVAL if flags is not 0.
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -5566,6 +5599,7 @@ union bpf_attr {
 	FN(tcp_raw_check_syncookie_ipv4),	\
 	FN(tcp_raw_check_syncookie_ipv6),	\
 	FN(ktime_get_tai_ns),		\
+	FN(dynptr_from_skb),		\
 	/* */
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.30.2
#2 lore raw

Re: [PATCH bpf-next v3 1/3] bpf: Add skb dynptrs

Quoted 73 lines · Joanne Koong

Add skb dynptrs, which are dynptrs whose underlying pointer points to a skb. The dynptr acts on skb data. skb dynptrs have two main benefits. One is that they allow operations on sizes that are not statically known at compile-time (eg variable-sized accesses). Another is that parsing the packet data through dynptrs (instead of through direct access of skb->data and skb->data_end) can be more ergonomic and less brittle (eg does not need manual if checking for being within bounds of data_end).

For bpf prog types that don't support writes on skb data, the dynptr is read-only. For reads and writes through the bpf_dynptr_read() and bpf_dynptr_write() interfaces, this supports reading and writing into data in the non-linear paged buffers. For data slices (through the bpf_dynptr_data() interface), if the data is in a paged buffer, the user must first call bpf_skb_pull_data() to pull the data into the linear portion. The returned data slice from a call to bpf_dynptr_data() is of reg type PTR_TO_PACKET | PTR_MAYBE_NULL.

Any bpf_dynptr_write() automatically invalidates any prior data slices to the skb dynptr. This is because a bpf_dynptr_write() may be writing to data in a paged buffer, so it will need to pull the buffer first into the head. The reason it needs to be pulled instead of writing directly to the paged buffers is because they may be cloned (only the head of the skb is by default uncloned). As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head (the verifier has no way of differentiating whether the write is to the head or paged buffers during program load time). Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well. Whenever such a helper call is made, the verifier marks any PTR_TO_PACKET reg type (which includes skb dynptr slices since they are PTR_TO_PACKETs) as unknown. The stack trace for this is check_helper_call() -> clear_all_pkt_pointers() -> __clear_all_pkt_pointers() -> mark_reg_unknown()

For examples of how skb dynptrs can be used, please see the attached selftests.

---
 include/linux/bpf.h            |  8 ++-
 include/linux/filter.h         |  4 ++
 include/uapi/linux/bpf.h       | 40 ++++++++++++--
 kernel/bpf/helpers.c           | 81 +++++++++++++++++++++++++---
 kernel/bpf/verifier.c          | 99 ++++++++++++++++++++++++++++------
 net/core/filter.c              | 53 ++++++++++++++++--
 tools/include/uapi/linux/bpf.h | 40 ++++++++++++--
 7 files changed, 289 insertions(+), 36 deletions(-)
include/linux/bpf.h +4 -1
index 39bd36359c1e..a1fdc4d350c0 100644
@@ -407,11 +407,14 @@ enum bpf_type_flag {
        /* Size is known at compile time. */
        MEM_FIXED_SIZE          = BIT(10 + BPF_BASE_TYPE_BITS),
 
+       /* DYNPTR points to sk_buff */
+       DYNPTR_TYPE_SKB         = BIT(11 + BPF_BASE_TYPE_BITS),
+
        __BPF_TYPE_FLAG_MAX,
        __BPF_TYPE_LAST_FLAG    = __BPF_TYPE_FLAG_MAX - 1,
 };
 
-#define DYNPTR_TYPE_FLAG_MASK  (DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF)
+#define DYNPTR_TYPE_FLAG_MASK  (DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB)
 
 /* Max number of base types. */
 #define BPF_BASE_TYPE_LIMIT    (1UL << BPF_BASE_TYPE_BITS)
@@ -2570,12 +2573,15 @@ enum bpf_dynptr_type {
        BPF_DYNPTR_TYPE_LOCAL,
        /* Underlying data is a ringbuf record */

include/linux/bpf.h enum bpf_dynptr_type { · line 2584

Quoted 10 lines
include/linux/bpf.h +3 -0
        BPF_DYNPTR_TYPE_RINGBUF,
+       /* Underlying data is a sk_buff */
+       BPF_DYNPTR_TYPE_SKB,
 };
 
 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
                     enum bpf_dynptr_type type, u32 offset, u32 size);
 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr);
 int bpf_dynptr_check_size(u32 size);
+void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr);

I forgot to "git commit --amend" the test robot build error fix-ups for this version (as such, this v3 is the exact same as v2 [0]). I'll submit v4 that includes the fix-ups.

[0] https://lore.kernel.org/bpf/[email protected]/

Quoted 600 lines
include/linux/bpf.h +0 -0
 #ifdef CONFIG_BPF_LSM
 void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype);
include/linux/filter.h +4 -0
index a5f21dc3c432..649063d9cbfd 100644
@@ -1532,4 +1532,8 @@ static __always_inline int __bpf_xdp_redirect_map(struct bpf_map *map, u32 ifind
        return XDP_REDIRECT;
 }
 
+int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len);
+int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
+                         u32 len, u64 flags);
+
 #endif /* __LINUX_FILTER_H__ */
include/uapi/linux/bpf.h +37 -3
index 934a2a8beb87..320e6b95d95c 100644
@@ -5253,11 +5253,22 @@ union bpf_attr {
  *     Description
  *             Write *len* bytes from *src* into *dst*, starting from *offset*
  *             into *dst*.
- *             *flags* is currently unused.
+ *
+ *             *flags* must be 0 except for skb-type dynptrs.
+ *
+ *             For skb-type dynptrs:
+ *                 *  All data slices of the dynptr are automatically
+ *                    invalidated after **bpf_dynptr_write**\ (). If you wish to
+ *                    avoid this, please perform the write using direct data slices
+ *                    instead.
+ *
+ *                 *  For *flags*, please see the flags accepted by
+ *                    **bpf_skb_store_bytes**\ ().
  *     Return
  *             0 on success, -E2BIG if *offset* + *len* exceeds the length
  *             of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst*
- *             is a read-only dynptr or if *flags* is not 0.
+ *             is a read-only dynptr or if *flags* is not correct. For skb-type dynptrs,
+ *             other errors correspond to errors returned by **bpf_skb_store_bytes**\ ().
  *
  * void *bpf_dynptr_data(struct bpf_dynptr *ptr, u32 offset, u32 len)
  *     Description
@@ -5265,10 +5276,20 @@ union bpf_attr {
  *
  *             *len* must be a statically known value. The returned data slice
  *             is invalidated whenever the dynptr is invalidated.
+ *
+ *             For skb-type dynptrs:
+ *                 * If *offset* + *len* extends into the skb's paged buffers,
+ *                   the user should manually pull the skb with **bpf_skb_pull_data**\ ()
+ *                   and try again.
+ *
+ *                 * The data slice is automatically invalidated anytime
+ *                   **bpf_dynptr_write**\ () or a helper call that changes
+ *                   the underlying packet buffer (eg **bpf_skb_pull_data**\ ())
+ *                   is called.
  *     Return
  *             Pointer to the underlying dynptr data, NULL if the dynptr is
  *             read-only, if the dynptr is invalid, or if the offset and length
- *             is out of bounds.
+ *             is out of bounds or in a paged buffer for skb-type dynptrs.
  *
  * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
  *     Description
@@ -5355,6 +5376,18 @@ union bpf_attr {
  *     Return
  *             Current *ktime*.
  *
+ * long bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags, struct bpf_dynptr *ptr)
+ *     Description
+ *             Get a dynptr to the data in *skb*. *skb* must be the BPF program
+ *             context. Depending on program type, the dynptr may be read-only.
+ *
+ *             Calls that change the *skb*'s underlying packet buffer
+ *             (eg **bpf_skb_pull_data**\ ()) do not invalidate the dynptr, but
+ *             they do invalidate any data slices associated with the dynptr.
+ *
+ *             *flags* is currently unused, it must be 0 for now.
+ *     Return
+ *             0 on success or -EINVAL if flags is not 0.
  */
 #define __BPF_FUNC_MAPPER(FN)          \
        FN(unspec),                     \
@@ -5566,6 +5599,7 @@ union bpf_attr {
        FN(tcp_raw_check_syncookie_ipv4),       \
        FN(tcp_raw_check_syncookie_ipv6),       \
        FN(ktime_get_tai_ns),           \
+       FN(dynptr_from_skb),            \
        /* */
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/helpers.c +73 -8
index 3c1b9bbcf971..471a01a9b6ae 100644
@@ -1437,11 +1437,21 @@ static bool bpf_dynptr_is_rdonly(struct bpf_dynptr_kern *ptr)
        return ptr->size & DYNPTR_RDONLY_BIT;
 }
 
+void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
+{
+       ptr->size |= DYNPTR_RDONLY_BIT;
+}
+
 static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
 {
        ptr->size |= type << DYNPTR_TYPE_SHIFT;
 }
 
+static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr)
+{
+       return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT;
+}
+
 static u32 bpf_dynptr_get_size(struct bpf_dynptr_kern *ptr)
 {
        return ptr->size & DYNPTR_SIZE_MASK;
@@ -1512,6 +1522,7 @@ static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
 BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, struct bpf_dynptr_kern *, src,
           u32, offset, u64, flags)
 {
+       enum bpf_dynptr_type type;
        int err;
 
        if (!src->data || flags)
@@ -1521,9 +1532,19 @@ BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, struct bpf_dynptr_kern *, src
        if (err)
                return err;
 
-       memcpy(dst, src->data + src->offset + offset, len);
+       type = bpf_dynptr_get_type(src);
 
-       return 0;
+       switch (type) {
+       case BPF_DYNPTR_TYPE_LOCAL:
+       case BPF_DYNPTR_TYPE_RINGBUF:
+               memcpy(dst, src->data + src->offset + offset, len);
+               return 0;
+       case BPF_DYNPTR_TYPE_SKB:
+               return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
+       default:
+               WARN(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
+               return -EFAULT;
+       }
 }
 
 static const struct bpf_func_proto bpf_dynptr_read_proto = {
@@ -1540,18 +1561,32 @@ static const struct bpf_func_proto bpf_dynptr_read_proto = {
 BPF_CALL_5(bpf_dynptr_write, struct bpf_dynptr_kern *, dst, u32, offset, void *, src,
           u32, len, u64, flags)
 {
+       enum bpf_dynptr_type type;
        int err;
 
-       if (!dst->data || flags || bpf_dynptr_is_rdonly(dst))
+       if (!dst->data || bpf_dynptr_is_rdonly(dst))
                return -EINVAL;
 
        err = bpf_dynptr_check_off_len(dst, offset, len);
        if (err)
                return err;
 
-       memcpy(dst->data + dst->offset + offset, src, len);
+       type = bpf_dynptr_get_type(dst);
 
-       return 0;
+       switch (type) {
+       case BPF_DYNPTR_TYPE_LOCAL:
+       case BPF_DYNPTR_TYPE_RINGBUF:
+               if (flags)
+                       return -EINVAL;
+               memcpy(dst->data + dst->offset + offset, src, len);
+               return 0;
+       case BPF_DYNPTR_TYPE_SKB:
+               return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
+                                            flags);
+       default:
+               WARN(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
+               return -EFAULT;
+       }
 }
 
 static const struct bpf_func_proto bpf_dynptr_write_proto = {
@@ -1567,6 +1602,9 @@ static const struct bpf_func_proto bpf_dynptr_write_proto = {
 
 BPF_CALL_3(bpf_dynptr_data, struct bpf_dynptr_kern *, ptr, u32, offset, u32, len)
 {
+       enum bpf_dynptr_type type;
+       bool is_rdonly;
+       void *data;
        int err;
 
        if (!ptr->data)
@@ -1576,10 +1614,37 @@ BPF_CALL_3(bpf_dynptr_data, struct bpf_dynptr_kern *, ptr, u32, offset, u32, len
        if (err)
                return 0;
 
-       if (bpf_dynptr_is_rdonly(ptr))
-               return 0;
+       type = bpf_dynptr_get_type(ptr);
+
+       /* Only skb dynptrs can get read-only data slices, because the
+        * verifier enforces PTR_TO_PACKET accesses
+        */
+       is_rdonly = bpf_dynptr_is_rdonly(ptr);
+
+       switch (type) {
+       case BPF_DYNPTR_TYPE_LOCAL:
+       case BPF_DYNPTR_TYPE_RINGBUF:
+               if (is_rdonly)
+                       return 0;
+
+               data = ptr->data;
+               break;
+       case BPF_DYNPTR_TYPE_SKB:
+       {
+               struct sk_buff *skb = ptr->data;
 
-       return (unsigned long)(ptr->data + ptr->offset + offset);
+               /* if the data is paged, the caller needs to pull it first */
+               if (ptr->offset + offset + len > skb->len - skb->data_len)
+                       return 0;
+
+               data = skb->data;
+               break;
+       }
+       default:
+               WARN(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
+               return 0;
+       }
+       return (unsigned long)(data + ptr->offset + offset);
 }
 
 static const struct bpf_func_proto bpf_dynptr_data_proto = {
kernel/bpf/verifier.c +82 -17
index 2c1f8069f7b7..1ea295f47525 100644
@@ -684,6 +684,8 @@ static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
                return BPF_DYNPTR_TYPE_LOCAL;
        case DYNPTR_TYPE_RINGBUF:
                return BPF_DYNPTR_TYPE_RINGBUF;
+       case DYNPTR_TYPE_SKB:
+               return BPF_DYNPTR_TYPE_SKB;
        default:
                return BPF_DYNPTR_TYPE_INVALID;
        }
@@ -5826,12 +5828,29 @@ int check_func_arg_reg_off(struct bpf_verifier_env *env,
        return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
 }
 
-static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
+static struct bpf_reg_state *get_dynptr_arg_reg(const struct bpf_func_proto *fn,
+                                               struct bpf_reg_state *regs)
+{
+       int i;
+
+       for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
+               if (arg_type_is_dynptr(fn->arg_type[i]))
+                       return &regs[BPF_REG_1 + i];
+
+       return NULL;
+}
+
+static enum bpf_dynptr_type stack_slot_get_dynptr_info(struct bpf_verifier_env *env,
+                                                      struct bpf_reg_state *reg,
+                                                      int *ref_obj_id)
 {
        struct bpf_func_state *state = func(env, reg);
        int spi = get_spi(reg->off);
 
-       return state->stack[spi].spilled_ptr.id;
+       if (ref_obj_id)
+               *ref_obj_id = state->stack[spi].spilled_ptr.id;
+
+       return state->stack[spi].spilled_ptr.dynptr.type;
 }
 
 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
@@ -6056,7 +6075,8 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
                        case DYNPTR_TYPE_RINGBUF:
                                err_extra = "ringbuf ";
                                break;
-                       default:
+                       case DYNPTR_TYPE_SKB:
+                               err_extra = "skb ";
                                break;
                        }
 
@@ -7149,6 +7169,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 {
        enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
        const struct bpf_func_proto *fn = NULL;
+       enum bpf_dynptr_type dynptr_type;
        enum bpf_return_type ret_type;
        enum bpf_type_flag ret_flag;
        struct bpf_reg_state *regs;
@@ -7320,24 +7341,43 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
                        }
                }
                break;
-       case BPF_FUNC_dynptr_data:
-               for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
-                       if (arg_type_is_dynptr(fn->arg_type[i])) {
-                               if (meta.ref_obj_id) {
-                                       verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
-                                       return -EFAULT;
-                               }
-                               /* Find the id of the dynptr we're tracking the reference of */
-                               meta.ref_obj_id = stack_slot_get_id(env, &regs[BPF_REG_1 + i]);
-                               break;
-                       }
+       case BPF_FUNC_dynptr_write:
+       {
+               struct bpf_reg_state *reg;
+
+               reg = get_dynptr_arg_reg(fn, regs);
+               if (!reg) {
+                       verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
+                       return -EFAULT;
                }
-               if (i == MAX_BPF_FUNC_REG_ARGS) {
+
+               /* bpf_dynptr_write() for skb-type dynptrs may pull the skb, so we must
+                * invalidate all data slices associated with it
+                */
+               if (stack_slot_get_dynptr_info(env, reg, NULL) == BPF_DYNPTR_TYPE_SKB)
+                       changes_data = true;
+
+               break;
+       }
+       case BPF_FUNC_dynptr_data:
+       {
+               struct bpf_reg_state *reg;
+
+               reg = get_dynptr_arg_reg(fn, regs);
+               if (!reg) {
                        verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
                        return -EFAULT;
                }
+
+               if (meta.ref_obj_id) {
+                       verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
+                       return -EFAULT;
+               }
+
+               dynptr_type = stack_slot_get_dynptr_info(env, reg, &meta.ref_obj_id);
                break;
        }
+       }
 
        if (err)
                return err;
@@ -7397,8 +7437,15 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
                break;
        case RET_PTR_TO_ALLOC_MEM:
                mark_reg_known_zero(env, regs, BPF_REG_0);
-               regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
-               regs[BPF_REG_0].mem_size = meta.mem_size;
+
+               if (func_id == BPF_FUNC_dynptr_data &&
+                   dynptr_type == BPF_DYNPTR_TYPE_SKB) {
+                       regs[BPF_REG_0].type = PTR_TO_PACKET | ret_flag;
+                       regs[BPF_REG_0].range = meta.mem_size;
+               } else {
+                       regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
+                       regs[BPF_REG_0].mem_size = meta.mem_size;
+               }
                break;
        case RET_PTR_TO_MEM_OR_BTF_ID:
        {
@@ -14141,6 +14188,24 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
                        goto patch_call_imm;
                }
 
+               if (insn->imm == BPF_FUNC_dynptr_from_skb) {
+                       bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
+
+                       insn_buf[0] = BPF_MOV32_IMM(BPF_REG_4, is_rdonly);
+                       insn_buf[1] = *insn;
+                       cnt = 2;
+
+                       new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
+                       if (!new_prog)
+                               return -ENOMEM;
+
+                       delta += cnt - 1;
+                       env->prog = new_prog;
+                       prog = new_prog;
+                       insn = new_prog->insnsi + i + delta;
+                       goto patch_call_imm;
+               }
+
                /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
                 * and other inlining handlers are currently limited to 64 bit
                 * only.
net/core/filter.c +49 -4
index 1acfaffeaf32..5b204b42fb3e 100644
@@ -1681,8 +1681,8 @@ static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
                skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
 }
 
-BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
-          const void *, from, u32, len, u64, flags)
+int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
+                         u32 len, u64 flags)
 {
        void *ptr;
 
@@ -1707,6 +1707,12 @@ BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
        return 0;
 }
 
+BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
+          const void *, from, u32, len, u64, flags)
+{
+       return __bpf_skb_store_bytes(skb, offset, from, len, flags);
+}
+
 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
        .func           = bpf_skb_store_bytes,
        .gpl_only       = false,
@@ -1718,8 +1724,7 @@ static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
        .arg5_type      = ARG_ANYTHING,
 };
 
-BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
-          void *, to, u32, len)
+int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len)
 {
        void *ptr;
 
@@ -1738,6 +1743,12 @@ BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
        return -EFAULT;
 }
 
+BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
+          void *, to, u32, len)
+{
+       return __bpf_skb_load_bytes(skb, offset, to, len);
+}
+
 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
        .func           = bpf_skb_load_bytes,
        .gpl_only       = false,
@@ -1849,6 +1860,32 @@ static const struct bpf_func_proto bpf_skb_pull_data_proto = {
        .arg2_type      = ARG_ANYTHING,
 };
 
+/* is_rdonly is set by the verifier */
+BPF_CALL_4(bpf_dynptr_from_skb, struct sk_buff *, skb, u64, flags,
+          struct bpf_dynptr_kern *, ptr, u32, is_rdonly)
+{
+       if (flags) {
+               bpf_dynptr_set_null(ptr);
+               return -EINVAL;
+       }
+
+       bpf_dynptr_init(ptr, skb, BPF_DYNPTR_TYPE_SKB, 0, skb->len);
+
+       if (is_rdonly)
+               bpf_dynptr_set_rdonly(ptr);
+
+       return 0;
+}
+
+static const struct bpf_func_proto bpf_dynptr_from_skb_proto = {
+       .func           = bpf_dynptr_from_skb,
+       .gpl_only       = false,
+       .ret_type       = RET_INTEGER,
+       .arg1_type      = ARG_PTR_TO_CTX,
+       .arg2_type      = ARG_ANYTHING,
+       .arg3_type      = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_SKB | MEM_UNINIT,
+};
+
 BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk)
 {
        return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL;
@@ -7726,6 +7763,8 @@ sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
                return &bpf_get_socket_uid_proto;
        case BPF_FUNC_perf_event_output:
                return &bpf_skb_event_output_proto;
+       case BPF_FUNC_dynptr_from_skb:
+               return &bpf_dynptr_from_skb_proto;
        default:
                return bpf_sk_base_func_proto(func_id);
        }
@@ -7909,6 +7948,8 @@ tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
                return &bpf_tcp_raw_check_syncookie_ipv6_proto;
 #endif
 #endif
+       case BPF_FUNC_dynptr_from_skb:
+               return &bpf_dynptr_from_skb_proto;
        default:
                return bpf_sk_base_func_proto(func_id);
        }
@@ -8104,6 +8145,8 @@ sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
        case BPF_FUNC_skc_lookup_tcp:
                return &bpf_skc_lookup_tcp_proto;
 #endif
+       case BPF_FUNC_dynptr_from_skb:
+               return &bpf_dynptr_from_skb_proto;
        default:
                return bpf_sk_base_func_proto(func_id);
        }
@@ -8142,6 +8185,8 @@ lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
                return &bpf_get_smp_processor_id_proto;
        case BPF_FUNC_skb_under_cgroup:
                return &bpf_skb_under_cgroup_proto;
+       case BPF_FUNC_dynptr_from_skb:
+               return &bpf_dynptr_from_skb_proto;
        default:
                return bpf_sk_base_func_proto(func_id);
        }
tools/include/uapi/linux/bpf.h +37 -4
index 1d6085e15fc8..3f1800a2b77c 100644
@@ -5253,11 +5253,22 @@ union bpf_attr {
  *     Description
  *             Write *len* bytes from *src* into *dst*, starting from *offset*
  *             into *dst*.
- *             *flags* is currently unused.
+ *
+ *             *flags* must be 0 except for skb-type dynptrs.
+ *
+ *             For skb-type dynptrs:
+ *                 *  All data slices of the dynptr are automatically
+ *                    invalidated after **bpf_dynptr_write**\ (). If you wish to
+ *                    avoid this, please perform the write using direct data slices
+ *                    instead.
+ *
+ *                 *  For *flags*, please see the flags accepted by
+ *                    **bpf_skb_store_bytes**\ ().
  *     Return
  *             0 on success, -E2BIG if *offset* + *len* exceeds the length
  *             of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst*
- *             is a read-only dynptr or if *flags* is not 0.
+ *             is a read-only dynptr or if *flags* is not correct. For skb-type dynptrs,
+ *             other errors correspond to errors returned by **bpf_skb_store_bytes**\ ().
  *
  * void *bpf_dynptr_data(struct bpf_dynptr *ptr, u32 offset, u32 len)
  *     Description
@@ -5265,10 +5276,20 @@ union bpf_attr {
  *
  *             *len* must be a statically known value. The returned data slice
  *             is invalidated whenever the dynptr is invalidated.
+ *
+ *             For skb-type dynptrs:
+ *                 * If *offset* + *len* extends into the skb's paged buffers,
+ *                   the user should manually pull the skb with **bpf_skb_pull_data**\ ()
+ *                   and try again.
+ *
+ *                 * The data slice is automatically invalidated anytime
+ *                   **bpf_dynptr_write**\ () or a helper call that changes
+ *                   the underlying packet buffer (eg **bpf_skb_pull_data**\ ())
+ *                   is called.
  *     Return
  *             Pointer to the underlying dynptr data, NULL if the dynptr is
  *             read-only, if the dynptr is invalid, or if the offset and length
- *             is out of bounds.
+ *             is out of bounds or in a paged buffer for skb-type dynptrs.
  *
  * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
  *     Description
@@ -5355,6 +5376,18 @@ union bpf_attr {
  *     Return
  *             Current *ktime*.
  *
+ * long bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags, struct bpf_dynptr *ptr)
+ *     Description
+ *             Get a dynptr to the data in *skb*. *skb* must be the BPF program
+ *             context. Depending on program type, the dynptr may be read-only.
+ *
+ *             Calls that change the *skb*'s underlying packet buffer
+ *             (eg **bpf_skb_pull_data**\ ()) do not invalidate the dynptr, but
+ *             they do invalidate any data slices associated with the dynptr.
+ *
+ *             *flags* is currently unused, it must be 0 for now.
+ *     Return
+ *             0 on success or -EINVAL if flags is not 0.
  */
 #define __BPF_FUNC_MAPPER(FN)          \
        FN(unspec),                     \
@@ -5566,6 +5599,7 @@ union bpf_attr {
        FN(tcp_raw_check_syncookie_ipv4),       \
        FN(tcp_raw_check_syncookie_ipv6),       \
        FN(ktime_get_tai_ns),           \
+       FN(dynptr_from_skb),            \
        /* */
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
--

2.30.2

#3 lore raw

PATCH v3 2/3 bpf: Add xdp dynptrs

In reply to Joanne Koong

Add xdp dynptrs, which are dynptrs whose underlying pointer points to a xdp_buff. The dynptr acts on xdp data. xdp dynptrs have two main benefits. One is that they allow operations on sizes that are not statically known at compile-time (eg variable-sized accesses). Another is that parsing the packet data through dynptrs (instead of through direct access of xdp->data and xdp->data_end) can be more ergonomic and less brittle (eg does not need manual if checking for being within bounds of data_end).

For reads and writes on the dynptr, this includes reading/writing from/to and across fragments. For data slices, direct access to data in fragments is also permitted, but access across fragments is not. The returned data slice is reg type PTR_TO_PACKET | PTR_MAYBE_NULL.

Any helper calls that change the underlying packet buffer (eg bpf_xdp_adjust_head) invalidates any data slices of the associated dynptr. Whenever such a helper call is made, the verifier marks any PTR_TO_PACKET reg type (which includes xdp dynptr slices since they are PTR_TO_PACKETs) as unknown. The stack trace for this is check_helper_call() -> clear_all_pkt_pointers() -> __clear_all_pkt_pointers() -> mark_reg_unknown()

For examples of how xdp dynptrs can be used, please see the attached selftests.

---
 include/linux/bpf.h            |  8 +++++-
 include/linux/filter.h         |  3 +++
 include/uapi/linux/bpf.h       | 25 +++++++++++++++---
 kernel/bpf/helpers.c           | 14 ++++++++++-
 kernel/bpf/verifier.c          |  8 +++++-
 net/core/filter.c              | 46 +++++++++++++++++++++++++++++-----
 tools/include/uapi/linux/bpf.h | 25 +++++++++++++++---
 7 files changed, 114 insertions(+), 15 deletions(-)
include/linux/bpf.h +7 -1
index a1fdc4d350c0..e3ff3e3758cc 100644
@@ -410,11 +410,15 @@ enum bpf_type_flag {
 	/* DYNPTR points to sk_buff */
 	DYNPTR_TYPE_SKB		= BIT(11 + BPF_BASE_TYPE_BITS),
 
+	/* DYNPTR points to xdp_buff */
+	DYNPTR_TYPE_XDP		= BIT(12 + BPF_BASE_TYPE_BITS),
+
 	__BPF_TYPE_FLAG_MAX,
 	__BPF_TYPE_LAST_FLAG	= __BPF_TYPE_FLAG_MAX - 1,
 };
 
-#define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB)
+#define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB \
+				 | DYNPTR_TYPE_XDP)
 
 /* Max number of base types. */
 #define BPF_BASE_TYPE_LIMIT	(1UL << BPF_BASE_TYPE_BITS)
@@ -2575,6 +2579,8 @@ enum bpf_dynptr_type {
 	BPF_DYNPTR_TYPE_RINGBUF,
 	/* Underlying data is a sk_buff */
 	BPF_DYNPTR_TYPE_SKB,
+	/* Underlying data is a xdp_buff */
+	BPF_DYNPTR_TYPE_XDP,
 };
 
 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
include/linux/filter.h +3 -0
index 649063d9cbfd..80f030239877 100644
@@ -1535,5 +1535,8 @@ static __always_inline int __bpf_xdp_redirect_map(struct bpf_map *map, u32 ifind
 int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len);
 int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
 			  u32 len, u64 flags);
+int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len);
+int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len);
+void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len);
 
 #endif /* __LINUX_FILTER_H__ */
include/uapi/linux/bpf.h +22 -3
index 320e6b95d95c..9feea29eebcd 100644
@@ -5283,13 +5283,18 @@ union bpf_attr {
  *		      and try again.
  *
  *		    * The data slice is automatically invalidated anytime
- *		      **bpf_dynptr_write**\ () or a helper call that changes
- *		      the underlying packet buffer (eg **bpf_skb_pull_data**\ ())
+ *		      **bpf_dynptr_write**\ () is called.
+ *
+ *		For skb-type and xdp-type dynptrs:
+ *		    * The data slice is automatically invalidated anytime a
+ *		      helper call that changes the underlying packet buffer
+ *		      (eg **bpf_skb_pull_data**\ (), **bpf_xdp_adjust_head**\ ())
  *		      is called.
  *	Return
  *		Pointer to the underlying dynptr data, NULL if the dynptr is
  *		read-only, if the dynptr is invalid, or if the offset and length
- *		is out of bounds or in a paged buffer for skb-type dynptrs.
+ *		is out of bounds or in a paged buffer for skb-type dynptrs or
+ *		across fragments for xdp-type dynptrs.
  *
  * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
  *	Description
@@ -5388,6 +5393,19 @@ union bpf_attr {
  *		*flags* is currently unused, it must be 0 for now.
  *	Return
  *		0 on success or -EINVAL if flags is not 0.
+ *
+ * long bpf_dynptr_from_xdp(struct xdp_buff *xdp_md, u64 flags, struct bpf_dynptr *ptr)
+ *	Description
+ *		Get a dynptr to the data in *xdp_md*. *xdp_md* must be the BPF program
+ *		context.
+ *
+ *		Calls that change the *xdp_md*'s underlying packet buffer
+ *		(eg **bpf_xdp_adjust_head**\ ()) do not invalidate the dynptr, but
+ *		they do invalidate any data slices associated with the dynptr.
+ *
+ *		*flags* is currently unused, it must be 0 for now.
+ *	Return
+ *		0 on success, -EINVAL if flags is not 0.
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -5600,6 +5618,7 @@ union bpf_attr {
 	FN(tcp_raw_check_syncookie_ipv6),	\
 	FN(ktime_get_tai_ns),		\
 	FN(dynptr_from_skb),		\
+	FN(dynptr_from_xdp),		\
 	/* */
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/helpers.c +13 -1
index 471a01a9b6ae..2b9dc4c6de04 100644
@@ -1541,6 +1541,8 @@ BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, struct bpf_dynptr_kern *, src
 		return 0;
 	case BPF_DYNPTR_TYPE_SKB:
 		return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
+	case BPF_DYNPTR_TYPE_XDP:
+		return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len);
 	default:
 		WARN(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
 		return -EFAULT;
@@ -1583,6 +1585,10 @@ BPF_CALL_5(bpf_dynptr_write, struct bpf_dynptr_kern *, dst, u32, offset, void *,
 	case BPF_DYNPTR_TYPE_SKB:
 		return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
 					     flags);
+	case BPF_DYNPTR_TYPE_XDP:
+		if (flags)
+			return -EINVAL;
+		return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len);
 	default:
 		WARN(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
 		return -EFAULT;
@@ -1616,7 +1622,7 @@ BPF_CALL_3(bpf_dynptr_data, struct bpf_dynptr_kern *, ptr, u32, offset, u32, len
 
 	type = bpf_dynptr_get_type(ptr);
 
-	/* Only skb dynptrs can get read-only data slices, because the
+	/* Only skb and xdp dynptrs can get read-only data slices, because the
 	 * verifier enforces PTR_TO_PACKET accesses
 	 */
 	is_rdonly = bpf_dynptr_is_rdonly(ptr);
@@ -1640,6 +1646,12 @@ BPF_CALL_3(bpf_dynptr_data, struct bpf_dynptr_kern *, ptr, u32, offset, u32, len
 		data = skb->data;
 		break;
 	}
+	case BPF_DYNPTR_TYPE_XDP:
+		/* if the requested data in across fragments, then it cannot
+		 * be accessed directly - bpf_xdp_pointer will return NULL
+		 */
+		return (unsigned long)bpf_xdp_pointer(ptr->data,
+						      ptr->offset + offset, len);
 	default:
 		WARN(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
 		return 0;
kernel/bpf/verifier.c +7 -1
index 1ea295f47525..d33648eee188 100644
@@ -686,6 +686,8 @@ static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
 		return BPF_DYNPTR_TYPE_RINGBUF;
 	case DYNPTR_TYPE_SKB:
 		return BPF_DYNPTR_TYPE_SKB;
+	case DYNPTR_TYPE_XDP:
+		return BPF_DYNPTR_TYPE_XDP;
 	default:
 		return BPF_DYNPTR_TYPE_INVALID;
 	}
@@ -6078,6 +6080,9 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
 			case DYNPTR_TYPE_SKB:
 				err_extra = "skb ";
 				break;
+			case DYNPTR_TYPE_XDP:
+				err_extra = "xdp ";
+				break;
 			}
 
 			verbose(env, "Expected an initialized %sdynptr as arg #%d\n",
@@ -7439,7 +7444,8 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		mark_reg_known_zero(env, regs, BPF_REG_0);
 
 		if (func_id == BPF_FUNC_dynptr_data &&
-		    dynptr_type == BPF_DYNPTR_TYPE_SKB) {
+		    (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
+		     dynptr_type == BPF_DYNPTR_TYPE_XDP)) {
 			regs[BPF_REG_0].type = PTR_TO_PACKET | ret_flag;
 			regs[BPF_REG_0].range = meta.mem_size;
 		} else {
net/core/filter.c +40 -6

88 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +22 -3
index 3f1800a2b77c..0d5b0117db2a 100644
@@ -5283,13 +5283,18 @@ union bpf_attr {
  *		      and try again.
  *
  *		    * The data slice is automatically invalidated anytime
- *		      **bpf_dynptr_write**\ () or a helper call that changes
- *		      the underlying packet buffer (eg **bpf_skb_pull_data**\ ())
+ *		      **bpf_dynptr_write**\ () is called.
+ *
+ *		For skb-type and xdp-type dynptrs:
+ *		    * The data slice is automatically invalidated anytime a
+ *		      helper call that changes the underlying packet buffer
+ *		      (eg **bpf_skb_pull_data**\ (), **bpf_xdp_adjust_head**\ ())
  *		      is called.
  *	Return
  *		Pointer to the underlying dynptr data, NULL if the dynptr is
  *		read-only, if the dynptr is invalid, or if the offset and length
- *		is out of bounds or in a paged buffer for skb-type dynptrs.
+ *		is out of bounds or in a paged buffer for skb-type dynptrs or
+ *		across fragments for xdp-type dynptrs.
  *
  * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
  *	Description
@@ -5388,6 +5393,19 @@ union bpf_attr {
  *		*flags* is currently unused, it must be 0 for now.
  *	Return
  *		0 on success or -EINVAL if flags is not 0.
+ *
+ * long bpf_dynptr_from_xdp(struct xdp_buff *xdp_md, u64 flags, struct bpf_dynptr *ptr)
+ *	Description
+ *		Get a dynptr to the data in *xdp_md*. *xdp_md* must be the BPF program
+ *		context.
+ *
+ *		Calls that change the *xdp_md*'s underlying packet buffer
+ *		(eg **bpf_xdp_adjust_head**\ ()) do not invalidate the dynptr, but
+ *		they do invalidate any data slices associated with the dynptr.
+ *
+ *		*flags* is currently unused, it must be 0 for now.
+ *	Return
+ *		0 on success, -EINVAL if flags is not 0.
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -5600,6 +5618,7 @@ union bpf_attr {
 	FN(tcp_raw_check_syncookie_ipv6),	\
 	FN(ktime_get_tai_ns),		\
 	FN(dynptr_from_skb),		\
+	FN(dynptr_from_xdp),		\
 	/* */
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.30.2
#4 lore raw

PATCH v3 3/3 selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

In reply to Joanne Koong

Test skb and xdp dynptr functionality in the following ways:

1) progs/test_cls_redirect_dynptr.c
* Rewrite "progs/test_cls_redirect.c" test to use dynptrs to parse skb data

* This is a great example of how dynptrs can be used to simplify a lot of the parsing logic for non-statically known values, and speed up execution times.

When measuring the user + system time between the original version vs. using dynptrs, and averaging the time for 10 runs (using "time ./test_progs -t cls_redirect"), there was a 2x speed-up:
original version: 0.053 sec
with dynptrs: 0.025 sec

2) progs/test_xdp_dynptr.c
* Rewrite "progs/test_xdp.c" test to use dynptrs to parse xdp data

There were no noticeable diferences in user + system time between the original version vs. using dynptrs. Averaging the time for 10 runs (run using "time ./test_progs -t xdp_bpf2bpf"):
original version: 0.0449 sec
with dynptrs: 0.0429 sec

3) progs/test_l4lb_noinline_dynptr.c
* Rewrite "progs/test_l4lb_noinline.c" test to use dynptrs to parse skb data

There were no noticeable diferences in user + system time between the original version vs. using dynptrs. Averaging the time for 10 runs (run using "time ./test_progs -t l4lb_all"):
original version: 0.0502 sec
with dynptrs: 0.055 sec

For number of processed verifier instructions:
original version: 6284 insns
with dynptrs: 2538 insns

4) progs/test_parse_tcp_hdr_opt_dynptr.c
* Add sample code for parsing tcp hdr opt lookup using dynptrs. This logic is lifted from a real-world use case of packet parsing in katran [0], a layer 4 load balancer. The original version "progs/test_parse_tcp_hdr_opt.c" (not using dynptrs) is included here as well, for comparison.

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing attempts at writes / data slices on a prog type with read-only skb ctx.

6) progs/dynptr_fail.c
* Add test cases "skb_invalid_data_slice{1,2}" and "xdp_invalid_data_slice" for testing that helpers that modify the underlying packet buffer automatically invalidate the associated data slice.
* Add test cases "skb_invalid_ctx" and "xdp_invalid_ctx" for testing that prog types that do not support bpf_dynptr_from_skb/xdp don't have access to the API.
* Add test case "skb_invalid_write" for testing that read-only skb dynptrs can't be written to through data slices.

[0] https://github.com/facebookincubator/katran/blob/main/katran/lib/bpf/pckt_parsing.h

---
 .../selftests/bpf/prog_tests/cls_redirect.c   |  25 +
 .../testing/selftests/bpf/prog_tests/dynptr.c | 132 ++-
 .../selftests/bpf/prog_tests/l4lb_all.c       |   2 +
 .../bpf/prog_tests/parse_tcp_hdr_opt.c        |  85 ++
 .../selftests/bpf/prog_tests/xdp_attach.c     |   9 +-
 .../testing/selftests/bpf/progs/dynptr_fail.c | 111 ++
 .../selftests/bpf/progs/dynptr_success.c      |  29 +
 .../bpf/progs/test_cls_redirect_dynptr.c      | 968 ++++++++++++++++++
 .../bpf/progs/test_l4lb_noinline_dynptr.c     | 468 +++++++++
 .../bpf/progs/test_parse_tcp_hdr_opt.c        | 119 +++
 .../bpf/progs/test_parse_tcp_hdr_opt_dynptr.c | 110 ++
 .../selftests/bpf/progs/test_xdp_dynptr.c     | 240 +++++
 .../selftests/bpf/test_tcp_hdr_options.h      |   1 +
 13 files changed, 2255 insertions(+), 44 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/parse_tcp_hdr_opt.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_cls_redirect_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_xdp_dynptr.c
tools/testing/selftests/bpf/prog_tests/cls_redirect.c +25 -0
index 224f016b0a53..2a55f717fc07 100644
@@ -13,6 +13,7 @@
 
 #include "progs/test_cls_redirect.h"
 #include "test_cls_redirect.skel.h"
+#include "test_cls_redirect_dynptr.skel.h"
 #include "test_cls_redirect_subprogs.skel.h"
 
 #define ENCAP_IP INADDR_LOOPBACK
@@ -446,6 +447,28 @@ static void test_cls_redirect_common(struct bpf_program *prog)
 	close_fds((int *)conns, sizeof(conns) / sizeof(conns[0][0]));
 }
 
+static void test_cls_redirect_dynptr(void)
+{
+	struct test_cls_redirect_dynptr *skel;
+	int err;
+
+	skel = test_cls_redirect_dynptr__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open"))
+		return;
+
+	skel->rodata->ENCAPSULATION_IP = htonl(ENCAP_IP);
+	skel->rodata->ENCAPSULATION_PORT = htons(ENCAP_PORT);
+
+	err = test_cls_redirect_dynptr__load(skel);
+	if (!ASSERT_OK(err, "skel_load"))
+		goto cleanup;
+
+	test_cls_redirect_common(skel->progs.cls_redirect);
+
+cleanup:
+	test_cls_redirect_dynptr__destroy(skel);
+}
+
 static void test_cls_redirect_inlined(void)
 {
 	struct test_cls_redirect *skel;
@@ -496,4 +519,6 @@ void test_cls_redirect(void)
 		test_cls_redirect_inlined();
 	if (test__start_subtest("cls_redirect_subprogs"))
 		test_cls_redirect_subprogs();
+	if (test__start_subtest("cls_redirect_dynptr"))
+		test_cls_redirect_dynptr();
 }
tools/testing/selftests/bpf/prog_tests/dynptr.c +90 -42

169 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/l4lb_all.c +2 -0
index 55f733ff4109..94079c89f2e9 100644
@@ -93,4 +93,6 @@ void test_l4lb_all(void)
 		test_l4lb("test_l4lb.o");
 	if (test__start_subtest("l4lb_noinline"))
 		test_l4lb("test_l4lb_noinline.o");
+	if (test__start_subtest("l4lb_noinline_dynptr"))
+		test_l4lb("test_l4lb_noinline_dynptr.o");
 }
tools/testing/selftests/bpf/prog_tests/parse_tcp_hdr_opt.c new file +85 -0

85 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/xdp_attach.c +7 -2
index 62aa3edda5e6..40d0d61af9e6 100644
@@ -4,11 +4,10 @@
 #define IFINDEX_LO 1
 #define XDP_FLAGS_REPLACE		(1U << 4)
 
-void serial_test_xdp_attach(void)
+static void serial_test_xdp_attach(const char *file)
 {
 	__u32 duration = 0, id1, id2, id0 = 0, len;
 	struct bpf_object *obj1, *obj2, *obj3;
-	const char *file = "./test_xdp.o";
 	struct bpf_prog_info info = {};
 	int err, fd1, fd2, fd3;
 	LIBBPF_OPTS(bpf_xdp_attach_opts, opts);
@@ -85,3 +84,9 @@ void serial_test_xdp_attach(void)
 out_1:
 	bpf_object__close(obj1);
 }
+
+void test_xdp_attach(void)
+{
+	serial_test_xdp_attach("./test_xdp.o");
+	serial_test_xdp_attach("./test_xdp_dynptr.o");
+}
tools/testing/selftests/bpf/progs/dynptr_fail.c +111 -0

120 lines not on this page · raw message

tools/testing/selftests/bpf/progs/dynptr_success.c +29 -0
index a3a6103c8569..d0e504d7aae7 100644
@@ -162,3 +162,32 @@ int test_ringbuf(void *ctx)
 	bpf_ringbuf_discard_dynptr(&ptr, 0);
 	return 0;
 }
+
+SEC("cgroup_skb/egress")
+int test_skb_readonly(struct __sk_buff *skb)
+{
+	__u8 write_data[2] = {1, 2};
+	struct bpf_dynptr ptr;
+	__u64 *data;
+	int ret;
+
+	if (bpf_dynptr_from_skb(skb, 0, &ptr)) {
+		err = 1;
+		return 0;
+	}
+
+	data = bpf_dynptr_data(&ptr, 0, sizeof(*data));
+	if (!data) {
+		err = 2;
+		return 0;
+	}
+
+	/* since cgroup skbs are read only, writes should fail */
+	ret = bpf_dynptr_write(&ptr, 0, write_data, sizeof(write_data), 0);
+	if (ret != -EINVAL) {
+		err = 3;
+		return 0;
+	}
+
+	return 0;
+}
tools/testing/selftests/bpf/progs/test_cls_redirect_dynptr.c new file +968 -0

968 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c new file +468 -0

468 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt.c new file +119 -0

119 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt_dynptr.c new file +110 -0

110 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_xdp_dynptr.c new file +240 -0

240 lines not on this page · raw message

tools/testing/selftests/bpf/test_tcp_hdr_options.h +1 -0
index 6118e3ab61fc..56c9f8a3ad3d 100644
@@ -50,6 +50,7 @@ struct linum_err {
 
 #define TCPOPT_EOL		0
 #define TCPOPT_NOP		1
+#define TCPOPT_MSS		2
 #define TCPOPT_WINDOW		3
 #define TCPOPT_EXP		254
 
Signature · 1 line
2.30.2