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