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