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