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