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