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