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