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