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