1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2022 Benjamin Tissoires
4 * This is a pure HID-BPF example, and should be considered as such:
5 * on the Etekcity Scroll 6E, the X and Y axes will be swapped and
6 * inverted. On any other device... Not sure what this will do.
8 * This C main file is generic though. To adapt the code and test, users
9 * must amend only the .bpf.c file, which this program will load any
10 * eBPF program it finds.
22 #include <sys/resource.h>
25 #include <linux/bpf.h>
26 #include <linux/errno.h>
29 #include <bpf/libbpf.h>
31 #include "hid_mouse.skel.h"
33 static bool running = true;
35 static void int_exit(int sig)
41 static void usage(const char *prog)
44 "%s: %s /sys/bus/hid/devices/0BUS:0VID:0PID:00ID\n\n",
47 "This program will upload and attach a HID-BPF program to the given device.\n"
48 "On the Etekcity Scroll 6E, the X and Y axis will be inverted, but on any other\n"
49 "device, chances are high that the device will not be working anymore\n\n"
50 "consider this as a demo and adapt the eBPF program to your needs\n"
51 "Hit Ctrl-C to unbind the program and reset the device\n");
54 static int get_hid_id(const char *path)
56 const char *str_id, *dir;
60 memset(uevent, 0, sizeof(uevent));
61 snprintf(uevent, sizeof(uevent) - 1, "%s/uevent", path);
63 fd = open(uevent, O_RDONLY | O_NONBLOCK);
69 dir = basename((char *)path);
71 str_id = dir + sizeof("0003:0001:0A37.");
72 return (int)strtol(str_id, NULL, 16);
75 int main(int argc, char **argv)
77 struct hid_mouse *skel;
78 struct bpf_link *link;
80 const char *optstr = "";
81 const char *sysfs_path;
84 while ((opt = getopt(argc, argv, optstr)) != -1) {
87 usage(basename(argv[0]));
93 usage(basename(argv[0]));
97 sysfs_path = argv[optind];
103 skel = hid_mouse__open();
105 fprintf(stderr, "%s %s:%d", __func__, __FILE__, __LINE__);
109 hid_id = get_hid_id(sysfs_path);
112 fprintf(stderr, "can not open HID device: %m\n");
115 skel->struct_ops.mouse_invert->hid_id = hid_id;
117 err = hid_mouse__load(skel);
119 fprintf(stderr, "can not load HID-BPF program: %m\n");
123 link = bpf_map__attach_struct_ops(skel->maps.mouse_invert);
125 fprintf(stderr, "can not attach HID-BPF program: %m\n");
129 signal(SIGINT, int_exit);
130 signal(SIGTERM, int_exit);
135 hid_mouse__destroy(skel);