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