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