xref: /freebsd-11-stable/sys/dev/usb/input/wsp.c (revision 26a4e18e6ac6ba7c693305144810d6c69542171f)
1 /*-
2  * Copyright (c) 2012 Huang Wen Hui
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/malloc.h>
34 #include <sys/module.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/bus.h>
38 #include <sys/conf.h>
39 #include <sys/fcntl.h>
40 #include <sys/file.h>
41 #include <sys/selinfo.h>
42 #include <sys/poll.h>
43 #include <sys/sysctl.h>
44 
45 #include <dev/usb/usb.h>
46 #include <dev/usb/usbdi.h>
47 #include <dev/usb/usbdi_util.h>
48 #include <dev/usb/usbhid.h>
49 
50 #include "usbdevs.h"
51 
52 #define	USB_DEBUG_VAR wsp_debug
53 #include <dev/usb/usb_debug.h>
54 
55 #include <sys/mouse.h>
56 
57 #define	WSP_DRIVER_NAME "wsp"
58 #define	WSP_BUFFER_MAX	1024
59 
60 #define	WSP_CLAMP(x,low,high) do {		\
61 	if ((x) < (low))			\
62 		(x) = (low);			\
63 	else if ((x) > (high))			\
64 		(x) = (high);			\
65 } while (0)
66 
67 /* Tunables */
68 static	SYSCTL_NODE(_hw_usb, OID_AUTO, wsp, CTLFLAG_RW, 0, "USB wsp");
69 
70 #ifdef USB_DEBUG
71 enum wsp_log_level {
72 	WSP_LLEVEL_DISABLED = 0,
73 	WSP_LLEVEL_ERROR,
74 	WSP_LLEVEL_DEBUG,		/* for troubleshooting */
75 	WSP_LLEVEL_INFO,		/* for diagnostics */
76 };
77 static int wsp_debug = WSP_LLEVEL_ERROR;/* the default is to only log errors */
78 
79 SYSCTL_INT(_hw_usb_wsp, OID_AUTO, debug, CTLFLAG_RWTUN,
80     &wsp_debug, WSP_LLEVEL_ERROR, "WSP debug level");
81 #endif					/* USB_DEBUG */
82 
83 static struct wsp_tuning {
84 	int	scale_factor;
85 	int	z_factor;
86 	int	pressure_touch_threshold;
87 	int	pressure_untouch_threshold;
88 	int	pressure_tap_threshold;
89 	int	scr_hor_threshold;
90 	int	enable_single_tap_clicks;
91 }
92 	wsp_tuning =
93 {
94 	.scale_factor = 12,
95 	.z_factor = 5,
96 	.pressure_touch_threshold = 50,
97 	.pressure_untouch_threshold = 10,
98 	.pressure_tap_threshold = 120,
99 	.scr_hor_threshold = 20,
100 	.enable_single_tap_clicks = 1,
101 };
102 
103 static void
wsp_runing_rangecheck(struct wsp_tuning * ptun)104 wsp_runing_rangecheck(struct wsp_tuning *ptun)
105 {
106 	WSP_CLAMP(ptun->scale_factor, 1, 63);
107 	WSP_CLAMP(ptun->z_factor, 1, 63);
108 	WSP_CLAMP(ptun->pressure_touch_threshold, 1, 255);
109 	WSP_CLAMP(ptun->pressure_untouch_threshold, 1, 255);
110 	WSP_CLAMP(ptun->pressure_tap_threshold, 1, 255);
111 	WSP_CLAMP(ptun->scr_hor_threshold, 1, 255);
112 	WSP_CLAMP(ptun->enable_single_tap_clicks, 0, 1);
113 }
114 
115 SYSCTL_INT(_hw_usb_wsp, OID_AUTO, scale_factor, CTLFLAG_RWTUN,
116     &wsp_tuning.scale_factor, 0, "movement scale factor");
117 SYSCTL_INT(_hw_usb_wsp, OID_AUTO, z_factor, CTLFLAG_RWTUN,
118     &wsp_tuning.z_factor, 0, "Z-axis scale factor");
119 SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_touch_threshold, CTLFLAG_RWTUN,
120     &wsp_tuning.pressure_touch_threshold, 0, "touch pressure threshold");
121 SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_untouch_threshold, CTLFLAG_RWTUN,
122     &wsp_tuning.pressure_untouch_threshold, 0, "untouch pressure threshold");
123 SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_tap_threshold, CTLFLAG_RWTUN,
124     &wsp_tuning.pressure_tap_threshold, 0, "tap pressure threshold");
125 SYSCTL_INT(_hw_usb_wsp, OID_AUTO, scr_hor_threshold, CTLFLAG_RWTUN,
126     &wsp_tuning.scr_hor_threshold, 0, "horizontal scrolling threshold");
127 SYSCTL_INT(_hw_usb_wsp, OID_AUTO, enable_single_tap_clicks, CTLFLAG_RWTUN,
128     &wsp_tuning.enable_single_tap_clicks, 0, "enable single tap clicks");
129 
130 /*
131  * Some tables, structures, definitions and constant values for the
132  * touchpad protocol has been copied from Linux's
133  * "drivers/input/mouse/bcm5974.c" which has the following copyright
134  * holders under GPLv2. All device specific code in this driver has
135  * been written from scratch. The decoding algorithm is based on
136  * output from FreeBSD's usbdump.
137  *
138  * Copyright (C) 2008      Henrik Rydberg (rydberg@euromail.se)
139  * Copyright (C) 2008      Scott Shawcroft (scott.shawcroft@gmail.com)
140  * Copyright (C) 2001-2004 Greg Kroah-Hartman (greg@kroah.com)
141  * Copyright (C) 2005      Johannes Berg (johannes@sipsolutions.net)
142  * Copyright (C) 2005      Stelian Pop (stelian@popies.net)
143  * Copyright (C) 2005      Frank Arnold (frank@scirocco-5v-turbo.de)
144  * Copyright (C) 2005      Peter Osterlund (petero2@telia.com)
145  * Copyright (C) 2005      Michael Hanselmann (linux-kernel@hansmi.ch)
146  * Copyright (C) 2006      Nicolas Boichat (nicolas@boichat.ch)
147  */
148 
149 /* button data structure */
150 struct bt_data {
151 	uint8_t	unknown1;		/* constant */
152 	uint8_t	button;			/* left button */
153 	uint8_t	rel_x;			/* relative x coordinate */
154 	uint8_t	rel_y;			/* relative y coordinate */
155 } __packed;
156 
157 /* trackpad header types */
158 enum tp_type {
159 	TYPE1,			/* plain trackpad */
160 	TYPE2,			/* button integrated in trackpad */
161 	TYPE3,			/* additional header fields since June 2013 */
162 	TYPE4                   /* additional header field for pressure data */
163 };
164 
165 /* trackpad finger data offsets, le16-aligned */
166 #define	FINGER_TYPE1		(13 * 2)
167 #define	FINGER_TYPE2		(15 * 2)
168 #define	FINGER_TYPE3		(19 * 2)
169 #define	FINGER_TYPE4		(23 * 2)
170 
171 /* trackpad button data offsets */
172 #define	BUTTON_TYPE2		15
173 #define	BUTTON_TYPE3		23
174 #define	BUTTON_TYPE4		31
175 
176 /* list of device capability bits */
177 #define	HAS_INTEGRATED_BUTTON	1
178 
179 /* trackpad finger data block size */
180 #define FSIZE_TYPE1             (14 * 2)
181 #define FSIZE_TYPE2             (14 * 2)
182 #define FSIZE_TYPE3             (14 * 2)
183 #define FSIZE_TYPE4             (15 * 2)
184 
185 /* trackpad finger header - little endian */
186 struct tp_header {
187 	uint8_t	flag;
188 	uint8_t	sn0;
189 	uint16_t wFixed0;
190 	uint32_t dwSn1;
191 	uint32_t dwFixed1;
192 	uint16_t wLength;
193 	uint8_t	nfinger;
194 	uint8_t	ibt;
195 	int16_t	wUnknown[6];
196 	uint8_t	q1;
197 	uint8_t	q2;
198 } __packed;
199 
200 /* trackpad finger structure - little endian */
201 struct tp_finger {
202 	int16_t	origin;			/* zero when switching track finger */
203 	int16_t	abs_x;			/* absolute x coodinate */
204 	int16_t	abs_y;			/* absolute y coodinate */
205 	int16_t	rel_x;			/* relative x coodinate */
206 	int16_t	rel_y;			/* relative y coodinate */
207 	int16_t	tool_major;		/* tool area, major axis */
208 	int16_t	tool_minor;		/* tool area, minor axis */
209 	int16_t	orientation;		/* 16384 when point, else 15 bit angle */
210 	int16_t	touch_major;		/* touch area, major axis */
211 	int16_t	touch_minor;		/* touch area, minor axis */
212 	int16_t	unused[2];		/* zeros */
213 	int16_t pressure;		/* pressure on forcetouch touchpad */
214 	int16_t	multi;			/* one finger: varies, more fingers:
215 				 	 * constant */
216 } __packed;
217 
218 /* trackpad finger data size, empirically at least ten fingers */
219 #define	MAX_FINGERS		16
220 #define	SIZEOF_FINGER		sizeof(struct tp_finger)
221 #define	SIZEOF_ALL_FINGERS	(MAX_FINGERS * SIZEOF_FINGER)
222 
223 #if (WSP_BUFFER_MAX < ((MAX_FINGERS * FSIZE_TYPE4) + FINGER_TYPE4))
224 #error "WSP_BUFFER_MAX is too small"
225 #endif
226 
227 enum {
228 	WSP_FLAG_WELLSPRING1,
229 	WSP_FLAG_WELLSPRING2,
230 	WSP_FLAG_WELLSPRING3,
231 	WSP_FLAG_WELLSPRING4,
232 	WSP_FLAG_WELLSPRING4A,
233 	WSP_FLAG_WELLSPRING5,
234 	WSP_FLAG_WELLSPRING6A,
235 	WSP_FLAG_WELLSPRING6,
236 	WSP_FLAG_WELLSPRING5A,
237 	WSP_FLAG_WELLSPRING7,
238 	WSP_FLAG_WELLSPRING7A,
239 	WSP_FLAG_WELLSPRING8,
240 	WSP_FLAG_WELLSPRING9,
241 	WSP_FLAG_MAX,
242 };
243 
244 /* device-specific configuration */
245 struct wsp_dev_params {
246 	uint8_t	caps;			/* device capability bitmask */
247 	uint8_t	tp_type;		/* type of trackpad interface */
248 	uint8_t	tp_button;		/* offset to button data */
249 	uint8_t	tp_offset;		/* offset to trackpad finger data */
250 	uint8_t tp_fsize;		/* bytes in single finger block */
251 	uint8_t tp_delta;		/* offset from header to finger struct */
252 	uint8_t iface_index;
253 	uint8_t um_size;		/* usb control message length */
254 	uint8_t um_req_val;		/* usb control message value */
255 	uint8_t um_req_idx;		/* usb control message index */
256 	uint8_t um_switch_idx;		/* usb control message mode switch index */
257 	uint8_t um_switch_on;		/* usb control message mode switch on */
258 	uint8_t um_switch_off;		/* usb control message mode switch off */
259 };
260 
261 static const struct wsp_dev_params wsp_dev_params[WSP_FLAG_MAX] = {
262 	[WSP_FLAG_WELLSPRING1] = {
263 		.caps = 0,
264 		.tp_type = TYPE1,
265 		.tp_button = 0,
266 		.tp_offset = FINGER_TYPE1,
267 		.tp_fsize = FSIZE_TYPE1,
268 		.tp_delta = 0,
269 		.iface_index = 0,
270 		.um_size = 8,
271 		.um_req_val = 0x03,
272 		.um_req_idx = 0x00,
273 		.um_switch_idx = 0,
274 		.um_switch_on = 0x01,
275 		.um_switch_off = 0x08,
276 	},
277 	[WSP_FLAG_WELLSPRING2] = {
278 		.caps = 0,
279 		.tp_type = TYPE1,
280 		.tp_button = 0,
281 		.tp_offset = FINGER_TYPE1,
282 		.tp_fsize = FSIZE_TYPE1,
283 		.tp_delta = 0,
284 		.iface_index = 0,
285 		.um_size = 8,
286 		.um_req_val = 0x03,
287 		.um_req_idx = 0x00,
288 		.um_switch_idx = 0,
289 		.um_switch_on = 0x01,
290 		.um_switch_off = 0x08,
291 	},
292 	[WSP_FLAG_WELLSPRING3] = {
293 		.caps = HAS_INTEGRATED_BUTTON,
294 		.tp_type = TYPE2,
295 		.tp_button = BUTTON_TYPE2,
296 		.tp_offset = FINGER_TYPE2,
297 		.tp_fsize = FSIZE_TYPE2,
298 		.tp_delta = 0,
299 		.iface_index = 0,
300 		.um_size = 8,
301 		.um_req_val = 0x03,
302 		.um_req_idx = 0x00,
303 		.um_switch_idx = 0,
304 		.um_switch_on = 0x01,
305 		.um_switch_off = 0x08,
306 	},
307 	[WSP_FLAG_WELLSPRING4] = {
308 		.caps = HAS_INTEGRATED_BUTTON,
309 		.tp_type = TYPE2,
310 		.tp_button = BUTTON_TYPE2,
311 		.tp_offset = FINGER_TYPE2,
312 		.tp_fsize = FSIZE_TYPE2,
313 		.tp_delta = 0,
314 		.iface_index = 0,
315 		.um_size = 8,
316 		.um_req_val = 0x03,
317 		.um_req_idx = 0x00,
318 		.um_switch_idx = 0,
319 		.um_switch_on = 0x01,
320 		.um_switch_off = 0x08,
321 	},
322 	[WSP_FLAG_WELLSPRING4A] = {
323 		.caps = HAS_INTEGRATED_BUTTON,
324 		.tp_type = TYPE2,
325 		.tp_button = BUTTON_TYPE2,
326 		.tp_offset = FINGER_TYPE2,
327 		.tp_fsize = FSIZE_TYPE2,
328 		.tp_delta = 0,
329 		.iface_index = 0,
330 		.um_size = 8,
331 		.um_req_val = 0x03,
332 		.um_req_idx = 0x00,
333 		.um_switch_idx = 0,
334 		.um_switch_on = 0x01,
335 		.um_switch_off = 0x08,
336 	},
337 	[WSP_FLAG_WELLSPRING5] = {
338 		.caps = HAS_INTEGRATED_BUTTON,
339 		.tp_type = TYPE2,
340 		.tp_button = BUTTON_TYPE2,
341 		.tp_offset = FINGER_TYPE2,
342 		.tp_fsize = FSIZE_TYPE2,
343 		.tp_delta = 0,
344 		.iface_index = 0,
345 		.um_size = 8,
346 		.um_req_val = 0x03,
347 		.um_req_idx = 0x00,
348 		.um_switch_idx = 0,
349 		.um_switch_on = 0x01,
350 		.um_switch_off = 0x08,
351 	},
352 	[WSP_FLAG_WELLSPRING6] = {
353 		.caps = HAS_INTEGRATED_BUTTON,
354 		.tp_type = TYPE2,
355 		.tp_button = BUTTON_TYPE2,
356 		.tp_offset = FINGER_TYPE2,
357 		.tp_fsize = FSIZE_TYPE2,
358 		.tp_delta = 0,
359 		.iface_index = 0,
360 		.um_size = 8,
361 		.um_req_val = 0x03,
362 		.um_req_idx = 0x00,
363 		.um_switch_idx = 0,
364 		.um_switch_on = 0x01,
365 		.um_switch_off = 0x08,
366 	},
367 	[WSP_FLAG_WELLSPRING5A] = {
368 		.caps = HAS_INTEGRATED_BUTTON,
369 		.tp_type = TYPE2,
370 		.tp_button = BUTTON_TYPE2,
371 		.tp_offset = FINGER_TYPE2,
372 		.tp_fsize = FSIZE_TYPE2,
373 		.tp_delta = 0,
374 		.iface_index = 0,
375 		.um_size = 8,
376 		.um_req_val = 0x03,
377 		.um_req_idx = 0x00,
378 		.um_switch_idx = 0,
379 		.um_switch_on = 0x01,
380 		.um_switch_off = 0x08,
381 	},
382 	[WSP_FLAG_WELLSPRING6A] = {
383 		.caps = HAS_INTEGRATED_BUTTON,
384 		.tp_type = TYPE2,
385 		.tp_button = BUTTON_TYPE2,
386 		.tp_offset = FINGER_TYPE2,
387 		.tp_fsize = FSIZE_TYPE2,
388 		.tp_delta = 0,
389 		.um_size = 8,
390 		.um_req_val = 0x03,
391 		.um_req_idx = 0x00,
392 		.um_switch_idx = 0,
393 		.um_switch_on = 0x01,
394 		.um_switch_off = 0x08,
395 	},
396 	[WSP_FLAG_WELLSPRING7] = {
397 		.caps = HAS_INTEGRATED_BUTTON,
398 		.tp_type = TYPE2,
399 		.tp_button = BUTTON_TYPE2,
400 		.tp_offset = FINGER_TYPE2,
401 		.tp_fsize = FSIZE_TYPE2,
402 		.tp_delta = 0,
403 		.iface_index = 0,
404 		.um_size = 8,
405 		.um_req_val = 0x03,
406 		.um_req_idx = 0x00,
407 		.um_switch_idx = 0,
408 		.um_switch_on = 0x01,
409 		.um_switch_off = 0x08,
410 	},
411 	[WSP_FLAG_WELLSPRING7A] = {
412 		.caps = HAS_INTEGRATED_BUTTON,
413 		.tp_type = TYPE2,
414 		.tp_button = BUTTON_TYPE2,
415 		.tp_offset = FINGER_TYPE2,
416 		.tp_fsize = FSIZE_TYPE2,
417 		.tp_delta = 0,
418 		.iface_index = 0,
419 		.um_size = 8,
420 		.um_req_val = 0x03,
421 		.um_req_idx = 0x00,
422 		.um_switch_idx = 0,
423 		.um_switch_on = 0x01,
424 		.um_switch_off = 0x08,
425 	},
426 	[WSP_FLAG_WELLSPRING8] = {
427 		.caps = HAS_INTEGRATED_BUTTON,
428 		.tp_type = TYPE3,
429 		.tp_button = BUTTON_TYPE3,
430 		.tp_offset = FINGER_TYPE3,
431 		.tp_fsize = FSIZE_TYPE3,
432 		.tp_delta = 0,
433 		.iface_index = 0,
434 		.um_size = 8,
435 		.um_req_val = 0x03,
436 		.um_req_idx = 0x00,
437 		.um_switch_idx = 0,
438 		.um_switch_on = 0x01,
439 		.um_switch_off = 0x08,
440 	},
441 	[WSP_FLAG_WELLSPRING9] = {
442 		.caps = HAS_INTEGRATED_BUTTON,
443 		.tp_type = TYPE4,
444 		.tp_button = BUTTON_TYPE4,
445 		.tp_offset = FINGER_TYPE4,
446 		.tp_fsize = FSIZE_TYPE4,
447 		.tp_delta = 2,
448 		.iface_index = 2,
449 		.um_size = 2,
450 		.um_req_val = 0x03,
451 		.um_req_idx = 0x02,
452 		.um_switch_idx = 1,
453 		.um_switch_on = 0x01,
454 		.um_switch_off = 0x00,
455 	},
456 };
457 
458 #define	WSP_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) }
459 
460 static const STRUCT_USB_HOST_ID wsp_devs[] = {
461 	/* MacbookAir1.1 */
462 	WSP_DEV(APPLE, WELLSPRING_ANSI, WSP_FLAG_WELLSPRING1),
463 	WSP_DEV(APPLE, WELLSPRING_ISO, WSP_FLAG_WELLSPRING1),
464 	WSP_DEV(APPLE, WELLSPRING_JIS, WSP_FLAG_WELLSPRING1),
465 
466 	/* MacbookProPenryn, aka wellspring2 */
467 	WSP_DEV(APPLE, WELLSPRING2_ANSI, WSP_FLAG_WELLSPRING2),
468 	WSP_DEV(APPLE, WELLSPRING2_ISO, WSP_FLAG_WELLSPRING2),
469 	WSP_DEV(APPLE, WELLSPRING2_JIS, WSP_FLAG_WELLSPRING2),
470 
471 	/* Macbook5,1 (unibody), aka wellspring3 */
472 	WSP_DEV(APPLE, WELLSPRING3_ANSI, WSP_FLAG_WELLSPRING3),
473 	WSP_DEV(APPLE, WELLSPRING3_ISO, WSP_FLAG_WELLSPRING3),
474 	WSP_DEV(APPLE, WELLSPRING3_JIS, WSP_FLAG_WELLSPRING3),
475 
476 	/* MacbookAir3,2 (unibody), aka wellspring4 */
477 	WSP_DEV(APPLE, WELLSPRING4_ANSI, WSP_FLAG_WELLSPRING4),
478 	WSP_DEV(APPLE, WELLSPRING4_ISO, WSP_FLAG_WELLSPRING4),
479 	WSP_DEV(APPLE, WELLSPRING4_JIS, WSP_FLAG_WELLSPRING4),
480 
481 	/* MacbookAir3,1 (unibody), aka wellspring4 */
482 	WSP_DEV(APPLE, WELLSPRING4A_ANSI, WSP_FLAG_WELLSPRING4A),
483 	WSP_DEV(APPLE, WELLSPRING4A_ISO, WSP_FLAG_WELLSPRING4A),
484 	WSP_DEV(APPLE, WELLSPRING4A_JIS, WSP_FLAG_WELLSPRING4A),
485 
486 	/* Macbook8 (unibody, March 2011) */
487 	WSP_DEV(APPLE, WELLSPRING5_ANSI, WSP_FLAG_WELLSPRING5),
488 	WSP_DEV(APPLE, WELLSPRING5_ISO, WSP_FLAG_WELLSPRING5),
489 	WSP_DEV(APPLE, WELLSPRING5_JIS, WSP_FLAG_WELLSPRING5),
490 
491 	/* MacbookAir4,1 (unibody, July 2011) */
492 	WSP_DEV(APPLE, WELLSPRING6A_ANSI, WSP_FLAG_WELLSPRING6A),
493 	WSP_DEV(APPLE, WELLSPRING6A_ISO, WSP_FLAG_WELLSPRING6A),
494 	WSP_DEV(APPLE, WELLSPRING6A_JIS, WSP_FLAG_WELLSPRING6A),
495 
496 	/* MacbookAir4,2 (unibody, July 2011) */
497 	WSP_DEV(APPLE, WELLSPRING6_ANSI, WSP_FLAG_WELLSPRING6),
498 	WSP_DEV(APPLE, WELLSPRING6_ISO, WSP_FLAG_WELLSPRING6),
499 	WSP_DEV(APPLE, WELLSPRING6_JIS, WSP_FLAG_WELLSPRING6),
500 
501 	/* Macbook8,2 (unibody) */
502 	WSP_DEV(APPLE, WELLSPRING5A_ANSI, WSP_FLAG_WELLSPRING5A),
503 	WSP_DEV(APPLE, WELLSPRING5A_ISO, WSP_FLAG_WELLSPRING5A),
504 	WSP_DEV(APPLE, WELLSPRING5A_JIS, WSP_FLAG_WELLSPRING5A),
505 
506 	/* MacbookPro10,1 (unibody, June 2012) */
507 	/* MacbookPro11,1-3 (unibody, June 2013) */
508 	WSP_DEV(APPLE, WELLSPRING7_ANSI, WSP_FLAG_WELLSPRING7),
509 	WSP_DEV(APPLE, WELLSPRING7_ISO, WSP_FLAG_WELLSPRING7),
510 	WSP_DEV(APPLE, WELLSPRING7_JIS, WSP_FLAG_WELLSPRING7),
511 
512 	/* MacbookPro10,2 (unibody, October 2012) */
513 	WSP_DEV(APPLE, WELLSPRING7A_ANSI, WSP_FLAG_WELLSPRING7A),
514 	WSP_DEV(APPLE, WELLSPRING7A_ISO, WSP_FLAG_WELLSPRING7A),
515 	WSP_DEV(APPLE, WELLSPRING7A_JIS, WSP_FLAG_WELLSPRING7A),
516 
517 	/* MacbookAir6,2 (unibody, June 2013) */
518 	WSP_DEV(APPLE, WELLSPRING8_ANSI, WSP_FLAG_WELLSPRING8),
519 	WSP_DEV(APPLE, WELLSPRING8_ISO, WSP_FLAG_WELLSPRING8),
520 	WSP_DEV(APPLE, WELLSPRING8_JIS, WSP_FLAG_WELLSPRING8),
521 
522 	/* MacbookPro12,1 MacbookPro11,4 */
523 	WSP_DEV(APPLE, WELLSPRING9_ANSI, WSP_FLAG_WELLSPRING9),
524 	WSP_DEV(APPLE, WELLSPRING9_ISO, WSP_FLAG_WELLSPRING9),
525 	WSP_DEV(APPLE, WELLSPRING9_JIS, WSP_FLAG_WELLSPRING9),
526 };
527 
528 #define	WSP_FIFO_BUF_SIZE	 8	/* bytes */
529 #define	WSP_FIFO_QUEUE_MAXLEN	50	/* units */
530 
531 enum {
532 	WSP_INTR_DT,
533 	WSP_N_TRANSFER,
534 };
535 
536 struct wsp_softc {
537 	struct usb_device *sc_usb_device;
538 	struct mtx sc_mutex;		/* for synchronization */
539 	struct usb_xfer *sc_xfer[WSP_N_TRANSFER];
540 	struct usb_fifo_sc sc_fifo;
541 
542 	const struct wsp_dev_params *sc_params;	/* device configuration */
543 
544 	mousehw_t sc_hw;
545 	mousemode_t sc_mode;
546 	u_int	sc_pollrate;
547 	mousestatus_t sc_status;
548 	u_int	sc_state;
549 #define	WSP_ENABLED	       0x01
550 
551 	struct tp_finger *index[MAX_FINGERS];	/* finger index data */
552 	int16_t	pos_x[MAX_FINGERS];	/* position array */
553 	int16_t	pos_y[MAX_FINGERS];	/* position array */
554 	u_int	sc_touch;		/* touch status */
555 #define	WSP_UNTOUCH		0x00
556 #define	WSP_FIRST_TOUCH		0x01
557 #define	WSP_SECOND_TOUCH	0x02
558 #define	WSP_TOUCHING		0x04
559 	int16_t	pre_pos_x;		/* previous position array */
560 	int16_t	pre_pos_y;		/* previous position array */
561 	int	dx_sum;			/* x axis cumulative movement */
562 	int	dy_sum;			/* y axis cumulative movement */
563 	int	dz_sum;			/* z axis cumulative movement */
564 	int	dz_count;
565 #define	WSP_DZ_MAX_COUNT	32
566 	int	dt_sum;			/* T-axis cumulative movement */
567 	int	rdx;			/* x axis remainder of divide by scale_factor */
568 	int	rdy;			/* y axis remainder of divide by scale_factor */
569 	int	rdz;			/* z axis remainder of divide by scale_factor */
570 	int	tp_datalen;
571 	uint8_t o_ntouch;		/* old touch finger status */
572 	uint8_t	finger;			/* 0 or 1 *, check which finger moving */
573 	uint16_t intr_count;
574 #define	WSP_TAP_THRESHOLD	3
575 #define	WSP_TAP_MAX_COUNT	20
576 	int	distance;		/* the distance of 2 fingers */
577 #define	MAX_DISTANCE		2500	/* the max allowed distance */
578 	uint8_t	ibtn;			/* button status in tapping */
579 	uint8_t	ntaps;			/* finger status in tapping */
580 	uint8_t	scr_mode;		/* scroll status in movement */
581 #define	WSP_SCR_NONE		0
582 #define	WSP_SCR_VER		1
583 #define	WSP_SCR_HOR		2
584 	uint8_t tp_data[WSP_BUFFER_MAX] __aligned(4);		/* trackpad transferred data */
585 };
586 
587 /*
588  * function prototypes
589  */
590 static usb_fifo_cmd_t wsp_start_read;
591 static usb_fifo_cmd_t wsp_stop_read;
592 static usb_fifo_open_t wsp_open;
593 static usb_fifo_close_t wsp_close;
594 static usb_fifo_ioctl_t wsp_ioctl;
595 
596 static struct usb_fifo_methods wsp_fifo_methods = {
597 	.f_open = &wsp_open,
598 	.f_close = &wsp_close,
599 	.f_ioctl = &wsp_ioctl,
600 	.f_start_read = &wsp_start_read,
601 	.f_stop_read = &wsp_stop_read,
602 	.basename[0] = WSP_DRIVER_NAME,
603 };
604 
605 /* device initialization and shutdown */
606 static int wsp_enable(struct wsp_softc *sc);
607 static void wsp_disable(struct wsp_softc *sc);
608 
609 /* updating fifo */
610 static void wsp_reset_buf(struct wsp_softc *sc);
611 static void wsp_add_to_queue(struct wsp_softc *, int, int, int, uint32_t);
612 
613 /* Device methods. */
614 static device_probe_t wsp_probe;
615 static device_attach_t wsp_attach;
616 static device_detach_t wsp_detach;
617 static usb_callback_t wsp_intr_callback;
618 
619 static const struct usb_config wsp_config[WSP_N_TRANSFER] = {
620 	[WSP_INTR_DT] = {
621 		.type = UE_INTERRUPT,
622 		.endpoint = UE_ADDR_ANY,
623 		.direction = UE_DIR_IN,
624 		.flags = {
625 			.pipe_bof = 0,
626 			.short_xfer_ok = 1,
627 		},
628 		.bufsize = WSP_BUFFER_MAX,
629 		.callback = &wsp_intr_callback,
630 	},
631 };
632 
633 static usb_error_t
wsp_set_device_mode(struct wsp_softc * sc,uint8_t on)634 wsp_set_device_mode(struct wsp_softc *sc, uint8_t on)
635 {
636 	const struct wsp_dev_params *params = sc->sc_params;
637 	uint8_t	mode_bytes[8];
638 	usb_error_t err;
639 
640 	/* Type 3 does not require a mode switch */
641 	if (params->tp_type == TYPE3)
642 		return 0;
643 
644 	err = usbd_req_get_report(sc->sc_usb_device, NULL,
645 	    mode_bytes, params->um_size, params->iface_index,
646 	    params->um_req_val, params->um_req_idx);
647 
648 	if (err != USB_ERR_NORMAL_COMPLETION) {
649 		DPRINTF("Failed to read device mode (%d)\n", err);
650 		return (err);
651 	}
652 
653 	/*
654 	 * XXX Need to wait at least 250ms for hardware to get
655 	 * ready. The device mode handling appears to be handled
656 	 * asynchronously and we should not issue these commands too
657 	 * quickly.
658 	 */
659 	pause("WHW", hz / 4);
660 
661 	mode_bytes[params->um_switch_idx] =
662 	    on ? params->um_switch_on : params->um_switch_off;
663 
664 	return (usbd_req_set_report(sc->sc_usb_device, NULL,
665 	    mode_bytes, params->um_size, params->iface_index,
666 	    params->um_req_val, params->um_req_idx));
667 }
668 
669 static int
wsp_enable(struct wsp_softc * sc)670 wsp_enable(struct wsp_softc *sc)
671 {
672 	/* reset status */
673 	memset(&sc->sc_status, 0, sizeof(sc->sc_status));
674 	sc->sc_state |= WSP_ENABLED;
675 
676 	DPRINTFN(WSP_LLEVEL_INFO, "enabled wsp\n");
677 	return (0);
678 }
679 
680 static void
wsp_disable(struct wsp_softc * sc)681 wsp_disable(struct wsp_softc *sc)
682 {
683 	sc->sc_state &= ~WSP_ENABLED;
684 	DPRINTFN(WSP_LLEVEL_INFO, "disabled wsp\n");
685 }
686 
687 static int
wsp_probe(device_t self)688 wsp_probe(device_t self)
689 {
690 	struct usb_attach_arg *uaa = device_get_ivars(self);
691 	struct usb_interface_descriptor *id;
692 	struct usb_interface *iface;
693 	uint8_t i;
694 
695 	if (uaa->usb_mode != USB_MODE_HOST)
696 		return (ENXIO);
697 
698 	/* figure out first interface matching */
699 	for (i = 1;; i++) {
700 		iface = usbd_get_iface(uaa->device, i);
701 		if (iface == NULL || i == 3)
702 			return (ENXIO);
703 		id = iface->idesc;
704 		if ((id == NULL) ||
705 		    (id->bInterfaceClass != UICLASS_HID) ||
706 		    (id->bInterfaceProtocol != 0 &&
707 		    id->bInterfaceProtocol != UIPROTO_MOUSE))
708 			continue;
709 		break;
710 	}
711 	/* check if we are attaching to the first match */
712 	if (uaa->info.bIfaceIndex != i)
713 		return (ENXIO);
714 	return (usbd_lookup_id_by_uaa(wsp_devs, sizeof(wsp_devs), uaa));
715 }
716 
717 static int
wsp_attach(device_t dev)718 wsp_attach(device_t dev)
719 {
720 	struct wsp_softc *sc = device_get_softc(dev);
721 	struct usb_attach_arg *uaa = device_get_ivars(dev);
722 	usb_error_t err;
723 	void *d_ptr = NULL;
724 	uint16_t d_len;
725 
726 	DPRINTFN(WSP_LLEVEL_INFO, "sc=%p\n", sc);
727 
728 	/* Get HID descriptor */
729 	err = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr,
730 	    &d_len, M_TEMP, uaa->info.bIfaceIndex);
731 
732 	if (err == USB_ERR_NORMAL_COMPLETION) {
733 		/* Get HID report descriptor length */
734 		sc->tp_datalen = hid_report_size(d_ptr, d_len, hid_input, NULL);
735 		free(d_ptr, M_TEMP);
736 
737 		if (sc->tp_datalen <= 0 || sc->tp_datalen > WSP_BUFFER_MAX) {
738 			DPRINTF("Invalid datalength or too big "
739 			    "datalength: %d\n", sc->tp_datalen);
740 			return (ENXIO);
741 		}
742 	} else {
743 		return (ENXIO);
744 	}
745 
746 	sc->sc_usb_device = uaa->device;
747 
748 	/* get device specific configuration */
749 	sc->sc_params = wsp_dev_params + USB_GET_DRIVER_INFO(uaa);
750 
751 	/*
752 	 * By default the touchpad behaves like a HID device, sending
753 	 * packets with reportID = 8. Such reports contain only
754 	 * limited information. They encode movement deltas and button
755 	 * events, but do not include data from the pressure
756 	 * sensors. The device input mode can be switched from HID
757 	 * reports to raw sensor data using vendor-specific USB
758 	 * control commands:
759 	 */
760 
761 	/*
762 	 * During re-enumeration of the device we need to force the
763 	 * device back into HID mode before switching it to RAW
764 	 * mode. Else the device does not work like expected.
765 	 */
766 	err = wsp_set_device_mode(sc, 0);
767 	if (err != USB_ERR_NORMAL_COMPLETION) {
768 		DPRINTF("Failed to set mode to HID MODE (%d)\n", err);
769 		return (ENXIO);
770 	}
771 
772 	err = wsp_set_device_mode(sc, 1);
773 	if (err != USB_ERR_NORMAL_COMPLETION) {
774 		DPRINTF("failed to set mode to RAW MODE (%d)\n", err);
775 		return (ENXIO);
776 	}
777 
778 	mtx_init(&sc->sc_mutex, "wspmtx", NULL, MTX_DEF | MTX_RECURSE);
779 
780 	err = usbd_transfer_setup(uaa->device,
781 	    &uaa->info.bIfaceIndex, sc->sc_xfer, wsp_config,
782 	    WSP_N_TRANSFER, sc, &sc->sc_mutex);
783 	if (err) {
784 		DPRINTF("error=%s\n", usbd_errstr(err));
785 		goto detach;
786 	}
787 	if (usb_fifo_attach(sc->sc_usb_device, sc, &sc->sc_mutex,
788 	    &wsp_fifo_methods, &sc->sc_fifo,
789 	    device_get_unit(dev), -1, uaa->info.bIfaceIndex,
790 	    UID_ROOT, GID_OPERATOR, 0644)) {
791 		goto detach;
792 	}
793 	device_set_usb_desc(dev);
794 
795 	sc->sc_hw.buttons = 3;
796 	sc->sc_hw.iftype = MOUSE_IF_USB;
797 	sc->sc_hw.type = MOUSE_PAD;
798 	sc->sc_hw.model = MOUSE_MODEL_GENERIC;
799 	sc->sc_mode.protocol = MOUSE_PROTO_MSC;
800 	sc->sc_mode.rate = -1;
801 	sc->sc_mode.resolution = MOUSE_RES_UNKNOWN;
802 	sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
803 	sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
804 	sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
805 
806 	sc->sc_touch = WSP_UNTOUCH;
807 	sc->scr_mode = WSP_SCR_NONE;
808 
809 	return (0);
810 
811 detach:
812 	wsp_detach(dev);
813 	return (ENOMEM);
814 }
815 
816 static int
wsp_detach(device_t dev)817 wsp_detach(device_t dev)
818 {
819 	struct wsp_softc *sc = device_get_softc(dev);
820 
821 	(void) wsp_set_device_mode(sc, 0);
822 
823 	mtx_lock(&sc->sc_mutex);
824 	if (sc->sc_state & WSP_ENABLED)
825 		wsp_disable(sc);
826 	mtx_unlock(&sc->sc_mutex);
827 
828 	usb_fifo_detach(&sc->sc_fifo);
829 
830 	usbd_transfer_unsetup(sc->sc_xfer, WSP_N_TRANSFER);
831 
832 	mtx_destroy(&sc->sc_mutex);
833 
834 	return (0);
835 }
836 
837 static void
wsp_intr_callback(struct usb_xfer * xfer,usb_error_t error)838 wsp_intr_callback(struct usb_xfer *xfer, usb_error_t error)
839 {
840 	struct wsp_softc *sc = usbd_xfer_softc(xfer);
841 	const struct wsp_dev_params *params = sc->sc_params;
842 	struct usb_page_cache *pc;
843 	struct tp_finger *f;
844 	struct tp_header *h;
845 	struct wsp_tuning tun = wsp_tuning;
846 	int ntouch = 0;			/* the finger number in touch */
847 	int ibt = 0;			/* button status */
848 	int dx = 0;
849 	int dy = 0;
850 	int dz = 0;
851 	int rdx = 0;
852 	int rdy = 0;
853 	int rdz = 0;
854 	int len;
855 	int i;
856 
857 	wsp_runing_rangecheck(&tun);
858 
859 	if (sc->dz_count == 0)
860 		sc->dz_count = WSP_DZ_MAX_COUNT;
861 
862 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
863 
864 	switch (USB_GET_STATE(xfer)) {
865 	case USB_ST_TRANSFERRED:
866 
867 		/* copy out received data */
868 		pc = usbd_xfer_get_frame(xfer, 0);
869 		usbd_copy_out(pc, 0, sc->tp_data, len);
870 
871 		if ((len < params->tp_offset + params->tp_fsize) ||
872 		    ((len - params->tp_offset) % params->tp_fsize) != 0) {
873 			DPRINTFN(WSP_LLEVEL_INFO, "Invalid length: %d, %x, %x\n",
874 			    len, sc->tp_data[0], sc->tp_data[1]);
875 			goto tr_setup;
876 		}
877 
878 		if (len < sc->tp_datalen) {
879 			/* make sure we don't process old data */
880 			memset(sc->tp_data + len, 0, sc->tp_datalen - len);
881 		}
882 
883 		h = (struct tp_header *)(sc->tp_data);
884 
885 		if (params->tp_type >= TYPE2) {
886 			ibt = sc->tp_data[params->tp_button];
887 			ntouch = sc->tp_data[params->tp_button - 1];
888 		}
889 		/* range check */
890 		if (ntouch < 0)
891 			ntouch = 0;
892 		else if (ntouch > MAX_FINGERS)
893 			ntouch = MAX_FINGERS;
894 
895 		for (i = 0; i != ntouch; i++) {
896 			f = (struct tp_finger *)(sc->tp_data + params->tp_offset + params->tp_delta + i * params->tp_fsize);
897 			/* swap endianness, if any */
898 			if (le16toh(0x1234) != 0x1234) {
899 				f->origin = le16toh((uint16_t)f->origin);
900 				f->abs_x = le16toh((uint16_t)f->abs_x);
901 				f->abs_y = le16toh((uint16_t)f->abs_y);
902 				f->rel_x = le16toh((uint16_t)f->rel_x);
903 				f->rel_y = le16toh((uint16_t)f->rel_y);
904 				f->tool_major = le16toh((uint16_t)f->tool_major);
905 				f->tool_minor = le16toh((uint16_t)f->tool_minor);
906 				f->orientation = le16toh((uint16_t)f->orientation);
907 				f->touch_major = le16toh((uint16_t)f->touch_major);
908 				f->touch_minor = le16toh((uint16_t)f->touch_minor);
909 				f->pressure = le16toh((uint16_t)f->pressure);
910 				f->multi = le16toh((uint16_t)f->multi);
911 			}
912 			DPRINTFN(WSP_LLEVEL_INFO,
913 			    "[%d]ibt=%d, taps=%d, o=%4d, ax=%5d, ay=%5d, "
914 			    "rx=%5d, ry=%5d, tlmaj=%4d, tlmin=%4d, ot=%4x, "
915 			    "tchmaj=%4d, tchmin=%4d, presure=%4d, m=%4x\n",
916 			    i, ibt, ntouch, f->origin, f->abs_x, f->abs_y,
917 			    f->rel_x, f->rel_y, f->tool_major, f->tool_minor, f->orientation,
918 			    f->touch_major, f->touch_minor, f->pressure, f->multi);
919 			sc->pos_x[i] = f->abs_x;
920 			sc->pos_y[i] = -f->abs_y;
921 			sc->index[i] = f;
922 		}
923 
924 		sc->sc_status.flags &= ~MOUSE_POSCHANGED;
925 		sc->sc_status.flags &= ~MOUSE_STDBUTTONSCHANGED;
926 		sc->sc_status.obutton = sc->sc_status.button;
927 		sc->sc_status.button = 0;
928 
929 		if (ibt != 0) {
930 			if ((params->caps & HAS_INTEGRATED_BUTTON) && ntouch == 2)
931 				sc->sc_status.button |= MOUSE_BUTTON3DOWN;
932 			else if ((params->caps & HAS_INTEGRATED_BUTTON) && ntouch == 3)
933 				sc->sc_status.button |= MOUSE_BUTTON2DOWN;
934 			else
935 				sc->sc_status.button |= MOUSE_BUTTON1DOWN;
936 			sc->ibtn = 1;
937 		}
938 		sc->intr_count++;
939 
940 		if (sc->ntaps < ntouch) {
941 			switch (ntouch) {
942 			case 1:
943 				if (sc->index[0]->touch_major > tun.pressure_tap_threshold &&
944 				    sc->index[0]->tool_major <= 1200)
945 					sc->ntaps = 1;
946 				break;
947 			case 2:
948 				if (sc->index[0]->touch_major > tun.pressure_tap_threshold-30 &&
949 				    sc->index[1]->touch_major > tun.pressure_tap_threshold-30)
950 					sc->ntaps = 2;
951 				break;
952 			case 3:
953 				if (sc->index[0]->touch_major > tun.pressure_tap_threshold-40 &&
954 				    sc->index[1]->touch_major > tun.pressure_tap_threshold-40 &&
955 				    sc->index[2]->touch_major > tun.pressure_tap_threshold-40)
956 					sc->ntaps = 3;
957 				break;
958 			default:
959 				break;
960 			}
961 		}
962 		if (ntouch == 2) {
963 			sc->distance = max(sc->distance, max(
964 			    abs(sc->pos_x[0] - sc->pos_x[1]),
965 			    abs(sc->pos_y[0] - sc->pos_y[1])));
966 		}
967 		if (sc->index[0]->touch_major < tun.pressure_untouch_threshold &&
968 		    sc->sc_status.button == 0) {
969 			sc->sc_touch = WSP_UNTOUCH;
970 			if (sc->intr_count < WSP_TAP_MAX_COUNT &&
971 			    sc->intr_count > WSP_TAP_THRESHOLD &&
972 			    sc->ntaps && sc->ibtn == 0) {
973 				/*
974 				 * Add a pair of events (button-down and
975 				 * button-up).
976 				 */
977 				switch (sc->ntaps) {
978 				case 1:
979 					if (!(params->caps & HAS_INTEGRATED_BUTTON) || tun.enable_single_tap_clicks) {
980 						wsp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON1DOWN);
981 						DPRINTFN(WSP_LLEVEL_INFO, "LEFT CLICK!\n");
982 					}
983 					break;
984 				case 2:
985 					DPRINTFN(WSP_LLEVEL_INFO, "sum_x=%5d, sum_y=%5d\n",
986 					    sc->dx_sum, sc->dy_sum);
987 					if (sc->distance < MAX_DISTANCE && abs(sc->dx_sum) < 5 &&
988 					    abs(sc->dy_sum) < 5) {
989 						wsp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON3DOWN);
990 						DPRINTFN(WSP_LLEVEL_INFO, "RIGHT CLICK!\n");
991 					}
992 					break;
993 				case 3:
994 					wsp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON2DOWN);
995 					break;
996 				default:
997 					/* we don't handle taps of more than three fingers */
998 					break;
999 				}
1000 				wsp_add_to_queue(sc, 0, 0, 0, 0);	/* button release */
1001 			}
1002 			if ((sc->dt_sum / tun.scr_hor_threshold) != 0 &&
1003 			    sc->ntaps == 2 && sc->scr_mode == WSP_SCR_HOR) {
1004 
1005 				/*
1006 				 * translate T-axis into button presses
1007 				 * until further
1008 				 */
1009 				if (sc->dt_sum > 0)
1010 					wsp_add_to_queue(sc, 0, 0, 0, 1UL << 3);
1011 				else if (sc->dt_sum < 0)
1012 					wsp_add_to_queue(sc, 0, 0, 0, 1UL << 4);
1013 			}
1014 			sc->dz_count = WSP_DZ_MAX_COUNT;
1015 			sc->dz_sum = 0;
1016 			sc->intr_count = 0;
1017 			sc->ibtn = 0;
1018 			sc->ntaps = 0;
1019 			sc->finger = 0;
1020 			sc->distance = 0;
1021 			sc->dt_sum = 0;
1022 			sc->dx_sum = 0;
1023 			sc->dy_sum = 0;
1024 			sc->rdx = 0;
1025 			sc->rdy = 0;
1026 			sc->rdz = 0;
1027 			sc->scr_mode = WSP_SCR_NONE;
1028 		} else if (sc->index[0]->touch_major >= tun.pressure_touch_threshold &&
1029 		    sc->sc_touch == WSP_UNTOUCH) {	/* ignore first touch */
1030 			sc->sc_touch = WSP_FIRST_TOUCH;
1031 		} else if (sc->index[0]->touch_major >= tun.pressure_touch_threshold &&
1032 		    sc->sc_touch == WSP_FIRST_TOUCH) {	/* ignore second touch */
1033 			sc->sc_touch = WSP_SECOND_TOUCH;
1034 			DPRINTFN(WSP_LLEVEL_INFO, "Fist pre_x=%5d, pre_y=%5d\n",
1035 			    sc->pre_pos_x, sc->pre_pos_y);
1036 		} else {
1037 			if (sc->sc_touch == WSP_SECOND_TOUCH)
1038 				sc->sc_touch = WSP_TOUCHING;
1039 
1040 			if (ntouch != 0 &&
1041 			    sc->index[0]->touch_major >= tun.pressure_touch_threshold) {
1042 				dx = sc->pos_x[0] - sc->pre_pos_x;
1043 				dy = sc->pos_y[0] - sc->pre_pos_y;
1044 
1045 				/* Ignore movement during button is releasing */
1046 				if (sc->ibtn != 0 && sc->sc_status.button == 0)
1047 					dx = dy = 0;
1048 
1049 				/* Ignore movement if ntouch changed */
1050 				if (sc->o_ntouch != ntouch)
1051 					dx = dy = 0;
1052 
1053 				/* Ignore unexpeted movement when typing */
1054 				if (ntouch == 1 && sc->index[0]->tool_major > 1200)
1055 					dx = dy = 0;
1056 
1057 				if (sc->ibtn != 0 && ntouch == 1 &&
1058 				    sc->intr_count < WSP_TAP_MAX_COUNT &&
1059 				    abs(sc->dx_sum) < 1 && abs(sc->dy_sum) < 1 )
1060 					dx = dy = 0;
1061 
1062 				if (ntouch == 2 && sc->sc_status.button != 0) {
1063 					dx = sc->pos_x[sc->finger] - sc->pre_pos_x;
1064 					dy = sc->pos_y[sc->finger] - sc->pre_pos_y;
1065 
1066 					/*
1067 					 * Ignore movement of switch finger or
1068 					 * movement from ibt=0 to ibt=1
1069 					 */
1070 					if (sc->index[0]->origin == 0 || sc->index[1]->origin == 0 ||
1071 					    sc->sc_status.obutton != sc->sc_status.button) {
1072 						dx = dy = 0;
1073 						sc->finger = 0;
1074 					}
1075 					if ((abs(sc->index[0]->rel_x) + abs(sc->index[0]->rel_y)) <
1076 					    (abs(sc->index[1]->rel_x) + abs(sc->index[1]->rel_y)) &&
1077 					    sc->finger == 0) {
1078 						sc->sc_touch = WSP_SECOND_TOUCH;
1079 						dx = dy = 0;
1080 						sc->finger = 1;
1081 					}
1082 					if ((abs(sc->index[0]->rel_x) + abs(sc->index[0]->rel_y)) >=
1083 					    (abs(sc->index[1]->rel_x) + abs(sc->index[1]->rel_y)) &&
1084 					    sc->finger == 1) {
1085 						sc->sc_touch = WSP_SECOND_TOUCH;
1086 						dx = dy = 0;
1087 						sc->finger = 0;
1088 					}
1089 					DPRINTFN(WSP_LLEVEL_INFO, "dx=%5d, dy=%5d, mov=%5d\n",
1090 					    dx, dy, sc->finger);
1091 				}
1092 				if (sc->dz_count--) {
1093 					rdz = (dy + sc->rdz) % tun.scale_factor;
1094 					sc->dz_sum -= (dy + sc->rdz) / tun.scale_factor;
1095 					sc->rdz = rdz;
1096 				}
1097 				if ((sc->dz_sum / tun.z_factor) != 0)
1098 					sc->dz_count = 0;
1099 			}
1100 			rdx = (dx + sc->rdx) % tun.scale_factor;
1101 			dx = (dx + sc->rdx) / tun.scale_factor;
1102 			sc->rdx = rdx;
1103 
1104 			rdy = (dy + sc->rdy) % tun.scale_factor;
1105 			dy = (dy + sc->rdy) / tun.scale_factor;
1106 			sc->rdy = rdy;
1107 
1108 			sc->dx_sum += dx;
1109 			sc->dy_sum += dy;
1110 
1111 			if (ntouch == 2 && sc->sc_status.button == 0) {
1112 				if (sc->scr_mode == WSP_SCR_NONE &&
1113 				    abs(sc->dx_sum) + abs(sc->dy_sum) > tun.scr_hor_threshold)
1114 					sc->scr_mode = abs(sc->dx_sum) >
1115 					    abs(sc->dy_sum) * 2 ? WSP_SCR_HOR : WSP_SCR_VER;
1116 				DPRINTFN(WSP_LLEVEL_INFO, "scr_mode=%5d, count=%d, dx_sum=%d, dy_sum=%d\n",
1117 				    sc->scr_mode, sc->intr_count, sc->dx_sum, sc->dy_sum);
1118 				if (sc->scr_mode == WSP_SCR_HOR)
1119 					sc->dt_sum += dx;
1120 				else
1121 					sc->dt_sum = 0;
1122 
1123 				dx = dy = 0;
1124 				if (sc->dz_count == 0)
1125 					dz = sc->dz_sum / tun.z_factor;
1126 				if (sc->scr_mode == WSP_SCR_HOR ||
1127 				    abs(sc->pos_x[0] - sc->pos_x[1]) > MAX_DISTANCE ||
1128 				    abs(sc->pos_y[0] - sc->pos_y[1]) > MAX_DISTANCE)
1129 					dz = 0;
1130 			}
1131 			if (ntouch == 3)
1132 				dx = dy = dz = 0;
1133 			if (sc->intr_count < WSP_TAP_MAX_COUNT &&
1134 			    abs(dx) < 3 && abs(dy) < 3 && abs(dz) < 3)
1135 				dx = dy = dz = 0;
1136 			else
1137 				sc->intr_count = WSP_TAP_MAX_COUNT;
1138 			if (dx || dy || dz)
1139 				sc->sc_status.flags |= MOUSE_POSCHANGED;
1140 			DPRINTFN(WSP_LLEVEL_INFO, "dx=%5d, dy=%5d, dz=%5d, sc_touch=%x, btn=%x\n",
1141 			    dx, dy, dz, sc->sc_touch, sc->sc_status.button);
1142 			sc->sc_status.dx += dx;
1143 			sc->sc_status.dy += dy;
1144 			sc->sc_status.dz += dz;
1145 
1146 			wsp_add_to_queue(sc, dx, -dy, dz, sc->sc_status.button);
1147 			if (sc->dz_count == 0) {
1148 				sc->dz_sum = 0;
1149 				sc->rdz = 0;
1150 			}
1151 
1152 		}
1153 		sc->pre_pos_x = sc->pos_x[0];
1154 		sc->pre_pos_y = sc->pos_y[0];
1155 
1156 		if (ntouch == 2 && sc->sc_status.button != 0) {
1157 			sc->pre_pos_x = sc->pos_x[sc->finger];
1158 			sc->pre_pos_y = sc->pos_y[sc->finger];
1159 		}
1160 		sc->o_ntouch = ntouch;
1161 
1162 	case USB_ST_SETUP:
1163 tr_setup:
1164 		/* check if we can put more data into the FIFO */
1165 		if (usb_fifo_put_bytes_max(
1166 		    sc->sc_fifo.fp[USB_FIFO_RX]) != 0) {
1167 			usbd_xfer_set_frame_len(xfer, 0,
1168 			    sc->tp_datalen);
1169 			usbd_transfer_submit(xfer);
1170 		}
1171 		break;
1172 
1173 	default:			/* Error */
1174 		if (error != USB_ERR_CANCELLED) {
1175 			/* try clear stall first */
1176 			usbd_xfer_set_stall(xfer);
1177 			goto tr_setup;
1178 		}
1179 		break;
1180 	}
1181 }
1182 
1183 static void
wsp_add_to_queue(struct wsp_softc * sc,int dx,int dy,int dz,uint32_t buttons_in)1184 wsp_add_to_queue(struct wsp_softc *sc, int dx, int dy, int dz,
1185     uint32_t buttons_in)
1186 {
1187 	uint32_t buttons_out;
1188 	uint8_t buf[8];
1189 
1190 	dx = imin(dx, 254);
1191 	dx = imax(dx, -256);
1192 	dy = imin(dy, 254);
1193 	dy = imax(dy, -256);
1194 	dz = imin(dz, 126);
1195 	dz = imax(dz, -128);
1196 
1197 	buttons_out = MOUSE_MSC_BUTTONS;
1198 	if (buttons_in & MOUSE_BUTTON1DOWN)
1199 		buttons_out &= ~MOUSE_MSC_BUTTON1UP;
1200 	else if (buttons_in & MOUSE_BUTTON2DOWN)
1201 		buttons_out &= ~MOUSE_MSC_BUTTON2UP;
1202 	else if (buttons_in & MOUSE_BUTTON3DOWN)
1203 		buttons_out &= ~MOUSE_MSC_BUTTON3UP;
1204 
1205 	/* Encode the mouse data in standard format; refer to mouse(4) */
1206 	buf[0] = sc->sc_mode.syncmask[1];
1207 	buf[0] |= buttons_out;
1208 	buf[1] = dx >> 1;
1209 	buf[2] = dy >> 1;
1210 	buf[3] = dx - (dx >> 1);
1211 	buf[4] = dy - (dy >> 1);
1212 	/* Encode extra bytes for level 1 */
1213 	if (sc->sc_mode.level == 1) {
1214 		buf[5] = dz >> 1;	/* dz / 2 */
1215 		buf[6] = dz - (dz >> 1);/* dz - (dz / 2) */
1216 		buf[7] = (((~buttons_in) >> 3) & MOUSE_SYS_EXTBUTTONS);
1217 	}
1218 	usb_fifo_put_data_linear(sc->sc_fifo.fp[USB_FIFO_RX], buf,
1219 	    sc->sc_mode.packetsize, 1);
1220 }
1221 
1222 static void
wsp_reset_buf(struct wsp_softc * sc)1223 wsp_reset_buf(struct wsp_softc *sc)
1224 {
1225 	/* reset read queue */
1226 	usb_fifo_reset(sc->sc_fifo.fp[USB_FIFO_RX]);
1227 }
1228 
1229 static void
wsp_start_read(struct usb_fifo * fifo)1230 wsp_start_read(struct usb_fifo *fifo)
1231 {
1232 	struct wsp_softc *sc = usb_fifo_softc(fifo);
1233 	int rate;
1234 
1235 	/* Check if we should override the default polling interval */
1236 	rate = sc->sc_pollrate;
1237 	/* Range check rate */
1238 	if (rate > 1000)
1239 		rate = 1000;
1240 	/* Check for set rate */
1241 	if ((rate > 0) && (sc->sc_xfer[WSP_INTR_DT] != NULL)) {
1242 		/* Stop current transfer, if any */
1243 		usbd_transfer_stop(sc->sc_xfer[WSP_INTR_DT]);
1244 		/* Set new interval */
1245 		usbd_xfer_set_interval(sc->sc_xfer[WSP_INTR_DT], 1000 / rate);
1246 		/* Only set pollrate once */
1247 		sc->sc_pollrate = 0;
1248 	}
1249 	usbd_transfer_start(sc->sc_xfer[WSP_INTR_DT]);
1250 }
1251 
1252 static void
wsp_stop_read(struct usb_fifo * fifo)1253 wsp_stop_read(struct usb_fifo *fifo)
1254 {
1255 	struct wsp_softc *sc = usb_fifo_softc(fifo);
1256 
1257 	usbd_transfer_stop(sc->sc_xfer[WSP_INTR_DT]);
1258 }
1259 
1260 
1261 static int
wsp_open(struct usb_fifo * fifo,int fflags)1262 wsp_open(struct usb_fifo *fifo, int fflags)
1263 {
1264 	DPRINTFN(WSP_LLEVEL_INFO, "\n");
1265 
1266 	if (fflags & FREAD) {
1267 		struct wsp_softc *sc = usb_fifo_softc(fifo);
1268 		int rc;
1269 
1270 		if (sc->sc_state & WSP_ENABLED)
1271 			return (EBUSY);
1272 
1273 		if (usb_fifo_alloc_buffer(fifo,
1274 		    WSP_FIFO_BUF_SIZE, WSP_FIFO_QUEUE_MAXLEN)) {
1275 			return (ENOMEM);
1276 		}
1277 		rc = wsp_enable(sc);
1278 		if (rc != 0) {
1279 			usb_fifo_free_buffer(fifo);
1280 			return (rc);
1281 		}
1282 	}
1283 	return (0);
1284 }
1285 
1286 static void
wsp_close(struct usb_fifo * fifo,int fflags)1287 wsp_close(struct usb_fifo *fifo, int fflags)
1288 {
1289 	if (fflags & FREAD) {
1290 		struct wsp_softc *sc = usb_fifo_softc(fifo);
1291 
1292 		wsp_disable(sc);
1293 		usb_fifo_free_buffer(fifo);
1294 	}
1295 }
1296 
1297 int
wsp_ioctl(struct usb_fifo * fifo,u_long cmd,void * addr,int fflags)1298 wsp_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags)
1299 {
1300 	struct wsp_softc *sc = usb_fifo_softc(fifo);
1301 	mousemode_t mode;
1302 	int error = 0;
1303 
1304 	mtx_lock(&sc->sc_mutex);
1305 
1306 	switch (cmd) {
1307 	case MOUSE_GETHWINFO:
1308 		*(mousehw_t *)addr = sc->sc_hw;
1309 		break;
1310 	case MOUSE_GETMODE:
1311 		*(mousemode_t *)addr = sc->sc_mode;
1312 		break;
1313 	case MOUSE_SETMODE:
1314 		mode = *(mousemode_t *)addr;
1315 
1316 		if (mode.level == -1)
1317 			/* Don't change the current setting */
1318 			;
1319 		else if ((mode.level < 0) || (mode.level > 1)) {
1320 			error = EINVAL;
1321 			goto done;
1322 		}
1323 		sc->sc_mode.level = mode.level;
1324 		sc->sc_pollrate = mode.rate;
1325 		sc->sc_hw.buttons = 3;
1326 
1327 		if (sc->sc_mode.level == 0) {
1328 			sc->sc_mode.protocol = MOUSE_PROTO_MSC;
1329 			sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
1330 			sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
1331 			sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
1332 		} else if (sc->sc_mode.level == 1) {
1333 			sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE;
1334 			sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE;
1335 			sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
1336 			sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC;
1337 		}
1338 		wsp_reset_buf(sc);
1339 		break;
1340 	case MOUSE_GETLEVEL:
1341 		*(int *)addr = sc->sc_mode.level;
1342 		break;
1343 	case MOUSE_SETLEVEL:
1344 		if (*(int *)addr < 0 || *(int *)addr > 1) {
1345 			error = EINVAL;
1346 			goto done;
1347 		}
1348 		sc->sc_mode.level = *(int *)addr;
1349 		sc->sc_hw.buttons = 3;
1350 
1351 		if (sc->sc_mode.level == 0) {
1352 			sc->sc_mode.protocol = MOUSE_PROTO_MSC;
1353 			sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
1354 			sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
1355 			sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
1356 		} else if (sc->sc_mode.level == 1) {
1357 			sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE;
1358 			sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE;
1359 			sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
1360 			sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC;
1361 		}
1362 		wsp_reset_buf(sc);
1363 		break;
1364 	case MOUSE_GETSTATUS:{
1365 			mousestatus_t *status = (mousestatus_t *)addr;
1366 
1367 			*status = sc->sc_status;
1368 			sc->sc_status.obutton = sc->sc_status.button;
1369 			sc->sc_status.button = 0;
1370 			sc->sc_status.dx = 0;
1371 			sc->sc_status.dy = 0;
1372 			sc->sc_status.dz = 0;
1373 
1374 			if (status->dx || status->dy || status->dz)
1375 				status->flags |= MOUSE_POSCHANGED;
1376 			if (status->button != status->obutton)
1377 				status->flags |= MOUSE_BUTTONSCHANGED;
1378 			break;
1379 		}
1380 	default:
1381 		error = ENOTTY;
1382 	}
1383 
1384 done:
1385 	mtx_unlock(&sc->sc_mutex);
1386 	return (error);
1387 }
1388 
1389 static device_method_t wsp_methods[] = {
1390 	/* Device interface */
1391 	DEVMETHOD(device_probe, wsp_probe),
1392 	DEVMETHOD(device_attach, wsp_attach),
1393 	DEVMETHOD(device_detach, wsp_detach),
1394 	DEVMETHOD_END
1395 };
1396 
1397 static driver_t wsp_driver = {
1398 	.name = WSP_DRIVER_NAME,
1399 	.methods = wsp_methods,
1400 	.size = sizeof(struct wsp_softc)
1401 };
1402 
1403 static devclass_t wsp_devclass;
1404 
1405 DRIVER_MODULE(wsp, uhub, wsp_driver, wsp_devclass, NULL, 0);
1406 MODULE_DEPEND(wsp, usb, 1, 1, 1);
1407 MODULE_VERSION(wsp, 1);
1408 USB_PNP_HOST_INFO(wsp_devs);
1409