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