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