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