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