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