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