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