xref: /freebsd/sys/dev/usb/gadget/g_keyboard.c (revision faf25f48d601ae39f5752602f3020e2e92605625)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2010 Hans Petter Selasky. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
30  */
31 
32 #include <sys/param.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/stdint.h>
36 #include <sys/stddef.h>
37 #include <sys/queue.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/bus.h>
41 #include <sys/linker_set.h>
42 #include <sys/module.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/condvar.h>
46 #include <sys/sysctl.h>
47 #include <sys/sx.h>
48 #include <sys/unistd.h>
49 #include <sys/callout.h>
50 #include <sys/malloc.h>
51 #include <sys/priv.h>
52 
53 #include <dev/usb/usb.h>
54 #include <dev/usb/usbdi.h>
55 #include <dev/usb/usbdi_util.h>
56 #include <dev/usb/usbhid.h>
57 #include "usb_if.h"
58 
59 #define	USB_DEBUG_VAR g_keyboard_debug
60 #include <dev/usb/usb_debug.h>
61 
62 #include <dev/usb/gadget/g_keyboard.h>
63 
64 static SYSCTL_NODE(_hw_usb, OID_AUTO, g_keyboard,
65     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
66     "USB keyboard gadget");
67 
68 #ifdef USB_DEBUG
69 static int g_keyboard_debug = 0;
70 
71 SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, debug, CTLFLAG_RWTUN,
72     &g_keyboard_debug, 0, "Debug level");
73 #endif
74 
75 static int g_keyboard_mode = 0;
76 
77 SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, mode, CTLFLAG_RWTUN,
78     &g_keyboard_mode, 0, "Mode selection");
79 
80 static int g_keyboard_key_press_interval = 1000;
81 
82 SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, key_press_interval, CTLFLAG_RWTUN,
83     &g_keyboard_key_press_interval, 0, "Key Press Interval in milliseconds");
84 
85 static char g_keyboard_key_press_pattern[G_KEYBOARD_MAX_STRLEN];
86 
87 SYSCTL_STRING(_hw_usb_g_keyboard, OID_AUTO, key_press_pattern, CTLFLAG_RW,
88     g_keyboard_key_press_pattern, sizeof(g_keyboard_key_press_pattern),
89     "Key Press Patterns");
90 
91 #define	UPROTO_BOOT_KEYBOARD 1
92 
93 #define	G_KEYBOARD_NMOD                     8	/* units */
94 #define	G_KEYBOARD_NKEYCODE                 6	/* units */
95 
96 struct g_keyboard_data {
97 	uint8_t	modifiers;
98 #define	MOD_CONTROL_L	0x01
99 #define	MOD_CONTROL_R	0x10
100 #define	MOD_SHIFT_L	0x02
101 #define	MOD_SHIFT_R	0x20
102 #define	MOD_ALT_L	0x04
103 #define	MOD_ALT_R	0x40
104 #define	MOD_WIN_L	0x08
105 #define	MOD_WIN_R	0x80
106 	uint8_t	reserved;
107 	uint8_t	keycode[G_KEYBOARD_NKEYCODE];
108 };
109 
110 enum {
111 	G_KEYBOARD_INTR_DT,
112 	G_KEYBOARD_N_TRANSFER,
113 };
114 
115 struct g_keyboard_softc {
116 	struct mtx sc_mtx;
117 	struct usb_callout sc_callout;
118 	struct g_keyboard_data sc_data[2];
119 	struct usb_xfer *sc_xfer[G_KEYBOARD_N_TRANSFER];
120 
121 	int	sc_mode;
122 	int	sc_state;
123 	int	sc_pattern_len;
124 
125 	char	sc_pattern[G_KEYBOARD_MAX_STRLEN];
126 
127 	uint8_t	sc_led_state[4];
128 };
129 
130 static device_probe_t g_keyboard_probe;
131 static device_attach_t g_keyboard_attach;
132 static device_detach_t g_keyboard_detach;
133 static usb_handle_request_t g_keyboard_handle_request;
134 static usb_callback_t g_keyboard_intr_callback;
135 
136 static device_method_t g_keyboard_methods[] = {
137 	/* USB interface */
138 	DEVMETHOD(usb_handle_request, g_keyboard_handle_request),
139 
140 	/* Device interface */
141 	DEVMETHOD(device_probe, g_keyboard_probe),
142 	DEVMETHOD(device_attach, g_keyboard_attach),
143 	DEVMETHOD(device_detach, g_keyboard_detach),
144 
145 	DEVMETHOD_END
146 };
147 
148 static driver_t g_keyboard_driver = {
149 	.name = "g_keyboard",
150 	.methods = g_keyboard_methods,
151 	.size = sizeof(struct g_keyboard_softc),
152 };
153 
154 DRIVER_MODULE(g_keyboard, uhub, g_keyboard_driver, 0, 0);
155 MODULE_DEPEND(g_keyboard, usb, 1, 1, 1);
156 
157 static const struct usb_config g_keyboard_config[G_KEYBOARD_N_TRANSFER] = {
158 	[G_KEYBOARD_INTR_DT] = {
159 		.type = UE_INTERRUPT,
160 		.endpoint = UE_ADDR_ANY,
161 		.direction = UE_DIR_IN,
162 		.flags = {.ext_buffer = 1,.pipe_bof = 1,},
163 		.bufsize = sizeof(struct g_keyboard_data),
164 		.callback = &g_keyboard_intr_callback,
165 		.frames = 2,
166 		.usb_mode = USB_MODE_DEVICE,
167 	},
168 };
169 
170 static void g_keyboard_timeout(void *arg);
171 
172 static void
173 g_keyboard_timeout_reset(struct g_keyboard_softc *sc)
174 {
175 	int i = g_keyboard_key_press_interval;
176 
177 	if (i <= 0)
178 		i = 1;
179 	else if (i > 1023)
180 		i = 1023;
181 
182 	i = USB_MS_TO_TICKS(i);
183 
184 	usb_callout_reset(&sc->sc_callout, i, &g_keyboard_timeout, sc);
185 }
186 
187 static void
188 g_keyboard_timeout(void *arg)
189 {
190 	struct g_keyboard_softc *sc = arg;
191 
192 	sc->sc_mode = g_keyboard_mode;
193 
194 	memcpy(sc->sc_pattern, g_keyboard_key_press_pattern, sizeof(sc->sc_pattern));
195 
196 	sc->sc_pattern[G_KEYBOARD_MAX_STRLEN - 1] = 0;
197 
198 	sc->sc_pattern_len = strlen(sc->sc_pattern);
199 
200 	DPRINTFN(11, "Timeout %p\n", sc->sc_xfer[G_KEYBOARD_INTR_DT]);
201 
202 	usbd_transfer_start(sc->sc_xfer[G_KEYBOARD_INTR_DT]);
203 
204 	g_keyboard_timeout_reset(sc);
205 }
206 
207 static int
208 g_keyboard_probe(device_t dev)
209 {
210 	struct usb_attach_arg *uaa = device_get_ivars(dev);
211 
212 	DPRINTFN(11, "\n");
213 
214 	if (uaa->usb_mode != USB_MODE_DEVICE)
215 		return (ENXIO);
216 
217 	if ((uaa->info.bInterfaceClass == UICLASS_HID) &&
218 	    (uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) &&
219 	    (uaa->info.bInterfaceProtocol == UPROTO_BOOT_KEYBOARD))
220 		return (0);
221 
222 	return (ENXIO);
223 }
224 
225 static int
226 g_keyboard_attach(device_t dev)
227 {
228 	struct g_keyboard_softc *sc = device_get_softc(dev);
229 	struct usb_attach_arg *uaa = device_get_ivars(dev);
230 	int error;
231 
232 	DPRINTFN(11, "\n");
233 
234 	device_set_usb_desc(dev);
235 
236 	mtx_init(&sc->sc_mtx, "g_keyboard", NULL, MTX_DEF);
237 
238 	usb_callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0);
239 
240 	sc->sc_mode = G_KEYBOARD_MODE_SILENT;
241 
242 	error = usbd_transfer_setup(uaa->device,
243 	    &uaa->info.bIfaceIndex, sc->sc_xfer, g_keyboard_config,
244 	    G_KEYBOARD_N_TRANSFER, sc, &sc->sc_mtx);
245 
246 	if (error) {
247 		DPRINTF("error=%s\n", usbd_errstr(error));
248 		goto detach;
249 	}
250 	mtx_lock(&sc->sc_mtx);
251 	g_keyboard_timeout_reset(sc);
252 	mtx_unlock(&sc->sc_mtx);
253 
254 	return (0);			/* success */
255 
256 detach:
257 	g_keyboard_detach(dev);
258 
259 	return (ENXIO);			/* error */
260 }
261 
262 static int
263 g_keyboard_detach(device_t dev)
264 {
265 	struct g_keyboard_softc *sc = device_get_softc(dev);
266 
267 	DPRINTF("\n");
268 
269 	mtx_lock(&sc->sc_mtx);
270 	usb_callout_stop(&sc->sc_callout);
271 	mtx_unlock(&sc->sc_mtx);
272 
273 	usbd_transfer_unsetup(sc->sc_xfer, G_KEYBOARD_N_TRANSFER);
274 
275 	usb_callout_drain(&sc->sc_callout);
276 
277 	mtx_destroy(&sc->sc_mtx);
278 
279 	return (0);
280 }
281 
282 static uint8_t
283 g_keyboard_get_keycode(struct g_keyboard_softc *sc, int index)
284 {
285 	int key;
286 	int mod = sc->sc_pattern_len;
287 
288 	if (mod == 0)
289 		index = 0;
290 	else
291 		index %= mod;
292 
293 	if ((index >= 0) && (index < sc->sc_pattern_len))
294 		key = sc->sc_pattern[index];
295 	else
296 		key = 'a';
297 
298 	if (key >= 'a' && key <= 'z')
299 		return (key - 'a' + 0x04);
300 	else
301 		return (0x04);
302 }
303 
304 static void
305 g_keyboard_intr_callback(struct usb_xfer *xfer, usb_error_t error)
306 {
307 	struct g_keyboard_softc *sc = usbd_xfer_softc(xfer);
308 	int actlen;
309 	int aframes;
310 
311 	usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
312 
313 	DPRINTF("st=%d aframes=%d actlen=%d bytes\n",
314 	    USB_GET_STATE(xfer), aframes, actlen);
315 
316 	switch (USB_GET_STATE(xfer)) {
317 	case USB_ST_TRANSFERRED:
318 		break;
319 
320 	case USB_ST_SETUP:
321 tr_setup:
322 		if (sc->sc_mode == G_KEYBOARD_MODE_SILENT) {
323 			memset(&sc->sc_data, 0, sizeof(sc->sc_data));
324 			usbd_xfer_set_frame_data(xfer, 0, &sc->sc_data[0], sizeof(sc->sc_data[0]));
325 			usbd_xfer_set_frame_data(xfer, 1, &sc->sc_data[1], sizeof(sc->sc_data[1]));
326 			usbd_xfer_set_frames(xfer, 2);
327 			usbd_transfer_submit(xfer);
328 
329 		} else if (sc->sc_mode == G_KEYBOARD_MODE_PATTERN) {
330 			memset(&sc->sc_data, 0, sizeof(sc->sc_data));
331 
332 			if ((sc->sc_state < 0) || (sc->sc_state >= G_KEYBOARD_MAX_STRLEN))
333 				sc->sc_state = 0;
334 
335 			switch (sc->sc_state % 6) {
336 			case 0:
337 				sc->sc_data[0].keycode[0] =
338 				    g_keyboard_get_keycode(sc, sc->sc_state + 0);
339 			case 1:
340 				sc->sc_data[0].keycode[1] =
341 				    g_keyboard_get_keycode(sc, sc->sc_state + 1);
342 			case 2:
343 				sc->sc_data[0].keycode[2] =
344 				    g_keyboard_get_keycode(sc, sc->sc_state + 2);
345 			case 3:
346 				sc->sc_data[0].keycode[3] =
347 				    g_keyboard_get_keycode(sc, sc->sc_state + 3);
348 			case 4:
349 				sc->sc_data[0].keycode[4] =
350 				    g_keyboard_get_keycode(sc, sc->sc_state + 4);
351 			default:
352 				sc->sc_data[0].keycode[5] =
353 				    g_keyboard_get_keycode(sc, sc->sc_state + 5);
354 			}
355 
356 			sc->sc_state++;
357 
358 			usbd_xfer_set_frame_data(xfer, 0, &sc->sc_data[0], sizeof(sc->sc_data[0]));
359 			usbd_xfer_set_frame_data(xfer, 1, &sc->sc_data[1], sizeof(sc->sc_data[1]));
360 			usbd_xfer_set_frames(xfer, 2);
361 			usbd_transfer_submit(xfer);
362 		}
363 		break;
364 
365 	default:			/* Error */
366 		DPRINTF("error=%s\n", usbd_errstr(error));
367 
368 		if (error != USB_ERR_CANCELLED) {
369 			/* try to clear stall first */
370 			usbd_xfer_set_stall(xfer);
371 			goto tr_setup;
372 		}
373 		break;
374 	}
375 }
376 
377 static int
378 g_keyboard_handle_request(device_t dev,
379     const void *preq, void **pptr, uint16_t *plen,
380     uint16_t offset, uint8_t *pstate)
381 {
382 	struct g_keyboard_softc *sc = device_get_softc(dev);
383 	const struct usb_device_request *req = preq;
384 	uint8_t is_complete = *pstate;
385 
386 	if (!is_complete) {
387 		if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) &&
388 		    (req->bRequest == UR_SET_REPORT) &&
389 		    (req->wValue[0] == 0x00) &&
390 		    (req->wValue[1] == 0x02)) {
391 			if (offset == 0) {
392 				*plen = sizeof(sc->sc_led_state);
393 				*pptr = &sc->sc_led_state;
394 			} else {
395 				*plen = 0;
396 			}
397 			return (0);
398 		} else if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) &&
399 			    (req->bRequest == UR_SET_PROTOCOL) &&
400 			    (req->wValue[0] == 0x00) &&
401 		    (req->wValue[1] == 0x00)) {
402 			*plen = 0;
403 			return (0);
404 		} else if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) &&
405 		    (req->bRequest == UR_SET_IDLE)) {
406 			*plen = 0;
407 			return (0);
408 		}
409 	}
410 	return (ENXIO);			/* use builtin handler */
411 }
412