Introduce eBPF support for HID devices
Subsystems (8)
v2 cover Introduce eBPF support for HID devices
Hi,
This is a followup of my v1 at [0].
The short summary of the previous cover letter and discussions is that HID could benefit from BPF for the following use cases:
- simple fixup of report descriptor:
benefits are faster development time and testing, with the produced bpf program being shipped in the kernel directly (the shipping part is *not* addressed here).
- Universal Stylus Interface:
allows a user-space program to define its own kernel interface
- Surface Dial:
somehow similar to the previous one except that userspace can decide to change the shape of the exported device
- firewall:
still partly missing there, there is not yet interception of hidraw calls, but it's coming in a followup series, I promise
- tracing:
well, tracing.
I tried to address as many comments as I could and here is the short log of changes:
v2:
===
- split the series by subsystem (bpf, HID, libbpf, selftests and samples)
- Added an extra patch at the beginning to not require CAP_NET_ADMIN for BPF_PROG_TYPE_LIRC_MODE2 (please shout if this is wrong)
- made the bpf context attached to HID program of dynamic size:
* the first 1 kB will be able to be addressed directly
* the rest can be retrieved through bpf_hid_{set|get}_data (note that I am definitivey not happy with that API, because there is part of it in bits and other in bytes. ouch)
- added an extra patch to prevent non GPL HID bpf programs to be loaded of type BPF_PROG_TYPE_HID
* same here, not really happy but I don't know where to put that check in verifier.c
- added a new flag BPF_F_INSERT_HEAD for BPF_LINK_CREATE syscall when in used with HID program types.
* this flag is used for tracing, to be able to load a program before any others that might already have been inserted and that might change the data stream.
Cheers,
Benjamin
[0] https://lore.kernel.org/linux-input/[email protected]/T/#t
Benjamin Tissoires (28):
bpf: add new is_sys_admin_prog_type() helper
bpf: introduce hid program type
HID: hook up with bpf
libbpf: add HID program type and API
selftests/bpf: add tests for the HID-bpf initial implementation samples/bpf: add new hid_mouse example
bpf/hid: add a new attach type to change the report descriptor
HID: allow to change the report descriptor from an eBPF program
libbpf: add new attach type BPF_HID_RDESC_FIXUP selftests/bpf: add report descriptor fixup tests samples/bpf: add a report descriptor fixup
bpf/hid: add hid_{get|set}_data helpers
HID: bpf: implement hid_bpf_get|set_data
selftests/bpf: add tests for hid_{get|set}_data helpers bpf/hid: add new BPF type to trigger commands from userspace
libbpf: add new attach type BPF_HID_USER_EVENT selftests/bpf: add test for user call of HID bpf programs selftests/bpf: hid: rely on uhid event to know if a test device is
ready
bpf/hid: add bpf_hid_raw_request helper function
HID: add implementation of bpf_hid_raw_request selftests/bpf: add tests for bpf_hid_hw_request bpf/verifier: prevent non GPL programs to be loaded against HID
HID: bpf: compute only the required buffer size for the device
HID: bpf: only call hid_bpf_raw_event() if a ctx is available bpf/hid: Add a flag to add the program at the beginning of the list
libbpf: add handling for BPF_F_INSERT_HEAD in HID programs selftests/bpf: Add a test for BPF_F_INSERT_HEAD samples/bpf: fix bpf_program__attach_hid() api change
drivers/hid/Makefile | 1 + drivers/hid/hid-bpf.c | 361 +++++++++ drivers/hid/hid-core.c | 34 +- include/linux/bpf-hid.h | 129 +++ include/linux/bpf_types.h | 4 + include/linux/hid.h | 25 + include/uapi/linux/bpf.h | 59 ++ include/uapi/linux/bpf_hid.h | 50 ++ kernel/bpf/Makefile | 3 + kernel/bpf/hid.c | 652 +++++++++++++++ kernel/bpf/syscall.c | 26 +- kernel/bpf/verifier.c | 7 + samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 4 + samples/bpf/hid_mouse_kern.c | 91 +++ samples/bpf/hid_mouse_user.c | 129 +++ tools/include/uapi/linux/bpf.h | 59 ++ tools/lib/bpf/libbpf.c | 22 +- tools/lib/bpf/libbpf.h | 2 + tools/lib/bpf/libbpf.map | 1 + tools/testing/selftests/bpf/prog_tests/hid.c | 788 +++++++++++++++++++ tools/testing/selftests/bpf/progs/hid.c | 216 +++++ 22 files changed, 2649 insertions(+), 15 deletions(-) create mode 100644 drivers/hid/hid-bpf.c create mode 100644 include/linux/bpf-hid.h create mode 100644 include/uapi/linux/bpf_hid.h create mode 100644 kernel/bpf/hid.c create mode 100644 samples/bpf/hid_mouse_kern.c create mode 100644 samples/bpf/hid_mouse_user.c create mode 100644 tools/testing/selftests/bpf/prog_tests/hid.c create mode 100644 tools/testing/selftests/bpf/progs/hid.c
Signature · 1 line
2.35.1
PATCH v2 1/28 bpf: add new is_sys_admin_prog_type() helper
LIRC_MODE2 does not really need net_admin capability, but only sys_admin.
Extract a new helper for it, it will be also used for the HID bpf implementation.
---
new in v2
--- kernel/bpf/syscall.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
kernel/bpf/syscall.c +13 -1
@@ -2165,7 +2165,6 @@ static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)case BPF_PROG_TYPE_LWT_SEG6LOCAL :case BPF_PROG_TYPE_SK_SKB :case BPF_PROG_TYPE_SK_MSG : -case BPF_PROG_TYPE_LIRC_MODE2 :case BPF_PROG_TYPE_FLOW_DISSECTOR :case BPF_PROG_TYPE_CGROUP_DEVICE :case BPF_PROG_TYPE_CGROUP_SOCK :
@@ -2202,6 +2201,17 @@ static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) } } +static bool is_sys_admin_prog_type (enum bpf_prog_type prog_type) +{ +switch (prog_type) { +case BPF_PROG_TYPE_LIRC_MODE2 : +case BPF_PROG_TYPE_EXT :/* extends any prog */ +return true; +default : +return false; + } +} +/* last field in 'union bpf_attr' used by this command */ #define BPF_PROG_LOAD_LAST_FIELD core_relo_rec_size
@@ -2252,6 +2262,8 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr)return -EPERM ;if (is_perfmon_prog_type (type) && !perfmon_capable ())return -EPERM ; +if (is_sys_admin_prog_type (type) && !capable (CAP_SYS_ADMIN )) +return -EPERM ;/* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog * or btf, we need to check which one it is
Signature · 1 line
2.35.1
Song Liu
reviewerRe: [PATCH bpf-next v2 01/28] bpf: add new is_sys_admin_prog_type() helper
Quoted 32 lines · Benjamin Tissoires
LIRC_MODE2does not really neednet_admincapability, but onlysys_admin.Extract a new helper for it, it will be also used for the HID bpf implementation.
Cc Sean Young <[email protected]>Signed-off-by Benjamin Tissoires <[email protected]>---
new in v2
--- kernel/bpf/syscall.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)kernel/bpf/syscall.c +0
-1@@ -2165,7 +2165,6 @@ static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)case BPF_PROG_TYPE_LWT_SEG6LOCAL :case BPF_PROG_TYPE_SK_SKB :case BPF_PROG_TYPE_SK_MSG : -case BPF_PROG_TYPE_LIRC_MODE2 :case BPF_PROG_TYPE_FLOW_DISSECTOR :case BPF_PROG_TYPE_CGROUP_DEVICE :case BPF_PROG_TYPE_CGROUP_SOCK :@@ -2202,6 +2201,17 @@ static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) } }
kernel/bpf/syscall.c static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) · line 2213
Quoted 10 lines
kernel/bpf/syscall.c +10
-0+static bool is_sys_admin_prog_type (enum bpf_prog_type prog_type) +{ +switch (prog_type) { +case BPF_PROG_TYPE_LIRC_MODE2 : +case BPF_PROG_TYPE_EXT :/* extends any prog */ +return true; +default : +return false; + } +}
I am not sure whether we should do this. This is a behavior change, that may break some user space. Also, BPF_PROG_TYPE_EXT is checked in is_perfmon_prog_type(), and this change will make that case useless.
Thanks,
Song
[...]
Re: [PATCH bpf-next v2 01/28] bpf: add new is_sys_admin_prog_type() helper
Quoted 35 lines · Song Liu
Quoted 32 lines · Benjamin Tissoires
LIRC_MODE2does not really neednet_admincapability, but onlysys_admin.Extract a new helper for it, it will be also used for the HID bpf implementation.
Cc Sean Young <[email protected]>Signed-off-by Benjamin Tissoires <[email protected]>---
new in v2
--- kernel/bpf/syscall.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)kernel/bpf/syscall.c +0
-1@@ -2165,7 +2165,6 @@ static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)case BPF_PROG_TYPE_LWT_SEG6LOCAL :case BPF_PROG_TYPE_SK_SKB :case BPF_PROG_TYPE_SK_MSG : -case BPF_PROG_TYPE_LIRC_MODE2 :case BPF_PROG_TYPE_FLOW_DISSECTOR :case BPF_PROG_TYPE_CGROUP_DEVICE :case BPF_PROG_TYPE_CGROUP_SOCK :@@ -2202,6 +2201,17 @@ static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) } }
Quoted 14 lines
kernel/bpf/syscall.c static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) · line 2213
Quoted 10 lines
kernel/bpf/syscall.c +10
-0+static bool is_sys_admin_prog_type (enum bpf_prog_type prog_type) +{ +switch (prog_type) { +case BPF_PROG_TYPE_LIRC_MODE2 : +case BPF_PROG_TYPE_EXT :/* extends any prog */ +return true; +default : +return false; + } +}I am not sure whether we should do this. This is a behavior change, that may break some user space. Also,
BPF_PROG_TYPE_EXTis checked inis_perfmon_prog_type(), and this change will make that case useless.
Sure, I can drop it from v3 and make this function appear for HID only.
Regarding BPF_PROG_TYPE_EXT, it was already in both is_net_admin_prog_type() and is_perfmon_prog_type(), so I duplicated it here, but I agree, given that it's already in the first function there, CPA_SYS_ADMIN is already checked.
Cheers,
Benjamin
Quoted 6 lines
Thanks,
Song[...]
Re: [PATCH bpf-next v2 01/28] bpf: add new is_sys_admin_prog_type() helper
Quoted 51 lines · Benjamin Tissoires
Quoted 35 lines · Song Liu
Quoted 32 lines · Benjamin Tissoires
LIRC_MODE2does not really neednet_admincapability, but onlysys_admin.Extract a new helper for it, it will be also used for the HID bpf implementation.
Cc Sean Young <[email protected]>Signed-off-by Benjamin Tissoires <[email protected]>---
new in v2
--- kernel/bpf/syscall.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)kernel/bpf/syscall.c +0
-1@@ -2165,7 +2165,6 @@ static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)case BPF_PROG_TYPE_LWT_SEG6LOCAL :case BPF_PROG_TYPE_SK_SKB :case BPF_PROG_TYPE_SK_MSG : -case BPF_PROG_TYPE_LIRC_MODE2 :case BPF_PROG_TYPE_FLOW_DISSECTOR :case BPF_PROG_TYPE_CGROUP_DEVICE :case BPF_PROG_TYPE_CGROUP_SOCK :@@ -2202,6 +2201,17 @@ static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) } }Quoted 14 lines
kernel/bpf/syscall.c static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) · line 2213
Quoted 10 lines
kernel/bpf/syscall.c +10
-0+static bool is_sys_admin_prog_type (enum bpf_prog_type prog_type) +{ +switch (prog_type) { +case BPF_PROG_TYPE_LIRC_MODE2 : +case BPF_PROG_TYPE_EXT :/* extends any prog */ +return true; +default : +return false; + } +}I am not sure whether we should do this. This is a behavior change, that may break some user space. Also,
BPF_PROG_TYPE_EXTis checked inis_perfmon_prog_type(), and this change will make that case useless.
Quoted 1 line
Sure, I can drop it from v3 and make this function appear for HID only.
For BPF_PROG_TYPE_LIRC_MODE2, I don't think this change will break userspace. This is called from ir-keytable(1) which is called from udev. It should have all the necessary permissions.
In addition, the vast majority IR decoders are non-bpf. bpf ir decoders have very few users at the moment.
I am working on completely new userspace tooling which will make extensive use of bpf ir decoding with full lircd and IRP compatibility, but this is not finished yet (see https://github.com/seanyoung/cir).
Thanks
Sean
Song Liu
reviewerRe: [PATCH bpf-next v2 01/28] bpf: add new is_sys_admin_prog_type() helper
Quoted 59 lines · Sean Young
Quoted 51 lines · Benjamin Tissoires
Quoted 35 lines · Song Liu
Quoted 32 lines · Benjamin Tissoires
LIRC_MODE2does not really neednet_admincapability, but onlysys_admin.Extract a new helper for it, it will be also used for the HID bpf implementation.
Cc Sean Young <[email protected]>Signed-off-by Benjamin Tissoires <[email protected]>---
new in v2
--- kernel/bpf/syscall.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)kernel/bpf/syscall.c +0
-1@@ -2165,7 +2165,6 @@ static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)case BPF_PROG_TYPE_LWT_SEG6LOCAL :case BPF_PROG_TYPE_SK_SKB :case BPF_PROG_TYPE_SK_MSG : -case BPF_PROG_TYPE_LIRC_MODE2 :case BPF_PROG_TYPE_FLOW_DISSECTOR :case BPF_PROG_TYPE_CGROUP_DEVICE :case BPF_PROG_TYPE_CGROUP_SOCK :@@ -2202,6 +2201,17 @@ static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) } }Quoted 14 lines
kernel/bpf/syscall.c static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) · line 2213
Quoted 10 lines
kernel/bpf/syscall.c +10
-0+static bool is_sys_admin_prog_type (enum bpf_prog_type prog_type) +{ +switch (prog_type) { +case BPF_PROG_TYPE_LIRC_MODE2 : +case BPF_PROG_TYPE_EXT :/* extends any prog */ +return true; +default : +return false; + } +}I am not sure whether we should do this. This is a behavior change, that may break some user space. Also,
BPF_PROG_TYPE_EXTis checked inis_perfmon_prog_type(), and this change will make that case useless.Quoted 1 line
Sure, I can drop it from v3 and make this function appear for HID only.
For
BPF_PROG_TYPE_LIRC_MODE2, I don't think this change will break userspace. This is called from ir-keytable(1) which is called from udev. It should have all the necessary permissions.
Quoted 6 lines
In addition, the vast majority IR decoders are non-bpf. bpf ir decoders have very few users at the moment.
I am working on completely new userspace tooling which will make extensive use of bpf ir decoding with full lircd and IRP compatibility, but this is not finished yet (see https://github.com/seanyoung/cir).
Thanks for these information. I guess change for BPF_PROG_TYPE_LIRC_MODE2 is ok then. Would you mind ack or review this change (either current version or a later version)?
Thanks,
Song
Song Liu
reviewerRe: [PATCH bpf-next v2 01/28] bpf: add new is_sys_admin_prog_type() helper
In reply to Benjamin TissoiresQuoted 52 lines · Benjamin Tissoires
Quoted 35 lines · Song Liu
Quoted 32 lines · Benjamin Tissoires
LIRC_MODE2does not really neednet_admincapability, but onlysys_admin.Extract a new helper for it, it will be also used for the HID bpf implementation.
Cc Sean Young <[email protected]>Signed-off-by Benjamin Tissoires <[email protected]>---
new in v2
--- kernel/bpf/syscall.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)kernel/bpf/syscall.c +0
-1@@ -2165,7 +2165,6 @@ static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)case BPF_PROG_TYPE_LWT_SEG6LOCAL :case BPF_PROG_TYPE_SK_SKB :case BPF_PROG_TYPE_SK_MSG : -case BPF_PROG_TYPE_LIRC_MODE2 :case BPF_PROG_TYPE_FLOW_DISSECTOR :case BPF_PROG_TYPE_CGROUP_DEVICE :case BPF_PROG_TYPE_CGROUP_SOCK :@@ -2202,6 +2201,17 @@ static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) } }Quoted 14 lines
kernel/bpf/syscall.c static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) · line 2213
Quoted 10 lines
kernel/bpf/syscall.c +10
-0+static bool is_sys_admin_prog_type (enum bpf_prog_type prog_type) +{ +switch (prog_type) { +case BPF_PROG_TYPE_LIRC_MODE2 : +case BPF_PROG_TYPE_EXT :/* extends any prog */ +return true; +default : +return false; + } +}I am not sure whether we should do this. This is a behavior change, that may break some user space. Also,
BPF_PROG_TYPE_EXTis checked inis_perfmon_prog_type(), and this change will make that case useless.
Quoted 6 lines
Sure, I can drop it from v3 and make this function appear for HID only.
Regarding
BPF_PROG_TYPE_EXT, it was already in bothis_net_admin_prog_type()andis_perfmon_prog_type(), so I duplicated it here, but I agree, given that it's already in the first function there,CPA_SYS_ADMINis already checked.
I think with current code, a user with CAP_BPF, CAP_NET_ADMIN, and CAP_PERFMON (but not CAP_SYS_ADMIN) can load programs of type BPF_PROG_TYPE_EXT. But after the patch, the same user will not be able to do it. Did I misread it? It is not a common case though.
Re: [PATCH bpf-next v2 01/28] bpf: add new is_sys_admin_prog_type() helper
In reply to Benjamin TissoiresQuoted 7 lines · Benjamin Tissoires
LIRC_MODE2does not really neednet_admincapability, but onlysys_admin.Extract a new helper for it, it will be also used for the HID bpf implementation.
Cc Sean Young <[email protected]>Signed-off-by Benjamin Tissoires <[email protected]>
For BPF_PROG_TYPE_LIRC_MODE2, I don't think this change will break userspace. This is called from ir-keytable(1) which is called from udev. It should have all the necessary permissions.
In addition, the vast majority IR decoders are non-bpf. bpf ir decoders have very few users at the moment.
Sean
Quoted 49 lines
---
new in v2
--- kernel/bpf/syscall.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)kernel/bpf/syscall.c +13
-1@@ -2165,7 +2165,6 @@ static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)case BPF_PROG_TYPE_LWT_SEG6LOCAL :case BPF_PROG_TYPE_SK_SKB :case BPF_PROG_TYPE_SK_MSG : -case BPF_PROG_TYPE_LIRC_MODE2 :case BPF_PROG_TYPE_FLOW_DISSECTOR :case BPF_PROG_TYPE_CGROUP_DEVICE :case BPF_PROG_TYPE_CGROUP_SOCK :@@ -2202,6 +2201,17 @@ static bool is_perfmon_prog_type(enum bpf_prog_type prog_type) } } +static bool is_sys_admin_prog_type (enum bpf_prog_type prog_type) +{ +switch (prog_type) { +case BPF_PROG_TYPE_LIRC_MODE2 : +case BPF_PROG_TYPE_EXT :/* extends any prog */ +return true; +default : +return false; + } +} +/* last field in 'union bpf_attr' used by this command */ #define BPF_PROG_LOAD_LAST_FIELD core_relo_rec_size@@ -2252,6 +2262,8 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr)return -EPERM ;if (is_perfmon_prog_type (type) && !perfmon_capable ())return -EPERM ; +if (is_sys_admin_prog_type (type) && !capable (CAP_SYS_ADMIN )) +return -EPERM ;/* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog * or btf, we need to check which one it is Signature · 1 line
2.35.1
PATCH v2 2/28 bpf: introduce hid program type
In reply to Benjamin TissoiresHID is a protocol that could benefit from using BPF too.
This patch implements a net-like use of BPF capability for HID. Any incoming report coming from the device can be injected into a series of BPF programs that can modify it or even discard it by setting the size in the context to 0.
The kernel/bpf implementation is based on net-namespace.c, with only the bpf_link part kept, there is no real points in keeping the bpf_prog_{attach|detach} API.
The implementation here is only focusing on the bpf changes. The HID changes that hooks onto this are coming in a separate patch.
Given that HID can be compiled in as a module, and the functions that kernel/bpf/hid.c needs to call in hid.ko are exported in struct hid_hooks.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
- unsigned long -> __u16 in uapi/linux/bpf_hid.h
- change the bpf_ctx to be of variable size, with a min of 1024 bytes
- make this 1 kB available directly from bpf program, the rest will need a helper
- add some more doc comments in uapi
--- include/linux/bpf-hid.h | 108 ++++++++ include/linux/bpf_types.h | 4 + include/linux/hid.h | 5 + include/uapi/linux/bpf.h | 7 + include/uapi/linux/bpf_hid.h | 39 +++ kernel/bpf/Makefile | 3 + kernel/bpf/hid.c | 437 +++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 8 + tools/include/uapi/linux/bpf.h | 7 + 9 files changed, 618 insertions(+) create mode 100644 include/linux/bpf-hid.h create mode 100644 include/uapi/linux/bpf_hid.h create mode 100644 kernel/bpf/hid.c
include/linux/bpf-hid.h new file +108 -0
@@ -0,0 +1,108 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _BPF_HID_H +#define _BPF_HID_H + +#include <linux/mutex.h> +#include <uapi/linux/bpf.h> +#include <uapi/linux/bpf_hid.h> +#include <linux/list.h> +#include <linux/slab.h> + +struct bpf_prog ; +struct bpf_prog_array ; +struct hid_device ; + +enum bpf_hid_attach_type { +BPF_HID_ATTACH_INVALID =-1 , +BPF_HID_ATTACH_DEVICE_EVENT =0 , +MAX_BPF_HID_ATTACH_TYPE +}; + +struct bpf_hid { +struct hid_bpf_ctx *ctx; + +/* Array of programs to run compiled from links */ +struct bpf_prog_array __rcu *run_array[MAX_BPF_HID_ATTACH_TYPE ]; +struct list_head links[MAX_BPF_HID_ATTACH_TYPE ]; +}; + +static inline enum bpf_hid_attach_type +to_bpf_hid_attach_type (enum bpf_attach_type attach_type) +{ +switch (attach_type) { +case BPF_HID_DEVICE_EVENT : +return BPF_HID_ATTACH_DEVICE_EVENT ; +default : +return BPF_HID_ATTACH_INVALID ; + } +} + +static inline struct hid_bpf_ctx *bpf_hid_allocate_ctx (struct hid_device *hdev, +size_t data_size) +{ +struct hid_bpf_ctx *ctx; + +/* ensure data_size is between min and max */ + data_size =clamp_val (data_size, +HID_BPF_MIN_BUFFER_SIZE , +HID_BPF_MAX_BUFFER_SIZE ); + + ctx =kzalloc (sizeof (*ctx) + data_size,GFP_KERNEL ); +if (!ctx) +return ERR_PTR (-ENOMEM ); + + ctx->hdev = hdev; + ctx->allocated_size = data_size; + +return ctx; +} + +union bpf_attr ; +struct bpf_prog ; + +#if IS_ENABLED (CONFIG_HID ) +int bpf_hid_prog_query (const union bpf_attr *attr, +union bpf_attr __user *uattr); +int bpf_hid_link_create (const union bpf_attr *attr, +struct bpf_prog *prog); +#else +static inline int bpf_hid_prog_query (const union bpf_attr *attr, +union bpf_attr __user *uattr) +{ +return -EOPNOTSUPP ; +} + +static inline int bpf_hid_link_create (const union bpf_attr *attr, +struct bpf_prog *prog) +{ +return -EOPNOTSUPP ; +} +#endif + +static inline bool bpf_hid_link_empty (struct bpf_hid *bpf, +enum bpf_hid_attach_type type) +{ +return list_empty (&bpf->links[type]); +} + +struct bpf_hid_hooks { +struct hid_device *(*hdev_from_fd)(int fd); +int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type); +void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +}; + +#ifdef CONFIG_BPF +int bpf_hid_init (struct hid_device *hdev); +void bpf_hid_exit (struct hid_device *hdev); +void bpf_hid_set_hooks (struct bpf_hid_hooks *hooks); +#else +static inline int bpf_hid_init (struct hid_device *hdev) +{ +return 0 ; +} + +static inline void bpf_hid_exit (struct hid_device *hdev) {} +static inline void bpf_hid_set_hooks (struct bpf_hid_hooks *hooks) {} +#endif + +#endif /* _BPF_HID_H */
include/linux/bpf_types.h +4 -0
@@ -76,6 +76,10 @@ BPF_PROG_TYPE(BPF_PROG_TYPE_EXT, bpf_extension, BPF_PROG_TYPE(BPF_PROG_TYPE_LSM, lsm, void *, void *) #endif /* CONFIG_BPF_LSM */ +#if IS_ENABLED(CONFIG_HID) +BPF_PROG_TYPE(BPF_PROG_TYPE_HID, hid, + __u32, u32) +#endif #endif BPF_PROG_TYPE(BPF_PROG_TYPE_SYSCALL, bpf_syscall, void *, void *)
include/linux/hid.h +5 -0
@@ -15,6 +15,7 @@#include <linux/bitops.h> +#include <linux/bpf-hid.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/list.h>
@@ -639,6 +640,10 @@ struct hid_device { /* device report descriptor */struct list_head debug_list;spinlock_t debug_list_lock;wait_queue_head_t debug_wait; + +#ifdef CONFIG_BPF +struct bpf_hid bpf; +#endif };#define to_hid_device (pdev) \
include/uapi/linux/bpf.h +7 -0
@@ -952,6 +952,7 @@ enum bpf_prog_type {BPF_PROG_TYPE_LSM ,BPF_PROG_TYPE_SK_LOOKUP ,BPF_PROG_TYPE_SYSCALL ,/* a program that can execute syscalls */ + BPF_PROG_TYPE_HID, }; enum bpf_attach_type {
@@ -997,6 +998,7 @@ enum bpf_attach_type {BPF_SK_REUSEPORT_SELECT ,BPF_SK_REUSEPORT_SELECT_OR_MIGRATE ,BPF_PERF_EVENT , +BPF_HID_DEVICE_EVENT , __MAX_BPF_ATTACH_TYPE };
@@ -1011,6 +1013,7 @@ enum bpf_link_type {BPF_LINK_TYPE_NETNS =5 ,BPF_LINK_TYPE_XDP =6 ,BPF_LINK_TYPE_PERF_EVENT =7 , +BPF_LINK_TYPE_HID =8 , MAX_BPF_LINK_TYPE, };
@@ -5870,6 +5873,10 @@ struct bpf_link_info {struct {__u32 ifindex; } xdp; +struct { +__s32 hidraw_ino; +__u32 attach_type; + } hid; }; } __attribute__((aligned(8)));
include/uapi/linux/bpf_hid.h new file +39 -0
@@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later WITH Linux-syscall-note */ + +/* +* HID BPF public headers +* +* Copyright (c) 2021 Benjamin Tissoires +*/ + +#ifndef _UAPI__LINUX_BPF_HID_H__ +#define _UAPI__LINUX_BPF_HID_H__ + +#include <linux/types.h> + +/* +* The first 1024 bytes are available directly in the bpf programs. +* To access the rest of the data (if allocated_size is bigger +* than 1024, you need to use bpf_hid_ helpers. +*/ +#define HID_BPF_MIN_BUFFER_SIZE 1024 +#define HID_BPF_MAX_BUFFER_SIZE 16384/* in sync with HID_MAX_BUFFER_SIZE */ + +struct hid_device ; + +enum hid_bpf_event { +HID_BPF_UNDEF =0 , +HID_BPF_DEVICE_EVENT ,/* when attach type is BPF_HID_DEVICE_EVENT */ +}; + +struct hid_bpf_ctx { +enum hid_bpf_event type;/* read-only */ +__u16 allocated_size;/* the allocated size of data below (RO) */ +struct hid_device *hdev;/* read-only */ + +__u16 size;/* used size in data (RW) */ +__u8 data[];/* data buffer (RW) */ +}; + +#endif /* _UAPI__LINUX_BPF_HID_H__ */ +
kernel/bpf/Makefile +3 -0
@@ -35,6 +35,9 @@ ifeq ($(CONFIG_BPF_JIT),y) obj-$(CONFIG_BPF_SYSCALL) += bpf_struct_ops.o obj-${CONFIG_BPF_LSM} += bpf_lsm.o endif +ifneq ($(CONFIG_HID),) +obj-$(CONFIG_BPF_SYSCALL) += hid.o +endif obj-$(CONFIG_BPF_PRELOAD) += preload/ obj-$(CONFIG_BPF_SYSCALL) += relo_core.o
kernel/bpf/hid.c new file +437 -0
437 lines not on this page · raw message
kernel/bpf/syscall.c +8 -0
@@ -3,6 +3,7 @@*/ #include <linux/bpf.h> #include <linux/bpf-cgroup.h> +#include <linux/bpf-hid.h> #include <linux/bpf_trace.h> #include <linux/bpf_lirc.h> #include <linux/bpf_verifier.h>
@@ -2205,6 +2206,7 @@ static bool is_sys_admin_prog_type(enum bpf_prog_type prog_type) {switch (prog_type) {case BPF_PROG_TYPE_LIRC_MODE2 : +case BPF_PROG_TYPE_HID :case BPF_PROG_TYPE_EXT :/* extends any prog */ return true;default :
@@ -3200,6 +3202,8 @@ attach_type_to_prog_type(enum bpf_attach_type attach_type)return BPF_PROG_TYPE_SK_LOOKUP ;case BPF_XDP :return BPF_PROG_TYPE_XDP ; +case BPF_HID_DEVICE_EVENT : +return BPF_PROG_TYPE_HID ;default :return BPF_PROG_TYPE_UNSPEC ; }
@@ -3343,6 +3347,8 @@ static int bpf_prog_query(const union bpf_attr *attr,case BPF_SK_MSG_VERDICT :case BPF_SK_SKB_VERDICT :return sock_map_bpf_prog_query (attr, uattr); +case BPF_HID_DEVICE_EVENT : +return bpf_hid_prog_query (attr, uattr);default :return -EINVAL ; }
@@ -4337,6 +4343,8 @@ static int link_create(union bpf_attr *attr, bpfptr_t uattr) ret =bpf_perf_link_attach (attr, prog);break ;#endif +case BPF_PROG_TYPE_HID : +return bpf_hid_link_create (attr, prog);default : ret = -EINVAL ; }
tools/include/uapi/linux/bpf.h +7 -0
@@ -952,6 +952,7 @@ enum bpf_prog_type {BPF_PROG_TYPE_LSM ,BPF_PROG_TYPE_SK_LOOKUP ,BPF_PROG_TYPE_SYSCALL ,/* a program that can execute syscalls */ + BPF_PROG_TYPE_HID, }; enum bpf_attach_type {
@@ -997,6 +998,7 @@ enum bpf_attach_type {BPF_SK_REUSEPORT_SELECT ,BPF_SK_REUSEPORT_SELECT_OR_MIGRATE ,BPF_PERF_EVENT , +BPF_HID_DEVICE_EVENT , __MAX_BPF_ATTACH_TYPE };
@@ -1011,6 +1013,7 @@ enum bpf_link_type {BPF_LINK_TYPE_NETNS =5 ,BPF_LINK_TYPE_XDP =6 ,BPF_LINK_TYPE_PERF_EVENT =7 , +BPF_LINK_TYPE_HID =8 , MAX_BPF_LINK_TYPE, };
@@ -5870,6 +5873,10 @@ struct bpf_link_info {struct {__u32 ifindex; } xdp; +struct { +__s32 hidraw_ino; +__u32 attach_type; + } hid; }; } __attribute__((aligned(8)));
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 02/28] bpf: introduce hid program type
Quoted 87 lines · Benjamin Tissoires
HID is a protocol that could benefit from using BPF too.
This patch implements a net-like use of BPF capability for HID. Any incoming report coming from the device can be injected into a series of BPF programs that can modify it or even discard it by setting the size in the context to 0.
The kernel/bpf implementation is based on
net-namespace.c, with only thebpf_linkpart kept, there is no real points in keeping the bpf_prog_{attach|detach} API.The implementation here is only focusing on the bpf changes. The HID changes that hooks onto this are coming in a separate patch.
Given that HID can be compiled in as a module, and the functions that
kernel/bpf/hid.cneeds to call in hid.ko are exported in structhid_hooks.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
- unsigned long ->__u16inuapi/linux/bpf_hid.h
- change thebpf_ctxto be of variable size, with a min of 1024 bytes
- make this 1 kB available directly from bpf program, the rest will need a helper
- add some more doc comments in uapi--- include/linux/bpf-hid.h | 108 ++++++++ include/linux/bpf_types.h | 4 + include/linux/hid.h | 5 + include/uapi/linux/bpf.h | 7 + include/uapi/linux/bpf_hid.h | 39 +++ kernel/bpf/Makefile | 3 + kernel/bpf/hid.c | 437 +++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 8 + tools/include/uapi/linux/bpf.h | 7 + 9 files changed, 618 insertions(+) create mode 100644 include/linux/bpf-hid.h create mode 100644 include/uapi/linux/bpf_hid.h create mode 100644 kernel/bpf/hid.cinclude/linux/bpf-hid.h new file +38
-0@@ -0,0 +1,108 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _BPF_HID_H +#define _BPF_HID_H + +#include <linux/mutex.h> +#include <uapi/linux/bpf.h> +#include <uapi/linux/bpf_hid.h> +#include <linux/list.h> +#include <linux/slab.h> + +struct bpf_prog ; +struct bpf_prog_array ; +struct hid_device ; + +enum bpf_hid_attach_type { +BPF_HID_ATTACH_INVALID =-1 , +BPF_HID_ATTACH_DEVICE_EVENT =0 , +MAX_BPF_HID_ATTACH_TYPE +}; + +struct bpf_hid { +struct hid_bpf_ctx *ctx; + +/* Array of programs to run compiled from links */ +struct bpf_prog_array __rcu *run_array[MAX_BPF_HID_ATTACH_TYPE ]; +struct list_head links[MAX_BPF_HID_ATTACH_TYPE ]; +}; + +static inline enum bpf_hid_attach_type +to_bpf_hid_attach_type (enum bpf_attach_type attach_type) +{ +switch (attach_type) { +case BPF_HID_DEVICE_EVENT : +return BPF_HID_ATTACH_DEVICE_EVENT ; +default : +return BPF_HID_ATTACH_INVALID ; + } +}
include/linux/bpf-hid.h line 48
Quoted 10 lines
include/linux/bpf-hid.h new file +10
-0+ +static inline struct hid_bpf_ctx *bpf_hid_allocate_ctx (struct hid_device *hdev, +size_t data_size) +{ +struct hid_bpf_ctx *ctx; + +/* ensure data_size is between min and max */ + data_size =clamp_val (data_size, +HID_BPF_MIN_BUFFER_SIZE , +HID_BPF_MAX_BUFFER_SIZE );
Do you want to return an error if the data size is not within the range? Otherwise people will just start to use crazy values and you will always be limiting them?
include/linux/bpf-hid.h line 58
Quoted 10 lines
include/linux/bpf-hid.h new file +10
-0+ + ctx =kzalloc (sizeof (*ctx) + data_size,GFP_KERNEL ); +if (!ctx) +return ERR_PTR (-ENOMEM ); + + ctx->hdev = hdev; + ctx->allocated_size = data_size; + +return ctx; +}
And why is this an inline function? Why not put it in a .c file?
Quoted 55 lines
include/linux/bpf-hid.h new file +50
-0+ +union bpf_attr ; +struct bpf_prog ; + +#if IS_ENABLED (CONFIG_HID ) +int bpf_hid_prog_query (const union bpf_attr *attr, +union bpf_attr __user *uattr); +int bpf_hid_link_create (const union bpf_attr *attr, +struct bpf_prog *prog); +#else +static inline int bpf_hid_prog_query (const union bpf_attr *attr, +union bpf_attr __user *uattr) +{ +return -EOPNOTSUPP ; +} + +static inline int bpf_hid_link_create (const union bpf_attr *attr, +struct bpf_prog *prog) +{ +return -EOPNOTSUPP ; +} +#endif + +static inline bool bpf_hid_link_empty (struct bpf_hid *bpf, +enum bpf_hid_attach_type type) +{ +return list_empty (&bpf->links[type]); +} + +struct bpf_hid_hooks { +struct hid_device *(*hdev_from_fd)(int fd); +int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type); +void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +}; + +#ifdef CONFIG_BPF +int bpf_hid_init (struct hid_device *hdev); +void bpf_hid_exit (struct hid_device *hdev); +void bpf_hid_set_hooks (struct bpf_hid_hooks *hooks); +#else +static inline int bpf_hid_init (struct hid_device *hdev) +{ +return 0 ; +} + +static inline void bpf_hid_exit (struct hid_device *hdev) {} +static inline void bpf_hid_set_hooks (struct bpf_hid_hooks *hooks) {} +#endif + +#endif /* _BPF_HID_H */ include/linux/bpf_types.h +0
-0
include/linux/bpf_types.h BPF_PROG_TYPE(BPF_PROG_TYPE_EXT, bpf_extension, · line 81
Quoted 6 lines
include/linux/bpf_types.h +3
-0@@ -76,6 +76,10 @@ BPF_PROG_TYPE(BPF_PROG_TYPE_EXT, bpf_extension,BPF_PROG_TYPE (BPF_PROG_TYPE_LSM , lsm, void *, void *) #endif /* CONFIG_BPF_LSM */ +#if IS_ENABLED(CONFIG_HID) +BPF_PROG_TYPE (BPF_PROG_TYPE_HID , hid, + __u32, u32)
Why the mix of __u32 and u32 here?
Quoted 56 lines
include/linux/bpf_types.h +1
-0+#endif #endif BPF_PROG_TYPE (BPF_PROG_TYPE_SYSCALL , bpf_syscall, void *, void *)include/linux/hid.h +5
-0@@ -15,6 +15,7 @@#include <linux/bitops.h> +#include <linux/bpf-hid.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/list.h> @@ -639,6 +640,10 @@ struct hid_device { /* device report descriptor */struct list_head debug_list;spinlock_t debug_list_lock;wait_queue_head_t debug_wait; + +#ifdef CONFIG_BPF +struct bpf_hid bpf; +#endif };#define to_hid_device (pdev) \include/uapi/linux/bpf.h +3
-0@@ -952,6 +952,7 @@ enum bpf_prog_type {BPF_PROG_TYPE_LSM ,BPF_PROG_TYPE_SK_LOOKUP ,BPF_PROG_TYPE_SYSCALL ,/* a program that can execute syscalls */ + BPF_PROG_TYPE_HID, }; enum bpf_attach_type {@@ -997,6 +998,7 @@ enum bpf_attach_type {BPF_SK_REUSEPORT_SELECT ,BPF_SK_REUSEPORT_SELECT_OR_MIGRATE ,BPF_PERF_EVENT , +BPF_HID_DEVICE_EVENT , __MAX_BPF_ATTACH_TYPE };@@ -1011,6 +1013,7 @@ enum bpf_link_type {BPF_LINK_TYPE_NETNS =5 ,BPF_LINK_TYPE_XDP =6 ,BPF_LINK_TYPE_PERF_EVENT =7 , +BPF_LINK_TYPE_HID =8 , MAX_BPF_LINK_TYPE, };
include/uapi/linux/bpf.h struct bpf_link_info { · line 5877
Quoted 5 lines
include/uapi/linux/bpf.h +2
-0@@ -5870,6 +5873,10 @@ struct bpf_link_info {struct {__u32 ifindex; } xdp; +struct { +__s32 hidraw_ino;
"ino"? We have lots of letters to spell words out :)
Quoted 11 lines
include/uapi/linux/bpf.h +2
-0+__u32 attach_type; + } hid; }; } __attribute__((aligned(8)));include/uapi/linux/bpf_hid.h new file +0
-0
include/uapi/linux/bpf_hid.h line 6
Quoted 6 lines
include/uapi/linux/bpf_hid.h new file +6
-0@@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later WITH Linux-syscall-note */ + +/* +* HID BPF public headers +* +* Copyright (c) 2021 Benjamin Tissoires
Did you forget the copyright line on the other .h file above?
Quoted 4 lines
include/uapi/linux/bpf_hid.h new file +4
-0+*/ + +#ifndef _UAPI__LINUX_BPF_HID_H__ +#define _UAPI__LINUX_BPF_HID_H__
include/uapi/linux/bpf_hid.h line 20
Quoted 10 lines
include/uapi/linux/bpf_hid.h new file +10
-0+ +#include <linux/types.h> + +/* +* The first 1024 bytes are available directly in the bpf programs. +* To access the rest of the data (if allocated_size is bigger +* than 1024, you need to use bpf_hid_ helpers. +*/ +#define HID_BPF_MIN_BUFFER_SIZE 1024 +#define HID_BPF_MAX_BUFFER_SIZE 16384/* in sync with HID_MAX_BUFFER_SIZE */
Can't you just use HID_MAX_BUFFER_SIZE?
Anyway, all minor stuff, looks good!
Re: [PATCH bpf-next v2 02/28] bpf: introduce hid program type
Quoted 93 lines · Greg KH
Quoted 91 lines · Benjamin Tissoires
HID is a protocol that could benefit from using BPF too.
This patch implements a net-like use of BPF capability for HID. Any incoming report coming from the device can be injected into a series of BPF programs that can modify it or even discard it by setting the size in the context to 0.
The kernel/bpf implementation is based on
net-namespace.c, with only thebpf_linkpart kept, there is no real points in keeping the bpf_prog_{attach|detach} API.The implementation here is only focusing on the bpf changes. The HID changes that hooks onto this are coming in a separate patch.
Given that HID can be compiled in as a module, and the functions that
kernel/bpf/hid.cneeds to call in hid.ko are exported in structhid_hooks.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
- unsigned long ->__u16inuapi/linux/bpf_hid.h
- change thebpf_ctxto be of variable size, with a min of 1024 bytes
- make this 1 kB available directly from bpf program, the rest will need a helper
- add some more doc comments in uapi--- include/linux/bpf-hid.h | 108 ++++++++ include/linux/bpf_types.h | 4 + include/linux/hid.h | 5 + include/uapi/linux/bpf.h | 7 + include/uapi/linux/bpf_hid.h | 39 +++ kernel/bpf/Makefile | 3 + kernel/bpf/hid.c | 437 +++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 8 + tools/include/uapi/linux/bpf.h | 7 + 9 files changed, 618 insertions(+) create mode 100644 include/linux/bpf-hid.h create mode 100644 include/uapi/linux/bpf_hid.h create mode 100644 kernel/bpf/hid.cinclude/linux/bpf-hid.h new file +42
-0@@ -0,0 +1,108 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _BPF_HID_H +#define _BPF_HID_H + +#include <linux/mutex.h> +#include <uapi/linux/bpf.h> +#include <uapi/linux/bpf_hid.h> +#include <linux/list.h> +#include <linux/slab.h> + +struct bpf_prog ; +struct bpf_prog_array ; +struct hid_device ; + +enum bpf_hid_attach_type { +BPF_HID_ATTACH_INVALID =-1 , +BPF_HID_ATTACH_DEVICE_EVENT =0 , +MAX_BPF_HID_ATTACH_TYPE +}; + +struct bpf_hid { +struct hid_bpf_ctx *ctx; + +/* Array of programs to run compiled from links */ +struct bpf_prog_array __rcu *run_array[MAX_BPF_HID_ATTACH_TYPE ]; +struct list_head links[MAX_BPF_HID_ATTACH_TYPE ]; +}; + +static inline enum bpf_hid_attach_type +to_bpf_hid_attach_type (enum bpf_attach_type attach_type) +{ +switch (attach_type) { +case BPF_HID_DEVICE_EVENT : +return BPF_HID_ATTACH_DEVICE_EVENT ; +default : +return BPF_HID_ATTACH_INVALID ; + } +} + +static inline struct hid_bpf_ctx *bpf_hid_allocate_ctx (struct hid_device *hdev, +size_t data_size) +{
Quoted 8 lines
include/linux/bpf-hid.h line 48
Quoted 6 lines
include/linux/bpf-hid.h new file +6
-0+struct hid_bpf_ctx *ctx; + +/* ensure data_size is between min and max */ + data_size =clamp_val (data_size, +HID_BPF_MIN_BUFFER_SIZE , +HID_BPF_MAX_BUFFER_SIZE );Do you want to return an error if the data size is not within the range?
That was not something I was counting on.
Though I am thinking of not necessarily clamping this value in the end because I might have found a way to not do the initial memcpy when running a prog, and so not having to limit the size of the data.
Quoted 2 lines
Otherwise people will just start to use crazy values and you will always be limiting them?
The users of this helper are really limited to drivers/hid/hid_pbf.c and kernel/bpf/hid.c. And they are known in advance and there must be only one user per attach type.
The only thing where the data might explode is when in used with SEC(hid/device_event), because we statically allocate one bpf_ctx based on the device report descriptor.
But if the required size is bigger than HID_BPF_MAX_BUFFER_SIZE, the device will not probe or at least already logs something in the dmesg that we are using a too big buffer.
Quoted 13 lines
include/linux/bpf-hid.h line 58
Quoted 11 lines
include/linux/bpf-hid.h new file +10
-0+ + ctx =kzalloc (sizeof (*ctx) + data_size,GFP_KERNEL ); +if (!ctx) +return ERR_PTR (-ENOMEM ); + + ctx->hdev = hdev; + ctx->allocated_size = data_size; + +return ctx; +}And why is this an inline function? Why not put it in a .c file?
The problem I have here is that the hid module can be loaded as an external module. So I can not directly use that helper from hid.ko from kernel/bpf/hid.c (I need it there once for the SEC(hid/user_event) bprogram attach type).
So the solution would be to have the code in the c part of kernel/bpf/hid.c and export the function as GPL, but I wanted to have the minimum of knowledge of HID-BPF internals in that file. So I ended up using an inline so I can reuse it independently in kernel/bpf/hid.c and drivers/hid/hid-bpf.c.
Quoted 56 lines
Quoted 56 lines
include/linux/bpf-hid.h new file +50
-0+ +union bpf_attr ; +struct bpf_prog ; + +#if IS_ENABLED (CONFIG_HID ) +int bpf_hid_prog_query (const union bpf_attr *attr, +union bpf_attr __user *uattr); +int bpf_hid_link_create (const union bpf_attr *attr, +struct bpf_prog *prog); +#else +static inline int bpf_hid_prog_query (const union bpf_attr *attr, +union bpf_attr __user *uattr) +{ +return -EOPNOTSUPP ; +} + +static inline int bpf_hid_link_create (const union bpf_attr *attr, +struct bpf_prog *prog) +{ +return -EOPNOTSUPP ; +} +#endif + +static inline bool bpf_hid_link_empty (struct bpf_hid *bpf, +enum bpf_hid_attach_type type) +{ +return list_empty (&bpf->links[type]); +} + +struct bpf_hid_hooks { +struct hid_device *(*hdev_from_fd)(int fd); +int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type); +void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +}; + +#ifdef CONFIG_BPF +int bpf_hid_init (struct hid_device *hdev); +void bpf_hid_exit (struct hid_device *hdev); +void bpf_hid_set_hooks (struct bpf_hid_hooks *hooks); +#else +static inline int bpf_hid_init (struct hid_device *hdev) +{ +return 0 ; +} + +static inline void bpf_hid_exit (struct hid_device *hdev) {} +static inline void bpf_hid_set_hooks (struct bpf_hid_hooks *hooks) {} +#endif + +#endif /* _BPF_HID_H */ include/linux/bpf_types.h +0
-0@@ -76,6 +76,10 @@ BPF_PROG_TYPE(BPF_PROG_TYPE_EXT, bpf_extension,
Quoted 8 lines
include/linux/bpf_types.h BPF_PROG_TYPE(BPF_PROG_TYPE_EXT, bpf_extension, · line 81
Quoted 6 lines
include/linux/bpf_types.h +3
-0BPF_PROG_TYPE (BPF_PROG_TYPE_LSM , lsm, void *, void *) #endif /* CONFIG_BPF_LSM */ +#if IS_ENABLED(CONFIG_HID) +BPF_PROG_TYPE (BPF_PROG_TYPE_HID , hid, + __u32, u32)Why the mix of
__u32and u32 here?
This is actually valid. I tracked it down to kernel/bpf/btf.c with:
static union {
struct bpf_ctx_convert {
#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
prog_ctx_type _id##_prog; \
kern_ctx_type _id##_kern;
#include <linux/bpf_types.h>
#undef BPF_PROG_TYPE
} *__t;
/* 't' is written once under lock. Read many times. */
const struct btf_type *t;
} bpf_ctx_convert;So prog_ctx_type represents a user API, while kern_ctx_type represents the kernel counterpart.
That being said, this is plain wrong, because I am not using u32 as bpf context, but a properly defined struct :o)
So I probably need to amend this to be either "void *, void *)" or something better (I'll ask Song in my reply to him).
Quoted 54 lines
Quoted 54 lines
include/linux/bpf_types.h +1
-0+#endif #endif BPF_PROG_TYPE (BPF_PROG_TYPE_SYSCALL , bpf_syscall, void *, void *)include/linux/hid.h +5
-0@@ -15,6 +15,7 @@#include <linux/bitops.h> +#include <linux/bpf-hid.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/list.h> @@ -639,6 +640,10 @@ struct hid_device { /* device report descriptor */struct list_head debug_list;spinlock_t debug_list_lock;wait_queue_head_t debug_wait; + +#ifdef CONFIG_BPF +struct bpf_hid bpf; +#endif };#define to_hid_device (pdev) \include/uapi/linux/bpf.h +3
-0@@ -952,6 +952,7 @@ enum bpf_prog_type {BPF_PROG_TYPE_LSM ,BPF_PROG_TYPE_SK_LOOKUP ,BPF_PROG_TYPE_SYSCALL ,/* a program that can execute syscalls */ + BPF_PROG_TYPE_HID, }; enum bpf_attach_type {@@ -997,6 +998,7 @@ enum bpf_attach_type {BPF_SK_REUSEPORT_SELECT ,BPF_SK_REUSEPORT_SELECT_OR_MIGRATE ,BPF_PERF_EVENT , +BPF_HID_DEVICE_EVENT , __MAX_BPF_ATTACH_TYPE };@@ -1011,6 +1013,7 @@ enum bpf_link_type {BPF_LINK_TYPE_NETNS =5 ,BPF_LINK_TYPE_XDP =6 ,BPF_LINK_TYPE_PERF_EVENT =7 , + BPF_LINK_TYPE_HID = 8,
Quoted 10 lines
include/uapi/linux/bpf.h struct bpf_link_info { · line 5877
Quoted 8 lines
include/uapi/linux/bpf.h +2
-0MAX_BPF_LINK_TYPE, };@@ -5870,6 +5873,10 @@ struct bpf_link_info {struct {__u32 ifindex; } xdp; +struct { +__s32 hidraw_ino;"ino"? We have lots of letters to spell words out :)
no comments... :)
Quoted 6 lines
Quoted 6 lines
include/uapi/linux/bpf.h +2
-0+__u32 attach_type; + } hid; }; } __attribute__((aligned(8)));
Quoted 14 lines
include/uapi/linux/bpf_hid.h line 6
Quoted 12 lines
include/uapi/linux/bpf_hid.h new file +6
-0@@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later WITH Linux-syscall-note */ + +/* +* HID BPF public headers +* +* Copyright (c) 2021 Benjamin Tissoires Did you forget the copyright line on the other .h file above?
oops
Quoted 17 lines
Quoted 5 lines
include/uapi/linux/bpf_hid.h new file +4
-0+*/ + +#ifndef _UAPI__LINUX_BPF_HID_H__ +#define _UAPI__LINUX_BPF_HID_H__include/uapi/linux/bpf_hid.h line 20
Quoted 10 lines
include/uapi/linux/bpf_hid.h new file +10
-0+ +#include <linux/types.h> + +/* +* The first 1024 bytes are available directly in the bpf programs. +* To access the rest of the data (if allocated_size is bigger +* than 1024, you need to use bpf_hid_ helpers. +*/ +#define HID_BPF_MIN_BUFFER_SIZE 1024 +#define HID_BPF_MAX_BUFFER_SIZE 16384/* in sync with HID_MAX_BUFFER_SIZE */ Can't you just use
HID_MAX_BUFFER_SIZE?
Call me dumb, but curiously I could not get my code to compile there. If I include linux/hid.h, things are getting messy and either the tools or the kernel itself was not compiling properly (couldn't really remember what was failing exactly, sorry).
Quoted 2 lines
Anyway, all minor stuff, looks good!
Thanks. Not sure I'll keep the bpf_ctx the same after further thoughts, but I appreciate the review :)
Cheers,
Benjamin
Quoted 3 lines
Reviewed-by Greg Kroah-Hartman <[email protected]>
Song Liu
reviewerRe: [PATCH bpf-next v2 02/28] bpf: introduce hid program type
In reply to Benjamin TissoiresQuoted 2 lines · Benjamin Tissoires
HID is a protocol that could benefit from using BPF too.
[...]
include/linux/bpf-hid.h line 18
Quoted 11 lines
include/linux/bpf-hid.h new file +11
-0+#include <linux/list.h> +#include <linux/slab.h> + +struct bpf_prog ; +struct bpf_prog_array ; +struct hid_device ; + +enum bpf_hid_attach_type { +BPF_HID_ATTACH_INVALID =-1 , +BPF_HID_ATTACH_DEVICE_EVENT =0 , +MAX_BPF_HID_ATTACH_TYPE
Is it typical to have different BPF programs for different attach types? Otherwise, (different types may have similar BPF programs), maybe we can pass type as an argument to the program (shared among different types)?
[...]
include/uapi/linux/bpf_hid.h line 31
Quoted 10 lines
include/uapi/linux/bpf_hid.h new file +10
-0+struct hid_device ; + +enum hid_bpf_event { +HID_BPF_UNDEF =0 , +HID_BPF_DEVICE_EVENT ,/* when attach type is BPF_HID_DEVICE_EVENT */ +}; + +struct hid_bpf_ctx { +enum hid_bpf_event type;/* read-only */ +__u16 allocated_size;/* the allocated size of data below (RO) */
There is a (6-byte?) hole here.
include/uapi/linux/bpf_hid.h line 36
Quoted 5 lines
include/uapi/linux/bpf_hid.h new file +5
-0+struct hid_device *hdev;/* read-only */ + +__u16 size;/* used size in data (RW) */ +__u8 data[];/* data buffer (RW) */ +};
Do we really need hit_bpf_ctx in uapi? Maybe we can just use it from vmlinuxh?
[...]
kernel/bpf/hid.c line 56
Quoted 9 lines
kernel/bpf/hid.c new file +9
-0+ +static bool hid_is_valid_access (int off,int size, +enum bpf_access_type access_type, +const struct bpf_prog *prog, +struct bpf_insn_access_aux *info) +{ +/* everything not in ctx is prohibited */ +if (off <0 || off + size >sizeof (struct hid_bpf_ctx ) +HID_BPF_MIN_BUFFER_SIZE ) +return false;
Mabe add the following here to fail unaligned accesses
if (off % size != 0)
return false;[...]
Re: [PATCH bpf-next v2 02/28] bpf: introduce hid program type
Quoted 8 lines · Song Liu
Quoted 2 lines · Benjamin Tissoires
HID is a protocol that could benefit from using BPF too.
[...]
Quoted 16 lines
include/linux/bpf-hid.h line 18
Quoted 11 lines
include/linux/bpf-hid.h new file +11
-0+#include <linux/list.h> +#include <linux/slab.h> + +struct bpf_prog ; +struct bpf_prog_array ; +struct hid_device ; + +enum bpf_hid_attach_type { +BPF_HID_ATTACH_INVALID =-1 , +BPF_HID_ATTACH_DEVICE_EVENT =0 , +MAX_BPF_HID_ATTACH_TYPE Is it typical to have different BPF programs for different attach types? Otherwise, (different types may have similar BPF programs), maybe we can pass type as an argument to the program (shared among different types)?
Not quite sure I am entirely following you, but I consider the various attach types to be quite different and thus you can not really reuse the same BPF program with 2 different attach types.
In my view, we have 4 attach types:
- BPF_HID_ATTACH_DEVICE_EVENT: called whenever we receive an IRQ from the given device (so this is net-like event stream)
- BPF_HID_ATTACH_RDESC_FIXUP: there can be only one of this type, and this is called to change the device capabilities. So you can not reuse the other programs for this one
- BPF_HID_ATTACH_USER_EVENT: called explicitly by the userspace process owning the program. There we can use functions that are sleeping (we are not in IRQ context), so this is also fundamentally different from the 3 others.
- BPF_HID_ATTACH_DRIVER_EVENT: whenever the driver gets called into, we get a bpf program run. This can be suspend/resume, or even specific request to the device (change a feature on the device or get its current state). Again, IMO fundamentally different from the others.
So I'm open to any suggestions, but if we can keep the userspace API being defined with different SEC in libbpf, that would be the best.
Quoted 16 lines
[...]
include/uapi/linux/bpf_hid.h line 31
Quoted 10 lines
include/uapi/linux/bpf_hid.h new file +10
-0+struct hid_device ; + +enum hid_bpf_event { +HID_BPF_UNDEF =0 , +HID_BPF_DEVICE_EVENT ,/* when attach type is BPF_HID_DEVICE_EVENT */ +}; + +struct hid_bpf_ctx { +enum hid_bpf_event type;/* read-only */ +__u16 allocated_size;/* the allocated size of data below (RO) */ There is a (6-byte?) hole here.
Quoted 8 lines
include/uapi/linux/bpf_hid.h line 36
Quoted 5 lines
include/uapi/linux/bpf_hid.h new file +5
-0+struct hid_device *hdev;/* read-only */ + +__u16 size;/* used size in data (RW) */ +__u8 data[];/* data buffer (RW) */ +};Do we really need
hit_bpf_ctxin uapi? Maybe we can just use it from vmlinuxh?
I had a thought at this context today, and I think I am getting to the limit of what I understand.
My first worry is that the way I wrote it there, with a variable data field length is that this is not forward compatible. Unless BTF and CORE are making magic, this will bite me in the long run IMO.
But then, you are talking about not using uapi, and I am starting to
wonder: am I doing the things correctly?
To solve my first issue (and the weird API I had to introduce in the bpf_hid_get/set_data), I came up to the following:
instead of exporting the data directly in the context, I could create a helper bpf_hid_get_data_buf(ctx, const uint size) that returns a RET_PTR_TO_ALLOC_MEM_OR_NULL in the same way bpf_ringbuf_reserve() does.
This way, I can directly access the fields within the bpf program without having to worry about the size.
But now, I am wondering whether the uapi I defined here is correct in the way CORE works.
My goal is to have HID-BPF programs to be CORE compatible, and not have to recompile them depending on the underlying kernel.
I can not understand right now if I need to add some other BTF helpers in the same way the access to struct xdp_md and struct xdp_buff are converted between one and other, or if defining a forward compatible struct hid_bpf_ctx is enough.
As far as I understand, .convert_ctx_access allows to export a stable uapi to the bpf prog users with the verifier doing the conversion between the structs for me. But is this really required for all the BPF programs if we want them to be CORE?
Also, I am starting to wonder if I should not hide fields in the context to the users. The .data field could be a pointer and only accessed through the helper I mentioned above. This would be forward compatible, and also allows to use whatever available memory in the kernel to be forwarded to the BPF program. This way I can skip the memcpy part and work directly with the incoming dma data buffer from the IRQ.
But is it best practice to do such a thing?
Cheers,
Benjamin
Quoted 19 lines
[...]
kernel/bpf/hid.c line 56
Quoted 9 lines
kernel/bpf/hid.c new file +9
-0+ +static bool hid_is_valid_access (int off,int size, +enum bpf_access_type access_type, +const struct bpf_prog *prog, +struct bpf_insn_access_aux *info) +{ +/* everything not in ctx is prohibited */ +if (off <0 || off + size >sizeof (struct hid_bpf_ctx ) +HID_BPF_MIN_BUFFER_SIZE ) +return false;Mabe add the following here to fail unaligned accesses
if (off % size != 0) return false;[...]
Song Liu
reviewerRe: [PATCH bpf-next v2 02/28] bpf: introduce hid program type
Quoted 46 lines · Benjamin Tissoires
Quoted 8 lines · Song Liu
Quoted 2 lines · Benjamin Tissoires
HID is a protocol that could benefit from using BPF too.
[...]
Quoted 16 lines
include/linux/bpf-hid.h line 18
Quoted 11 lines
include/linux/bpf-hid.h new file +11
-0+#include <linux/list.h> +#include <linux/slab.h> + +struct bpf_prog ; +struct bpf_prog_array ; +struct hid_device ; + +enum bpf_hid_attach_type { +BPF_HID_ATTACH_INVALID =-1 , +BPF_HID_ATTACH_DEVICE_EVENT =0 , +MAX_BPF_HID_ATTACH_TYPE Is it typical to have different BPF programs for different attach types? Otherwise, (different types may have similar BPF programs), maybe we can pass type as an argument to the program (shared among different types)?
Not quite sure I am entirely following you, but I consider the various attach types to be quite different and thus you can not really reuse the same BPF program with 2 different attach types.
In my view, we have 4 attach types:
-BPF_HID_ATTACH_DEVICE_EVENT: called whenever we receive an IRQ from the given device (so this is net-like event stream)
-BPF_HID_ATTACH_RDESC_FIXUP: there can be only one of this type, and this is called to change the device capabilities. So you can not reuse the other programs for this one
-BPF_HID_ATTACH_USER_EVENT: called explicitly by the userspace process owning the program. There we can use functions that are sleeping (we are not in IRQ context), so this is also fundamentally different from the 3 others.
-BPF_HID_ATTACH_DRIVER_EVENT: whenever the driver gets called into, we get a bpf program run. This can be suspend/resume, or even specific request to the device (change a feature on the device or get its current state). Again, IMO fundamentally different from the others.
Quoted 2 lines
So I'm open to any suggestions, but if we can keep the userspace API being defined with different SEC in libbpf, that would be the best.
Thanks for this information. Different attach_types sound right for the use case.
Quoted 69 lines
Quoted 17 lines
[...]
include/uapi/linux/bpf_hid.h line 31
Quoted 10 lines
include/uapi/linux/bpf_hid.h new file +10
-0+struct hid_device ; + +enum hid_bpf_event { +HID_BPF_UNDEF =0 , +HID_BPF_DEVICE_EVENT ,/* when attach type is BPF_HID_DEVICE_EVENT */ +}; + +struct hid_bpf_ctx { +enum hid_bpf_event type;/* read-only */ +__u16 allocated_size;/* the allocated size of data below (RO) */ There is a (6-byte?) hole here.
Quoted 8 lines
include/uapi/linux/bpf_hid.h line 36
Quoted 5 lines
include/uapi/linux/bpf_hid.h new file +5
-0+struct hid_device *hdev;/* read-only */ + +__u16 size;/* used size in data (RW) */ +__u8 data[];/* data buffer (RW) */ +};Do we really need
hit_bpf_ctxin uapi? Maybe we can just use it from vmlinuxh?I had a thought at this context today, and I think I am getting to the limit of what I understand.
My first worry is that the way I wrote it there, with a variable data field length is that this is not forward compatible. Unless BTF and CORE are making magic, this will bite me in the long run IMO.
But then, you are talking about not using uapi, and I am starting to
wonder: am I doing the things correctly?To solve my first issue (and the weird API I had to introduce in the bpf_hid_get/set_data), I came up to the following:
instead of exporting the data directly in the context, I could create a helperbpf_hid_get_data_buf(ctx, const uint size)that returns aRET_PTR_TO_ALLOC_MEM_OR_NULLin the same waybpf_ringbuf_reserve()does.This way, I can directly access the fields within the bpf program without having to worry about the size.
But now, I am wondering whether the uapi I defined here is correct in the way CORE works.
My goal is to have HID-BPF programs to be CORE compatible, and not have to recompile them depending on the underlying kernel.
I can not understand right now if I need to add some other BTF helpers in the same way the access to struct
xdp_mdand structxdp_buffare converted between one and other, or if defining a forward compatible structhid_bpf_ctxis enough.
As far as I understand, .convert_ctx_access allows to export a stable uapi to the bpf prog users with the verifier doing the conversion between the structs for me. But is this really required for all the BPF programs if we want them to be CORE?Also, I am starting to wonder if I should not hide fields in the context to the users. The .data field could be a pointer and only accessed through the helper I mentioned above. This would be forward compatible, and also allows to use whatever available memory in the kernel to be forwarded to the BPF program. This way I can skip the memcpy part and work directly with the incoming dma data buffer from the IRQ.
Quoted 1 line
But is it best practice to do such a thing?
I think .convert_ctx_access is the way to go if we want to access the data buffer without memcpy. I am not sure how much work is needed to make it compatible with CORE though.
To make sure I understand the case, do we want something like
bpf_prog(struct hid_bpf_ctx *ctx)
{
/* makes sure n < ctx->size */
x = ctx->data[n]; /* read data */
ctx->data[n] = <something>; /* write data */
ctx->size = <something <= n>; /* change data size */
}We also need it to be CORE, so that we may modify hid_bpf_ctx by inserting more members to it before data.
Is this accurate?
Song
Re: [PATCH bpf-next v2 02/28] bpf: introduce hid program type
Quoted 140 lines · Song Liu
Quoted 46 lines · Benjamin Tissoires
Quoted 8 lines · Song Liu
Quoted 2 lines · Benjamin Tissoires
HID is a protocol that could benefit from using BPF too.
[...]
Quoted 16 lines
include/linux/bpf-hid.h line 18
Quoted 11 lines
include/linux/bpf-hid.h new file +11
-0+#include <linux/list.h> +#include <linux/slab.h> + +struct bpf_prog ; +struct bpf_prog_array ; +struct hid_device ; + +enum bpf_hid_attach_type { +BPF_HID_ATTACH_INVALID =-1 , +BPF_HID_ATTACH_DEVICE_EVENT =0 , +MAX_BPF_HID_ATTACH_TYPE Is it typical to have different BPF programs for different attach types? Otherwise, (different types may have similar BPF programs), maybe we can pass type as an argument to the program (shared among different types)?
Not quite sure I am entirely following you, but I consider the various attach types to be quite different and thus you can not really reuse the same BPF program with 2 different attach types.
In my view, we have 4 attach types:
-BPF_HID_ATTACH_DEVICE_EVENT: called whenever we receive an IRQ from the given device (so this is net-like event stream)
-BPF_HID_ATTACH_RDESC_FIXUP: there can be only one of this type, and this is called to change the device capabilities. So you can not reuse the other programs for this one
-BPF_HID_ATTACH_USER_EVENT: called explicitly by the userspace process owning the program. There we can use functions that are sleeping (we are not in IRQ context), so this is also fundamentally different from the 3 others.
-BPF_HID_ATTACH_DRIVER_EVENT: whenever the driver gets called into, we get a bpf program run. This can be suspend/resume, or even specific request to the device (change a feature on the device or get its current state). Again, IMO fundamentally different from the others.Quoted 2 lines
So I'm open to any suggestions, but if we can keep the userspace API being defined with different SEC in libbpf, that would be the best.
Thanks for this information. Different
attach_typessound right for the use case.Quoted 69 lines
Quoted 17 lines
[...]
include/uapi/linux/bpf_hid.h line 31
Quoted 10 lines
include/uapi/linux/bpf_hid.h new file +10
-0+struct hid_device ; + +enum hid_bpf_event { +HID_BPF_UNDEF =0 , +HID_BPF_DEVICE_EVENT ,/* when attach type is BPF_HID_DEVICE_EVENT */ +}; + +struct hid_bpf_ctx { +enum hid_bpf_event type;/* read-only */ +__u16 allocated_size;/* the allocated size of data below (RO) */ There is a (6-byte?) hole here.
Quoted 8 lines
include/uapi/linux/bpf_hid.h line 36
Quoted 5 lines
include/uapi/linux/bpf_hid.h new file +5
-0+struct hid_device *hdev;/* read-only */ + +__u16 size;/* used size in data (RW) */ +__u8 data[];/* data buffer (RW) */ +};Do we really need
hit_bpf_ctxin uapi? Maybe we can just use it from vmlinuxh?I had a thought at this context today, and I think I am getting to the limit of what I understand.
My first worry is that the way I wrote it there, with a variable data field length is that this is not forward compatible. Unless BTF and CORE are making magic, this will bite me in the long run IMO.
But then, you are talking about not using uapi, and I am starting to
wonder: am I doing the things correctly?To solve my first issue (and the weird API I had to introduce in the bpf_hid_get/set_data), I came up to the following:
instead of exporting the data directly in the context, I could create a helperbpf_hid_get_data_buf(ctx, const uint size)that returns aRET_PTR_TO_ALLOC_MEM_OR_NULLin the same waybpf_ringbuf_reserve()does.This way, I can directly access the fields within the bpf program without having to worry about the size.
But now, I am wondering whether the uapi I defined here is correct in the way CORE works.
My goal is to have HID-BPF programs to be CORE compatible, and not have to recompile them depending on the underlying kernel.
I can not understand right now if I need to add some other BTF helpers in the same way the access to struct
xdp_mdand structxdp_buffare converted between one and other, or if defining a forward compatible structhid_bpf_ctxis enough.
As far as I understand, .convert_ctx_access allows to export a stable uapi to the bpf prog users with the verifier doing the conversion between the structs for me. But is this really required for all the BPF programs if we want them to be CORE?Also, I am starting to wonder if I should not hide fields in the context to the users. The .data field could be a pointer and only accessed through the helper I mentioned above. This would be forward compatible, and also allows to use whatever available memory in the kernel to be forwarded to the BPF program. This way I can skip the memcpy part and work directly with the incoming dma data buffer from the IRQ.
Quoted 1 line
But is it best practice to do such a thing?
I think .convert_ctx_access is the way to go if we want to access the data buffer without memcpy. I am not sure how much work is needed to make it compatible with CORE though.
To make sure I understand the case, do we want something like
bpf_prog(struct hid_bpf_ctx *ctx){ /* makes sure n < ctx->size */ x = ctx->data[n]; /* read data */ ctx->data[n] = <something>; /* write data */ ctx->size = <something <= n>; /* change data size */ }
Quoted 5 lines
We also need it to be CORE, so that we may modify
hid_bpf_ctxby inserting more members to it before data.Is this accurate?
Yes, you pretty much summed it all (except maybe that we might want to have allocated_size in addition to size so we can also grow the value of .size within the allocated limit).
All in all, what I want for HID bpf programs is to be able to read and write an array of bytes, and change its size within an allocated kernel limit.
This will apply to every HID bpf attach type, to the exception of some BPF_HID_ATTACH_DRIVER_EVENT when we are receiving a suspend/resume notification. Though in the suspend/resume case we won't have the data array available, so it won't matter much.
I want the HID bpf programs to be CORE, but if you tell me that it would matter only if we need to reshuffle hid_bpf_ctx, I would be fine simply put a comment "new fields must be added at the end" like some other definitions of contexts are doing.
Besides that, I currently do not want to allow access to the content of struct hid_device (or any other kernel struct) in HID BPF programs. That might be of interest at some point for debugging, but with just the array capability I should be able to achieve all of my use cases.
Cheers,
Benjamin
Re: [PATCH bpf-next v2 02/28] bpf: introduce hid program type
Quoted 11 lines · Benjamin Tissoires
Quoted 9 lines · Song Liu
Quoted 6 lines · Benjamin Tissoires
Quoted 4 lines · Song Liu
Quoted 1 line · Benjamin Tissoires
[...]
Quoted 58 lines
Quoted 58 lines
Quoted 58 lines
Quoted 6 lines
include/uapi/linux/bpf_hid.h line 31
Quoted 3 lines
include/uapi/linux/bpf_hid.h new file +3
-0+struct hid_bpf_ctx { +enum hid_bpf_event type;/* read-only */ +__u16 allocated_size;/* the allocated size of data below (RO) */ There is a (6-byte?) hole here.
Quoted 8 lines
include/uapi/linux/bpf_hid.h line 36
Quoted 5 lines
include/uapi/linux/bpf_hid.h new file +5
-0+struct hid_device *hdev;/* read-only */ + +__u16 size;/* used size in data (RW) */ +__u8 data[];/* data buffer (RW) */ +};Do we really need
hit_bpf_ctxin uapi? Maybe we can just use it from vmlinuxh?I had a thought at this context today, and I think I am getting to the limit of what I understand.
My first worry is that the way I wrote it there, with a variable data field length is that this is not forward compatible. Unless BTF and CORE are making magic, this will bite me in the long run IMO.
But then, you are talking about not using uapi, and I am starting to
wonder: am I doing the things correctly?To solve my first issue (and the weird API I had to introduce in the bpf_hid_get/set_data), I came up to the following:
instead of exporting the data directly in the context, I could create a helperbpf_hid_get_data_buf(ctx, const uint size)that returns aRET_PTR_TO_ALLOC_MEM_OR_NULLin the same waybpf_ringbuf_reserve()does.This way, I can directly access the fields within the bpf program without having to worry about the size.
But now, I am wondering whether the uapi I defined here is correct in the way CORE works.
My goal is to have HID-BPF programs to be CORE compatible, and not have to recompile them depending on the underlying kernel.
I can not understand right now if I need to add some other BTF helpers in the same way the access to struct
xdp_mdand structxdp_buffare converted between one and other, or if defining a forward compatible structhid_bpf_ctxis enough.
As far as I understand, .convert_ctx_access allows to export a stable uapi to the bpf prog users with the verifier doing the conversion between the structs for me. But is this really required for all the BPF programs if we want them to be CORE?Also, I am starting to wonder if I should not hide fields in the context to the users. The .data field could be a pointer and only accessed through the helper I mentioned above. This would be forward compatible, and also allows to use whatever available memory in the kernel to be forwarded to the BPF program. This way I can skip the memcpy part and work directly with the incoming dma data buffer from the IRQ.
Quoted 5 lines
Quoted 5 lines
Quoted 1 line
But is it best practice to do such a thing?
I think .convert_ctx_access is the way to go if we want to access the data buffer without memcpy. I am not sure how much work is needed to make it compatible with CORE though.
I spent the week working on that, and I am really amazed at how smart and simple the .convert_ctx_access is working.
With that in place, I can hide the internal fields and export "virtual" public fields that are remapped on the fly by the kernel at load time :)
Quoted 11 lines
Quoted 11 lines
To make sure I understand the case, do we want something like
bpf_prog(struct hid_bpf_ctx *ctx){ /* makes sure n < ctx->size */ x = ctx->data[n]; /* read data */ ctx->data[n] = <something>; /* write data */ ctx->size = <something <= n>; /* change data size */ }
Quoted 5 lines
Quoted 5 lines
We also need it to be CORE, so that we may modify
hid_bpf_ctxby inserting more members to it before data.Is this accurate?
I have been trying to implement that, based on the PTR_TO_PACKET implementation. It works, but is kind of verbose while using it because we need to teach the verifier about the size of the arrays.
For instance, I have the following:
int bpf_prog(struct hid_bpf_ctx *ctx)
{
/* we need to store a pointer on the stack to store its accessible size */ __u8 *data = ctx->data;
if (data + 3 > ctx->data_end)
return 0; /* EPERM, bounds check */
data[1] = data[0] + 3;
return 0;
}
This is OK, but it gets worse if I want to access a random offset:
__s64 offset = 0;
int bpf_prog(struct hid_bpf_ctx *ctx)
{
__u8 *data = ctx->data;
__u16 *x;
/* first assign the size of data */
if (data + 4 > ctx->data_end)
return 0; /* EPERM, bounds check */
/* teach the verifier the range of offset (needs to be a s64) */
if (offset >= 0 && offset < 2) {
x = (__u16 *)&data[offset]; /* now store the size of x in its register */
if (x + 2 > ctx->data_end)
return 0;
/* finally we can read/write the data */
*x += 1;}
return 0;
}
OTOH, I managed to define a simpler helper that allows me to return a pointer to the internal data:
BPF_CALL_3(bpf_hid_get_data, struct hid_bpf_ctx_kern*, ctx, u64, offset, u64, size)
{
if (!size)
return (unsigned long)0;
if (offset + size > ctx->data_end - ctx->data)
return (unsigned long)0;
return (unsigned long)(ctx->data + offset);}
static const struct bpf_func_proto bpf_hid_get_data_proto = {
.func = bpf_hid_get_data,
.gpl_only = true,
.ret_type = RET_PTR_TO_ALLOC_MEM_OR_NULL,
.arg1_type = ARG_PTR_TO_CTX,
.arg2_type = ARG_ANYTHING,
.arg3_type = ARG_CONST_ALLOC_SIZE_OR_ZERO,
};Which makes the previous bpf code into:
__u64 offset = 0;
int bpf_prog(struct hid_bpf_ctx *ctx)
{
__u16 *x = bpf_hid_get_data(ctx, offset, 2);
if (!x)
return 0; /* EPERM, bounds check */
*x += 1;
return 0;
}
The advantage of both of those solutions is that they are removing the need for bpf_hid_{get|set}_bytes().
The second solution is much simpler in terms of usage, but it doesn't feel "right" to have to reimplement the wheel when we should have direct array accesses.
OTOH, the first solution with the packet implementation is bulky and requiring users to do that for every single access of the data is IMO way too much...
Any thoughts?
Cheers,
Benjamin
Song Liu
reviewerRe: [PATCH bpf-next v2 02/28] bpf: introduce hid program type
In reply to Benjamin TissoiresQuoted 1 line · Benjamin Tissoires
[...]
include/linux/bpf-hid.h line 91
Quoted 12 lines
include/linux/bpf-hid.h new file +12
-0+#endif + +static inline bool bpf_hid_link_empty (struct bpf_hid *bpf, +enum bpf_hid_attach_type type) +{ +return list_empty (&bpf->links[type]); +} + +struct bpf_hid_hooks { +struct hid_device *(*hdev_from_fd)(int fd); +int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type); +void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type);
shall we call this array_detach()? detached sounds like a function that checks the status of link/hook.
[...]
kernel/bpf/hid.c line 4
Quoted 7 lines
kernel/bpf/hid.c new file +4
-0@@ -0,0 +1,437 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* based on kernel/bpf/net-namespace.c +*/
I guess we don't need this comment.
Quoted 6 lines
kernel/bpf/hid.c new file +6
-0+ +#include <linux/bpf.h> +#include <linux/bpf-hid.h> +#include <linux/filter.h> +#include <linux/hid.h> +#include <linux/hidraw.h>
[...]
PATCH v2 3/28 HID: hook up with bpf
In reply to Benjamin TissoiresNow that BPF can be compatible with HID, add the capability into HID. drivers/hid/hid-bpf.c takes care of the glue between bpf and HID, and hid-core can then inject any incoming event from the device into a BPF program to filter/analyze it.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
- addressed review comments from v1
--- drivers/hid/Makefile | 1 + drivers/hid/hid-bpf.c | 157 +++++++++++++++++++++++++++++++++++++++++ drivers/hid/hid-core.c | 21 +++++- include/linux/hid.h | 11 +++ 4 files changed, 187 insertions(+), 3 deletions(-) create mode 100644 drivers/hid/hid-bpf.c
drivers/hid/Makefile +1 -0
@@ -4,6 +4,7 @@ # hid-y := hid-core.o hid-input.o hid-quirks.o hid-$(CONFIG_DEBUG_FS) += hid-debug.o +hid-$(CONFIG_BPF) += hid-bpf.o obj-$(CONFIG_HID) += hid.o obj-$(CONFIG_UHID) += uhid.o
drivers/hid/hid-bpf.c new file +157 -0
157 lines not on this page · raw message
drivers/hid/hid-core.c +18 -3
@@ -1748,13 +1748,21 @@ int hid_report_raw_event(struct hid_device *hid, int type, u8 *data, u32 size,struct hid_driver *hdrv;unsigned int a;u32 rsize, csize = size; -u8 *cdata = data; +u8 *cdata;int ret =0 ; + data =hid_bpf_raw_event (hid, data, &size); +if (IS_ERR (data)) { + ret =PTR_ERR (data); + goto out; + } + report =hid_get_report (report_enum, data);if (!report) goto out; + cdata = data; +if (report_enum->numbered) { cdata++; csize--;
@@ -2528,10 +2536,12 @@ int hid_add_device(struct hid_device *hdev)hid_debug_register (hdev,dev_name (&hdev->dev)); ret =device_add (&hdev->dev); -if (!ret) +if (!ret) { hdev->status |=HID_STAT_ADDED ; -else + }else {hid_debug_unregister (hdev); +bpf_hid_exit (hdev); + }return ret; }
@@ -2567,6 +2577,7 @@ struct hid_device *hid_allocate_device(void)spin_lock_init (&hdev->debug_list_lock);sema_init (&hdev->driver_input_lock,1 );mutex_init (&hdev->ll_open_lock); +bpf_hid_init (hdev);return hdev; }
@@ -2574,6 +2585,7 @@ EXPORT_SYMBOL_GPL(hid_allocate_device);static void hid_remove_device (struct hid_device *hdev) { +bpf_hid_exit (hdev);if (hdev->status &HID_STAT_ADDED ) {device_del (&hdev->dev);hid_debug_unregister (hdev);
@@ -2700,6 +2712,8 @@ static int __init hid_init(void)hid_debug_init (); +hid_bpf_module_init (); +return 0 ; err_bus:bus_unregister (&hid_bus_type);
@@ -2709,6 +2723,7 @@ static int __init hid_init(void) static void __exit hid_exit(void) { +hid_bpf_module_exit ();hid_debug_exit ();hidraw_exit ();bus_unregister (&hid_bus_type);
include/linux/hid.h +11 -0
@@ -27,6 +27,7 @@#include <linux/mutex.h> #include <linux/power_supply.h> #include <uapi/linux/hid.h> +#include <uapi/linux/bpf_hid.h> /* * We parse each description item into this structure. Short items data
@@ -1210,4 +1211,14 @@ do { \#define hid_dbg_once (hid, fmt, ...) \ dev_dbg_once(&(hid)->dev, fmt, ##__VA_ARGS__) +#ifdef CONFIG_BPF +u8 *hid_bpf_raw_event (struct hid_device *hdev,u8 *rd,int *size); +int hid_bpf_module_init (void ); +void hid_bpf_module_exit (void ); +#else +static inline u8 *hid_bpf_raw_event (struct hid_device *hdev,u8 *rd,int *size) {return rd; } +static inline int hid_bpf_module_init (void ) {return 0 ; } +static inline void hid_bpf_module_exit (void ) {} +#endif +#endif
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 03/28] HID: hook up with bpf
Quoted 7 lines · Benjamin Tissoires
Now that BPF can be compatible with HID, add the capability into HID.
drivers/hid/hid-bpf.ctakes care of the glue between bpf and HID, and hid-core can then inject any incoming event from the device into a BPF program to filter/analyze it.Signed-off-by Benjamin Tissoires <[email protected]>
Song Liu
reviewerRe: [PATCH bpf-next v2 03/28] HID: hook up with bpf
In reply to Benjamin TissoiresQuoted 8 lines · Benjamin Tissoires
Now that BPF can be compatible with HID, add the capability into HID.
drivers/hid/hid-bpf.ctakes care of the glue between bpf and HID, and hid-core can then inject any incoming event from the device into a BPF program to filter/analyze it.Signed-off-by Benjamin Tissoires <[email protected]>
[...]
Quoted 7 lines
drivers/hid/hid-bpf.c new file +7
-0+ +static int hid_bpf_link_attach (struct hid_device *hdev,enum bpf_hid_attach_type type) +{ +int err =0 ; + +switch (type) { +case BPF_HID_ATTACH_DEVICE_EVENT :
drivers/hid/hid-bpf.c line 68
Quoted 10 lines
drivers/hid/hid-bpf.c new file +10
-0+if (!hdev->bpf.ctx) { + hdev->bpf.ctx =bpf_hid_allocate_ctx (hdev,HID_BPF_MAX_BUFFER_SIZE ); +if (IS_ERR (hdev->bpf.ctx)) { + err =PTR_ERR (hdev->bpf.ctx); + hdev->bpf.ctx =NULL ; + } + } +break ; +default : +/* do nothing */
Do we need to show warning and/or return EINVAL here?
Quoted 4 lines
drivers/hid/hid-bpf.c new file +4
-0+ } + +return err; +}
drivers/hid/hid-bpf.c line 82
Quoted 10 lines
drivers/hid/hid-bpf.c new file +10
-0+ +static void hid_bpf_array_detached (struct hid_device *hdev,enum bpf_hid_attach_type type) +{ +switch (type) { +case BPF_HID_ATTACH_DEVICE_EVENT : +kfree (hdev->bpf.ctx); + hdev->bpf.ctx =NULL ; +break ; +default : +/* do nothing */
ditto
[...]
Re: [PATCH bpf-next v2 03/28] HID: hook up with bpf
In reply to Benjamin TissoiresHi Benjamin,
Quoted 96 lines · Benjamin Tissoires
Now that BPF can be compatible with HID, add the capability into HID.
drivers/hid/hid-bpf.ctakes care of the glue between bpf and HID, and hid-core can then inject any incoming event from the device into a BPF program to filter/analyze it.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
- addressed review comments from v1--- drivers/hid/Makefile | 1 + drivers/hid/hid-bpf.c | 157 +++++++++++++++++++++++++++++++++++++++++ drivers/hid/hid-core.c | 21 +++++- include/linux/hid.h | 11 +++ 4 files changed, 187 insertions(+), 3 deletions(-)create mode 100644
drivers/hid/hid-bpf.cdrivers/hid/Makefile +1
-0@@ -4,6 +4,7 @@ # hid-y := hid-core.o hid-input.o hid-quirks.o hid-$(CONFIG_DEBUG_FS) += hid-debug.o +hid-$(CONFIG_BPF) += hid-bpf.o obj-$(CONFIG_HID) += hid.o obj-$(CONFIG_UHID) += uhid.odrivers/hid/hid-bpf.c new file +58
-0@@ -0,0 +1,157 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* BPF in HID support for Linux +* +* Copyright (c) 2022 Benjamin Tissoires +*/ + +#include <linux/filter.h> +#include <linux/mutex.h> +#include <linux/slab.h> + +#include <uapi/linux/bpf_hid.h> +#include <linux/hid.h> + +static int __hid_bpf_match_sysfs (struct device *dev,const void *data) +{ +struct kernfs_node *kn = dev->kobj.sd; +struct kernfs_node *uevent_kn; + + uevent_kn =kernfs_find_and_get_ns (kn,"uevent" ,NULL ); + +return uevent_kn == data; +} + +static struct hid_device *hid_bpf_fd_to_hdev (int fd) +{ +struct device *dev; +struct hid_device *hdev; +struct fd f =fdget (fd); +struct inode *inode; +struct kernfs_node *node; + +if (!f.file) { + hdev =ERR_PTR (-EBADF ); + goto out; + } + + inode =file_inode (f.file); + node = inode->i_private; + + dev =bus_find_device (&hid_bus_type,NULL , node, __hid_bpf_match_sysfs); + +if (dev) + hdev =to_hid_device (dev); +else + hdev =ERR_PTR (-EINVAL ); + + out: +fdput (f); +return hdev; +} + +static int hid_bpf_link_attach (struct hid_device *hdev,enum bpf_hid_attach_type type) +{ +int err =0 ; + +switch (type) { +case BPF_HID_ATTACH_DEVICE_EVENT :
drivers/hid/hid-bpf.c line 68
Quoted 10 lines
drivers/hid/hid-bpf.c new file +10
-0+if (!hdev->bpf.ctx) { + hdev->bpf.ctx =bpf_hid_allocate_ctx (hdev,HID_BPF_MAX_BUFFER_SIZE ); +if (IS_ERR (hdev->bpf.ctx)) { + err =PTR_ERR (hdev->bpf.ctx); + hdev->bpf.ctx =NULL ; + } + } +break ; +default : +/* do nothing */
These cause following error:
CC drivers/hid/hid-bpf.odrivers/hid/hid-bpf.c: In function ‘hid_bpf_link_attach’:drivers/hid/hid-bpf.c:88:2: error: label at end of compound statement 88 | default:
| ^~~~~~~drivers/hid/hid-bpf.c: In function ‘hid_bpf_link_attached’:drivers/hid/hid-bpf.c:101:2: error: label at end of compound statement 101 | default:
| ^~~~~~~drivers/hid/hid-bpf.c: In function ‘hid_bpf_array_detached’:drivers/hid/hid-bpf.c:116:2: error: label at end of compound statement 116 | default:
| ^~~~~~~
make[2]: *** [scripts/Makefile.build:288: drivers/hid/hid-bpf.o] Error 1 make[1]: *** [scripts/Makefile.build:550: drivers/hid] Error 2 make[1]: *** Waiting for unfinished jobs....
make: *** [Makefile:1831: drivers] Error 2
To fix that, you need to add a break statement at end:
default:
/* do nothing */
break;
Same for couple of other occurrences in the file.
-Tero
PATCH v2 4/28 libbpf: add HID program type and API
In reply to Benjamin TissoiresHID-bpf program type are needing a new SEC.
To bind a hid-bpf program, we can rely on bpf_program__attach_fd() so export a new function to the API.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- tools/lib/bpf/libbpf.c | 7 +++++++ tools/lib/bpf/libbpf.h | 2 ++ tools/lib/bpf/libbpf.map | 1 + 3 files changed, 10 insertions(+)
tools/lib/bpf/libbpf.c +7 -0
@@ -8680,6 +8680,7 @@ static const struct bpf_sec_def section_defs[] = {SEC_DEF ("cgroup/setsockopt" ,CGROUP_SOCKOPT ,BPF_CGROUP_SETSOCKOPT ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ),SEC_DEF ("struct_ops+" ,STRUCT_OPS ,0 ,SEC_NONE ),SEC_DEF ("sk_lookup" ,SK_LOOKUP ,BPF_SK_LOOKUP ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ), + SEC_DEF("hid/device_event", HID, BPF_HID_DEVICE_EVENT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), };#define MAX_TYPE_NAME_SIZE 32
@@ -10659,6 +10660,12 @@ static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)return bpf_program__attach_iter (prog,NULL ); } +struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd) +{ +return bpf_program__attach_fd (prog, hid_fd,0 ,"hid" ); +} +struct bpf_link *bpf_program__attach (const struct bpf_program *prog) {if (!prog->sec_def || !prog->sec_def->attach_fn)
tools/lib/bpf/libbpf.h +2 -0
@@ -529,6 +529,8 @@ struct bpf_iter_attach_opts { LIBBPF_API struct bpf_link *bpf_program__attach_iter (const struct bpf_program *prog,const struct bpf_iter_attach_opts *opts); +LIBBPF_API struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd);/* * Libbpf allows callers to adjust BPF programs before being loaded
tools/lib/bpf/libbpf.map +1 -0
@@ -424,6 +424,7 @@ LIBBPF_0.6.0 { LIBBPF_0.7.0 { global: bpf_btf_load; + bpf_program__attach_hid; bpf_program__expected_attach_type; bpf_program__log_buf; bpf_program__log_level;
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 04/28] libbpf: add HID program type and API
Quoted 6 lines · Benjamin Tissoires
HID-bpf program type are needing a new SEC.
To bind a hid-bpf program, we can rely onbpf_program__attach_fd()so export a new function to the API.Signed-off-by Benjamin Tissoires <[email protected]>
Quoted 64 lines
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples--- tools/lib/bpf/libbpf.c | 7 +++++++ tools/lib/bpf/libbpf.h | 2 ++ tools/lib/bpf/libbpf.map | 1 + 3 files changed, 10 insertions(+)tools/lib/bpf/libbpf.c +7
-0@@ -8680,6 +8680,7 @@ static const struct bpf_sec_def section_defs[] = {SEC_DEF ("cgroup/setsockopt" ,CGROUP_SOCKOPT ,BPF_CGROUP_SETSOCKOPT ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ),SEC_DEF ("struct_ops+" ,STRUCT_OPS ,0 ,SEC_NONE ),SEC_DEF ("sk_lookup" ,SK_LOOKUP ,BPF_SK_LOOKUP ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ), + SEC_DEF("hid/device_event", HID, BPF_HID_DEVICE_EVENT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), };#define MAX_TYPE_NAME_SIZE 32@@ -10659,6 +10660,12 @@ static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)return bpf_program__attach_iter (prog,NULL ); } +struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd) +{ +return bpf_program__attach_fd (prog, hid_fd,0 ,"hid" ); +} +struct bpf_link *bpf_program__attach (const struct bpf_program *prog) {if (!prog->sec_def || !prog->sec_def->attach_fn)tools/lib/bpf/libbpf.h +2
-0@@ -529,6 +529,8 @@ struct bpf_iter_attach_opts { LIBBPF_API struct bpf_link *bpf_program__attach_iter (const struct bpf_program *prog,const struct bpf_iter_attach_opts *opts); +LIBBPF_API struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd);/* * Libbpf allows callers to adjust BPF programs before being loaded tools/lib/bpf/libbpf.map +1
-1@@ -424,6 +424,7 @@ LIBBPF_0.6.0 { LIBBPF_0.7.0 { global: bpf_btf_load; + bpf_program__attach_hid; bpf_program__expected_attach_type; bpf_program__log_buf; bpf_program__log_level; --2.35.1
Re: [PATCH bpf-next v2 04/28] libbpf: add HID program type and API
In reply to Benjamin TissoiresQuoted 22 lines · Benjamin Tissoires
HID-bpf program type are needing a new SEC.
To bind a hid-bpf program, we can rely onbpf_program__attach_fd()so export a new function to the API.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples--- tools/lib/bpf/libbpf.c | 7 +++++++ tools/lib/bpf/libbpf.h | 2 ++ tools/lib/bpf/libbpf.map | 1 + 3 files changed, 10 insertions(+)tools/lib/bpf/libbpf.c +0
-0
tools/lib/bpf/libbpf.c static const struct bpf_sec_def section_defs[] = { · line 8683
Quoted 4 lines
tools/lib/bpf/libbpf.c +1
-0@@ -8680,6 +8680,7 @@ static const struct bpf_sec_def section_defs[] = {SEC_DEF ("cgroup/setsockopt" ,CGROUP_SOCKOPT ,BPF_CGROUP_SETSOCKOPT ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ),SEC_DEF ("struct_ops+" ,STRUCT_OPS ,0 ,SEC_NONE ),SEC_DEF ("sk_lookup" ,SK_LOOKUP ,BPF_SK_LOOKUP ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ), + SEC_DEF("hid/device_event", HID, BPF_HID_DEVICE_EVENT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
no SEC_SLOPPY_PFX for any new program type, please
Quoted 34 lines
tools/lib/bpf/libbpf.c +6
-0};#define MAX_TYPE_NAME_SIZE 32@@ -10659,6 +10660,12 @@ static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)return bpf_program__attach_iter (prog,NULL ); } +struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd) +{ +return bpf_program__attach_fd (prog, hid_fd,0 ,"hid" ); +} +struct bpf_link *bpf_program__attach (const struct bpf_program *prog) {if (!prog->sec_def || !prog->sec_def->attach_fn)tools/lib/bpf/libbpf.h +2
-0@@ -529,6 +529,8 @@ struct bpf_iter_attach_opts { LIBBPF_API struct bpf_link *bpf_program__attach_iter (const struct bpf_program *prog,const struct bpf_iter_attach_opts *opts); +LIBBPF_API struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd);/* * Libbpf allows callers to adjust BPF programs before being loaded tools/lib/bpf/libbpf.map +0
-0
tools/lib/bpf/libbpf.map LIBBPF_0.6.0 { · line 427
Quoted 4 lines
tools/lib/bpf/libbpf.map +1
-0@@ -424,6 +424,7 @@ LIBBPF_0.6.0 { LIBBPF_0.7.0 { global: bpf_btf_load; + bpf_program__attach_hid;
should go into 0.8.0
Quoted 6 lines
tools/lib/bpf/libbpf.map +0
-1bpf_program__expected_attach_type; bpf_program__log_buf; bpf_program__log_level; --2.35.1
Re: [PATCH bpf-next v2 04/28] libbpf: add HID program type and API
Quoted 63 lines · Andrii Nakryiko
Quoted 22 lines · Benjamin Tissoires
HID-bpf program type are needing a new SEC.
To bind a hid-bpf program, we can rely onbpf_program__attach_fd()so export a new function to the API.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
---tools/lib/bpf/libbpf.c | 7 +++++++ tools/lib/bpf/libbpf.h | 2 ++ tools/lib/bpf/libbpf.map | 1 + 3 files changed, 10 insertions(+)tools/lib/bpf/libbpf.c +0
-0tools/lib/bpf/libbpf.c static const struct bpf_sec_def section_defs[] = { · line 8683
Quoted 4 lines
tools/lib/bpf/libbpf.c +1
-0@@ -8680,6 +8680,7 @@ static const struct bpf_sec_def section_defs[] = {SEC_DEF ("cgroup/setsockopt" ,CGROUP_SOCKOPT ,BPF_CGROUP_SETSOCKOPT ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ),SEC_DEF ("struct_ops+" ,STRUCT_OPS ,0 ,SEC_NONE ),SEC_DEF ("sk_lookup" ,SK_LOOKUP ,BPF_SK_LOOKUP ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ), + SEC_DEF("hid/device_event", HID, BPF_HID_DEVICE_EVENT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),no
SEC_SLOPPY_PFXfor any new program type, pleaseQuoted 27 lines
tools/lib/bpf/libbpf.c +6
-0};#define MAX_TYPE_NAME_SIZE 32@@ -10659,6 +10660,12 @@ static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)return bpf_program__attach_iter (prog,NULL ); } +struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd) +{ +return bpf_program__attach_fd (prog, hid_fd,0 ,"hid" ); +} +struct bpf_link *bpf_program__attach (const struct bpf_program *prog) {if (!prog->sec_def || !prog->sec_def->attach_fn)tools/lib/bpf/libbpf.h +0
-0@@ -529,6 +529,8 @@ struct bpf_iter_attach_opts {
LIBBPF_APIstructbpf_link* bpf_program__attach_iter(const structbpf_program*prog,const struct bpf_iter_attach_opts *opts);tools/lib/bpf/libbpf.h +2
-0+LIBBPF_API struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd);
Quoted 13 lines
tools/lib/bpf/libbpf.map LIBBPF_0.6.0 { · line 427
Quoted 11 lines
/*
* Libbpf allows callers to adjust BPF programs before being loadedtools/lib/bpf/libbpf.map +1
-0@@ -424,6 +424,7 @@ LIBBPF_0.6.0 { LIBBPF_0.7.0 { global: bpf_btf_load; + bpf_program__attach_hid;should go into 0.8.0
Ah, I missed this one.
btw, bpf_xdp_attach and buddies should also go into 0.8.0, no?
Quoted 7 lines
Quoted 7 lines
tools/lib/bpf/libbpf.map +0
-1bpf_program__expected_attach_type; bpf_program__log_buf; bpf_program__log_level; --2.35.1
Re: [PATCH bpf-next v2 04/28] libbpf: add HID program type and API
Quoted 78 lines · Song Liu
Quoted 64 lines · Andrii Nakryiko
Quoted 22 lines · Benjamin Tissoires
HID-bpf program type are needing a new SEC.
To bind a hid-bpf program, we can rely onbpf_program__attach_fd()so export a new function to the API.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
---tools/lib/bpf/libbpf.c | 7 +++++++ tools/lib/bpf/libbpf.h | 2 ++ tools/lib/bpf/libbpf.map | 1 + 3 files changed, 10 insertions(+)tools/lib/bpf/libbpf.c +0
-0tools/lib/bpf/libbpf.c static const struct bpf_sec_def section_defs[] = { · line 8683
Quoted 4 lines
tools/lib/bpf/libbpf.c +1
-0@@ -8680,6 +8680,7 @@ static const struct bpf_sec_def section_defs[] = {SEC_DEF ("cgroup/setsockopt" ,CGROUP_SOCKOPT ,BPF_CGROUP_SETSOCKOPT ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ),SEC_DEF ("struct_ops+" ,STRUCT_OPS ,0 ,SEC_NONE ),SEC_DEF ("sk_lookup" ,SK_LOOKUP ,BPF_SK_LOOKUP ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ), + SEC_DEF("hid/device_event", HID, BPF_HID_DEVICE_EVENT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),no
SEC_SLOPPY_PFXfor any new program type, pleaseQuoted 27 lines
tools/lib/bpf/libbpf.c +6
-0};#define MAX_TYPE_NAME_SIZE 32@@ -10659,6 +10660,12 @@ static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)return bpf_program__attach_iter (prog,NULL ); } +struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd) +{ +return bpf_program__attach_fd (prog, hid_fd,0 ,"hid" ); +} +struct bpf_link *bpf_program__attach (const struct bpf_program *prog) {if (!prog->sec_def || !prog->sec_def->attach_fn)tools/lib/bpf/libbpf.h +0
-0@@ -529,6 +529,8 @@ struct bpf_iter_attach_opts {
LIBBPF_APIstructbpf_link* bpf_program__attach_iter(const structbpf_program*prog,const struct bpf_iter_attach_opts *opts);tools/lib/bpf/libbpf.h +2
-0+LIBBPF_API struct bpf_link * +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd);Quoted 13 lines
tools/lib/bpf/libbpf.map LIBBPF_0.6.0 { · line 427
Quoted 11 lines
/*
* Libbpf allows callers to adjust BPF programs before being loadedtools/lib/bpf/libbpf.map +1
-0@@ -424,6 +424,7 @@ LIBBPF_0.6.0 { LIBBPF_0.7.0 { global: bpf_btf_load; + bpf_program__attach_hid;should go into 0.8.0
Quoted 3 lines
Ah, I missed this one.
btw,
bpf_xdp_attachand buddies should also go into 0.8.0, no?
not really, they were released in libbpf v0.7, it's just any new incoming API that should go into 0.8.0
Quoted 9 lines
Quoted 8 lines
Quoted 8 lines
tools/lib/bpf/libbpf.map +0
-1bpf_program__expected_attach_type; bpf_program__log_buf; bpf_program__log_level; --2.35.1
PATCH v2 5/28 selftests/bpf: add tests for the HID-bpf initial implementation
In reply to Benjamin TissoiresThe test is pretty basic:
- create a virtual uhid device that no userspace will like (to not mess up the running system)
- attach a BPF prog to it
- open the matching hidraw node
- inject one event and check:
* that the BPF program can do something on the event stream
* can modify the event stream
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- tools/testing/selftests/bpf/prog_tests/hid.c | 335 +++++++++++++++++++ tools/testing/selftests/bpf/progs/hid.c | 20 ++ 2 files changed, 355 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/hid.c create mode 100644 tools/testing/selftests/bpf/progs/hid.c
tools/testing/selftests/bpf/prog_tests/hid.c new file +335 -0
@@ -0,0 +1,335 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2022 Red Hat */ +#include <test_progs.h> +#include <testing_helpers.h> +#include "hid.skel.h" + +#include <fcntl.h> +#include <fnmatch.h> +#include <dirent.h> +#include <poll.h> +#include <stdbool.h> +#include <linux/uhid.h> + +static unsigned char rdesc[] = { +0x06 ,0x00 ,0xff ,/* Usage Page (Vendor Defined Page 1) */ +0x09 ,0x21 ,/* Usage (Vendor Usage 0x21) */ +0xa1 ,0x01 ,/* COLLECTION (Application) */ +0x09 ,0x01 ,/* Usage (Vendor Usage 0x01) */ +0xa1 ,0x00 ,/* COLLECTION (Physical) */ +0x85 ,0x01 ,/* REPORT_ID (1) */ +0x06 ,0x00 ,0xff ,/* Usage Page (Vendor Defined Page 1) */ +0x19 ,0x01 ,/* USAGE_MINIMUM (1) */ +0x29 ,0x03 ,/* USAGE_MAXIMUM (3) */ +0x15 ,0x00 ,/* LOGICAL_MINIMUM (0) */ +0x25 ,0x01 ,/* LOGICAL_MAXIMUM (1) */ +0x95 ,0x03 ,/* REPORT_COUNT (3) */ +0x75 ,0x01 ,/* REPORT_SIZE (1) */ +0x81 ,0x02 ,/* INPUT (Data,Var,Abs) */ +0x95 ,0x01 ,/* REPORT_COUNT (1) */ +0x75 ,0x05 ,/* REPORT_SIZE (5) */ +0x81 ,0x01 ,/* INPUT (Cnst,Var,Abs) */ +0x05 ,0x01 ,/* USAGE_PAGE (Generic Desktop) */ +0x09 ,0x30 ,/* USAGE (X) */ +0x09 ,0x31 ,/* USAGE (Y) */ +0x15 ,0x81 ,/* LOGICAL_MINIMUM (-127) */ +0x25 ,0x7f ,/* LOGICAL_MAXIMUM (127) */ +0x75 ,0x10 ,/* REPORT_SIZE (16) */ +0x95 ,0x02 ,/* REPORT_COUNT (2) */ +0x81 ,0x06 ,/* INPUT (Data,Var,Rel) */ + +0x06 ,0x00 ,0xff ,/* Usage Page (Vendor Defined Page 1) */ +0x19 ,0x01 ,/* USAGE_MINIMUM (1) */ +0x29 ,0x03 ,/* USAGE_MAXIMUM (3) */ +0x15 ,0x00 ,/* LOGICAL_MINIMUM (0) */ +0x25 ,0x01 ,/* LOGICAL_MAXIMUM (1) */ +0x95 ,0x03 ,/* REPORT_COUNT (3) */ +0x75 ,0x01 ,/* REPORT_SIZE (1) */ +0x91 ,0x02 ,/* Output (Data,Var,Abs) */ +0x95 ,0x01 ,/* REPORT_COUNT (1) */ +0x75 ,0x05 ,/* REPORT_SIZE (5) */ +0x91 ,0x01 ,/* Output (Cnst,Var,Abs) */ + +0x06 ,0x00 ,0xff ,/* Usage Page (Vendor Defined Page 1) */ +0x19 ,0x06 ,/* USAGE_MINIMUM (6) */ +0x29 ,0x08 ,/* USAGE_MAXIMUM (8) */ +0x15 ,0x00 ,/* LOGICAL_MINIMUM (0) */ +0x25 ,0x01 ,/* LOGICAL_MAXIMUM (1) */ +0x95 ,0x03 ,/* REPORT_COUNT (3) */ +0x75 ,0x01 ,/* REPORT_SIZE (1) */ +0xb1 ,0x02 ,/* Feature (Data,Var,Abs) */ +0x95 ,0x01 ,/* REPORT_COUNT (1) */ +0x75 ,0x05 ,/* REPORT_SIZE (5) */ +0x91 ,0x01 ,/* Output (Cnst,Var,Abs) */ + +0xc0 ,/* END_COLLECTION */ +0xc0 ,/* END_COLLECTION */ +}; + +static int uhid_write (int fd,const struct uhid_event *ev) +{ +ssize_t ret; + + ret =write (fd, ev,sizeof (*ev)); +if (ret <0 ) { +fprintf (stderr,"Cannot write to uhid: %m\n" ); +return -errno; + }else if (ret !=sizeof (*ev)) { +fprintf (stderr,"Wrong size written to uhid: %zd != %zu\n" , + ret,sizeof (ev)); +return -EFAULT ; + }else { +return 0 ; + } +} + +static int create (int fd,int rand_nb) +{ +struct uhid_event ev; +char buf[25 ]; + +sprintf (buf,"test-uhid-device-%d" , rand_nb); + +memset (&ev,0 ,sizeof (ev)); + ev.type =UHID_CREATE ; +strcpy ((char *)ev.u.create.name, buf); + ev.u.create.rd_data = rdesc; + ev.u.create.rd_size =sizeof (rdesc); + ev.u.create.bus =BUS_USB ; + ev.u.create.vendor =0x0001 ; + ev.u.create.product =0x0a37 ; + ev.u.create.version =0 ; + ev.u.create.country =0 ; + +sprintf (buf,"%d" , rand_nb); +strcpy ((char *)ev.u.create.phys, buf); + +return uhid_write (fd, &ev); +} + +static void destroy (int fd) +{ +struct uhid_event ev; + +memset (&ev,0 ,sizeof (ev)); + ev.type =UHID_DESTROY ; + +uhid_write (fd, &ev); +} + +static int send_event (int fd,u8 *buf,size_t size) +{ +struct uhid_event ev; + +if (size >sizeof (ev.u.input.data)) +return -E2BIG ; + +memset (&ev,0 ,sizeof (ev)); + ev.type =UHID_INPUT2 ; + ev.u.input2.size = size; + +memcpy (ev.u.input2.data, buf, size); + +return uhid_write (fd, &ev); +} + +static int setup_uhid (int rand_nb) +{ +int fd; +const char *path ="/dev/uhid" ; +int ret; + + fd =open (path,O_RDWR |O_CLOEXEC ); +if (!ASSERT_GE (fd,0 ,"open uhid-cdev" )) +return -EPERM ; + + ret =create (fd, rand_nb); +if (!ASSERT_OK (ret,"create uhid device" )) { +close (fd); +return -EPERM ; + } + +return fd; +} + +static int get_sysfs_fd (int rand_nb) +{ +const char *workdir ="/sys/devices/virtual/misc/uhid" ; +const char *target ="0003:0001:0A37.*" ; +char uevent[1024 ]; +char temp[512 ]; +char phys[512 ]; +DIR *d; +struct dirent *dir; +int fd, nread; +int found =-1 ; + +/* it would be nice to be able to use nftw, but the no_alu32 target doesn't support it */ + +sprintf (phys,"PHYS=%d" , rand_nb); + + d =opendir (workdir); +if (d) { +while ((dir =readdir (d)) !=NULL ) { +if (fnmatch (target, dir->d_name,0 )) +continue ; + +/* we found the correct VID/PID, now check for phys */ +sprintf (uevent,"%s/%s/uevent" , workdir, dir->d_name); + fd =open (uevent,O_RDONLY |O_NONBLOCK ); +if (fd <0 ) +continue ; + + nread =read (fd, temp,ARRAY_SIZE (temp)); +if (nread >0 && (strstr (temp, phys)) !=NULL ) { + found = fd; +break ; + } + +close (fd); + fd =0 ; + } +closedir (d); + } + +return found; +} + +static int get_hidraw (struct bpf_link *link) +{ +struct bpf_link_info info = {0 }; +int prog_id, i; + +/* retry 5 times in case the system is loaded */ +for (i =5 ; i >0 ; i--) { +usleep (10 ); + prog_id =link_info_prog_id (link, &info); +if (!prog_id) +continue ; +if (info.hid.hidraw_ino >=0 ) +break ; + } + +if (!prog_id) +return -1 ; + +return info.hid.hidraw_ino; +} + +/* +* Attach hid_first_event to the given uhid device, +* retrieve and open the matching hidraw node, +* inject one event in the uhid device, +* check that the program sees it and can change the data +*/ +static int test_hid_raw_event (struct hid *hid_skel,int uhid_fd,int sysfs_fd) +{ +int err, hidraw_ino, hidraw_fd =-1 ; +char hidraw_path[64 ] = {0 }; +u8 buf[10 ] = {0 }; +int ret =-1 ; + +/* check that the program is correctly loaded */ +ASSERT_EQ (hid_skel->data->callback_check,52 ,"callback_check1" ); +ASSERT_EQ (hid_skel->data->callback2_check,52 ,"callback2_check1" ); + +/* attach the first program */ + hid_skel->links.hid_first_event = +bpf_program__attach_hid (hid_skel->progs.hid_first_event, sysfs_fd); +if (!ASSERT_OK_PTR (hid_skel->links.hid_first_event, +"attach_hid(hid_first_event)" )) +return PTR_ERR (hid_skel->links.hid_first_event); + + hidraw_ino =get_hidraw (hid_skel->links.hid_first_event); +if (!ASSERT_GE (hidraw_ino,0 ,"get_hidraw" )) + goto cleanup; + +/* open hidraw node to check the other side of the pipe */ +sprintf (hidraw_path,"/dev/hidraw%d" , hidraw_ino); + hidraw_fd =open (hidraw_path,O_RDWR |O_NONBLOCK ); + +if (!ASSERT_GE (hidraw_fd,0 ,"open_hidraw" )) + goto cleanup; + +/* inject one event */ + buf[0 ] =1 ; + buf[1 ] =42 ; +send_event (uhid_fd, buf,6 ); + +/* check that hid_first_event() was executed */ +ASSERT_EQ (hid_skel->data->callback_check,42 ,"callback_check1" ); + +/* read the data from hidraw */ +memset (buf,0 ,sizeof (buf)); + err =read (hidraw_fd, buf,sizeof (buf)); +if (!ASSERT_EQ (err,6 ,"read_hidraw" )) + goto cleanup; + +if (!ASSERT_EQ (buf[2 ],47 ,"hid_first_event" )) + goto cleanup; + +/* inject another event */ + buf[0 ] =1 ; + buf[1 ] =47 ; +send_event (uhid_fd, buf,6 ); + +/* check that hid_first_event() was executed */ +ASSERT_EQ (hid_skel->data->callback_check,47 ,"callback_check1" ); + +/* read the data from hidraw */ +memset (buf,0 ,sizeof (buf)); + err =read (hidraw_fd, buf,sizeof (buf)); +if (!ASSERT_EQ (err,6 ,"read_hidraw" )) + goto cleanup; + +if (!ASSERT_EQ (buf[2 ],52 ,"hid_first_event" )) + goto cleanup; + + ret =0 ; + +cleanup: +if (hidraw_fd >=0 ) +close (hidraw_fd); + +hid__detach (hid_skel); + +return ret; +} + +void serial_test_hid_bpf (void ) +{ +struct hid *hid_skel =NULL ; +int err, uhid_fd, sysfs_fd; +time_t t; +int rand_nb; + +/* initialize random number generator */ +srand ((unsigned int )time (&t)); + + rand_nb =rand () %1024 ; + + uhid_fd =setup_uhid (rand_nb); +if (!ASSERT_GE (uhid_fd,0 ,"setup uhid" )) +return ; + +/* give a little bit of time for the device to appear */ +/* TODO: check on uhid events */ +usleep (1000 ); + +/* locate the uevent file of the created device */ + sysfs_fd =get_sysfs_fd (rand_nb); +if (!ASSERT_GE (sysfs_fd,0 ,"locate sysfs uhid device" )) + goto cleanup; + + hid_skel =hid__open_and_load (); +if (!ASSERT_OK_PTR (hid_skel,"hid_skel_load" )) + goto cleanup; + +/* start the tests! */ + err =test_hid_raw_event (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid" ); + +cleanup: +hid__destroy (hid_skel); +destroy (uhid_fd); +}
tools/testing/selftests/bpf/progs/hid.c new file +20 -0
@@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2022 Red hat */ +#include <linux/bpf.h> +#include <bpf/bpf_helpers.h> +#include <linux/bpf_hid.h> + +char _license[] SEC("license") = "GPL"; + +__u64 callback_check =52 ; +__u64 callback2_check =52 ; + +SEC("hid/device_event") +int hid_first_event (struct hid_bpf_ctx *ctx) +{ + callback_check = ctx->data[1 ]; + + ctx->data[2 ] = ctx->data[1 ] +5 ; + +return 0 ; +}
Signature · 1 line
2.35.1
Song Liu
reviewerRe: [PATCH bpf-next v2 05/28] selftests/bpf: add tests for the HID-bpf initial implementation
Quoted 10 lines · Benjamin Tissoires
The test is pretty basic:
- create a virtual uhid device that no userspace will like (to not mess up the running system)
- attach a BPF prog to it
- open the matching hidraw node
- inject one event and check:
* that the BPF program can do something on the event stream
* can modify the event stream
Quoted 2 lines
Signed-off-by Benjamin Tissoires <[email protected]>
Does this test run with vm (qemu, etc.)? Maybe we need to update tools/testing/selftests/bpf/config ?
Thanks,
Song
Re: [PATCH bpf-next v2 05/28] selftests/bpf: add tests for the HID-bpf initial implementation
Quoted 13 lines · Song Liu
Quoted 10 lines · Benjamin Tissoires
The test is pretty basic:
- create a virtual uhid device that no userspace will like (to not mess up the running system)
- attach a BPF prog to it
- open the matching hidraw node
- inject one event and check:
* that the BPF program can do something on the event stream
* can modify the event stream
Quoted 5 lines
Quoted 2 lines
Signed-off-by Benjamin Tissoires <[email protected]>Does this test run with vm (qemu, etc.)? Maybe we need to update
tools/testing/selftests/bpf/config?
Good point. I'll give it a shot. I was testing on my devel machine so it was quicker to iterate, but I completely forgot to make a run at qemu with the scripts in place.
Cheers,
Benjamin
Quoted 4 lines
Thanks,
Song
PATCH v2 6/28 samples/bpf: add new hid_mouse example
In reply to Benjamin TissoiresEverything should be available in the selftest part of the tree, but providing an example without uhid and hidraw will be more easy to follow for users.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 4 ++ samples/bpf/hid_mouse_kern.c | 66 ++++++++++++++++++ samples/bpf/hid_mouse_user.c | 129 +++++++++++++++++++++++++++++++++++ 4 files changed, 200 insertions(+) create mode 100644 samples/bpf/hid_mouse_kern.c create mode 100644 samples/bpf/hid_mouse_user.c
samples/bpf/.gitignore +1 -0
@@ -2,6 +2,7 @@ cpustat fds_example hbm +hid_mouse ibumad lathist lwt_len_hist
samples/bpf/Makefile +4 -0
@@ -60,6 +60,8 @@ tprogs-y += xdp_redirect_map tprogs-y += xdp_redirect tprogs-y += xdp_monitor +tprogs-y += hid_mouse + # Libbpf dependencies LIBBPF_SRC = $(TOOLS_PATH)/lib/bpf LIBBPF_OUTPUT = $(abspath $(BPF_SAMPLES_PATH))/libbpf
@@ -124,6 +126,7 @@ xdp_redirect_cpu-objs := xdp_redirect_cpu_user.o $(XDP_SAMPLE) xdp_redirect_map-objs := xdp_redirect_map_user.o $(XDP_SAMPLE) xdp_redirect-objs := xdp_redirect_user.o $(XDP_SAMPLE) xdp_monitor-objs := xdp_monitor_user.o $(XDP_SAMPLE) +hid_mouse-objs := hid_mouse_user.o # Tell kbuild to always build the programs always-y := $(tprogs-y)
@@ -181,6 +184,7 @@ always-y += ibumad_kern.o always-y += hbm_out_kern.o always-y += hbm_edt_kern.o always-y += xdpsock_kern.o +always-y += hid_mouse_kern.o ifeq ($(ARCH), arm) # Strip all except -D__LINUX_ARM_ARCH__ option needed to handle linux
samples/bpf/hid_mouse_kern.c new file +66 -0
66 lines not on this page · raw message
samples/bpf/hid_mouse_user.c new file +129 -0
129 lines not on this page · raw message
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 06/28] samples/bpf: add new hid_mouse example
Quoted 66 lines · Benjamin Tissoires
Everything should be available in the selftest part of the tree, but providing an example without uhid and hidraw will be more easy to follow for users.
Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples--- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 4 ++ samples/bpf/hid_mouse_kern.c | 66 ++++++++++++++++++ samples/bpf/hid_mouse_user.c | 129 +++++++++++++++++++++++++++++++++++ 4 files changed, 200 insertions(+) create mode 100644 samples/bpf/hid_mouse_kern.c create mode 100644 samples/bpf/hid_mouse_user.csamples/bpf/.gitignore +1
-0@@ -2,6 +2,7 @@ cpustat fds_example hbm +hid_mouse ibumad lathist lwt_len_histsamples/bpf/Makefile +4
-0@@ -60,6 +60,8 @@ tprogs-y += xdp_redirect_map tprogs-y += xdp_redirect tprogs-y += xdp_monitor +tprogs-y += hid_mouse + # Libbpf dependencies LIBBPF_SRC = $(TOOLS_PATH)/lib/bpf LIBBPF_OUTPUT = $(abspath $(BPF_SAMPLES_PATH))/libbpf@@ -124,6 +126,7 @@ xdp_redirect_cpu-objs := xdp_redirect_cpu_user.o $(XDP_SAMPLE) xdp_redirect_map-objs := xdp_redirect_map_user.o $(XDP_SAMPLE) xdp_redirect-objs := xdp_redirect_user.o $(XDP_SAMPLE) xdp_monitor-objs := xdp_monitor_user.o $(XDP_SAMPLE) +hid_mouse-objs := hid_mouse_user.o # Tell kbuild to always build the programs always-y := $(tprogs-y)@@ -181,6 +184,7 @@ always-y += ibumad_kern.o always-y += hbm_out_kern.o always-y += hbm_edt_kern.o always-y += xdpsock_kern.o +always-y += hid_mouse_kern.o ifeq ($(ARCH), arm) # Strip all except -D__LINUX_ARM_ARCH__ option needed to handle linuxsamples/bpf/hid_mouse_kern.c new file +0
-0
samples/bpf/hid_mouse_kern.c line 2
Quoted 2 lines
samples/bpf/hid_mouse_kern.c new file +2
-0@@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Copyright (c) 2021 Benjamin Tissoires
It's 2022 now :(
Other than that, looks nice and simple, good work!
PATCH v2 7/28 bpf/hid: add a new attach type to change the report descriptor
In reply to Benjamin TissoiresThe report descriptor is the dictionary of the HID protocol specific to the given device.
Changing it is a common habit in the HID world, and making that feature accessible from eBPF allows to fix devices without having to install a new kernel.
However, the report descriptor is supposed to be static on a device. To be able to change it, we need to reconnect the device at the HID level.
So whenever the report descriptor program type is attached or detached, we call on a hook on HID to notify it that there is something to be done.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
- unsigned long -> __u16 in uapi/linux/bpf_hid.h
--- include/linux/bpf-hid.h | 4 ++++ include/uapi/linux/bpf.h | 1 + include/uapi/linux/bpf_hid.h | 1 + kernel/bpf/hid.c | 5 +++++ kernel/bpf/syscall.c | 2 ++ tools/include/uapi/linux/bpf.h | 1 + 6 files changed, 14 insertions(+)
include/linux/bpf-hid.h +4 -0
@@ -15,6 +15,7 @@ struct hid_device;enum bpf_hid_attach_type {BPF_HID_ATTACH_INVALID =-1 ,BPF_HID_ATTACH_DEVICE_EVENT =0 , +BPF_HID_ATTACH_RDESC_FIXUP ,MAX_BPF_HID_ATTACH_TYPE };
@@ -32,6 +33,8 @@ to_bpf_hid_attach_type(enum bpf_attach_type attach_type)switch (attach_type) {case BPF_HID_DEVICE_EVENT :return BPF_HID_ATTACH_DEVICE_EVENT ; +case BPF_HID_RDESC_FIXUP : +return BPF_HID_ATTACH_RDESC_FIXUP ;default :return BPF_HID_ATTACH_INVALID ; }
@@ -88,6 +91,7 @@ static inline bool bpf_hid_link_empty(struct bpf_hid *bpf,struct bpf_hid_hooks {struct hid_device *(*hdev_from_fd)(int fd);int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type); +void (*link_attached)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); };
include/uapi/linux/bpf.h +1 -0
@@ -999,6 +999,7 @@ enum bpf_attach_type {BPF_SK_REUSEPORT_SELECT_OR_MIGRATE ,BPF_PERF_EVENT ,BPF_HID_DEVICE_EVENT , +BPF_HID_RDESC_FIXUP , __MAX_BPF_ATTACH_TYPE };
include/uapi/linux/bpf_hid.h +1 -0
@@ -24,6 +24,7 @@ struct hid_device;enum hid_bpf_event {HID_BPF_UNDEF =0 ,HID_BPF_DEVICE_EVENT ,/* when attach type is BPF_HID_DEVICE_EVENT */ +HID_BPF_RDESC_FIXUP ,/* ................... BPF_HID_RDESC_FIXUP */ };struct hid_bpf_ctx {
kernel/bpf/hid.c +5 -0
@@ -315,6 +315,8 @@ static int bpf_hid_max_progs(enum bpf_hid_attach_type type)switch (type) {case BPF_HID_ATTACH_DEVICE_EVENT :return 64 ; +case BPF_HID_ATTACH_RDESC_FIXUP : +return 1 ;default :return 0 ; }
@@ -355,6 +357,9 @@ static int bpf_hid_link_attach(struct hid_device *hdev, struct bpf_link *link, lockdep_is_held(&bpf_hid_mutex));bpf_prog_array_free (run_array); +if (hid_hooks.link_attached) + hid_hooks.link_attached (hdev, type); + out_unlock:mutex_unlock (&bpf_hid_mutex);return err;
kernel/bpf/syscall.c +2 -0
@@ -3203,6 +3203,7 @@ attach_type_to_prog_type(enum bpf_attach_type attach_type)case BPF_XDP :return BPF_PROG_TYPE_XDP ;case BPF_HID_DEVICE_EVENT : +case BPF_HID_RDESC_FIXUP :return BPF_PROG_TYPE_HID ;default :return BPF_PROG_TYPE_UNSPEC ;
@@ -3348,6 +3349,7 @@ static int bpf_prog_query(const union bpf_attr *attr,case BPF_SK_SKB_VERDICT :return sock_map_bpf_prog_query (attr, uattr);case BPF_HID_DEVICE_EVENT : +case BPF_HID_RDESC_FIXUP :return bpf_hid_prog_query (attr, uattr);default :return -EINVAL ;
tools/include/uapi/linux/bpf.h +1 -0
@@ -999,6 +999,7 @@ enum bpf_attach_type {BPF_SK_REUSEPORT_SELECT_OR_MIGRATE ,BPF_PERF_EVENT ,BPF_HID_DEVICE_EVENT , +BPF_HID_RDESC_FIXUP , __MAX_BPF_ATTACH_TYPE };
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 07/28] bpf/hid: add a new attach type to change the report descriptor
Quoted 6 lines · Benjamin Tissoires
The report descriptor is the dictionary of the HID protocol specific to the given device.
Changing it is a common habit in the HID world, and making that feature accessible from eBPF allows to fix devices without having to install a new kernel.
Quoted 8 lines
However, the report descriptor is supposed to be static on a device. To be able to change it, we need to reconnect the device at the HID level.
So whenever the report descriptor program type is attached or detached, we call on a hook on HID to notify it that there is something to be done.Signed-off-by Benjamin Tissoires <[email protected]>
PATCH v2 8/28 HID: allow to change the report descriptor from an eBPF program
In reply to Benjamin TissoiresMake use of BPF_HID_ATTACH_RDESC_FIXUP so we can trigger an rdesc fixup in the bpf world.
Whenever the program gets attached/detached, the device is reconnected meaning that userspace will see it disappearing and reappearing with the new report descriptor.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- drivers/hid/hid-bpf.c | 60 ++++++++++++++++++++++++++++++++++++++++++ drivers/hid/hid-core.c | 3 ++- include/linux/hid.h | 6 +++++ 3 files changed, 68 insertions(+), 1 deletion(-)
drivers/hid/hid-bpf.c +60 -0
@@ -50,6 +50,14 @@ static struct hid_device *hid_bpf_fd_to_hdev(int fd)return hdev; } +static int hid_reconnect (struct hid_device *hdev) +{ +if (!test_and_set_bit (ffs (HID_STAT_REPROBED ), &hdev->status)) +return device_reprobe (&hdev->dev); + +return 0 ; +} +static int hid_bpf_link_attach (struct hid_device *hdev,enum bpf_hid_attach_type type) {int err =0 ;
@@ -71,6 +79,17 @@ static int hid_bpf_link_attach(struct hid_device *hdev, enum bpf_hid_attach_typereturn err; } +static void hid_bpf_link_attached (struct hid_device *hdev,enum bpf_hid_attach_type type) +{ +switch (type) { +case BPF_HID_ATTACH_RDESC_FIXUP : +hid_reconnect (hdev); +break ; +default : +/* do nothing */ + } +} +static void hid_bpf_array_detached (struct hid_device *hdev,enum bpf_hid_attach_type type) {switch (type) {
@@ -78,6 +97,9 @@ static void hid_bpf_array_detached(struct hid_device *hdev, enum bpf_hid_attach_kfree (hdev->bpf.ctx); hdev->bpf.ctx =NULL ;break ; +case BPF_HID_ATTACH_RDESC_FIXUP : +hid_reconnect (hdev); +break ;default :/* do nothing */ }
@@ -98,6 +120,9 @@ static int hid_bpf_run_progs(struct hid_device *hdev, enum bpf_hid_attach_type tcase BPF_HID_ATTACH_DEVICE_EVENT : event =HID_BPF_DEVICE_EVENT ;break ; +case BPF_HID_ATTACH_RDESC_FIXUP : + event =HID_BPF_RDESC_FIXUP ; +break ;default :return -EINVAL ; }
@@ -138,11 +163,46 @@ u8 *hid_bpf_raw_event(struct hid_device *hdev, u8 *data, int *size)return hdev->bpf.ctx->data; } +u8 *hid_bpf_report_fixup (struct hid_device *hdev,u8 *rdesc,unsigned int *size) +{ +struct hid_bpf_ctx *ctx =NULL ; +int ret; + +if (bpf_hid_link_empty (&hdev->bpf,BPF_HID_ATTACH_RDESC_FIXUP )) + goto ignore_bpf; + + ctx =bpf_hid_allocate_ctx (hdev,HID_MAX_DESCRIPTOR_SIZE ); +if (IS_ERR (ctx)) + goto ignore_bpf; + + ret =hid_bpf_run_progs (hdev,BPF_HID_ATTACH_RDESC_FIXUP , ctx, rdesc, *size); +if (ret) + goto ignore_bpf; + + *size = ctx->size; + +if (!*size) { + rdesc =NULL ; + goto unlock; + } + + rdesc =kmemdup (ctx->data, *size,GFP_KERNEL ); + + unlock: +kfree (ctx); +return rdesc; + + ignore_bpf: +kfree (ctx); +return kmemdup (rdesc, *size,GFP_KERNEL ); +} +int __init hid_bpf_module_init (void ) {struct bpf_hid_hooks hooks = { .hdev_from_fd = hid_bpf_fd_to_hdev, .link_attach = hid_bpf_link_attach, + .link_attached = hid_bpf_link_attached, .array_detached = hid_bpf_array_detached, };
drivers/hid/hid-core.c +2 -1
@@ -1213,7 +1213,8 @@ int hid_open_report(struct hid_device *device)return -ENODEV ; size = device->dev_rsize; - buf =kmemdup (start, size,GFP_KERNEL ); +/* hid_bpf_report_fixup() ensures we work on a copy of rdesc */ + buf =hid_bpf_report_fixup (device, start, &size);if (buf ==NULL )return -ENOMEM ;
include/linux/hid.h +6 -0
@@ -1213,10 +1213,16 @@ do { \#ifdef CONFIG_BPF u8 *hid_bpf_raw_event (struct hid_device *hdev,u8 *rd,int *size); +u8 *hid_bpf_report_fixup (struct hid_device *hdev,u8 *rdesc,unsigned int *size);int hid_bpf_module_init (void );void hid_bpf_module_exit (void );#else static inline u8 *hid_bpf_raw_event (struct hid_device *hdev,u8 *rd,int *size) {return rd; } +static inline u8 *hid_bpf_report_fixup (struct hid_device *hdev,u8 *rdesc, +unsigned int *size) +{ +return kmemdup (rdesc, *size,GFP_KERNEL ); +}static inline int hid_bpf_module_init (void ) {return 0 ; }static inline void hid_bpf_module_exit (void ) {}#endif
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 08/28] HID: allow to change the report descriptor from an eBPF program
Quoted 9 lines · Benjamin Tissoires
Make use of
BPF_HID_ATTACH_RDESC_FIXUPso we can trigger an rdesc fixup in the bpf world.Whenever the program gets attached/detached, the device is reconnected meaning that userspace will see it disappearing and reappearing with the new report descriptor.
Signed-off-by Benjamin Tissoires <[email protected]>
PATCH v2 9/28 libbpf: add new attach type BPF_HID_RDESC_FIXUP
In reply to Benjamin TissoiresAdds the SEC definiton for report descriptor fixups.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- tools/lib/bpf/libbpf.c | 1 + 1 file changed, 1 insertion(+)
tools/lib/bpf/libbpf.c +1 -0
@@ -8681,6 +8681,7 @@ static const struct bpf_sec_def section_defs[] = {SEC_DEF ("struct_ops+" ,STRUCT_OPS ,0 ,SEC_NONE ),SEC_DEF ("sk_lookup" ,SK_LOOKUP ,BPF_SK_LOOKUP ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ),SEC_DEF ("hid/device_event" ,HID ,BPF_HID_DEVICE_EVENT ,SEC_ATTACHABLE_OPT |SEC_SLOPPY_PFX ), + SEC_DEF("hid/rdesc_fixup", HID, BPF_HID_RDESC_FIXUP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), };#define MAX_TYPE_NAME_SIZE 32
Signature · 1 line
2.35.1
PATCH v2 10/28 selftests/bpf: add report descriptor fixup tests
In reply to Benjamin TissoiresSimple report descriptor override in HID: replace part of the report descriptor from a static definition in the bpf kernel program.
Note that this test should be run last because we disconnect/reconnect the device, meaning that it changes the overall uhid device.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- tools/testing/selftests/bpf/prog_tests/hid.c | 69 ++++++++++++++++++++ tools/testing/selftests/bpf/progs/hid.c | 48 ++++++++++++++ 2 files changed, 117 insertions(+)
tools/testing/selftests/bpf/prog_tests/hid.c +69 -0
@@ -9,6 +9,7 @@#include <dirent.h> #include <poll.h> #include <stdbool.h> +#include <linux/hidraw.h> #include <linux/uhid.h> static unsigned char rdesc[] = {
@@ -296,6 +297,71 @@ static int test_hid_raw_event(struct hid *hid_skel, int uhid_fd, int sysfs_fd)return ret; } +/* +* Attach hid_rdesc_fixup to the given uhid device, +* retrieve and open the matching hidraw node, +* check that the hidraw report descriptor has been updated. +*/ +static int test_rdesc_fixup (struct hid *hid_skel,int uhid_fd,int sysfs_fd) +{ +struct hidraw_report_descriptor rpt_desc = {0 }; +int err, desc_size, hidraw_ino, hidraw_fd =-1 ; +char hidraw_path[64 ] = {0 }; +int ret =-1 ; + +/* attach the program */ + hid_skel->links.hid_rdesc_fixup = +bpf_program__attach_hid (hid_skel->progs.hid_rdesc_fixup, sysfs_fd); +if (!ASSERT_OK_PTR (hid_skel->links.hid_rdesc_fixup, +"attach_hid(hid_rdesc_fixup)" )) +return PTR_ERR (hid_skel->links.hid_rdesc_fixup); + +/* give a little bit of time for the device to appear */ +/* TODO: check on uhid events */ +usleep (1000 ); + + hidraw_ino =get_hidraw (hid_skel->links.hid_rdesc_fixup); +if (!ASSERT_GE (hidraw_ino,0 ,"get_hidraw" )) + goto cleanup; + +/* open hidraw node to check the other side of the pipe */ +sprintf (hidraw_path,"/dev/hidraw%d" , hidraw_ino); + hidraw_fd =open (hidraw_path,O_RDWR |O_NONBLOCK ); + +if (!ASSERT_GE (hidraw_fd,0 ,"open_hidraw" )) + goto cleanup; + +/* check that hid_rdesc_fixup() was executed */ +ASSERT_EQ (hid_skel->data->callback2_check,0x21 ,"callback_check2" ); + +/* read the exposed report descriptor from hidraw */ + err =ioctl (hidraw_fd,HIDIOCGRDESCSIZE , &desc_size); +if (!ASSERT_GE (err,0 ,"HIDIOCGRDESCSIZE" )) + goto cleanup; + +/* ensure the new size of the rdesc is bigger than the old one */ +if (!ASSERT_GT (desc_size,sizeof (rdesc),"new_rdesc_size" )) + goto cleanup; + + rpt_desc.size = desc_size; + err =ioctl (hidraw_fd,HIDIOCGRDESC , &rpt_desc); +if (!ASSERT_GE (err,0 ,"HIDIOCGRDESC" )) + goto cleanup; + +if (!ASSERT_EQ (rpt_desc.value[4 ],0x42 ,"hid_rdesc_fixup" )) + goto cleanup; + + ret =0 ; + +cleanup: +if (hidraw_fd >=0 ) +close (hidraw_fd); + +hid__detach (hid_skel); + +return ret; +} +void serial_test_hid_bpf (void ) {struct hid *hid_skel =NULL ;
@@ -329,6 +395,9 @@ void serial_test_hid_bpf(void) err =test_hid_raw_event (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid" ); + err =test_rdesc_fixup (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid_rdesc_fixup" ); + cleanup:hid__destroy (hid_skel);destroy (uhid_fd);
tools/testing/selftests/bpf/progs/hid.c +48 -0
51 lines not on this page · raw message
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 10/28] selftests/bpf: add report descriptor fixup tests
Quoted 5 lines · Benjamin Tissoires
Simple report descriptor override in HID: replace part of the report descriptor from a static definition in the bpf kernel program.
Note that this test should be run last because we disconnect/reconnect the device, meaning that it changes the overall uhid device.
You might want to add that in a comment right before:
tools/testing/selftests/bpf/prog_tests/hid.c void serial_test_hid_bpf(void) · line 399
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/hid.c +2
-0@@ -329,6 +395,9 @@ void serial_test_hid_bpf(void) err =test_hid_raw_event (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid" ); + err =test_rdesc_fixup (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid_rdesc_fixup" );
There, so that you don't add another test after this later on in 5 years.
Anyway, just a nit:
PATCH v2 11/28 samples/bpf: add a report descriptor fixup
In reply to Benjamin Tissoiresthe program inverts the definition of X and Y at a given place in the report descriptor of my mouse.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- samples/bpf/hid_mouse_kern.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)
samples/bpf/hid_mouse_kern.c +25 -0
@@ -62,5 +62,30 @@ int hid_x_event(struct hid_bpf_ctx *ctx)return 0 ; } +SEC("hid/rdesc_fixup") +int hid_rdesc_fixup (struct hid_bpf_ctx *ctx) +{ +if (ctx->type !=HID_BPF_RDESC_FIXUP ) +return 0 ; + +bpf_printk ("rdesc: %02x %02x %02x" , + ctx->data[0 ], + ctx->data[1 ], + ctx->data[2 ]); +bpf_printk (" %02x %02x %02x" , + ctx->data[3 ], + ctx->data[4 ], + ctx->data[5 ]); +bpf_printk (" %02x %02x %02x ..." , + ctx->data[6 ], + ctx->data[7 ], + ctx->data[8 ]); + + ctx->data[39 ] =0x31 ; + ctx->data[41 ] =0x30 ; + +return 0 ; +} + char _license[] SEC("license") = "GPL"; u32 _version SEC("version") = LINUX_VERSION_CODE;
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 11/28] samples/bpf: add a report descriptor fixup
Quoted 18 lines · Benjamin Tissoires
the program inverts the definition of X and Y at a given place in the report descriptor of my mouse.
Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples--- samples/bpf/hid_mouse_kern.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)samples/bpf/hid_mouse_kern.c +0
-0
samples/bpf/hid_mouse_kern.c int hid_x_event(struct hid_bpf_ctx *ctx) · line 66
Quoted 5 lines
samples/bpf/hid_mouse_kern.c +2
-0@@ -62,5 +62,30 @@ int hid_x_event(struct hid_bpf_ctx *ctx)return 0 ; } +SEC("hid/rdesc_fixup") +int hid_rdesc_fixup (struct hid_bpf_ctx *ctx)
No comment here to show the same as you put in the changelog saying what this function is doing?
Otherwise it's hard for a non-HID developer to know that:
samples/bpf/hid_mouse_kern.c int hid_x_event(struct hid_bpf_ctx *ctx) · line 85
Quoted 3 lines
samples/bpf/hid_mouse_kern.c +3
-0+ + ctx->data[39 ] =0x31 ; + ctx->data[41 ] =0x30 ;
Is flipping things.
thanks,
greg k-h
PATCH v2 12/28 bpf/hid: add hid_{get|set}_data helpers
In reply to Benjamin TissoiresWhen we process an incoming HID report, it is common to have to account for fields that are not aligned in the report. HID is using 2 helpers hid_field_extract() and implement() to pick up any data at any offset within the report.
Export those 2 helpers in BPF programs so users can also rely on them. The second net worth advantage of those helpers is that now we can fetch data anywhere in the report without knowing at compile time the location of it. The boundary checks are done in hid-bpf.c, to prevent a memory leak.
---
changes in v2:
- split the patch with libbpf and HID left outside.
--- include/linux/bpf-hid.h | 4 +++ include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ kernel/bpf/hid.c | 53 ++++++++++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ 4 files changed, 121 insertions(+)
include/linux/bpf-hid.h +4 -0
@@ -93,6 +93,10 @@ struct bpf_hid_hooks {int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*link_attached)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +int (*hid_get_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); +int (*hid_set_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); };#ifdef CONFIG_BPF
include/uapi/linux/bpf.h +32 -0
@@ -5090,6 +5090,36 @@ union bpf_attr {* Return * 0 on success, or a negative error in case of failure. On error * *dst* buffer is zeroed out. +* +* int bpf_hid_get_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Get the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field and store it into data. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into data. On error, a negative value +* is returned. +* +* int bpf_hid_set_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Set the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into ctx->event.data. On error, a negative +* value is returned. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5284,6 +5314,8 @@ union bpf_attr {FN (xdp_load_bytes), \FN (xdp_store_bytes), \FN (copy_from_user_task), \ +FN (hid_get_data), \ +FN (hid_set_data), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/hid.c +53 -0
63 lines not on this page · raw message
tools/include/uapi/linux/bpf.h +32 -0
@@ -5090,6 +5090,36 @@ union bpf_attr {* Return * 0 on success, or a negative error in case of failure. On error * *dst* buffer is zeroed out. +* +* int bpf_hid_get_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Get the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field and store it into data. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into data. On error, a negative value +* is returned. +* +* int bpf_hid_set_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Set the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into ctx->event.data. On error, a negative +* value is returned. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5284,6 +5314,8 @@ union bpf_attr {FN (xdp_load_bytes), \FN (xdp_store_bytes), \FN (copy_from_user_task), \ +FN (hid_get_data), \ +FN (hid_set_data), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 12/28] bpf/hid: add hid_{get|set}_data helpers
Quoted 5 lines · Benjamin Tissoires
When we process an incoming HID report, it is common to have to account for fields that are not aligned in the report. HID is using 2 helpers
hid_field_extract()andimplement()to pick up any data at any offset within the report.
Quoted 7 lines
Export those 2 helpers in BPF programs so users can also rely on them. The second net worth advantage of those helpers is that now we can fetch data anywhere in the report without knowing at compile time the location of it. The boundary checks are done in
hid-bpf.c, to prevent a memory leak.Signed-off-by Benjamin Tissoires <[email protected]>
Re: [PATCH bpf-next v2 12/28] bpf/hid: add hid_{get|set}_data helpers
In reply to Benjamin TissoiresQuoted 67 lines · Benjamin Tissoires
When we process an incoming HID report, it is common to have to account for fields that are not aligned in the report. HID is using 2 helpers
hid_field_extract()andimplement()to pick up any data at any offset within the report.Export those 2 helpers in BPF programs so users can also rely on them. The second net worth advantage of those helpers is that now we can fetch data anywhere in the report without knowing at compile time the location of it. The boundary checks are done in
hid-bpf.c, to prevent a memory leak.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the patch with libbpf and HID left outside.--- include/linux/bpf-hid.h | 4 +++ include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ kernel/bpf/hid.c | 53 ++++++++++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ 4 files changed, 121 insertions(+)include/linux/bpf-hid.h +4
-0@@ -93,6 +93,10 @@ struct bpf_hid_hooks {int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*link_attached)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +int (*hid_get_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); +int (*hid_set_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); };#ifdef CONFIG_BPF include/uapi/linux/bpf.h +20
-0@@ -5090,6 +5090,36 @@ union bpf_attr {* Return * 0 on success, or a negative error in case of failure. On error * *dst* buffer is zeroed out. +* +* int bpf_hid_get_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Get the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field and store it into data. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into data. On error, a negative value +* is returned. +* +* int bpf_hid_set_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Set the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field.
include/uapi/linux/bpf.h union bpf_attr { · line 5122
Quoted 10 lines
include/uapi/linux/bpf.h +10
-0+* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into ctx->event.data. On error, a negative +* value is returned.
Wait, nevermind my reviewed-by previously, see my comment about how this might be split into 4:
bpf_hid_set_bytes() bpf_hid_get_bytes() bpf_hid_set_bits() bpf_hid_get_bits()
Should be easier to understand and maintain over time, right?
thanks,
greg k-h
Re: [PATCH bpf-next v2 12/28] bpf/hid: add hid_{get|set}_data helpers
Quoted 71 lines · Greg KH
Quoted 69 lines · Benjamin Tissoires
When we process an incoming HID report, it is common to have to account for fields that are not aligned in the report. HID is using 2 helpers
hid_field_extract()andimplement()to pick up any data at any offset within the report.Export those 2 helpers in BPF programs so users can also rely on them. The second net worth advantage of those helpers is that now we can fetch data anywhere in the report without knowing at compile time the location of it. The boundary checks are done in
hid-bpf.c, to prevent a memory leak.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the patch with libbpf and HID left outside.--- include/linux/bpf-hid.h | 4 +++ include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ kernel/bpf/hid.c | 53 ++++++++++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ 4 files changed, 121 insertions(+)include/linux/bpf-hid.h +4
-0@@ -93,6 +93,10 @@ struct bpf_hid_hooks {int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*link_attached)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +int (*hid_get_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); +int (*hid_set_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); };#ifdef CONFIG_BPF include/uapi/linux/bpf.h +22
-0@@ -5090,6 +5090,36 @@ union bpf_attr {* Return * 0 on success, or a negative error in case of failure. On error * *dst* buffer is zeroed out. +* +* int bpf_hid_get_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Get the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field and store it into data. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into data. On error, a negative value +* is returned. +* +* int bpf_hid_set_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Set the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field. +* +* if n is less or equal than 32, we can address with bit precision,
Quoted 9 lines
include/uapi/linux/bpf.h union bpf_attr { · line 5122
Quoted 8 lines
include/uapi/linux/bpf.h +8
-0+* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into ctx->event.data. On error, a negative +* value is returned.
Quick answer on this one (before going deeper with the other remarks next week):
Quoted 8 lines
Wait, nevermind my reviewed-by previously, see my comment about how this might be split into 4:
bpf_hid_set_bytes() bpf_hid_get_bytes() bpf_hid_set_bits() bpf_hid_get_bits()Should be easier to understand and maintain over time, right?
Yes, definitively. I thought about adding a bytes suffix to the function name for n > 32, but not the bits one, meaning the API was still bunkers in my head.
And as I mentioned in the commit notes, I knew the API proposed in this patch was not correct, simply because while working on the selftests it was completely wrong :)
In terms of API usage, does it feel wrong for you to have only a subset of the array available "for free" and enforce the rest to be used through these helpers?
That's the point I am not sure but I feel like 1024 (or slightly more) would be enough for most use cases, and when we are dealing with bigger data sets the helpers can be justified.
Thanks for the suggestion.
Cheers,
Benjamin
Quoted 5 lines
thanks,
greg k-h
Re: [PATCH bpf-next v2 12/28] bpf/hid: add hid_{get|set}_data helpers
Quoted 97 lines · Benjamin Tissoires
Quoted 71 lines · Greg KH
Quoted 69 lines · Benjamin Tissoires
When we process an incoming HID report, it is common to have to account for fields that are not aligned in the report. HID is using 2 helpers
hid_field_extract()andimplement()to pick up any data at any offset within the report.Export those 2 helpers in BPF programs so users can also rely on them. The second net worth advantage of those helpers is that now we can fetch data anywhere in the report without knowing at compile time the location of it. The boundary checks are done in
hid-bpf.c, to prevent a memory leak.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the patch with libbpf and HID left outside.--- include/linux/bpf-hid.h | 4 +++ include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ kernel/bpf/hid.c | 53 ++++++++++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ 4 files changed, 121 insertions(+)include/linux/bpf-hid.h +4
-0@@ -93,6 +93,10 @@ struct bpf_hid_hooks {int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*link_attached)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +int (*hid_get_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); +int (*hid_set_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); };#ifdef CONFIG_BPF include/uapi/linux/bpf.h +22
-0@@ -5090,6 +5090,36 @@ union bpf_attr {* Return * 0 on success, or a negative error in case of failure. On error * *dst* buffer is zeroed out. +* +* int bpf_hid_get_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Get the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field and store it into data. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into data. On error, a negative value +* is returned. +* +* int bpf_hid_set_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Set the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field. +* +* if n is less or equal than 32, we can address with bit precision, Quoted 9 lines
include/uapi/linux/bpf.h union bpf_attr { · line 5122
Quoted 8 lines
include/uapi/linux/bpf.h +8
-0+* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into ctx->event.data. On error, a negative +* value is returned. Quick answer on this one (before going deeper with the other remarks next week):
Quoted 8 lines
Wait, nevermind my reviewed-by previously, see my comment about how this might be split into 4:
bpf_hid_set_bytes() bpf_hid_get_bytes() bpf_hid_set_bits() bpf_hid_get_bits()Should be easier to understand and maintain over time, right?
Yes, definitively. I thought about adding a
bytessuffix to the function name for n > 32, but not thebitsone, meaning the API was still bunkers in my head.
Quoted 7 lines
And as I mentioned in the commit notes, I knew the API proposed in this patch was not correct, simply because while working on the selftests it was completely wrong :)
In terms of API usage, does it feel wrong for you to have only a subset of the array available "for free" and enforce the rest to be used through these helpers?
It does feel "odd" but:
Quoted 3 lines
That's the point I am not sure but I feel like 1024 (or slightly more) would be enough for most use cases, and when we are dealing with bigger data sets the helpers can be justified.
How often are hid reports that big? If providing access to the first 1024 or so bytes for free would handle the huge majority of fixup cases, and only if you have crazy devices with large reports would you have to use the functions, it might be fine.
The problem is, only time will tell, and then, it's too late to change the api :)
So I agree with this for now, stick with what you have (if you split this into 4 functions), and let's see what happens.
thanks,
greg k-h
Song Liu
reviewerRe: [PATCH bpf-next v2 12/28] bpf/hid: add hid_{get|set}_data helpers
Quoted 93 lines · Greg KH
Quoted 91 lines · Benjamin Tissoires
Quoted 71 lines · Greg KH
Quoted 69 lines · Benjamin Tissoires
When we process an incoming HID report, it is common to have to account for fields that are not aligned in the report. HID is using 2 helpers
hid_field_extract()andimplement()to pick up any data at any offset within the report.Export those 2 helpers in BPF programs so users can also rely on them. The second net worth advantage of those helpers is that now we can fetch data anywhere in the report without knowing at compile time the location of it. The boundary checks are done in
hid-bpf.c, to prevent a memory leak.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the patch with libbpf and HID left outside.--- include/linux/bpf-hid.h | 4 +++ include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ kernel/bpf/hid.c | 53 ++++++++++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ 4 files changed, 121 insertions(+)include/linux/bpf-hid.h +4
-0@@ -93,6 +93,10 @@ struct bpf_hid_hooks {int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*link_attached)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +int (*hid_get_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); +int (*hid_set_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); };#ifdef CONFIG_BPF include/uapi/linux/bpf.h +22
-0@@ -5090,6 +5090,36 @@ union bpf_attr {* Return * 0 on success, or a negative error in case of failure. On error * *dst* buffer is zeroed out. +* +* int bpf_hid_get_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Get the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field and store it into data. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into data. On error, a negative value +* is returned. +* +* int bpf_hid_set_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Set the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field. +* +* if n is less or equal than 32, we can address with bit precision, Quoted 9 lines
include/uapi/linux/bpf.h union bpf_attr { · line 5122
Quoted 8 lines
include/uapi/linux/bpf.h +8
-0+* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into ctx->event.data. On error, a negative +* value is returned. Quick answer on this one (before going deeper with the other remarks next week):
Quoted 7 lines
Wait, nevermind my reviewed-by previously, see my comment about how this might be split into 4:
bpf_hid_set_bytes() bpf_hid_get_bytes() bpf_hid_set_bits() bpf_hid_get_bits()
Quoted 5 lines
Quoted 5 lines
Quoted 1 line
Should be easier to understand and maintain over time, right?
Yes, definitively. I thought about adding a
bytessuffix to the function name for n > 32, but not thebitsone, meaning the API was still bunkers in my head.
Do we really need per-bit access? I was under the impression that only one BPF program is working on a ctx/buffer at a time, so we can just do read-modify-write at byte level, no?
Thanks,
Song
Re: [PATCH bpf-next v2 12/28] bpf/hid: add hid_{get|set}_data helpers
Quoted 97 lines · Song Liu
Quoted 95 lines · Greg KH
Quoted 93 lines · Benjamin Tissoires
Quoted 71 lines · Greg KH
Quoted 69 lines · Benjamin Tissoires
When we process an incoming HID report, it is common to have to account for fields that are not aligned in the report. HID is using 2 helpers
hid_field_extract()andimplement()to pick up any data at any offset within the report.Export those 2 helpers in BPF programs so users can also rely on them. The second net worth advantage of those helpers is that now we can fetch data anywhere in the report without knowing at compile time the location of it. The boundary checks are done in
hid-bpf.c, to prevent a memory leak.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the patch with libbpf and HID left outside.--- include/linux/bpf-hid.h | 4 +++ include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ kernel/bpf/hid.c | 53 ++++++++++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 32 ++++++++++++++++++++ 4 files changed, 121 insertions(+)include/linux/bpf-hid.h +4
-0@@ -93,6 +93,10 @@ struct bpf_hid_hooks {int (*link_attach)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*link_attached)(struct hid_device *hdev,enum bpf_hid_attach_type type);void (*array_detached)(struct hid_device *hdev,enum bpf_hid_attach_type type); +int (*hid_get_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); +int (*hid_set_data)(struct hid_device *hdev,u8 *buf,size_t buf_size, +u64 offset,u32 n,u8 *data,u64 data_size); };#ifdef CONFIG_BPF include/uapi/linux/bpf.h +22
-0@@ -5090,6 +5090,36 @@ union bpf_attr {* Return * 0 on success, or a negative error in case of failure. On error * *dst* buffer is zeroed out. +* +* int bpf_hid_get_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Get the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field and store it into data. +* +* if n is less or equal than 32, we can address with bit precision, +* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into data. On error, a negative value +* is returned. +* +* int bpf_hid_set_data(void *ctx, u64 offset, u32 n, u8 *data, u64 size) +* Description +* Set the data of size n (in bits) at the given offset (bits) in the +* ctx->event.data field. +* +* if n is less or equal than 32, we can address with bit precision, Quoted 9 lines
include/uapi/linux/bpf.h union bpf_attr { · line 5122
Quoted 8 lines
include/uapi/linux/bpf.h +8
-0+* the value in the buffer. However, data must be a pointer to a u32 +* and size must be 4. +* +* if n is greater than 32, offset and n must be a multiple of 8 +* and the result is working with a memcpy internally. +* Return +* The length of data copied into ctx->event.data. On error, a negative +* value is returned. Quick answer on this one (before going deeper with the other remarks next week):
Quoted 8 lines
Wait, nevermind my reviewed-by previously, see my comment about how this might be split into 4:
bpf_hid_set_bytes() bpf_hid_get_bytes() bpf_hid_set_bits() bpf_hid_get_bits()Should be easier to understand and maintain over time, right?
Quoted 8 lines
Quoted 3 lines
Quoted 3 lines
Yes, definitively. I thought about adding a
bytessuffix to the function name for n > 32, but not thebitsone, meaning the API was still bunkers in my head.Do we really need per-bit access? I was under the impression that only one BPF program is working on a ctx/buffer at a time, so we can just do read-modify-write at byte level, no?
Yes, we really need per-bit access, and yes only one BPF program is working on a ctx/buffer at a time.
The per-bit access is a HID requirement and a much more convenient way of accessing data in the buffer. Well, there is another advantage too that I'll add later.
Basically, in the HID world, HW makers are trying to 'compact' the reports their device is sending to a minimum value.
For instance, when you have a 3 buttons + wheel mouse you may need:
3 bits of information for the 3 buttons
4 bits for the wheel
16 bits for X
16 bits for Y.
This usually translates almost verbatim in the report (we can add one bit of padding between buttons and wheel), which means that accessing the wheel data requires the user to access the offset 4 (bits) of size 4 bits in the report.
Some HW vendors are not even bothering aligning the data, so this can be messy from time to time with just plain byte access. All in all, the HID report descriptor gives you that information, and internally, the HID stack stores the offset in bits and the sizes in bits to access them without too much trouble.
The second advantage I have with these 2 accessors is that it allows me to not know statically the offset and size values. Because the helper in the kernel checks them for me, I can use registers values that are unknown to the verifier and can basically have:
```
__u64 offsetX = 0;
__u64 offsetY = 0;
__u32 sizeX = 0;
__u32 sizeY = 0;
SEC("hid/device_event")
int invert_xy(struct hid_bpf_ctx *ctx)
{
__u16 x, y;
if (sizeX == 16) {
x = bpf_hid_get_bits(ctx, offsetX, sizeX);
bpf_hid_set_bits(ctx, offsetX, -x);
}
if (sizeY == 16) {
y = bpf_hid_get_bits(ctx, offsetY, sizeY);
bpf_hid_set_bits(ctx, offsetY, -y);
}
return 0;
}
```Then, I have my userspace program parse the report descriptor, set the correct values for size{X|Y} and offset{X|Y} and I can have this program compiled once and redistributed many times.
Cheers,
Benjamin
PATCH v2 13/28 HID: bpf: implement hid_bpf_get|set_data
In reply to Benjamin TissoiresWe have 2 cases of usage here:
- either n <= 32: we are addressing individual bits at the given offset
- either n > 32: we are using a memcpy to transmit the data to the caller, meaning that we need to be byte-aligned.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
- allow for n > 32, by relying on memcpy
--- drivers/hid/hid-bpf.c | 68 ++++++++++++++++++++++++++++++++++++++++++ drivers/hid/hid-core.c | 4 +-- include/linux/hid.h | 2 ++ 3 files changed, 72 insertions(+), 2 deletions(-)
drivers/hid/hid-bpf.c +68 -0
@@ -105,6 +105,72 @@ static void hid_bpf_array_detached(struct hid_device *hdev, enum bpf_hid_attach_ } } +int hid_bpf_get_data (struct hid_device *hdev,u8 *buf,size_t buf_size,u64 offset,u32 n, +u8 *data,u64 data_size) +{ +u32 *value = (u32 *)data; + +if (((offset + n) >>3 ) >= buf_size) +return -E2BIG ; + +if (n <=32 ) { +/* data must be a pointer to a u32 */ +if (data_size !=4 ) +return -EINVAL ; + + *value =hid_field_extract (hdev, buf, offset, n); +return 4 ; + } + +/* if n > 32, use memcpy, but ensure we are dealing with full bytes */ +if ((n | offset) &0x7 ) +return -EINVAL ; + +/* work on bytes now */ + offset = offset >>3 ; + n = n >>3 ; + +if (n > data_size) +return -EINVAL ; + +memcpy (data, buf + offset, n); + +return n; +} + +int hid_bpf_set_data (struct hid_device *hdev,u8 *buf,size_t buf_size,u64 offset,u32 n, +u8 *data,u64 data_size) +{ +u32 *value = (u32 *)data; + +if (((offset + n) >>3 ) >= buf_size) +return -E2BIG ; + +if (n <=32 ) { +/* data must be a pointer to a u32 */ +if (data_size !=4 ) +return -EINVAL ; + +implement (hdev, buf, offset, n, *value); +return 4 ; + } + +/* if n > 32, use memcpy, but ensure we are dealing with full bytes */ +if ((n | offset) &0x7 ) +return -EINVAL ; + +/* work on bytes now */ + offset = offset >>3 ; + n = n >>3 ; + +if (n > data_size) +return -EINVAL ; + +memcpy (buf + offset, data, n); + +return n; +} +static int hid_bpf_run_progs (struct hid_device *hdev,enum bpf_hid_attach_type type,struct hid_bpf_ctx *ctx,u8 *data,int size) {
@@ -204,6 +270,8 @@ int __init hid_bpf_module_init(void) .link_attach = hid_bpf_link_attach, .link_attached = hid_bpf_link_attached, .array_detached = hid_bpf_array_detached, + .hid_get_data = hid_bpf_get_data, + .hid_set_data = hid_bpf_set_data, };bpf_hid_set_hooks (&hooks);
drivers/hid/hid-core.c +2 -2
@@ -1416,8 +1416,8 @@ static void __implement(u8 *report, unsigned offset, int n, u32 value) } } -static void implement (const struct hid_device *hid,u8 *report, -unsigned offset,unsigned n,u32 value) +void implement (const struct hid_device *hid,u8 *report,unsigned int offset,unsigned int n, +u32 value) {if (unlikely (n >32 )) { hid_warn(hid, "%s() called with n (%d) > 32! (%s)\n",
include/linux/hid.h +2 -0
@@ -944,6 +944,8 @@ bool hid_compare_device_paths(struct hid_device *hdev_a,s32 hid_snto32 (__u32 value,unsigned n);__u32 hid_field_extract (const struct hid_device *hid,__u8 *report,unsigned offset,unsigned n); +void implement (const struct hid_device *hid,u8 *report,unsigned int offset,unsigned int n, +u32 value);#ifdef CONFIG_PM int hid_driver_suspend (struct hid_device *hdev,pm_message_t state);
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 13/28] HID: bpf: implement hid_bpf_get|set_data
Quoted 5 lines · Benjamin Tissoires
We have 2 cases of usage here:
- either n <= 32: we are addressing individual bits at the given offset- either n > 32: we are using a memcpy to transmit the data to the caller, meaning that we need to be byte-aligned.
That is crazy. Can you split this into a bits/bytes function set to have 4 of them? You are using each function in two totally different ways.
thanks,
greg k-h
PATCH v2 14/28 selftests/bpf: add tests for hid_{get|set}_data helpers
In reply to Benjamin TissoiresSimple test added here, with one use of each helper.
---
changes in v2:
- split the patch with libbpf left outside.
--- tools/testing/selftests/bpf/prog_tests/hid.c | 65 ++++++++++++++++++++ tools/testing/selftests/bpf/progs/hid.c | 45 ++++++++++++++ 2 files changed, 110 insertions(+)
tools/testing/selftests/bpf/prog_tests/hid.c +65 -0
@@ -297,6 +297,68 @@ static int test_hid_raw_event(struct hid *hid_skel, int uhid_fd, int sysfs_fd)return ret; } +/* +* Attach hid_set_get_data to the given uhid device, +* retrieve and open the matching hidraw node, +* inject one event in the uhid device, +* check that the program makes correct use of bpf_hid_{set|get}_data. +*/ +static int test_hid_set_get_data (struct hid *hid_skel,int uhid_fd,int sysfs_fd) +{ +int err, hidraw_ino, hidraw_fd =-1 ; +char hidraw_path[64 ] = {0 }; +u8 buf[10 ] = {0 }; +int ret =-1 ; + +/* attach hid_set_get_data program */ + hid_skel->links.hid_set_get_data = +bpf_program__attach_hid (hid_skel->progs.hid_set_get_data, sysfs_fd); +if (!ASSERT_OK_PTR (hid_skel->links.hid_set_get_data, +"attach_hid(hid_set_get_data)" )) +return PTR_ERR (hid_skel->links.hid_set_get_data); + + hidraw_ino =get_hidraw (hid_skel->links.hid_set_get_data); +if (!ASSERT_GE (hidraw_ino,0 ,"get_hidraw" )) + goto cleanup; + +/* open hidraw node to check the other side of the pipe */ +sprintf (hidraw_path,"/dev/hidraw%d" , hidraw_ino); + hidraw_fd =open (hidraw_path,O_RDWR |O_NONBLOCK ); + +if (!ASSERT_GE (hidraw_fd,0 ,"open_hidraw" )) + goto cleanup; + +/* inject one event */ + buf[0 ] =1 ; + buf[1 ] =42 ; +send_event (uhid_fd, buf,6 ); + +/* read the data from hidraw */ +memset (buf,0 ,sizeof (buf)); + err =read (hidraw_fd, buf,sizeof (buf)); +if (!ASSERT_EQ (err,6 ,"read_hidraw" )) + goto cleanup; + +if (!ASSERT_EQ (buf[2 ], (42 >>2 ),"hid_set_get_data" )) + goto cleanup; + +if (!ASSERT_EQ (buf[3 ],1 ,"hid_set_get_data" )) + goto cleanup; + +if (!ASSERT_EQ (buf[4 ],42 ,"hid_set_get_data" )) + goto cleanup; + + ret =0 ; + +cleanup: +if (hidraw_fd >=0 ) +close (hidraw_fd); + +hid__detach (hid_skel); + +return ret; +} +/* * Attach hid_rdesc_fixup to the given uhid device, * retrieve and open the matching hidraw node,
@@ -395,6 +457,9 @@ void serial_test_hid_bpf(void) err =test_hid_raw_event (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid" ); + err =test_hid_set_get_data (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid_set_get_data" ); + err =test_rdesc_fixup (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_rdesc_fixup" );
tools/testing/selftests/bpf/progs/hid.c +45 -0
48 lines not on this page · raw message
Signature · 1 line
2.35.1
Re: [PATCH bpf-next v2 14/28] selftests/bpf: add tests for hid_{get|set}_data helpers
Hi Benjamin,
Quoted 102 lines · Benjamin Tissoires
Simple test added here, with one use of each helper.
Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the patch with libbpf left outside.--- tools/testing/selftests/bpf/prog_tests/hid.c | 65 ++++++++++++++++++++ tools/testing/selftests/bpf/progs/hid.c | 45 ++++++++++++++ 2 files changed, 110 insertions(+)tools/testing/selftests/bpf/prog_tests/hid.c +65
-0@@ -297,6 +297,68 @@ static int test_hid_raw_event(struct hid *hid_skel, int uhid_fd, int sysfs_fd)return ret; } +/* +* Attach hid_set_get_data to the given uhid device, +* retrieve and open the matching hidraw node, +* inject one event in the uhid device, +* check that the program makes correct use of bpf_hid_{set|get}_data. +*/ +static int test_hid_set_get_data (struct hid *hid_skel,int uhid_fd,int sysfs_fd) +{ +int err, hidraw_ino, hidraw_fd =-1 ; +char hidraw_path[64 ] = {0 }; +u8 buf[10 ] = {0 }; +int ret =-1 ; + +/* attach hid_set_get_data program */ + hid_skel->links.hid_set_get_data = +bpf_program__attach_hid (hid_skel->progs.hid_set_get_data, sysfs_fd); +if (!ASSERT_OK_PTR (hid_skel->links.hid_set_get_data, +"attach_hid(hid_set_get_data)" )) +return PTR_ERR (hid_skel->links.hid_set_get_data); + + hidraw_ino =get_hidraw (hid_skel->links.hid_set_get_data); +if (!ASSERT_GE (hidraw_ino,0 ,"get_hidraw" )) + goto cleanup; + +/* open hidraw node to check the other side of the pipe */ +sprintf (hidraw_path,"/dev/hidraw%d" , hidraw_ino); + hidraw_fd =open (hidraw_path,O_RDWR |O_NONBLOCK ); + +if (!ASSERT_GE (hidraw_fd,0 ,"open_hidraw" )) + goto cleanup; + +/* inject one event */ + buf[0 ] =1 ; + buf[1 ] =42 ; +send_event (uhid_fd, buf,6 ); + +/* read the data from hidraw */ +memset (buf,0 ,sizeof (buf)); + err =read (hidraw_fd, buf,sizeof (buf)); +if (!ASSERT_EQ (err,6 ,"read_hidraw" )) + goto cleanup; + +if (!ASSERT_EQ (buf[2 ], (42 >>2 ),"hid_set_get_data" )) + goto cleanup; + +if (!ASSERT_EQ (buf[3 ],1 ,"hid_set_get_data" )) + goto cleanup; + +if (!ASSERT_EQ (buf[4 ],42 ,"hid_set_get_data" )) + goto cleanup; + + ret =0 ; + +cleanup: +if (hidraw_fd >=0 ) +close (hidraw_fd); + +hid__detach (hid_skel); + +return ret; +} +/* * Attach hid_rdesc_fixup to the given uhid device, * retrieve and open the matching hidraw node, @@ -395,6 +457,9 @@ void serial_test_hid_bpf(void) err =test_hid_raw_event (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid" ); + err =test_hid_set_get_data (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid_set_get_data" ); + err =test_rdesc_fixup (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_rdesc_fixup" );tools/testing/selftests/bpf/progs/hid.c +0
-0@@ -66,3 +66,48 @@ int hid_rdesc_fixup(struct hid_bpf_ctx *ctx)
tools/testing/selftests/bpf/progs/hid.c int hid_rdesc_fixup(struct hid_bpf_ctx *ctx) · line 76
Quoted 10 lines
tools/testing/selftests/bpf/progs/hid.c +8
-0return 0 ; } + +SEC("hid/device_event") +int hid_set_get_data (struct hid_bpf_ctx *ctx) +{ +int ret; +__u8 *buf; + + buf =bpf_ringbuf_reserve (&ringbuf,8 ,0 );
Ordering of patches is probably wrong, it seems the ringbuf is defined in patch #21 but used here.
Also, this usage of ringbuf leads into running out of available memory in the buffer if used for long time, it is not evident from the test case written here but I spent a couple of hours debugging my own BPF program that used ringbuf in similar way as what is done here. Basically the producer idx is increased with the bpf_ringbuf_reserve / discard, but the consumer index is not if you don't have a consumer in place.
I ended up using a global statically allocated buffer for the purpose for now.
-Tero
Quoted 37 lines
tools/testing/selftests/bpf/progs/hid.c +37
-0+if (!buf) +return -12 ;/* -ENOMEM */ + +/* first try read/write with n > 32 */ + ret =bpf_hid_get_data (ctx,0 ,64 , buf,8 ); +if (ret <0 ) + goto discard; + +/* reinject it */ + ret =bpf_hid_set_data (ctx,24 ,64 , buf,8 ); +if (ret <0 ) + goto discard; + +/* extract data at bit offset 10 of size 4 (half a byte) */ + ret =bpf_hid_get_data (ctx,10 ,4 , buf,8 );/* expected to fail */ +if (ret >0 ) { + ret =-1 ; + goto discard; + } + + ret =bpf_hid_get_data (ctx,10 ,4 , buf,4 ); +if (ret <0 ) + goto discard; + +/* reinject it */ + ret =bpf_hid_set_data (ctx,16 ,4 , buf,4 ); +if (ret <0 ) + goto discard; + + ret =0 ; + + discard: + +bpf_ringbuf_discard (buf,0 ); + +return ret; +}
Re: [PATCH bpf-next v2 14/28] selftests/bpf: add tests for hid_{get|set}_data helpers
Quoted 120 lines · Tero Kristo
Hi Benjamin,
Quoted 102 lines · Benjamin Tissoires
Simple test added here, with one use of each helper.
Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the patch with libbpf left outside.--- tools/testing/selftests/bpf/prog_tests/hid.c | 65 ++++++++++++++++++++ tools/testing/selftests/bpf/progs/hid.c | 45 ++++++++++++++ 2 files changed, 110 insertions(+)tools/testing/selftests/bpf/prog_tests/hid.c +65
-0@@ -297,6 +297,68 @@ static int test_hid_raw_event(struct hid *hid_skel, int uhid_fd, int sysfs_fd)return ret; } +/* +* Attach hid_set_get_data to the given uhid device, +* retrieve and open the matching hidraw node, +* inject one event in the uhid device, +* check that the program makes correct use of bpf_hid_{set|get}_data. +*/ +static int test_hid_set_get_data (struct hid *hid_skel,int uhid_fd,int sysfs_fd) +{ +int err, hidraw_ino, hidraw_fd =-1 ; +char hidraw_path[64 ] = {0 }; +u8 buf[10 ] = {0 }; +int ret =-1 ; + +/* attach hid_set_get_data program */ + hid_skel->links.hid_set_get_data = +bpf_program__attach_hid (hid_skel->progs.hid_set_get_data, sysfs_fd); +if (!ASSERT_OK_PTR (hid_skel->links.hid_set_get_data, +"attach_hid(hid_set_get_data)" )) +return PTR_ERR (hid_skel->links.hid_set_get_data); + + hidraw_ino =get_hidraw (hid_skel->links.hid_set_get_data); +if (!ASSERT_GE (hidraw_ino,0 ,"get_hidraw" )) + goto cleanup; + +/* open hidraw node to check the other side of the pipe */ +sprintf (hidraw_path,"/dev/hidraw%d" , hidraw_ino); + hidraw_fd =open (hidraw_path,O_RDWR |O_NONBLOCK ); + +if (!ASSERT_GE (hidraw_fd,0 ,"open_hidraw" )) + goto cleanup; + +/* inject one event */ + buf[0 ] =1 ; + buf[1 ] =42 ; +send_event (uhid_fd, buf,6 ); + +/* read the data from hidraw */ +memset (buf,0 ,sizeof (buf)); + err =read (hidraw_fd, buf,sizeof (buf)); +if (!ASSERT_EQ (err,6 ,"read_hidraw" )) + goto cleanup; + +if (!ASSERT_EQ (buf[2 ], (42 >>2 ),"hid_set_get_data" )) + goto cleanup; + +if (!ASSERT_EQ (buf[3 ],1 ,"hid_set_get_data" )) + goto cleanup; + +if (!ASSERT_EQ (buf[4 ],42 ,"hid_set_get_data" )) + goto cleanup; + + ret =0 ; + +cleanup: +if (hidraw_fd >=0 ) +close (hidraw_fd); + +hid__detach (hid_skel); + +return ret; +} +/* * Attach hid_rdesc_fixup to the given uhid device, * retrieve and open the matching hidraw node, @@ -395,6 +457,9 @@ void serial_test_hid_bpf(void) err =test_hid_raw_event (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid" ); + err =test_hid_set_get_data (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid_set_get_data" ); + err =test_rdesc_fixup (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_rdesc_fixup" );tools/testing/selftests/bpf/progs/hid.c +0
-0@@ -66,3 +66,48 @@ int hid_rdesc_fixup(struct hid_bpf_ctx *ctx)tools/testing/selftests/bpf/progs/hid.c int hid_rdesc_fixup(struct hid_bpf_ctx *ctx) · line 76
Quoted 10 lines
tools/testing/selftests/bpf/progs/hid.c +8
-0return 0 ; } + +SEC("hid/device_event") +int hid_set_get_data (struct hid_bpf_ctx *ctx) +{ +int ret; +__u8 *buf; + + buf =bpf_ringbuf_reserve (&ringbuf,8 ,0 );Ordering of patches is probably wrong, it seems the ringbuf is defined in patch #21 but used here.
Quoted 6 lines
Also, this usage of ringbuf leads into running out of available memory in the buffer if used for long time, it is not evident from the test case written here but I spent a couple of hours debugging my own BPF program that used ringbuf in similar way as what is done here. Basically the producer idx is increased with the
bpf_ringbuf_reserve/ discard, but the consumer index is not if you don't have a consumer in place.
Oh, that's good to know.
FWIW, on v3, we won't have to use a ringbuf at all. This is a new API break (sorry for that), but I think this will be better in the long run.
I have chosen to use the hid_bpf_get_data() from [0]. The net advantage is that we get a pointer to the internal buffer that can be of any size, and we can even re-inject that same pointer into bpf_hid_raw_request() without having to use another buffer.
I'm currently working on the documentation part and small fixes now that the big rewrite with that implementation is now done.
Cheers,
Benjamin
Quoted 6 lines
I ended up using a global statically allocated buffer for the purpose for now.
-Tero
PATCH v2 15/28 bpf/hid: add new BPF type to trigger commands from userspace
In reply to Benjamin TissoiresGiven that we can not call bpf_hid_raw_request() from within an IRQ, userspace needs to have a way to communicate with the device when it needs.
Implement a new type that the caller can run at will without being in an IRQ context.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
- unsigned long -> __u16 in uapi/linux/bpf_hid.h
- int -> __32 in uapi/linux/bpf_hid.h
--- include/linux/bpf-hid.h | 3 + include/uapi/linux/bpf.h | 1 + include/uapi/linux/bpf_hid.h | 10 +++ kernel/bpf/hid.c | 116 +++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 2 + tools/include/uapi/linux/bpf.h | 1 + 6 files changed, 133 insertions(+)
include/linux/bpf-hid.h +3 -0
@@ -16,6 +16,7 @@ enum bpf_hid_attach_type {BPF_HID_ATTACH_INVALID =-1 ,BPF_HID_ATTACH_DEVICE_EVENT =0 ,BPF_HID_ATTACH_RDESC_FIXUP , +BPF_HID_ATTACH_USER_EVENT , MAX_BPF_HID_ATTACH_TYPE };
@@ -35,6 +36,8 @@ to_bpf_hid_attach_type(enum bpf_attach_type attach_type)return BPF_HID_ATTACH_DEVICE_EVENT ;case BPF_HID_RDESC_FIXUP :return BPF_HID_ATTACH_RDESC_FIXUP ; +case BPF_HID_USER_EVENT : +return BPF_HID_ATTACH_USER_EVENT ;default :return BPF_HID_ATTACH_INVALID ; }
include/uapi/linux/bpf.h +1 -0
@@ -1000,6 +1000,7 @@ enum bpf_attach_type {BPF_PERF_EVENT ,BPF_HID_DEVICE_EVENT ,BPF_HID_RDESC_FIXUP , +BPF_HID_USER_EVENT , __MAX_BPF_ATTACH_TYPE };
include/uapi/linux/bpf_hid.h +10 -0
@@ -25,6 +25,12 @@ enum hid_bpf_event {HID_BPF_UNDEF =0 ,HID_BPF_DEVICE_EVENT ,/* when attach type is BPF_HID_DEVICE_EVENT */ HID_BPF_RDESC_FIXUP ,/* ................... BPF_HID_RDESC_FIXUP */ + HID_BPF_USER_EVENT, /* ................... BPF_HID_USER_EVENT */ +}; + +/* type is HID_BPF_USER_EVENT */ +struct hid_bpf_ctx_user_event { +__s32 retval; }; struct hid_bpf_ctx {
@@ -32,6 +38,10 @@ struct hid_bpf_ctx {__u16 allocated_size;/* the allocated size of data below (RO) */ struct hid_device *hdev;/* read-only */ +union { +struct hid_bpf_ctx_user_event user;/* read-write */ + } u; +__u16 size;/* used size in data (RW) */ __u8 data[];/* data buffer (RW) */ };
kernel/bpf/hid.c +116 -0
129 lines not on this page · raw message
kernel/bpf/syscall.c +2 -0
@@ -3204,6 +3204,7 @@ attach_type_to_prog_type(enum bpf_attach_type attach_type)return BPF_PROG_TYPE_XDP ;case BPF_HID_DEVICE_EVENT :case BPF_HID_RDESC_FIXUP : +case BPF_HID_USER_EVENT :return BPF_PROG_TYPE_HID ;default :return BPF_PROG_TYPE_UNSPEC ;
@@ -3350,6 +3351,7 @@ static int bpf_prog_query(const union bpf_attr *attr,return sock_map_bpf_prog_query (attr, uattr);case BPF_HID_DEVICE_EVENT :case BPF_HID_RDESC_FIXUP : +case BPF_HID_USER_EVENT :return bpf_hid_prog_query (attr, uattr);default :return -EINVAL ;
tools/include/uapi/linux/bpf.h +1 -0
@@ -1000,6 +1000,7 @@ enum bpf_attach_type {BPF_PERF_EVENT ,BPF_HID_DEVICE_EVENT ,BPF_HID_RDESC_FIXUP , +BPF_HID_USER_EVENT , __MAX_BPF_ATTACH_TYPE };
Signature · 1 line
2.35.1
Song Liu
reviewerRe: [PATCH bpf-next v2 15/28] bpf/hid: add new BPF type to trigger commands from userspace
Quoted 11 lines · Benjamin Tissoires
Given that we can not call
bpf_hid_raw_request()from within an IRQ, userspace needs to have a way to communicate with the device when it needs.Implement a new type that the caller can run at will without being in an IRQ context.
Signed-off-by Benjamin Tissoires <[email protected]>---
[...]
Quoted 9 lines
kernel/bpf/hid.c +9
-0+if (user_size_out && data_out) { + user_size_out =min3 (user_size_out, (u32 )ctx->size, (u32 )ctx->allocated_size); + +if (copy_to_user (data_out, ctx->data, user_size_out)) { + ret = -EFAULT ; + goto unlock; + } + + if (copy_to_user(&uattr->test.data_size_out,
kernel/bpf/hid.c int bpf_hid_link_create(const union bpf_attr *attr, struct bpf_prog *prog) · line 572
Quoted 10 lines
kernel/bpf/hid.c +10
-0+ &user_size_out, + sizeof(user_size_out))) { + ret = -EFAULT ; + goto unlock; + } + } + +if (copy_to_user (&uattr->test.retval, &ctx->u.user.retval,sizeof (ctx->u.user.retval))) { + ret = -EFAULT ; + goto unlock;
nit: this goto is not really needed.
Quoted 8 lines
kernel/bpf/hid.c +8
-0+ } + +unlock: +kfree (ctx); + +mutex_unlock (&bpf_hid_mutex); +return ret; +}
[...]
PATCH v2 16/28 libbpf: add new attach type BPF_HID_USER_EVENT
In reply to Benjamin TissoiresAdds the SEC definiton for the user callbacks of HID bpf.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- tools/lib/bpf/libbpf.c | 1 + 1 file changed, 1 insertion(+)
tools/lib/bpf/libbpf.c +1 -0
@@ -8682,6 +8682,7 @@ static const struct bpf_sec_def section_defs[] = {SEC_DEF ("sk_lookup" ,SK_LOOKUP ,BPF_SK_LOOKUP ,SEC_ATTACHABLE |SEC_SLOPPY_PFX ),SEC_DEF ("hid/device_event" ,HID ,BPF_HID_DEVICE_EVENT ,SEC_ATTACHABLE_OPT |SEC_SLOPPY_PFX ),SEC_DEF ("hid/rdesc_fixup" ,HID ,BPF_HID_RDESC_FIXUP ,SEC_ATTACHABLE_OPT |SEC_SLOPPY_PFX ), + SEC_DEF("hid/user_event", HID, BPF_HID_USER_EVENT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), };#define MAX_TYPE_NAME_SIZE 32
Signature · 1 line
2.35.1
PATCH v2 17/28 selftests/bpf: add test for user call of HID bpf programs
In reply to Benjamin TissoiresAdd a simple test to see if we can trigger a bpf program of type "hid/user_event".
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- tools/testing/selftests/bpf/prog_tests/hid.c | 56 ++++++++++++++++++++ tools/testing/selftests/bpf/progs/hid.c | 10 ++++ 2 files changed, 66 insertions(+)
tools/testing/selftests/bpf/prog_tests/hid.c +56 -0
@@ -359,6 +359,59 @@ static int test_hid_set_get_data(struct hid *hid_skel, int uhid_fd, int sysfs_fdreturn ret; } +/* +* Attach hid_user to the given uhid device, +* call the bpf program from userspace +* check that the program is called and does the expected. +*/ +static int test_hid_user_call (struct hid *hid_skel,int uhid_fd,int sysfs_fd) +{ +int err, prog_fd; +u8 buf[10 ] = {0 }; +int ret =-1 ; + +LIBBPF_OPTS (bpf_test_run_opts, run_attrs, + .repeat = 1, + .ctx_in = &sysfs_fd, + .ctx_size_in = sizeof(sysfs_fd), + .data_in = buf, + .data_size_in = sizeof(buf), + .data_out = buf, + .data_size_out = sizeof(buf), + ); + +/* attach hid_user program */ + hid_skel->links.hid_user =bpf_program__attach_hid (hid_skel->progs.hid_user, sysfs_fd); +if (!ASSERT_OK_PTR (hid_skel->links.hid_user, +"attach_hid(hid_user)" )) +return PTR_ERR (hid_skel->links.hid_user); + + buf[0 ] =39 ; + + prog_fd =bpf_program__fd (hid_skel->progs.hid_user); + + err =bpf_prog_test_run_opts (prog_fd, &run_attrs); +if (!ASSERT_EQ (err,0 ,"bpf_prog_test_run_xattr" )) + goto cleanup; + +if (!ASSERT_EQ (run_attrs.retval,72 ,"bpf_prog_test_run_opts" )) + goto cleanup; + +if (!ASSERT_EQ (buf[1 ],42 ,"hid_user_check_in" )) + goto cleanup; + +if (!ASSERT_EQ (buf[2 ],4 ,"hid_user_check_static_out" )) + goto cleanup; + + ret =0 ; + +cleanup: + +hid__detach (hid_skel); + +return ret; +} +/* * Attach hid_rdesc_fixup to the given uhid device, * retrieve and open the matching hidraw node,
@@ -460,6 +513,9 @@ void serial_test_hid_bpf(void) err =test_hid_set_get_data (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_set_get_data" ); + err =test_hid_user_call (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid_user" ); + err =test_rdesc_fixup (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_rdesc_fixup" );
tools/testing/selftests/bpf/progs/hid.c +10 -0
@@ -111,3 +111,13 @@ int hid_set_get_data(struct hid_bpf_ctx *ctx)return ret; } + +SEC("hid/user_event") +int hid_user (struct hid_bpf_ctx *ctx) +{ + ctx->data[1 ] = ctx->data[0 ] +3 ; + ctx->data[2 ] =4 ; + ctx->u.user.retval =72 ; + +return 0 ; +}
Signature · 1 line
2.35.1
PATCH v2 18/28 selftests/bpf: hid: rely on uhid event to know if a test device is ready
In reply to Benjamin TissoiresWe need this for 2 reasons:
- first we remove the ugly sleeps
- then when we try to communicate with the device, we need to have another thread that handles that communication and simulate a real device
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- tools/testing/selftests/bpf/prog_tests/hid.c | 126 ++++++++++++++++++- 1 file changed, 120 insertions(+), 6 deletions(-)
tools/testing/selftests/bpf/prog_tests/hid.c +120 -6
@@ -67,6 +67,12 @@ static unsigned char rdesc[] = { 0xc0, /* END_COLLECTION */ }; +static pthread_mutex_t uhid_started_mtx =PTHREAD_MUTEX_INITIALIZER ; +static pthread_cond_t uhid_started =PTHREAD_COND_INITIALIZER ; + +/* no need to protect uhid_stopped, only one thread accesses it */ +static bool uhid_stopped; +static int uhid_write (int fd,const struct uhid_event *ev) {ssize_t ret;
@@ -118,6 +124,104 @@ static void destroy(int fd)uhid_write (fd, &ev); } +static int event (int fd) +{ +struct uhid_event ev; +ssize_t ret; + +memset (&ev,0 ,sizeof (ev)); + ret =read (fd, &ev,sizeof (ev)); +if (ret ==0 ) { +fprintf (stderr,"Read HUP on uhid-cdev\n" ); +return -EFAULT ; + }else if (ret <0 ) { +fprintf (stderr,"Cannot read uhid-cdev: %m\n" ); +return -errno; + }else if (ret !=sizeof (ev)) { +fprintf (stderr,"Invalid size read from uhid-dev: %zd != %zu\n" , + ret,sizeof (ev)); +return -EFAULT ; + } + +switch (ev.type) { +case UHID_START : +pthread_mutex_lock (&uhid_started_mtx); +pthread_cond_signal (&uhid_started); +pthread_mutex_unlock (&uhid_started_mtx); + +fprintf (stderr,"UHID_START from uhid-dev\n" ); +break ; +case UHID_STOP : + uhid_stopped = true; + +fprintf (stderr,"UHID_STOP from uhid-dev\n" ); +break ; +case UHID_OPEN : +fprintf (stderr,"UHID_OPEN from uhid-dev\n" ); +break ; +case UHID_CLOSE : +fprintf (stderr,"UHID_CLOSE from uhid-dev\n" ); +break ; +case UHID_OUTPUT : +fprintf (stderr,"UHID_OUTPUT from uhid-dev\n" ); +break ; +case UHID_GET_REPORT : +fprintf (stderr,"UHID_GET_REPORT from uhid-dev\n" ); +break ; +case UHID_SET_REPORT : +fprintf (stderr,"UHID_SET_REPORT from uhid-dev\n" ); +break ; +default : +fprintf (stderr,"Invalid event from uhid-dev: %u\n" , ev.type); + } + +return 0 ; +} + +static void *read_uhid_events_thread (void *arg) +{ +int fd = *(int *)arg; +struct pollfd pfds[1 ]; +int ret =0 ; + + pfds[0 ].fd = fd; + pfds[0 ].events =POLLIN ; + + uhid_stopped = false; + +while (!uhid_stopped) { + ret =poll (pfds,1 ,100 ); +if (ret <0 ) { +fprintf (stderr,"Cannot poll for fds: %m\n" ); +break ; + } +if (pfds[0 ].revents &POLLIN ) { + ret =event (fd); +if (ret) +break ; + } + } + +return (void *)(long )ret; +} + +static int uhid_start_listener (pthread_t *tid,int uhid_fd) +{ +int fd = uhid_fd; + +pthread_mutex_lock (&uhid_started_mtx); +if (CHECK_FAIL (pthread_create (tid,NULL , read_uhid_events_thread, + (void *)&fd))) { +pthread_mutex_unlock (&uhid_started_mtx); +close (fd); +return -EIO ; + } +pthread_cond_wait (&uhid_started, &uhid_started_mtx); +pthread_mutex_unlock (&uhid_started_mtx); + +return 0 ; +} +static int send_event (int fd,u8 *buf,size_t size) {struct uhid_event ev;
@@ -422,7 +526,9 @@ static int test_rdesc_fixup(struct hid *hid_skel, int uhid_fd, int sysfs_fd)struct hidraw_report_descriptor rpt_desc = {0 };int err, desc_size, hidraw_ino, hidraw_fd =-1 ;char hidraw_path[64 ] = {0 }; +void *uhid_err;int ret =-1 ; +pthread_t tid;/* attach the program */ hid_skel->links.hid_rdesc_fixup =
@@ -431,9 +537,8 @@ static int test_rdesc_fixup(struct hid *hid_skel, int uhid_fd, int sysfs_fd) "attach_hid(hid_rdesc_fixup)"))return PTR_ERR (hid_skel->links.hid_rdesc_fixup); -/* give a little bit of time for the device to appear */ -/* TODO: check on uhid events */ -usleep (1000 ); + err =uhid_start_listener (&tid, uhid_fd); +ASSERT_OK (err,"uhid_start_listener" ); hidraw_ino =get_hidraw (hid_skel->links.hid_rdesc_fixup);if (!ASSERT_GE (hidraw_ino,0 ,"get_hidraw" ))
@@ -474,6 +579,10 @@ static int test_rdesc_fixup(struct hid *hid_skel, int uhid_fd, int sysfs_fd)hid__detach (hid_skel); +pthread_join (tid, &uhid_err); + err = (int )(long )uhid_err; +CHECK_FAIL (err); +return ret; }
@@ -481,7 +590,9 @@ void serial_test_hid_bpf(void) {struct hid *hid_skel =NULL ;int err, uhid_fd, sysfs_fd; +void *uhid_err;time_t t; +pthread_t tid;int rand_nb;/* initialize random number generator */
@@ -493,9 +604,8 @@ void serial_test_hid_bpf(void)if (!ASSERT_GE (uhid_fd,0 ,"setup uhid" ))return ; -/* give a little bit of time for the device to appear */ -/* TODO: check on uhid events */ -usleep (1000 ); + err =uhid_start_listener (&tid, uhid_fd); +ASSERT_OK (err,"uhid_start_listener" );/* locate the uevent file of the created device */ sysfs_fd =get_sysfs_fd (rand_nb);
@@ -522,4 +632,8 @@ void serial_test_hid_bpf(void) cleanup:hid__destroy (hid_skel);destroy (uhid_fd); + +pthread_join (tid, &uhid_err); + err = (int )(long )uhid_err; +CHECK_FAIL (err); }
Signature · 1 line
2.35.1
PATCH v2 19/28 bpf/hid: add bpf_hid_raw_request helper function
In reply to Benjamin TissoiresWhen we are in a user_event context, we can talk to the device to fetch or set features/outputs/inputs reports.
Add a bpf helper to do so. This helper is thus only available to user_events, because calling this function while in IRQ context (any other BPF type) is forbidden.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- include/linux/bpf-hid.h | 2 ++ include/uapi/linux/bpf.h | 8 ++++++++ kernel/bpf/hid.c | 26 ++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 8 ++++++++ 4 files changed, 44 insertions(+)
include/linux/bpf-hid.h +2 -0
@@ -100,6 +100,8 @@ struct bpf_hid_hooks { u64 offset, u32 n, u8 *data, u64 data_size);int (*hid_set_data)(struct hid_device *hdev,u8 *buf,size_t buf_size,u64 offset,u32 n,u8 *data,u64 data_size); +int (*hid_raw_request)(struct hid_device *hdev,u8 *buf,size_t size, +u8 rtype,u8 reqtype); };#ifdef CONFIG_BPF
include/uapi/linux/bpf.h +8 -0
@@ -5121,6 +5121,13 @@ union bpf_attr {* Return * The length of data copied into ctx->event.data. On error, a negative * value is returned. +* +* int bpf_hid_raw_request(void *ctx, void *buf, u64 size, u8 rtype, u8 reqtype) +* Description +* communicate with the HID device +* Return +* 0 on success. +* negative value on error. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5317,6 +5324,7 @@ union bpf_attr {FN (copy_from_user_task), \FN (hid_get_data), \FN (hid_set_data), \ +FN (hid_raw_request), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/hid.c +26 -0
@@ -86,6 +86,28 @@ static const struct bpf_func_proto bpf_hid_set_data_proto = { .arg5_type = ARG_CONST_SIZE_OR_ZERO, }; +BPF_CALL_5(bpf_hid_raw_request, void*, ctx, void*, buf, u64, size, + u8, rtype, u8, reqtype) +{ +struct hid_bpf_ctx *bpf_ctx = ctx; + +if (!hid_hooks.hid_raw_request) +return -EOPNOTSUPP ; + +return hid_hooks.hid_raw_request (bpf_ctx->hdev, buf, size, rtype, reqtype); +} + +static const struct bpf_func_proto bpf_hid_raw_request_proto = { + .func = bpf_hid_raw_request, + .gpl_only = true,/* hid_raw_request is EXPORT_SYMBOL_GPL */ + .ret_type =RET_INTEGER , + .arg1_type =ARG_PTR_TO_CTX , + .arg2_type =ARG_PTR_TO_MEM , + .arg3_type =ARG_CONST_SIZE_OR_ZERO , + .arg4_type =ARG_ANYTHING , + .arg5_type =ARG_ANYTHING , +}; +static const struct bpf_func_proto *hid_func_proto (enum bpf_func_id func_id,const struct bpf_prog *prog) {
@@ -94,6 +116,10 @@ hid_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)return &bpf_hid_get_data_proto;case BPF_FUNC_hid_set_data:return &bpf_hid_set_data_proto; +case BPF_FUNC_hid_raw_request: +if (prog->expected_attach_type !=BPF_HID_DEVICE_EVENT ) +return &bpf_hid_raw_request_proto; +return NULL ;default :return bpf_base_func_proto (func_id); }
tools/include/uapi/linux/bpf.h +8 -0
@@ -5121,6 +5121,13 @@ union bpf_attr {* Return * The length of data copied into ctx->event.data. On error, a negative * value is returned. +* +* int bpf_hid_raw_request(void *ctx, void *buf, u64 size, u8 rtype, u8 reqtype) +* Description +* communicate with the HID device +* Return +* 0 on success. +* negative value on error. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5317,6 +5324,7 @@ union bpf_attr {FN (copy_from_user_task), \FN (hid_get_data), \FN (hid_set_data), \ +FN (hid_raw_request), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.35.1
Song Liu
reviewerRe: [PATCH bpf-next v2 19/28] bpf/hid: add bpf_hid_raw_request helper function
Quoted 38 lines · Benjamin Tissoires
When we are in a
user_eventcontext, we can talk to the device to fetch or set features/outputs/inputs reports.
Add a bpf helper to do so. This helper is thus only available touser_events, because calling this function while in IRQ context (any other BPF type) is forbidden.Signed-off-by Benjamin Tissoires <[email protected]>---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples--- include/linux/bpf-hid.h | 2 ++ include/uapi/linux/bpf.h | 8 ++++++++ kernel/bpf/hid.c | 26 ++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 8 ++++++++ 4 files changed, 44 insertions(+)include/linux/bpf-hid.h +2
-0@@ -100,6 +100,8 @@ struct bpf_hid_hooks { u64 offset, u32 n, u8 *data, u64 data_size);int (*hid_set_data)(struct hid_device *hdev,u8 *buf,size_t buf_size,u64 offset,u32 n,u8 *data,u64 data_size); +int (*hid_raw_request)(struct hid_device *hdev,u8 *buf,size_t size, +u8 rtype,u8 reqtype); };#ifdef CONFIG_BPF include/uapi/linux/bpf.h +0
-0
include/uapi/linux/bpf.h union bpf_attr { · line 5127
Quoted 7 lines
include/uapi/linux/bpf.h +4
-0@@ -5121,6 +5121,13 @@ union bpf_attr {* Return * The length of data copied into ctx->event.data. On error, a negative * value is returned. +* +* int bpf_hid_raw_request(void *ctx, void *buf, u64 size, u8 rtype, u8 reqtype) +* Description +* communicate with the HID device
I think we need more description here, e.g. what are rtype and reqtype here?
Quoted 12 lines
include/uapi/linux/bpf.h +4
-0+* Return +* 0 on success. +* negative value on error. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \@@ -5317,6 +5324,7 @@ union bpf_attr {FN (copy_from_user_task), \FN (hid_get_data), \FN (hid_set_data), \ + FN(hid_raw_request), \/* */
[...]
PATCH v2 20/28 HID: add implementation of bpf_hid_raw_request
In reply to Benjamin TissoiresHook up BPF to hid_hw_raw_request.
Not much to report here except that we need to export hid_get_report from hid-core so it gets available in hid-bpf.c
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- drivers/hid/hid-bpf.c | 63 ++++++++++++++++++++++++++++++++++++++++++ drivers/hid/hid-core.c | 3 +- include/linux/hid.h | 1 + 3 files changed, 65 insertions(+), 2 deletions(-)
drivers/hid/hid-bpf.c +63 -0
@@ -171,6 +171,68 @@ int hid_bpf_set_data(struct hid_device *hdev, u8 *buf, size_t buf_size, u64 offsreturn n; } +int hid_bpf_raw_request (struct hid_device *hdev,u8 *buf,size_t size, +u8 rtype,u8 reqtype) +{ +struct hid_report *report; +struct hid_report_enum *report_enum; +u8 *dma_data; +u32 report_len; +int ret; + +/* check arguments */ +switch (rtype) { +case HID_INPUT_REPORT : +case HID_OUTPUT_REPORT : +case HID_FEATURE_REPORT : +break ; +default : +return -EINVAL ; + } + +switch (reqtype) { +case HID_REQ_GET_REPORT : +case HID_REQ_GET_IDLE : +case HID_REQ_GET_PROTOCOL : +case HID_REQ_SET_REPORT : +case HID_REQ_SET_IDLE : +case HID_REQ_SET_PROTOCOL : +break ; +default : +return -EINVAL ; + } + +if (size <1 ) +return -EINVAL ; + + report_enum = hdev->report_enum + rtype; + report =hid_get_report (report_enum, buf); +if (!report) +return -EINVAL ; + + report_len =hid_report_len (report); + +if (size > report_len) + size = report_len; + + dma_data =kmemdup (buf, size,GFP_KERNEL ); +if (!dma_data) +return -ENOMEM ; + + ret =hid_hw_raw_request (hdev, + dma_data[0 ], + dma_data, + size, + rtype, + reqtype); + +if (ret >0 ) +memcpy (buf, dma_data, ret); + +kfree (dma_data); +return ret; +} +static int hid_bpf_run_progs (struct hid_device *hdev,enum bpf_hid_attach_type type,struct hid_bpf_ctx *ctx,u8 *data,int size) {
@@ -272,6 +334,7 @@ int __init hid_bpf_module_init(void) .array_detached = hid_bpf_array_detached, .hid_get_data = hid_bpf_get_data, .hid_set_data = hid_bpf_set_data, + .hid_raw_request = hid_bpf_raw_request, };bpf_hid_set_hooks (&hooks);
drivers/hid/hid-core.c +1 -2
@@ -1686,8 +1686,7 @@ int hid_set_field(struct hid_field *field, unsigned offset, __s32 value) }EXPORT_SYMBOL_GPL (hid_set_field); -static struct hid_report *hid_get_report (struct hid_report_enum *report_enum, -const u8 *data) +struct hid_report *hid_get_report (struct hid_report_enum *report_enum,const u8 *data) {struct hid_report *report;unsigned int n =0 ;/* Normally report number is 0 */
include/linux/hid.h +1 -0
@@ -946,6 +946,7 @@ __u32 hid_field_extract(const struct hid_device *hid, __u8 *report, unsigned offset, unsigned n);void implement (const struct hid_device *hid,u8 *report,unsigned int offset,unsigned int n,u32 value); +struct hid_report *hid_get_report (struct hid_report_enum *report_enum,const u8 *data);#ifdef CONFIG_PM int hid_driver_suspend (struct hid_device *hdev,pm_message_t state);
Signature · 1 line
2.35.1
PATCH v2 21/28 selftests/bpf: add tests for bpf_hid_hw_request
In reply to Benjamin TissoiresAdd tests for the newly implemented function.
We test here only the GET_REPORT part because the other calls are pure HID protocol and won't infer the result of the test of the bpf hook.
---
changes in v2:
- split the series by bpf/libbpf/hid/selftests and samples
--- tools/testing/selftests/bpf/prog_tests/hid.c | 71 +++++++++++++++++++- tools/testing/selftests/bpf/progs/hid.c | 57 ++++++++++++++++ 2 files changed, 127 insertions(+), 1 deletion(-)
tools/testing/selftests/bpf/prog_tests/hid.c +70 -1
@@ -67,6 +67,8 @@ static unsigned char rdesc[] = { 0xc0, /* END_COLLECTION */ }; +static u8 feature_data[] = {1 ,2 }; +static pthread_mutex_t uhid_started_mtx =PTHREAD_MUTEX_INITIALIZER ;static pthread_cond_t uhid_started =PTHREAD_COND_INITIALIZER ;
@@ -126,7 +128,7 @@ static void destroy(int fd)static int event (int fd) { -struct uhid_event ev; +struct uhid_event ev, answer;ssize_t ret;memset (&ev,0 ,sizeof (ev));
@@ -143,6 +145,8 @@ static int event(int fd)return -EFAULT ; } +memset (&answer,0 ,sizeof (answer)); +switch (ev.type) {case UHID_START :pthread_mutex_lock (&uhid_started_mtx);
@@ -167,6 +171,15 @@ static int event(int fd)break ;case UHID_GET_REPORT :fprintf (stderr,"UHID_GET_REPORT from uhid-dev\n" ); + + answer.type =UHID_GET_REPORT_REPLY ; + answer.u.get_report_reply.id = ev.u.get_report.id; + answer.u.get_report_reply.err = ev.u.get_report.rnum ==1 ?0 : -EIO ; + answer.u.get_report_reply.size =sizeof (feature_data); +memcpy (answer.u.get_report_reply.data, feature_data,sizeof (feature_data)); + +uhid_write (fd, &answer); +break ;case UHID_SET_REPORT :fprintf (stderr,"UHID_SET_REPORT from uhid-dev\n" );
@@ -516,6 +529,59 @@ static int test_hid_user_call(struct hid *hid_skel, int uhid_fd, int sysfs_fd)return ret; } +/* +* Attach hid_user_raw_request to the given uhid device, +* call the bpf program from userspace +* check that the program is called and does the expected. +*/ +static int test_hid_user_raw_request_call (struct hid *hid_skel,int uhid_fd,int sysfs_fd) +{ +int err, prog_fd; +u8 buf[10 ] = {0 }; +int ret =-1 ; + +LIBBPF_OPTS (bpf_test_run_opts, run_attrs, + .repeat = 1, + .ctx_in = &sysfs_fd, + .ctx_size_in = sizeof(sysfs_fd), + .data_in = buf, + .data_size_in = sizeof(buf), + .data_out = buf, + .data_size_out = sizeof(buf), + ); + +/* attach hid_user_raw_request program */ + hid_skel->links.hid_user_raw_request = +bpf_program__attach_hid (hid_skel->progs.hid_user_raw_request, sysfs_fd); +if (!ASSERT_OK_PTR (hid_skel->links.hid_user_raw_request, +"attach_hid(hid_user_raw_request)" )) +return PTR_ERR (hid_skel->links.hid_user_raw_request); + + buf[0 ] =2 ;/* HID_FEATURE_REPORT */ + buf[1 ] =1 ;/* HID_REQ_GET_REPORT */ + buf[2 ] =1 ;/* report ID */ + + prog_fd =bpf_program__fd (hid_skel->progs.hid_user_raw_request); + + err =bpf_prog_test_run_opts (prog_fd, &run_attrs); +if (!ASSERT_EQ (err,0 ,"bpf_prog_test_run_xattr" )) + goto cleanup; + +if (!ASSERT_EQ (run_attrs.retval,2 ,"bpf_prog_test_run_xattr_retval" )) + goto cleanup; + +if (!ASSERT_EQ (buf[3 ],2 ,"hid_user_raw_request_check_in" )) + goto cleanup; + + ret =0 ; + +cleanup: + +hid__detach (hid_skel); + +return ret; +} +/* * Attach hid_rdesc_fixup to the given uhid device, * retrieve and open the matching hidraw node,
@@ -626,6 +692,9 @@ void serial_test_hid_bpf(void) err =test_hid_user_call (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_user" ); + err =test_hid_user_raw_request_call (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid_user_raw_request" ); + err =test_rdesc_fixup (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_rdesc_fixup" );
tools/testing/selftests/bpf/progs/hid.c +57 -0
66 lines not on this page · raw message
Signature · 1 line
2.35.1
PATCH v2 22/28 bpf/verifier: prevent non GPL programs to be loaded against HID
In reply to Benjamin TissoiresThis is just to hammer the obvious because I suspect you can not already load a bpf HID program which is not GPL because all of the useful functions are GPL only.
Anyway, this ensures that users are not tempted to bypass this requirement and will allow us to ship tested BPF programs in the kernel without having to aorry about the license.
---
new in v2:
- Note: I placed this statement in check_attach_btf_id() to be local to other similar checks (regarding LSM), however, I have no idea if this is the correct place. Please shout at me if it isn't.
--- include/linux/bpf-hid.h | 8 ++++++++ kernel/bpf/hid.c | 12 ++++++++++++ kernel/bpf/verifier.c | 7 +++++++ 3 files changed, 27 insertions(+)
include/linux/bpf-hid.h +8 -0
@@ -2,6 +2,7 @@#ifndef _BPF_HID_H#define _BPF_HID_H +#include <linux/bpf_verifier.h> #include <linux/mutex.h> #include <uapi/linux/bpf.h> #include <uapi/linux/bpf_hid.h>
@@ -71,6 +72,8 @@ int bpf_hid_prog_query(const union bpf_attr *attr, union bpf_attr __user *uattr);int bpf_hid_link_create (const union bpf_attr *attr,struct bpf_prog *prog); +int bpf_hid_verify_prog (struct bpf_verifier_log *vlog, +const struct bpf_prog *prog);#else static inline int bpf_hid_prog_query (const union bpf_attr *attr,union bpf_attr __user *uattr)
@@ -83,6 +86,11 @@ static inline int bpf_hid_link_create(const union bpf_attr *attr, {return -EOPNOTSUPP ; } +static inline int bpf_hid_verify_prog (struct bpf_verifier_log *vlog, +const struct bpf_prog *prog) +{ +return -EOPNOTSUPP ; +}#endif static inline bool bpf_hid_link_empty(struct bpf_hid *bpf,
kernel/bpf/hid.c +12 -0
@@ -37,6 +37,18 @@ void bpf_hid_set_hooks(struct bpf_hid_hooks *hooks) }EXPORT_SYMBOL_GPL (bpf_hid_set_hooks); +int bpf_hid_verify_prog (struct bpf_verifier_log *vlog, +const struct bpf_prog *prog) +{ +if (!prog->gpl_compatible) { +bpf_log (vlog, +"HID programs must have a GPL compatible license\n" ); +return -EINVAL ; + } + +return 0 ; +} + BPF_CALL_5(bpf_hid_get_data, void*, ctx, u64, offset, u32, n, void*, data, u64, size) {struct hid_bpf_ctx *bpf_ctx = ctx;
kernel/bpf/verifier.c +7 -0
@@ -21,6 +21,7 @@#include <linux/perf_event.h> #include <linux/ctype.h> #include <linux/error-injection.h> +#include <linux/bpf-hid.h> #include <linux/bpf_lsm.h> #include <linux/btf_ids.h>
@@ -14235,6 +14236,12 @@ static int check_attach_btf_id(struct bpf_verifier_env *env)if (prog->type ==BPF_PROG_TYPE_STRUCT_OPS )return check_struct_ops_btf_id (env); +if (prog->type ==BPF_PROG_TYPE_HID ) { + ret =bpf_hid_verify_prog (&env->log, prog); +if (ret <0 ) +return ret; + } +if (prog->type !=BPF_PROG_TYPE_TRACING && prog->type !=BPF_PROG_TYPE_LSM && prog->type !=BPF_PROG_TYPE_EXT )
Signature · 1 line
2.35.1
PATCH v2 23/28 HID: bpf: compute only the required buffer size for the device
In reply to Benjamin TissoiresThere is no point in using 16 kB of memory if the device needs less for all of its reports (uwhich is usually the case).
---
new in v2
--- drivers/hid/hid-bpf.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/hid/hid-bpf.c +14 -1
@@ -61,11 +61,24 @@ static int hid_reconnect(struct hid_device *hdev)static int hid_bpf_link_attach (struct hid_device *hdev,enum bpf_hid_attach_type type) {int err =0 ; +unsigned int i, j, max_report_len =0 ; + +/* compute the maximum report length for this device */ +for (i =0 ; i <HID_REPORT_TYPES ; i++) { +struct hid_report_enum *report_enum = hdev->report_enum + i; + +for (j =0 ; j <HID_MAX_IDS ; j++) { +struct hid_report *report = report_enum->report_id_hash[j]; + +if (report) + max_report_len =max (max_report_len,hid_report_len (report)); + } + }switch (type) {case BPF_HID_ATTACH_DEVICE_EVENT :if (!hdev->bpf.ctx) { - hdev->bpf.ctx =bpf_hid_allocate_ctx (hdev,HID_BPF_MAX_BUFFER_SIZE ); + hdev->bpf.ctx =bpf_hid_allocate_ctx (hdev, max_report_len);if (IS_ERR (hdev->bpf.ctx)) { err =PTR_ERR (hdev->bpf.ctx); hdev->bpf.ctx =NULL ;
Signature · 1 line
2.35.1
PATCH v2 24/28 HID: bpf: only call hid_bpf_raw_event() if a ctx is available
In reply to Benjamin Tissoiresthe context is allocated the first time a program of type DEVICE_EVENT is attached to the device. To not add too much jumps in the code for the general device handling, call hid_bpf_raw_event() only if we know that a program has been attached once during the life of the device.
---
new in v2
--- drivers/hid/hid-core.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
drivers/hid/hid-core.c +7 -4
@@ -1751,10 +1751,13 @@ int hid_report_raw_event(struct hid_device *hid, int type, u8 *data, u32 size,u8 *cdata;int ret =0 ; - data =hid_bpf_raw_event (hid, data, &size); -if (IS_ERR (data)) { - ret =PTR_ERR (data); - goto out; +/* we pre-test if ctx is available here to cut the calls at the earliest */ +if (hid->bpf.ctx) { + data =hid_bpf_raw_event (hid, data, &size); +if (IS_ERR (data)) { + ret =PTR_ERR (data); + goto out; + } } report =hid_get_report (report_enum, data);
Signature · 1 line
2.35.1
PATCH v2 25/28 bpf/hid: Add a flag to add the program at the beginning of the list
In reply to Benjamin TissoiresWhen tracing the incoming events, if a bpf program is already loaded, the next bpf program will see the potentially changed data.
Add a flag to BPF_LINK_CREATE that allows to chose the position of the inserted program: at the beginning or at the end.
This way, we can have a tracing program that compare the raw event from the device and the transformed stream from all the other bpf programs.
---
new in v2
--- include/uapi/linux/bpf.h | 10 ++++++++++ kernel/bpf/hid.c | 11 +++++++---- 2 files changed, 17 insertions(+), 4 deletions(-)
include/uapi/linux/bpf.h +10 -0
@@ -1123,6 +1123,16 @@ enum bpf_link_type {*/ #define BPF_F_XDP_HAS_FRAGS (1U << 5) +/* HID flag used in BPF_LINK_CREATE command +* +* NONE(default): The bpf program will be added at the tail of the list +* of existing bpf program for this type. +* +* BPF_F_INSERT_HEAD: The bpf program will be added at the beginning +* of the list of existing bpf program for this type.. +*/ +#define BPF_F_INSERT_HEAD (1U << 0) +/* When BPF ldimm64's insn[0].src_reg != 0 then this can have * the following extensions: *
kernel/bpf/hid.c +7 -4
@@ -416,7 +416,7 @@ static int bpf_hid_max_progs(enum bpf_hid_attach_type type) }static int bpf_hid_link_attach (struct hid_device *hdev,struct bpf_link *link, -enum bpf_hid_attach_type type) +enum bpf_hid_attach_type type,u32 flags) {struct bpf_hid_link *hid_link = container_of(link, struct bpf_hid_link, link);
@@ -443,7 +443,10 @@ static int bpf_hid_link_attach(struct hid_device *hdev, struct bpf_link *link, goto out_unlock; } -list_add_tail (&hid_link->node, &hdev->bpf.links[type]); +if (flags &BPF_F_INSERT_HEAD ) +list_add (&hid_link->node, &hdev->bpf.links[type]); +else +list_add_tail (&hid_link->node, &hdev->bpf.links[type]);fill_prog_array (hdev, type, run_array); run_array = rcu_replace_pointer(hdev->bpf.run_array[type], run_array,
@@ -467,7 +470,7 @@ int bpf_hid_link_create(const union bpf_attr *attr, struct bpf_prog *prog)struct hid_device *hdev;int err; -if (attr->link_create.flags || !hid_hooks.hdev_from_fd) +if ((attr->link_create.flags & ~BPF_F_INSERT_HEAD ) || !hid_hooks.hdev_from_fd)return -EINVAL ; type = attr->link_create.attach_type;
@@ -495,7 +498,7 @@ int bpf_hid_link_create(const union bpf_attr *attr, struct bpf_prog *prog)return err; } - err =bpf_hid_link_attach (hdev, &hid_link->link, hid_type); + err =bpf_hid_link_attach (hdev, &hid_link->link, hid_type, attr->link_create.flags);if (err) {bpf_link_cleanup (&link_primer);return err;
Signature · 1 line
2.35.1
PATCH v2 26/28 libbpf: add handling for BPF_F_INSERT_HEAD in HID programs
In reply to Benjamin TissoiresExport the newly created flag to libbpf.
---
new in v2
--- tools/include/uapi/linux/bpf.h | 10 ++++++++++ tools/lib/bpf/libbpf.c | 17 +++++++++-------- tools/lib/bpf/libbpf.h | 2 +- 3 files changed, 20 insertions(+), 9 deletions(-)
tools/include/uapi/linux/bpf.h +10 -0
@@ -1123,6 +1123,16 @@ enum bpf_link_type {*/ #define BPF_F_XDP_HAS_FRAGS (1U << 5) +/* HID flag used in BPF_LINK_CREATE command +* +* NONE(default): The bpf program will be added at the tail of the list +* of existing bpf program for this type. +* +* BPF_F_INSERT_HEAD: The bpf program will be added at the beginning +* of the list of existing bpf program for this type.. +*/ +#define BPF_F_INSERT_HEAD (1U << 0) +/* When BPF ldimm64's insn[0].src_reg != 0 then this can have * the following extensions: *
tools/lib/bpf/libbpf.c +9 -8
@@ -10533,10 +10533,11 @@ static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie)static struct bpf_link *bpf_program__attach_fd (const struct bpf_program *prog,int target_fd,int btf_id, -const char *target_name) +const char *target_name,__u32 flags) {DECLARE_LIBBPF_OPTS (bpf_link_create_opts, opts, - .target_btf_id = btf_id); + .target_btf_id = btf_id, + .flags = flags);enum bpf_attach_type attach_type;char errmsg[STRERR_BUFSIZE ];struct bpf_link *link;
@@ -10570,19 +10571,19 @@ bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_idstruct bpf_link *bpf_program__attach_cgroup (const struct bpf_program *prog,int cgroup_fd) { -return bpf_program__attach_fd (prog, cgroup_fd,0 ,"cgroup" ); +return bpf_program__attach_fd (prog, cgroup_fd,0 ,"cgroup" ,0 ); }struct bpf_link *bpf_program__attach_netns (const struct bpf_program *prog,int netns_fd) { -return bpf_program__attach_fd (prog, netns_fd,0 ,"netns" ); +return bpf_program__attach_fd (prog, netns_fd,0 ,"netns" ,0 ); }struct bpf_link *bpf_program__attach_xdp (const struct bpf_program *prog,int ifindex) {/* target_fd/target_ifindex use the same field in LINK_CREATE */ -return bpf_program__attach_fd (prog, ifindex,0 ,"xdp" ); +return bpf_program__attach_fd (prog, ifindex,0 ,"xdp" ,0 ); } struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
@@ -10608,7 +10609,7 @@ struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,if (btf_id <0 )return libbpf_err_ptr (btf_id); -return bpf_program__attach_fd (prog, target_fd, btf_id,"freplace" ); +return bpf_program__attach_fd (prog, target_fd, btf_id,"freplace" ,0 ); }else {/* no target, so use raw_tracepoint_open for compatibility * with old kernels
@@ -10663,9 +10664,9 @@ static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie) }struct bpf_link * -bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd) +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd,__u32 flags) { -return bpf_program__attach_fd (prog, hid_fd,0 ,"hid" ); +return bpf_program__attach_fd (prog, hid_fd,0 ,"hid" , flags); }struct bpf_link *bpf_program__attach (const struct bpf_program *prog)
tools/lib/bpf/libbpf.h +1 -1
@@ -530,7 +530,7 @@ LIBBPF_API struct bpf_link * bpf_program__attach_iter(const struct bpf_program *prog, const struct bpf_iter_attach_opts *opts); LIBBPF_API struct bpf_link * -bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd); +bpf_program__attach_hid (const struct bpf_program *prog,int hid_fd,__u32 flags);/* * Libbpf allows callers to adjust BPF programs before being loaded
Signature · 1 line
2.35.1
PATCH v2 27/28 selftests/bpf: Add a test for BPF_F_INSERT_HEAD
In reply to Benjamin TissoiresInsert 3 programs to check that we are doing the correct thing:
'2', '1', '3' are inserted, but '1' is supposed to be executed first.
---
new in v2
--- tools/testing/selftests/bpf/prog_tests/hid.c | 90 ++++++++++++++++++-- tools/testing/selftests/bpf/progs/hid.c | 36 ++++++++ 2 files changed, 121 insertions(+), 5 deletions(-)
tools/testing/selftests/bpf/prog_tests/hid.c +85 -5
@@ -353,7 +353,7 @@ static int test_hid_raw_event(struct hid *hid_skel, int uhid_fd, int sysfs_fd)/* attach the first program */ hid_skel->links.hid_first_event = -bpf_program__attach_hid (hid_skel->progs.hid_first_event, sysfs_fd); +bpf_program__attach_hid (hid_skel->progs.hid_first_event, sysfs_fd,0 );if (!ASSERT_OK_PTR (hid_skel->links.hid_first_event,"attach_hid(hid_first_event)" ))return PTR_ERR (hid_skel->links.hid_first_event);
@@ -429,7 +429,7 @@ static int test_hid_set_get_data(struct hid *hid_skel, int uhid_fd, int sysfs_fd/* attach hid_set_get_data program */ hid_skel->links.hid_set_get_data = -bpf_program__attach_hid (hid_skel->progs.hid_set_get_data, sysfs_fd); +bpf_program__attach_hid (hid_skel->progs.hid_set_get_data, sysfs_fd,0 );if (!ASSERT_OK_PTR (hid_skel->links.hid_set_get_data,"attach_hid(hid_set_get_data)" ))return PTR_ERR (hid_skel->links.hid_set_get_data);
@@ -498,7 +498,7 @@ static int test_hid_user_call(struct hid *hid_skel, int uhid_fd, int sysfs_fd) );/* attach hid_user program */ - hid_skel->links.hid_user =bpf_program__attach_hid (hid_skel->progs.hid_user, sysfs_fd); + hid_skel->links.hid_user =bpf_program__attach_hid (hid_skel->progs.hid_user, sysfs_fd,0 );if (!ASSERT_OK_PTR (hid_skel->links.hid_user,"attach_hid(hid_user)" ))return PTR_ERR (hid_skel->links.hid_user);
@@ -552,7 +552,7 @@ static int test_hid_user_raw_request_call(struct hid *hid_skel, int uhid_fd, int/* attach hid_user_raw_request program */ hid_skel->links.hid_user_raw_request = -bpf_program__attach_hid (hid_skel->progs.hid_user_raw_request, sysfs_fd); +bpf_program__attach_hid (hid_skel->progs.hid_user_raw_request, sysfs_fd,0 );if (!ASSERT_OK_PTR (hid_skel->links.hid_user_raw_request,"attach_hid(hid_user_raw_request)" ))return PTR_ERR (hid_skel->links.hid_user_raw_request);
@@ -582,6 +582,83 @@ static int test_hid_user_raw_request_call(struct hid *hid_skel, int uhid_fd, intreturn ret; } +/* +* Attach hid_insert{0,1,2} to the given uhid device, +* retrieve and open the matching hidraw node, +* inject one event in the uhid device, +* check that the programs have been inserted in the correct order. +*/ +static int test_hid_attach_flags (struct hid *hid_skel,int uhid_fd,int sysfs_fd) +{ +int err, hidraw_ino, hidraw_fd =-1 ; +char hidraw_path[64 ] = {0 }; +u8 buf[10 ] = {0 }; +int ret =-1 ; + +/* attach hid_test_insert2 program */ + hid_skel->links.hid_test_insert2 = +bpf_program__attach_hid (hid_skel->progs.hid_test_insert2, sysfs_fd,0 ); +if (!ASSERT_OK_PTR (hid_skel->links.hid_test_insert2, +"attach_hid(hid_test_insert2)" )) +return PTR_ERR (hid_skel->links.hid_test_insert2); + +/* then attach hid_test_insert1 program before the previous*/ + hid_skel->links.hid_test_insert1 = +bpf_program__attach_hid (hid_skel->progs.hid_test_insert1, + sysfs_fd, +BPF_F_INSERT_HEAD ); +if (!ASSERT_OK_PTR (hid_skel->links.hid_test_insert1, +"attach_hid(hid_test_insert1)" )) +return PTR_ERR (hid_skel->links.hid_test_insert1); + +/* finally attach hid_test_insert3 at the end */ + hid_skel->links.hid_test_insert3 = +bpf_program__attach_hid (hid_skel->progs.hid_test_insert3, sysfs_fd,0 ); +if (!ASSERT_OK_PTR (hid_skel->links.hid_test_insert3, +"attach_hid(hid_test_insert3)" )) +return PTR_ERR (hid_skel->links.hid_test_insert3); + + hidraw_ino =get_hidraw (hid_skel->links.hid_test_insert1); +if (!ASSERT_GE (hidraw_ino,0 ,"get_hidraw" )) + goto cleanup; + +/* open hidraw node to check the other side of the pipe */ +sprintf (hidraw_path,"/dev/hidraw%d" , hidraw_ino); + hidraw_fd =open (hidraw_path,O_RDWR |O_NONBLOCK ); + +if (!ASSERT_GE (hidraw_fd,0 ,"open_hidraw" )) + goto cleanup; + +/* inject one event */ + buf[0 ] =1 ; +send_event (uhid_fd, buf,6 ); + +/* read the data from hidraw */ +memset (buf,0 ,sizeof (buf)); + err =read (hidraw_fd, buf,sizeof (buf)); +if (!ASSERT_EQ (err,6 ,"read_hidraw" )) + goto cleanup; + +if (!ASSERT_EQ (buf[1 ],1 ,"hid_test_insert1" )) + goto cleanup; + +if (!ASSERT_EQ (buf[2 ],2 ,"hid_test_insert2" )) + goto cleanup; + +if (!ASSERT_EQ (buf[3 ],3 ,"hid_test_insert3" )) + goto cleanup; + + ret =0 ; + +cleanup: +if (hidraw_fd >=0 ) +close (hidraw_fd); + +hid__detach (hid_skel); + +return ret; +} +/* * Attach hid_rdesc_fixup to the given uhid device, * retrieve and open the matching hidraw node,
@@ -598,7 +675,7 @@ static int test_rdesc_fixup(struct hid *hid_skel, int uhid_fd, int sysfs_fd)/* attach the program */ hid_skel->links.hid_rdesc_fixup = -bpf_program__attach_hid (hid_skel->progs.hid_rdesc_fixup, sysfs_fd); +bpf_program__attach_hid (hid_skel->progs.hid_rdesc_fixup, sysfs_fd,0 );if (!ASSERT_OK_PTR (hid_skel->links.hid_rdesc_fixup,"attach_hid(hid_rdesc_fixup)" ))return PTR_ERR (hid_skel->links.hid_rdesc_fixup);
@@ -695,6 +772,9 @@ void serial_test_hid_bpf(void) err =test_hid_user_raw_request_call (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_user_raw_request" ); + err =test_hid_attach_flags (hid_skel, uhid_fd, sysfs_fd); +ASSERT_OK (err,"hid_user_raw_request" ); + err =test_rdesc_fixup (hid_skel, uhid_fd, sysfs_fd);ASSERT_OK (err,"hid_rdesc_fixup" );
tools/testing/selftests/bpf/progs/hid.c +36 -0
@@ -178,3 +178,39 @@ int hid_user_raw_request(struct hid_bpf_ctx *ctx)return ret; } + +SEC("hid/device_event") +int hid_test_insert1 (struct hid_bpf_ctx *ctx) +{ +/* we need to be run first */ +if (ctx->data[2 ] || ctx->data[3 ]) +return -1 ; + + ctx->data[1 ] =1 ; + +return 0 ; +} + +SEC("hid/device_event") +int hid_test_insert2 (struct hid_bpf_ctx *ctx) +{ +/* after insert0 and before insert2 */ +if (!ctx->data[1 ] || ctx->data[3 ]) +return -1 ; + + ctx->data[2 ] =2 ; + +return 0 ; +} + +SEC("hid/device_event") +int hid_test_insert3 (struct hid_bpf_ctx *ctx) +{ +/* at the end */ +if (!ctx->data[1 ] || !ctx->data[2 ]) +return -1 ; + + ctx->data[3 ] =3 ; + +return 0 ; +}
Signature · 1 line
2.35.1
PATCH v2 28/28 samples/bpf: fix bpf_program__attach_hid() api change
In reply to Benjamin TissoiresAdd the new flag parameter.
---
new in v2
--- samples/bpf/hid_mouse_user.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
samples/bpf/hid_mouse_user.c +1 -1
@@ -98,7 +98,7 @@ int main(int argc, char **argv)bpf_object__for_each_program (prog, obj) { progs[prog_count].fd =bpf_program__fd (prog); progs[prog_count].type =bpf_program__get_expected_attach_type (prog); - progs[prog_count].link =bpf_program__attach_hid (prog, sysfs_fd); + progs[prog_count].link =bpf_program__attach_hid (prog, sysfs_fd,0 );if (libbpf_get_error (progs[prog_count].link)) {fprintf (stderr,"bpf_prog_attach: err=%m\n" ); progs[prog_count].fd =0 ;
Signature · 1 line
2.35.1
Song Liu
reviewerQuoted 51 lines · Benjamin Tissoires
Hi,
This is a followup of my v1 at [0].
The short summary of the previous cover letter and discussions is that HID could benefit from BPF for the following use cases:
- simple fixup of report descriptor:
benefits are faster development time and testing, with the produced bpf program being shipped in the kernel directly (the shipping part is *not* addressed here).- Universal Stylus Interface:
allows a user-space program to define its own kernel interface- Surface Dial:
somehow similar to the previous one except that userspace can decide to change the shape of the exported device- firewall:
still partly missing there, there is not yet interception of hidraw calls, but it's coming in a followup series, I promise- tracing:
well, tracing.I tried to address as many comments as I could and here is the short log of changes:
v2:
===- split the series by subsystem (bpf, HID, libbpf, selftests and samples)
- Added an extra patch at the beginning to not require
CAP_NET_ADMINforBPF_PROG_TYPE_LIRC_MODE2(please shout if this is wrong)- made the bpf context attached to HID program of dynamic size:
* the first 1 kB will be able to be addressed directly
* the rest can be retrieved through bpf_hid_{set|get}_data (note that I am definitivey not happy with that API, because there is part of it in bits and other in bytes. ouch)- added an extra patch to prevent non GPL HID bpf programs to be loaded of type
BPF_PROG_TYPE_HID
* same here, not really happy but I don't know where to put that check inverifier.c
Quoted 9 lines
- added a new flag
BPF_F_INSERT_HEADforBPF_LINK_CREATEsyscall when in used with HID program types.
* this flag is used for tracing, to be able to load a program before any others that might already have been inserted and that might change the data stream.Cheers,
Benjamin
The set looks good so far. I will review the rest later.
[...]
A quick note about how we organize these patches. Maybe we can merge some of these patches like:
Quoted 3 lines
bpf: introduce hid program type
bpf/hid: add a new attach type to change the report descriptor bpf/hid: add new BPF type to trigger commands from userspace
I guess the three can merge into one.
Quoted 4 lines
HID: hook up with bpf
HID: allow to change the report descriptor from an eBPF program
HID: bpf: compute only the required buffer size for the device
HID: bpf: only callhid_bpf_raw_event()if a ctx is available
I haven't read through all of them, but I guess they can probably merge as well.
Quoted 3 lines
libbpf: add HID program type and API
libbpf: add new attach typeBPF_HID_RDESC_FIXUP
libbpf: add new attach typeBPF_HID_USER_EVENT
There 3 can merge, and maybe also the one below
Quoted 5 lines
libbpf: add handling for
BPF_F_INSERT_HEADin HID programs
samples/bpf: add newhid_mouseexamplesamples/bpf: add a report descriptor fixupsamples/bpf: fixbpf_program__attach_hid()api change
Maybe it makes sense to merge these 3?
Quoted 4 lines
bpf/hid: add hid_{get|set}_data helpers
HID: bpf: implement hid_bpf_get|set_data bpf/hid: addbpf_hid_raw_requesthelper function
HID: add implementation ofbpf_hid_raw_request
We can have 1 or 2 patches for these helpers
Quoted 8 lines
selftests/bpf: add tests for the HID-bpf initial implementation selftests/bpf: add report descriptor fixup tests selftests/bpf: add tests for hid_{get|set}_data helpers selftests/bpf: add test for user call of HID bpf programs selftests/bpf: hid: rely on uhid event to know if a test device is
ready
selftests/bpf: add tests forbpf_hid_hw_requestselftests/bpf: Add a test forBPF_F_INSERT_HEAD
These selftests could also merge into 1 or 2 patches I guess.
I understand rearranging these patches may take quite some effort. But I do feel that's a cleaner approach (from someone doesn't know much about HID). If you really hate it that way, we can discuss...
Thanks,
Song
Hi Song,
Thanks a lot for the review.
I'll comment on the review in more details next week, but I have a quick question here:
Quoted 64 lines · Song Liu
Quoted 51 lines · Benjamin Tissoires
Hi,
This is a followup of my v1 at [0].
The short summary of the previous cover letter and discussions is that HID could benefit from BPF for the following use cases:
- simple fixup of report descriptor:
benefits are faster development time and testing, with the produced bpf program being shipped in the kernel directly (the shipping part is *not* addressed here).- Universal Stylus Interface:
allows a user-space program to define its own kernel interface- Surface Dial:
somehow similar to the previous one except that userspace can decide to change the shape of the exported device- firewall:
still partly missing there, there is not yet interception of hidraw calls, but it's coming in a followup series, I promise- tracing:
well, tracing.I tried to address as many comments as I could and here is the short log of changes:
v2:
===- split the series by subsystem (bpf, HID, libbpf, selftests and samples)
- Added an extra patch at the beginning to not require
CAP_NET_ADMINforBPF_PROG_TYPE_LIRC_MODE2(please shout if this is wrong)- made the bpf context attached to HID program of dynamic size:
* the first 1 kB will be able to be addressed directly
* the rest can be retrieved through bpf_hid_{set|get}_data (note that I am definitivey not happy with that API, because there is part of it in bits and other in bytes. ouch)- added an extra patch to prevent non GPL HID bpf programs to be loaded of type
BPF_PROG_TYPE_HID
* same here, not really happy but I don't know where to put that check inverifier.cQuoted 9 lines
- added a new flag
BPF_F_INSERT_HEADforBPF_LINK_CREATEsyscall when in used with HID program types.
* this flag is used for tracing, to be able to load a program before any others that might already have been inserted and that might change the data stream.Cheers,
Benjamin
Quoted 6 lines
The set looks good so far. I will review the rest later.
[...]
A quick note about how we organize these patches. Maybe we can merge some of these patches like:
Just to be sure we are talking about the same thing: you mean squash the patch together?
Quoted 4 lines
Quoted 4 lines
bpf: introduce hid program type
bpf/hid: add a new attach type to change the report descriptor bpf/hid: add new BPF type to trigger commands from userspace
Quoted 8 lines
I guess the three can merge into one.
Quoted 4 lines
HID: hook up with bpf
HID: allow to change the report descriptor from an eBPF program
HID: bpf: compute only the required buffer size for the device
HID: bpf: only callhid_bpf_raw_event()if a ctx is availableI haven't read through all of them, but I guess they can probably merge as well.
There are certainly patches that we could squash together (3 and 4 from this list into the previous ones), but I'd like to keep some sort of granularity here to not have a patch bomb that gets harder to come back later.
Quoted 6 lines
Quoted 4 lines
libbpf: add HID program type and API
libbpf: add new attach typeBPF_HID_RDESC_FIXUP
libbpf: add new attach typeBPF_HID_USER_EVENTThere 3 can merge, and maybe also the one below
Quoted 1 line
libbpf: add handling for
BPF_F_INSERT_HEADin HID programs
Yeah, the libbpf changes are small enough to not really justify separate patches.
Quoted 5 lines
Quoted 4 lines
samples/bpf: add newhid_mouseexamplesamples/bpf: add a report descriptor fixupsamples/bpf: fixbpf_program__attach_hid()api changeMaybe it makes sense to merge these 3?
Sure, why not.
Quoted 6 lines
Quoted 5 lines
bpf/hid: add hid_{get|set}_data helpers
HID: bpf: implement hid_bpf_get|set_data bpf/hid: addbpf_hid_raw_requesthelper function
HID: add implementation ofbpf_hid_raw_requestWe can have 1 or 2 patches for these helpers
OK, the patches should be self-contained enough.
Quoted 10 lines
Quoted 9 lines
selftests/bpf: add tests for the HID-bpf initial implementation selftests/bpf: add report descriptor fixup tests selftests/bpf: add tests for hid_{get|set}_data helpers selftests/bpf: add test for user call of HID bpf programs selftests/bpf: hid: rely on uhid event to know if a test device is
ready
selftests/bpf: add tests forbpf_hid_hw_requestselftests/bpf: Add a test forBPF_F_INSERT_HEADThese selftests could also merge into 1 or 2 patches I guess.
I'd still like to link them to the granularity of the bpf changes, so I can refer a selftest change to a specific commit/functionality added. But that's just my personal taste, and I can be convinced otherwise. This should give us maybe 4 patches instead of 7.
Quoted 5 lines
I understand rearranging these patches may take quite some effort. But I do feel that's a cleaner approach (from someone doesn't know much about HID). If you really hate it that way, we can discuss...
No worries. I don't mind iterating on the series. IIRC I already rewrote it twice from scratch, and that's when the selftests I introduced in the second rewrite were tremendously helpful :) And honestly I don't think it'll be too much effort to reorder/squash the patches given that the v2 is *very* granular.
Anyway, I prefer having the reviewers happy so we can have a solid rock API from day 1 than keeping it obscure for everyone and having to deal with design issues forever. So if it takes 10 or 20 revisions to have everybody on the same page, that's fine with me (not that I want to have that many revisions, just that I won't be afraid of the bikeshedding we might have at some point).
Cheers,
Benjamin
Song Liu
reviewerQuoted 11 lines · Benjamin Tissoires
Quoted 8 lines
Quoted 1 line
The set looks good so far. I will review the rest later.
[...]
A quick note about how we organize these patches. Maybe we can merge some of these patches like:
Just to be sure we are talking about the same thing: you mean squash the patch together?
Right, squash some patches together.
Quoted 11 lines
Quoted 11 lines
Quoted 5 lines
bpf: introduce hid program type
bpf/hid: add a new attach type to change the report descriptor bpf/hid: add new BPF type to trigger commands from userspaceI guess the three can merge into one.
Quoted 4 lines
HID: hook up with bpf
HID: allow to change the report descriptor from an eBPF program
HID: bpf: compute only the required buffer size for the device
HID: bpf: only callhid_bpf_raw_event()if a ctx is available
Quoted 7 lines
Quoted 2 lines
I haven't read through all of them, but I guess they can probably merge as well.
There are certainly patches that we could squash together (3 and 4 from this list into the previous ones), but I'd like to keep some sort of granularity here to not have a patch bomb that gets harder to come back later.
Totally agreed with the granularity of patches. I am not a big fan of patch bombs either. :)
I guess the problem I have with the current version is that I don't have a big picture of the design while reading through relatively big patches. A overview with the following information in the cover letter would be really help here:
1. How different types of programs are triggered (IRQ, user input, etc.);
2. What are the operations and/or outcomes of these programs;
3. How would programs of different types (or attach types) interact with each other (via bpf maps? chaining?)
4. What's the new uapi;
5. New helpers and other logistics
Sometimes, I find the changes to uapi are the key for me to understand the patches, and I would like to see one or two patches with all the UAPI changes (i.e. bpf_hid_attach_type). However, that may or may not apply to this set due to granularity concerns.
Does this make sense?
Thanks,
Song
Quoted 66 lines
Quoted 7 lines
Quoted 5 lines
libbpf: add HID program type and API
libbpf: add new attach typeBPF_HID_RDESC_FIXUP
libbpf: add new attach typeBPF_HID_USER_EVENTThere 3 can merge, and maybe also the one below
Quoted 1 line
libbpf: add handling for
BPF_F_INSERT_HEADin HID programsYeah, the libbpf changes are small enough to not really justify separate patches.
Quoted 5 lines
Quoted 4 lines
samples/bpf: add newhid_mouseexamplesamples/bpf: add a report descriptor fixupsamples/bpf: fixbpf_program__attach_hid()api changeMaybe it makes sense to merge these 3?
Sure, why not.
Quoted 6 lines
Quoted 5 lines
bpf/hid: add hid_{get|set}_data helpers
HID: bpf: implement hid_bpf_get|set_data bpf/hid: addbpf_hid_raw_requesthelper function
HID: add implementation ofbpf_hid_raw_requestWe can have 1 or 2 patches for these helpers
OK, the patches should be self-contained enough.
Quoted 10 lines
Quoted 9 lines
selftests/bpf: add tests for the HID-bpf initial implementation selftests/bpf: add report descriptor fixup tests selftests/bpf: add tests for hid_{get|set}_data helpers selftests/bpf: add test for user call of HID bpf programs selftests/bpf: hid: rely on uhid event to know if a test device is
ready
selftests/bpf: add tests forbpf_hid_hw_requestselftests/bpf: Add a test forBPF_F_INSERT_HEADThese selftests could also merge into 1 or 2 patches I guess.
I'd still like to link them to the granularity of the bpf changes, so I can refer a selftest change to a specific commit/functionality added. But that's just my personal taste, and I can be convinced otherwise. This should give us maybe 4 patches instead of 7.
Quoted 5 lines
I understand rearranging these patches may take quite some effort. But I do feel that's a cleaner approach (from someone doesn't know much about HID). If you really hate it that way, we can discuss...
No worries. I don't mind iterating on the series. IIRC I already rewrote it twice from scratch, and that's when the selftests I introduced in the second rewrite were tremendously helpful :) And honestly I don't think it'll be too much effort to reorder/squash the patches given that the v2 is *very* granular.
Anyway, I prefer having the reviewers happy so we can have a solid rock API from day 1 than keeping it obscure for everyone and having to deal with design issues forever. So if it takes 10 or 20 revisions to have everybody on the same page, that's fine with me (not that I want to have that many revisions, just that I won't be afraid of the bikeshedding we might have at some point).
Cheers,
Benjamin
Quoted 50 lines · Song Liu
Quoted 11 lines · Benjamin Tissoires
Quoted 8 lines
Quoted 1 line
The set looks good so far. I will review the rest later.
[...]
A quick note about how we organize these patches. Maybe we can merge some of these patches like:
Just to be sure we are talking about the same thing: you mean squash the patch together?
Right, squash some patches together.
Quoted 11 lines
Quoted 11 lines
Quoted 5 lines
bpf: introduce hid program type
bpf/hid: add a new attach type to change the report descriptor bpf/hid: add new BPF type to trigger commands from userspaceI guess the three can merge into one.
Quoted 4 lines
HID: hook up with bpf
HID: allow to change the report descriptor from an eBPF program
HID: bpf: compute only the required buffer size for the device
HID: bpf: only callhid_bpf_raw_event()if a ctx is availableQuoted 7 lines
Quoted 2 lines
I haven't read through all of them, but I guess they can probably merge as well.
There are certainly patches that we could squash together (3 and 4 from this list into the previous ones), but I'd like to keep some sort of granularity here to not have a patch bomb that gets harder to come back later.
Totally agreed with the granularity of patches. I am not a big fan of patch bombs either. :)
I guess the problem I have with the current version is that I don't have a big picture of the design while reading through relatively big patches. A overview with the following information in the cover letter would be really help here:
1. How different types of programs are triggered (IRQ, user input, etc.);
2. What are the operations and/or outcomes of these programs;
3. How would programs of different types (or attach types) interact with each other (via bpf maps? chaining?)
4. What's the new uapi;
5. New helpers and other logistics
Quoted 7 lines
Sometimes, I find the changes to uapi are the key for me to understand the patches, and I would like to see one or two patches with all the UAPI changes (i.e.
bpf_hid_attach_type). However, that may or may not apply to this set due to granularity concerns.Does this make sense?
It definitely does. And as I read that, I realized that if I manage to get such a clear depiction of what HID-BPF is, it would certainly be a good idea to paste that in a file into the Documentation directory as well :)
I think you have a slightly better picture now with the exchanges we are having on the individual patches, but I'll try to come out with that description in the cover letter for v3.
Cheers,
Benjamin
Hi Benjamin,
Quoted 50 lines · Benjamin Tissoires
Hi,
This is a followup of my v1 at [0].
The short summary of the previous cover letter and discussions is that HID could benefit from BPF for the following use cases:
- simple fixup of report descriptor:
benefits are faster development time and testing, with the produced bpf program being shipped in the kernel directly (the shipping part is *not* addressed here).- Universal Stylus Interface:
allows a user-space program to define its own kernel interface- Surface Dial:
somehow similar to the previous one except that userspace can decide to change the shape of the exported device- firewall:
still partly missing there, there is not yet interception of hidraw calls, but it's coming in a followup series, I promise- tracing:
well, tracing.I tried to address as many comments as I could and here is the short log of changes:
v2:
===- split the series by subsystem (bpf, HID, libbpf, selftests and samples)
- Added an extra patch at the beginning to not require
CAP_NET_ADMINforBPF_PROG_TYPE_LIRC_MODE2(please shout if this is wrong)- made the bpf context attached to HID program of dynamic size:
* the first 1 kB will be able to be addressed directly
* the rest can be retrieved through bpf_hid_{set|get}_data (note that I am definitivey not happy with that API, because there is part of it in bits and other in bytes. ouch)- added an extra patch to prevent non GPL HID bpf programs to be loaded of type
BPF_PROG_TYPE_HID
* same here, not really happy but I don't know where to put that check inverifier.c
Quoted 8 lines
- added a new flag
BPF_F_INSERT_HEADforBPF_LINK_CREATEsyscall when in used with HID program types.
* this flag is used for tracing, to be able to load a program before any others that might already have been inserted and that might change the data stream.Cheers,
Benjamin
I posted a couple of comments to the series, but other than that for the whole series you can use:
I did test this with my USI-BPF program + userspace code, they work with few minor updates compared to previous version.
-Tero
Quoted 69 lines
[0] https://lore.kernel.org/linux-input/[email protected]/T/#t
Benjamin Tissoires (28):
bpf: add newis_sys_admin_prog_type()helper
bpf: introduce hid program type
HID: hook up with bpf
libbpf: add HID program type and API
selftests/bpf: add tests for the HID-bpf initial implementationsamples/bpf: add newhid_mouseexample
bpf/hid: add a new attach type to change the report descriptor
HID: allow to change the report descriptor from an eBPF program
libbpf: add new attach typeBPF_HID_RDESC_FIXUPselftests/bpf: add report descriptor fixup testssamples/bpf: add a report descriptor fixup
bpf/hid: add hid_{get|set}_data helpers
HID: bpf: implement hid_bpf_get|set_data
selftests/bpf: add tests for hid_{get|set}_data helpers bpf/hid: add new BPF type to trigger commands from userspace
libbpf: add new attach typeBPF_HID_USER_EVENTselftests/bpf: add test for user call of HID bpf programs selftests/bpf: hid: rely on uhid event to know if a test device is
ready
bpf/hid: addbpf_hid_raw_requesthelper function
HID: add implementation ofbpf_hid_raw_requestselftests/bpf: add tests forbpf_hid_hw_requestbpf/verifier: prevent non GPL programs to be loaded against HID
HID: bpf: compute only the required buffer size for the device
HID: bpf: only callhid_bpf_raw_event()if a ctx is available bpf/hid: Add a flag to add the program at the beginning of the list
libbpf: add handling forBPF_F_INSERT_HEADin HID programs selftests/bpf: Add a test forBPF_F_INSERT_HEADsamples/bpf: fixbpf_program__attach_hid()api changedrivers/hid/Makefile | 1 + drivers/hid/hid-bpf.c | 361 +++++++++ drivers/hid/hid-core.c | 34 +- include/linux/bpf-hid.h | 129 +++ include/linux/bpf_types.h | 4 + include/linux/hid.h | 25 + include/uapi/linux/bpf.h | 59 ++ include/uapi/linux/bpf_hid.h | 50 ++ kernel/bpf/Makefile | 3 + kernel/bpf/hid.c | 652 +++++++++++++++ kernel/bpf/syscall.c | 26 +- kernel/bpf/verifier.c | 7 + samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 4 + samples/bpf/hid_mouse_kern.c | 91 +++ samples/bpf/hid_mouse_user.c | 129 +++ tools/include/uapi/linux/bpf.h | 59 ++ tools/lib/bpf/libbpf.c | 22 +- tools/lib/bpf/libbpf.h | 2 + tools/lib/bpf/libbpf.map | 1 + tools/testing/selftests/bpf/prog_tests/hid.c | 788 +++++++++++++++++++ tools/testing/selftests/bpf/progs/hid.c | 216 +++++ 22 files changed, 2649 insertions(+), 15 deletions(-)create mode 100644
drivers/hid/hid-bpf.c
create mode 100644include/linux/bpf-hid.h
create mode 100644include/uapi/linux/bpf_hid.hcreate mode 100644kernel/bpf/hid.c
create mode 100644samples/bpf/hid_mouse_kern.ccreate mode 100644samples/bpf/hid_mouse_user.ccreate mode 100644tools/testing/selftests/bpf/prog_tests/hid.ccreate mode 100644tools/testing/selftests/bpf/progs/hid.c