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