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