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