xref: /linux/tools/testing/selftests/hid/hid_common.h (revision cdd30ebb1b9f36159d66f088b61aee264e649d7a)
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 		break;
234 	default:
235 		TH_LOG("Invalid event from uhid-dev: %u", ev.type);
236 	}
237 
238 	return 0;
239 }
240 
241 struct uhid_thread_args {
242 	int fd;
243 	struct __test_metadata *_metadata;
244 };
245 static void *uhid_read_events_thread(void *arg)
246 {
247 	struct uhid_thread_args *args = (struct uhid_thread_args *)arg;
248 	struct __test_metadata *_metadata = args->_metadata;
249 	struct pollfd pfds[1];
250 	int fd = args->fd;
251 	int ret = 0;
252 
253 	pfds[0].fd = fd;
254 	pfds[0].events = POLLIN;
255 
256 	uhid_stopped = false;
257 
258 	while (!uhid_stopped) {
259 		ret = poll(pfds, 1, 100);
260 		if (ret < 0) {
261 			TH_LOG("Cannot poll for fds: %m");
262 			break;
263 		}
264 		if (pfds[0].revents & POLLIN) {
265 			ret = uhid_event(_metadata, fd);
266 			if (ret)
267 				break;
268 		}
269 	}
270 
271 	return (void *)(long)ret;
272 }
273 
274 static int uhid_start_listener(struct __test_metadata *_metadata, pthread_t *tid, int uhid_fd)
275 {
276 	struct uhid_thread_args args = {
277 		.fd = uhid_fd,
278 		._metadata = _metadata,
279 	};
280 	int err;
281 
282 	pthread_mutex_lock(&uhid_started_mtx);
283 	err = pthread_create(tid, NULL, uhid_read_events_thread, (void *)&args);
284 	ASSERT_EQ(0, err) {
285 		TH_LOG("Could not start the uhid thread: %d", err);
286 		pthread_mutex_unlock(&uhid_started_mtx);
287 		close(uhid_fd);
288 		return -EIO;
289 	}
290 	pthread_cond_wait(&uhid_started, &uhid_started_mtx);
291 	pthread_mutex_unlock(&uhid_started_mtx);
292 
293 	return 0;
294 }
295 
296 static int uhid_send_event(struct __test_metadata *_metadata, struct uhid_device *hid,
297 			   __u8 *buf, size_t size)
298 {
299 	struct uhid_event ev;
300 
301 	if (size > sizeof(ev.u.input.data))
302 		return -E2BIG;
303 
304 	memset(&ev, 0, sizeof(ev));
305 	ev.type = UHID_INPUT2;
306 	ev.u.input2.size = size;
307 
308 	memcpy(ev.u.input2.data, buf, size);
309 
310 	return uhid_write(_metadata, hid->uhid_fd, &ev);
311 }
312 
313 static bool match_sysfs_device(struct uhid_device *hid, const char *workdir, struct dirent *dir)
314 {
315 	char target[20] = "";
316 	char phys[512];
317 	char uevent[1024];
318 	char temp[512];
319 	int fd, nread;
320 	bool found = false;
321 
322 	snprintf(target, sizeof(target), "%04X:%04X:%04X.*", hid->bus, hid->vid, hid->pid);
323 
324 	if (fnmatch(target, dir->d_name, 0))
325 		return false;
326 
327 	/* we found the correct VID/PID, now check for phys */
328 	sprintf(uevent, "%s/%s/uevent", workdir, dir->d_name);
329 
330 	fd = open(uevent, O_RDONLY | O_NONBLOCK);
331 	if (fd < 0)
332 		return false;
333 
334 	sprintf(phys, "PHYS=%d", hid->dev_id);
335 
336 	nread = read(fd, temp, ARRAY_SIZE(temp));
337 	if (nread > 0 && (strstr(temp, phys)) != NULL)
338 		found = true;
339 
340 	close(fd);
341 
342 	return found;
343 }
344 
345 static int get_hid_id(struct uhid_device *hid)
346 {
347 	const char *workdir = "/sys/devices/virtual/misc/uhid";
348 	const char *str_id;
349 	DIR *d;
350 	struct dirent *dir;
351 	int found = -1, attempts = 3;
352 
353 	/* it would be nice to be able to use nftw, but the no_alu32 target doesn't support it */
354 
355 	while (found < 0 && attempts > 0) {
356 		attempts--;
357 		d = opendir(workdir);
358 		if (d) {
359 			while ((dir = readdir(d)) != NULL) {
360 				if (!match_sysfs_device(hid, workdir, dir))
361 					continue;
362 
363 				str_id = dir->d_name + sizeof("0000:0000:0000.");
364 				found = (int)strtol(str_id, NULL, 16);
365 
366 				break;
367 			}
368 			closedir(d);
369 		}
370 		if (found < 0)
371 			usleep(100000);
372 	}
373 
374 	return found;
375 }
376 
377 static int get_hidraw(struct uhid_device *hid)
378 {
379 	const char *workdir = "/sys/devices/virtual/misc/uhid";
380 	char sysfs[1024];
381 	DIR *d, *subd;
382 	struct dirent *dir, *subdir;
383 	int i, found = -1;
384 
385 	/* retry 5 times in case the system is loaded */
386 	for (i = 5; i > 0; i--) {
387 		usleep(10);
388 		d = opendir(workdir);
389 
390 		if (!d)
391 			continue;
392 
393 		while ((dir = readdir(d)) != NULL) {
394 			if (!match_sysfs_device(hid, workdir, dir))
395 				continue;
396 
397 			sprintf(sysfs, "%s/%s/hidraw", workdir, dir->d_name);
398 
399 			subd = opendir(sysfs);
400 			if (!subd)
401 				continue;
402 
403 			while ((subdir = readdir(subd)) != NULL) {
404 				if (fnmatch("hidraw*", subdir->d_name, 0))
405 					continue;
406 
407 				found = atoi(subdir->d_name + strlen("hidraw"));
408 			}
409 
410 			closedir(subd);
411 
412 			if (found > 0)
413 				break;
414 		}
415 		closedir(d);
416 	}
417 
418 	return found;
419 }
420 
421 static int open_hidraw(struct uhid_device *hid)
422 {
423 	int hidraw_number;
424 	char hidraw_path[64] = { 0 };
425 
426 	hidraw_number = get_hidraw(hid);
427 	if (hidraw_number < 0)
428 		return hidraw_number;
429 
430 	/* open hidraw node to check the other side of the pipe */
431 	sprintf(hidraw_path, "/dev/hidraw%d", hidraw_number);
432 	return open(hidraw_path, O_RDWR | O_NONBLOCK);
433 }
434 
435 static int setup_uhid(struct __test_metadata *_metadata, struct uhid_device *hid,
436 		      __u16 bus, __u32 vid, __u32 pid, const __u8 *rdesc, size_t rdesc_size)
437 {
438 	const char *path = "/dev/uhid";
439 	time_t t;
440 	int ret;
441 
442 	/* initialize random number generator */
443 	srand((unsigned int)time(&t));
444 
445 	hid->dev_id = rand() % 1024;
446 	hid->bus = bus;
447 	hid->vid = vid;
448 	hid->pid = pid;
449 
450 	hid->uhid_fd = open(path, O_RDWR | O_CLOEXEC);
451 	ASSERT_GE(hid->uhid_fd, 0) TH_LOG("open uhid-cdev failed; %d", hid->uhid_fd);
452 
453 	ret = uhid_create(_metadata, hid->uhid_fd, hid->dev_id, bus, vid, pid,
454 			  (__u8 *)rdesc, rdesc_size);
455 	ASSERT_EQ(0, ret) {
456 		TH_LOG("create uhid device failed: %d", ret);
457 		close(hid->uhid_fd);
458 		return ret;
459 	}
460 
461 	/* locate the uevent file of the created device */
462 	hid->hid_id = get_hid_id(hid);
463 	ASSERT_GT(hid->hid_id, 0)
464 		TH_LOG("Could not locate uhid device id: %d", hid->hid_id);
465 
466 	ret = uhid_start_listener(_metadata, &hid->tid, hid->uhid_fd);
467 	ASSERT_EQ(0, ret) {
468 		TH_LOG("could not start udev listener: %d", ret);
469 		close(hid->uhid_fd);
470 		return ret;
471 	}
472 
473 	return 0;
474 }
475