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