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