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