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