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_mouse_debug
58#include <dev/usb/usb_debug.h>
59
60#include <dev/usb/gadget/g_mouse.h>
61
62static SYSCTL_NODE(_hw_usb, OID_AUTO, g_mouse, CTLFLAG_RW, 0, "USB mouse gadget");
63
64#ifdef USB_DEBUG
65static int g_mouse_debug = 0;
66
67SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, debug, CTLFLAG_RWTUN,
68    &g_mouse_debug, 0, "Debug level");
69#endif
70
71static int g_mouse_mode = 0;
72
73SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, mode, CTLFLAG_RWTUN,
74    &g_mouse_mode, 0, "Mode selection");
75
76static int g_mouse_button_press_interval = 0;
77
78SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, button_press_interval, CTLFLAG_RWTUN,
79    &g_mouse_button_press_interval, 0, "Mouse button update interval in milliseconds");
80
81static int g_mouse_cursor_update_interval = 1023;
82
83SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, cursor_update_interval, CTLFLAG_RWTUN,
84    &g_mouse_cursor_update_interval, 0, "Mouse cursor update interval in milliseconds");
85
86static int g_mouse_cursor_radius = 128;
87
88SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, cursor_radius, CTLFLAG_RWTUN,
89    &g_mouse_cursor_radius, 0, "Mouse cursor radius in pixels");
90
91struct g_mouse_data {
92	uint8_t buttons;
93#define	BUT_0 0x01
94#define	BUT_1 0x02
95#define	BUT_2 0x04
96	int8_t dx;
97	int8_t dy;
98	int8_t dz;
99};
100
101enum {
102	G_MOUSE_INTR_DT,
103	G_MOUSE_N_TRANSFER,
104};
105
106struct g_mouse_softc {
107	struct mtx sc_mtx;
108	struct usb_callout sc_button_press_callout;
109	struct usb_callout sc_cursor_update_callout;
110	struct g_mouse_data sc_data;
111	struct usb_xfer *sc_xfer[G_MOUSE_N_TRANSFER];
112
113	int	sc_mode;
114	int	sc_radius;
115	int	sc_last_x_state;
116	int	sc_last_y_state;
117	int	sc_curr_x_state;
118	int	sc_curr_y_state;
119	int	sc_tick;
120
121	uint8_t sc_do_cursor_update;
122	uint8_t sc_do_button_update;
123};
124
125static device_probe_t g_mouse_probe;
126static device_attach_t g_mouse_attach;
127static device_detach_t g_mouse_detach;
128static usb_handle_request_t g_mouse_handle_request;
129static usb_callback_t g_mouse_intr_callback;
130
131static devclass_t g_mouse_devclass;
132
133static device_method_t g_mouse_methods[] = {
134	/* USB interface */
135	DEVMETHOD(usb_handle_request, g_mouse_handle_request),
136
137	/* Device interface */
138	DEVMETHOD(device_probe, g_mouse_probe),
139	DEVMETHOD(device_attach, g_mouse_attach),
140	DEVMETHOD(device_detach, g_mouse_detach),
141
142	DEVMETHOD_END
143};
144
145static driver_t g_mouse_driver = {
146	.name = "g_mouse",
147	.methods = g_mouse_methods,
148	.size = sizeof(struct g_mouse_softc),
149};
150
151DRIVER_MODULE(g_mouse, uhub, g_mouse_driver, g_mouse_devclass, 0, 0);
152MODULE_DEPEND(g_mouse, usb, 1, 1, 1);
153
154static const struct usb_config g_mouse_config[G_MOUSE_N_TRANSFER] = {
155
156	[G_MOUSE_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_mouse_data),
162		.callback = &g_mouse_intr_callback,
163		.frames = 1,
164		.usb_mode = USB_MODE_DEVICE,
165	},
166};
167
168static void g_mouse_button_press_timeout(void *arg);
169static void g_mouse_cursor_update_timeout(void *arg);
170
171static void
172g_mouse_button_press_timeout_reset(struct g_mouse_softc *sc)
173{
174	int i = g_mouse_button_press_interval;
175
176	if (i <= 0) {
177		sc->sc_data.buttons = 0;
178		sc->sc_do_button_update = 0;
179	} else {
180		sc->sc_do_button_update = 1;
181	}
182
183	if ((i <= 0) || (i > 1023))
184		i = 1023;
185
186	i = USB_MS_TO_TICKS(i);
187
188	usb_callout_reset(&sc->sc_button_press_callout, i,
189	    &g_mouse_button_press_timeout, sc);
190}
191
192static void
193g_mouse_cursor_update_timeout_reset(struct g_mouse_softc *sc)
194{
195	int i = g_mouse_cursor_update_interval;
196
197	if (i <= 0) {
198		sc->sc_data.dx = 0;
199		sc->sc_data.dy = 0;
200		sc->sc_do_cursor_update = 0;
201		sc->sc_tick = 0;
202	} else {
203		sc->sc_do_cursor_update = 1;
204	}
205
206	if ((i <= 0) || (i > 1023))
207		i = 1023;
208
209	i = USB_MS_TO_TICKS(i);
210
211	usb_callout_reset(&sc->sc_cursor_update_callout, i,
212	    &g_mouse_cursor_update_timeout, sc);
213}
214
215static void
216g_mouse_update_mode_radius(struct g_mouse_softc *sc)
217{
218	sc->sc_mode = g_mouse_mode;
219	sc->sc_radius = g_mouse_cursor_radius;
220
221	if (sc->sc_radius < 0)
222		sc->sc_radius = 0;
223	else if (sc->sc_radius > 1023)
224		sc->sc_radius = 1023;
225}
226
227static void
228g_mouse_button_press_timeout(void *arg)
229{
230	struct g_mouse_softc *sc = arg;
231
232	g_mouse_update_mode_radius(sc);
233
234	DPRINTFN(11, "Timeout %p (button press)\n", sc->sc_xfer[G_MOUSE_INTR_DT]);
235
236	g_mouse_button_press_timeout_reset(sc);
237
238	usbd_transfer_start(sc->sc_xfer[G_MOUSE_INTR_DT]);
239}
240
241static void
242g_mouse_cursor_update_timeout(void *arg)
243{
244	struct g_mouse_softc *sc = arg;
245
246	g_mouse_update_mode_radius(sc);
247
248	DPRINTFN(11, "Timeout %p (cursor update)\n", sc->sc_xfer[G_MOUSE_INTR_DT]);
249
250	g_mouse_cursor_update_timeout_reset(sc);
251
252	usbd_transfer_start(sc->sc_xfer[G_MOUSE_INTR_DT]);
253}
254
255static int
256g_mouse_probe(device_t dev)
257{
258	struct usb_attach_arg *uaa = device_get_ivars(dev);
259
260	DPRINTFN(11, "\n");
261
262	if (uaa->usb_mode != USB_MODE_DEVICE)
263		return (ENXIO);
264
265	if ((uaa->info.bInterfaceClass == UICLASS_HID) &&
266	    (uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) &&
267	    (uaa->info.bInterfaceProtocol == UIPROTO_MOUSE))
268		return (0);
269
270	return (ENXIO);
271}
272
273static int
274g_mouse_attach(device_t dev)
275{
276	struct g_mouse_softc *sc = device_get_softc(dev);
277	struct usb_attach_arg *uaa = device_get_ivars(dev);
278	int error;
279
280	DPRINTFN(11, "\n");
281
282	device_set_usb_desc(dev);
283
284	mtx_init(&sc->sc_mtx, "g_mouse", NULL, MTX_DEF);
285
286	usb_callout_init_mtx(&sc->sc_button_press_callout, &sc->sc_mtx, 0);
287	usb_callout_init_mtx(&sc->sc_cursor_update_callout, &sc->sc_mtx, 0);
288
289	sc->sc_mode = G_MOUSE_MODE_SILENT;
290
291	error = usbd_transfer_setup(uaa->device,
292	    &uaa->info.bIfaceIndex, sc->sc_xfer, g_mouse_config,
293	    G_MOUSE_N_TRANSFER, sc, &sc->sc_mtx);
294
295	if (error) {
296		DPRINTF("error=%s\n", usbd_errstr(error));
297		goto detach;
298	}
299
300	mtx_lock(&sc->sc_mtx);
301	g_mouse_button_press_timeout_reset(sc);
302	g_mouse_cursor_update_timeout_reset(sc);
303	mtx_unlock(&sc->sc_mtx);
304
305	return (0);			/* success */
306
307detach:
308	g_mouse_detach(dev);
309
310	return (ENXIO);			/* error */
311}
312
313static int
314g_mouse_detach(device_t dev)
315{
316	struct g_mouse_softc *sc = device_get_softc(dev);
317
318	DPRINTF("\n");
319
320	mtx_lock(&sc->sc_mtx);
321	usb_callout_stop(&sc->sc_button_press_callout);
322	usb_callout_stop(&sc->sc_cursor_update_callout);
323	mtx_unlock(&sc->sc_mtx);
324
325	usbd_transfer_unsetup(sc->sc_xfer, G_MOUSE_N_TRANSFER);
326
327	usb_callout_drain(&sc->sc_button_press_callout);
328	usb_callout_drain(&sc->sc_cursor_update_callout);
329
330	mtx_destroy(&sc->sc_mtx);
331
332	return (0);
333}
334
335static void
336g_mouse_intr_callback(struct usb_xfer *xfer, usb_error_t error)
337{
338	struct g_mouse_softc *sc = usbd_xfer_softc(xfer);
339	int actlen;
340	int aframes;
341	int dx;
342	int dy;
343	int radius;
344
345	usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
346
347	DPRINTF("st=%d aframes=%d actlen=%d bytes\n",
348	    USB_GET_STATE(xfer), aframes, actlen);
349
350	switch (USB_GET_STATE(xfer)) {
351	case USB_ST_TRANSFERRED:
352		if (!(sc->sc_do_cursor_update || sc->sc_do_button_update))
353			break;
354
355	case USB_ST_SETUP:
356tr_setup:
357
358	  if (sc->sc_do_cursor_update) {
359		sc->sc_do_cursor_update = 0;
360		sc->sc_tick += 80;
361		if ((sc->sc_tick < 0) || (sc->sc_tick > 7999))
362			sc->sc_tick = 0;
363	  }
364
365	  if (sc->sc_do_button_update) {
366			sc->sc_do_button_update = 0;
367			sc->sc_data.buttons ^= BUT_0;
368	  }
369
370	  radius = sc->sc_radius;
371
372		switch (sc->sc_mode) {
373		case G_MOUSE_MODE_SILENT:
374			sc->sc_data.buttons = 0;
375			break;
376		case G_MOUSE_MODE_SPIRAL:
377			radius = (radius * (8000-sc->sc_tick)) / 8000;
378		case G_MOUSE_MODE_CIRCLE:
379			/* TODO */
380			sc->sc_curr_y_state = 0;
381			sc->sc_curr_x_state = 0;
382			break;
383		case G_MOUSE_MODE_BOX:
384			if (sc->sc_tick < 2000) {
385				sc->sc_curr_x_state = (sc->sc_tick * radius) / 2000;
386				sc->sc_curr_y_state = 0;
387			} else if (sc->sc_tick < 4000) {
388				sc->sc_curr_x_state = radius;
389				sc->sc_curr_y_state = -(((sc->sc_tick - 2000) * radius) / 2000);
390			} else if (sc->sc_tick < 6000) {
391				sc->sc_curr_x_state = radius - (((sc->sc_tick - 4000) * radius) / 2000);
392				sc->sc_curr_y_state = -radius;
393			} else {
394				sc->sc_curr_x_state = 0;
395				sc->sc_curr_y_state = -radius + (((sc->sc_tick - 6000) * radius) / 2000);
396			}
397			break;
398		default:
399			break;
400		}
401
402		dx = sc->sc_curr_x_state - sc->sc_last_x_state;
403		dy = sc->sc_curr_y_state - sc->sc_last_y_state;
404
405		if (dx < -63)
406		  dx = -63;
407		else if (dx > 63)
408		  dx = 63;
409
410		if (dy < -63)
411		  dy = -63;
412		else if (dy > 63)
413		  dy = 63;
414
415		sc->sc_last_x_state += dx;
416		sc->sc_last_y_state += dy;
417
418		sc->sc_data.dx = dx;
419		sc->sc_data.dy = dy;
420
421		usbd_xfer_set_frame_data(xfer, 0, &sc->sc_data, sizeof(sc->sc_data));
422		usbd_xfer_set_frames(xfer, 1);
423		usbd_transfer_submit(xfer);
424		break;
425
426	default:			/* Error */
427		DPRINTF("error=%s\n", usbd_errstr(error));
428
429		if (error != USB_ERR_CANCELLED) {
430			/* try to clear stall first */
431			usbd_xfer_set_stall(xfer);
432			goto tr_setup;
433		}
434		break;
435	}
436}
437
438static int
439g_mouse_handle_request(device_t dev,
440    const void *preq, void **pptr, uint16_t *plen,
441    uint16_t offset, uint8_t *pstate)
442{
443	const struct usb_device_request *req = preq;
444	uint8_t is_complete = *pstate;
445
446	if (!is_complete) {
447		if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) &&
448		    (req->bRequest == UR_SET_PROTOCOL) &&
449		    (req->wValue[0] == 0x00) &&
450		    (req->wValue[1] == 0x00)) {
451			*plen = 0;
452			return (0);
453		}
454	}
455	return (ENXIO);			/* use builtin handler */
456}
457