xref: /freebsd/sys/dev/atkbdc/psm.c (revision 78b9f0095b4af3aca6c931b2c7b009ddb8a05125)
1 /*-
2  * Copyright (c) 1992, 1993 Erik Forsberg.
3  * Copyright (c) 1996, 1997 Kazutaka YOKOTA.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY EXPRESS OR IMPLIED
13  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
15  * NO EVENT SHALL I BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
16  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
17  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
18  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
19  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
20  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
21  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22  */
23 /*
24  *  Ported to 386bsd Oct 17, 1992
25  *  Sandi Donno, Computer Science, University of Cape Town, South Africa
26  *  Please send bug reports to sandi@cs.uct.ac.za
27  *
28  *  Thanks are also due to Rick Macklem, rick@snowhite.cis.uoguelph.ca -
29  *  although I was only partially successful in getting the alpha release
30  *  of his "driver for the Logitech and ATI Inport Bus mice for use with
31  *  386bsd and the X386 port" to work with my Microsoft mouse, I nevertheless
32  *  found his code to be an invaluable reference when porting this driver
33  *  to 386bsd.
34  *
35  *  Further modifications for latest 386BSD+patchkit and port to NetBSD,
36  *  Andrew Herbert <andrew@werple.apana.org.au> - 8 June 1993
37  *
38  *  Cloned from the Microsoft Bus Mouse driver, also by Erik Forsberg, by
39  *  Andrew Herbert - 12 June 1993
40  *
41  *  Modified for PS/2 mouse by Charles Hannum <mycroft@ai.mit.edu>
42  *  - 13 June 1993
43  *
44  *  Modified for PS/2 AUX mouse by Shoji Yuen <yuen@nuie.nagoya-u.ac.jp>
45  *  - 24 October 1993
46  *
47  *  Hardware access routines and probe logic rewritten by
48  *  Kazutaka Yokota <yokota@zodiac.mech.utsunomiya-u.ac.jp>
49  *  - 3, 14, 22 October 1996.
50  *  - 12 November 1996. IOCTLs and rearranging `psmread', `psmioctl'...
51  *  - 14, 30 November 1996. Uses `kbdio.c'.
52  *  - 13 December 1996. Uses queuing version of `kbdio.c'.
53  *  - January/February 1997. Tweaked probe logic for
54  *    HiNote UltraII/Latitude/Armada laptops.
55  *  - 30 July 1997. Added APM support.
56  *  - 5 March 1997. Defined driver configuration flags (PSM_CONFIG_XXX).
57  *    Improved sync check logic.
58  *    Vendor specific support routines.
59  */
60 
61 #include <sys/cdefs.h>
62 __FBSDID("$FreeBSD$");
63 
64 #include "opt_isa.h"
65 #include "opt_psm.h"
66 #include "opt_evdev.h"
67 
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/kernel.h>
71 #include <sys/module.h>
72 #include <sys/bus.h>
73 #include <sys/conf.h>
74 #include <sys/filio.h>
75 #include <sys/poll.h>
76 #include <sys/sigio.h>
77 #include <sys/signalvar.h>
78 #include <sys/syslog.h>
79 #include <machine/bus.h>
80 #include <sys/rman.h>
81 #include <sys/selinfo.h>
82 #include <sys/sysctl.h>
83 #include <sys/time.h>
84 #include <sys/uio.h>
85 
86 #include <sys/limits.h>
87 #include <sys/mouse.h>
88 #include <machine/resource.h>
89 
90 #ifdef DEV_ISA
91 #include <isa/isavar.h>
92 #endif
93 
94 #ifdef EVDEV_SUPPORT
95 #include <dev/evdev/evdev.h>
96 #include <dev/evdev/input.h>
97 #endif
98 
99 #include <dev/atkbdc/atkbdcreg.h>
100 #include <dev/atkbdc/psm.h>
101 
102 /*
103  * Driver specific options: the following options may be set by
104  * `options' statements in the kernel configuration file.
105  */
106 
107 /* debugging */
108 #ifndef PSM_DEBUG
109 #define	PSM_DEBUG	0	/*
110 				 * logging: 0: none, 1: brief, 2: verbose
111 				 *          3: sync errors, 4: all packets
112 				 */
113 #endif
114 #define	VLOG(level, args)	do {	\
115 	if (verbose >= level)		\
116 		log args;		\
117 } while (0)
118 
119 #ifndef PSM_INPUT_TIMEOUT
120 #define	PSM_INPUT_TIMEOUT	2000000	/* 2 sec */
121 #endif
122 
123 #ifndef PSM_TAP_TIMEOUT
124 #define	PSM_TAP_TIMEOUT		125000
125 #endif
126 
127 #ifndef PSM_TAP_THRESHOLD
128 #define	PSM_TAP_THRESHOLD	25
129 #endif
130 
131 /* end of driver specific options */
132 
133 #define	PSMCPNP_DRIVER_NAME	"psmcpnp"
134 
135 struct psmcpnp_softc {
136 	enum {
137 		PSMCPNP_GENERIC,
138 		PSMCPNP_FORCEPAD,
139 		PSMCPNP_HPSYN81,
140 	} type;		/* Based on PnP ID */
141 };
142 
143 /* input queue */
144 #define	PSM_BUFSIZE		960
145 #define	PSM_SMALLBUFSIZE	240
146 
147 /* operation levels */
148 #define	PSM_LEVEL_BASE		0
149 #define	PSM_LEVEL_STANDARD	1
150 #define	PSM_LEVEL_NATIVE	2
151 #define	PSM_LEVEL_MIN		PSM_LEVEL_BASE
152 #define	PSM_LEVEL_MAX		PSM_LEVEL_NATIVE
153 
154 /* Logitech PS2++ protocol */
155 #define	MOUSE_PS2PLUS_CHECKBITS(b)	\
156     ((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
157 #define	MOUSE_PS2PLUS_PACKET_TYPE(b)	\
158     (((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
159 
160 /* ring buffer */
161 typedef struct ringbuf {
162 	int		count;	/* # of valid elements in the buffer */
163 	int		head;	/* head pointer */
164 	int		tail;	/* tail poiner */
165 	u_char buf[PSM_BUFSIZE];
166 } ringbuf_t;
167 
168 /* data buffer */
169 typedef struct packetbuf {
170 	u_char	ipacket[16];	/* interim input buffer */
171 	int	inputbytes;	/* # of bytes in the input buffer */
172 } packetbuf_t;
173 
174 #ifndef PSM_PACKETQUEUE
175 #define	PSM_PACKETQUEUE	128
176 #endif
177 
178 /*
179  * Typical bezel limits. Taken from 'Synaptics
180  * PS/2 TouchPad Interfacing Guide' p.3.2.3.
181  */
182 #define	SYNAPTICS_DEFAULT_MAX_X	5472
183 #define	SYNAPTICS_DEFAULT_MAX_Y	4448
184 #define	SYNAPTICS_DEFAULT_MIN_X	1472
185 #define	SYNAPTICS_DEFAULT_MIN_Y	1408
186 
187 typedef struct synapticsinfo {
188 	struct sysctl_ctx_list	 sysctl_ctx;
189 	struct sysctl_oid	*sysctl_tree;
190 	int			 directional_scrolls;
191 	int			 two_finger_scroll;
192 	int			 min_pressure;
193 	int			 max_pressure;
194 	int			 max_width;
195 	int			 margin_top;
196 	int			 margin_right;
197 	int			 margin_bottom;
198 	int			 margin_left;
199 	int			 na_top;
200 	int			 na_right;
201 	int			 na_bottom;
202 	int			 na_left;
203 	int			 window_min;
204 	int			 window_max;
205 	int			 multiplicator;
206 	int			 weight_current;
207 	int			 weight_previous;
208 	int			 weight_previous_na;
209 	int			 weight_len_squared;
210 	int			 div_min;
211 	int			 div_max;
212 	int			 div_max_na;
213 	int			 div_len;
214 	int			 tap_max_delta;
215 	int			 tap_min_queue;
216 	int			 taphold_timeout;
217 	int			 vscroll_ver_area;
218 	int			 vscroll_hor_area;
219 	int			 vscroll_min_delta;
220 	int			 vscroll_div_min;
221 	int			 vscroll_div_max;
222 	int			 touchpad_off;
223 	int			 softbuttons_y;
224 	int			 softbutton2_x;
225 	int			 softbutton3_x;
226 	int			 max_x;
227 	int			 max_y;
228 } synapticsinfo_t;
229 
230 typedef struct synapticspacket {
231 	int			x;
232 	int			y;
233 } synapticspacket_t;
234 
235 #define	SYNAPTICS_PACKETQUEUE 10
236 #define SYNAPTICS_QUEUE_CURSOR(x)					\
237 	(x + SYNAPTICS_PACKETQUEUE) % SYNAPTICS_PACKETQUEUE
238 
239 #define	SYNAPTICS_VERSION_GE(synhw, major, minor)			\
240     ((synhw).infoMajor > (major) ||					\
241      ((synhw).infoMajor == (major) && (synhw).infoMinor >= (minor)))
242 
243 typedef struct smoother {
244 	synapticspacket_t	queue[SYNAPTICS_PACKETQUEUE];
245 	int			queue_len;
246 	int			queue_cursor;
247 	int			start_x;
248 	int			start_y;
249 	int			avg_dx;
250 	int			avg_dy;
251 	int			squelch_x;
252 	int			squelch_y;
253 	int			is_fuzzy;
254 	int			active;
255 } smoother_t;
256 
257 typedef struct gesture {
258 	int			window_min;
259 	int			fingers_nb;
260 	int			tap_button;
261 	int			in_taphold;
262 	int			in_vscroll;
263 	int			zmax;		/* maximum pressure value */
264 	struct timeval		taptimeout;	/* tap timeout for touchpads */
265 } gesture_t;
266 
267 enum {
268 	TRACKPOINT_SYSCTL_SENSITIVITY,
269 	TRACKPOINT_SYSCTL_NEGATIVE_INERTIA,
270 	TRACKPOINT_SYSCTL_UPPER_PLATEAU,
271 	TRACKPOINT_SYSCTL_BACKUP_RANGE,
272 	TRACKPOINT_SYSCTL_DRAG_HYSTERESIS,
273 	TRACKPOINT_SYSCTL_MINIMUM_DRAG,
274 	TRACKPOINT_SYSCTL_UP_THRESHOLD,
275 	TRACKPOINT_SYSCTL_THRESHOLD,
276 	TRACKPOINT_SYSCTL_JENKS_CURVATURE,
277 	TRACKPOINT_SYSCTL_Z_TIME,
278 	TRACKPOINT_SYSCTL_PRESS_TO_SELECT,
279 	TRACKPOINT_SYSCTL_SKIP_BACKUPS
280 };
281 
282 typedef struct trackpointinfo {
283 	struct sysctl_ctx_list sysctl_ctx;
284 	struct sysctl_oid *sysctl_tree;
285 	int	sensitivity;
286 	int	inertia;
287 	int	uplateau;
288 	int	reach;
289 	int	draghys;
290 	int	mindrag;
291 	int	upthresh;
292 	int	threshold;
293 	int	jenks;
294 	int	ztime;
295 	int	pts;
296 	int	skipback;
297 } trackpointinfo_t;
298 
299 typedef struct finger {
300 	int			x;
301 	int			y;
302 	int			p;
303 	int			w;
304 	int			flags;
305 } finger_t;
306 #define	PSM_FINGERS		2	/* # of processed fingers */
307 #define	PSM_FINGER_IS_PEN	(1<<0)
308 #define	PSM_FINGER_FUZZY	(1<<1)
309 #define	PSM_FINGER_DEFAULT_P	tap_threshold
310 #define	PSM_FINGER_DEFAULT_W	1
311 #define	PSM_FINGER_IS_SET(f) ((f).x != -1 && (f).y != -1 && (f).p != 0)
312 #define	PSM_FINGER_RESET(f) do { \
313 	(f) = (finger_t) { .x = -1, .y = -1, .p = 0, .w = 0, .flags = 0 }; \
314 } while (0)
315 
316 typedef struct elantechhw {
317 	int			hwversion;
318 	int			fwversion;
319 	int			sizex;
320 	int			sizey;
321 	int			dpmmx;
322 	int			dpmmy;
323 	int			ntracesx;
324 	int			ntracesy;
325 	int			dptracex;
326 	int			dptracey;
327 	int			issemimt;
328 	int			isclickpad;
329 	int			hascrc;
330 	int			hastrackpoint;
331 	int			haspressure;
332 } elantechhw_t;
333 
334 /* minimum versions supported by this driver */
335 #define	ELANTECH_HW_IS_V1(fwver) ((fwver) < 0x020030 || (fwver) == 0x020600)
336 
337 #define	ELANTECH_MAGIC(magic)				\
338 	((magic)[0] == 0x3c && (magic)[1] == 0x03 &&	\
339 	((magic)[2] == 0xc8 || (magic)[2] == 0x00))
340 
341 #define	ELANTECH_FW_ID		0x00
342 #define	ELANTECH_FW_VERSION	0x01
343 #define	ELANTECH_CAPABILITIES	0x02
344 #define	ELANTECH_SAMPLE		0x03
345 #define	ELANTECH_RESOLUTION	0x04
346 #define	ELANTECH_REG_READ	0x10
347 #define	ELANTECH_REG_WRITE	0x11
348 #define	ELANTECH_REG_RDWR	0x00
349 #define	ELANTECH_CUSTOM_CMD	0xf8
350 
351 #ifdef EVDEV_SUPPORT
352 #define	ELANTECH_MAX_FINGERS	5
353 #else
354 #define	ELANTECH_MAX_FINGERS	PSM_FINGERS
355 #endif
356 
357 #define	ELANTECH_FINGER_MAX_P	255
358 #define	ELANTECH_FINGER_MAX_W	15
359 #define	ELANTECH_FINGER_SET_XYP(pb) (finger_t) {			\
360     .x = (((pb)->ipacket[1] & 0x0f) << 8) | (pb)->ipacket[2],		\
361     .y = (((pb)->ipacket[4] & 0x0f) << 8) | (pb)->ipacket[5],		\
362     .p = ((pb)->ipacket[1] & 0xf0) | (((pb)->ipacket[4] >> 4) & 0x0f),	\
363     .w = PSM_FINGER_DEFAULT_W,						\
364     .flags = 0								\
365 }
366 
367 enum {
368 	ELANTECH_PKT_NOP,
369 	ELANTECH_PKT_TRACKPOINT,
370 	ELANTECH_PKT_V2_COMMON,
371 	ELANTECH_PKT_V2_2FINGER,
372 	ELANTECH_PKT_V3,
373 	ELANTECH_PKT_V4_STATUS,
374 	ELANTECH_PKT_V4_HEAD,
375 	ELANTECH_PKT_V4_MOTION
376 };
377 
378 #define	ELANTECH_PKT_IS_TRACKPOINT(pb) (((pb)->ipacket[3] & 0x0f) == 0x06)
379 #define	ELANTECH_PKT_IS_DEBOUNCE(pb, hwversion) ((hwversion) == 4 ? 0 :	\
380     (pb)->ipacket[0] == ((hwversion) == 2 ? 0x84 : 0xc4) &&		\
381     (pb)->ipacket[1] == 0xff && (pb)->ipacket[2] == 0xff &&		\
382     (pb)->ipacket[3] == 0x02 && (pb)->ipacket[4] == 0xff &&		\
383     (pb)->ipacket[5] == 0xff)
384 #define	ELANTECH_PKT_IS_V2(pb) 						\
385     (((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0x0f) == 0x02)
386 #define	ELANTECH_PKT_IS_V3_HEAD(pb, hascrc) ((hascrc) ? 		\
387     ((pb)->ipacket[3] & 0x09) == 0x08 : 				\
388     ((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0xcf) == 0x02)
389 #define	ELANTECH_PKT_IS_V3_TAIL(pb, hascrc) ((hascrc) ? 		\
390     ((pb)->ipacket[3] & 0x09) == 0x09 : 				\
391     ((pb)->ipacket[0] & 0x0c) == 0x0c && ((pb)->ipacket[3] & 0xce) == 0x0c)
392 #define	ELANTECH_PKT_IS_V4(pb, hascrc) ((hascrc) ? 			\
393     ((pb)->ipacket[3] & 0x08) == 0x00 :					\
394     ((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0x1c) == 0x10)
395 
396 typedef struct elantechaction {
397 	finger_t		fingers[ELANTECH_MAX_FINGERS];
398 	int			mask;
399 	int			mask_v4wait;
400 } elantechaction_t;
401 
402 /* driver control block */
403 struct psm_softc {		/* Driver status information */
404 	int		unit;
405 	struct selinfo	rsel;		/* Process selecting for Input */
406 	u_char		state;		/* Mouse driver state */
407 	int		config;		/* driver configuration flags */
408 	int		flags;		/* other flags */
409 	KBDC		kbdc;		/* handle to access kbd controller */
410 	struct resource	*intr;		/* IRQ resource */
411 	void		*ih;		/* interrupt handle */
412 	mousehw_t	hw;		/* hardware information */
413 	synapticshw_t	synhw;		/* Synaptics hardware information */
414 	synapticsinfo_t	syninfo;	/* Synaptics configuration */
415 	smoother_t	smoother[PSM_FINGERS];	/* Motion smoothing */
416 	gesture_t	gesture;	/* Gesture context */
417 	elantechhw_t	elanhw;		/* Elantech hardware information */
418 	elantechaction_t elanaction;	/* Elantech action context */
419 	int		tphw;		/* TrackPoint hardware information */
420 	trackpointinfo_t tpinfo;	/* TrackPoint configuration */
421 	mousemode_t	mode;		/* operation mode */
422 	mousemode_t	dflt_mode;	/* default operation mode */
423 	mousestatus_t	status;		/* accumulated mouse movement */
424 	ringbuf_t	queue;		/* mouse status queue */
425 	packetbuf_t	pqueue[PSM_PACKETQUEUE]; /* mouse data queue */
426 	int		pqueue_start;	/* start of data in queue */
427 	int		pqueue_end;	/* end of data in queue */
428 	int		button;		/* the latest button state */
429 	int		xold;		/* previous absolute X position */
430 	int		yold;		/* previous absolute Y position */
431 	int		xaverage;	/* average X position */
432 	int		yaverage;	/* average Y position */
433 	int		squelch; /* level to filter movement at low speed */
434 	int		syncerrors; /* # of bytes discarded to synchronize */
435 	int		pkterrors;  /* # of packets failed during quaranteen. */
436 	int		fpcount;	/* forcePad valid packet counter */
437 	struct timeval	inputtimeout;
438 	struct timeval	lastsoftintr;	/* time of last soft interrupt */
439 	struct timeval	lastinputerr;	/* time last sync error happened */
440 	struct timeval	idletimeout;
441 	packetbuf_t	idlepacket;	/* packet to send after idle timeout */
442 	int		watchdog;	/* watchdog timer flag */
443 	struct callout	callout;	/* watchdog timer call out */
444 	struct callout	softcallout; /* buffer timer call out */
445 	struct cdev	*dev;
446 	struct cdev	*bdev;
447 	int		lasterr;
448 	int		cmdcount;
449 	struct sigio	*async;		/* Processes waiting for SIGIO */
450 	int		extended_buttons;
451 #ifdef EVDEV_SUPPORT
452 	struct evdev_dev *evdev_a;	/* Absolute reporting device */
453 	struct evdev_dev *evdev_r;	/* Relative reporting device */
454 #endif
455 };
456 static devclass_t psm_devclass;
457 
458 /* driver state flags (state) */
459 #define	PSM_VALID		0x80
460 #define	PSM_OPEN		1	/* Device is open */
461 #define	PSM_ASLP		2	/* Waiting for mouse data */
462 #define	PSM_SOFTARMED		4	/* Software interrupt armed */
463 #define	PSM_NEED_SYNCBITS	8	/* Set syncbits using next data pkt */
464 #define	PSM_EV_OPEN_R		0x10	/* Relative evdev device is open */
465 #define	PSM_EV_OPEN_A		0x20	/* Absolute evdev device is open */
466 
467 /* driver configuration flags (config) */
468 #define	PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
469 #define	PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
470 #define	PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
471 #define	PSM_CONFIG_NOIDPROBE	0x0200  /* disable mouse model probe */
472 #define	PSM_CONFIG_NORESET	0x0400  /* don't reset the mouse */
473 #define	PSM_CONFIG_FORCETAP	0x0800  /* assume `tap' action exists */
474 #define	PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
475 #define	PSM_CONFIG_HOOKRESUME	0x2000	/* hook the system resume event */
476 #define	PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
477 
478 #define	PSM_CONFIG_FLAGS	\
479     (PSM_CONFIG_RESOLUTION |	\
480     PSM_CONFIG_ACCEL |		\
481     PSM_CONFIG_NOCHECKSYNC |	\
482     PSM_CONFIG_NOIDPROBE |	\
483     PSM_CONFIG_NORESET |	\
484     PSM_CONFIG_FORCETAP |	\
485     PSM_CONFIG_IGNPORTERROR |	\
486     PSM_CONFIG_HOOKRESUME |	\
487     PSM_CONFIG_INITAFTERSUSPEND)
488 
489 /* other flags (flags) */
490 #define	PSM_FLAGS_FINGERDOWN	0x0001	/* VersaPad finger down */
491 
492 #define kbdcp(p)			((atkbdc_softc_t *)(p))
493 #define ALWAYS_RESTORE_CONTROLLER(kbdc)	!(kbdcp(kbdc)->quirks \
494     & KBDC_QUIRK_KEEP_ACTIVATED)
495 
496 /* Tunables */
497 static int tap_enabled = -1;
498 static int verbose = PSM_DEBUG;
499 static int synaptics_support = 0;
500 static int trackpoint_support = 0;
501 static int elantech_support = 0;
502 
503 /* for backward compatibility */
504 #define	OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
505 #define	OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
506 #define	OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)
507 
508 typedef struct old_mousehw {
509 	int	buttons;
510 	int	iftype;
511 	int	type;
512 	int	hwid;
513 } old_mousehw_t;
514 
515 typedef struct old_mousemode {
516 	int	protocol;
517 	int	rate;
518 	int	resolution;
519 	int	accelfactor;
520 } old_mousemode_t;
521 
522 #define SYN_OFFSET(field) offsetof(struct psm_softc, syninfo.field)
523 enum {
524 	SYNAPTICS_SYSCTL_MIN_PRESSURE =		SYN_OFFSET(min_pressure),
525 	SYNAPTICS_SYSCTL_MAX_PRESSURE =		SYN_OFFSET(max_pressure),
526 	SYNAPTICS_SYSCTL_MAX_WIDTH =		SYN_OFFSET(max_width),
527 	SYNAPTICS_SYSCTL_MARGIN_TOP =		SYN_OFFSET(margin_top),
528 	SYNAPTICS_SYSCTL_MARGIN_RIGHT =		SYN_OFFSET(margin_right),
529 	SYNAPTICS_SYSCTL_MARGIN_BOTTOM =	SYN_OFFSET(margin_bottom),
530 	SYNAPTICS_SYSCTL_MARGIN_LEFT =		SYN_OFFSET(margin_left),
531 	SYNAPTICS_SYSCTL_NA_TOP =		SYN_OFFSET(na_top),
532 	SYNAPTICS_SYSCTL_NA_RIGHT =		SYN_OFFSET(na_right),
533 	SYNAPTICS_SYSCTL_NA_BOTTOM =		SYN_OFFSET(na_bottom),
534 	SYNAPTICS_SYSCTL_NA_LEFT = 		SYN_OFFSET(na_left),
535 	SYNAPTICS_SYSCTL_WINDOW_MIN =		SYN_OFFSET(window_min),
536 	SYNAPTICS_SYSCTL_WINDOW_MAX =		SYN_OFFSET(window_max),
537 	SYNAPTICS_SYSCTL_MULTIPLICATOR =	SYN_OFFSET(multiplicator),
538 	SYNAPTICS_SYSCTL_WEIGHT_CURRENT =	SYN_OFFSET(weight_current),
539 	SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS =	SYN_OFFSET(weight_previous),
540 	SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA =	SYN_OFFSET(weight_previous_na),
541 	SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED =	SYN_OFFSET(weight_len_squared),
542 	SYNAPTICS_SYSCTL_DIV_MIN =		SYN_OFFSET(div_min),
543 	SYNAPTICS_SYSCTL_DIV_MAX =		SYN_OFFSET(div_max),
544 	SYNAPTICS_SYSCTL_DIV_MAX_NA =		SYN_OFFSET(div_max_na),
545 	SYNAPTICS_SYSCTL_DIV_LEN =		SYN_OFFSET(div_len),
546 	SYNAPTICS_SYSCTL_TAP_MAX_DELTA =	SYN_OFFSET(tap_max_delta),
547 	SYNAPTICS_SYSCTL_TAP_MIN_QUEUE =	SYN_OFFSET(tap_min_queue),
548 	SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT =	SYN_OFFSET(taphold_timeout),
549 	SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA =	SYN_OFFSET(vscroll_hor_area),
550 	SYNAPTICS_SYSCTL_VSCROLL_VER_AREA =	SYN_OFFSET(vscroll_ver_area),
551 	SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA =	SYN_OFFSET(vscroll_min_delta),
552 	SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN =	SYN_OFFSET(vscroll_div_min),
553 	SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX =	SYN_OFFSET(vscroll_div_max),
554 	SYNAPTICS_SYSCTL_TOUCHPAD_OFF =		SYN_OFFSET(touchpad_off),
555 	SYNAPTICS_SYSCTL_SOFTBUTTONS_Y =	SYN_OFFSET(softbuttons_y),
556 	SYNAPTICS_SYSCTL_SOFTBUTTON2_X =	SYN_OFFSET(softbutton2_x),
557 	SYNAPTICS_SYSCTL_SOFTBUTTON3_X =	SYN_OFFSET(softbutton3_x),
558 };
559 
560 /* packet formatting function */
561 typedef int	packetfunc_t(struct psm_softc *, u_char *, int *, int,
562     mousestatus_t *);
563 
564 /* function prototypes */
565 static void	psmidentify(driver_t *, device_t);
566 static int	psmprobe(device_t);
567 static int	psmattach(device_t);
568 static int	psmdetach(device_t);
569 static int	psmresume(device_t);
570 
571 static d_open_t		psm_cdev_open;
572 static d_close_t	psm_cdev_close;
573 static d_read_t		psmread;
574 static d_write_t	psmwrite;
575 static d_ioctl_t	psmioctl;
576 static d_poll_t		psmpoll;
577 
578 static int	psmopen(struct psm_softc *);
579 static int	psmclose(struct psm_softc *);
580 
581 #ifdef EVDEV_SUPPORT
582 static evdev_open_t	psm_ev_open_r;
583 static evdev_close_t	psm_ev_close_r;
584 static evdev_open_t	psm_ev_open_a;
585 static evdev_close_t	psm_ev_close_a;
586 #endif
587 
588 static int	enable_aux_dev(KBDC);
589 static int	disable_aux_dev(KBDC);
590 static int	get_mouse_status(KBDC, int *, int, int);
591 static int	get_aux_id(KBDC);
592 static int	set_mouse_sampling_rate(KBDC, int);
593 static int	set_mouse_scaling(KBDC, int);
594 static int	set_mouse_resolution(KBDC, int);
595 static int	set_mouse_mode(KBDC);
596 static int	get_mouse_buttons(KBDC);
597 static int	is_a_mouse(int);
598 static void	recover_from_error(KBDC);
599 static int	restore_controller(KBDC, int);
600 static int	doinitialize(struct psm_softc *, mousemode_t *);
601 static int	doopen(struct psm_softc *, int);
602 static int	reinitialize(struct psm_softc *, int);
603 static char	*model_name(int);
604 static void	psmsoftintr(void *);
605 static void	psmsoftintridle(void *);
606 static void	psmintr(void *);
607 static void	psmtimeout(void *);
608 static int	timeelapsed(const struct timeval *, int, int,
609 		    const struct timeval *);
610 static void	dropqueue(struct psm_softc *);
611 static void	flushpackets(struct psm_softc *);
612 static void	proc_mmanplus(struct psm_softc *, packetbuf_t *,
613 		    mousestatus_t *, int *, int *, int *);
614 static int	proc_synaptics(struct psm_softc *, packetbuf_t *,
615 		    mousestatus_t *, int *, int *, int *);
616 static void	proc_versapad(struct psm_softc *, packetbuf_t *,
617 		    mousestatus_t *, int *, int *, int *);
618 static int	proc_elantech(struct psm_softc *, packetbuf_t *,
619 		    mousestatus_t *, int *, int *, int *);
620 static int	psmpalmdetect(struct psm_softc *, finger_t *, int);
621 static void	psmgestures(struct psm_softc *, finger_t *, int,
622 		    mousestatus_t *);
623 static void	psmsmoother(struct psm_softc *, finger_t *, int,
624 		    mousestatus_t *, int *, int *);
625 static int	tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *,
626 		    u_char *);
627 
628 /* vendor specific features */
629 enum probearg { PROBE, REINIT };
630 typedef int	probefunc_t(struct psm_softc *, enum probearg);
631 
632 static int	mouse_id_proc1(KBDC, int, int, int *);
633 static int	mouse_ext_command(KBDC, int);
634 
635 static probefunc_t	enable_groller;
636 static probefunc_t	enable_gmouse;
637 static probefunc_t	enable_aglide;
638 static probefunc_t	enable_kmouse;
639 static probefunc_t	enable_msexplorer;
640 static probefunc_t	enable_msintelli;
641 static probefunc_t	enable_4dmouse;
642 static probefunc_t	enable_4dplus;
643 static probefunc_t	enable_mmanplus;
644 static probefunc_t	enable_synaptics;
645 static probefunc_t	enable_trackpoint;
646 static probefunc_t	enable_versapad;
647 static probefunc_t	enable_elantech;
648 
649 static void set_trackpoint_parameters(struct psm_softc *sc);
650 static void synaptics_passthrough_on(struct psm_softc *sc);
651 static void synaptics_passthrough_off(struct psm_softc *sc);
652 static int synaptics_preferred_mode(struct psm_softc *sc);
653 static void synaptics_set_mode(struct psm_softc *sc, int mode_byte);
654 
655 static struct {
656 	int		model;
657 	u_char		syncmask;
658 	int		packetsize;
659 	probefunc_t	*probefunc;
660 } vendortype[] = {
661 	/*
662 	 * WARNING: the order of probe is very important.  Don't mess it
663 	 * unless you know what you are doing.
664 	 */
665 	{ MOUSE_MODEL_NET,		/* Genius NetMouse */
666 	  0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse },
667 	{ MOUSE_MODEL_NETSCROLL,	/* Genius NetScroll */
668 	  0xc8, 6, enable_groller },
669 	{ MOUSE_MODEL_MOUSEMANPLUS,	/* Logitech MouseMan+ */
670 	  0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus },
671 	{ MOUSE_MODEL_EXPLORER,		/* Microsoft IntelliMouse Explorer */
672 	  0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer },
673 	{ MOUSE_MODEL_4D,		/* A4 Tech 4D Mouse */
674 	  0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse },
675 	{ MOUSE_MODEL_4DPLUS,		/* A4 Tech 4D+ Mouse */
676 	  0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus },
677 	{ MOUSE_MODEL_SYNAPTICS,	/* Synaptics Touchpad */
678 	  0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics },
679 	{ MOUSE_MODEL_ELANTECH,		/* Elantech Touchpad */
680 	  0x04, MOUSE_ELANTECH_PACKETSIZE, enable_elantech },
681 	{ MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
682 	  0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli },
683 	{ MOUSE_MODEL_GLIDEPOINT,	/* ALPS GlidePoint */
684 	  0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide },
685 	{ MOUSE_MODEL_THINK,		/* Kensington ThinkingMouse */
686 	  0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse },
687 	{ MOUSE_MODEL_VERSAPAD,		/* Interlink electronics VersaPad */
688 	  0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad },
689 	{ MOUSE_MODEL_TRACKPOINT,	/* IBM/Lenovo TrackPoint */
690 	  0xc0, MOUSE_PS2_PACKETSIZE, enable_trackpoint },
691 	{ MOUSE_MODEL_GENERIC,
692 	  0xc0, MOUSE_PS2_PACKETSIZE, NULL },
693 };
694 #define	GENERIC_MOUSE_ENTRY (nitems(vendortype) - 1)
695 
696 /* device driver declarateion */
697 static device_method_t psm_methods[] = {
698 	/* Device interface */
699 	DEVMETHOD(device_identify,	psmidentify),
700 	DEVMETHOD(device_probe,		psmprobe),
701 	DEVMETHOD(device_attach,	psmattach),
702 	DEVMETHOD(device_detach,	psmdetach),
703 	DEVMETHOD(device_resume,	psmresume),
704 
705 	{ 0, 0 }
706 };
707 
708 static driver_t psm_driver = {
709 	PSM_DRIVER_NAME,
710 	psm_methods,
711 	sizeof(struct psm_softc),
712 };
713 
714 static struct cdevsw psm_cdevsw = {
715 	.d_version =	D_VERSION,
716 	.d_flags =	D_NEEDGIANT,
717 	.d_open =	psm_cdev_open,
718 	.d_close =	psm_cdev_close,
719 	.d_read =	psmread,
720 	.d_write =	psmwrite,
721 	.d_ioctl =	psmioctl,
722 	.d_poll =	psmpoll,
723 	.d_name =	PSM_DRIVER_NAME,
724 };
725 
726 #ifdef EVDEV_SUPPORT
727 static const struct evdev_methods psm_ev_methods_r = {
728 	.ev_open = psm_ev_open_r,
729 	.ev_close = psm_ev_close_r,
730 };
731 static const struct evdev_methods psm_ev_methods_a = {
732 	.ev_open = psm_ev_open_a,
733 	.ev_close = psm_ev_close_a,
734 };
735 #endif
736 
737 /* device I/O routines */
738 static int
739 enable_aux_dev(KBDC kbdc)
740 {
741 	int res;
742 
743 	res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
744 	VLOG(2, (LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res));
745 
746 	return (res == PSM_ACK);
747 }
748 
749 static int
750 disable_aux_dev(KBDC kbdc)
751 {
752 	int res;
753 
754 	res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
755 	VLOG(2, (LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res));
756 
757 	return (res == PSM_ACK);
758 }
759 
760 static int
761 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
762 {
763 	int cmd;
764 	int res;
765 	int i;
766 
767 	switch (flag) {
768 	case 0:
769 	default:
770 		cmd = PSMC_SEND_DEV_STATUS;
771 		break;
772 	case 1:
773 		cmd = PSMC_SEND_DEV_DATA;
774 		break;
775 	}
776 	empty_aux_buffer(kbdc, 5);
777 	res = send_aux_command(kbdc, cmd);
778 	VLOG(2, (LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
779 	    (flag == 1) ? "DATA" : "STATUS", res));
780 	if (res != PSM_ACK)
781 		return (0);
782 
783 	for (i = 0; i < len; ++i) {
784 		status[i] = read_aux_data(kbdc);
785 		if (status[i] < 0)
786 			break;
787 	}
788 	if (len >= 3) {
789 		for (; i < 3; ++i)
790 			status[i] = 0;
791 		VLOG(1, (LOG_DEBUG, "psm: %s %02x %02x %02x\n",
792 		    (flag == 1) ? "data" : "status", status[0], status[1], status[2]));
793 	}
794 
795 	return (i);
796 }
797 
798 static int
799 get_aux_id(KBDC kbdc)
800 {
801 	int res;
802 	int id;
803 
804 	empty_aux_buffer(kbdc, 5);
805 	res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
806 	VLOG(2, (LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res));
807 	if (res != PSM_ACK)
808 		return (-1);
809 
810 	/* 10ms delay */
811 	DELAY(10000);
812 
813 	id = read_aux_data(kbdc);
814 	VLOG(2, (LOG_DEBUG, "psm: device ID: %04x\n", id));
815 
816 	return (id);
817 }
818 
819 static int
820 set_mouse_sampling_rate(KBDC kbdc, int rate)
821 {
822 	int res;
823 
824 	res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
825 	VLOG(2, (LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res));
826 
827 	return ((res == PSM_ACK) ? rate : -1);
828 }
829 
830 static int
831 set_mouse_scaling(KBDC kbdc, int scale)
832 {
833 	int res;
834 
835 	switch (scale) {
836 	case 1:
837 	default:
838 		scale = PSMC_SET_SCALING11;
839 		break;
840 	case 2:
841 		scale = PSMC_SET_SCALING21;
842 		break;
843 	}
844 	res = send_aux_command(kbdc, scale);
845 	VLOG(2, (LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
846 	    (scale == PSMC_SET_SCALING21) ? "21" : "11", res));
847 
848 	return (res == PSM_ACK);
849 }
850 
851 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
852 static int
853 set_mouse_resolution(KBDC kbdc, int val)
854 {
855 	int res;
856 
857 	res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
858 	VLOG(2, (LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res));
859 
860 	return ((res == PSM_ACK) ? val : -1);
861 }
862 
863 /*
864  * NOTE: once `set_mouse_mode()' is called, the mouse device must be
865  * re-enabled by calling `enable_aux_dev()'
866  */
867 static int
868 set_mouse_mode(KBDC kbdc)
869 {
870 	int res;
871 
872 	res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
873 	VLOG(2, (LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res));
874 
875 	return (res == PSM_ACK);
876 }
877 
878 static int
879 get_mouse_buttons(KBDC kbdc)
880 {
881 	int c = 2;		/* assume two buttons by default */
882 	int status[3];
883 
884 	/*
885 	 * NOTE: a special sequence to obtain Logitech Mouse specific
886 	 * information: set resolution to 25 ppi, set scaling to 1:1, set
887 	 * scaling to 1:1, set scaling to 1:1. Then the second byte of the
888 	 * mouse status bytes is the number of available buttons.
889 	 * Some manufactures also support this sequence.
890 	 */
891 	if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
892 		return (c);
893 	if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1) &&
894 	    set_mouse_scaling(kbdc, 1) &&
895 	    get_mouse_status(kbdc, status, 0, 3) >= 3 && status[1] != 0)
896 		return (status[1]);
897 	return (c);
898 }
899 
900 /* misc subroutines */
901 /*
902  * Someday, I will get the complete list of valid pointing devices and
903  * their IDs... XXX
904  */
905 static int
906 is_a_mouse(int id)
907 {
908 #if 0
909 	static int valid_ids[] = {
910 		PSM_MOUSE_ID,		/* mouse */
911 		PSM_BALLPOINT_ID,	/* ballpoint device */
912 		PSM_INTELLI_ID,		/* Intellimouse */
913 		PSM_EXPLORER_ID,	/* Intellimouse Explorer */
914 		-1			/* end of table */
915 	};
916 	int i;
917 
918 	for (i = 0; valid_ids[i] >= 0; ++i)
919 	if (valid_ids[i] == id)
920 		return (TRUE);
921 	return (FALSE);
922 #else
923 	return (TRUE);
924 #endif
925 }
926 
927 static char *
928 model_name(int model)
929 {
930 	static struct {
931 		int	model_code;
932 		char	*model_name;
933 	} models[] = {
934 		{ MOUSE_MODEL_NETSCROLL,	"NetScroll" },
935 		{ MOUSE_MODEL_NET,		"NetMouse/NetScroll Optical" },
936 		{ MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
937 		{ MOUSE_MODEL_THINK,		"ThinkingMouse" },
938 		{ MOUSE_MODEL_INTELLI,		"IntelliMouse" },
939 		{ MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
940 		{ MOUSE_MODEL_VERSAPAD,		"VersaPad" },
941 		{ MOUSE_MODEL_EXPLORER,		"IntelliMouse Explorer" },
942 		{ MOUSE_MODEL_4D,		"4D Mouse" },
943 		{ MOUSE_MODEL_4DPLUS,		"4D+ Mouse" },
944 		{ MOUSE_MODEL_SYNAPTICS,	"Synaptics Touchpad" },
945 		{ MOUSE_MODEL_TRACKPOINT,	"IBM/Lenovo TrackPoint" },
946 		{ MOUSE_MODEL_ELANTECH,		"Elantech Touchpad" },
947 		{ MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
948 		{ MOUSE_MODEL_UNKNOWN,		"Unknown" },
949 	};
950 	int i;
951 
952 	for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i)
953 		if (models[i].model_code == model)
954 			break;
955 	return (models[i].model_name);
956 }
957 
958 static void
959 recover_from_error(KBDC kbdc)
960 {
961 	/* discard anything left in the output buffer */
962 	empty_both_buffers(kbdc, 10);
963 
964 #if 0
965 	/*
966 	 * NOTE: KBDC_RESET_KBD may not restore the communication between the
967 	 * keyboard and the controller.
968 	 */
969 	reset_kbd(kbdc);
970 #else
971 	/*
972 	 * NOTE: somehow diagnostic and keyboard port test commands bring the
973 	 * keyboard back.
974 	 */
975 	if (!test_controller(kbdc))
976 		log(LOG_ERR, "psm: keyboard controller failed.\n");
977 	/* if there isn't a keyboard in the system, the following error is OK */
978 	if (test_kbd_port(kbdc) != 0)
979 		VLOG(1, (LOG_ERR, "psm: keyboard port failed.\n"));
980 #endif
981 }
982 
983 static int
984 restore_controller(KBDC kbdc, int command_byte)
985 {
986 	empty_both_buffers(kbdc, 10);
987 
988 	if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
989 		log(LOG_ERR, "psm: failed to restore the keyboard controller "
990 		    "command byte.\n");
991 		empty_both_buffers(kbdc, 10);
992 		return (FALSE);
993 	} else {
994 		empty_both_buffers(kbdc, 10);
995 		return (TRUE);
996 	}
997 }
998 
999 /*
1000  * Re-initialize the aux port and device. The aux port must be enabled
1001  * and its interrupt must be disabled before calling this routine.
1002  * The aux device will be disabled before returning.
1003  * The keyboard controller must be locked via `kbdc_lock()' before
1004  * calling this routine.
1005  */
1006 static int
1007 doinitialize(struct psm_softc *sc, mousemode_t *mode)
1008 {
1009 	KBDC kbdc = sc->kbdc;
1010 	int stat[3];
1011 	int i;
1012 
1013 	switch((i = test_aux_port(kbdc))) {
1014 	case 1:	/* ignore these errors */
1015 	case 2:
1016 	case 3:
1017 	case PSM_ACK:
1018 		if (verbose)
1019 			log(LOG_DEBUG,
1020 			    "psm%d: strange result for test aux port (%d).\n",
1021 			    sc->unit, i);
1022 		/* FALLTHROUGH */
1023 	case 0:		/* no error */
1024 		break;
1025 	case -1:	/* time out */
1026 	default:	/* error */
1027 		recover_from_error(kbdc);
1028 		if (sc->config & PSM_CONFIG_IGNPORTERROR)
1029 			break;
1030 		log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
1031 		    sc->unit, i);
1032 		return (FALSE);
1033 	}
1034 
1035 	if (sc->config & PSM_CONFIG_NORESET) {
1036 		/*
1037 		 * Don't try to reset the pointing device.  It may possibly
1038 		 * be left in the unknown state, though...
1039 		 */
1040 	} else {
1041 		/*
1042 		 * NOTE: some controllers appears to hang the `keyboard' when
1043 		 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
1044 		 */
1045 		if (!reset_aux_dev(kbdc)) {
1046 			recover_from_error(kbdc);
1047 			log(LOG_ERR, "psm%d: failed to reset the aux device.\n",
1048 			    sc->unit);
1049 			return (FALSE);
1050 		}
1051 	}
1052 
1053 	/*
1054 	 * both the aux port and the aux device is functioning, see
1055 	 * if the device can be enabled.
1056 	 */
1057 	if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
1058 		log(LOG_ERR, "psm%d: failed to enable the aux device.\n",
1059 		    sc->unit);
1060 		return (FALSE);
1061 	}
1062 	empty_both_buffers(kbdc, 10);	/* remove stray data if any */
1063 
1064 	/* Re-enable the mouse. */
1065 	for (i = 0; vendortype[i].probefunc != NULL; ++i)
1066 		if (vendortype[i].model == sc->hw.model)
1067 			(*vendortype[i].probefunc)(sc, REINIT);
1068 
1069 	/* set mouse parameters */
1070 	if (mode != (mousemode_t *)NULL) {
1071 		if (mode->rate > 0)
1072 			mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
1073 		if (mode->resolution >= 0)
1074 			mode->resolution =
1075 			    set_mouse_resolution(kbdc, mode->resolution);
1076 		set_mouse_scaling(kbdc, 1);
1077 		set_mouse_mode(kbdc);
1078 	}
1079 
1080 	/* Record sync on the next data packet we see. */
1081 	sc->flags |= PSM_NEED_SYNCBITS;
1082 
1083 	/* just check the status of the mouse */
1084 	if (get_mouse_status(kbdc, stat, 0, 3) < 3)
1085 		log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
1086 		    sc->unit);
1087 
1088 	return (TRUE);
1089 }
1090 
1091 static int
1092 doopen(struct psm_softc *sc, int command_byte)
1093 {
1094 	int stat[3];
1095 
1096 	/*
1097 	 * FIXME: Synaptics TouchPad seems to go back to Relative Mode with
1098 	 * no obvious reason. Thus we check the current mode and restore the
1099 	 * Absolute Mode if it was cleared.
1100 	 *
1101 	 * The previous hack at the end of psmprobe() wasn't efficient when
1102 	 * moused(8) was restarted.
1103 	 *
1104 	 * A Reset (FF) or Set Defaults (F6) command would clear the
1105 	 * Absolute Mode bit. But a verbose boot or debug.psm.loglevel=5
1106 	 * doesn't show any evidence of such a command.
1107 	 */
1108 	if (sc->hw.model == MOUSE_MODEL_SYNAPTICS) {
1109 		mouse_ext_command(sc->kbdc, 1);
1110 		get_mouse_status(sc->kbdc, stat, 0, 3);
1111 		if ((SYNAPTICS_VERSION_GE(sc->synhw, 7, 5) ||
1112 		     stat[1] == 0x46 || stat[1] == 0x47) &&
1113 		     stat[2] == 0x40) {
1114 			synaptics_set_mode(sc, synaptics_preferred_mode(sc));
1115 			VLOG(5, (LOG_DEBUG, "psm%d: Synaptis Absolute Mode "
1116 			    "hopefully restored\n",
1117 			    sc->unit));
1118 		}
1119 	}
1120 
1121 	/*
1122 	 * A user may want to disable tap and drag gestures on a Synaptics
1123 	 * TouchPad when it operates in Relative Mode.
1124 	 */
1125 	if (sc->hw.model == MOUSE_MODEL_GENERIC) {
1126 		if (tap_enabled > 0) {
1127 			VLOG(2, (LOG_DEBUG,
1128 			    "psm%d: enable tap and drag gestures\n",
1129 			    sc->unit));
1130 			synaptics_set_mode(sc, synaptics_preferred_mode(sc));
1131 		} else if (tap_enabled == 0) {
1132 			VLOG(2, (LOG_DEBUG,
1133 			    "psm%d: disable tap and drag gestures\n",
1134 			    sc->unit));
1135 			synaptics_set_mode(sc, synaptics_preferred_mode(sc));
1136 		}
1137 	}
1138 
1139 	/* enable the mouse device */
1140 	if (!enable_aux_dev(sc->kbdc)) {
1141 		/* MOUSE ERROR: failed to enable the mouse because:
1142 		 * 1) the mouse is faulty,
1143 		 * 2) the mouse has been removed(!?)
1144 		 * In the latter case, the keyboard may have hung, and need
1145 		 * recovery procedure...
1146 		 */
1147 		recover_from_error(sc->kbdc);
1148 #if 0
1149 		/* FIXME: we could reset the mouse here and try to enable
1150 		 * it again. But it will take long time and it's not a good
1151 		 * idea to disable the keyboard that long...
1152 		 */
1153 		if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
1154 			recover_from_error(sc->kbdc);
1155 #else
1156 		{
1157 #endif
1158 			restore_controller(sc->kbdc, command_byte);
1159 			/* mark this device is no longer available */
1160 			sc->state &= ~PSM_VALID;
1161 			log(LOG_ERR,
1162 			    "psm%d: failed to enable the device (doopen).\n",
1163 			sc->unit);
1164 			return (EIO);
1165 		}
1166 	}
1167 
1168 	if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1169 		log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n",
1170 		    sc->unit);
1171 
1172 	/* enable the aux port and interrupt */
1173 	if (!set_controller_command_byte(sc->kbdc,
1174 	    kbdc_get_device_mask(sc->kbdc),
1175 	    (command_byte & KBD_KBD_CONTROL_BITS) |
1176 	    KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
1177 		/* CONTROLLER ERROR */
1178 		disable_aux_dev(sc->kbdc);
1179 		restore_controller(sc->kbdc, command_byte);
1180 		log(LOG_ERR,
1181 		    "psm%d: failed to enable the aux interrupt (doopen).\n",
1182 		    sc->unit);
1183 		return (EIO);
1184 	}
1185 
1186 	/* start the watchdog timer */
1187 	sc->watchdog = FALSE;
1188 	callout_reset(&sc->callout, hz * 2, psmtimeout, sc);
1189 
1190 	return (0);
1191 }
1192 
1193 static int
1194 reinitialize(struct psm_softc *sc, int doinit)
1195 {
1196 	int err;
1197 	int c;
1198 	int s;
1199 
1200 	/* don't let anybody mess with the aux device */
1201 	if (!kbdc_lock(sc->kbdc, TRUE))
1202 		return (EIO);
1203 	s = spltty();
1204 
1205 	/* block our watchdog timer */
1206 	sc->watchdog = FALSE;
1207 	callout_stop(&sc->callout);
1208 
1209 	/* save the current controller command byte */
1210 	empty_both_buffers(sc->kbdc, 10);
1211 	c = get_controller_command_byte(sc->kbdc);
1212 	VLOG(2, (LOG_DEBUG,
1213 	    "psm%d: current command byte: %04x (reinitialize).\n",
1214 	    sc->unit, c));
1215 
1216 	/* enable the aux port but disable the aux interrupt and the keyboard */
1217 	if ((c == -1) || !set_controller_command_byte(sc->kbdc,
1218 	    kbdc_get_device_mask(sc->kbdc),
1219 	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1220 	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1221 		/* CONTROLLER ERROR */
1222 		splx(s);
1223 		kbdc_lock(sc->kbdc, FALSE);
1224 		log(LOG_ERR,
1225 		    "psm%d: unable to set the command byte (reinitialize).\n",
1226 		    sc->unit);
1227 		return (EIO);
1228 	}
1229 
1230 	/* flush any data */
1231 	if (sc->state & PSM_VALID) {
1232 		/* this may fail; but never mind... */
1233 		disable_aux_dev(sc->kbdc);
1234 		empty_aux_buffer(sc->kbdc, 10);
1235 	}
1236 	flushpackets(sc);
1237 	sc->syncerrors = 0;
1238 	sc->pkterrors = 0;
1239 	memset(&sc->lastinputerr, 0, sizeof(sc->lastinputerr));
1240 
1241 	/* try to detect the aux device; are you still there? */
1242 	err = 0;
1243 	if (doinit) {
1244 		if (doinitialize(sc, &sc->mode)) {
1245 			/* yes */
1246 			sc->state |= PSM_VALID;
1247 		} else {
1248 			/* the device has gone! */
1249 			restore_controller(sc->kbdc, c);
1250 			sc->state &= ~PSM_VALID;
1251 			log(LOG_ERR,
1252 			    "psm%d: the aux device has gone! (reinitialize).\n",
1253 			    sc->unit);
1254 			err = ENXIO;
1255 		}
1256 	}
1257 	splx(s);
1258 
1259 	/* restore the driver state */
1260 	if ((sc->state & (PSM_OPEN | PSM_EV_OPEN_R | PSM_EV_OPEN_A)) &&
1261 	    (err == 0)) {
1262 		/* enable the aux device and the port again */
1263 		err = doopen(sc, c);
1264 		if (err != 0)
1265 			log(LOG_ERR, "psm%d: failed to enable the device "
1266 			    "(reinitialize).\n", sc->unit);
1267 	} else {
1268 		/* restore the keyboard port and disable the aux port */
1269 		if (!set_controller_command_byte(sc->kbdc,
1270 		    kbdc_get_device_mask(sc->kbdc),
1271 		    (c & KBD_KBD_CONTROL_BITS) |
1272 		    KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1273 			/* CONTROLLER ERROR */
1274 			log(LOG_ERR, "psm%d: failed to disable the aux port "
1275 			    "(reinitialize).\n", sc->unit);
1276 			err = EIO;
1277 		}
1278 	}
1279 
1280 	kbdc_lock(sc->kbdc, FALSE);
1281 	return (err);
1282 }
1283 
1284 /* psm driver entry points */
1285 
1286 static void
1287 psmidentify(driver_t *driver, device_t parent)
1288 {
1289 	device_t psmc;
1290 	device_t psm;
1291 	u_long irq;
1292 	int unit;
1293 
1294 	unit = device_get_unit(parent);
1295 
1296 	/* always add at least one child */
1297 	psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
1298 	if (psm == NULL)
1299 		return;
1300 
1301 	irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
1302 	if (irq > 0)
1303 		return;
1304 
1305 	/*
1306 	 * If the PS/2 mouse device has already been reported by ACPI or
1307 	 * PnP BIOS, obtain the IRQ resource from it.
1308 	 * (See psmcpnp_attach() below.)
1309 	 */
1310 	psmc = device_find_child(device_get_parent(parent),
1311 	    PSMCPNP_DRIVER_NAME, unit);
1312 	if (psmc == NULL)
1313 		return;
1314 	irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
1315 	if (irq <= 0)
1316 		return;
1317 	bus_delete_resource(psmc, SYS_RES_IRQ, 0);
1318 	bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
1319 }
1320 
1321 #define	endprobe(v)	do {			\
1322 	if (bootverbose)			\
1323 		--verbose;			\
1324 	kbdc_set_device_mask(sc->kbdc, mask);	\
1325 	kbdc_lock(sc->kbdc, FALSE);		\
1326 	return (v);				\
1327 } while (0)
1328 
1329 static int
1330 psmprobe(device_t dev)
1331 {
1332 	int unit = device_get_unit(dev);
1333 	struct psm_softc *sc = device_get_softc(dev);
1334 	int stat[3];
1335 	int command_byte;
1336 	int mask;
1337 	int rid;
1338 	int i;
1339 
1340 #if 0
1341 	kbdc_debug(TRUE);
1342 #endif
1343 
1344 	/* see if IRQ is available */
1345 	rid = KBDC_RID_AUX;
1346 	sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1347 	if (sc->intr == NULL) {
1348 		if (bootverbose)
1349 			device_printf(dev, "unable to allocate IRQ\n");
1350 		return (ENXIO);
1351 	}
1352 	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1353 
1354 	sc->unit = unit;
1355 	sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
1356 	sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
1357 	/* XXX: for backward compatibility */
1358 #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
1359 	sc->config |=
1360 #ifdef PSM_RESETAFTERSUSPEND
1361 	PSM_CONFIG_INITAFTERSUSPEND;
1362 #else
1363 	PSM_CONFIG_HOOKRESUME;
1364 #endif
1365 #endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
1366 	sc->flags = 0;
1367 	if (bootverbose)
1368 		++verbose;
1369 
1370 	device_set_desc(dev, "PS/2 Mouse");
1371 
1372 	if (!kbdc_lock(sc->kbdc, TRUE)) {
1373 		printf("psm%d: unable to lock the controller.\n", unit);
1374 		if (bootverbose)
1375 			--verbose;
1376 		return (ENXIO);
1377 	}
1378 
1379 	/*
1380 	 * NOTE: two bits in the command byte controls the operation of the
1381 	 * aux port (mouse port): the aux port disable bit (bit 5) and the aux
1382 	 * port interrupt (IRQ 12) enable bit (bit 2).
1383 	 */
1384 
1385 	/* discard anything left after the keyboard initialization */
1386 	empty_both_buffers(sc->kbdc, 10);
1387 
1388 	/* save the current command byte; it will be used later */
1389 	mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
1390 	command_byte = get_controller_command_byte(sc->kbdc);
1391 	if (verbose)
1392 		printf("psm%d: current command byte:%04x\n", unit,
1393 		    command_byte);
1394 	if (command_byte == -1) {
1395 		/* CONTROLLER ERROR */
1396 		printf("psm%d: unable to get the current command byte value.\n",
1397 			unit);
1398 		endprobe(ENXIO);
1399 	}
1400 
1401 	/*
1402 	 * disable the keyboard port while probing the aux port, which must be
1403 	 * enabled during this routine
1404 	 */
1405 	if (!set_controller_command_byte(sc->kbdc,
1406 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1407 	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1408 	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1409 		/*
1410 		 * this is CONTROLLER ERROR; I don't know how to recover
1411 		 * from this error...
1412 		 */
1413 		if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1414 			restore_controller(sc->kbdc, command_byte);
1415 		printf("psm%d: unable to set the command byte.\n", unit);
1416 		endprobe(ENXIO);
1417 	}
1418 	write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
1419 
1420 	/*
1421 	 * NOTE: `test_aux_port()' is designed to return with zero if the aux
1422 	 * port exists and is functioning. However, some controllers appears
1423 	 * to respond with zero even when the aux port doesn't exist. (It may
1424 	 * be that this is only the case when the controller DOES have the aux
1425 	 * port but the port is not wired on the motherboard.) The keyboard
1426 	 * controllers without the port, such as the original AT, are
1427 	 * supposed to return with an error code or simply time out. In any
1428 	 * case, we have to continue probing the port even when the controller
1429 	 * passes this test.
1430 	 *
1431 	 * XXX: some controllers erroneously return the error code 1, 2 or 3
1432 	 * when it has a perfectly functional aux port. We have to ignore
1433 	 * this error code. Even if the controller HAS error with the aux
1434 	 * port, it will be detected later...
1435 	 * XXX: another incompatible controller returns PSM_ACK (0xfa)...
1436 	 */
1437 	switch ((i = test_aux_port(sc->kbdc))) {
1438 	case 1:		/* ignore these errors */
1439 	case 2:
1440 	case 3:
1441 	case PSM_ACK:
1442 		if (verbose)
1443 			printf("psm%d: strange result for test aux port "
1444 			    "(%d).\n", unit, i);
1445 		/* FALLTHROUGH */
1446 	case 0:		/* no error */
1447 		break;
1448 	case -1:	/* time out */
1449 	default:	/* error */
1450 		recover_from_error(sc->kbdc);
1451 		if (sc->config & PSM_CONFIG_IGNPORTERROR)
1452 			break;
1453 		if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1454 			restore_controller(sc->kbdc, command_byte);
1455 		if (verbose)
1456 			printf("psm%d: the aux port is not functioning (%d).\n",
1457 			    unit, i);
1458 		endprobe(ENXIO);
1459 	}
1460 
1461 	if (sc->config & PSM_CONFIG_NORESET) {
1462 		/*
1463 		 * Don't try to reset the pointing device.  It may possibly be
1464 		 * left in an unknown state, though...
1465 		 */
1466 	} else {
1467 		/*
1468 		 * NOTE: some controllers appears to hang the `keyboard' when
1469 		 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
1470 		 *
1471 		 * Attempt to reset the controller twice -- this helps
1472 		 * pierce through some KVM switches. The second reset
1473 		 * is non-fatal.
1474 		 */
1475 		if (!reset_aux_dev(sc->kbdc)) {
1476 			recover_from_error(sc->kbdc);
1477 			if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1478 				restore_controller(sc->kbdc, command_byte);
1479 			if (verbose)
1480 				printf("psm%d: failed to reset the aux "
1481 				    "device.\n", unit);
1482 			endprobe(ENXIO);
1483 		} else if (!reset_aux_dev(sc->kbdc)) {
1484 			recover_from_error(sc->kbdc);
1485 			if (verbose >= 2)
1486 				printf("psm%d: failed to reset the aux device "
1487 				    "(2).\n", unit);
1488 		}
1489 	}
1490 
1491 	/*
1492 	 * both the aux port and the aux device are functioning, see if the
1493 	 * device can be enabled. NOTE: when enabled, the device will start
1494 	 * sending data; we shall immediately disable the device once we know
1495 	 * the device can be enabled.
1496 	 */
1497 	if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1498 		/* MOUSE ERROR */
1499 		recover_from_error(sc->kbdc);
1500 		if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1501 			restore_controller(sc->kbdc, command_byte);
1502 		if (verbose)
1503 			printf("psm%d: failed to enable the aux device.\n",
1504 			    unit);
1505 		endprobe(ENXIO);
1506 	}
1507 
1508 	/* save the default values after reset */
1509 	if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1510 		sc->dflt_mode.rate = sc->mode.rate = stat[2];
1511 		sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1512 	} else {
1513 		sc->dflt_mode.rate = sc->mode.rate = -1;
1514 		sc->dflt_mode.resolution = sc->mode.resolution = -1;
1515 	}
1516 
1517 	/* hardware information */
1518 	sc->hw.iftype = MOUSE_IF_PS2;
1519 
1520 	/* verify the device is a mouse */
1521 	sc->hw.hwid = get_aux_id(sc->kbdc);
1522 	if (!is_a_mouse(sc->hw.hwid)) {
1523 		if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1524 			restore_controller(sc->kbdc, command_byte);
1525 		if (verbose)
1526 			printf("psm%d: unknown device type (%d).\n", unit,
1527 			    sc->hw.hwid);
1528 		endprobe(ENXIO);
1529 	}
1530 	switch (sc->hw.hwid) {
1531 	case PSM_BALLPOINT_ID:
1532 		sc->hw.type = MOUSE_TRACKBALL;
1533 		break;
1534 	case PSM_MOUSE_ID:
1535 	case PSM_INTELLI_ID:
1536 	case PSM_EXPLORER_ID:
1537 	case PSM_4DMOUSE_ID:
1538 	case PSM_4DPLUS_ID:
1539 		sc->hw.type = MOUSE_MOUSE;
1540 		break;
1541 	default:
1542 		sc->hw.type = MOUSE_UNKNOWN;
1543 		break;
1544 	}
1545 
1546 	if (sc->config & PSM_CONFIG_NOIDPROBE) {
1547 		sc->hw.buttons = 2;
1548 		i = GENERIC_MOUSE_ENTRY;
1549 	} else {
1550 		/* # of buttons */
1551 		sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1552 
1553 		/* other parameters */
1554 		for (i = 0; vendortype[i].probefunc != NULL; ++i)
1555 			if ((*vendortype[i].probefunc)(sc, PROBE)) {
1556 				if (verbose >= 2)
1557 					printf("psm%d: found %s\n", unit,
1558 					    model_name(vendortype[i].model));
1559 				break;
1560 			}
1561 	}
1562 
1563 	sc->hw.model = vendortype[i].model;
1564 
1565 	sc->dflt_mode.level = PSM_LEVEL_BASE;
1566 	sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1567 	sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1568 	if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1569 		sc->dflt_mode.syncmask[0] = 0;
1570 	else
1571 		sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1572 	if (sc->config & PSM_CONFIG_FORCETAP)
1573 		sc->dflt_mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1574 	sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
1575 	sc->mode = sc->dflt_mode;
1576 	sc->mode.packetsize = vendortype[i].packetsize;
1577 
1578 	/* set mouse parameters */
1579 #if 0
1580 	/*
1581 	 * A version of Logitech FirstMouse+ won't report wheel movement,
1582 	 * if SET_DEFAULTS is sent...  Don't use this command.
1583 	 * This fix was found by Takashi Nishida.
1584 	 */
1585 	i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1586 	if (verbose >= 2)
1587 		printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1588 #endif
1589 	if (sc->config & PSM_CONFIG_RESOLUTION)
1590 		sc->mode.resolution =
1591 		    set_mouse_resolution(sc->kbdc,
1592 		    (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1593 	else if (sc->mode.resolution >= 0)
1594 		sc->mode.resolution =
1595 		    set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1596 	if (sc->mode.rate > 0)
1597 		sc->mode.rate =
1598 		    set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1599 	set_mouse_scaling(sc->kbdc, 1);
1600 
1601 	/* Record sync on the next data packet we see. */
1602 	sc->flags |= PSM_NEED_SYNCBITS;
1603 
1604 	/* just check the status of the mouse */
1605 	/*
1606 	 * NOTE: XXX there are some arcane controller/mouse combinations out
1607 	 * there, which hung the controller unless there is data transmission
1608 	 * after ACK from the mouse.
1609 	 */
1610 	if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1611 		printf("psm%d: failed to get status.\n", unit);
1612 	else {
1613 		/*
1614 		 * When in its native mode, some mice operate with different
1615 		 * default parameters than in the PS/2 compatible mode.
1616 		 */
1617 		sc->dflt_mode.rate = sc->mode.rate = stat[2];
1618 		sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1619 	}
1620 
1621 	/* disable the aux port for now... */
1622 	if (!set_controller_command_byte(sc->kbdc,
1623 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1624 	    (command_byte & KBD_KBD_CONTROL_BITS) |
1625 	    KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1626 		/*
1627 		 * this is CONTROLLER ERROR; I don't know the proper way to
1628 		 * recover from this error...
1629 		 */
1630 		if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1631 			restore_controller(sc->kbdc, command_byte);
1632 		printf("psm%d: unable to set the command byte.\n", unit);
1633 		endprobe(ENXIO);
1634 	}
1635 
1636 	/* done */
1637 	kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1638 	kbdc_lock(sc->kbdc, FALSE);
1639 	return (0);
1640 }
1641 
1642 #ifdef EVDEV_SUPPORT
1643 /* Values are taken from Linux drivers for userland software compatibility */
1644 #define	PS2_MOUSE_VENDOR		0x0002
1645 #define	PS2_MOUSE_GENERIC_PRODUCT	0x0001
1646 #define	PS2_MOUSE_SYNAPTICS_NAME	"SynPS/2 Synaptics TouchPad"
1647 #define	PS2_MOUSE_SYNAPTICS_PRODUCT	0x0007
1648 #define	PS2_MOUSE_TRACKPOINT_NAME	"TPPS/2 IBM TrackPoint"
1649 #define	PS2_MOUSE_TRACKPOINT_PRODUCT	0x000A
1650 #define	PS2_MOUSE_ELANTECH_NAME		"ETPS/2 Elantech Touchpad"
1651 #define	PS2_MOUSE_ELANTECH_ST_NAME	"ETPS/2 Elantech TrackPoint"
1652 #define	PS2_MOUSE_ELANTECH_PRODUCT	0x000E
1653 
1654 #define	ABSINFO_END	{ ABS_CNT, 0, 0, 0 }
1655 
1656 static void
1657 psm_support_abs_bulk(struct evdev_dev *evdev, const uint16_t info[][4])
1658 {
1659 	size_t i;
1660 
1661 	for (i = 0; info[i][0] != ABS_CNT; i++)
1662 		evdev_support_abs(evdev, info[i][0], 0, info[i][1], info[i][2],
1663 		    0, 0, info[i][3]);
1664 }
1665 
1666 static void
1667 psm_push_mt_finger(struct psm_softc *sc, int id, const finger_t *f)
1668 {
1669 	int y = sc->synhw.minimumYCoord + sc->synhw.maximumYCoord - f->y;
1670 
1671 	evdev_push_abs(sc->evdev_a, ABS_MT_SLOT, id);
1672 	evdev_push_abs(sc->evdev_a, ABS_MT_TRACKING_ID, id);
1673 	evdev_push_abs(sc->evdev_a, ABS_MT_POSITION_X, f->x);
1674 	evdev_push_abs(sc->evdev_a, ABS_MT_POSITION_Y, y);
1675 	evdev_push_abs(sc->evdev_a, ABS_MT_PRESSURE, f->p);
1676 }
1677 
1678 static void
1679 psm_push_st_finger(struct psm_softc *sc, const finger_t *f)
1680 {
1681 	int y = sc->synhw.minimumYCoord + sc->synhw.maximumYCoord - f->y;
1682 
1683 	evdev_push_abs(sc->evdev_a, ABS_X, f->x);
1684 	evdev_push_abs(sc->evdev_a, ABS_Y, y);
1685 	evdev_push_abs(sc->evdev_a, ABS_PRESSURE, f->p);
1686 	if (sc->synhw.capPalmDetect)
1687 		evdev_push_abs(sc->evdev_a, ABS_TOOL_WIDTH, f->w);
1688 }
1689 
1690 static void
1691 psm_release_mt_slot(struct evdev_dev *evdev, int32_t slot)
1692 {
1693 
1694 	evdev_push_abs(evdev, ABS_MT_SLOT, slot);
1695 	evdev_push_abs(evdev, ABS_MT_TRACKING_ID, -1);
1696 }
1697 
1698 static int
1699 psm_register(device_t dev, int model_code)
1700 {
1701 	struct psm_softc *sc = device_get_softc(dev);
1702 	struct evdev_dev *evdev_r;
1703 	int error, i, nbuttons, nwheels, product;
1704 	bool is_pointing_stick;
1705 	const char *name;
1706 
1707 	name = model_name(model_code);
1708 	nbuttons = sc->hw.buttons;
1709 	product = PS2_MOUSE_GENERIC_PRODUCT;
1710 	nwheels = 0;
1711 	is_pointing_stick = false;
1712 
1713 	switch (model_code) {
1714 	case MOUSE_MODEL_TRACKPOINT:
1715 		name = PS2_MOUSE_TRACKPOINT_NAME;
1716 		product = PS2_MOUSE_TRACKPOINT_PRODUCT;
1717 		nbuttons = 3;
1718 		is_pointing_stick = true;
1719 		break;
1720 
1721 	case MOUSE_MODEL_ELANTECH:
1722 		name = PS2_MOUSE_ELANTECH_ST_NAME;
1723 		product = PS2_MOUSE_ELANTECH_PRODUCT;
1724 		nbuttons = 3;
1725 		is_pointing_stick = true;
1726 		break;
1727 
1728 	case MOUSE_MODEL_MOUSEMANPLUS:
1729 	case MOUSE_MODEL_4D:
1730 		nwheels = 2;
1731 		break;
1732 
1733 	case MOUSE_MODEL_EXPLORER:
1734 	case MOUSE_MODEL_INTELLI:
1735 	case MOUSE_MODEL_NET:
1736 	case MOUSE_MODEL_NETSCROLL:
1737 	case MOUSE_MODEL_4DPLUS:
1738 		nwheels = 1;
1739 		break;
1740 	}
1741 
1742 	evdev_r = evdev_alloc();
1743 	evdev_set_name(evdev_r, name);
1744 	evdev_set_phys(evdev_r, device_get_nameunit(dev));
1745 	evdev_set_id(evdev_r, BUS_I8042, PS2_MOUSE_VENDOR, product, 0);
1746 	evdev_set_methods(evdev_r, sc, &psm_ev_methods_r);
1747 
1748 	evdev_support_prop(evdev_r, INPUT_PROP_POINTER);
1749 	if (is_pointing_stick)
1750 		evdev_support_prop(evdev_r, INPUT_PROP_POINTING_STICK);
1751 	evdev_support_event(evdev_r, EV_SYN);
1752 	evdev_support_event(evdev_r, EV_KEY);
1753 	evdev_support_event(evdev_r, EV_REL);
1754 	evdev_support_rel(evdev_r, REL_X);
1755 	evdev_support_rel(evdev_r, REL_Y);
1756 	switch (nwheels) {
1757 	case 2:
1758 		evdev_support_rel(evdev_r, REL_HWHEEL);
1759 		/* FALLTHROUGH */
1760 	case 1:
1761 		evdev_support_rel(evdev_r, REL_WHEEL);
1762 	}
1763 	for (i = 0; i < nbuttons; i++)
1764 		evdev_support_key(evdev_r, BTN_MOUSE + i);
1765 
1766 	error = evdev_register_mtx(evdev_r, &Giant);
1767 	if (error)
1768 		evdev_free(evdev_r);
1769 	else
1770 		sc->evdev_r = evdev_r;
1771 	return (error);
1772 }
1773 
1774 static int
1775 psm_register_synaptics(device_t dev)
1776 {
1777 	struct psm_softc *sc = device_get_softc(dev);
1778 	const uint16_t synaptics_absinfo_st[][4] = {
1779 		{ ABS_X,		sc->synhw.minimumXCoord,
1780 		    sc->synhw.maximumXCoord, sc->synhw.infoXupmm },
1781 		{ ABS_Y,		sc->synhw.minimumYCoord,
1782 		    sc->synhw.maximumYCoord, sc->synhw.infoYupmm },
1783 		{ ABS_PRESSURE,		0, ELANTECH_FINGER_MAX_P, 0 },
1784 		ABSINFO_END,
1785 	};
1786 	const uint16_t synaptics_absinfo_mt[][4] = {
1787 		{ ABS_MT_SLOT,		0, PSM_FINGERS-1, 0},
1788 		{ ABS_MT_TRACKING_ID,	-1, PSM_FINGERS-1, 0},
1789 		{ ABS_MT_POSITION_X,	sc->synhw.minimumXCoord,
1790 		    sc->synhw.maximumXCoord, sc->synhw.infoXupmm },
1791 		{ ABS_MT_POSITION_Y,	sc->synhw.minimumYCoord,
1792 		    sc->synhw.maximumYCoord, sc->synhw.infoYupmm },
1793 		{ ABS_MT_PRESSURE,	0, ELANTECH_FINGER_MAX_P, 0 },
1794 		ABSINFO_END,
1795 	};
1796 	struct evdev_dev *evdev_a;
1797 	int error, i, guest_model;
1798 
1799 	evdev_a = evdev_alloc();
1800 	evdev_set_name(evdev_a, PS2_MOUSE_SYNAPTICS_NAME);
1801 	evdev_set_phys(evdev_a, device_get_nameunit(dev));
1802 	evdev_set_id(evdev_a, BUS_I8042, PS2_MOUSE_VENDOR,
1803 	    PS2_MOUSE_SYNAPTICS_PRODUCT, 0);
1804 	evdev_set_methods(evdev_a, sc, &psm_ev_methods_a);
1805 
1806 	evdev_support_event(evdev_a, EV_SYN);
1807 	evdev_support_event(evdev_a, EV_KEY);
1808 	evdev_support_event(evdev_a, EV_ABS);
1809 	evdev_support_prop(evdev_a, INPUT_PROP_POINTER);
1810 	if (sc->synhw.capAdvancedGestures)
1811 		evdev_support_prop(evdev_a, INPUT_PROP_SEMI_MT);
1812 	if (sc->synhw.capClickPad)
1813 		evdev_support_prop(evdev_a, INPUT_PROP_BUTTONPAD);
1814 	evdev_support_key(evdev_a, BTN_TOUCH);
1815 	evdev_support_nfingers(evdev_a, 3);
1816 	psm_support_abs_bulk(evdev_a, synaptics_absinfo_st);
1817 	if (sc->synhw.capAdvancedGestures || sc->synhw.capReportsV)
1818 		psm_support_abs_bulk(evdev_a, synaptics_absinfo_mt);
1819 	if (sc->synhw.capPalmDetect)
1820 		evdev_support_abs(evdev_a, ABS_TOOL_WIDTH, 0, 0, 15, 0, 0, 0);
1821 	evdev_support_key(evdev_a, BTN_LEFT);
1822 	if (!sc->synhw.capClickPad) {
1823 		evdev_support_key(evdev_a, BTN_RIGHT);
1824 		if (sc->synhw.capExtended && sc->synhw.capMiddle)
1825 			evdev_support_key(evdev_a, BTN_MIDDLE);
1826 	}
1827 	if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
1828 		evdev_support_key(evdev_a, BTN_BACK);
1829 		evdev_support_key(evdev_a, BTN_FORWARD);
1830 	}
1831 	if (sc->synhw.capExtended && (sc->synhw.nExtendedButtons > 0))
1832 		for (i = 0; i < sc->synhw.nExtendedButtons; i++)
1833 			evdev_support_key(evdev_a, BTN_0 + i);
1834 
1835 	error = evdev_register_mtx(evdev_a, &Giant);
1836 	if (!error && sc->synhw.capPassthrough) {
1837 		guest_model = sc->tpinfo.sysctl_tree != NULL ?
1838 		    MOUSE_MODEL_TRACKPOINT : MOUSE_MODEL_GENERIC;
1839 		error = psm_register(dev, guest_model);
1840 	}
1841 	if (error)
1842 		evdev_free(evdev_a);
1843 	else
1844 		sc->evdev_a = evdev_a;
1845 	return (error);
1846 }
1847 
1848 static int
1849 psm_register_elantech(device_t dev)
1850 {
1851 	struct psm_softc *sc = device_get_softc(dev);
1852 	const uint16_t elantech_absinfo[][4] = {
1853 		{ ABS_X,		0, sc->elanhw.sizex,
1854 					   sc->elanhw.dpmmx },
1855 		{ ABS_Y,		0, sc->elanhw.sizey,
1856 					   sc->elanhw.dpmmy },
1857 		{ ABS_PRESSURE,		0, ELANTECH_FINGER_MAX_P, 0 },
1858 		{ ABS_TOOL_WIDTH,	0, ELANTECH_FINGER_MAX_W, 0 },
1859 		{ ABS_MT_SLOT,		0, ELANTECH_MAX_FINGERS - 1, 0 },
1860 		{ ABS_MT_TRACKING_ID,	-1, ELANTECH_MAX_FINGERS - 1, 0 },
1861 		{ ABS_MT_POSITION_X,	0, sc->elanhw.sizex,
1862 					   sc->elanhw.dpmmx },
1863 		{ ABS_MT_POSITION_Y,	0, sc->elanhw.sizey,
1864 					   sc->elanhw.dpmmy },
1865 		{ ABS_MT_PRESSURE,	0, ELANTECH_FINGER_MAX_P, 0 },
1866 		{ ABS_MT_TOUCH_MAJOR,	0, ELANTECH_FINGER_MAX_W *
1867 					   sc->elanhw.dptracex, 0 },
1868 		ABSINFO_END,
1869 	};
1870 	struct evdev_dev *evdev_a;
1871 	int error;
1872 
1873 	evdev_a = evdev_alloc();
1874 	evdev_set_name(evdev_a, PS2_MOUSE_ELANTECH_NAME);
1875 	evdev_set_phys(evdev_a, device_get_nameunit(dev));
1876 	evdev_set_id(evdev_a, BUS_I8042, PS2_MOUSE_VENDOR,
1877 	    PS2_MOUSE_ELANTECH_PRODUCT, 0);
1878 	evdev_set_methods(evdev_a, sc, &psm_ev_methods_a);
1879 
1880 	evdev_support_event(evdev_a, EV_SYN);
1881 	evdev_support_event(evdev_a, EV_KEY);
1882 	evdev_support_event(evdev_a, EV_ABS);
1883 	evdev_support_prop(evdev_a, INPUT_PROP_POINTER);
1884 	if (sc->elanhw.issemimt)
1885 		evdev_support_prop(evdev_a, INPUT_PROP_SEMI_MT);
1886 	if (sc->elanhw.isclickpad)
1887 		evdev_support_prop(evdev_a, INPUT_PROP_BUTTONPAD);
1888 	evdev_support_key(evdev_a, BTN_TOUCH);
1889 	evdev_support_nfingers(evdev_a, ELANTECH_MAX_FINGERS);
1890 	evdev_support_key(evdev_a, BTN_LEFT);
1891 	if (!sc->elanhw.isclickpad)
1892 		evdev_support_key(evdev_a, BTN_RIGHT);
1893 	psm_support_abs_bulk(evdev_a, elantech_absinfo);
1894 
1895 	error = evdev_register_mtx(evdev_a, &Giant);
1896 	if (!error && sc->elanhw.hastrackpoint)
1897 		error = psm_register(dev, MOUSE_MODEL_ELANTECH);
1898 	if (error)
1899 		evdev_free(evdev_a);
1900 	else
1901 		sc->evdev_a = evdev_a;
1902 	return (error);
1903 }
1904 #endif
1905 
1906 static int
1907 psmattach(device_t dev)
1908 {
1909 	int unit = device_get_unit(dev);
1910 	struct psm_softc *sc = device_get_softc(dev);
1911 	int error;
1912 	int rid;
1913 
1914 	/* Setup initial state */
1915 	sc->state = PSM_VALID;
1916 	callout_init(&sc->callout, 0);
1917 	callout_init(&sc->softcallout, 0);
1918 
1919 	/* Setup our interrupt handler */
1920 	rid = KBDC_RID_AUX;
1921 	sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1922 	if (sc->intr == NULL)
1923 		return (ENXIO);
1924 	error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, NULL, psmintr, sc,
1925 	    &sc->ih);
1926 	if (error) {
1927 		bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1928 		return (error);
1929 	}
1930 
1931 	/* Done */
1932 	sc->dev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "psm%d", unit);
1933 	sc->dev->si_drv1 = sc;
1934 	sc->bdev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "bpsm%d", unit);
1935 	sc->bdev->si_drv1 = sc;
1936 
1937 #ifdef EVDEV_SUPPORT
1938 	switch (sc->hw.model) {
1939 	case MOUSE_MODEL_SYNAPTICS:
1940 		error = psm_register_synaptics(dev);
1941 		break;
1942 
1943 	case MOUSE_MODEL_ELANTECH:
1944 		error = psm_register_elantech(dev);
1945 		break;
1946 
1947 	default:
1948 		error = psm_register(dev, sc->hw.model);
1949 	}
1950 
1951 	if (error)
1952 		return (error);
1953 #endif
1954 
1955 	/* Some touchpad devices need full reinitialization after suspend. */
1956 	switch (sc->hw.model) {
1957 	case MOUSE_MODEL_SYNAPTICS:
1958 	case MOUSE_MODEL_GLIDEPOINT:
1959 	case MOUSE_MODEL_VERSAPAD:
1960 	case MOUSE_MODEL_ELANTECH:
1961 		sc->config |= PSM_CONFIG_INITAFTERSUSPEND;
1962 		break;
1963 	default:
1964 		if (sc->synhw.infoMajor >= 4 || sc->tphw > 0)
1965 			sc->config |= PSM_CONFIG_INITAFTERSUSPEND;
1966 		break;
1967 	}
1968 
1969 	/* Elantech trackpad`s sync bit differs from touchpad`s one */
1970 	if (sc->hw.model == MOUSE_MODEL_ELANTECH &&
1971 	    (sc->elanhw.hascrc || sc->elanhw.hastrackpoint)) {
1972 		sc->config |= PSM_CONFIG_NOCHECKSYNC;
1973 		sc->flags &= ~PSM_NEED_SYNCBITS;
1974 	}
1975 
1976 	if (!verbose)
1977 		printf("psm%d: model %s, device ID %d\n",
1978 		    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1979 	else {
1980 		printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1981 		    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff,
1982 		    sc->hw.hwid >> 8, sc->hw.buttons);
1983 		printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1984 		    unit, sc->config, sc->flags, sc->mode.packetsize);
1985 		printf("psm%d: syncmask:%02x, syncbits:%02x%s\n",
1986 		    unit, sc->mode.syncmask[0], sc->mode.syncmask[1],
1987 		    sc->config & PSM_CONFIG_NOCHECKSYNC ? " (sync not checked)" : "");
1988 	}
1989 
1990 	if (bootverbose)
1991 		--verbose;
1992 
1993 	return (0);
1994 }
1995 
1996 static int
1997 psmdetach(device_t dev)
1998 {
1999 	struct psm_softc *sc;
2000 	int rid;
2001 
2002 	sc = device_get_softc(dev);
2003 	if (sc->state & PSM_OPEN)
2004 		return (EBUSY);
2005 
2006 #ifdef EVDEV_SUPPORT
2007 	evdev_free(sc->evdev_r);
2008 	evdev_free(sc->evdev_a);
2009 #endif
2010 
2011 	rid = KBDC_RID_AUX;
2012 	bus_teardown_intr(dev, sc->intr, sc->ih);
2013 	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
2014 
2015 	destroy_dev(sc->dev);
2016 	destroy_dev(sc->bdev);
2017 
2018 	callout_drain(&sc->callout);
2019 	callout_drain(&sc->softcallout);
2020 
2021 	return (0);
2022 }
2023 
2024 #ifdef EVDEV_SUPPORT
2025 static int
2026 psm_ev_open_r(struct evdev_dev *evdev)
2027 {
2028 	struct psm_softc *sc = evdev_get_softc(evdev);
2029 	int err = 0;
2030 
2031 	/* Get device data */
2032 	if ((sc->state & PSM_VALID) == 0) {
2033 		/* the device is no longer valid/functioning */
2034 		return (ENXIO);
2035 	}
2036 
2037 	if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_A)))
2038 		err = psmopen(sc);
2039 
2040 	if (err == 0)
2041 		sc->state |= PSM_EV_OPEN_R;
2042 
2043 	return (err);
2044 }
2045 
2046 static int
2047 psm_ev_close_r(struct evdev_dev *evdev)
2048 {
2049 	struct psm_softc *sc = evdev_get_softc(evdev);
2050 	int err = 0;
2051 
2052 	sc->state &= ~PSM_EV_OPEN_R;
2053 
2054 	if (sc->state & (PSM_OPEN | PSM_EV_OPEN_A))
2055 		return (0);
2056 
2057 	if (sc->state & PSM_VALID)
2058 		err = psmclose(sc);
2059 
2060 	return (err);
2061 }
2062 
2063 static int
2064 psm_ev_open_a(struct evdev_dev *evdev)
2065 {
2066 	struct psm_softc *sc = evdev_get_softc(evdev);
2067 	int err = 0;
2068 
2069 	/* Get device data */
2070 	if ((sc->state & PSM_VALID) == 0) {
2071 		/* the device is no longer valid/functioning */
2072 		return (ENXIO);
2073 	}
2074 
2075 	if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_R)))
2076 		err = psmopen(sc);
2077 
2078 	if (err == 0)
2079 		sc->state |= PSM_EV_OPEN_A;
2080 
2081 	return (err);
2082 }
2083 
2084 static int
2085 psm_ev_close_a(struct evdev_dev *evdev)
2086 {
2087 	struct psm_softc *sc = evdev_get_softc(evdev);
2088 	int err = 0;
2089 
2090 	sc->state &= ~PSM_EV_OPEN_A;
2091 
2092 	if (sc->state & (PSM_OPEN | PSM_EV_OPEN_R))
2093 		return (0);
2094 
2095 	if (sc->state & PSM_VALID)
2096 		err = psmclose(sc);
2097 
2098 	return (err);
2099 }
2100 #endif
2101 
2102 static int
2103 psm_cdev_open(struct cdev *dev, int flag, int fmt, struct thread *td)
2104 {
2105 	struct psm_softc *sc;
2106 	int err = 0;
2107 
2108 	/* Get device data */
2109 	sc = dev->si_drv1;
2110 	if ((sc == NULL) || (sc->state & PSM_VALID) == 0) {
2111 		/* the device is no longer valid/functioning */
2112 		return (ENXIO);
2113 	}
2114 
2115 	/* Disallow multiple opens */
2116 	if (sc->state & PSM_OPEN)
2117 		return (EBUSY);
2118 
2119 	device_busy(devclass_get_device(psm_devclass, sc->unit));
2120 
2121 #ifdef EVDEV_SUPPORT
2122 	/* Already opened by evdev */
2123 	if (!(sc->state & (PSM_EV_OPEN_R | PSM_EV_OPEN_A)))
2124 #endif
2125 		err = psmopen(sc);
2126 
2127 	if (err == 0)
2128 		sc->state |= PSM_OPEN;
2129 	else
2130 		device_unbusy(devclass_get_device(psm_devclass, sc->unit));
2131 
2132 	return (err);
2133 }
2134 
2135 static int
2136 psm_cdev_close(struct cdev *dev, int flag, int fmt, struct thread *td)
2137 {
2138 	struct psm_softc *sc;
2139 	int err = 0;
2140 
2141 	/* Get device data */
2142 	sc = dev->si_drv1;
2143 	if ((sc == NULL) || (sc->state & PSM_VALID) == 0) {
2144 		/* the device is no longer valid/functioning */
2145 		return (ENXIO);
2146 	}
2147 
2148 #ifdef EVDEV_SUPPORT
2149 	/* Still opened by evdev */
2150 	if (!(sc->state & (PSM_EV_OPEN_R | PSM_EV_OPEN_A)))
2151 #endif
2152 		err = psmclose(sc);
2153 
2154 	if (err == 0) {
2155 		sc->state &= ~PSM_OPEN;
2156 		/* clean up and sigio requests */
2157 		if (sc->async != NULL) {
2158 			funsetown(&sc->async);
2159 			sc->async = NULL;
2160 		}
2161 		device_unbusy(devclass_get_device(psm_devclass, sc->unit));
2162 	}
2163 
2164 	return (err);
2165 }
2166 
2167 static int
2168 psmopen(struct psm_softc *sc)
2169 {
2170 	int command_byte;
2171 	int err;
2172 	int s;
2173 
2174 	/* Initialize state */
2175 	sc->mode.level = sc->dflt_mode.level;
2176 	sc->mode.protocol = sc->dflt_mode.protocol;
2177 	sc->watchdog = FALSE;
2178 	sc->async = NULL;
2179 
2180 	/* flush the event queue */
2181 	sc->queue.count = 0;
2182 	sc->queue.head = 0;
2183 	sc->queue.tail = 0;
2184 	sc->status.flags = 0;
2185 	sc->status.button = 0;
2186 	sc->status.obutton = 0;
2187 	sc->status.dx = 0;
2188 	sc->status.dy = 0;
2189 	sc->status.dz = 0;
2190 	sc->button = 0;
2191 	sc->pqueue_start = 0;
2192 	sc->pqueue_end = 0;
2193 
2194 	/* empty input buffer */
2195 	flushpackets(sc);
2196 	sc->syncerrors = 0;
2197 	sc->pkterrors = 0;
2198 
2199 	/* don't let timeout routines in the keyboard driver to poll the kbdc */
2200 	if (!kbdc_lock(sc->kbdc, TRUE))
2201 		return (EIO);
2202 
2203 	/* save the current controller command byte */
2204 	s = spltty();
2205 	command_byte = get_controller_command_byte(sc->kbdc);
2206 
2207 	/* enable the aux port and temporalily disable the keyboard */
2208 	if (command_byte == -1 || !set_controller_command_byte(sc->kbdc,
2209 	    kbdc_get_device_mask(sc->kbdc),
2210 	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
2211 	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2212 		/* CONTROLLER ERROR; do you know how to get out of this? */
2213 		kbdc_lock(sc->kbdc, FALSE);
2214 		splx(s);
2215 		log(LOG_ERR,
2216 		    "psm%d: unable to set the command byte (psmopen).\n",
2217 		    sc->unit);
2218 		return (EIO);
2219 	}
2220 	/*
2221 	 * Now that the keyboard controller is told not to generate
2222 	 * the keyboard and mouse interrupts, call `splx()' to allow
2223 	 * the other tty interrupts. The clock interrupt may also occur,
2224 	 * but timeout routines will be blocked by the poll flag set
2225 	 * via `kbdc_lock()'
2226 	 */
2227 	splx(s);
2228 
2229 	/* enable the mouse device */
2230 	err = doopen(sc, command_byte);
2231 
2232 	/* done */
2233 	kbdc_lock(sc->kbdc, FALSE);
2234 	return (err);
2235 }
2236 
2237 static int
2238 psmclose(struct psm_softc *sc)
2239 {
2240 	int stat[3];
2241 	int command_byte;
2242 	int s;
2243 
2244 	/* don't let timeout routines in the keyboard driver to poll the kbdc */
2245 	if (!kbdc_lock(sc->kbdc, TRUE))
2246 		return (EIO);
2247 
2248 	/* save the current controller command byte */
2249 	s = spltty();
2250 	command_byte = get_controller_command_byte(sc->kbdc);
2251 	if (command_byte == -1) {
2252 		kbdc_lock(sc->kbdc, FALSE);
2253 		splx(s);
2254 		return (EIO);
2255 	}
2256 
2257 	/* disable the aux interrupt and temporalily disable the keyboard */
2258 	if (!set_controller_command_byte(sc->kbdc,
2259 	    kbdc_get_device_mask(sc->kbdc),
2260 	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
2261 	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2262 		log(LOG_ERR,
2263 		    "psm%d: failed to disable the aux int (psmclose).\n",
2264 		    sc->unit);
2265 		/* CONTROLLER ERROR;
2266 		 * NOTE: we shall force our way through. Because the only
2267 		 * ill effect we shall see is that we may not be able
2268 		 * to read ACK from the mouse, and it doesn't matter much
2269 		 * so long as the mouse will accept the DISABLE command.
2270 		 */
2271 	}
2272 	splx(s);
2273 
2274 	/* stop the watchdog timer */
2275 	callout_stop(&sc->callout);
2276 
2277 	/* remove anything left in the output buffer */
2278 	empty_aux_buffer(sc->kbdc, 10);
2279 
2280 	/* disable the aux device, port and interrupt */
2281 	if (sc->state & PSM_VALID) {
2282 		if (!disable_aux_dev(sc->kbdc)) {
2283 			/* MOUSE ERROR;
2284 			 * NOTE: we don't return (error) and continue,
2285 			 * pretending we have successfully disabled the device.
2286 			 * It's OK because the interrupt routine will discard
2287 			 * any data from the mouse hereafter.
2288 			 */
2289 			log(LOG_ERR,
2290 			    "psm%d: failed to disable the device (psmclose).\n",
2291 			    sc->unit);
2292 		}
2293 
2294 		if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
2295 			log(LOG_DEBUG,
2296 			    "psm%d: failed to get status (psmclose).\n",
2297 			    sc->unit);
2298 	}
2299 
2300 	if (!set_controller_command_byte(sc->kbdc,
2301 	    kbdc_get_device_mask(sc->kbdc),
2302 	    (command_byte & KBD_KBD_CONTROL_BITS) |
2303 	    KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2304 		/*
2305 		 * CONTROLLER ERROR;
2306 		 * we shall ignore this error; see the above comment.
2307 		 */
2308 		log(LOG_ERR,
2309 		    "psm%d: failed to disable the aux port (psmclose).\n",
2310 		    sc->unit);
2311 	}
2312 
2313 	/* remove anything left in the output buffer */
2314 	empty_aux_buffer(sc->kbdc, 10);
2315 
2316 	/* close is almost always successful */
2317 	kbdc_lock(sc->kbdc, FALSE);
2318 	return (0);
2319 }
2320 
2321 static int
2322 tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status,
2323     u_char *buf)
2324 {
2325 	static u_char butmapps2[8] = {
2326 		0,
2327 		MOUSE_PS2_BUTTON1DOWN,
2328 		MOUSE_PS2_BUTTON2DOWN,
2329 		MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
2330 		MOUSE_PS2_BUTTON3DOWN,
2331 		MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
2332 		MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
2333 		MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN |
2334 		    MOUSE_PS2_BUTTON3DOWN,
2335 	};
2336 	static u_char butmapmsc[8] = {
2337 		MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP |
2338 		    MOUSE_MSC_BUTTON3UP,
2339 		MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
2340 		MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
2341 		MOUSE_MSC_BUTTON3UP,
2342 		MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
2343 		MOUSE_MSC_BUTTON2UP,
2344 		MOUSE_MSC_BUTTON1UP,
2345 		0,
2346 	};
2347 	int mapped;
2348 	int i;
2349 
2350 	if (sc->mode.level == PSM_LEVEL_BASE) {
2351 		mapped = status->button & ~MOUSE_BUTTON4DOWN;
2352 		if (status->button & MOUSE_BUTTON4DOWN)
2353 			mapped |= MOUSE_BUTTON1DOWN;
2354 		status->button = mapped;
2355 		buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
2356 		i = imax(imin(status->dx, 255), -256);
2357 		if (i < 0)
2358 			buf[0] |= MOUSE_PS2_XNEG;
2359 		buf[1] = i;
2360 		i = imax(imin(status->dy, 255), -256);
2361 		if (i < 0)
2362 			buf[0] |= MOUSE_PS2_YNEG;
2363 		buf[2] = i;
2364 		return (MOUSE_PS2_PACKETSIZE);
2365 	} else if (sc->mode.level == PSM_LEVEL_STANDARD) {
2366 		buf[0] = MOUSE_MSC_SYNC |
2367 		    butmapmsc[status->button & MOUSE_STDBUTTONS];
2368 		i = imax(imin(status->dx, 255), -256);
2369 		buf[1] = i >> 1;
2370 		buf[3] = i - buf[1];
2371 		i = imax(imin(status->dy, 255), -256);
2372 		buf[2] = i >> 1;
2373 		buf[4] = i - buf[2];
2374 		i = imax(imin(status->dz, 127), -128);
2375 		buf[5] = (i >> 1) & 0x7f;
2376 		buf[6] = (i - (i >> 1)) & 0x7f;
2377 		buf[7] = (~status->button >> 3) & 0x7f;
2378 		return (MOUSE_SYS_PACKETSIZE);
2379 	}
2380 	return (pb->inputbytes);
2381 }
2382 
2383 static int
2384 psmread(struct cdev *dev, struct uio *uio, int flag)
2385 {
2386 	struct psm_softc *sc = dev->si_drv1;
2387 	u_char buf[PSM_SMALLBUFSIZE];
2388 	int error = 0;
2389 	int s;
2390 	int l;
2391 
2392 	if ((sc->state & PSM_VALID) == 0)
2393 		return (EIO);
2394 
2395 	/* block until mouse activity occurred */
2396 	s = spltty();
2397 	while (sc->queue.count <= 0) {
2398 		if (dev != sc->bdev) {
2399 			splx(s);
2400 			return (EWOULDBLOCK);
2401 		}
2402 		sc->state |= PSM_ASLP;
2403 		error = tsleep(sc, PZERO | PCATCH, "psmrea", 0);
2404 		sc->state &= ~PSM_ASLP;
2405 		if (error) {
2406 			splx(s);
2407 			return (error);
2408 		} else if ((sc->state & PSM_VALID) == 0) {
2409 			/* the device disappeared! */
2410 			splx(s);
2411 			return (EIO);
2412 		}
2413 	}
2414 	splx(s);
2415 
2416 	/* copy data to the user land */
2417 	while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
2418 		s = spltty();
2419 		l = imin(sc->queue.count, uio->uio_resid);
2420 		if (l > sizeof(buf))
2421 			l = sizeof(buf);
2422 		if (l > sizeof(sc->queue.buf) - sc->queue.head) {
2423 			bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
2424 			    sizeof(sc->queue.buf) - sc->queue.head);
2425 			bcopy(&sc->queue.buf[0],
2426 			    &buf[sizeof(sc->queue.buf) - sc->queue.head],
2427 			    l - (sizeof(sc->queue.buf) - sc->queue.head));
2428 		} else
2429 			bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
2430 		sc->queue.count -= l;
2431 		sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
2432 		splx(s);
2433 		error = uiomove(buf, l, uio);
2434 		if (error)
2435 			break;
2436 	}
2437 
2438 	return (error);
2439 }
2440 
2441 static int
2442 block_mouse_data(struct psm_softc *sc, int *c)
2443 {
2444 	int s;
2445 
2446 	if (!kbdc_lock(sc->kbdc, TRUE))
2447 		return (EIO);
2448 
2449 	s = spltty();
2450 	*c = get_controller_command_byte(sc->kbdc);
2451 	if ((*c == -1) || !set_controller_command_byte(sc->kbdc,
2452 	    kbdc_get_device_mask(sc->kbdc),
2453 	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
2454 	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2455 		/* this is CONTROLLER ERROR */
2456 		splx(s);
2457 		kbdc_lock(sc->kbdc, FALSE);
2458 		return (EIO);
2459 	}
2460 
2461 	/*
2462 	 * The device may be in the middle of status data transmission.
2463 	 * The transmission will be interrupted, thus, incomplete status
2464 	 * data must be discarded. Although the aux interrupt is disabled
2465 	 * at the keyboard controller level, at most one aux interrupt
2466 	 * may have already been pending and a data byte is in the
2467 	 * output buffer; throw it away. Note that the second argument
2468 	 * to `empty_aux_buffer()' is zero, so that the call will just
2469 	 * flush the internal queue.
2470 	 * `psmintr()' will be invoked after `splx()' if an interrupt is
2471 	 * pending; it will see no data and returns immediately.
2472 	 */
2473 	empty_aux_buffer(sc->kbdc, 0);		/* flush the queue */
2474 	read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
2475 	flushpackets(sc);
2476 	splx(s);
2477 
2478 	return (0);
2479 }
2480 
2481 static void
2482 dropqueue(struct psm_softc *sc)
2483 {
2484 
2485 	sc->queue.count = 0;
2486 	sc->queue.head = 0;
2487 	sc->queue.tail = 0;
2488 	if ((sc->state & PSM_SOFTARMED) != 0) {
2489 		sc->state &= ~PSM_SOFTARMED;
2490 		callout_stop(&sc->softcallout);
2491 	}
2492 	sc->pqueue_start = sc->pqueue_end;
2493 }
2494 
2495 static void
2496 flushpackets(struct psm_softc *sc)
2497 {
2498 
2499 	dropqueue(sc);
2500 	bzero(&sc->pqueue, sizeof(sc->pqueue));
2501 }
2502 
2503 static int
2504 unblock_mouse_data(struct psm_softc *sc, int c)
2505 {
2506 	int error = 0;
2507 
2508 	/*
2509 	 * We may have seen a part of status data during `set_mouse_XXX()'.
2510 	 * they have been queued; flush it.
2511 	 */
2512 	empty_aux_buffer(sc->kbdc, 0);
2513 
2514 	/* restore ports and interrupt */
2515 	if (!set_controller_command_byte(sc->kbdc,
2516 	    kbdc_get_device_mask(sc->kbdc),
2517 	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
2518 		/*
2519 		 * CONTROLLER ERROR; this is serious, we may have
2520 		 * been left with the inaccessible keyboard and
2521 		 * the disabled mouse interrupt.
2522 		 */
2523 		error = EIO;
2524 	}
2525 
2526 	kbdc_lock(sc->kbdc, FALSE);
2527 	return (error);
2528 }
2529 
2530 static int
2531 psmwrite(struct cdev *dev, struct uio *uio, int flag)
2532 {
2533 	struct psm_softc *sc = dev->si_drv1;
2534 	u_char buf[PSM_SMALLBUFSIZE];
2535 	int error = 0, i, l;
2536 
2537 	if ((sc->state & PSM_VALID) == 0)
2538 		return (EIO);
2539 
2540 	if (sc->mode.level < PSM_LEVEL_NATIVE)
2541 		return (ENODEV);
2542 
2543 	/* copy data from the user land */
2544 	while (uio->uio_resid > 0) {
2545 		l = imin(PSM_SMALLBUFSIZE, uio->uio_resid);
2546 		error = uiomove(buf, l, uio);
2547 		if (error)
2548 			break;
2549 		for (i = 0; i < l; i++) {
2550 			VLOG(4, (LOG_DEBUG, "psm: cmd 0x%x\n", buf[i]));
2551 			if (!write_aux_command(sc->kbdc, buf[i])) {
2552 				VLOG(2, (LOG_DEBUG,
2553 				    "psm: cmd 0x%x failed.\n", buf[i]));
2554 				return (reinitialize(sc, FALSE));
2555 			}
2556 		}
2557 	}
2558 
2559 	return (error);
2560 }
2561 
2562 static int
2563 psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2564     struct thread *td)
2565 {
2566 	struct psm_softc *sc = dev->si_drv1;
2567 	mousemode_t mode;
2568 	mousestatus_t status;
2569 	mousedata_t *data;
2570 	int stat[3];
2571 	int command_byte;
2572 	int error = 0;
2573 	int s;
2574 
2575 	/* Perform IOCTL command */
2576 	switch (cmd) {
2577 
2578 	case OLD_MOUSE_GETHWINFO:
2579 		s = spltty();
2580 		((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
2581 		((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
2582 		((old_mousehw_t *)addr)->type = sc->hw.type;
2583 		((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
2584 		splx(s);
2585 		break;
2586 
2587 	case MOUSE_GETHWINFO:
2588 		s = spltty();
2589 		*(mousehw_t *)addr = sc->hw;
2590 		if (sc->mode.level == PSM_LEVEL_BASE)
2591 			((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
2592 		splx(s);
2593 		break;
2594 
2595 	case MOUSE_SYN_GETHWINFO:
2596 		s = spltty();
2597 		if (sc->synhw.infoMajor >= 4)
2598 			*(synapticshw_t *)addr = sc->synhw;
2599 		else
2600 			error = EINVAL;
2601 		splx(s);
2602 		break;
2603 
2604 	case OLD_MOUSE_GETMODE:
2605 		s = spltty();
2606 		switch (sc->mode.level) {
2607 		case PSM_LEVEL_BASE:
2608 			((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2609 			break;
2610 		case PSM_LEVEL_STANDARD:
2611 			((old_mousemode_t *)addr)->protocol =
2612 			    MOUSE_PROTO_SYSMOUSE;
2613 			break;
2614 		case PSM_LEVEL_NATIVE:
2615 			((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2616 			break;
2617 		}
2618 		((old_mousemode_t *)addr)->rate = sc->mode.rate;
2619 		((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
2620 		((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
2621 		splx(s);
2622 		break;
2623 
2624 	case MOUSE_GETMODE:
2625 		s = spltty();
2626 		*(mousemode_t *)addr = sc->mode;
2627 		if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2628 			((mousemode_t *)addr)->syncmask[0] = 0;
2629 			((mousemode_t *)addr)->syncmask[1] = 0;
2630 		}
2631 		((mousemode_t *)addr)->resolution =
2632 			MOUSE_RES_LOW - sc->mode.resolution;
2633 		switch (sc->mode.level) {
2634 		case PSM_LEVEL_BASE:
2635 			((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2636 			((mousemode_t *)addr)->packetsize =
2637 			    MOUSE_PS2_PACKETSIZE;
2638 			break;
2639 		case PSM_LEVEL_STANDARD:
2640 			((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
2641 			((mousemode_t *)addr)->packetsize =
2642 			    MOUSE_SYS_PACKETSIZE;
2643 			((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
2644 			((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
2645 			break;
2646 		case PSM_LEVEL_NATIVE:
2647 			/* FIXME: this isn't quite correct... XXX */
2648 			((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2649 			break;
2650 		}
2651 		splx(s);
2652 		break;
2653 
2654 	case OLD_MOUSE_SETMODE:
2655 	case MOUSE_SETMODE:
2656 		if (cmd == OLD_MOUSE_SETMODE) {
2657 			mode.rate = ((old_mousemode_t *)addr)->rate;
2658 			/*
2659 			 * resolution  old I/F   new I/F
2660 			 * default        0         0
2661 			 * low            1        -2
2662 			 * medium low     2        -3
2663 			 * medium high    3        -4
2664 			 * high           4        -5
2665 			 */
2666 			if (((old_mousemode_t *)addr)->resolution > 0)
2667 				mode.resolution =
2668 				    -((old_mousemode_t *)addr)->resolution - 1;
2669 			else
2670 				mode.resolution = 0;
2671 			mode.accelfactor =
2672 			    ((old_mousemode_t *)addr)->accelfactor;
2673 			mode.level = -1;
2674 		} else
2675 			mode = *(mousemode_t *)addr;
2676 
2677 		/* adjust and validate parameters. */
2678 		if (mode.rate > UCHAR_MAX)
2679 			return (EINVAL);
2680 		if (mode.rate == 0)
2681 			mode.rate = sc->dflt_mode.rate;
2682 		else if (mode.rate == -1)
2683 			/* don't change the current setting */
2684 			;
2685 		else if (mode.rate < 0)
2686 			return (EINVAL);
2687 		if (mode.resolution >= UCHAR_MAX)
2688 			return (EINVAL);
2689 		if (mode.resolution >= 200)
2690 			mode.resolution = MOUSE_RES_HIGH;
2691 		else if (mode.resolution >= 100)
2692 			mode.resolution = MOUSE_RES_MEDIUMHIGH;
2693 		else if (mode.resolution >= 50)
2694 			mode.resolution = MOUSE_RES_MEDIUMLOW;
2695 		else if (mode.resolution > 0)
2696 			mode.resolution = MOUSE_RES_LOW;
2697 		if (mode.resolution == MOUSE_RES_DEFAULT)
2698 			mode.resolution = sc->dflt_mode.resolution;
2699 		else if (mode.resolution == -1)
2700 			/* don't change the current setting */
2701 			;
2702 		else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2703 			mode.resolution = MOUSE_RES_LOW - mode.resolution;
2704 		if (mode.level == -1)
2705 			/* don't change the current setting */
2706 			mode.level = sc->mode.level;
2707 		else if ((mode.level < PSM_LEVEL_MIN) ||
2708 		    (mode.level > PSM_LEVEL_MAX))
2709 			return (EINVAL);
2710 		if (mode.accelfactor == -1)
2711 			/* don't change the current setting */
2712 			mode.accelfactor = sc->mode.accelfactor;
2713 		else if (mode.accelfactor < 0)
2714 			return (EINVAL);
2715 
2716 		/* don't allow anybody to poll the keyboard controller */
2717 		error = block_mouse_data(sc, &command_byte);
2718 		if (error)
2719 			return (error);
2720 
2721 		/* set mouse parameters */
2722 		if (mode.rate > 0)
2723 			mode.rate = set_mouse_sampling_rate(sc->kbdc,
2724 			    mode.rate);
2725 		if (mode.resolution >= 0)
2726 			mode.resolution =
2727 			    set_mouse_resolution(sc->kbdc, mode.resolution);
2728 		set_mouse_scaling(sc->kbdc, 1);
2729 		get_mouse_status(sc->kbdc, stat, 0, 3);
2730 
2731 		s = spltty();
2732 		sc->mode.rate = mode.rate;
2733 		sc->mode.resolution = mode.resolution;
2734 		sc->mode.accelfactor = mode.accelfactor;
2735 		sc->mode.level = mode.level;
2736 		splx(s);
2737 
2738 		unblock_mouse_data(sc, command_byte);
2739 		break;
2740 
2741 	case MOUSE_GETLEVEL:
2742 		*(int *)addr = sc->mode.level;
2743 		break;
2744 
2745 	case MOUSE_SETLEVEL:
2746 		if ((*(int *)addr < PSM_LEVEL_MIN) ||
2747 		    (*(int *)addr > PSM_LEVEL_MAX))
2748 			return (EINVAL);
2749 		sc->mode.level = *(int *)addr;
2750 		break;
2751 
2752 	case MOUSE_GETSTATUS:
2753 		s = spltty();
2754 		status = sc->status;
2755 		sc->status.flags = 0;
2756 		sc->status.obutton = sc->status.button;
2757 		sc->status.button = 0;
2758 		sc->status.dx = 0;
2759 		sc->status.dy = 0;
2760 		sc->status.dz = 0;
2761 		splx(s);
2762 		*(mousestatus_t *)addr = status;
2763 		break;
2764 
2765 	case MOUSE_READSTATE:
2766 	case MOUSE_READDATA:
2767 		data = (mousedata_t *)addr;
2768 		if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
2769 			return (EINVAL);
2770 
2771 		error = block_mouse_data(sc, &command_byte);
2772 		if (error)
2773 			return (error);
2774 		if ((data->len = get_mouse_status(sc->kbdc, data->buf,
2775 		    (cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
2776 			error = EIO;
2777 		unblock_mouse_data(sc, command_byte);
2778 		break;
2779 
2780 #if (defined(MOUSE_SETRESOLUTION))
2781 	case MOUSE_SETRESOLUTION:
2782 		mode.resolution = *(int *)addr;
2783 		if (mode.resolution >= UCHAR_MAX)
2784 			return (EINVAL);
2785 		else if (mode.resolution >= 200)
2786 			mode.resolution = MOUSE_RES_HIGH;
2787 		else if (mode.resolution >= 100)
2788 			mode.resolution = MOUSE_RES_MEDIUMHIGH;
2789 		else if (mode.resolution >= 50)
2790 			mode.resolution = MOUSE_RES_MEDIUMLOW;
2791 		else if (mode.resolution > 0)
2792 			mode.resolution = MOUSE_RES_LOW;
2793 		if (mode.resolution == MOUSE_RES_DEFAULT)
2794 			mode.resolution = sc->dflt_mode.resolution;
2795 		else if (mode.resolution == -1)
2796 			mode.resolution = sc->mode.resolution;
2797 		else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2798 			mode.resolution = MOUSE_RES_LOW - mode.resolution;
2799 
2800 		error = block_mouse_data(sc, &command_byte);
2801 		if (error)
2802 			return (error);
2803 		sc->mode.resolution =
2804 		    set_mouse_resolution(sc->kbdc, mode.resolution);
2805 		if (sc->mode.resolution != mode.resolution)
2806 			error = EIO;
2807 		unblock_mouse_data(sc, command_byte);
2808 		break;
2809 #endif /* MOUSE_SETRESOLUTION */
2810 
2811 #if (defined(MOUSE_SETRATE))
2812 	case MOUSE_SETRATE:
2813 		mode.rate = *(int *)addr;
2814 		if (mode.rate > UCHAR_MAX)
2815 			return (EINVAL);
2816 		if (mode.rate == 0)
2817 			mode.rate = sc->dflt_mode.rate;
2818 		else if (mode.rate < 0)
2819 			mode.rate = sc->mode.rate;
2820 
2821 		error = block_mouse_data(sc, &command_byte);
2822 		if (error)
2823 			return (error);
2824 		sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
2825 		if (sc->mode.rate != mode.rate)
2826 			error = EIO;
2827 		unblock_mouse_data(sc, command_byte);
2828 		break;
2829 #endif /* MOUSE_SETRATE */
2830 
2831 #if (defined(MOUSE_SETSCALING))
2832 	case MOUSE_SETSCALING:
2833 		if ((*(int *)addr <= 0) || (*(int *)addr > 2))
2834 			return (EINVAL);
2835 
2836 		error = block_mouse_data(sc, &command_byte);
2837 		if (error)
2838 			return (error);
2839 		if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
2840 			error = EIO;
2841 		unblock_mouse_data(sc, command_byte);
2842 		break;
2843 #endif /* MOUSE_SETSCALING */
2844 
2845 #if (defined(MOUSE_GETHWID))
2846 	case MOUSE_GETHWID:
2847 		error = block_mouse_data(sc, &command_byte);
2848 		if (error)
2849 			return (error);
2850 		sc->hw.hwid &= ~0x00ff;
2851 		sc->hw.hwid |= get_aux_id(sc->kbdc);
2852 		*(int *)addr = sc->hw.hwid & 0x00ff;
2853 		unblock_mouse_data(sc, command_byte);
2854 		break;
2855 #endif /* MOUSE_GETHWID */
2856 
2857 	case FIONBIO:
2858 	case FIOASYNC:
2859 		break;
2860 	case FIOSETOWN:
2861 		error = fsetown(*(int *)addr, &sc->async);
2862 		break;
2863 	case FIOGETOWN:
2864 		*(int *) addr = fgetown(&sc->async);
2865 		break;
2866 	default:
2867 		return (ENOTTY);
2868 	}
2869 
2870 	return (error);
2871 }
2872 
2873 static void
2874 psmtimeout(void *arg)
2875 {
2876 	struct psm_softc *sc;
2877 	int s;
2878 
2879 	sc = (struct psm_softc *)arg;
2880 	s = spltty();
2881 	if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
2882 		VLOG(6, (LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit));
2883 		psmintr(sc);
2884 		kbdc_lock(sc->kbdc, FALSE);
2885 	}
2886 	sc->watchdog = TRUE;
2887 	splx(s);
2888 	callout_reset(&sc->callout, hz, psmtimeout, sc);
2889 }
2890 
2891 /* Add all sysctls under the debug.psm and hw.psm nodes */
2892 static SYSCTL_NODE(_debug, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2893 static SYSCTL_NODE(_hw, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2894 
2895 SYSCTL_INT(_debug_psm, OID_AUTO, loglevel, CTLFLAG_RWTUN, &verbose, 0,
2896     "Verbosity level");
2897 
2898 static int psmhz = 20;
2899 SYSCTL_INT(_debug_psm, OID_AUTO, hz, CTLFLAG_RW, &psmhz, 0,
2900     "Frequency of the softcallout (in hz)");
2901 static int psmerrsecs = 2;
2902 SYSCTL_INT(_debug_psm, OID_AUTO, errsecs, CTLFLAG_RW, &psmerrsecs, 0,
2903     "Number of seconds during which packets will dropped after a sync error");
2904 static int psmerrusecs = 0;
2905 SYSCTL_INT(_debug_psm, OID_AUTO, errusecs, CTLFLAG_RW, &psmerrusecs, 0,
2906     "Microseconds to add to psmerrsecs");
2907 static int psmsecs = 0;
2908 SYSCTL_INT(_debug_psm, OID_AUTO, secs, CTLFLAG_RW, &psmsecs, 0,
2909     "Max number of seconds between soft interrupts");
2910 static int psmusecs = 500000;
2911 SYSCTL_INT(_debug_psm, OID_AUTO, usecs, CTLFLAG_RW, &psmusecs, 0,
2912     "Microseconds to add to psmsecs");
2913 static int pkterrthresh = 2;
2914 SYSCTL_INT(_debug_psm, OID_AUTO, pkterrthresh, CTLFLAG_RW, &pkterrthresh, 0,
2915     "Number of error packets allowed before reinitializing the mouse");
2916 
2917 SYSCTL_INT(_hw_psm, OID_AUTO, tap_enabled, CTLFLAG_RWTUN, &tap_enabled, 0,
2918     "Enable tap and drag gestures");
2919 static int tap_threshold = PSM_TAP_THRESHOLD;
2920 SYSCTL_INT(_hw_psm, OID_AUTO, tap_threshold, CTLFLAG_RW, &tap_threshold, 0,
2921     "Button tap threshold");
2922 static int tap_timeout = PSM_TAP_TIMEOUT;
2923 SYSCTL_INT(_hw_psm, OID_AUTO, tap_timeout, CTLFLAG_RW, &tap_timeout, 0,
2924     "Tap timeout for touchpads");
2925 
2926 /* Tunables */
2927 SYSCTL_INT(_hw_psm, OID_AUTO, synaptics_support, CTLFLAG_RDTUN,
2928     &synaptics_support, 0, "Enable support for Synaptics touchpads");
2929 
2930 SYSCTL_INT(_hw_psm, OID_AUTO, trackpoint_support, CTLFLAG_RDTUN,
2931     &trackpoint_support, 0, "Enable support for IBM/Lenovo TrackPoint");
2932 
2933 SYSCTL_INT(_hw_psm, OID_AUTO, elantech_support, CTLFLAG_RDTUN,
2934     &elantech_support, 0, "Enable support for Elantech touchpads");
2935 
2936 static void
2937 psmintr(void *arg)
2938 {
2939 	struct psm_softc *sc = arg;
2940 	struct timeval now;
2941 	int c;
2942 	packetbuf_t *pb;
2943 
2944 
2945 	/* read until there is nothing to read */
2946 	while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
2947 		pb = &sc->pqueue[sc->pqueue_end];
2948 
2949 		/* discard the byte if the device is not open */
2950 		if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_R | PSM_EV_OPEN_A)))
2951 			continue;
2952 
2953 		getmicrouptime(&now);
2954 		if ((pb->inputbytes > 0) &&
2955 		    timevalcmp(&now, &sc->inputtimeout, >)) {
2956 			VLOG(3, (LOG_DEBUG, "psmintr: delay too long; "
2957 			    "resetting byte count\n"));
2958 			pb->inputbytes = 0;
2959 			sc->syncerrors = 0;
2960 			sc->pkterrors = 0;
2961 		}
2962 		sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT / 1000000;
2963 		sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT % 1000000;
2964 		timevaladd(&sc->inputtimeout, &now);
2965 
2966 		pb->ipacket[pb->inputbytes++] = c;
2967 
2968 		if (sc->mode.level == PSM_LEVEL_NATIVE) {
2969 			VLOG(4, (LOG_DEBUG, "psmintr: %02x\n", pb->ipacket[0]));
2970 			sc->syncerrors = 0;
2971 			sc->pkterrors = 0;
2972 			goto next;
2973 		} else {
2974 			if (pb->inputbytes < sc->mode.packetsize)
2975 				continue;
2976 
2977 			VLOG(4, (LOG_DEBUG,
2978 			    "psmintr: %02x %02x %02x %02x %02x %02x\n",
2979 			    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
2980 			    pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
2981 		}
2982 
2983 		c = pb->ipacket[0];
2984 
2985 		if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2986 			sc->mode.syncmask[1] = (c & sc->mode.syncmask[0]);
2987 			sc->flags &= ~PSM_NEED_SYNCBITS;
2988 			VLOG(2, (LOG_DEBUG,
2989 			    "psmintr: Sync bytes now %04x,%04x\n",
2990 			    sc->mode.syncmask[0], sc->mode.syncmask[1]));
2991 		} else if ((sc->config & PSM_CONFIG_NOCHECKSYNC) == 0 &&
2992 		    (c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
2993 			VLOG(3, (LOG_DEBUG, "psmintr: out of sync "
2994 			    "(%04x != %04x) %d cmds since last error.\n",
2995 			    c & sc->mode.syncmask[0], sc->mode.syncmask[1],
2996 			    sc->cmdcount - sc->lasterr));
2997 			sc->lasterr = sc->cmdcount;
2998 			/*
2999 			 * The sync byte test is a weak measure of packet
3000 			 * validity.  Conservatively discard any input yet
3001 			 * to be seen by userland when we detect a sync
3002 			 * error since there is a good chance some of
3003 			 * the queued packets have undetected errors.
3004 			 */
3005 			dropqueue(sc);
3006 			if (sc->syncerrors == 0)
3007 				sc->pkterrors++;
3008 			++sc->syncerrors;
3009 			sc->lastinputerr = now;
3010 			if (sc->syncerrors >= sc->mode.packetsize * 2 ||
3011 			    sc->pkterrors >= pkterrthresh) {
3012 				/*
3013 				 * If we've failed to find a single sync byte
3014 				 * in 2 packets worth of data, or we've seen
3015 				 * persistent packet errors during the
3016 				 * validation period, reinitialize the mouse
3017 				 * in hopes of returning it to the expected
3018 				 * mode.
3019 				 */
3020 				VLOG(3, (LOG_DEBUG,
3021 				    "psmintr: reset the mouse.\n"));
3022 				reinitialize(sc, TRUE);
3023 			} else if (sc->syncerrors == sc->mode.packetsize) {
3024 				/*
3025 				 * Try a soft reset after searching for a sync
3026 				 * byte through a packet length of bytes.
3027 				 */
3028 				VLOG(3, (LOG_DEBUG,
3029 				    "psmintr: re-enable the mouse.\n"));
3030 				pb->inputbytes = 0;
3031 				disable_aux_dev(sc->kbdc);
3032 				enable_aux_dev(sc->kbdc);
3033 			} else {
3034 				VLOG(3, (LOG_DEBUG,
3035 				    "psmintr: discard a byte (%d)\n",
3036 				    sc->syncerrors));
3037 				pb->inputbytes--;
3038 				bcopy(&pb->ipacket[1], &pb->ipacket[0],
3039 				    pb->inputbytes);
3040 			}
3041 			continue;
3042 		}
3043 
3044 		/*
3045 		 * We have what appears to be a valid packet.
3046 		 * Reset the error counters.
3047 		 */
3048 		sc->syncerrors = 0;
3049 
3050 		/*
3051 		 * Drop even good packets if they occur within a timeout
3052 		 * period of a sync error.  This allows the detection of
3053 		 * a change in the mouse's packet mode without exposing
3054 		 * erratic mouse behavior to the user.  Some KVMs forget
3055 		 * enhanced mouse modes during switch events.
3056 		 */
3057 		if (!timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs,
3058 		    &now)) {
3059 			pb->inputbytes = 0;
3060 			continue;
3061 		}
3062 
3063 		/*
3064 		 * Now that we're out of the validation period, reset
3065 		 * the packet error count.
3066 		 */
3067 		sc->pkterrors = 0;
3068 
3069 		sc->cmdcount++;
3070 next:
3071 		if (++sc->pqueue_end >= PSM_PACKETQUEUE)
3072 			sc->pqueue_end = 0;
3073 		/*
3074 		 * If we've filled the queue then call the softintr ourselves,
3075 		 * otherwise schedule the interrupt for later.
3076 		 */
3077 		if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
3078 		    (sc->pqueue_end == sc->pqueue_start)) {
3079 			if ((sc->state & PSM_SOFTARMED) != 0) {
3080 				sc->state &= ~PSM_SOFTARMED;
3081 				callout_stop(&sc->softcallout);
3082 			}
3083 			psmsoftintr(arg);
3084 		} else if ((sc->state & PSM_SOFTARMED) == 0) {
3085 			sc->state |= PSM_SOFTARMED;
3086 			callout_reset(&sc->softcallout,
3087 			    psmhz < 1 ? 1 : (hz/psmhz), psmsoftintr, arg);
3088 		}
3089 	}
3090 }
3091 
3092 static void
3093 proc_mmanplus(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
3094     int *x, int *y, int *z)
3095 {
3096 
3097 	/*
3098 	 * PS2++ protocol packet
3099 	 *
3100 	 *          b7 b6 b5 b4 b3 b2 b1 b0
3101 	 * byte 1:  *  1  p3 p2 1  *  *  *
3102 	 * byte 2:  c1 c2 p1 p0 d1 d0 1  0
3103 	 *
3104 	 * p3-p0: packet type
3105 	 * c1, c2: c1 & c2 == 1, if p2 == 0
3106 	 *         c1 & c2 == 0, if p2 == 1
3107 	 *
3108 	 * packet type: 0 (device type)
3109 	 * See comments in enable_mmanplus() below.
3110 	 *
3111 	 * packet type: 1 (wheel data)
3112 	 *
3113 	 *          b7 b6 b5 b4 b3 b2 b1 b0
3114 	 * byte 3:  h  *  B5 B4 s  d2 d1 d0
3115 	 *
3116 	 * h: 1, if horizontal roller data
3117 	 *    0, if vertical roller data
3118 	 * B4, B5: button 4 and 5
3119 	 * s: sign bit
3120 	 * d2-d0: roller data
3121 	 *
3122 	 * packet type: 2 (reserved)
3123 	 */
3124 	if (((pb->ipacket[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC) &&
3125 	    (abs(*x) > 191) && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
3126 		/*
3127 		 * the extended data packet encodes button
3128 		 * and wheel events
3129 		 */
3130 		switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
3131 		case 1:
3132 			/* wheel data packet */
3133 			*x = *y = 0;
3134 			if (pb->ipacket[2] & 0x80) {
3135 				/* XXX horizontal roller count - ignore it */
3136 				;
3137 			} else {
3138 				/* vertical roller count */
3139 				*z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG) ?
3140 				    (pb->ipacket[2] & 0x0f) - 16 :
3141 				    (pb->ipacket[2] & 0x0f);
3142 			}
3143 			ms->button |= (pb->ipacket[2] &
3144 			    MOUSE_PS2PLUS_BUTTON4DOWN) ?
3145 			    MOUSE_BUTTON4DOWN : 0;
3146 			ms->button |= (pb->ipacket[2] &
3147 			    MOUSE_PS2PLUS_BUTTON5DOWN) ?
3148 			    MOUSE_BUTTON5DOWN : 0;
3149 			break;
3150 		case 2:
3151 			/*
3152 			 * this packet type is reserved by
3153 			 * Logitech...
3154 			 */
3155 			/*
3156 			 * IBM ScrollPoint Mouse uses this
3157 			 * packet type to encode both vertical
3158 			 * and horizontal scroll movement.
3159 			 */
3160 			*x = *y = 0;
3161 			/* horizontal count */
3162 			if (pb->ipacket[2] & 0x0f)
3163 				*z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ?
3164 				    -2 : 2;
3165 			/* vertical count */
3166 			if (pb->ipacket[2] & 0xf0)
3167 				*z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ?
3168 				    -1 : 1;
3169 			break;
3170 		case 0:
3171 			/* device type packet - shouldn't happen */
3172 			/* FALLTHROUGH */
3173 		default:
3174 			*x = *y = 0;
3175 			ms->button = ms->obutton;
3176 			VLOG(1, (LOG_DEBUG, "psmintr: unknown PS2++ packet "
3177 			    "type %d: 0x%02x 0x%02x 0x%02x\n",
3178 			    MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
3179 			    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]));
3180 			break;
3181 		}
3182 	} else {
3183 		/* preserve button states */
3184 		ms->button |= ms->obutton & MOUSE_EXTBUTTONS;
3185 	}
3186 }
3187 
3188 static int
3189 proc_synaptics(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
3190     int *x, int *y, int *z)
3191 {
3192 	static int touchpad_buttons;
3193 	static int guest_buttons;
3194 	static finger_t f[PSM_FINGERS];
3195 	int w, id, nfingers, ewcode, extended_buttons, clickpad_pressed;
3196 
3197 	extended_buttons = 0;
3198 
3199 	/* TouchPad PS/2 absolute mode message format with capFourButtons:
3200 	 *
3201 	 *  Bits:        7   6   5   4   3   2   1   0 (LSB)
3202 	 *  ------------------------------------------------
3203 	 *  ipacket[0]:  1   0  W3  W2   0  W1   R   L
3204 	 *  ipacket[1]: Yb  Ya  Y9  Y8  Xb  Xa  X9  X8
3205 	 *  ipacket[2]: Z7  Z6  Z5  Z4  Z3  Z2  Z1  Z0
3206 	 *  ipacket[3]:  1   1  Yc  Xc   0  W0 D^R U^L
3207 	 *  ipacket[4]: X7  X6  X5  X4  X3  X2  X1  X0
3208 	 *  ipacket[5]: Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
3209 	 *
3210 	 * Legend:
3211 	 *  L: left physical mouse button
3212 	 *  R: right physical mouse button
3213 	 *  D: down button
3214 	 *  U: up button
3215 	 *  W: "wrist" value
3216 	 *  X: x position
3217 	 *  Y: y position
3218 	 *  Z: pressure
3219 	 *
3220 	 * Without capFourButtons but with nExtendeButtons and/or capMiddle
3221 	 *
3222 	 *  Bits:        7   6   5   4      3      2      1      0 (LSB)
3223 	 *  ------------------------------------------------------
3224 	 *  ipacket[3]:  1   1  Yc  Xc      0     W0    E^R    M^L
3225 	 *  ipacket[4]: X7  X6  X5  X4  X3|b7  X2|b5  X1|b3  X0|b1
3226 	 *  ipacket[5]: Y7  Y6  Y5  Y4  Y3|b8  Y2|b6  Y1|b4  Y0|b2
3227 	 *
3228 	 * Legend:
3229 	 *  M: Middle physical mouse button
3230 	 *  E: Extended mouse buttons reported instead of low bits of X and Y
3231 	 *  b1-b8: Extended mouse buttons
3232 	 *    Only ((nExtendedButtons + 1) >> 1) bits are used in packet
3233 	 *    4 and 5, for reading X and Y value they should be zeroed.
3234 	 *
3235 	 * Absolute reportable limits:    0 - 6143.
3236 	 * Typical bezel limits:       1472 - 5472.
3237 	 * Typical edge marings:       1632 - 5312.
3238 	 *
3239 	 * w = 3 Passthrough Packet
3240 	 *
3241 	 * Byte 2,5,6 == Byte 1,2,3 of "Guest"
3242 	 */
3243 
3244 	if (!synaptics_support)
3245 		return (0);
3246 
3247 	/* Sanity check for out of sync packets. */
3248 	if ((pb->ipacket[0] & 0xc8) != 0x80 ||
3249 	    (pb->ipacket[3] & 0xc8) != 0xc0)
3250 		return (-1);
3251 
3252 	*x = *y = 0;
3253 	ms->button = ms->obutton;
3254 
3255 	/*
3256 	 * Pressure value.
3257 	 * Interpretation:
3258 	 *   z = 0      No finger contact
3259 	 *   z = 10     Finger hovering near the pad
3260 	 *   z = 30     Very light finger contact
3261 	 *   z = 80     Normal finger contact
3262 	 *   z = 110    Very heavy finger contact
3263 	 *   z = 200    Finger lying flat on pad surface
3264 	 *   z = 255    Maximum reportable Z
3265 	 */
3266 	*z = pb->ipacket[2];
3267 
3268 	/*
3269 	 * Finger width value
3270 	 * Interpretation:
3271 	 *   w = 0      Two finger on the pad (capMultiFinger needed)
3272 	 *   w = 1      Three or more fingers (capMultiFinger needed)
3273 	 *   w = 2      Pen (instead of finger) (capPen needed)
3274 	 *   w = 3      Reserved (passthrough?)
3275 	 *   w = 4-7    Finger of normal width (capPalmDetect needed)
3276 	 *   w = 8-14   Very wide finger or palm (capPalmDetect needed)
3277 	 *   w = 15     Maximum reportable width (capPalmDetect needed)
3278 	 */
3279 	/* XXX Is checking capExtended enough? */
3280 	if (sc->synhw.capExtended)
3281 		w = ((pb->ipacket[0] & 0x30) >> 2) |
3282 		    ((pb->ipacket[0] & 0x04) >> 1) |
3283 		    ((pb->ipacket[3] & 0x04) >> 2);
3284 	else {
3285 		/* Assume a finger of regular width. */
3286 		w = 4;
3287 	}
3288 
3289 	switch (w) {
3290 	case 3:
3291 		/*
3292 		 * Handle packets from the guest device. See:
3293 		 * Synaptics PS/2 TouchPad Interfacing Guide, Section 5.1
3294 		 */
3295 		if (sc->synhw.capPassthrough) {
3296 			*x = ((pb->ipacket[1] & 0x10) ?
3297 			    pb->ipacket[4] - 256 : pb->ipacket[4]);
3298 			*y = ((pb->ipacket[1] & 0x20) ?
3299 			    pb->ipacket[5] - 256 : pb->ipacket[5]);
3300 			*z = 0;
3301 
3302 			guest_buttons = 0;
3303 			if (pb->ipacket[1] & 0x01)
3304 				guest_buttons |= MOUSE_BUTTON1DOWN;
3305 			if (pb->ipacket[1] & 0x04)
3306 				guest_buttons |= MOUSE_BUTTON2DOWN;
3307 			if (pb->ipacket[1] & 0x02)
3308 				guest_buttons |= MOUSE_BUTTON3DOWN;
3309 #ifdef EVDEV_SUPPORT
3310 			if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
3311 				evdev_push_rel(sc->evdev_r, REL_X, *x);
3312 				evdev_push_rel(sc->evdev_r, REL_Y, -*y);
3313 				evdev_push_mouse_btn(sc->evdev_r,
3314 				    guest_buttons);
3315 				evdev_sync(sc->evdev_r);
3316 			}
3317 #endif
3318 			ms->button = touchpad_buttons | guest_buttons |
3319 			    sc->extended_buttons;
3320 		}
3321 		goto SYNAPTICS_END;
3322 
3323 	case 2:
3324 		/* Handle Extended W mode packets */
3325 		ewcode = (pb->ipacket[5] & 0xf0) >> 4;
3326 #if PSM_FINGERS > 1
3327 		switch (ewcode) {
3328 		case 1:
3329 			/* Secondary finger */
3330 			if (sc->synhw.capAdvancedGestures)
3331 				f[1] = (finger_t) {
3332 					.x = (((pb->ipacket[4] & 0x0f) << 8) |
3333 					    pb->ipacket[1]) << 1,
3334 					.y = (((pb->ipacket[4] & 0xf0) << 4) |
3335 					    pb->ipacket[2]) << 1,
3336 					.p = ((pb->ipacket[3] & 0x30) |
3337 					    (pb->ipacket[5] & 0x0f)) << 1,
3338 					.w = PSM_FINGER_DEFAULT_W,
3339 					.flags = PSM_FINGER_FUZZY,
3340 				};
3341 			else if (sc->synhw.capReportsV)
3342 				f[1] = (finger_t) {
3343 					.x = (((pb->ipacket[4] & 0x0f) << 8) |
3344 					    (pb->ipacket[1] & 0xfe)) << 1,
3345 					.y = (((pb->ipacket[4] & 0xf0) << 4) |
3346 					    (pb->ipacket[2] & 0xfe)) << 1,
3347 					.p = ((pb->ipacket[3] & 0x30) |
3348 					    (pb->ipacket[5] & 0x0e)) << 1,
3349 					.w = (((pb->ipacket[5] & 0x01) << 2) |
3350 					    ((pb->ipacket[2] & 0x01) << 1) |
3351 					    (pb->ipacket[1] & 0x01)) + 8,
3352 					.flags = PSM_FINGER_FUZZY,
3353 				};
3354 		default:
3355 			break;
3356 		}
3357 #endif
3358 		goto SYNAPTICS_END;
3359 
3360 	case 1:
3361 	case 0:
3362 		nfingers = w + 2;
3363 		break;
3364 
3365 	default:
3366 		nfingers = 1;
3367 	}
3368 
3369 	if (sc->syninfo.touchpad_off)
3370 		goto SYNAPTICS_END;
3371 
3372 	/* Button presses */
3373 	touchpad_buttons = 0;
3374 	if (pb->ipacket[0] & 0x01)
3375 		touchpad_buttons |= MOUSE_BUTTON1DOWN;
3376 	if (pb->ipacket[0] & 0x02)
3377 		touchpad_buttons |= MOUSE_BUTTON3DOWN;
3378 
3379 	if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
3380 		if ((pb->ipacket[3] ^ pb->ipacket[0]) & 0x01)
3381 			touchpad_buttons |= MOUSE_BUTTON4DOWN;
3382 		if ((pb->ipacket[3] ^ pb->ipacket[0]) & 0x02)
3383 			touchpad_buttons |= MOUSE_BUTTON5DOWN;
3384 	} else if (sc->synhw.capExtended && sc->synhw.capMiddle &&
3385 	    !sc->synhw.capClickPad) {
3386 		/* Middle Button */
3387 		if ((pb->ipacket[0] ^ pb->ipacket[3]) & 0x01)
3388 			touchpad_buttons |= MOUSE_BUTTON2DOWN;
3389 	} else if (sc->synhw.capExtended && (sc->synhw.nExtendedButtons > 0)) {
3390 		/* Extended Buttons */
3391 		if ((pb->ipacket[0] ^ pb->ipacket[3]) & 0x02) {
3392 			if (sc->syninfo.directional_scrolls) {
3393 				if (pb->ipacket[4] & 0x01)
3394 					extended_buttons |= MOUSE_BUTTON4DOWN;
3395 				if (pb->ipacket[5] & 0x01)
3396 					extended_buttons |= MOUSE_BUTTON5DOWN;
3397 				if (pb->ipacket[4] & 0x02)
3398 					extended_buttons |= MOUSE_BUTTON6DOWN;
3399 				if (pb->ipacket[5] & 0x02)
3400 					extended_buttons |= MOUSE_BUTTON7DOWN;
3401 			} else {
3402 				if (pb->ipacket[4] & 0x01)
3403 					extended_buttons |= MOUSE_BUTTON1DOWN;
3404 				if (pb->ipacket[5] & 0x01)
3405 					extended_buttons |= MOUSE_BUTTON3DOWN;
3406 				if (pb->ipacket[4] & 0x02)
3407 					extended_buttons |= MOUSE_BUTTON2DOWN;
3408 				sc->extended_buttons = extended_buttons;
3409 			}
3410 
3411 			/*
3412 			 * Zero out bits used by extended buttons to avoid
3413 			 * misinterpretation of the data absolute position.
3414 			 *
3415 			 * The bits represented by
3416 			 *
3417 			 *     (nExtendedButtons + 1) >> 1
3418 			 *
3419 			 * will be masked out in both bytes.
3420 			 * The mask for n bits is computed with the formula
3421 			 *
3422 			 *     (1 << n) - 1
3423 			 */
3424 			int maskedbits = 0;
3425 			int mask = 0;
3426 			maskedbits = (sc->synhw.nExtendedButtons + 1) >> 1;
3427 			mask = (1 << maskedbits) - 1;
3428 #ifdef EVDEV_SUPPORT
3429 			int i;
3430 			if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
3431 				if (sc->synhw.capPassthrough) {
3432 					evdev_push_mouse_btn(sc->evdev_r,
3433 						extended_buttons);
3434 					evdev_sync(sc->evdev_r);
3435 				}
3436 				for (i = 0; i < maskedbits; i++) {
3437 					evdev_push_key(sc->evdev_a,
3438 					    BTN_0 + i * 2,
3439 					    pb->ipacket[4] & (1 << i));
3440 					evdev_push_key(sc->evdev_a,
3441 					    BTN_0 + i * 2 + 1,
3442 					    pb->ipacket[5] & (1 << i));
3443 				}
3444 			}
3445 #endif
3446 			pb->ipacket[4] &= ~(mask);
3447 			pb->ipacket[5] &= ~(mask);
3448 		} else	if (!sc->syninfo.directional_scrolls &&
3449 		    !sc->gesture.in_vscroll) {
3450 			/*
3451 			 * Keep reporting MOUSE DOWN until we get a new packet
3452 			 * indicating otherwise.
3453 			 */
3454 			extended_buttons |= sc->extended_buttons;
3455 		}
3456 	}
3457 
3458 	if (sc->synhw.capReportsV && nfingers > 1)
3459 		f[0] = (finger_t) {
3460 			.x = ((pb->ipacket[3] & 0x10) << 8) |
3461 			    ((pb->ipacket[1] & 0x0f) << 8) |
3462 			    (pb->ipacket[4] & 0xfd),
3463 			.y = ((pb->ipacket[3] & 0x20) << 7) |
3464 			    ((pb->ipacket[1] & 0xf0) << 4) |
3465 			    (pb->ipacket[5] & 0xfd),
3466 			.p = *z & 0xfe,
3467 			.w = (((pb->ipacket[2] & 0x01) << 2) |
3468 			    (pb->ipacket[5] & 0x02) |
3469 			    ((pb->ipacket[4] & 0x02) >> 1)) + 8,
3470 			.flags = PSM_FINGER_FUZZY,
3471 		};
3472 	else
3473 		f[0] = (finger_t) {
3474 			.x = ((pb->ipacket[3] & 0x10) << 8) |
3475 			    ((pb->ipacket[1] & 0x0f) << 8) |
3476 			    pb->ipacket[4],
3477 			.y = ((pb->ipacket[3] & 0x20) << 7) |
3478 			    ((pb->ipacket[1] & 0xf0) << 4) |
3479 			    pb->ipacket[5],
3480 			.p = *z,
3481 			.w = w,
3482 			.flags = nfingers > 1 ? PSM_FINGER_FUZZY : 0,
3483 		};
3484 
3485 	/* Ignore hovering and unmeasurable touches */
3486 	if (f[0].p < sc->syninfo.min_pressure || f[0].x < 2)
3487 		nfingers = 0;
3488 
3489 	/* Handle ClickPad */
3490 	if (sc->synhw.capClickPad) {
3491 		clickpad_pressed = (pb->ipacket[0] ^ pb->ipacket[3]) & 0x01;
3492 		if (sc->synhw.forcePad) {
3493 			/*
3494 			 * Forcepads erroneously report button click if there
3495 			 * are 2 or more fingers on the touchpad breaking
3496 			 * multifinger gestures. To workaround this start
3497 			 * reporting a click only after 4 consecutive single
3498 			 * touch packets has been received.
3499 			 * Skip these packets in case more contacts appear.
3500 			 */
3501 			switch (nfingers) {
3502 			case 0:
3503 				sc->fpcount = 0;
3504 				break;
3505 			case 1:
3506 				if (clickpad_pressed && sc->fpcount < INT_MAX)
3507 					++sc->fpcount;
3508 				/* FALLTHROUGH */
3509 			default:
3510 				if (!clickpad_pressed)
3511 					sc->fpcount = 0;
3512 				if (sc->fpcount >= sc->syninfo.window_min)
3513 					touchpad_buttons |= MOUSE_BUTTON1DOWN;
3514 			}
3515 		} else if (clickpad_pressed)
3516 			touchpad_buttons |= MOUSE_BUTTON1DOWN;
3517 	}
3518 
3519 	for (id = 0; id < PSM_FINGERS; id++)
3520 		if (id >= nfingers)
3521 			PSM_FINGER_RESET(f[id]);
3522 
3523 #ifdef EVDEV_SUPPORT
3524 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
3525 		for (id = 0; id < PSM_FINGERS; id++) {
3526 			if (PSM_FINGER_IS_SET(f[id]))
3527 				psm_push_mt_finger(sc, id, &f[id]);
3528 			else
3529 				psm_release_mt_slot(sc->evdev_a, id);
3530 		}
3531 		evdev_push_key(sc->evdev_a, BTN_TOUCH, nfingers > 0);
3532 		evdev_push_nfingers(sc->evdev_a, nfingers);
3533 		if (nfingers > 0)
3534 			psm_push_st_finger(sc, &f[0]);
3535 		else
3536 			evdev_push_abs(sc->evdev_a, ABS_PRESSURE, 0);
3537 		evdev_push_mouse_btn(sc->evdev_a, touchpad_buttons);
3538 		if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
3539 			evdev_push_key(sc->evdev_a, BTN_FORWARD,
3540 			    touchpad_buttons & MOUSE_BUTTON4DOWN);
3541 			evdev_push_key(sc->evdev_a, BTN_BACK,
3542 			    touchpad_buttons & MOUSE_BUTTON5DOWN);
3543 		}
3544 		evdev_sync(sc->evdev_a);
3545 	}
3546 #endif
3547 
3548 	ms->button = touchpad_buttons;
3549 
3550 	psmgestures(sc, &f[0], nfingers, ms);
3551 	for (id = 0; id < PSM_FINGERS; id++)
3552 		psmsmoother(sc, &f[id], id, ms, x, y);
3553 
3554 	/* Palm detection doesn't terminate the current action. */
3555 	if (psmpalmdetect(sc, &f[0], nfingers)) {
3556 		*x = *y = *z = 0;
3557 		ms->button = ms->obutton;
3558 		return (0);
3559 	}
3560 
3561 	ms->button |= extended_buttons | guest_buttons;
3562 
3563 SYNAPTICS_END:
3564 	/*
3565 	 * Use the extra buttons as a scrollwheel
3566 	 *
3567 	 * XXX X.Org uses the Z axis for vertical wheel only,
3568 	 * whereas moused(8) understands special values to differ
3569 	 * vertical and horizontal wheels.
3570 	 *
3571 	 * xf86-input-mouse needs therefore a small patch to
3572 	 * understand these special values. Without it, the
3573 	 * horizontal wheel acts as a vertical wheel in X.Org.
3574 	 *
3575 	 * That's why the horizontal wheel is disabled by
3576 	 * default for now.
3577 	 */
3578 	if (ms->button & MOUSE_BUTTON4DOWN)
3579 		*z = -1;
3580 	else if (ms->button & MOUSE_BUTTON5DOWN)
3581 		*z = 1;
3582 	else if (ms->button & MOUSE_BUTTON6DOWN)
3583 		*z = -2;
3584 	else if (ms->button & MOUSE_BUTTON7DOWN)
3585 		*z = 2;
3586 	else
3587 		*z = 0;
3588 	ms->button &= ~(MOUSE_BUTTON4DOWN | MOUSE_BUTTON5DOWN |
3589 	    MOUSE_BUTTON6DOWN | MOUSE_BUTTON7DOWN);
3590 
3591 	return (0);
3592 }
3593 
3594 static int
3595 psmpalmdetect(struct psm_softc *sc, finger_t *f, int nfingers)
3596 {
3597 	if (!(
3598 	    ((sc->synhw.capMultiFinger || sc->synhw.capAdvancedGestures) &&
3599 	      !sc->synhw.capReportsV && nfingers > 1) ||
3600 	    (sc->synhw.capReportsV && nfingers > 2) ||
3601 	    (sc->synhw.capPalmDetect && f->w <= sc->syninfo.max_width) ||
3602 	    (!sc->synhw.capPalmDetect && f->p <= sc->syninfo.max_pressure) ||
3603 	    (sc->synhw.capPen && f->flags & PSM_FINGER_IS_PEN))) {
3604 		/*
3605 		 * We consider the packet irrelevant for the current
3606 		 * action when:
3607 		 *  - the width isn't comprised in:
3608 		 *    [1; max_width]
3609 		 *  - the pressure isn't comprised in:
3610 		 *    [min_pressure; max_pressure]
3611 		 *  - pen aren't supported but PSM_FINGER_IS_PEN is set
3612 		 */
3613 		VLOG(2, (LOG_DEBUG, "synaptics: palm detected! (%d)\n", f->w));
3614 		return (1);
3615 	}
3616 	return (0);
3617 }
3618 
3619 static void
3620 psmgestures(struct psm_softc *sc, finger_t *fingers, int nfingers,
3621     mousestatus_t *ms)
3622 {
3623 	smoother_t *smoother;
3624 	gesture_t *gest;
3625 	finger_t *f;
3626 	int y_ok, center_button, center_x, right_button, right_x, i;
3627 
3628 	f = &fingers[0];
3629 	smoother = &sc->smoother[0];
3630 	gest = &sc->gesture;
3631 
3632 	/* Find first active finger. */
3633 	if (nfingers > 0) {
3634 		for (i = 0; i < PSM_FINGERS; i++) {
3635 			if (PSM_FINGER_IS_SET(fingers[i])) {
3636 				f = &fingers[i];
3637 				smoother = &sc->smoother[i];
3638 				break;
3639 			}
3640 		}
3641 	}
3642 
3643 	/*
3644 	 * Check pressure to detect a real wanted action on the
3645 	 * touchpad.
3646 	 */
3647 	if (f->p >= sc->syninfo.min_pressure) {
3648 		int x0, y0;
3649 		int dxp, dyp;
3650 		int start_x, start_y;
3651 		int queue_len;
3652 		int margin_top, margin_right, margin_bottom, margin_left;
3653 		int window_min, window_max;
3654 		int vscroll_hor_area, vscroll_ver_area;
3655 		int two_finger_scroll;
3656 		int max_x, max_y;
3657 
3658 		/* Read sysctl. */
3659 		/* XXX Verify values? */
3660 		margin_top = sc->syninfo.margin_top;
3661 		margin_right = sc->syninfo.margin_right;
3662 		margin_bottom = sc->syninfo.margin_bottom;
3663 		margin_left = sc->syninfo.margin_left;
3664 		window_min = sc->syninfo.window_min;
3665 		window_max = sc->syninfo.window_max;
3666 		vscroll_hor_area = sc->syninfo.vscroll_hor_area;
3667 		vscroll_ver_area = sc->syninfo.vscroll_ver_area;
3668 		two_finger_scroll = sc->syninfo.two_finger_scroll;
3669 		max_x = sc->syninfo.max_x;
3670 		max_y = sc->syninfo.max_y;
3671 
3672 		/* Read current absolute position. */
3673 		x0 = f->x;
3674 		y0 = f->y;
3675 
3676 		/*
3677 		 * Limit the coordinates to the specified margins because
3678 		 * this area isn't very reliable.
3679 		 */
3680 		if (x0 <= margin_left)
3681 			x0 = margin_left;
3682 		else if (x0 >= max_x - margin_right)
3683 			x0 = max_x - margin_right;
3684 		if (y0 <= margin_bottom)
3685 			y0 = margin_bottom;
3686 		else if (y0 >= max_y - margin_top)
3687 			y0 = max_y - margin_top;
3688 
3689 		VLOG(3, (LOG_DEBUG, "synaptics: ipacket: [%d, %d], %d, %d\n",
3690 		    x0, y0, f->p, f->w));
3691 
3692 		/*
3693 		 * If the action is just beginning, init the structure and
3694 		 * compute tap timeout.
3695 		 */
3696 		if (!(sc->flags & PSM_FLAGS_FINGERDOWN)) {
3697 			VLOG(3, (LOG_DEBUG, "synaptics: ----\n"));
3698 
3699 			/* Initialize queue. */
3700 			gest->window_min = window_min;
3701 
3702 			/* Reset pressure peak. */
3703 			gest->zmax = 0;
3704 
3705 			/* Reset fingers count. */
3706 			gest->fingers_nb = 0;
3707 
3708 			/* Reset virtual scrolling state. */
3709 			gest->in_vscroll = 0;
3710 
3711 			/* Compute tap timeout. */
3712 			gest->taptimeout.tv_sec  = tap_timeout / 1000000;
3713 			gest->taptimeout.tv_usec = tap_timeout % 1000000;
3714 			timevaladd(&gest->taptimeout, &sc->lastsoftintr);
3715 
3716 			sc->flags |= PSM_FLAGS_FINGERDOWN;
3717 
3718 			/* Smoother has not been reset yet */
3719 			queue_len = 1;
3720 			start_x = x0;
3721 			start_y = y0;
3722 		} else {
3723 			queue_len = smoother->queue_len + 1;
3724 			start_x = smoother->start_x;
3725 			start_y = smoother->start_y;
3726 		}
3727 
3728 		/* Process ClickPad softbuttons */
3729 		if (sc->synhw.capClickPad && ms->button & MOUSE_BUTTON1DOWN) {
3730 			y_ok = sc->syninfo.softbuttons_y >= 0 ?
3731 			    start_y < sc->syninfo.softbuttons_y :
3732 			    start_y > max_y + sc->syninfo.softbuttons_y;
3733 
3734 			center_button = MOUSE_BUTTON2DOWN;
3735 			center_x = sc->syninfo.softbutton2_x;
3736 			right_button = MOUSE_BUTTON3DOWN;
3737 			right_x = sc->syninfo.softbutton3_x;
3738 
3739 			if (center_x > 0 && right_x > 0 && center_x > right_x) {
3740 				center_button = MOUSE_BUTTON3DOWN;
3741 				center_x = sc->syninfo.softbutton3_x;
3742 				right_button = MOUSE_BUTTON2DOWN;
3743 				right_x = sc->syninfo.softbutton2_x;
3744 			}
3745 
3746 			if (right_x > 0 && start_x > right_x && y_ok)
3747 				ms->button = (ms->button &
3748 				    ~MOUSE_BUTTON1DOWN) | right_button;
3749 			else if (center_x > 0 && start_x > center_x && y_ok)
3750 				ms->button = (ms->button &
3751 				    ~MOUSE_BUTTON1DOWN) | center_button;
3752 		}
3753 
3754 		/* If in tap-hold, add the recorded button. */
3755 		if (gest->in_taphold)
3756 			ms->button |= gest->tap_button;
3757 
3758 		/*
3759 		 * For tap, we keep the maximum number of fingers and the
3760 		 * pressure peak. Also with multiple fingers, we increase
3761 		 * the minimum window.
3762 		 */
3763 		if (nfingers > 1)
3764 			gest->window_min = window_max;
3765 		gest->fingers_nb = imax(nfingers, gest->fingers_nb);
3766 		gest->zmax = imax(f->p, gest->zmax);
3767 
3768 		/* Do we have enough packets to consider this a gesture? */
3769 		if (queue_len < gest->window_min)
3770 			return;
3771 
3772 		dyp = -1;
3773 		dxp = -1;
3774 
3775 		/* Is a scrolling action occurring? */
3776 		if (!gest->in_taphold && !ms->button &&
3777 		    (!gest->in_vscroll || two_finger_scroll)) {
3778 			/*
3779 			 * A scrolling action must not conflict with a tap
3780 			 * action. Here are the conditions to consider a
3781 			 * scrolling action:
3782 			 *  - the action in a configurable area
3783 			 *  - one of the following:
3784 			 *     . the distance between the last packet and the
3785 			 *       first should be above a configurable minimum
3786 			 *     . tap timed out
3787 			 */
3788 			dxp = abs(x0 - start_x);
3789 			dyp = abs(y0 - start_y);
3790 
3791 			if (timevalcmp(&sc->lastsoftintr, &gest->taptimeout, >) ||
3792 			    dxp >= sc->syninfo.vscroll_min_delta ||
3793 			    dyp >= sc->syninfo.vscroll_min_delta) {
3794 				/*
3795 				 * Handle two finger scrolling.
3796 				 * Note that we don't rely on fingers_nb
3797 				 * as that keeps the maximum number of fingers.
3798 				 */
3799 				if (two_finger_scroll) {
3800 					if (nfingers == 2) {
3801 						gest->in_vscroll +=
3802 						    dyp ? 2 : 0;
3803 						gest->in_vscroll +=
3804 						    dxp ? 1 : 0;
3805 					}
3806 				} else {
3807 					/* Check for horizontal scrolling. */
3808 					if ((vscroll_hor_area > 0 &&
3809 					    start_y <= vscroll_hor_area) ||
3810 					    (vscroll_hor_area < 0 &&
3811 					     start_y >=
3812 					     max_y + vscroll_hor_area))
3813 						gest->in_vscroll += 2;
3814 
3815 					/* Check for vertical scrolling. */
3816 					if ((vscroll_ver_area > 0 &&
3817 					    start_x <= vscroll_ver_area) ||
3818 					    (vscroll_ver_area < 0 &&
3819 					     start_x >=
3820 					     max_x + vscroll_ver_area))
3821 						gest->in_vscroll += 1;
3822 				}
3823 
3824 				/* Avoid conflicts if area overlaps. */
3825 				if (gest->in_vscroll >= 3)
3826 					gest->in_vscroll =
3827 					    (dxp > dyp) ? 2 : 1;
3828 			}
3829 		}
3830 		/*
3831 		 * Reset two finger scrolling when the number of fingers
3832 		 * is different from two or any button is pressed.
3833 		 */
3834 		if (two_finger_scroll && gest->in_vscroll != 0 &&
3835 		    (nfingers != 2 || ms->button))
3836 			gest->in_vscroll = 0;
3837 
3838 		VLOG(5, (LOG_DEBUG,
3839 			"synaptics: virtual scrolling: %s "
3840 			"(direction=%d, dxp=%d, dyp=%d, fingers=%d)\n",
3841 			gest->in_vscroll ? "YES" : "NO",
3842 			gest->in_vscroll, dxp, dyp,
3843 			gest->fingers_nb));
3844 
3845 	} else if (sc->flags & PSM_FLAGS_FINGERDOWN) {
3846 		/*
3847 		 * An action is currently taking place but the pressure
3848 		 * dropped under the minimum, putting an end to it.
3849 		 */
3850 		int taphold_timeout, dx, dy, tap_max_delta;
3851 
3852 		dx = abs(smoother->queue[smoother->queue_cursor].x -
3853 		    smoother->start_x);
3854 		dy = abs(smoother->queue[smoother->queue_cursor].y -
3855 		    smoother->start_y);
3856 
3857 		/* Max delta is disabled for multi-fingers tap. */
3858 		if (gest->fingers_nb > 1)
3859 			tap_max_delta = imax(dx, dy);
3860 		else
3861 			tap_max_delta = sc->syninfo.tap_max_delta;
3862 
3863 		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
3864 
3865 		/* Check for tap. */
3866 		VLOG(3, (LOG_DEBUG,
3867 		    "synaptics: zmax=%d, dx=%d, dy=%d, "
3868 		    "delta=%d, fingers=%d, queue=%d\n",
3869 		    gest->zmax, dx, dy, tap_max_delta, gest->fingers_nb,
3870 		    smoother->queue_len));
3871 		if (!gest->in_vscroll && gest->zmax >= tap_threshold &&
3872 		    timevalcmp(&sc->lastsoftintr, &gest->taptimeout, <=) &&
3873 		    dx <= tap_max_delta && dy <= tap_max_delta &&
3874 		    smoother->queue_len >= sc->syninfo.tap_min_queue) {
3875 			/*
3876 			 * We have a tap if:
3877 			 *   - the maximum pressure went over tap_threshold
3878 			 *   - the action ended before tap_timeout
3879 			 *
3880 			 * To handle tap-hold, we must delay any button push to
3881 			 * the next action.
3882 			 */
3883 			if (gest->in_taphold) {
3884 				/*
3885 				 * This is the second and last tap of a
3886 				 * double tap action, not a tap-hold.
3887 				 */
3888 				gest->in_taphold = 0;
3889 
3890 				/*
3891 				 * For double-tap to work:
3892 				 *   - no button press is emitted (to
3893 				 *     simulate a button release)
3894 				 *   - PSM_FLAGS_FINGERDOWN is set to
3895 				 *     force the next packet to emit a
3896 				 *     button press)
3897 				 */
3898 				VLOG(2, (LOG_DEBUG,
3899 				    "synaptics: button RELEASE: %d\n",
3900 				    gest->tap_button));
3901 				sc->flags |= PSM_FLAGS_FINGERDOWN;
3902 
3903 				/* Schedule button press on next interrupt */
3904 				sc->idletimeout.tv_sec  = psmhz > 1 ?
3905 				    0 : 1;
3906 				sc->idletimeout.tv_usec = psmhz > 1 ?
3907 				    1000000 / psmhz : 0;
3908 			} else {
3909 				/*
3910 				 * This is the first tap: we set the
3911 				 * tap-hold state and notify the button
3912 				 * down event.
3913 				 */
3914 				gest->in_taphold = 1;
3915 				taphold_timeout = sc->syninfo.taphold_timeout;
3916 				gest->taptimeout.tv_sec  = taphold_timeout /
3917 				    1000000;
3918 				gest->taptimeout.tv_usec = taphold_timeout %
3919 				    1000000;
3920 				sc->idletimeout = gest->taptimeout;
3921 				timevaladd(&gest->taptimeout,
3922 				    &sc->lastsoftintr);
3923 
3924 				switch (gest->fingers_nb) {
3925 				case 3:
3926 					gest->tap_button =
3927 					    MOUSE_BUTTON2DOWN;
3928 					break;
3929 				case 2:
3930 					gest->tap_button =
3931 					    MOUSE_BUTTON3DOWN;
3932 					break;
3933 				default:
3934 					gest->tap_button =
3935 					    MOUSE_BUTTON1DOWN;
3936 				}
3937 				VLOG(2, (LOG_DEBUG,
3938 				    "synaptics: button PRESS: %d\n",
3939 				    gest->tap_button));
3940 				ms->button |= gest->tap_button;
3941 			}
3942 		} else {
3943 			/*
3944 			 * Not enough pressure or timeout: reset
3945 			 * tap-hold state.
3946 			 */
3947 			if (gest->in_taphold) {
3948 				VLOG(2, (LOG_DEBUG,
3949 				    "synaptics: button RELEASE: %d\n",
3950 				    gest->tap_button));
3951 				gest->in_taphold = 0;
3952 			} else {
3953 				VLOG(2, (LOG_DEBUG,
3954 				    "synaptics: not a tap-hold\n"));
3955 			}
3956 		}
3957 	} else if (!(sc->flags & PSM_FLAGS_FINGERDOWN) && gest->in_taphold) {
3958 		/*
3959 		 * For a tap-hold to work, the button must remain down at
3960 		 * least until timeout (where the in_taphold flags will be
3961 		 * cleared) or during the next action.
3962 		 */
3963 		if (timevalcmp(&sc->lastsoftintr, &gest->taptimeout, <=)) {
3964 			ms->button |= gest->tap_button;
3965 		} else {
3966 			VLOG(2, (LOG_DEBUG, "synaptics: button RELEASE: %d\n",
3967 			    gest->tap_button));
3968 			gest->in_taphold = 0;
3969 		}
3970 	}
3971 
3972 	return;
3973 }
3974 
3975 static void
3976 psmsmoother(struct psm_softc *sc, finger_t *f, int smoother_id,
3977     mousestatus_t *ms, int *x, int *y)
3978 {
3979 	smoother_t *smoother = &sc->smoother[smoother_id];
3980 	gesture_t *gest = &(sc->gesture);
3981 
3982 	/*
3983 	 * Check pressure to detect a real wanted action on the
3984 	 * touchpad.
3985 	 */
3986 	if (f->p >= sc->syninfo.min_pressure) {
3987 		int x0, y0;
3988 		int cursor, peer, window;
3989 		int dx, dy, dxp, dyp;
3990 		int max_width, max_pressure;
3991 		int margin_top, margin_right, margin_bottom, margin_left;
3992 		int na_top, na_right, na_bottom, na_left;
3993 		int window_min, window_max;
3994 		int multiplicator;
3995 		int weight_current, weight_previous, weight_len_squared;
3996 		int div_min, div_max, div_len;
3997 		int vscroll_hor_area, vscroll_ver_area;
3998 		int two_finger_scroll;
3999 		int max_x, max_y;
4000 		int len, weight_prev_x, weight_prev_y;
4001 		int div_max_x, div_max_y, div_x, div_y;
4002 		int is_fuzzy;
4003 
4004 		/* Read sysctl. */
4005 		/* XXX Verify values? */
4006 		max_width = sc->syninfo.max_width;
4007 		max_pressure = sc->syninfo.max_pressure;
4008 		margin_top = sc->syninfo.margin_top;
4009 		margin_right = sc->syninfo.margin_right;
4010 		margin_bottom = sc->syninfo.margin_bottom;
4011 		margin_left = sc->syninfo.margin_left;
4012 		na_top = sc->syninfo.na_top;
4013 		na_right = sc->syninfo.na_right;
4014 		na_bottom = sc->syninfo.na_bottom;
4015 		na_left = sc->syninfo.na_left;
4016 		window_min = sc->syninfo.window_min;
4017 		window_max = sc->syninfo.window_max;
4018 		multiplicator = sc->syninfo.multiplicator;
4019 		weight_current = sc->syninfo.weight_current;
4020 		weight_previous = sc->syninfo.weight_previous;
4021 		weight_len_squared = sc->syninfo.weight_len_squared;
4022 		div_min = sc->syninfo.div_min;
4023 		div_max = sc->syninfo.div_max;
4024 		div_len = sc->syninfo.div_len;
4025 		vscroll_hor_area = sc->syninfo.vscroll_hor_area;
4026 		vscroll_ver_area = sc->syninfo.vscroll_ver_area;
4027 		two_finger_scroll = sc->syninfo.two_finger_scroll;
4028 		max_x = sc->syninfo.max_x;
4029 		max_y = sc->syninfo.max_y;
4030 
4031 		is_fuzzy = (f->flags & PSM_FINGER_FUZZY) != 0;
4032 
4033 		/* Read current absolute position. */
4034 		x0 = f->x;
4035 		y0 = f->y;
4036 
4037 		/*
4038 		 * Limit the coordinates to the specified margins because
4039 		 * this area isn't very reliable.
4040 		 */
4041 		if (x0 <= margin_left)
4042 			x0 = margin_left;
4043 		else if (x0 >= max_x - margin_right)
4044 			x0 = max_x - margin_right;
4045 		if (y0 <= margin_bottom)
4046 			y0 = margin_bottom;
4047 		else if (y0 >= max_y - margin_top)
4048 			y0 = max_y - margin_top;
4049 
4050 		/* If the action is just beginning, init the structure. */
4051 		if (smoother->active == 0) {
4052 			VLOG(3, (LOG_DEBUG, "smoother%d: ---\n", smoother_id));
4053 
4054 			/* Store the first point of this action. */
4055 			smoother->start_x = x0;
4056 			smoother->start_y = y0;
4057 			dx = dy = 0;
4058 
4059 			/* Initialize queue. */
4060 			smoother->queue_cursor = SYNAPTICS_PACKETQUEUE;
4061 			smoother->queue_len = 0;
4062 
4063 			/* Reset average. */
4064 			smoother->avg_dx = 0;
4065 			smoother->avg_dy = 0;
4066 
4067 			/* Reset squelch. */
4068 			smoother->squelch_x = 0;
4069 			smoother->squelch_y = 0;
4070 
4071 			/* Activate queue */
4072 			smoother->active = 1;
4073 		} else {
4074 			/* Calculate the current delta. */
4075 			cursor = smoother->queue_cursor;
4076 			dx = x0 - smoother->queue[cursor].x;
4077 			dy = y0 - smoother->queue[cursor].y;
4078 		}
4079 
4080 		VLOG(3, (LOG_DEBUG, "smoother%d: ipacket: [%d, %d], %d, %d\n",
4081 		    smoother_id, x0, y0, f->p, f->w));
4082 
4083 		/* Queue this new packet. */
4084 		cursor = SYNAPTICS_QUEUE_CURSOR(smoother->queue_cursor - 1);
4085 		smoother->queue[cursor].x = x0;
4086 		smoother->queue[cursor].y = y0;
4087 		smoother->queue_cursor = cursor;
4088 		if (smoother->queue_len < SYNAPTICS_PACKETQUEUE)
4089 			smoother->queue_len++;
4090 		VLOG(5, (LOG_DEBUG,
4091 		    "smoother%d: cursor[%d]: x=%d, y=%d, dx=%d, dy=%d\n",
4092 		    smoother_id, cursor, x0, y0, dx, dy));
4093 
4094 		/* Do we have enough packets to consider this a movement? */
4095 		if (smoother->queue_len < gest->window_min)
4096 			return;
4097 
4098 		weight_prev_x = weight_prev_y = weight_previous;
4099 		div_max_x = div_max_y = div_max;
4100 
4101 		if (gest->in_vscroll) {
4102 			/* Dividers are different with virtual scrolling. */
4103 			div_min = sc->syninfo.vscroll_div_min;
4104 			div_max_x = div_max_y = sc->syninfo.vscroll_div_max;
4105 		} else {
4106 			/*
4107 			 * There's a lot of noise in coordinates when
4108 			 * the finger is on the touchpad's borders. When
4109 			 * using this area, we apply a special weight and
4110 			 * div.
4111 			 */
4112 			if (x0 <= na_left || x0 >= max_x - na_right) {
4113 				weight_prev_x = sc->syninfo.weight_previous_na;
4114 				div_max_x = sc->syninfo.div_max_na;
4115 			}
4116 
4117 			if (y0 <= na_bottom || y0 >= max_y - na_top) {
4118 				weight_prev_y = sc->syninfo.weight_previous_na;
4119 				div_max_y = sc->syninfo.div_max_na;
4120 			}
4121 		}
4122 
4123 		/*
4124 		 * Calculate weights for the average operands and
4125 		 * the divisor. Both depend on the distance between
4126 		 * the current packet and a previous one (based on the
4127 		 * window width).
4128 		 */
4129 		window = imin(smoother->queue_len, window_max);
4130 		peer = SYNAPTICS_QUEUE_CURSOR(cursor + window - 1);
4131 		dxp = abs(x0 - smoother->queue[peer].x) + 1;
4132 		dyp = abs(y0 - smoother->queue[peer].y) + 1;
4133 		len = (dxp * dxp) + (dyp * dyp);
4134 		weight_prev_x = imin(weight_prev_x,
4135 		    weight_len_squared * weight_prev_x / len);
4136 		weight_prev_y = imin(weight_prev_y,
4137 		    weight_len_squared * weight_prev_y / len);
4138 
4139 		len = (dxp + dyp) / 2;
4140 		div_x = div_len * div_max_x / len;
4141 		div_x = imin(div_max_x, div_x);
4142 		div_x = imax(div_min, div_x);
4143 		div_y = div_len * div_max_y / len;
4144 		div_y = imin(div_max_y, div_y);
4145 		div_y = imax(div_min, div_y);
4146 
4147 		VLOG(3, (LOG_DEBUG,
4148 		    "smoother%d: peer=%d, len=%d, weight=%d/%d, div=%d/%d\n",
4149 		    smoother_id, peer, len, weight_prev_x, weight_prev_y,
4150 		    div_x, div_y));
4151 
4152 		/* Compute averages. */
4153 		smoother->avg_dx =
4154 		    (weight_current * dx * multiplicator +
4155 		     weight_prev_x * smoother->avg_dx) /
4156 		    (weight_current + weight_prev_x);
4157 
4158 		smoother->avg_dy =
4159 		    (weight_current * dy * multiplicator +
4160 		     weight_prev_y * smoother->avg_dy) /
4161 		    (weight_current + weight_prev_y);
4162 
4163 		VLOG(5, (LOG_DEBUG,
4164 		    "smoother%d: avg_dx~=%d, avg_dy~=%d\n", smoother_id,
4165 		    smoother->avg_dx / multiplicator,
4166 		    smoother->avg_dy / multiplicator));
4167 
4168 		/* Use these averages to calculate x & y. */
4169 		smoother->squelch_x += smoother->avg_dx;
4170 		dxp = smoother->squelch_x / (div_x * multiplicator);
4171 		smoother->squelch_x = smoother->squelch_x %
4172 		    (div_x * multiplicator);
4173 
4174 		smoother->squelch_y += smoother->avg_dy;
4175 		dyp = smoother->squelch_y / (div_y * multiplicator);
4176 		smoother->squelch_y = smoother->squelch_y %
4177 		    (div_y * multiplicator);
4178 
4179 		switch(gest->in_vscroll) {
4180 		case 0: /* Pointer movement. */
4181 			/* On real<->fuzzy finger switch the x/y pos jumps */
4182 			if (is_fuzzy == smoother->is_fuzzy) {
4183 				*x += dxp;
4184 				*y += dyp;
4185 			}
4186 
4187 			VLOG(3, (LOG_DEBUG, "smoother%d: [%d, %d] -> [%d, %d]\n",
4188 			    smoother_id, dx, dy, dxp, dyp));
4189 			break;
4190 		case 1: /* Vertical scrolling. */
4191 			if (dyp != 0)
4192 				ms->button |= (dyp > 0) ?
4193 				    MOUSE_BUTTON4DOWN : MOUSE_BUTTON5DOWN;
4194 			break;
4195 		case 2: /* Horizontal scrolling. */
4196 			if (dxp != 0)
4197 				ms->button |= (dxp > 0) ?
4198 				    MOUSE_BUTTON7DOWN : MOUSE_BUTTON6DOWN;
4199 			break;
4200 		}
4201 
4202 		smoother->is_fuzzy = is_fuzzy;
4203 
4204 	} else {
4205 		/*
4206 		 * Deactivate queue. Note: We can not just reset queue here
4207 		 * as these values are still used by gesture processor.
4208 		 * So postpone reset till next touch.
4209 		 */
4210 		smoother->active = 0;
4211 	}
4212 }
4213 
4214 static int
4215 proc_elantech(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
4216     int *x, int *y, int *z)
4217 {
4218 	static int touchpad_button, trackpoint_button;
4219 	finger_t fn, f[ELANTECH_MAX_FINGERS];
4220 	int pkt, id, scale, i, nfingers, mask;
4221 
4222 	if (!elantech_support)
4223 		return (0);
4224 
4225 	/* Determine packet format and do a sanity check for out of sync packets. */
4226 	if (ELANTECH_PKT_IS_DEBOUNCE(pb, sc->elanhw.hwversion))
4227 		pkt = ELANTECH_PKT_NOP;
4228 	else if (sc->elanhw.hastrackpoint && ELANTECH_PKT_IS_TRACKPOINT(pb))
4229 		pkt = ELANTECH_PKT_TRACKPOINT;
4230 	else
4231 	switch (sc->elanhw.hwversion) {
4232 	case 2:
4233 		if (!ELANTECH_PKT_IS_V2(pb))
4234 			return (-1);
4235 
4236 		pkt = (pb->ipacket[0] & 0xc0) == 0x80 ?
4237 		    ELANTECH_PKT_V2_2FINGER : ELANTECH_PKT_V2_COMMON;
4238 		break;
4239 	case 3:
4240 		if (!ELANTECH_PKT_IS_V3_HEAD(pb, sc->elanhw.hascrc) &&
4241 		    !ELANTECH_PKT_IS_V3_TAIL(pb, sc->elanhw.hascrc))
4242 			return (-1);
4243 
4244 		pkt = ELANTECH_PKT_V3;
4245 		break;
4246 	case 4:
4247 		if (!ELANTECH_PKT_IS_V4(pb, sc->elanhw.hascrc))
4248 			return (-1);
4249 
4250 		switch (pb->ipacket[3] & 0x03) {
4251 		case 0x00:
4252 			pkt = ELANTECH_PKT_V4_STATUS;
4253 			break;
4254 		case 0x01:
4255 			pkt = ELANTECH_PKT_V4_HEAD;
4256 			break;
4257 		case 0x02:
4258 			pkt = ELANTECH_PKT_V4_MOTION;
4259 			break;
4260 		default:
4261 			return (-1);
4262 		}
4263 		break;
4264 	default:
4265 		return (-1);
4266 	}
4267 
4268 	VLOG(5, (LOG_DEBUG, "elantech: ipacket format: %d\n", pkt));
4269 
4270 	for (id = 0; id < ELANTECH_MAX_FINGERS; id++)
4271 		PSM_FINGER_RESET(f[id]);
4272 
4273 	*x = *y = *z = 0;
4274 	ms->button = ms->obutton;
4275 
4276 	if (sc->syninfo.touchpad_off)
4277 		return (0);
4278 
4279 	/* Common legend
4280 	 * L: Left mouse button pressed
4281 	 * R: Right mouse button pressed
4282 	 * N: number of fingers on touchpad
4283 	 * X: absolute x value (horizontal)
4284 	 * Y: absolute y value (vertical)
4285 	 * W; width of the finger touch
4286 	 * P: pressure
4287 	 */
4288 	switch (pkt) {
4289 	case ELANTECH_PKT_V2_COMMON:	/* HW V2. One/Three finger touch */
4290 		/*               7   6   5   4   3   2   1   0 (LSB)
4291 		 * -------------------------------------------
4292 		 * ipacket[0]:  N1  N0  W3  W2   .   .   R   L
4293 		 * ipacket[1]:  P7  P6  P5  P4 X11 X10  X9  X8
4294 		 * ipacket[2]:  X7  X6  X5  X4  X3  X2  X1  X0
4295 		 * ipacket[3]:  N4  VF  W1  W0   .   .   .  B2
4296 		 * ipacket[4]:  P3  P1  P2  P0 Y11 Y10  Y9  Y8
4297 		 * ipacket[5]:  Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
4298 		 * -------------------------------------------
4299 		 * N4: set if more than 3 fingers (only in 3 fingers mode)
4300 		 * VF: a kind of flag? (only on EF123, 0 when finger
4301 		 *     is over one of the buttons, 1 otherwise)
4302 		 * B2: (on EF113 only, 0 otherwise), one button pressed
4303 		 * P & W is not reported on EF113 touchpads
4304 		 */
4305 		nfingers = (pb->ipacket[0] & 0xc0) >> 6;
4306 		if (nfingers == 3 && (pb->ipacket[3] & 0x80))
4307 			nfingers = 4;
4308 
4309 		if (nfingers == 0) {
4310 			mask = (1 << nfingers) - 1;	/* = 0x00 */
4311 			break;
4312 		}
4313 
4314 		/* Map 3-rd and 4-th fingers to first finger */
4315 		mask = (1 << 1) - 1;	/* = 0x01 */
4316 		f[0] = ELANTECH_FINGER_SET_XYP(pb);
4317 		if (sc->elanhw.haspressure) {
4318 			f[0].w = ((pb->ipacket[0] & 0x30) >> 2) |
4319 			    ((pb->ipacket[3] & 0x30) >> 4);
4320 		} else {
4321 			f[0].p = PSM_FINGER_DEFAULT_P;
4322 			f[0].w = PSM_FINGER_DEFAULT_W;
4323 		}
4324 
4325 		/*
4326 		 * HW v2 dont report exact finger positions when 3 or more
4327 		 * fingers are on touchpad.
4328 		 */
4329 		if (nfingers > 2)
4330 			f[0].flags = PSM_FINGER_FUZZY;
4331 
4332 		break;
4333 
4334 	case ELANTECH_PKT_V2_2FINGER:	/*HW V2. Two finger touch */
4335 		/*               7   6   5   4   3   2   1   0 (LSB)
4336 		 * -------------------------------------------
4337 		 * ipacket[0]:  N1  N0 AY8 AX8   .   .   R   L
4338 		 * ipacket[1]: AX7 AX6 AX5 AX4 AX3 AX2 AX1 AX0
4339 		 * ipacket[2]: AY7 AY6 AY5 AY4 AY3 AY2 AY1 AY0
4340 		 * ipacket[3]:   .   . BY8 BX8   .   .   .   .
4341 		 * ipacket[4]: BX7 BX6 BX5 BX4 BX3 BX2 BX1 BX0
4342 		 * ipacket[5]: BY7 BY6 BY5 BY4 BY3 BY2 BY1 BY0
4343 		 * -------------------------------------------
4344 		 * AX: lower-left finger absolute x value
4345 		 * AY: lower-left finger absolute y value
4346 		 * BX: upper-right finger absolute x value
4347 		 * BY: upper-right finger absolute y value
4348 		 */
4349 		nfingers = 2;
4350 		mask = (1 << nfingers) - 1;
4351 
4352 		for (id = 0; id < imin(2, ELANTECH_MAX_FINGERS); id ++)
4353 			f[id] = (finger_t) {
4354 				.x = (((pb->ipacket[id * 3] & 0x10) << 4) |
4355 				    pb->ipacket[id * 3 + 1]) << 2,
4356 				.y = (((pb->ipacket[id * 3] & 0x20) << 3) |
4357 				    pb->ipacket[id * 3 + 2]) << 2,
4358 				.p = PSM_FINGER_DEFAULT_P,
4359 				.w = PSM_FINGER_DEFAULT_W,
4360 				/* HW ver.2 sends bounding box */
4361 				.flags = PSM_FINGER_FUZZY
4362 			};
4363 		break;
4364 
4365 	case ELANTECH_PKT_V3:	/* HW Version 3 */
4366 		/*               7   6   5   4   3   2   1   0 (LSB)
4367 		 * -------------------------------------------
4368 		 * ipacket[0]:  N1  N0  W3  W2   0   1   R   L
4369 		 * ipacket[1]:  P7  P6  P5  P4 X11 X10  X9  X8
4370 		 * ipacket[2]:  X7  X6  X5  X4  X3  X2  X1  X0
4371 		 * ipacket[3]:   0   0  W1  W0   0   0   1   0
4372 		 * ipacket[4]:  P3  P1  P2  P0 Y11 Y10  Y9  Y8
4373 		 * ipacket[5]:  Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
4374 		 * -------------------------------------------
4375 		 */
4376 		nfingers = (pb->ipacket[0] & 0xc0) >> 6;
4377 		/* Map 3-rd finger to first finger */
4378 		id = nfingers > 2 ? 0 : nfingers - 1;
4379 		mask = (1 << (id + 1)) - 1;
4380 
4381 		if (nfingers == 0)
4382 			break;
4383 
4384 		fn = ELANTECH_FINGER_SET_XYP(pb);
4385 		fn.w = ((pb->ipacket[0] & 0x30) >> 2) |
4386 		    ((pb->ipacket[3] & 0x30) >> 4);
4387 
4388 		/*
4389 		 * HW v3 dont report exact finger positions when 3 or more
4390 		 * fingers are on touchpad.
4391 		 */
4392 		if (nfingers > 1)
4393 			fn.flags = PSM_FINGER_FUZZY;
4394 
4395 		if (nfingers == 2) {
4396 			if (ELANTECH_PKT_IS_V3_HEAD(pb, sc->elanhw.hascrc)) {
4397 				sc->elanaction.fingers[0] = fn;
4398 				return (0);
4399 			} else
4400 				f[0] = sc->elanaction.fingers[0];
4401 		}
4402 		f[id] = fn;
4403 		break;
4404 
4405 	case ELANTECH_PKT_V4_STATUS:	/* HW Version 4. Status packet */
4406 		/*               7   6   5   4   3   2   1   0 (LSB)
4407 		 * -------------------------------------------
4408 		 * ipacket[0]:   .   .   .   .   0   1   R   L
4409 		 * ipacket[1]:   .   .   .  F4  F3  F2  F1  F0
4410 		 * ipacket[2]:   .   .   .   .   .   .   .   .
4411 		 * ipacket[3]:   .   .   .   1   0   0   0   0
4412 		 * ipacket[4]:  PL   .   .   .   .   .   .   .
4413 		 * ipacket[5]:   .   .   .   .   .   .   .   .
4414 		 * -------------------------------------------
4415 		 * Fn: finger n is on touchpad
4416 		 * PL: palm
4417 		 * HV ver4 sends a status packet to indicate that the numbers
4418 		 * or identities of the fingers has been changed
4419 		 */
4420 
4421 		mask = pb->ipacket[1] & 0x1f;
4422 		nfingers = bitcount(mask);
4423 
4424 		if (sc->elanaction.mask_v4wait != 0)
4425 			VLOG(3, (LOG_DEBUG, "elantech: HW v4 status packet"
4426 			    " when not all previous head packets received\n"));
4427 
4428 		/* Bitmap of fingers to receive before gesture processing */
4429 		sc->elanaction.mask_v4wait = mask & ~sc->elanaction.mask;
4430 
4431 		/* Skip "new finger is on touchpad" packets */
4432 		if (sc->elanaction.mask_v4wait) {
4433 			sc->elanaction.mask = mask;
4434 			return (0);
4435 		}
4436 
4437 		break;
4438 
4439 	case ELANTECH_PKT_V4_HEAD:	/* HW Version 4. Head packet */
4440 		/*               7   6   5   4   3   2   1   0 (LSB)
4441 		 * -------------------------------------------
4442 		 * ipacket[0]:  W3  W2  W1  W0   0   1   R   L
4443 		 * ipacket[1]:  P7  P6  P5  P4 X11 X10  X9  X8
4444 		 * ipacket[2]:  X7  X6  X5  X4  X3  X2  X1  X0
4445 		 * ipacket[3]: ID2 ID1 ID0   1   0   0   0   1
4446 		 * ipacket[4]:  P3  P1  P2  P0 Y11 Y10  Y9  Y8
4447 		 * ipacket[5]:  Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
4448 		 * -------------------------------------------
4449 		 * ID: finger id
4450 		 * HW ver 4 sends head packets in two cases:
4451 		 * 1. One finger touch and movement.
4452 		 * 2. Next after status packet to tell new finger positions.
4453 		 */
4454 		mask = sc->elanaction.mask;
4455 		nfingers = bitcount(mask);
4456 		id = ((pb->ipacket[3] & 0xe0) >> 5) - 1;
4457 		fn = ELANTECH_FINGER_SET_XYP(pb);
4458 		fn.w =(pb->ipacket[0] & 0xf0) >> 4;
4459 
4460 		if (id < 0)
4461 			return (0);
4462 
4463 		/* Packet is finger position update. Report it */
4464 		if (sc->elanaction.mask_v4wait == 0) {
4465 			if (id < ELANTECH_MAX_FINGERS)
4466 				f[id] = fn;
4467 			break;
4468 		}
4469 
4470 		/* Remove finger from waiting bitmap and store into context */
4471 		sc->elanaction.mask_v4wait &= ~(1 << id);
4472 		if (id < ELANTECH_MAX_FINGERS)
4473 			sc->elanaction.fingers[id] = fn;
4474 
4475 		/* Wait for other fingers if needed */
4476 		if (sc->elanaction.mask_v4wait != 0)
4477 			return (0);
4478 
4479 		/* All new fingers are received. Report them from context */
4480 		for (id = 0; id < ELANTECH_MAX_FINGERS; id++)
4481 			if (sc->elanaction.mask & (1 << id))
4482 				f[id] =  sc->elanaction.fingers[id];
4483 
4484 		break;
4485 
4486 	case ELANTECH_PKT_V4_MOTION:	/* HW Version 4. Motion packet */
4487 		/*               7   6   5   4   3   2   1   0 (LSB)
4488 		 * -------------------------------------------
4489 		 * ipacket[0]: ID2 ID1 ID0  OF   0   1   R   L
4490 		 * ipacket[1]: DX7 DX6 DX5 DX4 DX3 DX2 DX1 DX0
4491 		 * ipacket[2]: DY7 DY6 DY5 DY4 DY3 DY2 DY1 DY0
4492 		 * ipacket[3]: ID2 ID1 ID0   1   0   0   1   0
4493 		 * ipacket[4]: DX7 DX6 DX5 DX4 DX3 DX2 DX1 DX0
4494 		 * ipacket[5]: DY7 DY6 DY5 DY4 DY3 DY2 DY1 DY0
4495 		 * -------------------------------------------
4496 		 * OF: delta overflows (> 127 or < -128), in this case
4497 		 *     firmware sends us (delta x / 5) and (delta y / 5)
4498 		 * ID: finger id
4499 		 * DX: delta x (two's complement)
4500 		 * XY: delta y (two's complement)
4501 		 * byte 0 ~ 2 for one finger
4502 		 * byte 3 ~ 5 for another finger
4503 		 */
4504 		mask = sc->elanaction.mask;
4505 		nfingers = bitcount(mask);
4506 
4507 		scale = (pb->ipacket[0] & 0x10) ? 5 : 1;
4508 		for (i = 0; i <= 3; i += 3) {
4509 			id = ((pb->ipacket[i] & 0xe0) >> 5) - 1;
4510 			if (id < 0 || id >= ELANTECH_MAX_FINGERS)
4511 				continue;
4512 
4513 			if (PSM_FINGER_IS_SET(sc->elanaction.fingers[id])) {
4514 				f[id] = sc->elanaction.fingers[id];
4515 				f[id].x += imax(-f[id].x,
4516 				    (signed char)pb->ipacket[i+1] * scale);
4517 				f[id].y += imax(-f[id].y,
4518 				    (signed char)pb->ipacket[i+2] * scale);
4519 			} else {
4520 				VLOG(3, (LOG_DEBUG, "elantech: "
4521 				    "HW v4 motion packet skipped\n"));
4522 			}
4523 		}
4524 
4525 		break;
4526 
4527 	case ELANTECH_PKT_TRACKPOINT:
4528 		/*               7   6   5   4   3   2   1   0 (LSB)
4529 		 * -------------------------------------------
4530 		 * ipacket[0]:   0   0  SX  SY   0   M   R   L
4531 		 * ipacket[1]: ~SX   0   0   0   0   0   0   0
4532 		 * ipacket[2]: ~SY   0   0   0   0   0   0   0
4533 		 * ipacket[3]:   0   0 ~SY ~SX   0   1   1   0
4534 		 * ipacket[4]:  X7  X6  X5  X4  X3  X2  X1  X0
4535 		 * ipacket[5]:  Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
4536 		 * -------------------------------------------
4537 		 * X and Y are written in two's complement spread
4538 		 * over 9 bits with SX/SY the relative top bit and
4539 		 * X7..X0 and Y7..Y0 the lower bits.
4540 		 */
4541 		*x = (pb->ipacket[0] & 0x20) ?
4542 		    pb->ipacket[4] - 256 : pb->ipacket[4];
4543 		*y = (pb->ipacket[0] & 0x10) ?
4544 		    pb->ipacket[5] - 256 : pb->ipacket[5];
4545 
4546 		trackpoint_button =
4547 		    ((pb->ipacket[0] & 0x01) ? MOUSE_BUTTON1DOWN : 0) |
4548 		    ((pb->ipacket[0] & 0x02) ? MOUSE_BUTTON3DOWN : 0) |
4549 		    ((pb->ipacket[0] & 0x04) ? MOUSE_BUTTON2DOWN : 0);
4550 #ifdef EVDEV_SUPPORT
4551 		evdev_push_rel(sc->evdev_r, REL_X, *x);
4552 		evdev_push_rel(sc->evdev_r, REL_Y, -*y);
4553 		evdev_push_mouse_btn(sc->evdev_r, trackpoint_button);
4554 		evdev_sync(sc->evdev_r);
4555 #endif
4556 		ms->button = touchpad_button | trackpoint_button;
4557 		return (0);
4558 
4559 	case ELANTECH_PKT_NOP:
4560 		return (0);
4561 
4562 	default:
4563 		return (-1);
4564 	}
4565 
4566 	for (id = 0; id < ELANTECH_MAX_FINGERS; id++)
4567 		if (PSM_FINGER_IS_SET(f[id]))
4568 			VLOG(2, (LOG_DEBUG, "elantech: "
4569 			    "finger %d: down [%d, %d], %d, %d, %d\n", id + 1,
4570 			    f[id].x, f[id].y, f[id].p, f[id].w, f[id].flags));
4571 
4572 	/* Touchpad button presses */
4573 	if (sc->elanhw.isclickpad) {
4574 		touchpad_button =
4575 		    ((pb->ipacket[0] & 0x03) ? MOUSE_BUTTON1DOWN : 0);
4576 	} else {
4577 		touchpad_button =
4578 		    ((pb->ipacket[0] & 0x01) ? MOUSE_BUTTON1DOWN : 0) |
4579 		    ((pb->ipacket[0] & 0x02) ? MOUSE_BUTTON3DOWN : 0);
4580 	}
4581 
4582 #ifdef EVDEV_SUPPORT
4583 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
4584 		for (id = 0; id < ELANTECH_MAX_FINGERS; id++) {
4585 			if (PSM_FINGER_IS_SET(f[id])) {
4586 				psm_push_mt_finger(sc, id, &f[id]);
4587 				/* Convert touch width to surface units */
4588 				evdev_push_abs(sc->evdev_a, ABS_MT_TOUCH_MAJOR,
4589 				    f[id].w * sc->elanhw.dptracex);
4590 			}
4591 			if (sc->elanaction.mask & (1 << id) &&
4592 			    !(mask & (1 << id)))
4593 				psm_release_mt_slot(sc->evdev_a, id);
4594 		}
4595 		evdev_push_key(sc->evdev_a, BTN_TOUCH, nfingers > 0);
4596 		evdev_push_nfingers(sc->evdev_a, nfingers);
4597 		if (nfingers > 0) {
4598 			if (PSM_FINGER_IS_SET(f[0]))
4599 				psm_push_st_finger(sc, &f[0]);
4600 		} else
4601 			evdev_push_abs(sc->evdev_a, ABS_PRESSURE, 0);
4602 		evdev_push_mouse_btn(sc->evdev_a, touchpad_button);
4603 		evdev_sync(sc->evdev_a);
4604 	}
4605 #endif
4606 
4607 	ms->button = touchpad_button | trackpoint_button;
4608 
4609 	/* Send finger 1 position to gesture processor */
4610 	if (PSM_FINGER_IS_SET(f[0]) || PSM_FINGER_IS_SET(f[1]) ||
4611 	    nfingers == 0)
4612 		psmgestures(sc, &f[0], imin(nfingers, 3), ms);
4613 	/* Send fingers positions to movement smoothers */
4614 	for (id = 0; id < PSM_FINGERS; id++)
4615 		if (PSM_FINGER_IS_SET(f[id]) || !(mask & (1 << id)))
4616 			psmsmoother(sc, &f[id], id, ms, x, y);
4617 
4618 	/* Store current finger positions in action context */
4619 	for (id = 0; id < ELANTECH_MAX_FINGERS; id++) {
4620 		if (PSM_FINGER_IS_SET(f[id]))
4621 			sc->elanaction.fingers[id] = f[id];
4622 		if ((sc->elanaction.mask & (1 << id)) && !(mask & (1 << id)))
4623 			PSM_FINGER_RESET(sc->elanaction.fingers[id]);
4624 	}
4625 	sc->elanaction.mask = mask;
4626 
4627 	/* Palm detection doesn't terminate the current action. */
4628 	if (psmpalmdetect(sc, &f[0], nfingers)) {
4629 		*x = *y = *z = 0;
4630 		ms->button = ms->obutton;
4631 		return (0);
4632 	}
4633 
4634 	/* Use the extra buttons as a scrollwheel */
4635 	if (ms->button & MOUSE_BUTTON4DOWN)
4636 		*z = -1;
4637 	else if (ms->button & MOUSE_BUTTON5DOWN)
4638 		*z = 1;
4639 	else if (ms->button & MOUSE_BUTTON6DOWN)
4640 		*z = -2;
4641 	else if (ms->button & MOUSE_BUTTON7DOWN)
4642 		*z = 2;
4643 	else
4644 		*z = 0;
4645 	ms->button &= ~(MOUSE_BUTTON4DOWN | MOUSE_BUTTON5DOWN |
4646 	    MOUSE_BUTTON6DOWN | MOUSE_BUTTON7DOWN);
4647 
4648 	return (0);
4649 }
4650 
4651 static void
4652 proc_versapad(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
4653     int *x, int *y, int *z)
4654 {
4655 	static int butmap_versapad[8] = {
4656 		0,
4657 		MOUSE_BUTTON3DOWN,
4658 		0,
4659 		MOUSE_BUTTON3DOWN,
4660 		MOUSE_BUTTON1DOWN,
4661 		MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
4662 		MOUSE_BUTTON1DOWN,
4663 		MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
4664 	};
4665 	int c, x0, y0;
4666 
4667 	/* VersaPad PS/2 absolute mode message format
4668 	 *
4669 	 * [packet1]     7   6   5   4   3   2   1   0(LSB)
4670 	 *  ipacket[0]:  1   1   0   A   1   L   T   R
4671 	 *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
4672 	 *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
4673 	 *  ipacket[3]:  1   1   1   A   1   L   T   R
4674 	 *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
4675 	 *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
4676 	 *
4677 	 * [note]
4678 	 *  R: right physical mouse button (1=on)
4679 	 *  T: touch pad virtual button (1=tapping)
4680 	 *  L: left physical mouse button (1=on)
4681 	 *  A: position data is valid (1=valid)
4682 	 *  H: horizontal data (12bit signed integer. H11 is sign bit.)
4683 	 *  V: vertical data (12bit signed integer. V11 is sign bit.)
4684 	 *  P: pressure data
4685 	 *
4686 	 * Tapping is mapped to MOUSE_BUTTON4.
4687 	 */
4688 	c = pb->ipacket[0];
4689 	*x = *y = 0;
4690 	ms->button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
4691 	ms->button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
4692 	if (c & MOUSE_PS2VERSA_IN_USE) {
4693 		x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
4694 		y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
4695 		if (x0 & 0x800)
4696 			x0 -= 0x1000;
4697 		if (y0 & 0x800)
4698 			y0 -= 0x1000;
4699 		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
4700 			*x = sc->xold - x0;
4701 			*y = y0 - sc->yold;
4702 			if (*x < 0)	/* XXX */
4703 				++*x;
4704 			else if (*x)
4705 				--*x;
4706 			if (*y < 0)
4707 				++*y;
4708 			else if (*y)
4709 				--*y;
4710 		} else
4711 			sc->flags |= PSM_FLAGS_FINGERDOWN;
4712 		sc->xold = x0;
4713 		sc->yold = y0;
4714 	} else
4715 		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
4716 }
4717 
4718 static void
4719 psmsoftintridle(void *arg)
4720 {
4721 	struct psm_softc *sc = arg;
4722 	packetbuf_t *pb;
4723 
4724 	/* Invoke soft handler only when pqueue is empty. Otherwise it will be
4725 	 * invoked from psmintr soon with pqueue filled with real data */
4726 	if (sc->pqueue_start == sc->pqueue_end &&
4727 	    sc->idlepacket.inputbytes > 0) {
4728 		/* Grow circular queue backwards to avoid race with psmintr */
4729 		if (--sc->pqueue_start < 0)
4730 			sc->pqueue_start = PSM_PACKETQUEUE - 1;
4731 
4732 		pb = &sc->pqueue[sc->pqueue_start];
4733 		memcpy(pb, &sc->idlepacket, sizeof(packetbuf_t));
4734 		VLOG(4, (LOG_DEBUG,
4735 		    "psmsoftintridle: %02x %02x %02x %02x %02x %02x\n",
4736 		    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
4737 		    pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
4738 
4739 		psmsoftintr(arg);
4740 	}
4741 }
4742 
4743 static void
4744 psmsoftintr(void *arg)
4745 {
4746 	/*
4747 	 * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
4748 	 * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
4749 	 */
4750 	static int butmap[8] = {
4751 		0,
4752 		MOUSE_BUTTON1DOWN,
4753 		MOUSE_BUTTON3DOWN,
4754 		MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
4755 		MOUSE_BUTTON2DOWN,
4756 		MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
4757 		MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
4758 		MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
4759 	};
4760 	struct psm_softc *sc = arg;
4761 	mousestatus_t ms;
4762 	packetbuf_t *pb;
4763 	int x, y, z, c, l, s;
4764 
4765 	getmicrouptime(&sc->lastsoftintr);
4766 
4767 	s = spltty();
4768 
4769 	do {
4770 		pb = &sc->pqueue[sc->pqueue_start];
4771 
4772 		if (sc->mode.level == PSM_LEVEL_NATIVE)
4773 			goto next_native;
4774 
4775 		c = pb->ipacket[0];
4776 		/*
4777 		 * A kludge for Kensington device!
4778 		 * The MSB of the horizontal count appears to be stored in
4779 		 * a strange place.
4780 		 */
4781 		if (sc->hw.model == MOUSE_MODEL_THINK)
4782 			pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
4783 
4784 		/* ignore the overflow bits... */
4785 		x = (c & MOUSE_PS2_XNEG) ?
4786 		    pb->ipacket[1] - 256 : pb->ipacket[1];
4787 		y = (c & MOUSE_PS2_YNEG) ?
4788 		    pb->ipacket[2] - 256 : pb->ipacket[2];
4789 		z = 0;
4790 		ms.obutton = sc->button;	  /* previous button state */
4791 		ms.button = butmap[c & MOUSE_PS2_BUTTONS];
4792 		/* `tapping' action */
4793 		if (sc->config & PSM_CONFIG_FORCETAP)
4794 			ms.button |= ((c & MOUSE_PS2_TAP)) ?
4795 			    0 : MOUSE_BUTTON4DOWN;
4796 		timevalclear(&sc->idletimeout);
4797 		sc->idlepacket.inputbytes = 0;
4798 
4799 		switch (sc->hw.model) {
4800 
4801 		case MOUSE_MODEL_EXPLORER:
4802 			/*
4803 			 *          b7 b6 b5 b4 b3 b2 b1 b0
4804 			 * byte 1:  oy ox sy sx 1  M  R  L
4805 			 * byte 2:  x  x  x  x  x  x  x  x
4806 			 * byte 3:  y  y  y  y  y  y  y  y
4807 			 * byte 4:  *  *  S2 S1 s  d2 d1 d0
4808 			 *
4809 			 * L, M, R, S1, S2: left, middle, right and side buttons
4810 			 * s: wheel data sign bit
4811 			 * d2-d0: wheel data
4812 			 */
4813 			z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG) ?
4814 			    (pb->ipacket[3] & 0x0f) - 16 :
4815 			    (pb->ipacket[3] & 0x0f);
4816 			ms.button |=
4817 			    (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN) ?
4818 			    MOUSE_BUTTON4DOWN : 0;
4819 			ms.button |=
4820 			    (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN) ?
4821 			    MOUSE_BUTTON5DOWN : 0;
4822 			break;
4823 
4824 		case MOUSE_MODEL_INTELLI:
4825 		case MOUSE_MODEL_NET:
4826 			/* wheel data is in the fourth byte */
4827 			z = (char)pb->ipacket[3];
4828 			/*
4829 			 * XXX some mice may send 7 when there is no Z movement?			 */
4830 			if ((z >= 7) || (z <= -7))
4831 				z = 0;
4832 			/* some compatible mice have additional buttons */
4833 			ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN) ?
4834 			    MOUSE_BUTTON4DOWN : 0;
4835 			ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN) ?
4836 			    MOUSE_BUTTON5DOWN : 0;
4837 			break;
4838 
4839 		case MOUSE_MODEL_MOUSEMANPLUS:
4840 			proc_mmanplus(sc, pb, &ms, &x, &y, &z);
4841 			break;
4842 
4843 		case MOUSE_MODEL_GLIDEPOINT:
4844 			/* `tapping' action */
4845 			ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 :
4846 			    MOUSE_BUTTON4DOWN;
4847 			break;
4848 
4849 		case MOUSE_MODEL_NETSCROLL:
4850 			/*
4851 			 * three additional bytes encode buttons and
4852 			 * wheel events
4853 			 */
4854 			ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN) ?
4855 			    MOUSE_BUTTON4DOWN : 0;
4856 			ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN) ?
4857 			    MOUSE_BUTTON5DOWN : 0;
4858 			z = (pb->ipacket[3] & MOUSE_PS2_XNEG) ?
4859 			    pb->ipacket[4] - 256 : pb->ipacket[4];
4860 			break;
4861 
4862 		case MOUSE_MODEL_THINK:
4863 			/* the fourth button state in the first byte */
4864 			ms.button |= (c & MOUSE_PS2_TAP) ?
4865 			    MOUSE_BUTTON4DOWN : 0;
4866 			break;
4867 
4868 		case MOUSE_MODEL_VERSAPAD:
4869 			proc_versapad(sc, pb, &ms, &x, &y, &z);
4870 			c = ((x < 0) ? MOUSE_PS2_XNEG : 0) |
4871 			    ((y < 0) ? MOUSE_PS2_YNEG : 0);
4872 			break;
4873 
4874 		case MOUSE_MODEL_4D:
4875 			/*
4876 			 *          b7 b6 b5 b4 b3 b2 b1 b0
4877 			 * byte 1:  s2 d2 s1 d1 1  M  R  L
4878 			 * byte 2:  sx x  x  x  x  x  x  x
4879 			 * byte 3:  sy y  y  y  y  y  y  y
4880 			 *
4881 			 * s1: wheel 1 direction
4882 			 * d1: wheel 1 data
4883 			 * s2: wheel 2 direction
4884 			 * d2: wheel 2 data
4885 			 */
4886 			x = (pb->ipacket[1] & 0x80) ?
4887 			    pb->ipacket[1] - 256 : pb->ipacket[1];
4888 			y = (pb->ipacket[2] & 0x80) ?
4889 			    pb->ipacket[2] - 256 : pb->ipacket[2];
4890 			switch (c & MOUSE_4D_WHEELBITS) {
4891 			case 0x10:
4892 				z = 1;
4893 				break;
4894 			case 0x30:
4895 				z = -1;
4896 				break;
4897 			case 0x40:	/* XXX 2nd wheel turning right */
4898 				z = 2;
4899 				break;
4900 			case 0xc0:	/* XXX 2nd wheel turning left */
4901 				z = -2;
4902 				break;
4903 			}
4904 			break;
4905 
4906 		case MOUSE_MODEL_4DPLUS:
4907 			if ((x < 16 - 256) && (y < 16 - 256)) {
4908 				/*
4909 				 *          b7 b6 b5 b4 b3 b2 b1 b0
4910 				 * byte 1:  0  0  1  1  1  M  R  L
4911 				 * byte 2:  0  0  0  0  1  0  0  0
4912 				 * byte 3:  0  0  0  0  S  s  d1 d0
4913 				 *
4914 				 * L, M, R, S: left, middle, right,
4915 				 *             and side buttons
4916 				 * s: wheel data sign bit
4917 				 * d1-d0: wheel data
4918 				 */
4919 				x = y = 0;
4920 				if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
4921 					ms.button |= MOUSE_BUTTON4DOWN;
4922 				z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG) ?
4923 				    ((pb->ipacket[2] & 0x07) - 8) :
4924 				    (pb->ipacket[2] & 0x07) ;
4925 			} else {
4926 				/* preserve previous button states */
4927 				ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
4928 			}
4929 			break;
4930 
4931 		case MOUSE_MODEL_SYNAPTICS:
4932 			if (proc_synaptics(sc, pb, &ms, &x, &y, &z) != 0) {
4933 				VLOG(3, (LOG_DEBUG, "synaptics: "
4934 				    "packet rejected\n"));
4935 				goto next;
4936 			}
4937 			break;
4938 
4939 		case MOUSE_MODEL_ELANTECH:
4940 			if (proc_elantech(sc, pb, &ms, &x, &y, &z) != 0) {
4941 				VLOG(3, (LOG_DEBUG, "elantech: "
4942 				    "packet rejected\n"));
4943 				goto next;
4944 			}
4945 			break;
4946 
4947 		case MOUSE_MODEL_TRACKPOINT:
4948 		case MOUSE_MODEL_GENERIC:
4949 		default:
4950 			break;
4951 		}
4952 
4953 #ifdef EVDEV_SUPPORT
4954 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE &&
4955 	    sc->hw.model != MOUSE_MODEL_ELANTECH &&
4956 	    sc->hw.model != MOUSE_MODEL_SYNAPTICS) {
4957 		evdev_push_rel(sc->evdev_r, REL_X, x);
4958 		evdev_push_rel(sc->evdev_r, REL_Y, -y);
4959 
4960 		switch (sc->hw.model) {
4961 		case MOUSE_MODEL_EXPLORER:
4962 		case MOUSE_MODEL_INTELLI:
4963 		case MOUSE_MODEL_NET:
4964 		case MOUSE_MODEL_NETSCROLL:
4965 		case MOUSE_MODEL_4DPLUS:
4966 			evdev_push_rel(sc->evdev_r, REL_WHEEL, -z);
4967 			break;
4968 		case MOUSE_MODEL_MOUSEMANPLUS:
4969 		case MOUSE_MODEL_4D:
4970 			switch (z) {
4971 			case 1:
4972 			case -1:
4973 				evdev_push_rel(sc->evdev_r, REL_WHEEL, -z);
4974 				break;
4975 			case 2:
4976 			case -2:
4977 				evdev_push_rel(sc->evdev_r, REL_HWHEEL, z / 2);
4978 				break;
4979 			}
4980 			break;
4981 		}
4982 
4983 		evdev_push_mouse_btn(sc->evdev_r, ms.button);
4984 		evdev_sync(sc->evdev_r);
4985 	}
4986 #endif
4987 
4988 	/* scale values */
4989 	if (sc->mode.accelfactor >= 1) {
4990 		if (x != 0) {
4991 			x = x * x / sc->mode.accelfactor;
4992 			if (x == 0)
4993 				x = 1;
4994 			if (c & MOUSE_PS2_XNEG)
4995 				x = -x;
4996 		}
4997 		if (y != 0) {
4998 			y = y * y / sc->mode.accelfactor;
4999 			if (y == 0)
5000 				y = 1;
5001 			if (c & MOUSE_PS2_YNEG)
5002 				y = -y;
5003 		}
5004 	}
5005 
5006 	/* Store last packet for reinjection if it has not been set already */
5007 	if (timevalisset(&sc->idletimeout) && sc->idlepacket.inputbytes == 0)
5008 		sc->idlepacket = *pb;
5009 
5010 	ms.dx = x;
5011 	ms.dy = y;
5012 	ms.dz = z;
5013 	ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0) |
5014 	    (ms.obutton ^ ms.button);
5015 
5016 	pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);
5017 
5018 	sc->status.flags |= ms.flags;
5019 	sc->status.dx += ms.dx;
5020 	sc->status.dy += ms.dy;
5021 	sc->status.dz += ms.dz;
5022 	sc->status.button = ms.button;
5023 	sc->button = ms.button;
5024 
5025 next_native:
5026 	sc->watchdog = FALSE;
5027 
5028 	/* queue data */
5029 	if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
5030 		l = imin(pb->inputbytes,
5031 		    sizeof(sc->queue.buf) - sc->queue.tail);
5032 		bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
5033 		if (pb->inputbytes > l)
5034 			bcopy(&pb->ipacket[l], &sc->queue.buf[0],
5035 			    pb->inputbytes - l);
5036 		sc->queue.tail = (sc->queue.tail + pb->inputbytes) %
5037 		    sizeof(sc->queue.buf);
5038 		sc->queue.count += pb->inputbytes;
5039 	}
5040 
5041 next:
5042 	pb->inputbytes = 0;
5043 	if (++sc->pqueue_start >= PSM_PACKETQUEUE)
5044 		sc->pqueue_start = 0;
5045 	} while (sc->pqueue_start != sc->pqueue_end);
5046 
5047 	if (sc->state & PSM_ASLP) {
5048 		sc->state &= ~PSM_ASLP;
5049 		wakeup(sc);
5050 	}
5051 	selwakeuppri(&sc->rsel, PZERO);
5052 	if (sc->async != NULL) {
5053 		pgsigio(&sc->async, SIGIO, 0);
5054 	}
5055 	sc->state &= ~PSM_SOFTARMED;
5056 
5057 	/* schedule injection of predefined packet after idletimeout
5058 	 * if no data packets have been received from psmintr */
5059 	if (timevalisset(&sc->idletimeout)) {
5060 		sc->state |= PSM_SOFTARMED;
5061 		callout_reset(&sc->softcallout, tvtohz(&sc->idletimeout),
5062 		    psmsoftintridle, sc);
5063 		VLOG(2, (LOG_DEBUG, "softintr: callout set: %d ticks\n",
5064 		    tvtohz(&sc->idletimeout)));
5065 	}
5066 	splx(s);
5067 }
5068 
5069 static int
5070 psmpoll(struct cdev *dev, int events, struct thread *td)
5071 {
5072 	struct psm_softc *sc = dev->si_drv1;
5073 	int s;
5074 	int revents = 0;
5075 
5076 	/* Return true if a mouse event available */
5077 	s = spltty();
5078 	if (events & (POLLIN | POLLRDNORM)) {
5079 		if (sc->queue.count > 0)
5080 			revents |= events & (POLLIN | POLLRDNORM);
5081 		else
5082 			selrecord(td, &sc->rsel);
5083 	}
5084 	splx(s);
5085 
5086 	return (revents);
5087 }
5088 
5089 /* vendor/model specific routines */
5090 
5091 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
5092 {
5093 	if (set_mouse_resolution(kbdc, res) != res)
5094 		return (FALSE);
5095 	if (set_mouse_scaling(kbdc, scale) &&
5096 	    set_mouse_scaling(kbdc, scale) &&
5097 	    set_mouse_scaling(kbdc, scale) &&
5098 	    (get_mouse_status(kbdc, status, 0, 3) >= 3))
5099 		return (TRUE);
5100 	return (FALSE);
5101 }
5102 
5103 static int
5104 mouse_ext_command(KBDC kbdc, int command)
5105 {
5106 	int c;
5107 
5108 	c = (command >> 6) & 0x03;
5109 	if (set_mouse_resolution(kbdc, c) != c)
5110 		return (FALSE);
5111 	c = (command >> 4) & 0x03;
5112 	if (set_mouse_resolution(kbdc, c) != c)
5113 		return (FALSE);
5114 	c = (command >> 2) & 0x03;
5115 	if (set_mouse_resolution(kbdc, c) != c)
5116 		return (FALSE);
5117 	c = (command >> 0) & 0x03;
5118 	if (set_mouse_resolution(kbdc, c) != c)
5119 		return (FALSE);
5120 	return (TRUE);
5121 }
5122 
5123 #ifdef notyet
5124 /* Logitech MouseMan Cordless II */
5125 static int
5126 enable_lcordless(struct psm_softc *sc, enum probearg arg)
5127 {
5128 	KBDC kbdc = sc->kbdc;
5129 	int status[3];
5130 	int ch;
5131 
5132 	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 2, status))
5133 		return (FALSE);
5134 	if (status[1] == PSMD_RES_HIGH)
5135 		return (FALSE);
5136 	ch = (status[0] & 0x07) - 1;	/* channel # */
5137 	if ((ch <= 0) || (ch > 4))
5138 		return (FALSE);
5139 	/*
5140 	 * status[1]: always one?
5141 	 * status[2]: battery status? (0-100)
5142 	 */
5143 	return (TRUE);
5144 }
5145 #endif /* notyet */
5146 
5147 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
5148 static int
5149 enable_groller(struct psm_softc *sc, enum probearg arg)
5150 {
5151 	KBDC kbdc = sc->kbdc;
5152 	int status[3];
5153 
5154 	/*
5155 	 * The special sequence to enable the fourth button and the
5156 	 * roller. Immediately after this sequence check status bytes.
5157 	 * if the mouse is NetScroll, the second and the third bytes are
5158 	 * '3' and 'D'.
5159 	 */
5160 
5161 	/*
5162 	 * If the mouse is an ordinary PS/2 mouse, the status bytes should
5163 	 * look like the following.
5164 	 *
5165 	 * byte 1 bit 7 always 0
5166 	 *        bit 6 stream mode (0)
5167 	 *        bit 5 disabled (0)
5168 	 *        bit 4 1:1 scaling (0)
5169 	 *        bit 3 always 0
5170 	 *        bit 0-2 button status
5171 	 * byte 2 resolution (PSMD_RES_HIGH)
5172 	 * byte 3 report rate (?)
5173 	 */
5174 
5175 	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
5176 		return (FALSE);
5177 	if ((status[1] != '3') || (status[2] != 'D'))
5178 		return (FALSE);
5179 	/* FIXME: SmartScroll Mouse has 5 buttons! XXX */
5180 	if (arg == PROBE)
5181 		sc->hw.buttons = 4;
5182 	return (TRUE);
5183 }
5184 
5185 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
5186 static int
5187 enable_gmouse(struct psm_softc *sc, enum probearg arg)
5188 {
5189 	KBDC kbdc = sc->kbdc;
5190 	int status[3];
5191 
5192 	/*
5193 	 * The special sequence to enable the middle, "rubber" button.
5194 	 * Immediately after this sequence check status bytes.
5195 	 * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
5196 	 * the second and the third bytes are '3' and 'U'.
5197 	 * NOTE: NetMouse reports that it has three buttons although it has
5198 	 * two buttons and a rubber button. NetMouse Pro and MIE Mouse
5199 	 * say they have three buttons too and they do have a button on the
5200 	 * side...
5201 	 */
5202 	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
5203 		return (FALSE);
5204 	if ((status[1] != '3') || (status[2] != 'U'))
5205 		return (FALSE);
5206 	return (TRUE);
5207 }
5208 
5209 /* ALPS GlidePoint */
5210 static int
5211 enable_aglide(struct psm_softc *sc, enum probearg arg)
5212 {
5213 	KBDC kbdc = sc->kbdc;
5214 	int status[3];
5215 
5216 	/*
5217 	 * The special sequence to obtain ALPS GlidePoint specific
5218 	 * information. Immediately after this sequence, status bytes will
5219 	 * contain something interesting.
5220 	 * NOTE: ALPS produces several models of GlidePoint. Some of those
5221 	 * do not respond to this sequence, thus, cannot be detected this way.
5222 	 */
5223 	if (set_mouse_sampling_rate(kbdc, 100) != 100)
5224 		return (FALSE);
5225 	if (!mouse_id_proc1(kbdc, PSMD_RES_LOW, 2, status))
5226 		return (FALSE);
5227 	if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
5228 		return (FALSE);
5229 	return (TRUE);
5230 }
5231 
5232 /* Kensington ThinkingMouse/Trackball */
5233 static int
5234 enable_kmouse(struct psm_softc *sc, enum probearg arg)
5235 {
5236 	static u_char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
5237 	KBDC kbdc = sc->kbdc;
5238 	int status[3];
5239 	int id1;
5240 	int id2;
5241 	int i;
5242 
5243 	id1 = get_aux_id(kbdc);
5244 	if (set_mouse_sampling_rate(kbdc, 10) != 10)
5245 		return (FALSE);
5246 	/*
5247 	 * The device is now in the native mode? It returns a different
5248 	 * ID value...
5249 	 */
5250 	id2 = get_aux_id(kbdc);
5251 	if ((id1 == id2) || (id2 != 2))
5252 		return (FALSE);
5253 
5254 	if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
5255 		return (FALSE);
5256 #if PSM_DEBUG >= 2
5257 	/* at this point, resolution is LOW, sampling rate is 10/sec */
5258 	if (get_mouse_status(kbdc, status, 0, 3) < 3)
5259 		return (FALSE);
5260 #endif
5261 
5262 	/*
5263 	 * The special sequence to enable the third and fourth buttons.
5264 	 * Otherwise they behave like the first and second buttons.
5265 	 */
5266 	for (i = 0; i < nitems(rate); ++i)
5267 		if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
5268 			return (FALSE);
5269 
5270 	/*
5271 	 * At this point, the device is using default resolution and
5272 	 * sampling rate for the native mode.
5273 	 */
5274 	if (get_mouse_status(kbdc, status, 0, 3) < 3)
5275 		return (FALSE);
5276 	if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
5277 		return (FALSE);
5278 
5279 	/* the device appears be enabled by this sequence, diable it for now */
5280 	disable_aux_dev(kbdc);
5281 	empty_aux_buffer(kbdc, 5);
5282 
5283 	return (TRUE);
5284 }
5285 
5286 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
5287 static int
5288 enable_mmanplus(struct psm_softc *sc, enum probearg arg)
5289 {
5290 	KBDC kbdc = sc->kbdc;
5291 	int data[3];
5292 
5293 	/* the special sequence to enable the fourth button and the roller. */
5294 	/*
5295 	 * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
5296 	 * must be called exactly three times since the last RESET command
5297 	 * before this sequence. XXX
5298 	 */
5299 	if (!set_mouse_scaling(kbdc, 1))
5300 		return (FALSE);
5301 	if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
5302 		return (FALSE);
5303 	if (get_mouse_status(kbdc, data, 1, 3) < 3)
5304 		return (FALSE);
5305 
5306 	/*
5307 	 * PS2++ protocol, packet type 0
5308 	 *
5309 	 *          b7 b6 b5 b4 b3 b2 b1 b0
5310 	 * byte 1:  *  1  p3 p2 1  *  *  *
5311 	 * byte 2:  1  1  p1 p0 m1 m0 1  0
5312 	 * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
5313 	 *
5314 	 * p3-p0: packet type: 0
5315 	 * m7-m0: model ID: MouseMan+:0x50,
5316 	 *		    FirstMouse+:0x51,
5317 	 *		    ScrollPoint:0x58...
5318 	 */
5319 	/* check constant bits */
5320 	if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
5321 		return (FALSE);
5322 	if ((data[1] & 0xc3) != 0xc2)
5323 		return (FALSE);
5324 	/* check d3-d0 in byte 2 */
5325 	if (!MOUSE_PS2PLUS_CHECKBITS(data))
5326 		return (FALSE);
5327 	/* check p3-p0 */
5328 	if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
5329 		return (FALSE);
5330 
5331 	if (arg == PROBE) {
5332 		sc->hw.hwid &= 0x00ff;
5333 		sc->hw.hwid |= data[2] << 8;	/* save model ID */
5334 	}
5335 
5336 	/*
5337 	 * MouseMan+ (or FirstMouse+) is now in its native mode, in which
5338 	 * the wheel and the fourth button events are encoded in the
5339 	 * special data packet. The mouse may be put in the IntelliMouse mode
5340 	 * if it is initialized by the IntelliMouse's method.
5341 	 */
5342 	return (TRUE);
5343 }
5344 
5345 /* MS IntelliMouse Explorer */
5346 static int
5347 enable_msexplorer(struct psm_softc *sc, enum probearg arg)
5348 {
5349 	KBDC kbdc = sc->kbdc;
5350 	static u_char rate0[] = { 200, 100, 80, };
5351 	static u_char rate1[] = { 200, 200, 80, };
5352 	int id;
5353 	int i;
5354 
5355 	/*
5356 	 * This is needed for at least A4Tech X-7xx mice - they do not go
5357 	 * straight to Explorer mode, but need to be set to Intelli mode
5358 	 * first.
5359 	 */
5360 	enable_msintelli(sc, arg);
5361 
5362 	/* the special sequence to enable the extra buttons and the roller. */
5363 	for (i = 0; i < nitems(rate1); ++i)
5364 		if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
5365 			return (FALSE);
5366 	/* the device will give the genuine ID only after the above sequence */
5367 	id = get_aux_id(kbdc);
5368 	if (id != PSM_EXPLORER_ID)
5369 		return (FALSE);
5370 
5371 	if (arg == PROBE) {
5372 		sc->hw.buttons = 5;	/* IntelliMouse Explorer XXX */
5373 		sc->hw.hwid = id;
5374 	}
5375 
5376 	/*
5377 	 * XXX: this is a kludge to fool some KVM switch products
5378 	 * which think they are clever enough to know the 4-byte IntelliMouse
5379 	 * protocol, and assume any other protocols use 3-byte packets.
5380 	 * They don't convey 4-byte data packets from the IntelliMouse Explorer
5381 	 * correctly to the host computer because of this!
5382 	 * The following sequence is actually IntelliMouse's "wake up"
5383 	 * sequence; it will make the KVM think the mouse is IntelliMouse
5384 	 * when it is in fact IntelliMouse Explorer.
5385 	 */
5386 	for (i = 0; i < nitems(rate0); ++i)
5387 		if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
5388 			break;
5389 	get_aux_id(kbdc);
5390 
5391 	return (TRUE);
5392 }
5393 
5394 /*
5395  * MS IntelliMouse
5396  * Logitech MouseMan+ and FirstMouse+ will also respond to this
5397  * probe routine and act like IntelliMouse.
5398  */
5399 static int
5400 enable_msintelli(struct psm_softc *sc, enum probearg arg)
5401 {
5402 	KBDC kbdc = sc->kbdc;
5403 	static u_char rate[] = { 200, 100, 80, };
5404 	int id;
5405 	int i;
5406 
5407 	/* the special sequence to enable the third button and the roller. */
5408 	for (i = 0; i < nitems(rate); ++i)
5409 		if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
5410 			return (FALSE);
5411 	/* the device will give the genuine ID only after the above sequence */
5412 	id = get_aux_id(kbdc);
5413 	if (id != PSM_INTELLI_ID)
5414 		return (FALSE);
5415 
5416 	if (arg == PROBE) {
5417 		sc->hw.buttons = 3;
5418 		sc->hw.hwid = id;
5419 	}
5420 
5421 	return (TRUE);
5422 }
5423 
5424 /*
5425  * A4 Tech 4D Mouse
5426  * Newer wheel mice from A4 Tech may use the 4D+ protocol.
5427  */
5428 static int
5429 enable_4dmouse(struct psm_softc *sc, enum probearg arg)
5430 {
5431 	static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
5432 	KBDC kbdc = sc->kbdc;
5433 	int id;
5434 	int i;
5435 
5436 	for (i = 0; i < nitems(rate); ++i)
5437 		if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
5438 			return (FALSE);
5439 	id = get_aux_id(kbdc);
5440 	/*
5441 	 * WinEasy 4D, 4 Way Scroll 4D: 6
5442 	 * Cable-Free 4D: 8 (4DPLUS)
5443 	 * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
5444 	 */
5445 	if (id != PSM_4DMOUSE_ID)
5446 		return (FALSE);
5447 
5448 	if (arg == PROBE) {
5449 		sc->hw.buttons = 3;	/* XXX some 4D mice have 4? */
5450 		sc->hw.hwid = id;
5451 	}
5452 
5453 	return (TRUE);
5454 }
5455 
5456 /*
5457  * A4 Tech 4D+ Mouse
5458  * Newer wheel mice from A4 Tech seem to use this protocol.
5459  * Older models are recognized as either 4D Mouse or IntelliMouse.
5460  */
5461 static int
5462 enable_4dplus(struct psm_softc *sc, enum probearg arg)
5463 {
5464 	KBDC kbdc = sc->kbdc;
5465 	int id;
5466 
5467 	/*
5468 	 * enable_4dmouse() already issued the following ID sequence...
5469 	static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
5470 	int i;
5471 
5472 	for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
5473 		if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
5474 			return (FALSE);
5475 	*/
5476 
5477 	id = get_aux_id(kbdc);
5478 	switch (id) {
5479 	case PSM_4DPLUS_ID:
5480 		break;
5481 	case PSM_4DPLUS_RFSW35_ID:
5482 		break;
5483 	default:
5484 		return (FALSE);
5485 	}
5486 
5487 	if (arg == PROBE) {
5488 		sc->hw.buttons = (id == PSM_4DPLUS_ID) ? 4 : 3;
5489 		sc->hw.hwid = id;
5490 	}
5491 
5492 	return (TRUE);
5493 }
5494 
5495 /* Synaptics Touchpad */
5496 static int
5497 synaptics_sysctl(SYSCTL_HANDLER_ARGS)
5498 {
5499 	struct psm_softc *sc;
5500 	int error, arg;
5501 
5502 	if (oidp->oid_arg1 == NULL || oidp->oid_arg2 < 0 ||
5503 	    oidp->oid_arg2 > SYNAPTICS_SYSCTL_SOFTBUTTON3_X)
5504 		return (EINVAL);
5505 
5506 	sc = oidp->oid_arg1;
5507 
5508 	/* Read the current value. */
5509 	arg = *(int *)((char *)sc + oidp->oid_arg2);
5510 	error = sysctl_handle_int(oidp, &arg, 0, req);
5511 
5512 	/* Sanity check. */
5513 	if (error || !req->newptr)
5514 		return (error);
5515 
5516 	/*
5517 	 * Check that the new value is in the concerned node's range
5518 	 * of values.
5519 	 */
5520 	switch (oidp->oid_arg2) {
5521 	case SYNAPTICS_SYSCTL_MIN_PRESSURE:
5522 	case SYNAPTICS_SYSCTL_MAX_PRESSURE:
5523 		if (arg < 0 || arg > 255)
5524 			return (EINVAL);
5525 		break;
5526 	case SYNAPTICS_SYSCTL_MAX_WIDTH:
5527 		if (arg < 4 || arg > 15)
5528 			return (EINVAL);
5529 		break;
5530 	case SYNAPTICS_SYSCTL_MARGIN_TOP:
5531 	case SYNAPTICS_SYSCTL_MARGIN_BOTTOM:
5532 	case SYNAPTICS_SYSCTL_NA_TOP:
5533 	case SYNAPTICS_SYSCTL_NA_BOTTOM:
5534 		if (arg < 0 || arg > sc->synhw.maximumYCoord)
5535 			return (EINVAL);
5536 		break;
5537 	case SYNAPTICS_SYSCTL_SOFTBUTTON2_X:
5538 	case SYNAPTICS_SYSCTL_SOFTBUTTON3_X:
5539 		/* Softbuttons is clickpad only feature */
5540 		if (!sc->synhw.capClickPad && arg != 0)
5541 			return (EINVAL);
5542 		/* FALLTHROUGH */
5543 	case SYNAPTICS_SYSCTL_MARGIN_RIGHT:
5544 	case SYNAPTICS_SYSCTL_MARGIN_LEFT:
5545 	case SYNAPTICS_SYSCTL_NA_RIGHT:
5546 	case SYNAPTICS_SYSCTL_NA_LEFT:
5547 		if (arg < 0 || arg > sc->synhw.maximumXCoord)
5548 			return (EINVAL);
5549 		break;
5550 	case SYNAPTICS_SYSCTL_WINDOW_MIN:
5551 	case SYNAPTICS_SYSCTL_WINDOW_MAX:
5552 	case SYNAPTICS_SYSCTL_TAP_MIN_QUEUE:
5553 		if (arg < 1 || arg > SYNAPTICS_PACKETQUEUE)
5554 			return (EINVAL);
5555 		break;
5556 	case SYNAPTICS_SYSCTL_MULTIPLICATOR:
5557 	case SYNAPTICS_SYSCTL_WEIGHT_CURRENT:
5558 	case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS:
5559 	case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA:
5560 	case SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED:
5561 	case SYNAPTICS_SYSCTL_DIV_MIN:
5562 	case SYNAPTICS_SYSCTL_DIV_MAX:
5563 	case SYNAPTICS_SYSCTL_DIV_MAX_NA:
5564 	case SYNAPTICS_SYSCTL_DIV_LEN:
5565 	case SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN:
5566 	case SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX:
5567 		if (arg < 1)
5568 			return (EINVAL);
5569 		break;
5570 	case SYNAPTICS_SYSCTL_TAP_MAX_DELTA:
5571 	case SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT:
5572 	case SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA:
5573 		if (arg < 0)
5574 			return (EINVAL);
5575 		break;
5576 	case SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA:
5577 		if (arg < -sc->synhw.maximumXCoord ||
5578 		    arg > sc->synhw.maximumXCoord)
5579 			return (EINVAL);
5580 		break;
5581 	case SYNAPTICS_SYSCTL_SOFTBUTTONS_Y:
5582 		/* Softbuttons is clickpad only feature */
5583 		if (!sc->synhw.capClickPad && arg != 0)
5584 			return (EINVAL);
5585 		/* FALLTHROUGH */
5586 	case SYNAPTICS_SYSCTL_VSCROLL_VER_AREA:
5587 		if (arg < -sc->synhw.maximumYCoord ||
5588 		    arg > sc->synhw.maximumYCoord)
5589 			return (EINVAL);
5590 		break;
5591         case SYNAPTICS_SYSCTL_TOUCHPAD_OFF:
5592 		if (arg < 0 || arg > 1)
5593 			return (EINVAL);
5594 		break;
5595 	default:
5596 		return (EINVAL);
5597 	}
5598 
5599 	/* Update. */
5600 	*(int *)((char *)sc + oidp->oid_arg2) = arg;
5601 
5602 	return (error);
5603 }
5604 
5605 static void
5606 synaptics_sysctl_create_softbuttons_tree(struct psm_softc *sc)
5607 {
5608 	/*
5609 	 * Set predefined sizes for softbuttons.
5610 	 * Values are taken to match HP Pavilion dv6 clickpad drawings
5611 	 * with thin middle softbutton placed on separator
5612 	 */
5613 
5614 	/* hw.psm.synaptics.softbuttons_y */
5615 	sc->syninfo.softbuttons_y = 1700;
5616 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5617 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5618 	    "softbuttons_y", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5619 	    sc, SYNAPTICS_SYSCTL_SOFTBUTTONS_Y,
5620 	    synaptics_sysctl, "I",
5621 	    "Vertical size of softbuttons area");
5622 
5623 	/* hw.psm.synaptics.softbutton2_x */
5624 	sc->syninfo.softbutton2_x = 3100;
5625 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5626 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5627 	    "softbutton2_x", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5628 	    sc, SYNAPTICS_SYSCTL_SOFTBUTTON2_X,
5629 	    synaptics_sysctl, "I",
5630 	    "Horisontal position of 2-nd softbutton left edge (0-disable)");
5631 
5632 	/* hw.psm.synaptics.softbutton3_x */
5633 	sc->syninfo.softbutton3_x = 3900;
5634 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5635 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5636 	    "softbutton3_x", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5637 	    sc, SYNAPTICS_SYSCTL_SOFTBUTTON3_X,
5638 	    synaptics_sysctl, "I",
5639 	    "Horisontal position of 3-rd softbutton left edge (0-disable)");
5640 }
5641 
5642 static void
5643 synaptics_sysctl_create_tree(struct psm_softc *sc, const char *name,
5644     const char *descr)
5645 {
5646 
5647 	if (sc->syninfo.sysctl_tree != NULL)
5648 		return;
5649 
5650 	/* Attach extra synaptics sysctl nodes under hw.psm.synaptics */
5651 	sysctl_ctx_init(&sc->syninfo.sysctl_ctx);
5652 	sc->syninfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->syninfo.sysctl_ctx,
5653 	    SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, name, CTLFLAG_RD,
5654 	    0, descr);
5655 
5656 	/* hw.psm.synaptics.directional_scrolls. */
5657 	sc->syninfo.directional_scrolls = 0;
5658 	SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
5659 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5660 	    "directional_scrolls", CTLFLAG_RW|CTLFLAG_ANYBODY,
5661 	    &sc->syninfo.directional_scrolls, 0,
5662 	    "Enable hardware scrolling pad (if non-zero) or register it as "
5663 	    "extended buttons (if 0)");
5664 
5665 	/* hw.psm.synaptics.max_x. */
5666 	sc->syninfo.max_x = 6143;
5667 	SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
5668 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5669 	    "max_x", CTLFLAG_RD|CTLFLAG_ANYBODY,
5670 	    &sc->syninfo.max_x, 0,
5671 	    "Horizontal reporting range");
5672 
5673 	/* hw.psm.synaptics.max_y. */
5674 	sc->syninfo.max_y = 6143;
5675 	SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
5676 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5677 	    "max_y", CTLFLAG_RD|CTLFLAG_ANYBODY,
5678 	    &sc->syninfo.max_y, 0,
5679 	    "Vertical reporting range");
5680 
5681 	/*
5682 	 * Turn off two finger scroll if we have a
5683 	 * physical area reserved for scrolling or when
5684 	 * there's no multi finger support.
5685 	 */
5686 	if (sc->synhw.verticalScroll || (sc->synhw.capMultiFinger == 0 &&
5687 					 sc->synhw.capAdvancedGestures == 0))
5688 		sc->syninfo.two_finger_scroll = 0;
5689 	else
5690 		sc->syninfo.two_finger_scroll = 1;
5691 	/* hw.psm.synaptics.two_finger_scroll. */
5692 	SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
5693 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5694 	    "two_finger_scroll", CTLFLAG_RW|CTLFLAG_ANYBODY,
5695 	    &sc->syninfo.two_finger_scroll, 0,
5696 	    "Enable two finger scrolling");
5697 
5698 	/* hw.psm.synaptics.min_pressure. */
5699 	sc->syninfo.min_pressure = 32;
5700 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5701 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5702 	    "min_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5703 	    sc, SYNAPTICS_SYSCTL_MIN_PRESSURE,
5704 	    synaptics_sysctl, "I",
5705 	    "Minimum pressure required to start an action");
5706 
5707 	/* hw.psm.synaptics.max_pressure. */
5708 	sc->syninfo.max_pressure = 220;
5709 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5710 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5711 	    "max_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5712 	    sc, SYNAPTICS_SYSCTL_MAX_PRESSURE,
5713 	    synaptics_sysctl, "I",
5714 	    "Maximum pressure to detect palm");
5715 
5716 	/* hw.psm.synaptics.max_width. */
5717 	sc->syninfo.max_width = 10;
5718 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5719 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5720 	    "max_width", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5721 	    sc, SYNAPTICS_SYSCTL_MAX_WIDTH,
5722 	    synaptics_sysctl, "I",
5723 	    "Maximum finger width to detect palm");
5724 
5725 	/* hw.psm.synaptics.top_margin. */
5726 	sc->syninfo.margin_top = 200;
5727 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5728 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5729 	    "margin_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5730 	    sc, SYNAPTICS_SYSCTL_MARGIN_TOP,
5731 	    synaptics_sysctl, "I",
5732 	    "Top margin");
5733 
5734 	/* hw.psm.synaptics.right_margin. */
5735 	sc->syninfo.margin_right = 200;
5736 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5737 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5738 	    "margin_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5739 	    sc, SYNAPTICS_SYSCTL_MARGIN_RIGHT,
5740 	    synaptics_sysctl, "I",
5741 	    "Right margin");
5742 
5743 	/* hw.psm.synaptics.bottom_margin. */
5744 	sc->syninfo.margin_bottom = 200;
5745 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5746 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5747 	    "margin_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5748 	    sc, SYNAPTICS_SYSCTL_MARGIN_BOTTOM,
5749 	    synaptics_sysctl, "I",
5750 	    "Bottom margin");
5751 
5752 	/* hw.psm.synaptics.left_margin. */
5753 	sc->syninfo.margin_left = 200;
5754 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5755 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5756 	    "margin_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5757 	    sc, SYNAPTICS_SYSCTL_MARGIN_LEFT,
5758 	    synaptics_sysctl, "I",
5759 	    "Left margin");
5760 
5761 	/* hw.psm.synaptics.na_top. */
5762 	sc->syninfo.na_top = 1783;
5763 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5764 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5765 	    "na_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5766 	    sc, SYNAPTICS_SYSCTL_NA_TOP,
5767 	    synaptics_sysctl, "I",
5768 	    "Top noisy area, where weight_previous_na is used instead "
5769 	    "of weight_previous");
5770 
5771 	/* hw.psm.synaptics.na_right. */
5772 	sc->syninfo.na_right = 563;
5773 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5774 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5775 	    "na_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5776 	    sc, SYNAPTICS_SYSCTL_NA_RIGHT,
5777 	    synaptics_sysctl, "I",
5778 	    "Right noisy area, where weight_previous_na is used instead "
5779 	    "of weight_previous");
5780 
5781 	/* hw.psm.synaptics.na_bottom. */
5782 	sc->syninfo.na_bottom = 1408;
5783 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5784 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5785 	    "na_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5786 	    sc, SYNAPTICS_SYSCTL_NA_BOTTOM,
5787 	    synaptics_sysctl, "I",
5788 	    "Bottom noisy area, where weight_previous_na is used instead "
5789 	    "of weight_previous");
5790 
5791 	/* hw.psm.synaptics.na_left. */
5792 	sc->syninfo.na_left = 1600;
5793 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5794 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5795 	    "na_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5796 	    sc, SYNAPTICS_SYSCTL_NA_LEFT,
5797 	    synaptics_sysctl, "I",
5798 	    "Left noisy area, where weight_previous_na is used instead "
5799 	    "of weight_previous");
5800 
5801 	/* hw.psm.synaptics.window_min. */
5802 	sc->syninfo.window_min = 4;
5803 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5804 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5805 	    "window_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5806 	    sc, SYNAPTICS_SYSCTL_WINDOW_MIN,
5807 	    synaptics_sysctl, "I",
5808 	    "Minimum window size to start an action");
5809 
5810 	/* hw.psm.synaptics.window_max. */
5811 	sc->syninfo.window_max = 10;
5812 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5813 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5814 	    "window_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5815 	    sc, SYNAPTICS_SYSCTL_WINDOW_MAX,
5816 	    synaptics_sysctl, "I",
5817 	    "Maximum window size");
5818 
5819 	/* hw.psm.synaptics.multiplicator. */
5820 	sc->syninfo.multiplicator = 10000;
5821 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5822 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5823 	    "multiplicator", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5824 	    sc, SYNAPTICS_SYSCTL_MULTIPLICATOR,
5825 	    synaptics_sysctl, "I",
5826 	    "Multiplicator to increase precision in averages and divisions");
5827 
5828 	/* hw.psm.synaptics.weight_current. */
5829 	sc->syninfo.weight_current = 3;
5830 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5831 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5832 	    "weight_current", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5833 	    sc, SYNAPTICS_SYSCTL_WEIGHT_CURRENT,
5834 	    synaptics_sysctl, "I",
5835 	    "Weight of the current movement in the new average");
5836 
5837 	/* hw.psm.synaptics.weight_previous. */
5838 	sc->syninfo.weight_previous = 6;
5839 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5840 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5841 	    "weight_previous", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5842 	    sc, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS,
5843 	    synaptics_sysctl, "I",
5844 	    "Weight of the previous average");
5845 
5846 	/* hw.psm.synaptics.weight_previous_na. */
5847 	sc->syninfo.weight_previous_na = 20;
5848 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5849 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5850 	    "weight_previous_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5851 	    sc, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA,
5852 	    synaptics_sysctl, "I",
5853 	    "Weight of the previous average (inside the noisy area)");
5854 
5855 	/* hw.psm.synaptics.weight_len_squared. */
5856 	sc->syninfo.weight_len_squared = 2000;
5857 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5858 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5859 	    "weight_len_squared", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5860 	    sc, SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED,
5861 	    synaptics_sysctl, "I",
5862 	    "Length (squared) of segments where weight_previous "
5863 	    "starts to decrease");
5864 
5865 	/* hw.psm.synaptics.div_min. */
5866 	sc->syninfo.div_min = 9;
5867 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5868 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5869 	    "div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5870 	    sc, SYNAPTICS_SYSCTL_DIV_MIN,
5871 	    synaptics_sysctl, "I",
5872 	    "Divisor for fast movements");
5873 
5874 	/* hw.psm.synaptics.div_max. */
5875 	sc->syninfo.div_max = 17;
5876 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5877 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5878 	    "div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5879 	    sc, SYNAPTICS_SYSCTL_DIV_MAX,
5880 	    synaptics_sysctl, "I",
5881 	    "Divisor for slow movements");
5882 
5883 	/* hw.psm.synaptics.div_max_na. */
5884 	sc->syninfo.div_max_na = 30;
5885 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5886 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5887 	    "div_max_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5888 	    sc, SYNAPTICS_SYSCTL_DIV_MAX_NA,
5889 	    synaptics_sysctl, "I",
5890 	    "Divisor with slow movements (inside the noisy area)");
5891 
5892 	/* hw.psm.synaptics.div_len. */
5893 	sc->syninfo.div_len = 100;
5894 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5895 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5896 	    "div_len", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5897 	    sc, SYNAPTICS_SYSCTL_DIV_LEN,
5898 	    synaptics_sysctl, "I",
5899 	    "Length of segments where div_max starts to decrease");
5900 
5901 	/* hw.psm.synaptics.tap_max_delta. */
5902 	sc->syninfo.tap_max_delta = 80;
5903 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5904 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5905 	    "tap_max_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5906 	    sc, SYNAPTICS_SYSCTL_TAP_MAX_DELTA,
5907 	    synaptics_sysctl, "I",
5908 	    "Length of segments above which a tap is ignored");
5909 
5910 	/* hw.psm.synaptics.tap_min_queue. */
5911 	sc->syninfo.tap_min_queue = 2;
5912 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5913 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5914 	    "tap_min_queue", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5915 	    sc, SYNAPTICS_SYSCTL_TAP_MIN_QUEUE,
5916 	    synaptics_sysctl, "I",
5917 	    "Number of packets required to consider a tap");
5918 
5919 	/* hw.psm.synaptics.taphold_timeout. */
5920 	sc->gesture.in_taphold = 0;
5921 	sc->syninfo.taphold_timeout = tap_timeout;
5922 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5923 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5924 	    "taphold_timeout", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5925 	    sc, SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT,
5926 	    synaptics_sysctl, "I",
5927 	    "Maximum elapsed time between two taps to consider a tap-hold "
5928 	    "action");
5929 
5930 	/* hw.psm.synaptics.vscroll_hor_area. */
5931 	sc->syninfo.vscroll_hor_area = 0; /* 1300 */
5932 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5933 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5934 	    "vscroll_hor_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5935 	    sc, SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA,
5936 	    synaptics_sysctl, "I",
5937 	    "Area reserved for horizontal virtual scrolling");
5938 
5939 	/* hw.psm.synaptics.vscroll_ver_area. */
5940 	sc->syninfo.vscroll_ver_area = -400 - sc->syninfo.margin_right;
5941 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5942 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5943 	    "vscroll_ver_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5944 	    sc, SYNAPTICS_SYSCTL_VSCROLL_VER_AREA,
5945 	    synaptics_sysctl, "I",
5946 	    "Area reserved for vertical virtual scrolling");
5947 
5948 	/* hw.psm.synaptics.vscroll_min_delta. */
5949 	sc->syninfo.vscroll_min_delta = 50;
5950 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5951 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5952 	    "vscroll_min_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5953 	    sc, SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA,
5954 	    synaptics_sysctl, "I",
5955 	    "Minimum movement to consider virtual scrolling");
5956 
5957 	/* hw.psm.synaptics.vscroll_div_min. */
5958 	sc->syninfo.vscroll_div_min = 100;
5959 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5960 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5961 	    "vscroll_div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5962 	    sc, SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN,
5963 	    synaptics_sysctl, "I",
5964 	    "Divisor for fast scrolling");
5965 
5966 	/* hw.psm.synaptics.vscroll_div_min. */
5967 	sc->syninfo.vscroll_div_max = 150;
5968 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5969 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5970 	    "vscroll_div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5971 	    sc, SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX,
5972 	    synaptics_sysctl, "I",
5973 	    "Divisor for slow scrolling");
5974 
5975 	/* hw.psm.synaptics.touchpad_off. */
5976 	sc->syninfo.touchpad_off = 0;
5977 	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5978 	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5979 	    "touchpad_off", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
5980 	    sc, SYNAPTICS_SYSCTL_TOUCHPAD_OFF,
5981 	    synaptics_sysctl, "I",
5982 	    "Turn off touchpad");
5983 
5984 	sc->syninfo.softbuttons_y = 0;
5985 	sc->syninfo.softbutton2_x = 0;
5986 	sc->syninfo.softbutton3_x = 0;
5987 
5988 	/* skip softbuttons sysctl on not clickpads */
5989 	if (sc->synhw.capClickPad)
5990 		synaptics_sysctl_create_softbuttons_tree(sc);
5991 }
5992 
5993 static int
5994 synaptics_preferred_mode(struct psm_softc *sc) {
5995 	int mode_byte;
5996 
5997 	/* Check if we are in relative mode */
5998 	if (sc->hw.model != MOUSE_MODEL_SYNAPTICS) {
5999 		if (tap_enabled == 0)
6000 			/*
6001 			 * Disable tap & drag gestures. We use a Mode Byte
6002 			 * and set the DisGest bit (see §2.5 of Synaptics
6003 			 * TouchPad Interfacing Guide).
6004 			 */
6005 			return (0x04);
6006 		else
6007 			/*
6008 			 * Enable tap & drag gestures. We use a Mode Byte
6009 			 * and clear the DisGest bit (see §2.5 of Synaptics
6010 			 * TouchPad Interfacing Guide).
6011 			 */
6012 			return (0x00);
6013 	}
6014 
6015 	mode_byte = 0xc4;
6016 
6017 	/* request wmode where available */
6018 	if (sc->synhw.capExtended)
6019 		mode_byte |= 1;
6020 
6021 	return mode_byte;
6022 }
6023 
6024 static void
6025 synaptics_set_mode(struct psm_softc *sc, int mode_byte) {
6026 	mouse_ext_command(sc->kbdc, mode_byte);
6027 
6028 	/* "Commit" the Set Mode Byte command sent above. */
6029 	set_mouse_sampling_rate(sc->kbdc, 20);
6030 
6031 	/*
6032 	 * Enable advanced gestures mode if supported and we are not entering
6033 	 * passthrough or relative mode.
6034 	 */
6035 	if ((sc->synhw.capAdvancedGestures || sc->synhw.capReportsV) &&
6036 	    sc->hw.model == MOUSE_MODEL_SYNAPTICS && !(mode_byte & (1 << 5))) {
6037 		mouse_ext_command(sc->kbdc, 3);
6038 		set_mouse_sampling_rate(sc->kbdc, 0xc8);
6039 	}
6040 }
6041 
6042 static int
6043 enable_synaptics(struct psm_softc *sc, enum probearg arg)
6044 {
6045 	device_t psmcpnp;
6046 	struct psmcpnp_softc *psmcpnp_sc;
6047 	KBDC kbdc = sc->kbdc;
6048 	synapticshw_t synhw;
6049 	int status[3];
6050 	int buttons, middle_byte;
6051 
6052 	VLOG(3, (LOG_DEBUG, "synaptics: BEGIN init\n"));
6053 
6054 	/*
6055 	 * Just to be on the safe side: this avoids troubles with
6056 	 * following mouse_ext_command() when the previous command
6057 	 * was PSMC_SET_RESOLUTION. Set Scaling has no effect on
6058 	 * Synaptics Touchpad behaviour.
6059 	 */
6060 	set_mouse_scaling(kbdc, 1);
6061 
6062 	/* Identify the Touchpad version. */
6063 	if (mouse_ext_command(kbdc, 0) == 0)
6064 		return (FALSE);
6065 	if (get_mouse_status(kbdc, status, 0, 3) != 3)
6066 		return (FALSE);
6067 	middle_byte = status[1];
6068 	if (middle_byte != 0x46 && middle_byte != 0x47)
6069 		return (FALSE);
6070 
6071 	bzero(&synhw, sizeof(synhw));
6072 	synhw.infoMinor = status[0];
6073 	synhw.infoMajor = status[2] & 0x0f;
6074 
6075 	if (verbose >= 2)
6076 		printf("Synaptics Touchpad v%d.%d\n", synhw.infoMajor,
6077 		    synhw.infoMinor);
6078 
6079 	/*
6080 	 * Most synaptics touchpads return 0x47 in middle byte in responce to
6081 	 * identify command as stated in p.4.4 of "Synaptics PS/2 TouchPad
6082 	 * Interfacing Guide" and we only support v4.0 or better. But some
6083 	 * devices return 0x46 here and have a different numbering scheme.
6084 	 * In the case of 0x46, we allow versions as low as v2.0
6085 	 */
6086 	if ((middle_byte == 0x47 && synhw.infoMajor < 4) ||
6087 	    (middle_byte == 0x46 && synhw.infoMajor < 2)) {
6088 		printf("  Unsupported (pre-v4) Touchpad detected\n");
6089 		return (FALSE);
6090 	}
6091 
6092 	/* Get the Touchpad model information. */
6093 	if (mouse_ext_command(kbdc, 3) == 0)
6094 		return (FALSE);
6095 	if (get_mouse_status(kbdc, status, 0, 3) != 3)
6096 		return (FALSE);
6097 	if ((status[1] & 0x01) != 0) {
6098 		printf("  Failed to read model information\n");
6099 		return (FALSE);
6100 	}
6101 
6102 	synhw.infoRot180   = (status[0] & 0x80) != 0;
6103 	synhw.infoPortrait = (status[0] & 0x40) != 0;
6104 	synhw.infoSensor   =  status[0] & 0x3f;
6105 	synhw.infoHardware = (status[1] & 0xfe) >> 1;
6106 	synhw.infoNewAbs   = (status[2] & 0x80) != 0;
6107 	synhw.capPen       = (status[2] & 0x40) != 0;
6108 	synhw.infoSimplC   = (status[2] & 0x20) != 0;
6109 	synhw.infoGeometry =  status[2] & 0x0f;
6110 
6111 	if (verbose >= 2) {
6112 		printf("  Model information:\n");
6113 		printf("   infoRot180: %d\n", synhw.infoRot180);
6114 		printf("   infoPortrait: %d\n", synhw.infoPortrait);
6115 		printf("   infoSensor: %d\n", synhw.infoSensor);
6116 		printf("   infoHardware: %d\n", synhw.infoHardware);
6117 		printf("   infoNewAbs: %d\n", synhw.infoNewAbs);
6118 		printf("   capPen: %d\n", synhw.capPen);
6119 		printf("   infoSimplC: %d\n", synhw.infoSimplC);
6120 		printf("   infoGeometry: %d\n", synhw.infoGeometry);
6121 	}
6122 
6123 	/* Read the extended capability bits. */
6124 	if (mouse_ext_command(kbdc, 2) == 0)
6125 		return (FALSE);
6126 	if (get_mouse_status(kbdc, status, 0, 3) != 3)
6127 		return (FALSE);
6128 	if (!SYNAPTICS_VERSION_GE(synhw, 7, 5) && status[1] != middle_byte) {
6129 		printf("  Failed to read extended capability bits\n");
6130 		return (FALSE);
6131 	}
6132 
6133 	psmcpnp = devclass_get_device(devclass_find(PSMCPNP_DRIVER_NAME),
6134 	    sc->unit);
6135 	psmcpnp_sc = (psmcpnp != NULL) ? device_get_softc(psmcpnp) : NULL;
6136 
6137 	/*
6138 	 * Set conservative defaults for 0x46 middle byte touchpads
6139 	 * as ExtendedQueries return bogus data.
6140 	 */
6141 	if (middle_byte == 0x46) {
6142 		synhw.capExtended = 1;
6143 		synhw.capPalmDetect = 1;
6144 		synhw.capPassthrough = 1;
6145 		synhw.capMultiFinger = 1;
6146 		synhw.maximumXCoord = SYNAPTICS_DEFAULT_MAX_X;
6147 		synhw.maximumYCoord = SYNAPTICS_DEFAULT_MAX_Y;
6148 		synhw.minimumXCoord = SYNAPTICS_DEFAULT_MIN_X;
6149 		synhw.minimumYCoord = SYNAPTICS_DEFAULT_MIN_Y;
6150 		/* Enable multitouch mode for HW v8.1 devices */
6151 		if (psmcpnp_sc != NULL &&
6152 		    psmcpnp_sc->type == PSMCPNP_HPSYN81)
6153 			synhw.capReportsV = 1;
6154 	} else
6155 		synhw.capExtended = (status[0] & 0x80) != 0;
6156 
6157 	/* Set the different capabilities when they exist. */
6158 	buttons = 0;
6159 	if (synhw.capExtended && middle_byte == 0x47) {
6160 		synhw.nExtendedQueries = (status[0] & 0x70) >> 4;
6161 		synhw.capMiddle        = (status[0] & 0x04) != 0;
6162 		synhw.capPassthrough   = (status[2] & 0x80) != 0;
6163 		synhw.capLowPower      = (status[2] & 0x40) != 0;
6164 		synhw.capMultiFingerReport =
6165 					 (status[2] & 0x20) != 0;
6166 		synhw.capSleep         = (status[2] & 0x10) != 0;
6167 		synhw.capFourButtons   = (status[2] & 0x08) != 0;
6168 		synhw.capBallistics    = (status[2] & 0x04) != 0;
6169 		synhw.capMultiFinger   = (status[2] & 0x02) != 0;
6170 		synhw.capPalmDetect    = (status[2] & 0x01) != 0;
6171 
6172 		if (!set_mouse_scaling(kbdc, 1))
6173 			return (FALSE);
6174 		if (mouse_ext_command(kbdc, 0x08) == 0)
6175 			return (FALSE);
6176 		if (get_mouse_status(kbdc, status, 0, 3) != 3)
6177 			return (FALSE);
6178 
6179 		if (status[0] != 0 && (status[1] & 0x80) && status[2] != 0) {
6180 			synhw.infoXupmm = status[0];
6181 			synhw.infoYupmm = status[2];
6182 		}
6183 
6184 		if (verbose >= 2) {
6185 			printf("  Extended capabilities:\n");
6186 			printf("   capExtended: %d\n", synhw.capExtended);
6187 			printf("   capMiddle: %d\n", synhw.capMiddle);
6188 			printf("   nExtendedQueries: %d\n",
6189 			    synhw.nExtendedQueries);
6190 			printf("   capPassthrough: %d\n", synhw.capPassthrough);
6191 			printf("   capLowPower: %d\n", synhw.capLowPower);
6192 			printf("   capMultiFingerReport: %d\n",
6193 			    synhw.capMultiFingerReport);
6194 			printf("   capSleep: %d\n", synhw.capSleep);
6195 			printf("   capFourButtons: %d\n", synhw.capFourButtons);
6196 			printf("   capBallistics: %d\n", synhw.capBallistics);
6197 			printf("   capMultiFinger: %d\n", synhw.capMultiFinger);
6198 			printf("   capPalmDetect: %d\n", synhw.capPalmDetect);
6199 			printf("   infoXupmm: %d\n", synhw.infoXupmm);
6200 			printf("   infoYupmm: %d\n", synhw.infoYupmm);
6201 		}
6202 
6203 		/*
6204 		 * If nExtendedQueries is 1 or greater, then the TouchPad
6205 		 * supports this number of extended queries. We can load
6206 		 * more information about buttons using query 0x09.
6207 		 */
6208 		if (synhw.nExtendedQueries >= 1) {
6209 			if (!set_mouse_scaling(kbdc, 1))
6210 				return (FALSE);
6211 			if (mouse_ext_command(kbdc, 0x09) == 0)
6212 				return (FALSE);
6213 			if (get_mouse_status(kbdc, status, 0, 3) != 3)
6214 				return (FALSE);
6215 			synhw.verticalScroll   = (status[0] & 0x01) != 0;
6216 			synhw.horizontalScroll = (status[0] & 0x02) != 0;
6217 			synhw.verticalWheel    = (status[0] & 0x08) != 0;
6218 			synhw.nExtendedButtons = (status[1] & 0xf0) >> 4;
6219 			synhw.capEWmode        = (status[0] & 0x04) != 0;
6220 			if (verbose >= 2) {
6221 				printf("  Extended model ID:\n");
6222 				printf("   verticalScroll: %d\n",
6223 				    synhw.verticalScroll);
6224 				printf("   horizontalScroll: %d\n",
6225 				    synhw.horizontalScroll);
6226 				printf("   verticalWheel: %d\n",
6227 				    synhw.verticalWheel);
6228 				printf("   nExtendedButtons: %d\n",
6229 				    synhw.nExtendedButtons);
6230 				printf("   capEWmode: %d\n",
6231 				    synhw.capEWmode);
6232 			}
6233 			/*
6234 			 * Add the number of extended buttons to the total
6235 			 * button support count, including the middle button
6236 			 * if capMiddle support bit is set.
6237 			 */
6238 			buttons = synhw.nExtendedButtons + synhw.capMiddle;
6239 		} else
6240 			/*
6241 			 * If the capFourButtons support bit is set,
6242 			 * add a fourth button to the total button count.
6243 			 */
6244 			buttons = synhw.capFourButtons ? 1 : 0;
6245 
6246 		/* Read the continued capabilities bits. */
6247 		if (synhw.nExtendedQueries >= 4) {
6248 			if (!set_mouse_scaling(kbdc, 1))
6249 				return (FALSE);
6250 			if (mouse_ext_command(kbdc, 0x0c) == 0)
6251 				return (FALSE);
6252 			if (get_mouse_status(kbdc, status, 0, 3) != 3)
6253 				return (FALSE);
6254 
6255 			synhw.capClickPad         = (status[1] & 0x01) << 1;
6256 			synhw.capClickPad        |= (status[0] & 0x10) != 0;
6257 			synhw.capDeluxeLEDs       = (status[1] & 0x02) != 0;
6258 			synhw.noAbsoluteFilter    = (status[1] & 0x04) != 0;
6259 			synhw.capReportsV         = (status[1] & 0x08) != 0;
6260 			synhw.capUniformClickPad  = (status[1] & 0x10) != 0;
6261 			synhw.capReportsMin       = (status[1] & 0x20) != 0;
6262 			synhw.capInterTouch       = (status[1] & 0x40) != 0;
6263 			synhw.capReportsMax       = (status[0] & 0x02) != 0;
6264 			synhw.capClearPad         = (status[0] & 0x04) != 0;
6265 			synhw.capAdvancedGestures = (status[0] & 0x08) != 0;
6266 			synhw.capCoveredPad       = (status[0] & 0x80) != 0;
6267 
6268 			if (synhw.capReportsMax) {
6269 				if (!set_mouse_scaling(kbdc, 1))
6270 					return (FALSE);
6271 				if (mouse_ext_command(kbdc, 0x0d) == 0)
6272 					return (FALSE);
6273 				if (get_mouse_status(kbdc, status, 0, 3) != 3)
6274 					return (FALSE);
6275 
6276 				synhw.maximumXCoord = (status[0] << 5) |
6277 						     ((status[1] & 0x0f) << 1);
6278 				synhw.maximumYCoord = (status[2] << 5) |
6279 						     ((status[1] & 0xf0) >> 3);
6280 			} else {
6281 				synhw.maximumXCoord = SYNAPTICS_DEFAULT_MAX_X;
6282 				synhw.maximumYCoord = SYNAPTICS_DEFAULT_MAX_Y;
6283 			}
6284 
6285 			if (synhw.capReportsMin) {
6286 				if (!set_mouse_scaling(kbdc, 1))
6287 					return (FALSE);
6288 				if (mouse_ext_command(kbdc, 0x0f) == 0)
6289 					return (FALSE);
6290 				if (get_mouse_status(kbdc, status, 0, 3) != 3)
6291 					return (FALSE);
6292 
6293 				synhw.minimumXCoord = (status[0] << 5) |
6294 						     ((status[1] & 0x0f) << 1);
6295 				synhw.minimumYCoord = (status[2] << 5) |
6296 						     ((status[1] & 0xf0) >> 3);
6297 			} else {
6298 				synhw.minimumXCoord = SYNAPTICS_DEFAULT_MIN_X;
6299 				synhw.minimumYCoord = SYNAPTICS_DEFAULT_MIN_Y;
6300 			}
6301 
6302 			/*
6303 			 * ClickPad properties are not exported through PS/2
6304 			 * protocol. Detection is based on controller's PnP ID.
6305 			 */
6306 			if (synhw.capClickPad && psmcpnp_sc != NULL) {
6307 				switch (psmcpnp_sc->type) {
6308 				case PSMCPNP_FORCEPAD:
6309 					synhw.forcePad = 1;
6310 					break;
6311 				default:
6312 					break;
6313 				}
6314 			}
6315 
6316 			if (verbose >= 2) {
6317 				printf("  Continued capabilities:\n");
6318 				printf("   capClickPad: %d\n",
6319 				       synhw.capClickPad);
6320 				printf("   capDeluxeLEDs: %d\n",
6321 				       synhw.capDeluxeLEDs);
6322 				printf("   noAbsoluteFilter: %d\n",
6323 				       synhw.noAbsoluteFilter);
6324 				printf("   capReportsV: %d\n",
6325 				       synhw.capReportsV);
6326 				printf("   capUniformClickPad: %d\n",
6327 				       synhw.capUniformClickPad);
6328 				printf("   capReportsMin: %d\n",
6329 				       synhw.capReportsMin);
6330 				printf("   capInterTouch: %d\n",
6331 				       synhw.capInterTouch);
6332 				printf("   capReportsMax: %d\n",
6333 				       synhw.capReportsMax);
6334 				printf("   capClearPad: %d\n",
6335 				       synhw.capClearPad);
6336 				printf("   capAdvancedGestures: %d\n",
6337 				       synhw.capAdvancedGestures);
6338 				printf("   capCoveredPad: %d\n",
6339 				       synhw.capCoveredPad);
6340 				if (synhw.capReportsMax) {
6341 					printf("   maximumXCoord: %d\n",
6342 					       synhw.maximumXCoord);
6343 					printf("   maximumYCoord: %d\n",
6344 					       synhw.maximumYCoord);
6345 				}
6346 				if (synhw.capReportsMin) {
6347 					printf("   minimumXCoord: %d\n",
6348 					       synhw.minimumXCoord);
6349 					printf("   minimumYCoord: %d\n",
6350 					       synhw.minimumYCoord);
6351 				}
6352 				if (synhw.capClickPad) {
6353 					printf("   forcePad: %d\n",
6354 					       synhw.forcePad);
6355 				}
6356 			}
6357 			buttons += synhw.capClickPad;
6358 		}
6359 	}
6360 
6361 	if (verbose >= 2) {
6362 		if (synhw.capExtended)
6363 			printf("  Additional Buttons: %d\n", buttons);
6364 		else
6365 			printf("  No extended capabilities\n");
6366 	}
6367 
6368 	/*
6369 	 * Add the default number of 3 buttons to the total
6370 	 * count of supported buttons reported above.
6371 	 */
6372 	buttons += 3;
6373 
6374 	/*
6375 	 * Read the mode byte.
6376 	 *
6377 	 * XXX: Note the Synaptics documentation also defines the first
6378 	 * byte of the response to this query to be a constant 0x3b, this
6379 	 * does not appear to be true for Touchpads with guest devices.
6380 	 */
6381 	if (mouse_ext_command(kbdc, 1) == 0)
6382 		return (FALSE);
6383 	if (get_mouse_status(kbdc, status, 0, 3) != 3)
6384 		return (FALSE);
6385 	if (!SYNAPTICS_VERSION_GE(synhw, 7, 5) && status[1] != middle_byte) {
6386 		printf("  Failed to read mode byte\n");
6387 		return (FALSE);
6388 	}
6389 
6390 	if (arg == PROBE)
6391 		sc->synhw = synhw;
6392 	if (!synaptics_support)
6393 		return (FALSE);
6394 
6395 	/* Set mouse type just now for synaptics_set_mode() */
6396 	sc->hw.model = MOUSE_MODEL_SYNAPTICS;
6397 
6398 	synaptics_set_mode(sc, synaptics_preferred_mode(sc));
6399 
6400 	if (trackpoint_support && synhw.capPassthrough) {
6401 		enable_trackpoint(sc, arg);
6402 	}
6403 
6404 	VLOG(3, (LOG_DEBUG, "synaptics: END init (%d buttons)\n", buttons));
6405 
6406 	if (arg == PROBE) {
6407 		/* Create sysctl tree. */
6408 		synaptics_sysctl_create_tree(sc, "synaptics",
6409 		    "Synaptics TouchPad");
6410 		sc->hw.buttons = buttons;
6411 	}
6412 
6413 	return (TRUE);
6414 }
6415 
6416 static void
6417 synaptics_passthrough_on(struct psm_softc *sc)
6418 {
6419 	VLOG(2, (LOG_NOTICE, "psm: setting pass-through mode.\n"));
6420 	synaptics_set_mode(sc, synaptics_preferred_mode(sc) | (1 << 5));
6421 }
6422 
6423 static void
6424 synaptics_passthrough_off(struct psm_softc *sc)
6425 {
6426 	VLOG(2, (LOG_NOTICE, "psm: turning pass-through mode off.\n"));
6427 	set_mouse_scaling(sc->kbdc, 2);
6428 	set_mouse_scaling(sc->kbdc, 1);
6429 	synaptics_set_mode(sc, synaptics_preferred_mode(sc));
6430 }
6431 
6432 /* IBM/Lenovo TrackPoint */
6433 static int
6434 trackpoint_command(struct psm_softc *sc, int cmd, int loc, int val)
6435 {
6436 	const int seq[] = { 0xe2, cmd, loc, val };
6437 	int i;
6438 
6439 	if (sc->synhw.capPassthrough)
6440 		synaptics_passthrough_on(sc);
6441 
6442 	for (i = 0; i < nitems(seq); i++) {
6443 		if (sc->synhw.capPassthrough &&
6444 		    (seq[i] == 0xff || seq[i] == 0xe7))
6445 			if (send_aux_command(sc->kbdc, 0xe7) != PSM_ACK) {
6446 				synaptics_passthrough_off(sc);
6447 				return (EIO);
6448 			}
6449 		if (send_aux_command(sc->kbdc, seq[i]) != PSM_ACK) {
6450 			if (sc->synhw.capPassthrough)
6451 				synaptics_passthrough_off(sc);
6452 			return (EIO);
6453 		}
6454 	}
6455 
6456 	if (sc->synhw.capPassthrough)
6457 		synaptics_passthrough_off(sc);
6458 
6459 	return (0);
6460 }
6461 
6462 #define	PSM_TPINFO(x)	offsetof(struct psm_softc, tpinfo.x)
6463 #define	TPMASK		0
6464 #define	TPLOC		1
6465 #define	TPINFO		2
6466 
6467 static int
6468 trackpoint_sysctl(SYSCTL_HANDLER_ARGS)
6469 {
6470 	static const int data[][3] = {
6471 		{ 0x00, 0x4a, PSM_TPINFO(sensitivity) },
6472 		{ 0x00, 0x4d, PSM_TPINFO(inertia) },
6473 		{ 0x00, 0x60, PSM_TPINFO(uplateau) },
6474 		{ 0x00, 0x57, PSM_TPINFO(reach) },
6475 		{ 0x00, 0x58, PSM_TPINFO(draghys) },
6476 		{ 0x00, 0x59, PSM_TPINFO(mindrag) },
6477 		{ 0x00, 0x5a, PSM_TPINFO(upthresh) },
6478 		{ 0x00, 0x5c, PSM_TPINFO(threshold) },
6479 		{ 0x00, 0x5d, PSM_TPINFO(jenks) },
6480 		{ 0x00, 0x5e, PSM_TPINFO(ztime) },
6481 		{ 0x01, 0x2c, PSM_TPINFO(pts) },
6482 		{ 0x08, 0x2d, PSM_TPINFO(skipback) }
6483 	};
6484 	struct psm_softc *sc;
6485 	int error, newval, *oldvalp;
6486 	const int *tp;
6487 
6488 	if (arg1 == NULL || arg2 < 0 || arg2 >= nitems(data))
6489 		return (EINVAL);
6490 	sc = arg1;
6491 	tp = data[arg2];
6492 	oldvalp = (int *)((intptr_t)sc + tp[TPINFO]);
6493 	newval = *oldvalp;
6494 	error = sysctl_handle_int(oidp, &newval, 0, req);
6495 	if (error != 0)
6496 		return (error);
6497 	if (newval == *oldvalp)
6498 		return (0);
6499 	if (newval < 0 || newval > (tp[TPMASK] == 0 ? 255 : 1))
6500 		return (EINVAL);
6501 	error = trackpoint_command(sc, tp[TPMASK] == 0 ? 0x81 : 0x47,
6502 	    tp[TPLOC], tp[TPMASK] == 0 ? newval : tp[TPMASK]);
6503 	if (error != 0)
6504 		return (error);
6505 	*oldvalp = newval;
6506 
6507 	return (0);
6508 }
6509 
6510 static void
6511 trackpoint_sysctl_create_tree(struct psm_softc *sc)
6512 {
6513 
6514 	if (sc->tpinfo.sysctl_tree != NULL)
6515 		return;
6516 
6517 	/* Attach extra trackpoint sysctl nodes under hw.psm.trackpoint */
6518 	sysctl_ctx_init(&sc->tpinfo.sysctl_ctx);
6519 	sc->tpinfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->tpinfo.sysctl_ctx,
6520 	    SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "trackpoint", CTLFLAG_RD,
6521 	    0, "IBM/Lenovo TrackPoint");
6522 
6523 	/* hw.psm.trackpoint.sensitivity */
6524 	sc->tpinfo.sensitivity = 0x80;
6525 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6526 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6527 	    "sensitivity", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6528 	    sc, TRACKPOINT_SYSCTL_SENSITIVITY,
6529 	    trackpoint_sysctl, "I",
6530 	    "Sensitivity");
6531 
6532 	/* hw.psm.trackpoint.negative_inertia */
6533 	sc->tpinfo.inertia = 0x06;
6534 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6535 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6536 	    "negative_inertia", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6537 	    sc, TRACKPOINT_SYSCTL_NEGATIVE_INERTIA,
6538 	    trackpoint_sysctl, "I",
6539 	    "Negative inertia factor");
6540 
6541 	/* hw.psm.trackpoint.upper_plateau */
6542 	sc->tpinfo.uplateau = 0x61;
6543 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6544 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6545 	    "upper_plateau", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6546 	    sc, TRACKPOINT_SYSCTL_UPPER_PLATEAU,
6547 	    trackpoint_sysctl, "I",
6548 	    "Transfer function upper plateau speed");
6549 
6550 	/* hw.psm.trackpoint.backup_range */
6551 	sc->tpinfo.reach = 0x0a;
6552 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6553 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6554 	    "backup_range", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6555 	    sc, TRACKPOINT_SYSCTL_BACKUP_RANGE,
6556 	    trackpoint_sysctl, "I",
6557 	    "Backup range");
6558 
6559 	/* hw.psm.trackpoint.drag_hysteresis */
6560 	sc->tpinfo.draghys = 0xff;
6561 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6562 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6563 	    "drag_hysteresis", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6564 	    sc, TRACKPOINT_SYSCTL_DRAG_HYSTERESIS,
6565 	    trackpoint_sysctl, "I",
6566 	    "Drag hysteresis");
6567 
6568 	/* hw.psm.trackpoint.minimum_drag */
6569 	sc->tpinfo.mindrag = 0x14;
6570 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6571 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6572 	    "minimum_drag", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6573 	    sc, TRACKPOINT_SYSCTL_MINIMUM_DRAG,
6574 	    trackpoint_sysctl, "I",
6575 	    "Minimum drag");
6576 
6577 	/* hw.psm.trackpoint.up_threshold */
6578 	sc->tpinfo.upthresh = 0xff;
6579 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6580 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6581 	    "up_threshold", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6582 	    sc, TRACKPOINT_SYSCTL_UP_THRESHOLD,
6583 	    trackpoint_sysctl, "I",
6584 	    "Up threshold for release");
6585 
6586 	/* hw.psm.trackpoint.threshold */
6587 	sc->tpinfo.threshold = 0x08;
6588 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6589 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6590 	    "threshold", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6591 	    sc, TRACKPOINT_SYSCTL_THRESHOLD,
6592 	    trackpoint_sysctl, "I",
6593 	    "Threshold");
6594 
6595 	/* hw.psm.trackpoint.jenks_curvature */
6596 	sc->tpinfo.jenks = 0x87;
6597 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6598 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6599 	    "jenks_curvature", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6600 	    sc, TRACKPOINT_SYSCTL_JENKS_CURVATURE,
6601 	    trackpoint_sysctl, "I",
6602 	    "Jenks curvature");
6603 
6604 	/* hw.psm.trackpoint.z_time */
6605 	sc->tpinfo.ztime = 0x26;
6606 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6607 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6608 	    "z_time", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6609 	    sc, TRACKPOINT_SYSCTL_Z_TIME,
6610 	    trackpoint_sysctl, "I",
6611 	    "Z time constant");
6612 
6613 	/* hw.psm.trackpoint.press_to_select */
6614 	sc->tpinfo.pts = 0x00;
6615 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6616 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6617 	    "press_to_select", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6618 	    sc, TRACKPOINT_SYSCTL_PRESS_TO_SELECT,
6619 	    trackpoint_sysctl, "I",
6620 	    "Press to Select");
6621 
6622 	/* hw.psm.trackpoint.skip_backups */
6623 	sc->tpinfo.skipback = 0x00;
6624 	SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6625 	    SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6626 	    "skip_backups", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
6627 	    sc, TRACKPOINT_SYSCTL_SKIP_BACKUPS,
6628 	    trackpoint_sysctl, "I",
6629 	    "Skip backups from drags");
6630 }
6631 
6632 static void
6633 set_trackpoint_parameters(struct psm_softc *sc)
6634 {
6635 	trackpoint_command(sc, 0x81, 0x4a, sc->tpinfo.sensitivity);
6636 	trackpoint_command(sc, 0x81, 0x60, sc->tpinfo.uplateau);
6637 	trackpoint_command(sc, 0x81, 0x4d, sc->tpinfo.inertia);
6638 	trackpoint_command(sc, 0x81, 0x57, sc->tpinfo.reach);
6639 	trackpoint_command(sc, 0x81, 0x58, sc->tpinfo.draghys);
6640 	trackpoint_command(sc, 0x81, 0x59, sc->tpinfo.mindrag);
6641 	trackpoint_command(sc, 0x81, 0x5a, sc->tpinfo.upthresh);
6642 	trackpoint_command(sc, 0x81, 0x5c, sc->tpinfo.threshold);
6643 	trackpoint_command(sc, 0x81, 0x5d, sc->tpinfo.jenks);
6644 	trackpoint_command(sc, 0x81, 0x5e, sc->tpinfo.ztime);
6645 	if (sc->tpinfo.pts == 0x01)
6646 		trackpoint_command(sc, 0x47, 0x2c, 0x01);
6647 	if (sc->tpinfo.skipback == 0x01)
6648 		trackpoint_command(sc, 0x47, 0x2d, 0x08);
6649 }
6650 
6651 static int
6652 enable_trackpoint(struct psm_softc *sc, enum probearg arg)
6653 {
6654 	KBDC kbdc = sc->kbdc;
6655 	int id;
6656 
6657 	/*
6658 	 * If called from enable_synaptics(), make sure that passthrough
6659 	 * mode is enabled so we can reach the trackpoint.
6660 	 * However, passthrough mode must be disabled before setting the
6661 	 * trackpoint parameters, as rackpoint_command() enables and disables
6662 	 * passthrough mode on its own.
6663 	 */
6664 	if (sc->synhw.capPassthrough)
6665 		synaptics_passthrough_on(sc);
6666 
6667 	if (send_aux_command(kbdc, 0xe1) != PSM_ACK ||
6668 	    read_aux_data(kbdc) != 0x01)
6669 		goto no_trackpoint;
6670 	id = read_aux_data(kbdc);
6671 	if (id < 0x01)
6672 		goto no_trackpoint;
6673 	if (arg == PROBE)
6674 		sc->tphw = id;
6675 	if (!trackpoint_support)
6676 		goto no_trackpoint;
6677 
6678 	if (sc->synhw.capPassthrough)
6679 		synaptics_passthrough_off(sc);
6680 
6681 	if (arg == PROBE) {
6682 		trackpoint_sysctl_create_tree(sc);
6683 		/*
6684 		 * Don't overwrite hwid and buttons when we are
6685 		 * a guest device.
6686 		 */
6687 		if (!sc->synhw.capPassthrough) {
6688 			sc->hw.hwid = id;
6689 			sc->hw.buttons = 3;
6690 		}
6691 	}
6692 
6693 	set_trackpoint_parameters(sc);
6694 
6695 	return (TRUE);
6696 
6697 no_trackpoint:
6698 	if (sc->synhw.capPassthrough)
6699 		synaptics_passthrough_off(sc);
6700 
6701 	return (FALSE);
6702 }
6703 
6704 /* Interlink electronics VersaPad */
6705 static int
6706 enable_versapad(struct psm_softc *sc, enum probearg arg)
6707 {
6708 	KBDC kbdc = sc->kbdc;
6709 	int data[3];
6710 
6711 	set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
6712 	set_mouse_sampling_rate(kbdc, 100);		/* set rate 100 */
6713 	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
6714 	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
6715 	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
6716 	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
6717 	if (get_mouse_status(kbdc, data, 0, 3) < 3)	/* get status */
6718 		return (FALSE);
6719 	if (data[2] != 0xa || data[1] != 0 )	/* rate == 0xa && res. == 0 */
6720 		return (FALSE);
6721 	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
6722 
6723 	return (TRUE);				/* PS/2 absolute mode */
6724 }
6725 
6726 /* Elantech Touchpad */
6727 static int
6728 elantech_read_1(KBDC kbdc, int hwversion, int reg, int *val)
6729 {
6730 	int res, readcmd, retidx;
6731 	int resp[3];
6732 
6733 	readcmd = hwversion == 2 ? ELANTECH_REG_READ : ELANTECH_REG_RDWR;
6734 	retidx = hwversion == 4 ? 1 : 0;
6735 
6736 	res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
6737 	res |= send_aux_command(kbdc, readcmd) != PSM_ACK;
6738 	res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
6739 	res |= send_aux_command(kbdc, reg) != PSM_ACK;
6740 	res |= get_mouse_status(kbdc, resp, 0, 3) != 3;
6741 
6742 	if (res == 0)
6743 		*val = resp[retidx];
6744 
6745 	return (res);
6746 }
6747 
6748 static int
6749 elantech_write_1(KBDC kbdc, int hwversion, int reg, int val)
6750 {
6751 	int res, writecmd;
6752 
6753 	writecmd = hwversion == 2 ? ELANTECH_REG_WRITE : ELANTECH_REG_RDWR;
6754 
6755 	res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
6756 	res |= send_aux_command(kbdc, writecmd) != PSM_ACK;
6757 	res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
6758 	res |= send_aux_command(kbdc, reg) != PSM_ACK;
6759 	if (hwversion == 4) {
6760 		res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
6761 		res |= send_aux_command(kbdc, writecmd) != PSM_ACK;
6762 	}
6763 	res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
6764 	res |= send_aux_command(kbdc, val) != PSM_ACK;
6765 	res |= set_mouse_scaling(kbdc, 1) == 0;
6766 
6767 	return (res);
6768 }
6769 
6770 static int
6771 elantech_cmd(KBDC kbdc, int hwversion, int cmd, int *resp)
6772 {
6773 	int res;
6774 
6775 	if (hwversion == 2) {
6776 		res = set_mouse_scaling(kbdc, 1) == 0;
6777 		res |= mouse_ext_command(kbdc, cmd) == 0;
6778 	} else {
6779 		res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
6780 		res |= send_aux_command(kbdc, cmd) != PSM_ACK;
6781 	}
6782 	res |= get_mouse_status(kbdc, resp, 0, 3) != 3;
6783 
6784 	return (res);
6785 }
6786 
6787 static int
6788 elantech_init(KBDC kbdc, elantechhw_t *elanhw)
6789 {
6790 	int i, val, res, hwversion, reg10;
6791 
6792 	/* set absolute mode */
6793 	hwversion = elanhw->hwversion;
6794 	reg10 = -1;
6795 	switch (hwversion) {
6796 	case 2:
6797 		reg10 = elanhw->fwversion == 0x020030 ? 0x54 : 0xc4;
6798 		res = elantech_write_1(kbdc, hwversion, 0x10, reg10);
6799 		if (res)
6800 			break;
6801 		res = elantech_write_1(kbdc, hwversion, 0x11, 0x8A);
6802 		break;
6803 	case 3:
6804 		reg10 = 0x0b;
6805 		res = elantech_write_1(kbdc, hwversion, 0x10, reg10);
6806 		break;
6807 	case 4:
6808 		res = elantech_write_1(kbdc, hwversion, 0x07, 0x01);
6809 		break;
6810 	default:
6811 		res = 1;
6812 	}
6813 
6814 	/* Read back reg 0x10 to ensure hardware is ready. */
6815 	if (res == 0 && reg10 >= 0) {
6816 		for (i = 0; i < 5; i++) {
6817 			if (elantech_read_1(kbdc, hwversion, 0x10, &val) == 0)
6818 				break;
6819 			DELAY(2000);
6820 		}
6821 		if (i == 5)
6822 			res = 1;
6823 	}
6824 
6825 	if (res)
6826 		printf("couldn't set absolute mode\n");
6827 
6828 	return (res);
6829 }
6830 
6831 static void
6832 elantech_init_synaptics(struct psm_softc *sc)
6833 {
6834 
6835 	/* Set capabilites required by movement smother */
6836 	sc->synhw.infoMajor = sc->elanhw.hwversion;
6837 	sc->synhw.infoMinor = sc->elanhw.fwversion;
6838 	sc->synhw.infoXupmm = sc->elanhw.dpmmx;
6839 	sc->synhw.infoYupmm = sc->elanhw.dpmmy;
6840 	sc->synhw.verticalScroll = 0;
6841 	sc->synhw.nExtendedQueries = 4;
6842 	sc->synhw.capExtended = 1;
6843 	sc->synhw.capPassthrough = sc->elanhw.hastrackpoint;
6844 	sc->synhw.capClickPad = sc->elanhw.isclickpad;
6845 	sc->synhw.capMultiFinger = 1;
6846 	if (sc->elanhw.issemimt)
6847 		sc->synhw.capAdvancedGestures = 1;
6848 	else
6849 		sc->synhw.capReportsV = 1;
6850 	sc->synhw.capPalmDetect = 1;
6851 	sc->synhw.capPen = 0;
6852 	sc->synhw.capReportsMax = 1;
6853 	sc->synhw.maximumXCoord = sc->elanhw.sizex;
6854 	sc->synhw.maximumYCoord = sc->elanhw.sizey;
6855 	sc->synhw.capReportsMin = 1;
6856 	sc->synhw.minimumXCoord = 0;
6857 	sc->synhw.minimumYCoord = 0;
6858 
6859 	if (sc->syninfo.sysctl_tree == NULL) {
6860 		synaptics_sysctl_create_tree(sc, "elantech",
6861 		    "Elantech Touchpad");
6862 
6863 		/*
6864 		 * Adjust synaptic smoother tunables
6865 		 * 1. Disable finger detection pressure threshold. Unlike
6866 		 *    synaptics we assume the finger is acting when packet with
6867 		 *    its X&Y arrives not when pressure exceedes some threshold
6868 		 * 2. Disable unrelated features like margins and noisy areas
6869 		 * 3. Disable virtual scroll areas as 2nd finger is preferable
6870 		 * 4. For clickpads set bottom quarter as 42% - 16% - 42% sized
6871 		 *    softbuttons
6872 		 * 5. Scale down divisors and movement lengths by a factor of 3
6873 		 *    where 3 is Synaptics to Elantech (~2200/800) dpi ratio
6874 		 */
6875 
6876 		/* Set reporting range to be equal touchpad size */
6877 		sc->syninfo.max_x = sc->elanhw.sizex;
6878 		sc->syninfo.max_y = sc->elanhw.sizey;
6879 
6880 		/* Disable finger detection pressure threshold */
6881 		sc->syninfo.min_pressure = 1;
6882 
6883 		/* Adjust palm width to nearly match synaptics w=10 */
6884 		sc->syninfo.max_width = 7;
6885 
6886 		/* Elans often report double & triple taps as single event */
6887 		sc->syninfo.tap_min_queue = 1;
6888 
6889 		/* Use full area of touchpad */
6890 		sc->syninfo.margin_top = 0;
6891 		sc->syninfo.margin_right = 0;
6892 		sc->syninfo.margin_bottom = 0;
6893 		sc->syninfo.margin_left = 0;
6894 
6895 		/* Disable noisy area */
6896 		sc->syninfo.na_top = 0;
6897 		sc->syninfo.na_right = 0;
6898 		sc->syninfo.na_bottom = 0;
6899 		sc->syninfo.na_left = 0;
6900 
6901 		/* Tune divisors and movement lengths */
6902 		sc->syninfo.weight_len_squared = 200;
6903 		sc->syninfo.div_min = 3;
6904 		sc->syninfo.div_max = 6;
6905 		sc->syninfo.div_max_na = 10;
6906 		sc->syninfo.div_len = 30;
6907 		sc->syninfo.tap_max_delta = 25;
6908 
6909 		/* Disable virtual scrolling areas and tune its divisors */
6910 		sc->syninfo.vscroll_hor_area = 0;
6911 		sc->syninfo.vscroll_ver_area = 0;
6912 		sc->syninfo.vscroll_min_delta = 15;
6913 		sc->syninfo.vscroll_div_min = 30;
6914 		sc->syninfo.vscroll_div_max = 50;
6915 
6916 		/* Set bottom quarter as 42% - 16% - 42% sized softbuttons */
6917 		if (sc->elanhw.isclickpad) {
6918 			sc->syninfo.softbuttons_y = sc->elanhw.sizey / 4;
6919 			sc->syninfo.softbutton2_x = sc->elanhw.sizex * 11 / 25;
6920 			sc->syninfo.softbutton3_x = sc->elanhw.sizex * 14 / 25;
6921 		}
6922 	}
6923 
6924 	return;
6925 }
6926 
6927 static int
6928 enable_elantech(struct psm_softc *sc, enum probearg arg)
6929 {
6930 	static const int ic2hw[] =
6931 	/*IC: 0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f */
6932 	    { 0, 0, 2, 0, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0 };
6933 	static const int fw_sizes[][3] = {
6934 		/* FW.vers  MaxX  MaxY */
6935 		{ 0x020030, 1152,  768 },
6936 		{ 0x020800, 1152,  768 },
6937 		{ 0x020b00, 1152,  768 },
6938 		{ 0x040215,  900,  500 },
6939 		{ 0x040216,  819,  405 },
6940 		{ 0x040219,  900,  500 },
6941 	};
6942 	elantechhw_t elanhw;
6943 	int icversion, hwversion, xtr, i, id, resp[3], dpix, dpiy;
6944 	KBDC kbdc = sc->kbdc;
6945 
6946 	VLOG(3, (LOG_DEBUG, "elantech: BEGIN init\n"));
6947 
6948 	set_mouse_scaling(kbdc, 1);
6949 	set_mouse_scaling(kbdc, 1);
6950 	set_mouse_scaling(kbdc, 1);
6951 	if (get_mouse_status(kbdc, resp, 0, 3) != 3)
6952 		return (FALSE);
6953 
6954 	if (!ELANTECH_MAGIC(resp))
6955 		return (FALSE);
6956 
6957 	/* Identify the Touchpad version. */
6958 	if (elantech_cmd(kbdc, 2, ELANTECH_FW_VERSION, resp))
6959 		return (FALSE);
6960 
6961 	bzero(&elanhw, sizeof(elanhw));
6962 
6963 	elanhw.fwversion = (resp[0] << 16) | (resp[1] << 8) | resp[2];
6964 	icversion = resp[0] & 0x0f;
6965 	hwversion = ic2hw[icversion];
6966 
6967 	if (verbose >= 2)
6968 		printf("Elantech touchpad hardware v.%d firmware v.0x%06x\n",
6969 		    hwversion, elanhw.fwversion);
6970 
6971 	if (ELANTECH_HW_IS_V1(elanhw.fwversion)) {
6972 		printf ("  Unsupported touchpad hardware (v1)\n");
6973 		return (FALSE);
6974 	}
6975 	if (hwversion == 0) {
6976 		printf ("  Unknown touchpad hardware (firmware v.0x%06x)\n",
6977 		    elanhw.fwversion);
6978 		return (FALSE);
6979 	}
6980 
6981 	/* Get the Touchpad model information. */
6982 	elanhw.hwversion = hwversion;
6983 	elanhw.issemimt = hwversion == 2;
6984 	elanhw.isclickpad = (resp[1] & 0x10) != 0;
6985 	elanhw.hascrc = (resp[1] & 0x40) != 0;
6986 	elanhw.haspressure = elanhw.fwversion >= 0x020800;
6987 
6988 	/* Read the capability bits. */
6989 	if (elantech_cmd(kbdc, hwversion, ELANTECH_CAPABILITIES, resp) != 0) {
6990 		printf("  Failed to read capability bits\n");
6991 		return (FALSE);
6992 	}
6993 
6994 	elanhw.ntracesx = imax(resp[1], 3);
6995 	elanhw.ntracesy = imax(resp[2], 3);
6996 	elanhw.hastrackpoint = (resp[0] & 0x80) != 0;
6997 
6998 	/* Get the touchpad resolution */
6999 	switch (hwversion) {
7000 	case 4:
7001 		if (elantech_cmd(kbdc, hwversion, ELANTECH_RESOLUTION, resp)
7002 		    == 0) {
7003 			dpix = (resp[1] & 0x0f) * 10 + 790;
7004 			dpiy = ((resp[1] & 0xf0) >> 4) * 10 + 790;
7005 			elanhw.dpmmx = (dpix * 10 + 5) / 254;
7006 			elanhw.dpmmy = (dpiy * 10 + 5) / 254;
7007 			break;
7008 		}
7009 		/* FALLTHROUGH */
7010 	case 2:
7011 	case 3:
7012 		elanhw.dpmmx = elanhw.dpmmy = 32; /* 800 dpi */
7013 		break;
7014 	}
7015 
7016 	if (!elantech_support)
7017 		return (FALSE);
7018 
7019 	if (elantech_init(kbdc, &elanhw)) {
7020 		printf("couldn't initialize elantech touchpad\n");
7021 		return (FALSE);
7022 	}
7023 
7024 	/*
7025 	 * Get the touchpad reporting range.
7026 	 * On HW v.3 touchpads it should be done after switching hardware
7027 	 * to real resolution mode (by setting bit 3 of reg10)
7028 	 */
7029 	elanhw.dptracex = elanhw.dptracey = 64;
7030 	for (i = 0; i < nitems(fw_sizes); i++) {
7031 		if (elanhw.fwversion == fw_sizes[i][0]) {
7032 			elanhw.sizex = fw_sizes[i][1];
7033 			elanhw.sizey = fw_sizes[i][2];
7034 			goto found;
7035 		}
7036 	}
7037 	if (elantech_cmd(kbdc, hwversion, ELANTECH_FW_ID, resp) != 0) {
7038 		printf("  Failed to read touchpad size\n");
7039 		elanhw.sizex = 10000; /* Arbitrary high values to     */
7040 		elanhw.sizey = 10000; /* prevent clipping in smoother */
7041 	} else if (hwversion == 2) {
7042 		if ((elanhw.fwversion >> 16) == 0x14 && (resp[1] & 0x10) &&
7043 		    !elantech_cmd(kbdc, hwversion, ELANTECH_SAMPLE, resp)) {
7044 			elanhw.dptracex = resp[1] / 2;
7045 			elanhw.dptracey = resp[2] / 2;
7046 		}
7047 		xtr = ((elanhw.fwversion >> 8) == 0x0208) ? 1 : 2;
7048 		elanhw.sizex = (elanhw.ntracesx - xtr) * elanhw.dptracex;
7049 		elanhw.sizey = (elanhw.ntracesy - xtr) * elanhw.dptracey;
7050 	} else {
7051 		elanhw.sizex = (resp[0] & 0x0f) << 8 | resp[1];
7052 		elanhw.sizey = (resp[0] & 0xf0) << 4 | resp[2];
7053 		xtr = (elanhw.sizex % (elanhw.ntracesx - 2) == 0) ? 2 : 1;
7054 		elanhw.dptracex = elanhw.sizex / (elanhw.ntracesx - xtr);
7055 		elanhw.dptracey = elanhw.sizey / (elanhw.ntracesy - xtr);
7056 	}
7057 found:
7058 	if (verbose >= 2) {
7059 		printf("  Model information:\n");
7060 		printf("   MaxX:       %d\n", elanhw.sizex);
7061 		printf("   MaxY:       %d\n", elanhw.sizey);
7062 		printf("   DpmmX:      %d\n", elanhw.dpmmx);
7063 		printf("   DpmmY:      %d\n", elanhw.dpmmy);
7064 		printf("   TracesX:    %d\n", elanhw.ntracesx);
7065 		printf("   TracesY:    %d\n", elanhw.ntracesy);
7066 		printf("   DptraceX:   %d\n", elanhw.dptracex);
7067 		printf("   DptraceY:   %d\n", elanhw.dptracey);
7068 		printf("   SemiMT:     %d\n", elanhw.issemimt);
7069 		printf("   Clickpad:   %d\n", elanhw.isclickpad);
7070 		printf("   Trackpoint: %d\n", elanhw.hastrackpoint);
7071 		printf("   CRC:        %d\n", elanhw.hascrc);
7072 		printf("   Pressure:   %d\n", elanhw.haspressure);
7073 	}
7074 
7075 	VLOG(3, (LOG_DEBUG, "elantech: END init\n"));
7076 
7077 	if (arg == PROBE) {
7078 		sc->elanhw = elanhw;
7079 		sc->hw.buttons = 3;
7080 
7081 		/* Initialize synaptics movement smoother */
7082 		elantech_init_synaptics(sc);
7083 
7084 		for (id = 0; id < ELANTECH_MAX_FINGERS; id++)
7085 			PSM_FINGER_RESET(sc->elanaction.fingers[id]);
7086 	}
7087 
7088 	return (TRUE);
7089 }
7090 
7091 /*
7092  * Return true if 'now' is earlier than (start + (secs.usecs)).
7093  * Now may be NULL and the function will fetch the current time from
7094  * getmicrouptime(), or a cached 'now' can be passed in.
7095  * All values should be numbers derived from getmicrouptime().
7096  */
7097 static int
7098 timeelapsed(start, secs, usecs, now)
7099 	const struct timeval *start, *now;
7100 	int secs, usecs;
7101 {
7102 	struct timeval snow, tv;
7103 
7104 	/* if there is no 'now' passed in, the get it as a convience. */
7105 	if (now == NULL) {
7106 		getmicrouptime(&snow);
7107 		now = &snow;
7108 	}
7109 
7110 	tv.tv_sec = secs;
7111 	tv.tv_usec = usecs;
7112 	timevaladd(&tv, start);
7113 	return (timevalcmp(&tv, now, <));
7114 }
7115 
7116 static int
7117 psmresume(device_t dev)
7118 {
7119 	struct psm_softc *sc = device_get_softc(dev);
7120 	int unit = device_get_unit(dev);
7121 	int err;
7122 
7123 	VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit));
7124 
7125 	if ((sc->config &
7126 	    (PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND)) == 0)
7127 		return (0);
7128 
7129 	err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
7130 
7131 	if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
7132 		/*
7133 		 * Release the blocked process; it must be notified that
7134 		 * the device cannot be accessed anymore.
7135 		 */
7136 		sc->state &= ~PSM_ASLP;
7137 		wakeup(sc);
7138 	}
7139 
7140 	VLOG(2, (LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit));
7141 
7142 	return (err);
7143 }
7144 
7145 DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
7146 #ifdef EVDEV_SUPPORT
7147 MODULE_DEPEND(psm, evdev, 1, 1, 1);
7148 #endif
7149 
7150 #ifdef DEV_ISA
7151 
7152 /*
7153  * This sucks up assignments from PNPBIOS and ACPI.
7154  */
7155 
7156 /*
7157  * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
7158  * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
7159  * can be probed and attached only after the AT keyboard controller is
7160  * attached, we shall quietly reserve the IRQ resource for later use.
7161  * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
7162  * copy the IRQ resource to the PS/2 mouse device instance hanging
7163  * under the keyboard controller, then probe and attach it.
7164  */
7165 
7166 static	devclass_t			psmcpnp_devclass;
7167 
7168 static	device_probe_t			psmcpnp_probe;
7169 static	device_attach_t			psmcpnp_attach;
7170 
7171 static device_method_t psmcpnp_methods[] = {
7172 	DEVMETHOD(device_probe,		psmcpnp_probe),
7173 	DEVMETHOD(device_attach,	psmcpnp_attach),
7174 
7175 	{ 0, 0 }
7176 };
7177 
7178 static driver_t psmcpnp_driver = {
7179 	PSMCPNP_DRIVER_NAME,
7180 	psmcpnp_methods,
7181 	sizeof(struct psmcpnp_softc),
7182 };
7183 
7184 static struct isa_pnp_id psmcpnp_ids[] = {
7185 	{ 0x030fd041, "PS/2 mouse port" },		/* PNP0F03 */
7186 	{ 0x0e0fd041, "PS/2 mouse port" },		/* PNP0F0E */
7187 	{ 0x120fd041, "PS/2 mouse port" },		/* PNP0F12 */
7188 	{ 0x130fd041, "PS/2 mouse port" },		/* PNP0F13 */
7189 	{ 0x1303d041, "PS/2 port" },			/* PNP0313, XXX */
7190 	{ 0x02002e4f, "Dell PS/2 mouse port" },		/* Lat. X200, Dell */
7191 	{ 0x0002a906, "ALPS Glide Point" },		/* ALPS Glide Point */
7192 	{ 0x80374d24, "IBM PS/2 mouse port" },		/* IBM3780, ThinkPad */
7193 	{ 0x81374d24, "IBM PS/2 mouse port" },		/* IBM3781, ThinkPad */
7194 	{ 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
7195 	{ 0x0290d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9002, Vaio */
7196 	{ 0x0390d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9003, Vaio */
7197 	{ 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
7198 	{ 0 }
7199 };
7200 
7201 /* _HID list for quirk detection. Any device below has _CID from psmcpnp_ids */
7202 static struct isa_pnp_id forcepad_ids[] = {
7203 	{ 0x0d302e4f, "HP PS/2 forcepad port" },	/* SYN300D, EB 1040 */
7204 	{ 0x14302e4f, "HP PS/2 forcepad port" },	/* SYN3014, EB 1040 */
7205 	{ 0 }
7206 };
7207 
7208 /* List of HW v8.1 synaptics touchpads erroneously detected as HW v2.0 */
7209 static struct isa_pnp_id hpsyn81_ids[] = {
7210 	{ 0x9e012e4f, "HP PS/2 trackpad port" },	/* SYN019E, EB 9470 */
7211 	{ 0 }
7212 };
7213 
7214 static int
7215 create_a_copy(device_t atkbdc, device_t me)
7216 {
7217 	device_t psm;
7218 	u_long irq;
7219 
7220 	/* find the PS/2 mouse device instance under the keyboard controller */
7221 	psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
7222 	    device_get_unit(atkbdc));
7223 	if (psm == NULL)
7224 		return (ENXIO);
7225 	if (device_get_state(psm) != DS_NOTPRESENT)
7226 		return (0);
7227 
7228 	/* move our resource to the found device */
7229 	irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
7230 	bus_delete_resource(me, SYS_RES_IRQ, 0);
7231 	bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
7232 
7233 	/* ...then probe and attach it */
7234 	return (device_probe_and_attach(psm));
7235 }
7236 
7237 static int
7238 psmcpnp_probe(device_t dev)
7239 {
7240 	struct psmcpnp_softc *sc = device_get_softc(dev);
7241 	struct resource *res;
7242 	u_long irq;
7243 	int rid;
7244 
7245 	if (ISA_PNP_PROBE(device_get_parent(dev), dev, forcepad_ids) == 0)
7246 		sc->type = PSMCPNP_FORCEPAD;
7247 	else if(ISA_PNP_PROBE(device_get_parent(dev), dev, hpsyn81_ids) == 0)
7248 		sc->type = PSMCPNP_HPSYN81;
7249 	else if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids) == 0)
7250 		sc->type = PSMCPNP_GENERIC;
7251 	else
7252 		return (ENXIO);
7253 
7254 	/*
7255 	 * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
7256 	 * to the PS/2 mouse device node. But, some buggy PnP BIOS
7257 	 * declares the PS/2 mouse device node without an IRQ resource!
7258 	 * If this happens, we shall refer to device hints.
7259 	 * If we still don't find it there, use a hardcoded value... XXX
7260 	 */
7261 	rid = 0;
7262 	irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
7263 	if (irq <= 0) {
7264 		if (resource_long_value(PSM_DRIVER_NAME,
7265 		    device_get_unit(dev),"irq", &irq) != 0)
7266 			irq = 12;	/* XXX */
7267 		device_printf(dev, "irq resource info is missing; "
7268 		    "assuming irq %ld\n", irq);
7269 		bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
7270 	}
7271 	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, 0);
7272 	bus_release_resource(dev, SYS_RES_IRQ, rid, res);
7273 
7274 	/* keep quiet */
7275 	if (!bootverbose)
7276 		device_quiet(dev);
7277 
7278 	return ((res == NULL) ? ENXIO : 0);
7279 }
7280 
7281 static int
7282 psmcpnp_attach(device_t dev)
7283 {
7284 	device_t atkbdc;
7285 
7286 	/* find the keyboard controller, which may be on acpi* or isa* bus */
7287 	atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
7288 	    device_get_unit(dev));
7289 	if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED))
7290 		create_a_copy(atkbdc, dev);
7291 
7292 	return (0);
7293 }
7294 
7295 DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
7296 DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
7297 ISA_PNP_INFO(psmcpnp_ids);
7298 #endif /* DEV_ISA */
7299