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