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