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