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