Skip to contentSkip to conversation

Add skb + xdp dynptrs

PATCH Superseded Joanne Koong 3 participants 12 messages Jan 26, 2023 – Jan 28, 2023

Subsystems (8)

v8 of 13 Superseded Latest is v13 →

lore
Share & tools
lore
#0 lore raw

v8 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:

v7 = https://lore.kernel.org/bpf/[email protected]/
v7 -> v8:
* Change helpers to kfuncs
* Add 2 new patches (1/5 and 2/5)

v6 = https://lore.kernel.org/bpf/[email protected]/
v6 -> v7
* Change bpf_dynptr_data() to return read-only data slices if the skb prog is read-only (Martin)
* Add test "skb_invalid_write" to test that writes to rd-only data slices are rejected

v5 = https://lore.kernel.org/bpf/[email protected]/
v5 -> v6
* Address kernel test robot errors by static inlining

v4 = https://lore.kernel.org/bpf/[email protected]/
v4 -> v5
* Address kernel test robot errors for configs w/out CONFIG_NET set
* For data slices, return PTR_TO_MEM instead of PTR_TO_PACKET (Kumar)
* Split selftests into subtests (Andrii)
* Remove insn patching. Use rdonly and rdwr protos for dynptr skb construction (Andrii)
* bpf_dynptr_data() returns NULL for rd-only dynptrs. There will be a separate bpf_dynptr_data_rdonly() added later (Andrii and Kumar)

v3 = https://lore.kernel.org/bpf/[email protected]/
v3 -> v4
* Forgot to commit --amend the kernel test robot error fixups

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 (5):
bpf: Allow "sk_buff" and "xdp_buff" as valid kfunc arg types
bpf: Allow initializing dynptrs in kfuncs
bpf: Add skb dynptrs
bpf: Add xdp dynptrs
selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

 include/linux/bpf.h                           |  88 +-
 include/linux/bpf_verifier.h                  |   3 -
 include/linux/filter.h                        |  38 +
 include/uapi/linux/bpf.h                      |  41 +-
 kernel/bpf/btf.c                              |  22 +
 kernel/bpf/helpers.c                          | 107 +-
 kernel/bpf/verifier.c                         | 325 +++---
 net/core/filter.c                             | 104 +-
 tools/include/uapi/linux/bpf.h                |  41 +-
 .../selftests/bpf/prog_tests/cls_redirect.c   |  25 +
 .../testing/selftests/bpf/prog_tests/dynptr.c |  63 +-
 .../selftests/bpf/prog_tests/l4lb_all.c       |   2 +
 .../bpf/prog_tests/parse_tcp_hdr_opt.c        |  93 ++
 .../selftests/bpf/prog_tests/xdp_attach.c     |  11 +-
 .../testing/selftests/bpf/progs/dynptr_fail.c | 124 +++
 .../selftests/bpf/progs/dynptr_success.c      |  28 +
 .../bpf/progs/test_cls_redirect_dynptr.c      | 973 ++++++++++++++++++
 .../bpf/progs/test_l4lb_noinline_dynptr.c     | 474 +++++++++
 .../bpf/progs/test_parse_tcp_hdr_opt.c        | 119 +++
 .../bpf/progs/test_parse_tcp_hdr_opt_dynptr.c | 112 ++
 .../selftests/bpf/progs/test_xdp_dynptr.c     | 237 +++++
 .../selftests/bpf/test_tcp_hdr_options.h      |   1 +
 22 files changed, 2825 insertions(+), 206 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 v8 1/5 bpf: Allow "sk_buff" and "xdp_buff" as valid kfunc arg types

The bpf mirror of the in-kernel sk_buff and xdp_buff data structures are __sk_buff and xdp_md. Currently, when we pass in the program ctx to a kfunc where the program ctx is a skb or xdp buffer, we reject the program if the in-kernel definition is sk_buff/xdp_buff instead of __sk_buff/xdp_md.

This change allows sk_buff and __sk_buff, and xdp_buff and xdp_md to be valid matches. The user program may pass in their program ctx as a __sk_buff or xdp_md, and the in-kernel definition of the kfunc may define this arg as a sk_buff or xdp_buff. Please note that the __sk_buff/xdp_md -> sk_buff/xdp_buff conversion happens in convert_ctx_accesses() in the verifier.

---
 kernel/bpf/btf.c | 4 ++++
 1 file changed, 4 insertions(+)
kernel/bpf/btf.c +4 -0
index 47b8cb96f2c2..b4da17688c65 100644
@@ -5606,6 +5606,10 @@ btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
 	 * { // no fields of skb are ever used }
 	 */
+	if (strcmp(ctx_tname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
+		return ctx_type;
+	if (strcmp(ctx_tname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
+		return ctx_type;
 	if (strcmp(ctx_tname, tname))
 		return NULL;
 	return ctx_type;
Signature · 1 line
2.30.2
#2 lore raw

PATCH v8 2/5 bpf: Allow initializing dynptrs in kfuncs

In reply to Joanne Koong

This change allows kfuncs to take in an uninitialized dynptr as a parameter. Before this change, only helper functions could successfully use uninitialized dynptrs. This change moves the memory access check (and stack state growing) into process_dynptr_func(), which both helpers and kfuncs call.

This change also includes some light tidying up of existing code (eg remove unused parameter, move spi checking logic, remove unneeded checks)

---
 include/linux/bpf_verifier.h |   3 -
 kernel/bpf/verifier.c        | 139 +++++++++++++----------------------
 2 files changed, 52 insertions(+), 90 deletions(-)
include/linux/bpf_verifier.h +0 -3
index aa83de1fe755..bee10101222d 100644
@@ -618,9 +618,6 @@ int check_func_arg_reg_off(struct bpf_verifier_env *env,
 			   enum bpf_arg_type arg_type);
 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
 		   u32 regno, u32 mem_size);
-struct bpf_call_arg_meta;
-int process_dynptr_func(struct bpf_verifier_env *env, int regno,
-			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta);
 
 /* this lives here instead of in bpf.h because it needs to dereference tgt_prog */
 static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog,
kernel/bpf/verifier.c +52 -87

240 lines not on this page · raw message

Signature · 1 line
2.30.2
#3 lore raw

Re: [PATCH v8 bpf-next 2/5] bpf: Allow initializing dynptrs in kfuncs

Thank you for the patch! Perhaps something to improve:

Hi Joanne,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on bpf-next/master]

url:    https://github.com/intel-lab-lkp/linux/commits/Joanne-Koong/bpf-Allow-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230128-170947
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
patch link:    https://lore.kernel.org/r/20230126233439.3739120-3-joannelkoong%40gmail.com
patch subject: [PATCH v8 bpf-next 2/5] bpf: Allow initializing dynptrs in kfuncs
config: ia64-allyesconfig (https://download.01.org/0day-ci/archive/20230128/[email protected]/config)
compiler: ia64-linux-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/7993ffba3295a3a3c01c4b62099117b5abd48242
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Joanne-Koong/bpf-Allow-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230128-170947 git checkout 7993ffba3295a3a3c01c4b62099117b5abd48242
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=ia64 olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=ia64 SHELL=/bin/bash kernel/bpf/ net/core/

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All warnings (new ones prefixed by >>):

>> kernel/bpf/verifier.c:6150:5: warning: no previous prototype for 'process_dynptr_func' [-Wmissing-prototypes]

6150 | int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
| ^~~~~~~~~~~~~~~~~~~

vim +/process_dynptr_func +6150 kernel/bpf/verifier.c

6124
6125 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6126 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6127 *
6128 * In both cases we deal with the first 8 bytes, but need to mark the next 8
6129 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6130 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6131 *
6132 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6133 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6134 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6135 * mutate the view of the dynptr and also possibly destroy it. In the latter
6136 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6137 * memory that dynptr points to.
6138 *
6139 * The verifier will keep track both levels of mutation (bpf_dynptr's in
6140 * reg->type and the memory's in reg->dynptr.type), but there is no support for
6141 * readonly dynptr view yet, hence only the first case is tracked and checked.
6142 *
6143 * This is consistent with how C applies the const modifier to a struct object,
6144 * where the pointer itself inside bpf_dynptr becomes const but not what it
6145 * points to.
6146 *
6147 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6148 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6149 */

> 6150	int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,

6151 enum bpf_arg_type arg_type)
6152 {
6153 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6154 int err;
6155
6156 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6157 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6158 */
6159 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6160 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6161 return -EFAULT;
6162 }
6163
6164 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
6165 * constructing a mutable bpf_dynptr object.
6166 *
6167 * Currently, this is only possible with PTR_TO_STACK
6168 * pointing to a region of at least 16 bytes which doesn't
6169 * contain an existing bpf_dynptr.
6170 *
6171 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6172 * mutated or destroyed. However, the memory it points to
6173 * may be mutated.
6174 *
6175 * None - Points to a initialized dynptr that can be mutated and
6176 * destroyed, including mutation of the memory it points
6177 * to.
6178 */
6179 if (arg_type & MEM_UNINIT) {
6180 int i, spi;
6181
6182 if (base_type(reg->type) == CONST_PTR_TO_DYNPTR) {
6183 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
6184 return -EFAULT;
6185 }
6186
6187 /* For -ERANGE (i.e. spi not falling into allocated stack slots),
6188 * check_mem_access will check and update stack bounds, so this
6189 * is okay.
6190 */
6191 spi = dynptr_get_spi(env, reg);
6192 if (spi < 0 && spi != -ERANGE)
6193 return spi;
6194
6195 /* we write BPF_DW bits (8 bytes) at a time */
6196 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6197 err = check_mem_access(env, insn_idx, regno,
6198 i, BPF_DW, BPF_WRITE, -1, false);
6199 if (err)
6200 return err;
6201 }
6202
6203 /* Please note that we allow overwriting existing unreferenced STACK_DYNPTR
6204 * slots (mark_stack_slots_dynptr calls destroy_if_dynptr_stack_slot
6205 * to ensure dynptr objects at the slots we are touching are completely
6206 * destructed before we reinitialize them for a new one). For referenced
6207 * ones, destroy_if_dynptr_stack_slot returns an error early instead of
6208 * delaying it until the end where the user will get "Unreleased
6209 * reference" error.
6210 */
6211 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
6212 } else /* MEM_RDONLY and None case from above */ {
6213 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6214 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6215 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6216 return -EINVAL;
6217 }
6218
6219 if (!is_dynptr_reg_valid_init(env, reg)) {
6220 verbose(env, "Expected an initialized dynptr as arg #%d\n",
6221 regno);
6222 return -EINVAL;
6223 }
6224
6225 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6226 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6227 const char *err_extra = "";
6228
6229 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6230 case DYNPTR_TYPE_LOCAL:
6231 err_extra = "local";
6232 break;
6233 case DYNPTR_TYPE_RINGBUF:
6234 err_extra = "ringbuf";
6235 break;
6236 default:
6237 err_extra = "<unknown>";
6238 break;
6239 }
6240 verbose(env,
6241 "Expected a dynptr of type %s as arg #%d\n",
6242 err_extra, regno);
6243 return -EINVAL;
6244 }
6245
6246 err = mark_dynptr_read(env, reg);
6247 }
6248 return err;
6249 }
6250

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#4 lore raw

Re: [PATCH v8 bpf-next 2/5] bpf: Allow initializing dynptrs in kfuncs

In reply to Joanne Koong
Thank you for the patch! Perhaps something to improve:

Hi Joanne,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on bpf-next/master]

url:    https://github.com/intel-lab-lkp/linux/commits/Joanne-Koong/bpf-Allow-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230128-170947
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
patch link:    https://lore.kernel.org/r/20230126233439.3739120-3-joannelkoong%40gmail.com
patch subject: [PATCH v8 bpf-next 2/5] bpf: Allow initializing dynptrs in kfuncs
config: i386-randconfig-a012-20230123 (https://download.01.org/0day-ci/archive/20230128/[email protected]/config)
compiler: clang version 14.0.6 (https://github.com/llvm/llvm-project f28c006a5895fc0e329fe15fead81e37457cb1d1)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/7993ffba3295a3a3c01c4b62099117b5abd48242
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Joanne-Koong/bpf-Allow-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230128-170947 git checkout 7993ffba3295a3a3c01c4b62099117b5abd48242
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=i386 olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=i386 SHELL=/bin/bash kernel/bpf/ net/core/

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All warnings (new ones prefixed by >>):

>> kernel/bpf/verifier.c:6150:5: warning: no previous prototype for function 'process_dynptr_func' [-Wmissing-prototypes]
   int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
       ^

kernel/bpf/verifier.c:6150:1: note: declare 'static' if the function is not intended to be used outside of this translation unit int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
^
static
1 warning generated.

vim +/process_dynptr_func +6150 kernel/bpf/verifier.c

6124
6125 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6126 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6127 *
6128 * In both cases we deal with the first 8 bytes, but need to mark the next 8
6129 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6130 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6131 *
6132 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6133 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6134 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6135 * mutate the view of the dynptr and also possibly destroy it. In the latter
6136 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6137 * memory that dynptr points to.
6138 *
6139 * The verifier will keep track both levels of mutation (bpf_dynptr's in
6140 * reg->type and the memory's in reg->dynptr.type), but there is no support for
6141 * readonly dynptr view yet, hence only the first case is tracked and checked.
6142 *
6143 * This is consistent with how C applies the const modifier to a struct object,
6144 * where the pointer itself inside bpf_dynptr becomes const but not what it
6145 * points to.
6146 *
6147 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6148 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6149 */

> 6150	int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,

6151 enum bpf_arg_type arg_type)
6152 {
6153 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6154 int err;
6155
6156 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6157 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6158 */
6159 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6160 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6161 return -EFAULT;
6162 }
6163
6164 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
6165 * constructing a mutable bpf_dynptr object.
6166 *
6167 * Currently, this is only possible with PTR_TO_STACK
6168 * pointing to a region of at least 16 bytes which doesn't
6169 * contain an existing bpf_dynptr.
6170 *
6171 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6172 * mutated or destroyed. However, the memory it points to
6173 * may be mutated.
6174 *
6175 * None - Points to a initialized dynptr that can be mutated and
6176 * destroyed, including mutation of the memory it points
6177 * to.
6178 */
6179 if (arg_type & MEM_UNINIT) {
6180 int i, spi;
6181
6182 if (base_type(reg->type) == CONST_PTR_TO_DYNPTR) {
6183 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
6184 return -EFAULT;
6185 }
6186
6187 /* For -ERANGE (i.e. spi not falling into allocated stack slots),
6188 * check_mem_access will check and update stack bounds, so this
6189 * is okay.
6190 */
6191 spi = dynptr_get_spi(env, reg);
6192 if (spi < 0 && spi != -ERANGE)
6193 return spi;
6194
6195 /* we write BPF_DW bits (8 bytes) at a time */
6196 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6197 err = check_mem_access(env, insn_idx, regno,
6198 i, BPF_DW, BPF_WRITE, -1, false);
6199 if (err)
6200 return err;
6201 }
6202
6203 /* Please note that we allow overwriting existing unreferenced STACK_DYNPTR
6204 * slots (mark_stack_slots_dynptr calls destroy_if_dynptr_stack_slot
6205 * to ensure dynptr objects at the slots we are touching are completely
6206 * destructed before we reinitialize them for a new one). For referenced
6207 * ones, destroy_if_dynptr_stack_slot returns an error early instead of
6208 * delaying it until the end where the user will get "Unreleased
6209 * reference" error.
6210 */
6211 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
6212 } else /* MEM_RDONLY and None case from above */ {
6213 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6214 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6215 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6216 return -EINVAL;
6217 }
6218
6219 if (!is_dynptr_reg_valid_init(env, reg)) {
6220 verbose(env, "Expected an initialized dynptr as arg #%d\n",
6221 regno);
6222 return -EINVAL;
6223 }
6224
6225 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6226 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6227 const char *err_extra = "";
6228
6229 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6230 case DYNPTR_TYPE_LOCAL:
6231 err_extra = "local";
6232 break;
6233 case DYNPTR_TYPE_RINGBUF:
6234 err_extra = "ringbuf";
6235 break;
6236 default:
6237 err_extra = "<unknown>";
6238 break;
6239 }
6240 verbose(env,
6241 "Expected a dynptr of type %s as arg #%d\n",
6242 err_extra, regno);
6243 return -EINVAL;
6244 }
6245
6246 err = mark_dynptr_read(env, reg);
6247 }
6248 return err;
6249 }
6250

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#5 lore raw

PATCH v8 3/5 bpf: Add skb dynptrs

In reply to 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 (bpf_dynptr_write() will return an error and bpf_dynptr_data() will return a data slice that is read-only where any writes to it will be rejected by the verifier).

For reads and writes through the bpf_dynptr_read() and bpf_dynptr_write() interfaces, reading and writing from/to data in the head as well as from/to non-linear paged buffers is supported. 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.

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. 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            |  82 +++++++++------
 include/linux/filter.h         |  18 ++++
 include/uapi/linux/bpf.h       |  37 +++++--
 kernel/bpf/btf.c               |  18 ++++
 kernel/bpf/helpers.c           |  95 ++++++++++++++---
 kernel/bpf/verifier.c          | 181 ++++++++++++++++++++++++++-------
 net/core/filter.c              |  60 ++++++++++-
 tools/include/uapi/linux/bpf.h |  37 +++++--
 8 files changed, 428 insertions(+), 100 deletions(-)
include/linux/bpf.h +51 -31
index 14a0264fac57..1ac061b64582 100644
@@ -575,11 +575,14 @@ enum bpf_type_flag {
 	/* MEM is tagged with rcu and memory access needs rcu_read_lock protection. */
 	MEM_RCU			= BIT(13 + BPF_BASE_TYPE_BITS),
 
+	/* DYNPTR points to sk_buff */
+	DYNPTR_TYPE_SKB		= BIT(14 + 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)
@@ -1082,6 +1085,35 @@ static __always_inline __nocfi unsigned int bpf_dispatcher_nop_func(
 	return bpf_func(ctx, insnsi);
 }
 
+/* the implementation of the opaque uapi struct bpf_dynptr */
+struct bpf_dynptr_kern {
+	void *data;
+	/* Size represents the number of usable bytes of dynptr data.
+	 * If for example the offset is at 4 for a local dynptr whose data is
+	 * of type u64, the number of usable bytes is 4.
+	 *
+	 * The upper 8 bits are reserved. It is as follows:
+	 * Bits 0 - 23 = size
+	 * Bits 24 - 30 = dynptr type
+	 * Bit 31 = whether dynptr is read-only
+	 */
+	u32 size;
+	u32 offset;
+} __aligned(8);
+
+enum bpf_dynptr_type {
+	BPF_DYNPTR_TYPE_INVALID,
+	/* Points to memory that is local to the bpf program */
+	BPF_DYNPTR_TYPE_LOCAL,
+	/* Underlying data is a ringbuf record */
+	BPF_DYNPTR_TYPE_RINGBUF,
+	/* Underlying data is a sk_buff */
+	BPF_DYNPTR_TYPE_SKB,
+};
+
+int bpf_dynptr_check_size(u32 size);
+u32 bpf_dynptr_get_size(const struct bpf_dynptr_kern *ptr);
+
 #ifdef CONFIG_BPF_JIT
 int bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr);
 int bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr);
@@ -2216,6 +2248,11 @@ static inline bool has_current_bpf_ctx(void)
 }
 
 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog);
+
+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);
+void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr);
 #else /* !CONFIG_BPF_SYSCALL */
 static inline struct bpf_prog *bpf_prog_get(u32 ufd)
 {
@@ -2445,6 +2482,19 @@ static inline void bpf_prog_inc_misses_counter(struct bpf_prog *prog)
 static inline void bpf_cgrp_storage_free(struct cgroup *cgroup)
 {
 }
+
+static inline void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
+				   enum bpf_dynptr_type type, u32 offset, u32 size)
+{
+}
+
+static inline void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
+{
+}
+
+static inline void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
+{
+}
 #endif /* CONFIG_BPF_SYSCALL */
 
 void __bpf_free_used_btfs(struct bpf_prog_aux *aux,
@@ -2863,36 +2913,6 @@ int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
 			u32 num_args, struct bpf_bprintf_data *data);
 void bpf_bprintf_cleanup(struct bpf_bprintf_data *data);
 
-/* the implementation of the opaque uapi struct bpf_dynptr */
-struct bpf_dynptr_kern {
-	void *data;
-	/* Size represents the number of usable bytes of dynptr data.
-	 * If for example the offset is at 4 for a local dynptr whose data is
-	 * of type u64, the number of usable bytes is 4.
-	 *
-	 * The upper 8 bits are reserved. It is as follows:
-	 * Bits 0 - 23 = size
-	 * Bits 24 - 30 = dynptr type
-	 * Bit 31 = whether dynptr is read-only
-	 */
-	u32 size;
-	u32 offset;
-} __aligned(8);
-
-enum bpf_dynptr_type {
-	BPF_DYNPTR_TYPE_INVALID,
-	/* Points to memory that is local to the bpf program */
-	BPF_DYNPTR_TYPE_LOCAL,
-	/* Underlying data is a kernel-produced ringbuf record */
-	BPF_DYNPTR_TYPE_RINGBUF,
-};
-
-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);
-u32 bpf_dynptr_get_size(const struct bpf_dynptr_kern *ptr);
-
 #ifdef CONFIG_BPF_LSM
 void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype);
 void bpf_cgroup_atype_put(int cgroup_atype);
include/linux/filter.h +18 -0
index ccc4a4a58c72..c87d13954d89 100644
@@ -1541,4 +1541,22 @@ static __always_inline int __bpf_xdp_redirect_map(struct bpf_map *map, u64 index
 	return XDP_REDIRECT;
 }
 
+#ifdef CONFIG_NET
+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);
+#else /* CONFIG_NET */
+static inline int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset,
+				       void *to, u32 len)
+{
+	return -EOPNOTSUPP;
+}
+
+static inline int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset,
+					const void *from, u32 len, u64 flags)
+{
+	return -EOPNOTSUPP;
+}
+#endif /* CONFIG_NET */
+
 #endif /* __LINUX_FILTER_H__ */
include/uapi/linux/bpf.h +30 -7
index ba0f0cfb5e42..f6910392d339 100644
@@ -5320,22 +5320,45 @@ 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(const struct bpf_dynptr *ptr, u32 offset, u32 len)
  *	Description
  *		Get a pointer to the underlying dynptr data.
  *
  *		*len* must be a statically known value. The returned data slice
- *		is invalidated whenever the dynptr is invalidated.
- *	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 invalidated whenever the dynptr is invalidated. Please note
+ *		that if the dynptr is read-only, then the returned data slice will
+ *		be read-only.
+ *
+ *		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 invalid,
+ *		or if the offset and length 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
kernel/bpf/btf.c +18 -0
index b4da17688c65..35d0780f2eb9 100644
@@ -207,6 +207,11 @@ enum btf_kfunc_hook {
 	BTF_KFUNC_HOOK_TRACING,
 	BTF_KFUNC_HOOK_SYSCALL,
 	BTF_KFUNC_HOOK_FMODRET,
+	BTF_KFUNC_HOOK_CGROUP_SKB,
+	BTF_KFUNC_HOOK_SCHED_ACT,
+	BTF_KFUNC_HOOK_SK_SKB,
+	BTF_KFUNC_HOOK_SOCKET_FILTER,
+	BTF_KFUNC_HOOK_LWT,
 	BTF_KFUNC_HOOK_MAX,
 };
 
@@ -7609,6 +7614,19 @@ static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
 		return BTF_KFUNC_HOOK_TRACING;
 	case BPF_PROG_TYPE_SYSCALL:
 		return BTF_KFUNC_HOOK_SYSCALL;
+	case BPF_PROG_TYPE_CGROUP_SKB:
+		return BTF_KFUNC_HOOK_CGROUP_SKB;
+	case BPF_PROG_TYPE_SCHED_ACT:
+		return BTF_KFUNC_HOOK_SCHED_ACT;
+	case BPF_PROG_TYPE_SK_SKB:
+		return BTF_KFUNC_HOOK_SK_SKB;
+	case BPF_PROG_TYPE_SOCKET_FILTER:
+		return BTF_KFUNC_HOOK_SOCKET_FILTER;
+	case BPF_PROG_TYPE_LWT_OUT:
+	case BPF_PROG_TYPE_LWT_IN:
+	case BPF_PROG_TYPE_LWT_XMIT:
+	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
+		return BTF_KFUNC_HOOK_LWT;
 	default:
 		return BTF_KFUNC_HOOK_MAX;
 	}
kernel/bpf/helpers.c +79 -16

147 lines not on this page · raw message

kernel/bpf/verifier.c +146 -35

299 lines not on this page · raw message

net/core/filter.c +56 -4

93 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +30 -7
index 7f024ac22edd..6b58e5a75fc5 100644
@@ -5320,22 +5320,45 @@ 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(const struct bpf_dynptr *ptr, u32 offset, u32 len)
  *	Description
  *		Get a pointer to the underlying dynptr data.
  *
  *		*len* must be a statically known value. The returned data slice
- *		is invalidated whenever the dynptr is invalidated.
- *	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 invalidated whenever the dynptr is invalidated. Please note
+ *		that if the dynptr is read-only, then the returned data slice will
+ *		be read-only.
+ *
+ *		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 invalid,
+ *		or if the offset and length 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
Signature · 1 line
2.30.2
#6 lore raw

Re: [PATCH v8 bpf-next 3/5] bpf: Add skb dynptrs

kernel/bpf/verifier.c static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state · line 6655

Quoted 13 lines · Joanne Koong
kernel/bpf/verifier.c +13 -0
+static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
+					    struct bpf_reg_state *reg)
+{
+	struct bpf_func_state *state = func(env, reg);
+	int spi = __get_spi(reg->off);
+
+	if (spi < 0) {
+		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
+		return BPF_DYNPTR_TYPE_INVALID;
+	}
+
+	return state->stack[spi].spilled_ptr.dynptr.type;
+}

CI fails: https://github.com/kernel-patches/bpf/actions/runs/4020275998/jobs/6908210555

My local KASAN also reports the error.

#7 lore raw

Re: [PATCH v8 bpf-next 3/5] bpf: Add skb dynptrs

Quoted 19 lines · Martin KaFai Lau

kernel/bpf/verifier.c static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state · line 6655

Quoted 13 lines · Joanne Koong
kernel/bpf/verifier.c +13 -0
+static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
+                                         struct bpf_reg_state *reg)
+{
+     struct bpf_func_state *state = func(env, reg);
+     int spi = __get_spi(reg->off);
+
+     if (spi < 0) {
+             verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
+             return BPF_DYNPTR_TYPE_INVALID;
+     }
+
+     return state->stack[spi].spilled_ptr.dynptr.type;
+}

CI fails:
https://github.com/kernel-patches/bpf/actions/runs/4020275998/jobs/6908210555

Quoted 1 line

My local KASAN also reports the error.

Ooh thanks for flagging. user_ringbuf() test was failing because dynptr_get_type didn't account for CONST_PTR_TO_DYNPTR type. This fixes it:

@@ -6644,8 +6644,12 @@ static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
struct bpf_reg_state *reg)

 {
        struct bpf_func_state *state = func(env, reg);

- int spi = __get_spi(reg->off);
+ int spi;
+
+ if (reg->type == CONST_PTR_TO_DYNPTR)
+ return reg->dynptr.type;

+ spi = __get_spi(reg->off);
if (spi < 0) {
verbose(env, "verifier internal error: invalid spi
when querying dynptr type\n");

I will add this and respin v9.

#8 lore raw

Re: [PATCH v8 bpf-next 3/5] bpf: Add skb dynptrs

In reply to Joanne Koong
Thank you for the patch! Perhaps something to improve:

Hi Joanne,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on bpf-next/master]

url:    https://github.com/intel-lab-lkp/linux/commits/Joanne-Koong/bpf-Allow-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230128-170947
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
patch link:    https://lore.kernel.org/r/20230126233439.3739120-4-joannelkoong%40gmail.com
patch subject: [PATCH v8 bpf-next 3/5] bpf: Add skb dynptrs
config: ia64-allyesconfig (https://download.01.org/0day-ci/archive/20230128/[email protected]/config)
compiler: ia64-linux-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/2581b1dec73f18fa2b7302a1a2ecd788b82f3680
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Joanne-Koong/bpf-Allow-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230128-170947 git checkout 2581b1dec73f18fa2b7302a1a2ecd788b82f3680
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=ia64 olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=ia64 SHELL=/bin/bash net/core/

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All warnings (new ones prefixed by >>):

>> net/core/filter.c:1866:5: warning: no previous prototype for 'bpf_dynptr_from_skb' [-Wmissing-prototypes]

1866 | int bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags,
| ^~~~~~~~~~~~~~~~~~~

vim +/bpf_dynptr_from_skb +1866 net/core/filter.c

1865

> 1866	int bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags,

1867 struct bpf_dynptr_kern *ptr, int is_rdonly)
1868 {
1869 if (flags) {
1870 bpf_dynptr_set_null(ptr);
1871 return -EINVAL;
1872 }
1873
1874 bpf_dynptr_init(ptr, skb, BPF_DYNPTR_TYPE_SKB, 0, skb->len);
1875
1876 if (is_rdonly)
1877 bpf_dynptr_set_rdonly(ptr);
1878
1879 return 0;
1880 }
1881

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#9 lore raw

PATCH v8 4/5 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.

Any helper calls that change the underlying packet buffer (eg bpf_xdp_adjust_head) invalidates any data slices of the associated dynptr. 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         | 20 ++++++++++++
 include/uapi/linux/bpf.h       | 10 ++++--
 kernel/bpf/helpers.c           | 12 +++++++
 kernel/bpf/verifier.c          | 57 +++++++++++++++++++++-------------
 net/core/filter.c              | 46 ++++++++++++++++++++++-----
 tools/include/uapi/linux/bpf.h | 10 ++++--
 7 files changed, 127 insertions(+), 36 deletions(-)
include/linux/bpf.h +7 -1
index 1ac061b64582..94e910d9598e 100644
@@ -578,11 +578,15 @@ enum bpf_type_flag {
 	/* DYNPTR points to sk_buff */
 	DYNPTR_TYPE_SKB		= BIT(14 + BPF_BASE_TYPE_BITS),
 
+	/* DYNPTR points to xdp_buff */
+	DYNPTR_TYPE_XDP		= BIT(15 + 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)
@@ -1109,6 +1113,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,
 };
 
 int bpf_dynptr_check_size(u32 size);
include/linux/filter.h +20 -0
index c87d13954d89..674795ea9d20 100644
@@ -1545,6 +1545,9 @@ static __always_inline int __bpf_xdp_redirect_map(struct bpf_map *map, u64 index
 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);
 #else /* CONFIG_NET */
 static inline int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset,
 				       void *to, u32 len)
@@ -1557,6 +1560,23 @@ static inline int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset,
 {
 	return -EOPNOTSUPP;
 }
+
+static inline int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset,
+				       void *buf, u32 len)
+{
+	return -EOPNOTSUPP;
+}
+
+static inline int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset,
+					void *buf, u32 len)
+{
+	return -EOPNOTSUPP;
+}
+
+static inline void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
+{
+	return NULL;
+}
 #endif /* CONFIG_NET */
 
 #endif /* __LINUX_FILTER_H__ */
include/uapi/linux/bpf.h +7 -3
index f6910392d339..9cc988e063de 100644
@@ -5352,13 +5352,17 @@ 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 invalid,
  *		or if the offset and length is out of bounds or in a paged buffer for
- *		skb-type dynptrs.
+ *		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
kernel/bpf/helpers.c +12 -0
index a79d522b3a26..ede199107016 100644
@@ -1530,6 +1530,8 @@ BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern
 		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_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
 		return -EFAULT;
@@ -1576,6 +1578,10 @@ BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, v
 	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_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
 		return -EFAULT;
@@ -1631,6 +1637,12 @@ BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u3
 		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_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
 		return 0;
kernel/bpf/verifier.c +35 -22

112 lines not on this page · raw message

net/core/filter.c +39 -7

99 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +7 -3
index 6b58e5a75fc5..04aa7d0b6437 100644
@@ -5352,13 +5352,17 @@ 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 invalid,
  *		or if the offset and length is out of bounds or in a paged buffer for
- *		skb-type dynptrs.
+ *		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
Signature · 1 line
2.30.2
#10 lore raw

Re: [PATCH v8 bpf-next 4/5] bpf: Add xdp dynptrs

Thank you for the patch! Perhaps something to improve:

Hi Joanne,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on bpf-next/master]

url:    https://github.com/intel-lab-lkp/linux/commits/Joanne-Koong/bpf-Allow-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230128-170947
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
patch link:    https://lore.kernel.org/r/20230126233439.3739120-5-joannelkoong%40gmail.com
patch subject: [PATCH v8 bpf-next 4/5] bpf: Add xdp dynptrs
config: ia64-allyesconfig (https://download.01.org/0day-ci/archive/20230128/[email protected]/config)
compiler: ia64-linux-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/ca213ec890479169ac6661c55e4c3eb95b4d8464
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Joanne-Koong/bpf-Allow-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230128-170947 git checkout ca213ec890479169ac6661c55e4c3eb95b4d8464
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=ia64 olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=ia64 SHELL=/bin/bash net/core/

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All warnings (new ones prefixed by >>):

net/core/filter.c:1866:5: warning: no previous prototype for 'bpf_dynptr_from_skb' [-Wmissing-prototypes]
1866 | int bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags,
| ^~~~~~~~~~~~~~~~~~~

>> net/core/filter.c:3858:5: warning: no previous prototype for 'bpf_dynptr_from_xdp' [-Wmissing-prototypes]

3858 | int bpf_dynptr_from_xdp(struct xdp_buff *xdp, u64 flags, struct bpf_dynptr_kern *ptr)
| ^~~~~~~~~~~~~~~~~~~

vim +/bpf_dynptr_from_xdp +3858 net/core/filter.c

3857

> 3858	int bpf_dynptr_from_xdp(struct xdp_buff *xdp, u64 flags, struct bpf_dynptr_kern *ptr)

3859 {
3860 if (flags) {
3861 bpf_dynptr_set_null(ptr);
3862 return -EINVAL;
3863 }
3864
3865 bpf_dynptr_init(ptr, xdp, BPF_DYNPTR_TYPE_XDP, 0, xdp_get_buff_len(xdp));
3866
3867 return 0;
3868 }
3869

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#11 lore raw

PATCH v8 5/5 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"):
original version: 0.092 sec
with dynptrs: 0.078 sec

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

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 xdp_attach"):
original version: 0.118 sec
with dynptrs: 0.094 sec

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

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 l4lb_all"):
original version: 0.062 sec
with dynptrs: 0.081 sec

For number of processed verifier instructions:
original version: 6268 insns
with dynptrs: 2588 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.

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 parse_tcp_hdr_opt"):
original version: 0.031 sec
with dynptrs: 0.045 sec

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 writes to a read-only data slice are rejected by the verifier.

[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 |  63 +-
 .../selftests/bpf/prog_tests/l4lb_all.c       |   2 +
 .../bpf/prog_tests/parse_tcp_hdr_opt.c        |  93 ++
 .../selftests/bpf/prog_tests/xdp_attach.c     |  11 +-
 .../testing/selftests/bpf/progs/dynptr_fail.c | 124 +++
 .../selftests/bpf/progs/dynptr_success.c      |  28 +
 .../bpf/progs/test_cls_redirect_dynptr.c      | 973 ++++++++++++++++++
 .../bpf/progs/test_l4lb_noinline_dynptr.c     | 474 +++++++++
 .../bpf/progs/test_parse_tcp_hdr_opt.c        | 119 +++
 .../bpf/progs/test_parse_tcp_hdr_opt_dynptr.c | 112 ++
 .../selftests/bpf/progs/test_xdp_dynptr.c     | 237 +++++
 .../selftests/bpf/test_tcp_hdr_options.h      |   1 +
 13 files changed, 2248 insertions(+), 14 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 +51 -12

93 lines not on this page · raw message

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

93 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/xdp_attach.c +9 -2
index 062fbc8c8e5e..28c453bbb84a 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.bpf.o";
 	struct bpf_prog_info info = {};
 	int err, fd1, fd2, fd3;
 	LIBBPF_OPTS(bpf_xdp_attach_opts, opts);
@@ -85,3 +84,11 @@ void serial_test_xdp_attach(void)
 out_1:
 	bpf_object__close(obj1);
 }
+
+void test_xdp_attach(void)
+{
+	if (test__start_subtest("xdp_attach"))
+		serial_test_xdp_attach("./test_xdp.bpf.o");
+	if (test__start_subtest("xdp_attach_dynptr"))
+		serial_test_xdp_attach("./test_xdp_dynptr.bpf.o");
+}
tools/testing/selftests/bpf/progs/dynptr_fail.c +124 -0

149 lines not on this page · raw message

tools/testing/selftests/bpf/progs/dynptr_success.c +28 -0
index 35db7c6c1fc7..7341598bb4bf 100644
@@ -9,6 +9,11 @@
 
 char _license[] SEC("license") = "GPL";
 
+extern int bpf_dynptr_from_skb(struct __sk_buff *skb, __u64 flags,
+			       struct bpf_dynptr *ptr, int rd_only) __ksym;
+
+#define bpf_dynptr_from_skb(skb, flags, ptr) bpf_dynptr_from_skb(skb, flags, ptr, 0)
+
 int pid, err, val;
 
 struct sample {
@@ -163,3 +168,26 @@ 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;
+	}
+
+	/* 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 = 2;
+		return 0;
+	}
+
+	return 0;
+}
tools/testing/selftests/bpf/progs/test_cls_redirect_dynptr.c new file +973 -0

973 lines not on this page · raw message

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

474 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 +112 -0

112 lines not on this page · raw message

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

237 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