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