xref: /linux/tools/testing/selftests/hid/hid_common.h (revision 54ba6d9b1393a0061600c0e49c8ebef65d60a8b2)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /* Copyright (c) 2022-2024 Red Hat */
3 
4 #include "../kselftest_harness.h"
5 
6 #include <fcntl.h>
7 #include <fnmatch.h>
8 #include <dirent.h>
9 #include <poll.h>
10 #include <pthread.h>
11 #include <stdbool.h>
12 #include <linux/hidraw.h>
13 #include <linux/uhid.h>
14 
15 #define SHOW_UHID_DEBUG 0
16 
17 #define min(a, b) \
18 	({ __typeof__(a) _a = (a); \
19 	__typeof__(b) _b = (b); \
20 	_a < _b ? _a : _b; })
21 
22 struct uhid_device {
23 	int dev_id;		/* uniq (random) number to identify the device */
24 	int uhid_fd;
25 	int hid_id;		/* HID device id in the system */
26 	__u16 bus;
27 	__u32 vid;
28 	__u32 pid;
29 	pthread_t tid;		/* thread for reading uhid events */
30 };
31 
32 static unsigned char rdesc[] = {
33 	0x06, 0x00, 0xff,	/* Usage Page (Vendor Defined Page 1) */
34 	0x09, 0x21,		/* Usage (Vendor Usage 0x21) */
35 	0xa1, 0x01,		/* COLLECTION (Application) */
36 	0x09, 0x01,			/* Usage (Vendor Usage 0x01) */
37 	0xa1, 0x00,			/* COLLECTION (Physical) */
38 	0x85, 0x02,				/* REPORT_ID (2) */
39 	0x19, 0x01,				/* USAGE_MINIMUM (1) */
40 	0x29, 0x08,				/* USAGE_MAXIMUM (3) */
41 	0x15, 0x00,				/* LOGICAL_MINIMUM (0) */
42 	0x25, 0xff,				/* LOGICAL_MAXIMUM (255) */
43 	0x95, 0x08,				/* REPORT_COUNT (8) */
44 	0x75, 0x08,				/* REPORT_SIZE (8) */
45 	0x81, 0x02,				/* INPUT (Data,Var,Abs) */
46 	0xc0,				/* END_COLLECTION */
47 	0x09, 0x01,			/* Usage (Vendor Usage 0x01) */
48 	0xa1, 0x00,			/* COLLECTION (Physical) */
49 	0x85, 0x01,				/* REPORT_ID (1) */
50 	0x06, 0x00, 0xff,			/* Usage Page (Vendor Defined Page 1) */
51 	0x19, 0x01,				/* USAGE_MINIMUM (1) */
52 	0x29, 0x03,				/* USAGE_MAXIMUM (3) */
53 	0x15, 0x00,				/* LOGICAL_MINIMUM (0) */
54 	0x25, 0x01,				/* LOGICAL_MAXIMUM (1) */
55 	0x95, 0x03,				/* REPORT_COUNT (3) */
56 	0x75, 0x01,				/* REPORT_SIZE (1) */
57 	0x81, 0x02,				/* INPUT (Data,Var,Abs) */
58 	0x95, 0x01,				/* REPORT_COUNT (1) */
59 	0x75, 0x05,				/* REPORT_SIZE (5) */
60 	0x81, 0x01,				/* INPUT (Cnst,Var,Abs) */
61 	0x05, 0x01,				/* USAGE_PAGE (Generic Desktop) */
62 	0x09, 0x30,				/* USAGE (X) */
63 	0x09, 0x31,				/* USAGE (Y) */
64 	0x15, 0x81,				/* LOGICAL_MINIMUM (-127) */
65 	0x25, 0x7f,				/* LOGICAL_MAXIMUM (127) */
66 	0x75, 0x10,				/* REPORT_SIZE (16) */
67 	0x95, 0x02,				/* REPORT_COUNT (2) */
68 	0x81, 0x06,				/* INPUT (Data,Var,Rel) */
69 
70 	0x06, 0x00, 0xff,			/* Usage Page (Vendor Defined Page 1) */
71 	0x19, 0x01,				/* USAGE_MINIMUM (1) */
72 	0x29, 0x03,				/* USAGE_MAXIMUM (3) */
73 	0x15, 0x00,				/* LOGICAL_MINIMUM (0) */
74 	0x25, 0x01,				/* LOGICAL_MAXIMUM (1) */
75 	0x95, 0x03,				/* REPORT_COUNT (3) */
76 	0x75, 0x01,				/* REPORT_SIZE (1) */
77 	0x91, 0x02,				/* Output (Data,Var,Abs) */
78 	0x95, 0x01,				/* REPORT_COUNT (1) */
79 	0x75, 0x05,				/* REPORT_SIZE (5) */
80 	0x91, 0x01,				/* Output (Cnst,Var,Abs) */
81 
82 	0x06, 0x00, 0xff,			/* Usage Page (Vendor Defined Page 1) */
83 	0x19, 0x06,				/* USAGE_MINIMUM (6) */
84 	0x29, 0x08,				/* USAGE_MAXIMUM (8) */
85 	0x15, 0x00,				/* LOGICAL_MINIMUM (0) */
86 	0x25, 0x01,				/* LOGICAL_MAXIMUM (1) */
87 	0x95, 0x03,				/* REPORT_COUNT (3) */
88 	0x75, 0x01,				/* REPORT_SIZE (1) */
89 	0xb1, 0x02,				/* Feature (Data,Var,Abs) */
90 	0x95, 0x01,				/* REPORT_COUNT (1) */
91 	0x75, 0x05,				/* REPORT_SIZE (5) */
92 	0x91, 0x01,				/* Output (Cnst,Var,Abs) */
93 
94 	0xc0,				/* END_COLLECTION */
95 	0xc0,			/* END_COLLECTION */
96 };
97 
98 static __u8 feature_data[] = { 1, 2 };
99 
100 #define ASSERT_OK(data) ASSERT_FALSE(data)
101 #define ASSERT_OK_PTR(ptr) ASSERT_NE(NULL, ptr)
102 
103 #define UHID_LOG(fmt, ...) do { \
104 	if (SHOW_UHID_DEBUG) \
105 		TH_LOG(fmt, ##__VA_ARGS__); \
106 } while (0)
107 
108 static pthread_mutex_t uhid_started_mtx = PTHREAD_MUTEX_INITIALIZER;
109 static pthread_cond_t uhid_started = PTHREAD_COND_INITIALIZER;
110 
111 static pthread_mutex_t uhid_output_mtx = PTHREAD_MUTEX_INITIALIZER;
112 static pthread_cond_t uhid_output_cond = PTHREAD_COND_INITIALIZER;
113 static unsigned char output_report[10];
114 
115 /* no need to protect uhid_stopped, only one thread accesses it */
116 static bool uhid_stopped;
117 
118 static int uhid_write(struct __test_metadata *_metadata, int fd, const struct uhid_event *ev)
119 {
120 	ssize_t ret;
121 
122 	ret = write(fd, ev, sizeof(*ev));
123 	if (ret < 0) {
124 		TH_LOG("Cannot write to uhid: %m");
125 		return -errno;
126 	} else if (ret != sizeof(*ev)) {
127 		TH_LOG("Wrong size written to uhid: %zd != %zu",
128 			ret, sizeof(ev));
129 		return -EFAULT;
130 	} else {
131 		return 0;
132 	}
133 }
134 
135 static int uhid_create(struct __test_metadata *_metadata, int fd, int rand_nb,
136 		       __u16 bus, __u32 vid, __u32 pid, __u8 *rdesc,
137 		       size_t rdesc_size)
138 {
139 	struct uhid_event ev;
140 	char buf[25];
141 
142 	sprintf(buf, "test-uhid-device-%d", rand_nb);
143 
144 	memset(&ev, 0, sizeof(ev));
145 	ev.type = UHID_CREATE;
146 	strcpy((char *)ev.u.create.name, buf);
147 	ev.u.create.rd_data = rdesc;
148 	ev.u.create.rd_size = rdesc_size;
149 	ev.u.create.bus = bus;
150 	ev.u.create.vendor = vid;
151 	ev.u.create.product = pid;
152 	ev.u.create.version = 0;
153 	ev.u.create.country = 0;
154 
155 	sprintf(buf, "%d", rand_nb);
156 	strcpy((char *)ev.u.create.phys, buf);
157 
158 	return uhid_write(_metadata, fd, &ev);
159 }
160 
161 static void uhid_destroy(struct __test_metadata *_metadata, struct uhid_device *hid)
162 {
163 	struct uhid_event ev;
164 
165 	memset(&ev, 0, sizeof(ev));
166 	ev.type = UHID_DESTROY;
167 
168 	uhid_write(_metadata, hid->uhid_fd, &ev);
169 }
170 
171 static int uhid_event(struct __test_metadata *_metadata, int fd)
172 {
173 	struct uhid_event ev, answer;
174 	ssize_t ret;
175 
176 	memset(&ev, 0, sizeof(ev));
177 	ret = read(fd, &ev, sizeof(ev));
178 	if (ret == 0) {
179 		UHID_LOG("Read HUP on uhid-cdev");
180 		return -EFAULT;
181 	} else if (ret < 0) {
182 		UHID_LOG("Cannot read uhid-cdev: %m");
183 		return -errno;
184 	} else if (ret != sizeof(ev)) {
185 		UHID_LOG("Invalid size read from uhid-dev: %zd != %zu",
186 			ret, sizeof(ev));
187 		return -EFAULT;
188 	}
189 
190 	switch (ev.type) {
191 	case UHID_START:
192 		pthread_mutex_lock(&uhid_started_mtx);
193 		pthread_cond_signal(&uhid_started);
194 		pthread_mutex_unlock(&uhid_started_mtx);
195 
196 		UHID_LOG("UHID_START from uhid-dev");
197 		break;
198 	case UHID_STOP:
199 		uhid_stopped = true;
200 
201 		UHID_LOG("UHID_STOP from uhid-dev");
202 		break;
203 	case UHID_OPEN:
204 		UHID_LOG("UHID_OPEN from uhid-dev");
205 		break;
206 	case UHID_CLOSE:
207 		UHID_LOG("UHID_CLOSE from uhid-dev");
208 		break;
209 	case UHID_OUTPUT:
210 		UHID_LOG("UHID_OUTPUT from uhid-dev");
211 
212 		pthread_mutex_lock(&uhid_output_mtx);
213 		memcpy(output_report,
214 		       ev.u.output.data,
215 		       min(ev.u.output.size, sizeof(output_report)));
216 		pthread_cond_signal(&uhid_output_cond);
217 		pthread_mutex_unlock(&uhid_output_mtx);
218 		break;
219 	case UHID_GET_REPORT:
220 		UHID_LOG("UHID_GET_REPORT from uhid-dev");
221 
222 		answer.type = UHID_GET_REPORT_REPLY;
223 		answer.u.get_report_reply.id = ev.u.get_report.id;
224 		answer.u.get_report_reply.err = ev.u.get_report.rnum == 1 ? 0 : -EIO;
225 		answer.u.get_report_reply.size = sizeof(feature_data);
226 		memcpy(answer.u.get_report_reply.data, feature_data, sizeof(feature_data));
227 
228 		uhid_write(_metadata, fd, &answer);
229 
230 		break;
231 	case UHID_SET_REPORT:
232 		UHID_LOG("UHID_SET_REPORT from uhid-dev");
233 
234 		answer.type = UHID_SET_REPORT_REPLY;
235 		answer.u.set_report_reply.id = ev.u.set_report.id;
236 		answer.u.set_report_reply.err = 0; /* success */
237 
238 		uhid_write(_metadata, fd, &answer);
239 		break;
240 	default:
241 		TH_LOG("Invalid event from uhid-dev: %u", ev.type);
242 	}
243 
244 	return 0;
245 }
246 
247 struct uhid_thread_args {
248 	int fd;
249 	struct __test_metadata *_metadata;
250 };
251 static void *uhid_read_events_thread(void *arg)
252 {
253 	struct uhid_thread_args *args = (struct uhid_thread_args *)arg;
254 	struct __test_metadata *_metadata = args->_metadata;
255 	struct pollfd pfds[1];
256 	int fd = args->fd;
257 	int ret = 0;
258 
259 	pfds[0].fd = fd;
260 	pfds[0].events = POLLIN;
261 
262 	uhid_stopped = false;
263 
264 	while (!uhid_stopped) {
265 		ret = poll(pfds, 1, 100);
266 		if (ret < 0) {
267 			TH_LOG("Cannot poll for fds: %m");
268 			break;
269 		}
270 		if (pfds[0].revents & POLLIN) {
271 			ret = uhid_event(_metadata, fd);
272 			if (ret)
273 				break;
274 		}
275 	}
276 
277 	return (void *)(long)ret;
278 }
279 
280 static int uhid_start_listener(struct __test_metadata *_metadata, pthread_t *tid, int uhid_fd)
281 {
282 	struct uhid_thread_args args = {
283 		.fd = uhid_fd,
284 		._metadata = _metadata,
285 	};
286 	int err;
287 
288 	pthread_mutex_lock(&uhid_started_mtx);
289 	err = pthread_create(tid, NULL, uhid_read_events_thread, (void *)&args);
290 	ASSERT_EQ(0, err) {
291 		TH_LOG("Could not start the uhid thread: %d", err);
292 		pthread_mutex_unlock(&uhid_started_mtx);
293 		close(uhid_fd);
294 		return -EIO;
295 	}
296 	pthread_cond_wait(&uhid_started, &uhid_started_mtx);
297 	pthread_mutex_unlock(&uhid_started_mtx);
298 
299 	return 0;
300 }
301 
302 static int uhid_send_event(struct __test_metadata *_metadata, struct uhid_device *hid,
303 			   __u8 *buf, size_t size)
304 {
305 	struct uhid_event ev;
306 
307 	if (size > sizeof(ev.u.input.data))
308 		return -E2BIG;
309 
310 	memset(&ev, 0, sizeof(ev));
311 	ev.type = UHID_INPUT2;
312 	ev.u.input2.size = size;
313 
314 	memcpy(ev.u.input2.data, buf, size);
315 
316 	return uhid_write(_metadata, hid->uhid_fd, &ev);
317 }
318 
319 static bool match_sysfs_device(struct uhid_device *hid, const char *workdir, struct dirent *dir)
320 {
321 	char target[20] = "";
322 	char phys[512];
323 	char uevent[1024];
324 	char temp[512];
325 	int fd, nread;
326 	bool found = false;
327 
328 	snprintf(target, sizeof(target), "%04X:%04X:%04X.*", hid->bus, hid->vid, hid->pid);
329 
330 	if (fnmatch(target, dir->d_name, 0))
331 		return false;
332 
333 	/* we found the correct VID/PID, now check for phys */
334 	sprintf(uevent, "%s/%s/uevent", workdir, dir->d_name);
335 
336 	fd = open(uevent, O_RDONLY | O_NONBLOCK);
337 	if (fd < 0)
338 		return false;
339 
340 	sprintf(phys, "PHYS=%d", hid->dev_id);
341 
342 	nread = read(fd, temp, ARRAY_SIZE(temp));
343 	if (nread > 0 && (strstr(temp, phys)) != NULL)
344 		found = true;
345 
346 	close(fd);
347 
348 	return found;
349 }
350 
351 static int get_hid_id(struct uhid_device *hid)
352 {
353 	const char *workdir = "/sys/devices/virtual/misc/uhid";
354 	const char *str_id;
355 	DIR *d;
356 	struct dirent *dir;
357 	int found = -1, attempts = 3;
358 
359 	/* it would be nice to be able to use nftw, but the no_alu32 target doesn't support it */
360 
361 	while (found < 0 && attempts > 0) {
362 		attempts--;
363 		d = opendir(workdir);
364 		if (d) {
365 			while ((dir = readdir(d)) != NULL) {
366 				if (!match_sysfs_device(hid, workdir, dir))
367 					continue;
368 
369 				str_id = dir->d_name + sizeof("0000:0000:0000.");
370 				found = (int)strtol(str_id, NULL, 16);
371 
372 				break;
373 			}
374 			closedir(d);
375 		}
376 		if (found < 0)
377 			usleep(100000);
378 	}
379 
380 	return found;
381 }
382 
383 static int get_hidraw(struct uhid_device *hid)
384 {
385 	const char *workdir = "/sys/devices/virtual/misc/uhid";
386 	char sysfs[1024];
387 	DIR *d, *subd;
388 	struct dirent *dir, *subdir;
389 	int i, found = -1;
390 
391 	/* retry 5 times in case the system is loaded */
392 	for (i = 5; i > 0; i--) {
393 		usleep(10);
394 		d = opendir(workdir);
395 
396 		if (!d)
397 			continue;
398 
399 		while ((dir = readdir(d)) != NULL) {
400 			if (!match_sysfs_device(hid, workdir, dir))
401 				continue;
402 
403 			sprintf(sysfs, "%s/%s/hidraw", workdir, dir->d_name);
404 
405 			subd = opendir(sysfs);
406 			if (!subd)
407 				continue;
408 
409 			while ((subdir = readdir(subd)) != NULL) {
410 				if (fnmatch("hidraw*", subdir->d_name, 0))
411 					continue;
412 
413 				found = atoi(subdir->d_name + strlen("hidraw"));
414 			}
415 
416 			closedir(subd);
417 
418 			if (found > 0)
419 				break;
420 		}
421 		closedir(d);
422 	}
423 
424 	return found;
425 }
426 
427 static int open_hidraw(struct uhid_device *hid)
428 {
429 	int hidraw_number;
430 	char hidraw_path[64] = { 0 };
431 
432 	hidraw_number = get_hidraw(hid);
433 	if (hidraw_number < 0)
434 		return hidraw_number;
435 
436 	/* open hidraw node to check the other side of the pipe */
437 	sprintf(hidraw_path, "/dev/hidraw%d", hidraw_number);
438 	return open(hidraw_path, O_RDWR | O_NONBLOCK);
439 }
440 
441 static int setup_uhid(struct __test_metadata *_metadata, struct uhid_device *hid,
442 		      __u16 bus, __u32 vid, __u32 pid, const __u8 *rdesc, size_t rdesc_size)
443 {
444 	const char *path = "/dev/uhid";
445 	time_t t;
446 	int ret;
447 
448 	/* initialize random number generator */
449 	srand((unsigned int)time(&t));
450 
451 	hid->dev_id = rand() % 1024;
452 	hid->bus = bus;
453 	hid->vid = vid;
454 	hid->pid = pid;
455 
456 	hid->uhid_fd = open(path, O_RDWR | O_CLOEXEC);
457 	ASSERT_GE(hid->uhid_fd, 0) TH_LOG("open uhid-cdev failed; %d", hid->uhid_fd);
458 
459 	ret = uhid_create(_metadata, hid->uhid_fd, hid->dev_id, bus, vid, pid,
460 			  (__u8 *)rdesc, rdesc_size);
461 	ASSERT_EQ(0, ret) {
462 		TH_LOG("create uhid device failed: %d", ret);
463 		close(hid->uhid_fd);
464 		return ret;
465 	}
466 
467 	/* locate the uevent file of the created device */
468 	hid->hid_id = get_hid_id(hid);
469 	ASSERT_GT(hid->hid_id, 0)
470 		TH_LOG("Could not locate uhid device id: %d", hid->hid_id);
471 
472 	ret = uhid_start_listener(_metadata, &hid->tid, hid->uhid_fd);
473 	ASSERT_EQ(0, ret) {
474 		TH_LOG("could not start udev listener: %d", ret);
475 		close(hid->uhid_fd);
476 		return ret;
477 	}
478 
479 	return 0;
480 }
481