psm.c revision 242820
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/9/sys/dev/atkbdc/psm.c 242820 2012-11-09 07:05:28Z hselasky $");
63
64#include "opt_isa.h"
65#include "opt_psm.h"
66
67#include <sys/param.h>
68#include <sys/systm.h>
69#include <sys/kernel.h>
70#include <sys/module.h>
71#include <sys/bus.h>
72#include <sys/conf.h>
73#include <sys/filio.h>
74#include <sys/poll.h>
75#include <sys/sigio.h>
76#include <sys/signalvar.h>
77#include <sys/syslog.h>
78#include <machine/bus.h>
79#include <sys/rman.h>
80#include <sys/selinfo.h>
81#include <sys/sysctl.h>
82#include <sys/time.h>
83#include <sys/uio.h>
84
85#include <sys/limits.h>
86#include <sys/mouse.h>
87#include <machine/resource.h>
88
89#ifdef DEV_ISA
90#include <isa/isavar.h>
91#endif
92
93#include <dev/atkbdc/atkbdcreg.h>
94#include <dev/atkbdc/psm.h>
95
96/*
97 * Driver specific options: the following options may be set by
98 * `options' statements in the kernel configuration file.
99 */
100
101/* debugging */
102#ifndef PSM_DEBUG
103#define	PSM_DEBUG	0	/*
104				 * logging: 0: none, 1: brief, 2: verbose
105				 *          3: sync errors, 4: all packets
106				 */
107#endif
108#define	VLOG(level, args)	do {	\
109	if (verbose >= level)		\
110		log args;		\
111} while (0)
112
113#ifndef PSM_INPUT_TIMEOUT
114#define	PSM_INPUT_TIMEOUT	2000000	/* 2 sec */
115#endif
116
117#ifndef PSM_TAP_TIMEOUT
118#define	PSM_TAP_TIMEOUT		125000
119#endif
120
121#ifndef PSM_TAP_THRESHOLD
122#define	PSM_TAP_THRESHOLD	25
123#endif
124
125/* end of driver specific options */
126
127#define	PSMCPNP_DRIVER_NAME	"psmcpnp"
128
129/* input queue */
130#define	PSM_BUFSIZE		960
131#define	PSM_SMALLBUFSIZE	240
132
133/* operation levels */
134#define	PSM_LEVEL_BASE		0
135#define	PSM_LEVEL_STANDARD	1
136#define	PSM_LEVEL_NATIVE	2
137#define	PSM_LEVEL_MIN		PSM_LEVEL_BASE
138#define	PSM_LEVEL_MAX		PSM_LEVEL_NATIVE
139
140/* Logitech PS2++ protocol */
141#define	MOUSE_PS2PLUS_CHECKBITS(b)	\
142    ((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
143#define	MOUSE_PS2PLUS_PACKET_TYPE(b)	\
144    (((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
145
146/* ring buffer */
147typedef struct ringbuf {
148	int		count;	/* # of valid elements in the buffer */
149	int		head;	/* head pointer */
150	int		tail;	/* tail poiner */
151	u_char buf[PSM_BUFSIZE];
152} ringbuf_t;
153
154/* data buffer */
155typedef struct packetbuf {
156	u_char	ipacket[16];	/* interim input buffer */
157	int	inputbytes;	/* # of bytes in the input buffer */
158} packetbuf_t;
159
160#ifndef PSM_PACKETQUEUE
161#define	PSM_PACKETQUEUE	128
162#endif
163
164enum {
165	SYNAPTICS_SYSCTL_MIN_PRESSURE,
166	SYNAPTICS_SYSCTL_MAX_PRESSURE,
167	SYNAPTICS_SYSCTL_MAX_WIDTH,
168	SYNAPTICS_SYSCTL_MARGIN_TOP,
169	SYNAPTICS_SYSCTL_MARGIN_RIGHT,
170	SYNAPTICS_SYSCTL_MARGIN_BOTTOM,
171	SYNAPTICS_SYSCTL_MARGIN_LEFT,
172	SYNAPTICS_SYSCTL_NA_TOP,
173	SYNAPTICS_SYSCTL_NA_RIGHT,
174	SYNAPTICS_SYSCTL_NA_BOTTOM,
175	SYNAPTICS_SYSCTL_NA_LEFT,
176	SYNAPTICS_SYSCTL_WINDOW_MIN,
177	SYNAPTICS_SYSCTL_WINDOW_MAX,
178	SYNAPTICS_SYSCTL_MULTIPLICATOR,
179	SYNAPTICS_SYSCTL_WEIGHT_CURRENT,
180	SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS,
181	SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA,
182	SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED,
183	SYNAPTICS_SYSCTL_DIV_MIN,
184	SYNAPTICS_SYSCTL_DIV_MAX,
185	SYNAPTICS_SYSCTL_DIV_MAX_NA,
186	SYNAPTICS_SYSCTL_DIV_LEN,
187	SYNAPTICS_SYSCTL_TAP_MAX_DELTA,
188	SYNAPTICS_SYSCTL_TAP_MIN_QUEUE,
189	SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT,
190	SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA,
191	SYNAPTICS_SYSCTL_VSCROLL_VER_AREA,
192	SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA,
193	SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN,
194	SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX
195};
196
197typedef struct synapticsinfo {
198	struct sysctl_ctx_list	 sysctl_ctx;
199	struct sysctl_oid	*sysctl_tree;
200	int			 directional_scrolls;
201	int			 min_pressure;
202	int			 max_pressure;
203	int			 max_width;
204	int			 margin_top;
205	int			 margin_right;
206	int			 margin_bottom;
207	int			 margin_left;
208	int			 na_top;
209	int			 na_right;
210	int			 na_bottom;
211	int			 na_left;
212	int			 window_min;
213	int			 window_max;
214	int			 multiplicator;
215	int			 weight_current;
216	int			 weight_previous;
217	int			 weight_previous_na;
218	int			 weight_len_squared;
219	int			 div_min;
220	int			 div_max;
221	int			 div_max_na;
222	int			 div_len;
223	int			 tap_max_delta;
224	int			 tap_min_queue;
225	int			 taphold_timeout;
226	int			 vscroll_ver_area;
227	int			 vscroll_hor_area;
228	int			 vscroll_min_delta;
229	int			 vscroll_div_min;
230	int			 vscroll_div_max;
231} synapticsinfo_t;
232
233typedef struct synapticspacket {
234	int			x;
235	int			y;
236} synapticspacket_t;
237
238#define	SYNAPTICS_PACKETQUEUE 10
239#define SYNAPTICS_QUEUE_CURSOR(x)					\
240	(x + SYNAPTICS_PACKETQUEUE) % SYNAPTICS_PACKETQUEUE
241
242typedef struct synapticsaction {
243	synapticspacket_t	queue[SYNAPTICS_PACKETQUEUE];
244	int			queue_len;
245	int			queue_cursor;
246	int			window_min;
247	int			start_x;
248	int			start_y;
249	int			avg_dx;
250	int			avg_dy;
251	int			squelch_x;
252	int			squelch_y;
253	int			fingers_nb;
254	int			tap_button;
255	int			in_taphold;
256	int			in_vscroll;
257} synapticsaction_t;
258
259/* driver control block */
260struct psm_softc {		/* Driver status information */
261	int		unit;
262	struct selinfo	rsel;		/* Process selecting for Input */
263	u_char		state;		/* Mouse driver state */
264	int		config;		/* driver configuration flags */
265	int		flags;		/* other flags */
266	KBDC		kbdc;		/* handle to access kbd controller */
267	struct resource	*intr;		/* IRQ resource */
268	void		*ih;		/* interrupt handle */
269	mousehw_t	hw;		/* hardware information */
270	synapticshw_t	synhw;		/* Synaptics hardware information */
271	synapticsinfo_t	syninfo;	/* Synaptics configuration */
272	synapticsaction_t synaction;	/* Synaptics action context */
273	mousemode_t	mode;		/* operation mode */
274	mousemode_t	dflt_mode;	/* default operation mode */
275	mousestatus_t	status;		/* accumulated mouse movement */
276	ringbuf_t	queue;		/* mouse status queue */
277	packetbuf_t	pqueue[PSM_PACKETQUEUE]; /* mouse data queue */
278	int		pqueue_start;	/* start of data in queue */
279	int		pqueue_end;	/* end of data in queue */
280	int		button;		/* the latest button state */
281	int		xold;		/* previous absolute X position */
282	int		yold;		/* previous absolute Y position */
283	int		xaverage;	/* average X position */
284	int		yaverage;	/* average Y position */
285	int		squelch; /* level to filter movement at low speed */
286	int		zmax;	/* maximum pressure value for touchpads */
287	int		syncerrors; /* # of bytes discarded to synchronize */
288	int		pkterrors;  /* # of packets failed during quaranteen. */
289	struct timeval	inputtimeout;
290	struct timeval	lastsoftintr;	/* time of last soft interrupt */
291	struct timeval	lastinputerr;	/* time last sync error happened */
292	struct timeval	taptimeout;	/* tap timeout for touchpads */
293	int		watchdog;	/* watchdog timer flag */
294	struct callout_handle callout;	/* watchdog timer call out */
295	struct callout_handle softcallout; /* buffer timer call out */
296	struct cdev	*dev;
297	struct cdev	*bdev;
298	int		lasterr;
299	int		cmdcount;
300	struct sigio	*async;		/* Processes waiting for SIGIO */
301};
302static devclass_t psm_devclass;
303
304/* driver state flags (state) */
305#define	PSM_VALID		0x80
306#define	PSM_OPEN		1	/* Device is open */
307#define	PSM_ASLP		2	/* Waiting for mouse data */
308#define	PSM_SOFTARMED		4	/* Software interrupt armed */
309#define	PSM_NEED_SYNCBITS	8	/* Set syncbits using next data pkt */
310
311/* driver configuration flags (config) */
312#define	PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
313#define	PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
314#define	PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
315#define	PSM_CONFIG_NOIDPROBE	0x0200  /* disable mouse model probe */
316#define	PSM_CONFIG_NORESET	0x0400  /* don't reset the mouse */
317#define	PSM_CONFIG_FORCETAP	0x0800  /* assume `tap' action exists */
318#define	PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
319#define	PSM_CONFIG_HOOKRESUME	0x2000	/* hook the system resume event */
320#define	PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
321
322#define	PSM_CONFIG_FLAGS	\
323    (PSM_CONFIG_RESOLUTION |	\
324    PSM_CONFIG_ACCEL |		\
325    PSM_CONFIG_NOCHECKSYNC |	\
326    PSM_CONFIG_NOIDPROBE |	\
327    PSM_CONFIG_NORESET |	\
328    PSM_CONFIG_FORCETAP |	\
329    PSM_CONFIG_IGNPORTERROR |	\
330    PSM_CONFIG_HOOKRESUME |	\
331    PSM_CONFIG_INITAFTERSUSPEND)
332
333/* other flags (flags) */
334#define	PSM_FLAGS_FINGERDOWN	0x0001	/* VersaPad finger down */
335
336/* Tunables */
337static int tap_enabled = -1;
338TUNABLE_INT("hw.psm.tap_enabled", &tap_enabled);
339
340static int synaptics_support = 0;
341TUNABLE_INT("hw.psm.synaptics_support", &synaptics_support);
342
343static int verbose = PSM_DEBUG;
344TUNABLE_INT("debug.psm.loglevel", &verbose);
345
346/* for backward compatibility */
347#define	OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
348#define	OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
349#define	OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)
350
351typedef struct old_mousehw {
352	int	buttons;
353	int	iftype;
354	int	type;
355	int	hwid;
356} old_mousehw_t;
357
358typedef struct old_mousemode {
359	int	protocol;
360	int	rate;
361	int	resolution;
362	int	accelfactor;
363} old_mousemode_t;
364
365/* packet formatting function */
366typedef int	packetfunc_t(struct psm_softc *, u_char *, int *, int,
367    mousestatus_t *);
368
369/* function prototypes */
370static void	psmidentify(driver_t *, device_t);
371static int	psmprobe(device_t);
372static int	psmattach(device_t);
373static int	psmdetach(device_t);
374static int	psmresume(device_t);
375
376static d_open_t		psmopen;
377static d_close_t	psmclose;
378static d_read_t		psmread;
379static d_write_t	psmwrite;
380static d_ioctl_t	psmioctl;
381static d_poll_t		psmpoll;
382
383static int	enable_aux_dev(KBDC);
384static int	disable_aux_dev(KBDC);
385static int	get_mouse_status(KBDC, int *, int, int);
386static int	get_aux_id(KBDC);
387static int	set_mouse_sampling_rate(KBDC, int);
388static int	set_mouse_scaling(KBDC, int);
389static int	set_mouse_resolution(KBDC, int);
390static int	set_mouse_mode(KBDC);
391static int	get_mouse_buttons(KBDC);
392static int	is_a_mouse(int);
393static void	recover_from_error(KBDC);
394static int	restore_controller(KBDC, int);
395static int	doinitialize(struct psm_softc *, mousemode_t *);
396static int	doopen(struct psm_softc *, int);
397static int	reinitialize(struct psm_softc *, int);
398static char	*model_name(int);
399static void	psmsoftintr(void *);
400static void	psmintr(void *);
401static void	psmtimeout(void *);
402static int	timeelapsed(const struct timeval *, int, int,
403		    const struct timeval *);
404static void	dropqueue(struct psm_softc *);
405static void	flushpackets(struct psm_softc *);
406static void	proc_mmanplus(struct psm_softc *, packetbuf_t *,
407		    mousestatus_t *, int *, int *, int *);
408static int	proc_synaptics(struct psm_softc *, packetbuf_t *,
409		    mousestatus_t *, int *, int *, int *);
410static void	proc_versapad(struct psm_softc *, packetbuf_t *,
411		    mousestatus_t *, int *, int *, int *);
412static int	tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *,
413		    u_char *);
414
415/* vendor specific features */
416typedef int	probefunc_t(KBDC, struct psm_softc *);
417
418static int	mouse_id_proc1(KBDC, int, int, int *);
419static int	mouse_ext_command(KBDC, int);
420
421static probefunc_t	enable_groller;
422static probefunc_t	enable_gmouse;
423static probefunc_t	enable_aglide;
424static probefunc_t	enable_kmouse;
425static probefunc_t	enable_msexplorer;
426static probefunc_t	enable_msintelli;
427static probefunc_t	enable_4dmouse;
428static probefunc_t	enable_4dplus;
429static probefunc_t	enable_mmanplus;
430static probefunc_t	enable_synaptics;
431static probefunc_t	enable_versapad;
432
433static struct {
434	int		model;
435	u_char		syncmask;
436	int		packetsize;
437	probefunc_t	*probefunc;
438} vendortype[] = {
439	/*
440	 * WARNING: the order of probe is very important.  Don't mess it
441	 * unless you know what you are doing.
442	 */
443	{ MOUSE_MODEL_NET,		/* Genius NetMouse */
444	  0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse },
445	{ MOUSE_MODEL_NETSCROLL,	/* Genius NetScroll */
446	  0xc8, 6, enable_groller },
447	{ MOUSE_MODEL_MOUSEMANPLUS,	/* Logitech MouseMan+ */
448	  0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus },
449	{ MOUSE_MODEL_EXPLORER,		/* Microsoft IntelliMouse Explorer */
450	  0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer },
451	{ MOUSE_MODEL_4D,		/* A4 Tech 4D Mouse */
452	  0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse },
453	{ MOUSE_MODEL_4DPLUS,		/* A4 Tech 4D+ Mouse */
454	  0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus },
455	{ MOUSE_MODEL_SYNAPTICS,	/* Synaptics Touchpad */
456	  0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics },
457	{ MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
458	  0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli },
459	{ MOUSE_MODEL_GLIDEPOINT,	/* ALPS GlidePoint */
460	  0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide },
461	{ MOUSE_MODEL_THINK,		/* Kensington ThinkingMouse */
462	  0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse },
463	{ MOUSE_MODEL_VERSAPAD,		/* Interlink electronics VersaPad */
464	  0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad },
465	{ MOUSE_MODEL_GENERIC,
466	  0xc0, MOUSE_PS2_PACKETSIZE, NULL },
467};
468#define	GENERIC_MOUSE_ENTRY	\
469    ((sizeof(vendortype) / sizeof(*vendortype)) - 1)
470
471/* device driver declarateion */
472static device_method_t psm_methods[] = {
473	/* Device interface */
474	DEVMETHOD(device_identify,	psmidentify),
475	DEVMETHOD(device_probe,		psmprobe),
476	DEVMETHOD(device_attach,	psmattach),
477	DEVMETHOD(device_detach,	psmdetach),
478	DEVMETHOD(device_resume,	psmresume),
479
480	{ 0, 0 }
481};
482
483static driver_t psm_driver = {
484	PSM_DRIVER_NAME,
485	psm_methods,
486	sizeof(struct psm_softc),
487};
488
489static struct cdevsw psm_cdevsw = {
490	.d_version =	D_VERSION,
491	.d_flags =	D_NEEDGIANT,
492	.d_open =	psmopen,
493	.d_close =	psmclose,
494	.d_read =	psmread,
495	.d_write =	psmwrite,
496	.d_ioctl =	psmioctl,
497	.d_poll =	psmpoll,
498	.d_name =	PSM_DRIVER_NAME,
499};
500
501/* device I/O routines */
502static int
503enable_aux_dev(KBDC kbdc)
504{
505	int res;
506
507	res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
508	VLOG(2, (LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res));
509
510	return (res == PSM_ACK);
511}
512
513static int
514disable_aux_dev(KBDC kbdc)
515{
516	int res;
517
518	res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
519	VLOG(2, (LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res));
520
521	return (res == PSM_ACK);
522}
523
524static int
525get_mouse_status(KBDC kbdc, int *status, int flag, int len)
526{
527	int cmd;
528	int res;
529	int i;
530
531	switch (flag) {
532	case 0:
533	default:
534		cmd = PSMC_SEND_DEV_STATUS;
535		break;
536	case 1:
537		cmd = PSMC_SEND_DEV_DATA;
538		break;
539	}
540	empty_aux_buffer(kbdc, 5);
541	res = send_aux_command(kbdc, cmd);
542	VLOG(2, (LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
543	    (flag == 1) ? "DATA" : "STATUS", res));
544	if (res != PSM_ACK)
545		return (0);
546
547	for (i = 0; i < len; ++i) {
548		status[i] = read_aux_data(kbdc);
549		if (status[i] < 0)
550			break;
551	}
552
553	VLOG(1, (LOG_DEBUG, "psm: %s %02x %02x %02x\n",
554	    (flag == 1) ? "data" : "status", status[0], status[1], status[2]));
555
556	return (i);
557}
558
559static int
560get_aux_id(KBDC kbdc)
561{
562	int res;
563	int id;
564
565	empty_aux_buffer(kbdc, 5);
566	res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
567	VLOG(2, (LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res));
568	if (res != PSM_ACK)
569		return (-1);
570
571	/* 10ms delay */
572	DELAY(10000);
573
574	id = read_aux_data(kbdc);
575	VLOG(2, (LOG_DEBUG, "psm: device ID: %04x\n", id));
576
577	return (id);
578}
579
580static int
581set_mouse_sampling_rate(KBDC kbdc, int rate)
582{
583	int res;
584
585	res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
586	VLOG(2, (LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res));
587
588	return ((res == PSM_ACK) ? rate : -1);
589}
590
591static int
592set_mouse_scaling(KBDC kbdc, int scale)
593{
594	int res;
595
596	switch (scale) {
597	case 1:
598	default:
599		scale = PSMC_SET_SCALING11;
600		break;
601	case 2:
602		scale = PSMC_SET_SCALING21;
603		break;
604	}
605	res = send_aux_command(kbdc, scale);
606	VLOG(2, (LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
607	    (scale == PSMC_SET_SCALING21) ? "21" : "11", res));
608
609	return (res == PSM_ACK);
610}
611
612/* `val' must be 0 through PSMD_MAX_RESOLUTION */
613static int
614set_mouse_resolution(KBDC kbdc, int val)
615{
616	int res;
617
618	res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
619	VLOG(2, (LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res));
620
621	return ((res == PSM_ACK) ? val : -1);
622}
623
624/*
625 * NOTE: once `set_mouse_mode()' is called, the mouse device must be
626 * re-enabled by calling `enable_aux_dev()'
627 */
628static int
629set_mouse_mode(KBDC kbdc)
630{
631	int res;
632
633	res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
634	VLOG(2, (LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res));
635
636	return (res == PSM_ACK);
637}
638
639static int
640get_mouse_buttons(KBDC kbdc)
641{
642	int c = 2;		/* assume two buttons by default */
643	int status[3];
644
645	/*
646	 * NOTE: a special sequence to obtain Logitech Mouse specific
647	 * information: set resolution to 25 ppi, set scaling to 1:1, set
648	 * scaling to 1:1, set scaling to 1:1. Then the second byte of the
649	 * mouse status bytes is the number of available buttons.
650	 * Some manufactures also support this sequence.
651	 */
652	if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
653		return (c);
654	if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1) &&
655	    set_mouse_scaling(kbdc, 1) &&
656	    get_mouse_status(kbdc, status, 0, 3) >= 3 && status[1] != 0)
657		return (status[1]);
658	return (c);
659}
660
661/* misc subroutines */
662/*
663 * Someday, I will get the complete list of valid pointing devices and
664 * their IDs... XXX
665 */
666static int
667is_a_mouse(int id)
668{
669#if 0
670	static int valid_ids[] = {
671		PSM_MOUSE_ID,		/* mouse */
672		PSM_BALLPOINT_ID,	/* ballpoint device */
673		PSM_INTELLI_ID,		/* Intellimouse */
674		PSM_EXPLORER_ID,	/* Intellimouse Explorer */
675		-1			/* end of table */
676	};
677	int i;
678
679	for (i = 0; valid_ids[i] >= 0; ++i)
680	if (valid_ids[i] == id)
681		return (TRUE);
682	return (FALSE);
683#else
684	return (TRUE);
685#endif
686}
687
688static char *
689model_name(int model)
690{
691	static struct {
692		int	model_code;
693		char	*model_name;
694	} models[] = {
695		{ MOUSE_MODEL_NETSCROLL,	"NetScroll" },
696		{ MOUSE_MODEL_NET,		"NetMouse/NetScroll Optical" },
697		{ MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
698		{ MOUSE_MODEL_THINK,		"ThinkingMouse" },
699		{ MOUSE_MODEL_INTELLI,		"IntelliMouse" },
700		{ MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
701		{ MOUSE_MODEL_VERSAPAD,		"VersaPad" },
702		{ MOUSE_MODEL_EXPLORER,		"IntelliMouse Explorer" },
703		{ MOUSE_MODEL_4D,		"4D Mouse" },
704		{ MOUSE_MODEL_4DPLUS,		"4D+ Mouse" },
705		{ MOUSE_MODEL_SYNAPTICS,	"Synaptics Touchpad" },
706		{ MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
707		{ MOUSE_MODEL_UNKNOWN,		"Unknown" },
708	};
709	int i;
710
711	for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i)
712		if (models[i].model_code == model)
713			break;
714	return (models[i].model_name);
715}
716
717static void
718recover_from_error(KBDC kbdc)
719{
720	/* discard anything left in the output buffer */
721	empty_both_buffers(kbdc, 10);
722
723#if 0
724	/*
725	 * NOTE: KBDC_RESET_KBD may not restore the communication between the
726	 * keyboard and the controller.
727	 */
728	reset_kbd(kbdc);
729#else
730	/*
731	 * NOTE: somehow diagnostic and keyboard port test commands bring the
732	 * keyboard back.
733	 */
734	if (!test_controller(kbdc))
735		log(LOG_ERR, "psm: keyboard controller failed.\n");
736	/* if there isn't a keyboard in the system, the following error is OK */
737	if (test_kbd_port(kbdc) != 0)
738		VLOG(1, (LOG_ERR, "psm: keyboard port failed.\n"));
739#endif
740}
741
742static int
743restore_controller(KBDC kbdc, int command_byte)
744{
745	empty_both_buffers(kbdc, 10);
746
747	if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
748		log(LOG_ERR, "psm: failed to restore the keyboard controller "
749		    "command byte.\n");
750		empty_both_buffers(kbdc, 10);
751		return (FALSE);
752	} else {
753		empty_both_buffers(kbdc, 10);
754		return (TRUE);
755	}
756}
757
758/*
759 * Re-initialize the aux port and device. The aux port must be enabled
760 * and its interrupt must be disabled before calling this routine.
761 * The aux device will be disabled before returning.
762 * The keyboard controller must be locked via `kbdc_lock()' before
763 * calling this routine.
764 */
765static int
766doinitialize(struct psm_softc *sc, mousemode_t *mode)
767{
768	KBDC kbdc = sc->kbdc;
769	int stat[3];
770	int i;
771
772	switch((i = test_aux_port(kbdc))) {
773	case 1:	/* ignore these errors */
774	case 2:
775	case 3:
776	case PSM_ACK:
777		if (verbose)
778			log(LOG_DEBUG,
779			    "psm%d: strange result for test aux port (%d).\n",
780			    sc->unit, i);
781		/* FALLTHROUGH */
782	case 0:		/* no error */
783		break;
784	case -1:	/* time out */
785	default:	/* error */
786		recover_from_error(kbdc);
787		if (sc->config & PSM_CONFIG_IGNPORTERROR)
788			break;
789		log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
790		    sc->unit, i);
791		return (FALSE);
792	}
793
794	if (sc->config & PSM_CONFIG_NORESET) {
795		/*
796		 * Don't try to reset the pointing device.  It may possibly
797		 * be left in the unknown state, though...
798		 */
799	} else {
800		/*
801		 * NOTE: some controllers appears to hang the `keyboard' when
802		 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
803		 */
804		if (!reset_aux_dev(kbdc)) {
805			recover_from_error(kbdc);
806			log(LOG_ERR, "psm%d: failed to reset the aux device.\n",
807			    sc->unit);
808			return (FALSE);
809		}
810	}
811
812	/*
813	 * both the aux port and the aux device is functioning, see
814	 * if the device can be enabled.
815	 */
816	if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
817		log(LOG_ERR, "psm%d: failed to enable the aux device.\n",
818		    sc->unit);
819		return (FALSE);
820	}
821	empty_both_buffers(kbdc, 10);	/* remove stray data if any */
822
823	/* Re-enable the mouse. */
824	for (i = 0; vendortype[i].probefunc != NULL; ++i)
825		if (vendortype[i].model == sc->hw.model)
826			(*vendortype[i].probefunc)(sc->kbdc, NULL);
827
828	/* set mouse parameters */
829	if (mode != (mousemode_t *)NULL) {
830		if (mode->rate > 0)
831			mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
832		if (mode->resolution >= 0)
833			mode->resolution =
834			    set_mouse_resolution(kbdc, mode->resolution);
835		set_mouse_scaling(kbdc, 1);
836		set_mouse_mode(kbdc);
837	}
838
839	/* Record sync on the next data packet we see. */
840	sc->flags |= PSM_NEED_SYNCBITS;
841
842	/* just check the status of the mouse */
843	if (get_mouse_status(kbdc, stat, 0, 3) < 3)
844		log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
845		    sc->unit);
846
847	return (TRUE);
848}
849
850static int
851doopen(struct psm_softc *sc, int command_byte)
852{
853	int stat[3];
854
855	/*
856	 * FIXME: Synaptics TouchPad seems to go back to Relative Mode with
857	 * no obvious reason. Thus we check the current mode and restore the
858	 * Absolute Mode if it was cleared.
859	 *
860	 * The previous hack at the end of psmprobe() wasn't efficient when
861	 * moused(8) was restarted.
862	 *
863	 * A Reset (FF) or Set Defaults (F6) command would clear the
864	 * Absolute Mode bit. But a verbose boot or debug.psm.loglevel=5
865	 * doesn't show any evidence of such a command.
866	 */
867	if (sc->hw.model == MOUSE_MODEL_SYNAPTICS) {
868		mouse_ext_command(sc->kbdc, 1);
869		get_mouse_status(sc->kbdc, stat, 0, 3);
870		if (stat[1] == 0x47 && stat[2] == 0x40) {
871			/* Set the mode byte -- request wmode where
872			 * available */
873			if (sc->synhw.capExtended)
874				mouse_ext_command(sc->kbdc, 0xc1);
875			else
876				mouse_ext_command(sc->kbdc, 0xc0);
877			set_mouse_sampling_rate(sc->kbdc, 20);
878			VLOG(5, (LOG_DEBUG, "psm%d: Synaptis Absolute Mode "
879			    "hopefully restored\n",
880			    sc->unit));
881		}
882	}
883
884	/*
885	 * A user may want to disable tap and drag gestures on a Synaptics
886	 * TouchPad when it operates in Relative Mode.
887	 */
888	if (sc->hw.model == MOUSE_MODEL_GENERIC) {
889		if (tap_enabled > 0) {
890			/*
891			 * Enable tap & drag gestures. We use a Mode Byte
892			 * and clear the DisGest bit (see ��2.5 of Synaptics
893			 * TouchPad Interfacing Guide).
894			 */
895			VLOG(2, (LOG_DEBUG,
896			    "psm%d: enable tap and drag gestures\n",
897			    sc->unit));
898			mouse_ext_command(sc->kbdc, 0x00);
899			set_mouse_sampling_rate(sc->kbdc, 20);
900		} else if (tap_enabled == 0) {
901			/*
902			 * Disable tap & drag gestures. We use a Mode Byte
903			 * and set the DisGest bit (see ��2.5 of Synaptics
904			 * TouchPad Interfacing Guide).
905			 */
906			VLOG(2, (LOG_DEBUG,
907			    "psm%d: disable tap and drag gestures\n",
908			    sc->unit));
909			mouse_ext_command(sc->kbdc, 0x04);
910			set_mouse_sampling_rate(sc->kbdc, 20);
911		}
912	}
913
914	/* enable the mouse device */
915	if (!enable_aux_dev(sc->kbdc)) {
916		/* MOUSE ERROR: failed to enable the mouse because:
917		 * 1) the mouse is faulty,
918		 * 2) the mouse has been removed(!?)
919		 * In the latter case, the keyboard may have hung, and need
920		 * recovery procedure...
921		 */
922		recover_from_error(sc->kbdc);
923#if 0
924		/* FIXME: we could reset the mouse here and try to enable
925		 * it again. But it will take long time and it's not a good
926		 * idea to disable the keyboard that long...
927		 */
928		if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
929			recover_from_error(sc->kbdc);
930#else
931		{
932#endif
933			restore_controller(sc->kbdc, command_byte);
934			/* mark this device is no longer available */
935			sc->state &= ~PSM_VALID;
936			log(LOG_ERR,
937			    "psm%d: failed to enable the device (doopen).\n",
938			sc->unit);
939			return (EIO);
940		}
941	}
942
943	if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
944		log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n",
945		    sc->unit);
946
947	/* enable the aux port and interrupt */
948	if (!set_controller_command_byte(sc->kbdc,
949	    kbdc_get_device_mask(sc->kbdc),
950	    (command_byte & KBD_KBD_CONTROL_BITS) |
951	    KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
952		/* CONTROLLER ERROR */
953		disable_aux_dev(sc->kbdc);
954		restore_controller(sc->kbdc, command_byte);
955		log(LOG_ERR,
956		    "psm%d: failed to enable the aux interrupt (doopen).\n",
957		    sc->unit);
958		return (EIO);
959	}
960
961	/* start the watchdog timer */
962	sc->watchdog = FALSE;
963	sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz*2);
964
965	return (0);
966}
967
968static int
969reinitialize(struct psm_softc *sc, int doinit)
970{
971	int err;
972	int c;
973	int s;
974
975	/* don't let anybody mess with the aux device */
976	if (!kbdc_lock(sc->kbdc, TRUE))
977		return (EIO);
978	s = spltty();
979
980	/* block our watchdog timer */
981	sc->watchdog = FALSE;
982	untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
983	callout_handle_init(&sc->callout);
984
985	/* save the current controller command byte */
986	empty_both_buffers(sc->kbdc, 10);
987	c = get_controller_command_byte(sc->kbdc);
988	VLOG(2, (LOG_DEBUG,
989	    "psm%d: current command byte: %04x (reinitialize).\n",
990	    sc->unit, c));
991
992	/* enable the aux port but disable the aux interrupt and the keyboard */
993	if ((c == -1) || !set_controller_command_byte(sc->kbdc,
994	    kbdc_get_device_mask(sc->kbdc),
995	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
996	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
997		/* CONTROLLER ERROR */
998		splx(s);
999		kbdc_lock(sc->kbdc, FALSE);
1000		log(LOG_ERR,
1001		    "psm%d: unable to set the command byte (reinitialize).\n",
1002		    sc->unit);
1003		return (EIO);
1004	}
1005
1006	/* flush any data */
1007	if (sc->state & PSM_VALID) {
1008		/* this may fail; but never mind... */
1009		disable_aux_dev(sc->kbdc);
1010		empty_aux_buffer(sc->kbdc, 10);
1011	}
1012	flushpackets(sc);
1013	sc->syncerrors = 0;
1014	sc->pkterrors = 0;
1015	memset(&sc->lastinputerr, 0, sizeof(sc->lastinputerr));
1016
1017	/* try to detect the aux device; are you still there? */
1018	err = 0;
1019	if (doinit) {
1020		if (doinitialize(sc, &sc->mode)) {
1021			/* yes */
1022			sc->state |= PSM_VALID;
1023		} else {
1024			/* the device has gone! */
1025			restore_controller(sc->kbdc, c);
1026			sc->state &= ~PSM_VALID;
1027			log(LOG_ERR,
1028			    "psm%d: the aux device has gone! (reinitialize).\n",
1029			    sc->unit);
1030			err = ENXIO;
1031		}
1032	}
1033	splx(s);
1034
1035	/* restore the driver state */
1036	if ((sc->state & PSM_OPEN) && (err == 0)) {
1037		/* enable the aux device and the port again */
1038		err = doopen(sc, c);
1039		if (err != 0)
1040			log(LOG_ERR, "psm%d: failed to enable the device "
1041			    "(reinitialize).\n", sc->unit);
1042	} else {
1043		/* restore the keyboard port and disable the aux port */
1044		if (!set_controller_command_byte(sc->kbdc,
1045		    kbdc_get_device_mask(sc->kbdc),
1046		    (c & KBD_KBD_CONTROL_BITS) |
1047		    KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1048			/* CONTROLLER ERROR */
1049			log(LOG_ERR, "psm%d: failed to disable the aux port "
1050			    "(reinitialize).\n", sc->unit);
1051			err = EIO;
1052		}
1053	}
1054
1055	kbdc_lock(sc->kbdc, FALSE);
1056	return (err);
1057}
1058
1059/* psm driver entry points */
1060
1061static void
1062psmidentify(driver_t *driver, device_t parent)
1063{
1064	device_t psmc;
1065	device_t psm;
1066	u_long irq;
1067	int unit;
1068
1069	unit = device_get_unit(parent);
1070
1071	/* always add at least one child */
1072	psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
1073	if (psm == NULL)
1074		return;
1075
1076	irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
1077	if (irq > 0)
1078		return;
1079
1080	/*
1081	 * If the PS/2 mouse device has already been reported by ACPI or
1082	 * PnP BIOS, obtain the IRQ resource from it.
1083	 * (See psmcpnp_attach() below.)
1084	 */
1085	psmc = device_find_child(device_get_parent(parent),
1086	    PSMCPNP_DRIVER_NAME, unit);
1087	if (psmc == NULL)
1088		return;
1089	irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
1090	if (irq <= 0)
1091		return;
1092	bus_delete_resource(psmc, SYS_RES_IRQ, 0);
1093	bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
1094}
1095
1096#define	endprobe(v)	do {			\
1097	if (bootverbose)			\
1098		--verbose;			\
1099	kbdc_set_device_mask(sc->kbdc, mask);	\
1100	kbdc_lock(sc->kbdc, FALSE);		\
1101	return (v);				\
1102} while (0)
1103
1104static int
1105psmprobe(device_t dev)
1106{
1107	int unit = device_get_unit(dev);
1108	struct psm_softc *sc = device_get_softc(dev);
1109	int stat[3];
1110	int command_byte;
1111	int mask;
1112	int rid;
1113	int i;
1114
1115#if 0
1116	kbdc_debug(TRUE);
1117#endif
1118
1119	/* see if IRQ is available */
1120	rid = KBDC_RID_AUX;
1121	sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1122	if (sc->intr == NULL) {
1123		if (bootverbose)
1124			device_printf(dev, "unable to allocate IRQ\n");
1125		return (ENXIO);
1126	}
1127	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1128
1129	sc->unit = unit;
1130	sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
1131	sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
1132	/* XXX: for backward compatibility */
1133#if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
1134	sc->config |=
1135#ifdef PSM_RESETAFTERSUSPEND
1136	PSM_CONFIG_INITAFTERSUSPEND;
1137#else
1138	PSM_CONFIG_HOOKRESUME;
1139#endif
1140#endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
1141	sc->flags = 0;
1142	if (bootverbose)
1143		++verbose;
1144
1145	device_set_desc(dev, "PS/2 Mouse");
1146
1147	if (!kbdc_lock(sc->kbdc, TRUE)) {
1148		printf("psm%d: unable to lock the controller.\n", unit);
1149		if (bootverbose)
1150			--verbose;
1151		return (ENXIO);
1152	}
1153
1154	/*
1155	 * NOTE: two bits in the command byte controls the operation of the
1156	 * aux port (mouse port): the aux port disable bit (bit 5) and the aux
1157	 * port interrupt (IRQ 12) enable bit (bit 2).
1158	 */
1159
1160	/* discard anything left after the keyboard initialization */
1161	empty_both_buffers(sc->kbdc, 10);
1162
1163	/* save the current command byte; it will be used later */
1164	mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
1165	command_byte = get_controller_command_byte(sc->kbdc);
1166	if (verbose)
1167		printf("psm%d: current command byte:%04x\n", unit,
1168		    command_byte);
1169	if (command_byte == -1) {
1170		/* CONTROLLER ERROR */
1171		printf("psm%d: unable to get the current command byte value.\n",
1172			unit);
1173		endprobe(ENXIO);
1174	}
1175
1176	/*
1177	 * disable the keyboard port while probing the aux port, which must be
1178	 * enabled during this routine
1179	 */
1180	if (!set_controller_command_byte(sc->kbdc,
1181	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1182	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1183	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1184		/*
1185		 * this is CONTROLLER ERROR; I don't know how to recover
1186		 * from this error...
1187		 */
1188		restore_controller(sc->kbdc, command_byte);
1189		printf("psm%d: unable to set the command byte.\n", unit);
1190		endprobe(ENXIO);
1191	}
1192	write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
1193
1194	/*
1195	 * NOTE: `test_aux_port()' is designed to return with zero if the aux
1196	 * port exists and is functioning. However, some controllers appears
1197	 * to respond with zero even when the aux port doesn't exist. (It may
1198	 * be that this is only the case when the controller DOES have the aux
1199	 * port but the port is not wired on the motherboard.) The keyboard
1200	 * controllers without the port, such as the original AT, are
1201	 * supposed to return with an error code or simply time out. In any
1202	 * case, we have to continue probing the port even when the controller
1203	 * passes this test.
1204	 *
1205	 * XXX: some controllers erroneously return the error code 1, 2 or 3
1206	 * when it has a perfectly functional aux port. We have to ignore
1207	 * this error code. Even if the controller HAS error with the aux
1208	 * port, it will be detected later...
1209	 * XXX: another incompatible controller returns PSM_ACK (0xfa)...
1210	 */
1211	switch ((i = test_aux_port(sc->kbdc))) {
1212	case 1:		/* ignore these errors */
1213	case 2:
1214	case 3:
1215	case PSM_ACK:
1216		if (verbose)
1217			printf("psm%d: strange result for test aux port "
1218			    "(%d).\n", unit, i);
1219		/* FALLTHROUGH */
1220	case 0:		/* no error */
1221		break;
1222	case -1:	/* time out */
1223	default:	/* error */
1224		recover_from_error(sc->kbdc);
1225		if (sc->config & PSM_CONFIG_IGNPORTERROR)
1226			break;
1227		restore_controller(sc->kbdc, command_byte);
1228		if (verbose)
1229			printf("psm%d: the aux port is not functioning (%d).\n",
1230			    unit, i);
1231		endprobe(ENXIO);
1232	}
1233
1234	if (sc->config & PSM_CONFIG_NORESET) {
1235		/*
1236		 * Don't try to reset the pointing device.  It may possibly be
1237		 * left in an unknown state, though...
1238		 */
1239	} else {
1240		/*
1241		 * NOTE: some controllers appears to hang the `keyboard' when
1242		 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
1243		 *
1244		 * Attempt to reset the controller twice -- this helps
1245		 * pierce through some KVM switches. The second reset
1246		 * is non-fatal.
1247		 */
1248		if (!reset_aux_dev(sc->kbdc)) {
1249			recover_from_error(sc->kbdc);
1250			restore_controller(sc->kbdc, command_byte);
1251			if (verbose)
1252				printf("psm%d: failed to reset the aux "
1253				    "device.\n", unit);
1254			endprobe(ENXIO);
1255		} else if (!reset_aux_dev(sc->kbdc)) {
1256			recover_from_error(sc->kbdc);
1257			if (verbose >= 2)
1258				printf("psm%d: failed to reset the aux device "
1259				    "(2).\n", unit);
1260		}
1261	}
1262
1263	/*
1264	 * both the aux port and the aux device are functioning, see if the
1265	 * device can be enabled. NOTE: when enabled, the device will start
1266	 * sending data; we shall immediately disable the device once we know
1267	 * the device can be enabled.
1268	 */
1269	if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1270		/* MOUSE ERROR */
1271		recover_from_error(sc->kbdc);
1272		restore_controller(sc->kbdc, command_byte);
1273		if (verbose)
1274			printf("psm%d: failed to enable the aux device.\n",
1275			    unit);
1276		endprobe(ENXIO);
1277	}
1278
1279	/* save the default values after reset */
1280	if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1281		sc->dflt_mode.rate = sc->mode.rate = stat[2];
1282		sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1283	} else {
1284		sc->dflt_mode.rate = sc->mode.rate = -1;
1285		sc->dflt_mode.resolution = sc->mode.resolution = -1;
1286	}
1287
1288	/* hardware information */
1289	sc->hw.iftype = MOUSE_IF_PS2;
1290
1291	/* verify the device is a mouse */
1292	sc->hw.hwid = get_aux_id(sc->kbdc);
1293	if (!is_a_mouse(sc->hw.hwid)) {
1294		restore_controller(sc->kbdc, command_byte);
1295		if (verbose)
1296			printf("psm%d: unknown device type (%d).\n", unit,
1297			    sc->hw.hwid);
1298		endprobe(ENXIO);
1299	}
1300	switch (sc->hw.hwid) {
1301	case PSM_BALLPOINT_ID:
1302		sc->hw.type = MOUSE_TRACKBALL;
1303		break;
1304	case PSM_MOUSE_ID:
1305	case PSM_INTELLI_ID:
1306	case PSM_EXPLORER_ID:
1307	case PSM_4DMOUSE_ID:
1308	case PSM_4DPLUS_ID:
1309		sc->hw.type = MOUSE_MOUSE;
1310		break;
1311	default:
1312		sc->hw.type = MOUSE_UNKNOWN;
1313		break;
1314	}
1315
1316	if (sc->config & PSM_CONFIG_NOIDPROBE) {
1317		sc->hw.buttons = 2;
1318		i = GENERIC_MOUSE_ENTRY;
1319	} else {
1320		/* # of buttons */
1321		sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1322
1323		/* other parameters */
1324		for (i = 0; vendortype[i].probefunc != NULL; ++i)
1325			if ((*vendortype[i].probefunc)(sc->kbdc, sc)) {
1326				if (verbose >= 2)
1327					printf("psm%d: found %s\n", unit,
1328					    model_name(vendortype[i].model));
1329				break;
1330			}
1331	}
1332
1333	sc->hw.model = vendortype[i].model;
1334
1335	sc->dflt_mode.level = PSM_LEVEL_BASE;
1336	sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1337	sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1338	if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1339		sc->dflt_mode.syncmask[0] = 0;
1340	else
1341		sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1342	if (sc->config & PSM_CONFIG_FORCETAP)
1343		sc->dflt_mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1344	sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
1345	sc->mode = sc->dflt_mode;
1346	sc->mode.packetsize = vendortype[i].packetsize;
1347
1348	/* set mouse parameters */
1349#if 0
1350	/*
1351	 * A version of Logitech FirstMouse+ won't report wheel movement,
1352	 * if SET_DEFAULTS is sent...  Don't use this command.
1353	 * This fix was found by Takashi Nishida.
1354	 */
1355	i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1356	if (verbose >= 2)
1357		printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1358#endif
1359	if (sc->config & PSM_CONFIG_RESOLUTION)
1360		sc->mode.resolution =
1361		    set_mouse_resolution(sc->kbdc,
1362		    (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1363	else if (sc->mode.resolution >= 0)
1364		sc->mode.resolution =
1365		    set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1366	if (sc->mode.rate > 0)
1367		sc->mode.rate =
1368		    set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1369	set_mouse_scaling(sc->kbdc, 1);
1370
1371	/* Record sync on the next data packet we see. */
1372	sc->flags |= PSM_NEED_SYNCBITS;
1373
1374	/* just check the status of the mouse */
1375	/*
1376	 * NOTE: XXX there are some arcane controller/mouse combinations out
1377	 * there, which hung the controller unless there is data transmission
1378	 * after ACK from the mouse.
1379	 */
1380	if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1381		printf("psm%d: failed to get status.\n", unit);
1382	else {
1383		/*
1384		 * When in its native mode, some mice operate with different
1385		 * default parameters than in the PS/2 compatible mode.
1386		 */
1387		sc->dflt_mode.rate = sc->mode.rate = stat[2];
1388		sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1389	}
1390
1391	/* disable the aux port for now... */
1392	if (!set_controller_command_byte(sc->kbdc,
1393	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1394	    (command_byte & KBD_KBD_CONTROL_BITS) |
1395	    KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1396		/*
1397		 * this is CONTROLLER ERROR; I don't know the proper way to
1398		 * recover from this error...
1399		 */
1400		restore_controller(sc->kbdc, command_byte);
1401		printf("psm%d: unable to set the command byte.\n", unit);
1402		endprobe(ENXIO);
1403	}
1404
1405	/* done */
1406	kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1407	kbdc_lock(sc->kbdc, FALSE);
1408	return (0);
1409}
1410
1411static int
1412psmattach(device_t dev)
1413{
1414	int unit = device_get_unit(dev);
1415	struct psm_softc *sc = device_get_softc(dev);
1416	int error;
1417	int rid;
1418
1419	/* Setup initial state */
1420	sc->state = PSM_VALID;
1421	callout_handle_init(&sc->callout);
1422
1423	/* Setup our interrupt handler */
1424	rid = KBDC_RID_AUX;
1425	sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1426	if (sc->intr == NULL)
1427		return (ENXIO);
1428	error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, NULL, psmintr, sc,
1429	    &sc->ih);
1430	if (error) {
1431		bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1432		return (error);
1433	}
1434
1435	/* Done */
1436	sc->dev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "psm%d", unit);
1437	sc->dev->si_drv1 = sc;
1438	sc->bdev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "bpsm%d", unit);
1439	sc->bdev->si_drv1 = sc;
1440
1441	/* Some touchpad devices need full reinitialization after suspend. */
1442	switch (sc->hw.model) {
1443	case MOUSE_MODEL_SYNAPTICS:
1444	case MOUSE_MODEL_GLIDEPOINT:
1445	case MOUSE_MODEL_VERSAPAD:
1446		sc->config |= PSM_CONFIG_INITAFTERSUSPEND;
1447		break;
1448	default:
1449		if (sc->synhw.infoMajor >= 4)
1450			sc->config |= PSM_CONFIG_INITAFTERSUSPEND;
1451		break;
1452	}
1453
1454	if (!verbose)
1455		printf("psm%d: model %s, device ID %d\n",
1456		    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1457	else {
1458		printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1459		    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff,
1460		    sc->hw.hwid >> 8, sc->hw.buttons);
1461		printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1462		    unit, sc->config, sc->flags, sc->mode.packetsize);
1463		printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1464		    unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1465	}
1466
1467	if (bootverbose)
1468		--verbose;
1469
1470	return (0);
1471}
1472
1473static int
1474psmdetach(device_t dev)
1475{
1476	struct psm_softc *sc;
1477	int rid;
1478
1479	sc = device_get_softc(dev);
1480	if (sc->state & PSM_OPEN)
1481		return (EBUSY);
1482
1483	rid = KBDC_RID_AUX;
1484	bus_teardown_intr(dev, sc->intr, sc->ih);
1485	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1486
1487	destroy_dev(sc->dev);
1488	destroy_dev(sc->bdev);
1489
1490	return (0);
1491}
1492
1493static int
1494psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
1495{
1496	struct psm_softc *sc;
1497	int command_byte;
1498	int err;
1499	int s;
1500
1501	/* Get device data */
1502	sc = dev->si_drv1;
1503	if ((sc == NULL) || (sc->state & PSM_VALID) == 0) {
1504		/* the device is no longer valid/functioning */
1505		return (ENXIO);
1506	}
1507
1508	/* Disallow multiple opens */
1509	if (sc->state & PSM_OPEN)
1510		return (EBUSY);
1511
1512	device_busy(devclass_get_device(psm_devclass, sc->unit));
1513
1514	/* Initialize state */
1515	sc->mode.level = sc->dflt_mode.level;
1516	sc->mode.protocol = sc->dflt_mode.protocol;
1517	sc->watchdog = FALSE;
1518	sc->async = NULL;
1519
1520	/* flush the event queue */
1521	sc->queue.count = 0;
1522	sc->queue.head = 0;
1523	sc->queue.tail = 0;
1524	sc->status.flags = 0;
1525	sc->status.button = 0;
1526	sc->status.obutton = 0;
1527	sc->status.dx = 0;
1528	sc->status.dy = 0;
1529	sc->status.dz = 0;
1530	sc->button = 0;
1531	sc->pqueue_start = 0;
1532	sc->pqueue_end = 0;
1533
1534	/* empty input buffer */
1535	flushpackets(sc);
1536	sc->syncerrors = 0;
1537	sc->pkterrors = 0;
1538
1539	/* don't let timeout routines in the keyboard driver to poll the kbdc */
1540	if (!kbdc_lock(sc->kbdc, TRUE))
1541		return (EIO);
1542
1543	/* save the current controller command byte */
1544	s = spltty();
1545	command_byte = get_controller_command_byte(sc->kbdc);
1546
1547	/* enable the aux port and temporalily disable the keyboard */
1548	if (command_byte == -1 || !set_controller_command_byte(sc->kbdc,
1549	    kbdc_get_device_mask(sc->kbdc),
1550	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1551	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1552		/* CONTROLLER ERROR; do you know how to get out of this? */
1553		kbdc_lock(sc->kbdc, FALSE);
1554		splx(s);
1555		log(LOG_ERR,
1556		    "psm%d: unable to set the command byte (psmopen).\n",
1557		    sc->unit);
1558		return (EIO);
1559	}
1560	/*
1561	 * Now that the keyboard controller is told not to generate
1562	 * the keyboard and mouse interrupts, call `splx()' to allow
1563	 * the other tty interrupts. The clock interrupt may also occur,
1564	 * but timeout routines will be blocked by the poll flag set
1565	 * via `kbdc_lock()'
1566	 */
1567	splx(s);
1568
1569	/* enable the mouse device */
1570	err = doopen(sc, command_byte);
1571
1572	/* done */
1573	if (err == 0)
1574		sc->state |= PSM_OPEN;
1575	kbdc_lock(sc->kbdc, FALSE);
1576	return (err);
1577}
1578
1579static int
1580psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
1581{
1582	struct psm_softc *sc = dev->si_drv1;
1583	int stat[3];
1584	int command_byte;
1585	int s;
1586
1587	/* don't let timeout routines in the keyboard driver to poll the kbdc */
1588	if (!kbdc_lock(sc->kbdc, TRUE))
1589		return (EIO);
1590
1591	/* save the current controller command byte */
1592	s = spltty();
1593	command_byte = get_controller_command_byte(sc->kbdc);
1594	if (command_byte == -1) {
1595		kbdc_lock(sc->kbdc, FALSE);
1596		splx(s);
1597		return (EIO);
1598	}
1599
1600	/* disable the aux interrupt and temporalily disable the keyboard */
1601	if (!set_controller_command_byte(sc->kbdc,
1602	    kbdc_get_device_mask(sc->kbdc),
1603	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1604	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1605		log(LOG_ERR,
1606		    "psm%d: failed to disable the aux int (psmclose).\n",
1607		    sc->unit);
1608		/* CONTROLLER ERROR;
1609		 * NOTE: we shall force our way through. Because the only
1610		 * ill effect we shall see is that we may not be able
1611		 * to read ACK from the mouse, and it doesn't matter much
1612		 * so long as the mouse will accept the DISABLE command.
1613		 */
1614	}
1615	splx(s);
1616
1617	/* stop the watchdog timer */
1618	untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
1619	callout_handle_init(&sc->callout);
1620
1621	/* remove anything left in the output buffer */
1622	empty_aux_buffer(sc->kbdc, 10);
1623
1624	/* disable the aux device, port and interrupt */
1625	if (sc->state & PSM_VALID) {
1626		if (!disable_aux_dev(sc->kbdc)) {
1627			/* MOUSE ERROR;
1628			 * NOTE: we don't return (error) and continue,
1629			 * pretending we have successfully disabled the device.
1630			 * It's OK because the interrupt routine will discard
1631			 * any data from the mouse hereafter.
1632			 */
1633			log(LOG_ERR,
1634			    "psm%d: failed to disable the device (psmclose).\n",
1635			    sc->unit);
1636		}
1637
1638		if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1639			log(LOG_DEBUG,
1640			    "psm%d: failed to get status (psmclose).\n",
1641			    sc->unit);
1642	}
1643
1644	if (!set_controller_command_byte(sc->kbdc,
1645	    kbdc_get_device_mask(sc->kbdc),
1646	    (command_byte & KBD_KBD_CONTROL_BITS) |
1647	    KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1648		/*
1649		 * CONTROLLER ERROR;
1650		 * we shall ignore this error; see the above comment.
1651		 */
1652		log(LOG_ERR,
1653		    "psm%d: failed to disable the aux port (psmclose).\n",
1654		    sc->unit);
1655	}
1656
1657	/* remove anything left in the output buffer */
1658	empty_aux_buffer(sc->kbdc, 10);
1659
1660	/* clean up and sigio requests */
1661	if (sc->async != NULL) {
1662		funsetown(&sc->async);
1663		sc->async = NULL;
1664	}
1665
1666	/* close is almost always successful */
1667	sc->state &= ~PSM_OPEN;
1668	kbdc_lock(sc->kbdc, FALSE);
1669	device_unbusy(devclass_get_device(psm_devclass, sc->unit));
1670	return (0);
1671}
1672
1673static int
1674tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status,
1675    u_char *buf)
1676{
1677	static u_char butmapps2[8] = {
1678		0,
1679		MOUSE_PS2_BUTTON1DOWN,
1680		MOUSE_PS2_BUTTON2DOWN,
1681		MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1682		MOUSE_PS2_BUTTON3DOWN,
1683		MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1684		MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1685		MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN |
1686		    MOUSE_PS2_BUTTON3DOWN,
1687	};
1688	static u_char butmapmsc[8] = {
1689		MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP |
1690		    MOUSE_MSC_BUTTON3UP,
1691		MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1692		MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1693		MOUSE_MSC_BUTTON3UP,
1694		MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1695		MOUSE_MSC_BUTTON2UP,
1696		MOUSE_MSC_BUTTON1UP,
1697		0,
1698	};
1699	int mapped;
1700	int i;
1701
1702	if (sc->mode.level == PSM_LEVEL_BASE) {
1703		mapped = status->button & ~MOUSE_BUTTON4DOWN;
1704		if (status->button & MOUSE_BUTTON4DOWN)
1705			mapped |= MOUSE_BUTTON1DOWN;
1706		status->button = mapped;
1707		buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1708		i = imax(imin(status->dx, 255), -256);
1709		if (i < 0)
1710			buf[0] |= MOUSE_PS2_XNEG;
1711		buf[1] = i;
1712		i = imax(imin(status->dy, 255), -256);
1713		if (i < 0)
1714			buf[0] |= MOUSE_PS2_YNEG;
1715		buf[2] = i;
1716		return (MOUSE_PS2_PACKETSIZE);
1717	} else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1718		buf[0] = MOUSE_MSC_SYNC |
1719		    butmapmsc[status->button & MOUSE_STDBUTTONS];
1720		i = imax(imin(status->dx, 255), -256);
1721		buf[1] = i >> 1;
1722		buf[3] = i - buf[1];
1723		i = imax(imin(status->dy, 255), -256);
1724		buf[2] = i >> 1;
1725		buf[4] = i - buf[2];
1726		i = imax(imin(status->dz, 127), -128);
1727		buf[5] = (i >> 1) & 0x7f;
1728		buf[6] = (i - (i >> 1)) & 0x7f;
1729		buf[7] = (~status->button >> 3) & 0x7f;
1730		return (MOUSE_SYS_PACKETSIZE);
1731	}
1732	return (pb->inputbytes);
1733}
1734
1735static int
1736psmread(struct cdev *dev, struct uio *uio, int flag)
1737{
1738	struct psm_softc *sc = dev->si_drv1;
1739	u_char buf[PSM_SMALLBUFSIZE];
1740	int error = 0;
1741	int s;
1742	int l;
1743
1744	if ((sc->state & PSM_VALID) == 0)
1745		return (EIO);
1746
1747	/* block until mouse activity occured */
1748	s = spltty();
1749	while (sc->queue.count <= 0) {
1750		if (dev != sc->bdev) {
1751			splx(s);
1752			return (EWOULDBLOCK);
1753		}
1754		sc->state |= PSM_ASLP;
1755		error = tsleep(sc, PZERO | PCATCH, "psmrea", 0);
1756		sc->state &= ~PSM_ASLP;
1757		if (error) {
1758			splx(s);
1759			return (error);
1760		} else if ((sc->state & PSM_VALID) == 0) {
1761			/* the device disappeared! */
1762			splx(s);
1763			return (EIO);
1764		}
1765	}
1766	splx(s);
1767
1768	/* copy data to the user land */
1769	while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1770		s = spltty();
1771		l = imin(sc->queue.count, uio->uio_resid);
1772		if (l > sizeof(buf))
1773			l = sizeof(buf);
1774		if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1775			bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1776			    sizeof(sc->queue.buf) - sc->queue.head);
1777			bcopy(&sc->queue.buf[0],
1778			    &buf[sizeof(sc->queue.buf) - sc->queue.head],
1779			    l - (sizeof(sc->queue.buf) - sc->queue.head));
1780		} else
1781			bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1782		sc->queue.count -= l;
1783		sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1784		splx(s);
1785		error = uiomove(buf, l, uio);
1786		if (error)
1787			break;
1788	}
1789
1790	return (error);
1791}
1792
1793static int
1794block_mouse_data(struct psm_softc *sc, int *c)
1795{
1796	int s;
1797
1798	if (!kbdc_lock(sc->kbdc, TRUE))
1799		return (EIO);
1800
1801	s = spltty();
1802	*c = get_controller_command_byte(sc->kbdc);
1803	if ((*c == -1) || !set_controller_command_byte(sc->kbdc,
1804	    kbdc_get_device_mask(sc->kbdc),
1805	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1806	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1807		/* this is CONTROLLER ERROR */
1808		splx(s);
1809		kbdc_lock(sc->kbdc, FALSE);
1810		return (EIO);
1811	}
1812
1813	/*
1814	 * The device may be in the middle of status data transmission.
1815	 * The transmission will be interrupted, thus, incomplete status
1816	 * data must be discarded. Although the aux interrupt is disabled
1817	 * at the keyboard controller level, at most one aux interrupt
1818	 * may have already been pending and a data byte is in the
1819	 * output buffer; throw it away. Note that the second argument
1820	 * to `empty_aux_buffer()' is zero, so that the call will just
1821	 * flush the internal queue.
1822	 * `psmintr()' will be invoked after `splx()' if an interrupt is
1823	 * pending; it will see no data and returns immediately.
1824	 */
1825	empty_aux_buffer(sc->kbdc, 0);		/* flush the queue */
1826	read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
1827	flushpackets(sc);
1828	splx(s);
1829
1830	return (0);
1831}
1832
1833static void
1834dropqueue(struct psm_softc *sc)
1835{
1836
1837	sc->queue.count = 0;
1838	sc->queue.head = 0;
1839	sc->queue.tail = 0;
1840	if ((sc->state & PSM_SOFTARMED) != 0) {
1841		sc->state &= ~PSM_SOFTARMED;
1842		untimeout(psmsoftintr, (void *)(uintptr_t)sc, sc->softcallout);
1843	}
1844	sc->pqueue_start = sc->pqueue_end;
1845}
1846
1847static void
1848flushpackets(struct psm_softc *sc)
1849{
1850
1851	dropqueue(sc);
1852	bzero(&sc->pqueue, sizeof(sc->pqueue));
1853}
1854
1855static int
1856unblock_mouse_data(struct psm_softc *sc, int c)
1857{
1858	int error = 0;
1859
1860	/*
1861	 * We may have seen a part of status data during `set_mouse_XXX()'.
1862	 * they have been queued; flush it.
1863	 */
1864	empty_aux_buffer(sc->kbdc, 0);
1865
1866	/* restore ports and interrupt */
1867	if (!set_controller_command_byte(sc->kbdc,
1868	    kbdc_get_device_mask(sc->kbdc),
1869	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1870		/*
1871		 * CONTROLLER ERROR; this is serious, we may have
1872		 * been left with the inaccessible keyboard and
1873		 * the disabled mouse interrupt.
1874		 */
1875		error = EIO;
1876	}
1877
1878	kbdc_lock(sc->kbdc, FALSE);
1879	return (error);
1880}
1881
1882static int
1883psmwrite(struct cdev *dev, struct uio *uio, int flag)
1884{
1885	struct psm_softc *sc = dev->si_drv1;
1886	u_char buf[PSM_SMALLBUFSIZE];
1887	int error = 0, i, l;
1888
1889	if ((sc->state & PSM_VALID) == 0)
1890		return (EIO);
1891
1892	if (sc->mode.level < PSM_LEVEL_NATIVE)
1893		return (ENODEV);
1894
1895	/* copy data from the user land */
1896	while (uio->uio_resid > 0) {
1897		l = imin(PSM_SMALLBUFSIZE, uio->uio_resid);
1898		error = uiomove(buf, l, uio);
1899		if (error)
1900			break;
1901		for (i = 0; i < l; i++) {
1902			VLOG(4, (LOG_DEBUG, "psm: cmd 0x%x\n", buf[i]));
1903			if (!write_aux_command(sc->kbdc, buf[i])) {
1904				VLOG(2, (LOG_DEBUG,
1905				    "psm: cmd 0x%x failed.\n", buf[i]));
1906				return (reinitialize(sc, FALSE));
1907			}
1908		}
1909	}
1910
1911	return (error);
1912}
1913
1914static int
1915psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
1916    struct thread *td)
1917{
1918	struct psm_softc *sc = dev->si_drv1;
1919	mousemode_t mode;
1920	mousestatus_t status;
1921#if (defined(MOUSE_GETVARS))
1922	mousevar_t *var;
1923#endif
1924	mousedata_t *data;
1925	int stat[3];
1926	int command_byte;
1927	int error = 0;
1928	int s;
1929
1930	/* Perform IOCTL command */
1931	switch (cmd) {
1932
1933	case OLD_MOUSE_GETHWINFO:
1934		s = spltty();
1935		((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1936		((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1937		((old_mousehw_t *)addr)->type = sc->hw.type;
1938		((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
1939		splx(s);
1940		break;
1941
1942	case MOUSE_GETHWINFO:
1943		s = spltty();
1944		*(mousehw_t *)addr = sc->hw;
1945		if (sc->mode.level == PSM_LEVEL_BASE)
1946			((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1947		splx(s);
1948		break;
1949
1950	case MOUSE_SYN_GETHWINFO:
1951		s = spltty();
1952		if (sc->synhw.infoMajor >= 4)
1953			*(synapticshw_t *)addr = sc->synhw;
1954		else
1955			error = EINVAL;
1956		splx(s);
1957		break;
1958
1959	case OLD_MOUSE_GETMODE:
1960		s = spltty();
1961		switch (sc->mode.level) {
1962		case PSM_LEVEL_BASE:
1963			((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1964			break;
1965		case PSM_LEVEL_STANDARD:
1966			((old_mousemode_t *)addr)->protocol =
1967			    MOUSE_PROTO_SYSMOUSE;
1968			break;
1969		case PSM_LEVEL_NATIVE:
1970			((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1971			break;
1972		}
1973		((old_mousemode_t *)addr)->rate = sc->mode.rate;
1974		((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1975		((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1976		splx(s);
1977		break;
1978
1979	case MOUSE_GETMODE:
1980		s = spltty();
1981		*(mousemode_t *)addr = sc->mode;
1982		if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
1983			((mousemode_t *)addr)->syncmask[0] = 0;
1984			((mousemode_t *)addr)->syncmask[1] = 0;
1985		}
1986		((mousemode_t *)addr)->resolution =
1987			MOUSE_RES_LOW - sc->mode.resolution;
1988		switch (sc->mode.level) {
1989		case PSM_LEVEL_BASE:
1990			((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1991			((mousemode_t *)addr)->packetsize =
1992			    MOUSE_PS2_PACKETSIZE;
1993			break;
1994		case PSM_LEVEL_STANDARD:
1995			((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1996			((mousemode_t *)addr)->packetsize =
1997			    MOUSE_SYS_PACKETSIZE;
1998			((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1999			((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
2000			break;
2001		case PSM_LEVEL_NATIVE:
2002			/* FIXME: this isn't quite correct... XXX */
2003			((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2004			break;
2005		}
2006		splx(s);
2007		break;
2008
2009	case OLD_MOUSE_SETMODE:
2010	case MOUSE_SETMODE:
2011		if (cmd == OLD_MOUSE_SETMODE) {
2012			mode.rate = ((old_mousemode_t *)addr)->rate;
2013			/*
2014			 * resolution  old I/F   new I/F
2015			 * default        0         0
2016			 * low            1        -2
2017			 * medium low     2        -3
2018			 * medium high    3        -4
2019			 * high           4        -5
2020			 */
2021			if (((old_mousemode_t *)addr)->resolution > 0)
2022				mode.resolution =
2023				    -((old_mousemode_t *)addr)->resolution - 1;
2024			else
2025				mode.resolution = 0;
2026			mode.accelfactor =
2027			    ((old_mousemode_t *)addr)->accelfactor;
2028			mode.level = -1;
2029		} else
2030			mode = *(mousemode_t *)addr;
2031
2032		/* adjust and validate parameters. */
2033		if (mode.rate > UCHAR_MAX)
2034			return (EINVAL);
2035		if (mode.rate == 0)
2036			mode.rate = sc->dflt_mode.rate;
2037		else if (mode.rate == -1)
2038			/* don't change the current setting */
2039			;
2040		else if (mode.rate < 0)
2041			return (EINVAL);
2042		if (mode.resolution >= UCHAR_MAX)
2043			return (EINVAL);
2044		if (mode.resolution >= 200)
2045			mode.resolution = MOUSE_RES_HIGH;
2046		else if (mode.resolution >= 100)
2047			mode.resolution = MOUSE_RES_MEDIUMHIGH;
2048		else if (mode.resolution >= 50)
2049			mode.resolution = MOUSE_RES_MEDIUMLOW;
2050		else if (mode.resolution > 0)
2051			mode.resolution = MOUSE_RES_LOW;
2052		if (mode.resolution == MOUSE_RES_DEFAULT)
2053			mode.resolution = sc->dflt_mode.resolution;
2054		else if (mode.resolution == -1)
2055			/* don't change the current setting */
2056			;
2057		else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2058			mode.resolution = MOUSE_RES_LOW - mode.resolution;
2059		if (mode.level == -1)
2060			/* don't change the current setting */
2061			mode.level = sc->mode.level;
2062		else if ((mode.level < PSM_LEVEL_MIN) ||
2063		    (mode.level > PSM_LEVEL_MAX))
2064			return (EINVAL);
2065		if (mode.accelfactor == -1)
2066			/* don't change the current setting */
2067			mode.accelfactor = sc->mode.accelfactor;
2068		else if (mode.accelfactor < 0)
2069			return (EINVAL);
2070
2071		/* don't allow anybody to poll the keyboard controller */
2072		error = block_mouse_data(sc, &command_byte);
2073		if (error)
2074			return (error);
2075
2076		/* set mouse parameters */
2077		if (mode.rate > 0)
2078			mode.rate = set_mouse_sampling_rate(sc->kbdc,
2079			    mode.rate);
2080		if (mode.resolution >= 0)
2081			mode.resolution =
2082			    set_mouse_resolution(sc->kbdc, mode.resolution);
2083		set_mouse_scaling(sc->kbdc, 1);
2084		get_mouse_status(sc->kbdc, stat, 0, 3);
2085
2086		s = spltty();
2087		sc->mode.rate = mode.rate;
2088		sc->mode.resolution = mode.resolution;
2089		sc->mode.accelfactor = mode.accelfactor;
2090		sc->mode.level = mode.level;
2091		splx(s);
2092
2093		unblock_mouse_data(sc, command_byte);
2094		break;
2095
2096	case MOUSE_GETLEVEL:
2097		*(int *)addr = sc->mode.level;
2098		break;
2099
2100	case MOUSE_SETLEVEL:
2101		if ((*(int *)addr < PSM_LEVEL_MIN) ||
2102		    (*(int *)addr > PSM_LEVEL_MAX))
2103			return (EINVAL);
2104		sc->mode.level = *(int *)addr;
2105		break;
2106
2107	case MOUSE_GETSTATUS:
2108		s = spltty();
2109		status = sc->status;
2110		sc->status.flags = 0;
2111		sc->status.obutton = sc->status.button;
2112		sc->status.button = 0;
2113		sc->status.dx = 0;
2114		sc->status.dy = 0;
2115		sc->status.dz = 0;
2116		splx(s);
2117		*(mousestatus_t *)addr = status;
2118		break;
2119
2120#if (defined(MOUSE_GETVARS))
2121	case MOUSE_GETVARS:
2122		var = (mousevar_t *)addr;
2123		bzero(var, sizeof(*var));
2124		s = spltty();
2125		var->var[0] = MOUSE_VARS_PS2_SIG;
2126		var->var[1] = sc->config;
2127		var->var[2] = sc->flags;
2128		splx(s);
2129		break;
2130
2131	case MOUSE_SETVARS:
2132		return (ENODEV);
2133#endif /* MOUSE_GETVARS */
2134
2135	case MOUSE_READSTATE:
2136	case MOUSE_READDATA:
2137		data = (mousedata_t *)addr;
2138		if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
2139			return (EINVAL);
2140
2141		error = block_mouse_data(sc, &command_byte);
2142		if (error)
2143			return (error);
2144		if ((data->len = get_mouse_status(sc->kbdc, data->buf,
2145		    (cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
2146			error = EIO;
2147		unblock_mouse_data(sc, command_byte);
2148		break;
2149
2150#if (defined(MOUSE_SETRESOLUTION))
2151	case MOUSE_SETRESOLUTION:
2152		mode.resolution = *(int *)addr;
2153		if (mode.resolution >= UCHAR_MAX)
2154			return (EINVAL);
2155		else if (mode.resolution >= 200)
2156			mode.resolution = MOUSE_RES_HIGH;
2157		else if (mode.resolution >= 100)
2158			mode.resolution = MOUSE_RES_MEDIUMHIGH;
2159		else if (mode.resolution >= 50)
2160			mode.resolution = MOUSE_RES_MEDIUMLOW;
2161		else if (mode.resolution > 0)
2162			mode.resolution = MOUSE_RES_LOW;
2163		if (mode.resolution == MOUSE_RES_DEFAULT)
2164			mode.resolution = sc->dflt_mode.resolution;
2165		else if (mode.resolution == -1)
2166			mode.resolution = sc->mode.resolution;
2167		else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2168			mode.resolution = MOUSE_RES_LOW - mode.resolution;
2169
2170		error = block_mouse_data(sc, &command_byte);
2171		if (error)
2172			return (error);
2173		sc->mode.resolution =
2174		    set_mouse_resolution(sc->kbdc, mode.resolution);
2175		if (sc->mode.resolution != mode.resolution)
2176			error = EIO;
2177		unblock_mouse_data(sc, command_byte);
2178		break;
2179#endif /* MOUSE_SETRESOLUTION */
2180
2181#if (defined(MOUSE_SETRATE))
2182	case MOUSE_SETRATE:
2183		mode.rate = *(int *)addr;
2184		if (mode.rate > UCHAR_MAX)
2185			return (EINVAL);
2186		if (mode.rate == 0)
2187			mode.rate = sc->dflt_mode.rate;
2188		else if (mode.rate < 0)
2189			mode.rate = sc->mode.rate;
2190
2191		error = block_mouse_data(sc, &command_byte);
2192		if (error)
2193			return (error);
2194		sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
2195		if (sc->mode.rate != mode.rate)
2196			error = EIO;
2197		unblock_mouse_data(sc, command_byte);
2198		break;
2199#endif /* MOUSE_SETRATE */
2200
2201#if (defined(MOUSE_SETSCALING))
2202	case MOUSE_SETSCALING:
2203		if ((*(int *)addr <= 0) || (*(int *)addr > 2))
2204			return (EINVAL);
2205
2206		error = block_mouse_data(sc, &command_byte);
2207		if (error)
2208			return (error);
2209		if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
2210			error = EIO;
2211		unblock_mouse_data(sc, command_byte);
2212		break;
2213#endif /* MOUSE_SETSCALING */
2214
2215#if (defined(MOUSE_GETHWID))
2216	case MOUSE_GETHWID:
2217		error = block_mouse_data(sc, &command_byte);
2218		if (error)
2219			return (error);
2220		sc->hw.hwid &= ~0x00ff;
2221		sc->hw.hwid |= get_aux_id(sc->kbdc);
2222		*(int *)addr = sc->hw.hwid & 0x00ff;
2223		unblock_mouse_data(sc, command_byte);
2224		break;
2225#endif /* MOUSE_GETHWID */
2226
2227	case FIONBIO:
2228	case FIOASYNC:
2229		break;
2230	case FIOSETOWN:
2231		error = fsetown(*(int *)addr, &sc->async);
2232		break;
2233	case FIOGETOWN:
2234		*(int *) addr = fgetown(&sc->async);
2235		break;
2236	default:
2237		return (ENOTTY);
2238	}
2239
2240	return (error);
2241}
2242
2243static void
2244psmtimeout(void *arg)
2245{
2246	struct psm_softc *sc;
2247	int s;
2248
2249	sc = (struct psm_softc *)arg;
2250	s = spltty();
2251	if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
2252		VLOG(4, (LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit));
2253		psmintr(sc);
2254		kbdc_lock(sc->kbdc, FALSE);
2255	}
2256	sc->watchdog = TRUE;
2257	splx(s);
2258	sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz);
2259}
2260
2261/* Add all sysctls under the debug.psm and hw.psm nodes */
2262SYSCTL_NODE(_debug, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2263SYSCTL_NODE(_hw, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2264
2265SYSCTL_INT(_debug_psm, OID_AUTO, loglevel, CTLFLAG_RW, &verbose, 0,
2266    "Verbosity level");
2267
2268static int psmhz = 20;
2269SYSCTL_INT(_debug_psm, OID_AUTO, hz, CTLFLAG_RW, &psmhz, 0,
2270    "Frequency of the softcallout (in hz)");
2271static int psmerrsecs = 2;
2272SYSCTL_INT(_debug_psm, OID_AUTO, errsecs, CTLFLAG_RW, &psmerrsecs, 0,
2273    "Number of seconds during which packets will dropped after a sync error");
2274static int psmerrusecs = 0;
2275SYSCTL_INT(_debug_psm, OID_AUTO, errusecs, CTLFLAG_RW, &psmerrusecs, 0,
2276    "Microseconds to add to psmerrsecs");
2277static int psmsecs = 0;
2278SYSCTL_INT(_debug_psm, OID_AUTO, secs, CTLFLAG_RW, &psmsecs, 0,
2279    "Max number of seconds between soft interrupts");
2280static int psmusecs = 500000;
2281SYSCTL_INT(_debug_psm, OID_AUTO, usecs, CTLFLAG_RW, &psmusecs, 0,
2282    "Microseconds to add to psmsecs");
2283static int pkterrthresh = 2;
2284SYSCTL_INT(_debug_psm, OID_AUTO, pkterrthresh, CTLFLAG_RW, &pkterrthresh, 0,
2285    "Number of error packets allowed before reinitializing the mouse");
2286
2287SYSCTL_INT(_hw_psm, OID_AUTO, tap_enabled, CTLFLAG_RW, &tap_enabled, 0,
2288    "Enable tap and drag gestures");
2289static int tap_threshold = PSM_TAP_THRESHOLD;
2290SYSCTL_INT(_hw_psm, OID_AUTO, tap_threshold, CTLFLAG_RW, &tap_threshold, 0,
2291    "Button tap threshold");
2292static int tap_timeout = PSM_TAP_TIMEOUT;
2293SYSCTL_INT(_hw_psm, OID_AUTO, tap_timeout, CTLFLAG_RW, &tap_timeout, 0,
2294    "Tap timeout for touchpads");
2295
2296static void
2297psmintr(void *arg)
2298{
2299	struct psm_softc *sc = arg;
2300	struct timeval now;
2301	int c;
2302	packetbuf_t *pb;
2303
2304
2305	/* read until there is nothing to read */
2306	while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
2307		pb = &sc->pqueue[sc->pqueue_end];
2308
2309		/* discard the byte if the device is not open */
2310		if ((sc->state & PSM_OPEN) == 0)
2311			continue;
2312
2313		getmicrouptime(&now);
2314		if ((pb->inputbytes > 0) &&
2315		    timevalcmp(&now, &sc->inputtimeout, >)) {
2316			VLOG(3, (LOG_DEBUG, "psmintr: delay too long; "
2317			    "resetting byte count\n"));
2318			pb->inputbytes = 0;
2319			sc->syncerrors = 0;
2320			sc->pkterrors = 0;
2321		}
2322		sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT / 1000000;
2323		sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT % 1000000;
2324		timevaladd(&sc->inputtimeout, &now);
2325
2326		pb->ipacket[pb->inputbytes++] = c;
2327
2328		if (sc->mode.level == PSM_LEVEL_NATIVE) {
2329			VLOG(4, (LOG_DEBUG, "psmintr: %02x\n", pb->ipacket[0]));
2330			sc->syncerrors = 0;
2331			sc->pkterrors = 0;
2332			goto next;
2333		} else {
2334			if (pb->inputbytes < sc->mode.packetsize)
2335				continue;
2336
2337			VLOG(4, (LOG_DEBUG,
2338			    "psmintr: %02x %02x %02x %02x %02x %02x\n",
2339			    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
2340			    pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
2341		}
2342
2343		c = pb->ipacket[0];
2344
2345		if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2346			sc->mode.syncmask[1] = (c & sc->mode.syncmask[0]);
2347			sc->flags &= ~PSM_NEED_SYNCBITS;
2348			VLOG(2, (LOG_DEBUG,
2349			    "psmintr: Sync bytes now %04x,%04x\n",
2350			    sc->mode.syncmask[0], sc->mode.syncmask[0]));
2351		} else if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
2352			VLOG(3, (LOG_DEBUG, "psmintr: out of sync "
2353			    "(%04x != %04x) %d cmds since last error.\n",
2354			    c & sc->mode.syncmask[0], sc->mode.syncmask[1],
2355			    sc->cmdcount - sc->lasterr));
2356			sc->lasterr = sc->cmdcount;
2357			/*
2358			 * The sync byte test is a weak measure of packet
2359			 * validity.  Conservatively discard any input yet
2360			 * to be seen by userland when we detect a sync
2361			 * error since there is a good chance some of
2362			 * the queued packets have undetected errors.
2363			 */
2364			dropqueue(sc);
2365			if (sc->syncerrors == 0)
2366				sc->pkterrors++;
2367			++sc->syncerrors;
2368			sc->lastinputerr = now;
2369			if (sc->syncerrors >= sc->mode.packetsize * 2 ||
2370			    sc->pkterrors >= pkterrthresh) {
2371				/*
2372				 * If we've failed to find a single sync byte
2373				 * in 2 packets worth of data, or we've seen
2374				 * persistent packet errors during the
2375				 * validation period, reinitialize the mouse
2376				 * in hopes of returning it to the expected
2377				 * mode.
2378				 */
2379				VLOG(3, (LOG_DEBUG,
2380				    "psmintr: reset the mouse.\n"));
2381				reinitialize(sc, TRUE);
2382			} else if (sc->syncerrors == sc->mode.packetsize) {
2383				/*
2384				 * Try a soft reset after searching for a sync
2385				 * byte through a packet length of bytes.
2386				 */
2387				VLOG(3, (LOG_DEBUG,
2388				    "psmintr: re-enable the mouse.\n"));
2389				pb->inputbytes = 0;
2390				disable_aux_dev(sc->kbdc);
2391				enable_aux_dev(sc->kbdc);
2392			} else {
2393				VLOG(3, (LOG_DEBUG,
2394				    "psmintr: discard a byte (%d)\n",
2395				    sc->syncerrors));
2396				pb->inputbytes--;
2397				bcopy(&pb->ipacket[1], &pb->ipacket[0],
2398				    pb->inputbytes);
2399			}
2400			continue;
2401		}
2402
2403		/*
2404		 * We have what appears to be a valid packet.
2405		 * Reset the error counters.
2406		 */
2407		sc->syncerrors = 0;
2408
2409		/*
2410		 * Drop even good packets if they occur within a timeout
2411		 * period of a sync error.  This allows the detection of
2412		 * a change in the mouse's packet mode without exposing
2413		 * erratic mouse behavior to the user.  Some KVMs forget
2414		 * enhanced mouse modes during switch events.
2415		 */
2416		if (!timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs,
2417		    &now)) {
2418			pb->inputbytes = 0;
2419			continue;
2420		}
2421
2422		/*
2423		 * Now that we're out of the validation period, reset
2424		 * the packet error count.
2425		 */
2426		sc->pkterrors = 0;
2427
2428		sc->cmdcount++;
2429next:
2430		if (++sc->pqueue_end >= PSM_PACKETQUEUE)
2431			sc->pqueue_end = 0;
2432		/*
2433		 * If we've filled the queue then call the softintr ourselves,
2434		 * otherwise schedule the interrupt for later.
2435		 */
2436		if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
2437		    (sc->pqueue_end == sc->pqueue_start)) {
2438			if ((sc->state & PSM_SOFTARMED) != 0) {
2439				sc->state &= ~PSM_SOFTARMED;
2440				untimeout(psmsoftintr, arg, sc->softcallout);
2441			}
2442			psmsoftintr(arg);
2443		} else if ((sc->state & PSM_SOFTARMED) == 0) {
2444			sc->state |= PSM_SOFTARMED;
2445			sc->softcallout = timeout(psmsoftintr, arg,
2446			    psmhz < 1 ? 1 : (hz/psmhz));
2447		}
2448	}
2449}
2450
2451static void
2452proc_mmanplus(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
2453    int *x, int *y, int *z)
2454{
2455
2456	/*
2457	 * PS2++ protocol packet
2458	 *
2459	 *          b7 b6 b5 b4 b3 b2 b1 b0
2460	 * byte 1:  *  1  p3 p2 1  *  *  *
2461	 * byte 2:  c1 c2 p1 p0 d1 d0 1  0
2462	 *
2463	 * p3-p0: packet type
2464	 * c1, c2: c1 & c2 == 1, if p2 == 0
2465	 *         c1 & c2 == 0, if p2 == 1
2466	 *
2467	 * packet type: 0 (device type)
2468	 * See comments in enable_mmanplus() below.
2469	 *
2470	 * packet type: 1 (wheel data)
2471	 *
2472	 *          b7 b6 b5 b4 b3 b2 b1 b0
2473	 * byte 3:  h  *  B5 B4 s  d2 d1 d0
2474	 *
2475	 * h: 1, if horizontal roller data
2476	 *    0, if vertical roller data
2477	 * B4, B5: button 4 and 5
2478	 * s: sign bit
2479	 * d2-d0: roller data
2480	 *
2481	 * packet type: 2 (reserved)
2482	 */
2483	if (((pb->ipacket[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC) &&
2484	    (abs(*x) > 191) && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
2485		/*
2486		 * the extended data packet encodes button
2487		 * and wheel events
2488		 */
2489		switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
2490		case 1:
2491			/* wheel data packet */
2492			*x = *y = 0;
2493			if (pb->ipacket[2] & 0x80) {
2494				/* XXX horizontal roller count - ignore it */
2495				;
2496			} else {
2497				/* vertical roller count */
2498				*z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG) ?
2499				    (pb->ipacket[2] & 0x0f) - 16 :
2500				    (pb->ipacket[2] & 0x0f);
2501			}
2502			ms->button |= (pb->ipacket[2] &
2503			    MOUSE_PS2PLUS_BUTTON4DOWN) ?
2504			    MOUSE_BUTTON4DOWN : 0;
2505			ms->button |= (pb->ipacket[2] &
2506			    MOUSE_PS2PLUS_BUTTON5DOWN) ?
2507			    MOUSE_BUTTON5DOWN : 0;
2508			break;
2509		case 2:
2510			/*
2511			 * this packet type is reserved by
2512			 * Logitech...
2513			 */
2514			/*
2515			 * IBM ScrollPoint Mouse uses this
2516			 * packet type to encode both vertical
2517			 * and horizontal scroll movement.
2518			 */
2519			*x = *y = 0;
2520			/* horizontal count */
2521			if (pb->ipacket[2] & 0x0f)
2522				*z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ?
2523				    -2 : 2;
2524			/* vertical count */
2525			if (pb->ipacket[2] & 0xf0)
2526				*z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ?
2527				    -1 : 1;
2528			break;
2529		case 0:
2530			/* device type packet - shouldn't happen */
2531			/* FALLTHROUGH */
2532		default:
2533			*x = *y = 0;
2534			ms->button = ms->obutton;
2535			VLOG(1, (LOG_DEBUG, "psmintr: unknown PS2++ packet "
2536			    "type %d: 0x%02x 0x%02x 0x%02x\n",
2537			    MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
2538			    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]));
2539			break;
2540		}
2541	} else {
2542		/* preserve button states */
2543		ms->button |= ms->obutton & MOUSE_EXTBUTTONS;
2544	}
2545}
2546
2547static int
2548proc_synaptics(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
2549    int *x, int *y, int *z)
2550{
2551	static int touchpad_buttons;
2552	static int guest_buttons;
2553	int w, x0, y0;
2554
2555	/* TouchPad PS/2 absolute mode message format
2556	 *
2557	 *  Bits:        7   6   5   4   3   2   1   0 (LSB)
2558	 *  ------------------------------------------------
2559	 *  ipacket[0]:  1   0  W3  W2   0  W1   R   L
2560	 *  ipacket[1]: Yb  Ya  Y9  Y8  Xb  Xa  X9  X8
2561	 *  ipacket[2]: Z7  Z6  Z5  Z4  Z3  Z2  Z1  Z0
2562	 *  ipacket[3]:  1   1  Yc  Xc   0  W0   D   U
2563	 *  ipacket[4]: X7  X6  X5  X4  X3  X2  X1  X0
2564	 *  ipacket[5]: Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
2565	 *
2566	 * Legend:
2567	 *  L: left physical mouse button
2568	 *  R: right physical mouse button
2569	 *  D: down button
2570	 *  U: up button
2571	 *  W: "wrist" value
2572	 *  X: x position
2573	 *  Y: y position
2574	 *  Z: pressure
2575	 *
2576	 * Absolute reportable limits:    0 - 6143.
2577	 * Typical bezel limits:       1472 - 5472.
2578	 * Typical edge marings:       1632 - 5312.
2579	 *
2580	 * w = 3 Passthrough Packet
2581	 *
2582	 * Byte 2,5,6 == Byte 1,2,3 of "Guest"
2583	 */
2584
2585	if (!synaptics_support)
2586		return (0);
2587
2588	/* Sanity check for out of sync packets. */
2589	if ((pb->ipacket[0] & 0xc8) != 0x80 ||
2590	    (pb->ipacket[3] & 0xc8) != 0xc0)
2591		return (-1);
2592
2593	*x = *y = 0;
2594
2595	/*
2596	 * Pressure value.
2597	 * Interpretation:
2598	 *   z = 0      No finger contact
2599	 *   z = 10     Finger hovering near the pad
2600	 *   z = 30     Very light finger contact
2601	 *   z = 80     Normal finger contact
2602	 *   z = 110    Very heavy finger contact
2603	 *   z = 200    Finger lying flat on pad surface
2604	 *   z = 255    Maximum reportable Z
2605	 */
2606	*z = pb->ipacket[2];
2607
2608	/*
2609	 * Finger width value
2610	 * Interpretation:
2611	 *   w = 0      Two finger on the pad (capMultiFinger needed)
2612	 *   w = 1      Three or more fingers (capMultiFinger needed)
2613	 *   w = 2      Pen (instead of finger) (capPen needed)
2614	 *   w = 3      Reserved (passthrough?)
2615	 *   w = 4-7    Finger of normal width (capPalmDetect needed)
2616	 *   w = 8-14   Very wide finger or palm (capPalmDetect needed)
2617	 *   w = 15     Maximum reportable width (capPalmDetect needed)
2618	 */
2619	/* XXX Is checking capExtended enough? */
2620	if (sc->synhw.capExtended)
2621		w = ((pb->ipacket[0] & 0x30) >> 2) |
2622		    ((pb->ipacket[0] & 0x04) >> 1) |
2623		    ((pb->ipacket[3] & 0x04) >> 2);
2624	else {
2625		/* Assume a finger of regular width. */
2626		w = 4;
2627	}
2628
2629	/* Handle packets from the guest device */
2630	/* XXX Documentation? */
2631	if (w == 3 && sc->synhw.capPassthrough) {
2632		*x = ((pb->ipacket[1] & 0x10) ?
2633		    pb->ipacket[4] - 256 : pb->ipacket[4]);
2634		*y = ((pb->ipacket[1] & 0x20) ?
2635		    pb->ipacket[5] - 256 : pb->ipacket[5]);
2636		*z = 0;
2637
2638		guest_buttons = 0;
2639		if (pb->ipacket[1] & 0x01)
2640			guest_buttons |= MOUSE_BUTTON1DOWN;
2641		if (pb->ipacket[1] & 0x04)
2642			guest_buttons |= MOUSE_BUTTON2DOWN;
2643		if (pb->ipacket[1] & 0x02)
2644			guest_buttons |= MOUSE_BUTTON3DOWN;
2645
2646		ms->button = touchpad_buttons | guest_buttons;
2647		goto SYNAPTICS_END;
2648	}
2649
2650	/* Button presses */
2651	touchpad_buttons = 0;
2652	if (pb->ipacket[0] & 0x01)
2653		touchpad_buttons |= MOUSE_BUTTON1DOWN;
2654	if (pb->ipacket[0] & 0x02)
2655		touchpad_buttons |= MOUSE_BUTTON3DOWN;
2656
2657	if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
2658		if ((pb->ipacket[3] & 0x01) && (pb->ipacket[0] & 0x01) == 0)
2659			touchpad_buttons |= MOUSE_BUTTON4DOWN;
2660		if ((pb->ipacket[3] & 0x02) && (pb->ipacket[0] & 0x02) == 0)
2661			touchpad_buttons |= MOUSE_BUTTON5DOWN;
2662	}
2663
2664	/*
2665	 * In newer pads - bit 0x02 in the third byte of
2666	 * the packet indicates that we have an extended
2667	 * button press.
2668	 */
2669	/* XXX Documentation? */
2670	if (pb->ipacket[3] & 0x02) {
2671		/*
2672		 * if directional_scrolls is not 1, we treat any of
2673		 * the scrolling directions as middle-click.
2674		 */
2675		if (sc->syninfo.directional_scrolls) {
2676			if (pb->ipacket[4] & 0x01)
2677				touchpad_buttons |= MOUSE_BUTTON4DOWN;
2678			if (pb->ipacket[5] & 0x01)
2679				touchpad_buttons |= MOUSE_BUTTON5DOWN;
2680			if (pb->ipacket[4] & 0x02)
2681				touchpad_buttons |= MOUSE_BUTTON6DOWN;
2682			if (pb->ipacket[5] & 0x02)
2683				touchpad_buttons |= MOUSE_BUTTON7DOWN;
2684		} else {
2685			if ((pb->ipacket[4] & 0x0F) ||
2686			    (pb->ipacket[5] & 0x0F))
2687				touchpad_buttons |= MOUSE_BUTTON2DOWN;
2688		}
2689	}
2690
2691	ms->button = touchpad_buttons | guest_buttons;
2692
2693	/* Check pressure to detect a real wanted action on the
2694	 * touchpad. */
2695	if (*z >= sc->syninfo.min_pressure) {
2696		synapticsaction_t *synaction;
2697		int cursor, peer, window;
2698		int dx, dy, dxp, dyp;
2699		int max_width, max_pressure;
2700		int margin_top, margin_right, margin_bottom, margin_left;
2701		int na_top, na_right, na_bottom, na_left;
2702		int window_min, window_max;
2703		int multiplicator;
2704		int weight_current, weight_previous, weight_len_squared;
2705		int div_min, div_max, div_len;
2706		int vscroll_hor_area, vscroll_ver_area;
2707
2708		int len, weight_prev_x, weight_prev_y;
2709		int div_max_x, div_max_y, div_x, div_y;
2710
2711		/* Read sysctl. */
2712		/* XXX Verify values? */
2713		max_width = sc->syninfo.max_width;
2714		max_pressure = sc->syninfo.max_pressure;
2715		margin_top = sc->syninfo.margin_top;
2716		margin_right = sc->syninfo.margin_right;
2717		margin_bottom = sc->syninfo.margin_bottom;
2718		margin_left = sc->syninfo.margin_left;
2719		na_top = sc->syninfo.na_top;
2720		na_right = sc->syninfo.na_right;
2721		na_bottom = sc->syninfo.na_bottom;
2722		na_left = sc->syninfo.na_left;
2723		window_min = sc->syninfo.window_min;
2724		window_max = sc->syninfo.window_max;
2725		multiplicator = sc->syninfo.multiplicator;
2726		weight_current = sc->syninfo.weight_current;
2727		weight_previous = sc->syninfo.weight_previous;
2728		weight_len_squared = sc->syninfo.weight_len_squared;
2729		div_min = sc->syninfo.div_min;
2730		div_max = sc->syninfo.div_max;
2731		div_len = sc->syninfo.div_len;
2732		vscroll_hor_area = sc->syninfo.vscroll_hor_area;
2733		vscroll_ver_area = sc->syninfo.vscroll_ver_area;
2734
2735		/* Palm detection. */
2736		if (!(
2737		    (sc->synhw.capMultiFinger && (w == 0 || w == 1)) ||
2738		    (sc->synhw.capPalmDetect && w >= 4 && w <= max_width) ||
2739		    (!sc->synhw.capPalmDetect && *z <= max_pressure) ||
2740		    (sc->synhw.capPen && w == 2))) {
2741			/*
2742			 * We consider the packet irrelevant for the current
2743			 * action when:
2744			 *  - the width isn't comprised in:
2745			 *    [4; max_width]
2746			 *  - the pressure isn't comprised in:
2747			 *    [min_pressure; max_pressure]
2748			 *  - pen aren't supported but w is 2
2749			 *
2750			 *  Note that this doesn't terminate the current action.
2751			 */
2752			VLOG(2, (LOG_DEBUG,
2753			    "synaptics: palm detected! (%d)\n", w));
2754			goto SYNAPTICS_END;
2755		}
2756
2757		/* Read current absolute position. */
2758		x0 = ((pb->ipacket[3] & 0x10) << 8) |
2759		    ((pb->ipacket[1] & 0x0f) << 8) |
2760		    pb->ipacket[4];
2761		y0 = ((pb->ipacket[3] & 0x20) << 7) |
2762		    ((pb->ipacket[1] & 0xf0) << 4) |
2763		    pb->ipacket[5];
2764
2765		synaction = &(sc->synaction);
2766
2767		/*
2768		 * If the action is just beginning, init the structure and
2769		 * compute tap timeout.
2770		 */
2771		if (!(sc->flags & PSM_FLAGS_FINGERDOWN)) {
2772			VLOG(3, (LOG_DEBUG, "synaptics: ----\n"));
2773
2774			/* Store the first point of this action. */
2775			synaction->start_x = x0;
2776			synaction->start_y = y0;
2777			dx = dy = 0;
2778
2779			/* Initialize queue. */
2780			synaction->queue_cursor = SYNAPTICS_PACKETQUEUE;
2781			synaction->queue_len = 0;
2782			synaction->window_min = window_min;
2783
2784			/* Reset average. */
2785			synaction->avg_dx = 0;
2786			synaction->avg_dy = 0;
2787
2788			/* Reset squelch. */
2789			synaction->squelch_x = 0;
2790			synaction->squelch_y = 0;
2791
2792			/* Reset pressure peak. */
2793			sc->zmax = 0;
2794
2795			/* Reset fingers count. */
2796			synaction->fingers_nb = 0;
2797
2798			/* Reset virtual scrolling state. */
2799			synaction->in_vscroll = 0;
2800
2801			/* Compute tap timeout. */
2802			sc->taptimeout.tv_sec  = tap_timeout / 1000000;
2803			sc->taptimeout.tv_usec = tap_timeout % 1000000;
2804			timevaladd(&sc->taptimeout, &sc->lastsoftintr);
2805
2806			sc->flags |= PSM_FLAGS_FINGERDOWN;
2807		} else {
2808			/* Calculate the current delta. */
2809			cursor = synaction->queue_cursor;
2810			dx = x0 - synaction->queue[cursor].x;
2811			dy = y0 - synaction->queue[cursor].y;
2812		}
2813
2814		/* If in tap-hold, add the recorded button. */
2815		if (synaction->in_taphold)
2816			ms->button |= synaction->tap_button;
2817
2818		/*
2819		 * From now on, we can use the SYNAPTICS_END label to skip
2820		 * the current packet.
2821		 */
2822
2823		/*
2824		 * Limit the coordinates to the specified margins because
2825		 * this area isn't very reliable.
2826		 */
2827		if (x0 <= margin_left)
2828			x0 = margin_left;
2829		else if (x0 >= 6143 - margin_right)
2830			x0 = 6143 - margin_right;
2831		if (y0 <= margin_bottom)
2832			y0 = margin_bottom;
2833		else if (y0 >= 6143 - margin_top)
2834			y0 = 6143 - margin_top;
2835
2836		VLOG(3, (LOG_DEBUG, "synaptics: ipacket: [%d, %d], %d, %d\n",
2837		    x0, y0, *z, w));
2838
2839		/* Queue this new packet. */
2840		cursor = SYNAPTICS_QUEUE_CURSOR(synaction->queue_cursor - 1);
2841		synaction->queue[cursor].x = x0;
2842		synaction->queue[cursor].y = y0;
2843		synaction->queue_cursor = cursor;
2844		if (synaction->queue_len < SYNAPTICS_PACKETQUEUE)
2845			synaction->queue_len++;
2846		VLOG(5, (LOG_DEBUG,
2847		    "synaptics: cursor[%d]: x=%d, y=%d, dx=%d, dy=%d\n",
2848		    cursor, x0, y0, dx, dy));
2849
2850		/*
2851		 * For tap, we keep the maximum number of fingers and the
2852		 * pressure peak. Also with multiple fingers, we increase
2853		 * the minimum window.
2854		 */
2855		switch (w) {
2856		case 1: /* Three or more fingers. */
2857			synaction->fingers_nb = imax(3, synaction->fingers_nb);
2858			synaction->window_min = window_max;
2859			break;
2860		case 0: /* Two fingers. */
2861			synaction->fingers_nb = imax(2, synaction->fingers_nb);
2862			synaction->window_min = window_max;
2863			break;
2864		default: /* One finger or undetectable. */
2865			synaction->fingers_nb = imax(1, synaction->fingers_nb);
2866		}
2867		sc->zmax = imax(*z, sc->zmax);
2868
2869		/* Do we have enough packets to consider this a movement? */
2870		if (synaction->queue_len < synaction->window_min)
2871			goto SYNAPTICS_END;
2872
2873		/* Is a scrolling action occuring? */
2874		if (!synaction->in_taphold && !synaction->in_vscroll) {
2875			/*
2876			 * A scrolling action must not conflict with a tap
2877			 * action. Here are the conditions to consider a
2878			 * scrolling action:
2879			 *  - the action in a configurable area
2880			 *  - one of the following:
2881			 *     . the distance between the last packet and the
2882			 *       first should be above a configurable minimum
2883			 *     . tap timed out
2884			 */
2885			dxp = abs(synaction->queue[synaction->queue_cursor].x -
2886			    synaction->start_x);
2887			dyp = abs(synaction->queue[synaction->queue_cursor].y -
2888			    synaction->start_y);
2889
2890			if (timevalcmp(&sc->lastsoftintr, &sc->taptimeout, >) ||
2891			    dxp >= sc->syninfo.vscroll_min_delta ||
2892			    dyp >= sc->syninfo.vscroll_min_delta) {
2893				/* Check for horizontal scrolling. */
2894				if ((vscroll_hor_area > 0 &&
2895				    synaction->start_y <= vscroll_hor_area) ||
2896				    (vscroll_hor_area < 0 &&
2897				     synaction->start_y >=
2898				     6143 + vscroll_hor_area))
2899					synaction->in_vscroll += 2;
2900
2901				/* Check for vertical scrolling. */
2902				if ((vscroll_ver_area > 0 &&
2903				    synaction->start_x <= vscroll_ver_area) ||
2904				    (vscroll_ver_area < 0 &&
2905				     synaction->start_x >=
2906				     6143 + vscroll_ver_area))
2907					synaction->in_vscroll += 1;
2908
2909				/* Avoid conflicts if area overlaps. */
2910				if (synaction->in_vscroll == 3)
2911					synaction->in_vscroll =
2912					    (dxp > dyp) ? 2 : 1;
2913			}
2914			VLOG(5, (LOG_DEBUG,
2915			    "synaptics: virtual scrolling: %s "
2916			    "(direction=%d, dxp=%d, dyp=%d)\n",
2917			    synaction->in_vscroll ? "YES" : "NO",
2918			    synaction->in_vscroll, dxp, dyp));
2919		}
2920
2921		weight_prev_x = weight_prev_y = weight_previous;
2922		div_max_x = div_max_y = div_max;
2923
2924		if (synaction->in_vscroll) {
2925			/* Dividers are different with virtual scrolling. */
2926			div_min = sc->syninfo.vscroll_div_min;
2927			div_max_x = div_max_y = sc->syninfo.vscroll_div_max;
2928		} else {
2929			/*
2930			 * There's a lot of noise in coordinates when
2931			 * the finger is on the touchpad's borders. When
2932			 * using this area, we apply a special weight and
2933			 * div.
2934			 */
2935			if (x0 <= na_left || x0 >= 6143 - na_right) {
2936				weight_prev_x = sc->syninfo.weight_previous_na;
2937				div_max_x = sc->syninfo.div_max_na;
2938			}
2939
2940			if (y0 <= na_bottom || y0 >= 6143 - na_top) {
2941				weight_prev_y = sc->syninfo.weight_previous_na;
2942				div_max_y = sc->syninfo.div_max_na;
2943			}
2944		}
2945
2946		/*
2947		 * Calculate weights for the average operands and
2948		 * the divisor. Both depend on the distance between
2949		 * the current packet and a previous one (based on the
2950		 * window width).
2951		 */
2952		window = imin(synaction->queue_len, window_max);
2953		peer = SYNAPTICS_QUEUE_CURSOR(cursor + window - 1);
2954		dxp = abs(x0 - synaction->queue[peer].x) + 1;
2955		dyp = abs(y0 - synaction->queue[peer].y) + 1;
2956		len = (dxp * dxp) + (dyp * dyp);
2957		weight_prev_x = imin(weight_prev_x,
2958		    weight_len_squared * weight_prev_x / len);
2959		weight_prev_y = imin(weight_prev_y,
2960		    weight_len_squared * weight_prev_y / len);
2961
2962		len = (dxp + dyp) / 2;
2963		div_x = div_len * div_max_x / len;
2964		div_x = imin(div_max_x, div_x);
2965		div_x = imax(div_min, div_x);
2966		div_y = div_len * div_max_y / len;
2967		div_y = imin(div_max_y, div_y);
2968		div_y = imax(div_min, div_y);
2969
2970		VLOG(3, (LOG_DEBUG,
2971		    "synaptics: peer=%d, len=%d, weight=%d/%d, div=%d/%d\n",
2972		    peer, len, weight_prev_x, weight_prev_y, div_x, div_y));
2973
2974		/* Compute averages. */
2975		synaction->avg_dx =
2976		    (weight_current * dx * multiplicator +
2977		     weight_prev_x * synaction->avg_dx) /
2978		    (weight_current + weight_prev_x);
2979
2980		synaction->avg_dy =
2981		    (weight_current * dy * multiplicator +
2982		     weight_prev_y * synaction->avg_dy) /
2983		    (weight_current + weight_prev_y);
2984
2985		VLOG(5, (LOG_DEBUG,
2986		    "synaptics: avg_dx~=%d, avg_dy~=%d\n",
2987		    synaction->avg_dx / multiplicator,
2988		    synaction->avg_dy / multiplicator));
2989
2990		/* Use these averages to calculate x & y. */
2991		synaction->squelch_x += synaction->avg_dx;
2992		*x = synaction->squelch_x / (div_x * multiplicator);
2993		synaction->squelch_x = synaction->squelch_x %
2994		    (div_x * multiplicator);
2995
2996		synaction->squelch_y += synaction->avg_dy;
2997		*y = synaction->squelch_y / (div_y * multiplicator);
2998		synaction->squelch_y = synaction->squelch_y %
2999		    (div_y * multiplicator);
3000
3001		if (synaction->in_vscroll) {
3002			switch(synaction->in_vscroll) {
3003			case 1: /* Vertical scrolling. */
3004				if (*y != 0)
3005					ms->button |= (*y > 0) ?
3006					    MOUSE_BUTTON4DOWN :
3007					    MOUSE_BUTTON5DOWN;
3008				break;
3009			case 2: /* Horizontal scrolling. */
3010				if (*x != 0)
3011					ms->button |= (*x > 0) ?
3012					    MOUSE_BUTTON7DOWN :
3013					    MOUSE_BUTTON6DOWN;
3014				break;
3015			}
3016
3017			/* The pointer is not moved. */
3018			*x = *y = 0;
3019		} else {
3020			VLOG(3, (LOG_DEBUG, "synaptics: [%d, %d] -> [%d, %d]\n",
3021			    dx, dy, *x, *y));
3022		}
3023	} else if (sc->flags & PSM_FLAGS_FINGERDOWN) {
3024		/*
3025		 * An action is currently taking place but the pressure
3026		 * dropped under the minimum, putting an end to it.
3027		 */
3028		synapticsaction_t *synaction;
3029		int taphold_timeout, dx, dy, tap_max_delta;
3030
3031		synaction = &(sc->synaction);
3032		dx = abs(synaction->queue[synaction->queue_cursor].x -
3033		    synaction->start_x);
3034		dy = abs(synaction->queue[synaction->queue_cursor].y -
3035		    synaction->start_y);
3036
3037		/* Max delta is disabled for multi-fingers tap. */
3038		if (synaction->fingers_nb > 1)
3039			tap_max_delta = imax(dx, dy);
3040		else
3041			tap_max_delta = sc->syninfo.tap_max_delta;
3042
3043		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
3044
3045		/* Check for tap. */
3046		VLOG(3, (LOG_DEBUG,
3047		    "synaptics: zmax=%d, dx=%d, dy=%d, "
3048		    "delta=%d, fingers=%d, queue=%d\n",
3049		    sc->zmax, dx, dy, tap_max_delta, synaction->fingers_nb,
3050		    synaction->queue_len));
3051		if (!synaction->in_vscroll && sc->zmax >= tap_threshold &&
3052		    timevalcmp(&sc->lastsoftintr, &sc->taptimeout, <=) &&
3053		    dx <= tap_max_delta && dy <= tap_max_delta &&
3054		    synaction->queue_len >= sc->syninfo.tap_min_queue) {
3055			/*
3056			 * We have a tap if:
3057			 *   - the maximum pressure went over tap_threshold
3058			 *   - the action ended before tap_timeout
3059			 *
3060			 * To handle tap-hold, we must delay any button push to
3061			 * the next action.
3062			 */
3063			if (synaction->in_taphold) {
3064				/*
3065				 * This is the second and last tap of a
3066				 * double tap action, not a tap-hold.
3067				 */
3068				synaction->in_taphold = 0;
3069
3070				/*
3071				 * For double-tap to work:
3072				 *   - no button press is emitted (to
3073				 *     simulate a button release)
3074				 *   - PSM_FLAGS_FINGERDOWN is set to
3075				 *     force the next packet to emit a
3076				 *     button press)
3077				 */
3078				VLOG(2, (LOG_DEBUG,
3079				    "synaptics: button RELEASE: %d\n",
3080				    synaction->tap_button));
3081				sc->flags |= PSM_FLAGS_FINGERDOWN;
3082			} else {
3083				/*
3084				 * This is the first tap: we set the
3085				 * tap-hold state and notify the button
3086				 * down event.
3087				 */
3088				synaction->in_taphold = 1;
3089				taphold_timeout = sc->syninfo.taphold_timeout;
3090				sc->taptimeout.tv_sec  = taphold_timeout /
3091				    1000000;
3092				sc->taptimeout.tv_usec = taphold_timeout %
3093				    1000000;
3094				timevaladd(&sc->taptimeout, &sc->lastsoftintr);
3095
3096				switch (synaction->fingers_nb) {
3097				case 3:
3098					synaction->tap_button =
3099					    MOUSE_BUTTON2DOWN;
3100					break;
3101				case 2:
3102					synaction->tap_button =
3103					    MOUSE_BUTTON3DOWN;
3104					break;
3105				default:
3106					synaction->tap_button =
3107					    MOUSE_BUTTON1DOWN;
3108				}
3109				VLOG(2, (LOG_DEBUG,
3110				    "synaptics: button PRESS: %d\n",
3111				    synaction->tap_button));
3112				ms->button |= synaction->tap_button;
3113			}
3114		} else {
3115			/*
3116			 * Not enough pressure or timeout: reset
3117			 * tap-hold state.
3118			 */
3119			if (synaction->in_taphold) {
3120				VLOG(2, (LOG_DEBUG,
3121				    "synaptics: button RELEASE: %d\n",
3122				    synaction->tap_button));
3123				synaction->in_taphold = 0;
3124			} else {
3125				VLOG(2, (LOG_DEBUG,
3126				    "synaptics: not a tap-hold\n"));
3127			}
3128		}
3129	} else if (!(sc->flags & PSM_FLAGS_FINGERDOWN) &&
3130	    sc->synaction.in_taphold) {
3131		/*
3132		 * For a tap-hold to work, the button must remain down at
3133		 * least until timeout (where the in_taphold flags will be
3134		 * cleared) or during the next action.
3135		 */
3136		if (timevalcmp(&sc->lastsoftintr, &sc->taptimeout, <=)) {
3137			ms->button |= sc->synaction.tap_button;
3138		} else {
3139			VLOG(2, (LOG_DEBUG,
3140			    "synaptics: button RELEASE: %d\n",
3141			    sc->synaction.tap_button));
3142			sc->synaction.in_taphold = 0;
3143		}
3144	}
3145
3146SYNAPTICS_END:
3147	/*
3148	 * Use the extra buttons as a scrollwheel
3149	 *
3150	 * XXX X.Org uses the Z axis for vertical wheel only,
3151	 * whereas moused(8) understands special values to differ
3152	 * vertical and horizontal wheels.
3153	 *
3154	 * xf86-input-mouse needs therefore a small patch to
3155	 * understand these special values. Without it, the
3156	 * horizontal wheel acts as a vertical wheel in X.Org.
3157	 *
3158	 * That's why the horizontal wheel is disabled by
3159	 * default for now.
3160	 */
3161	if (ms->button & MOUSE_BUTTON4DOWN) {
3162		*z = -1;
3163		ms->button &= ~MOUSE_BUTTON4DOWN;
3164	} else if (ms->button & MOUSE_BUTTON5DOWN) {
3165		*z = 1;
3166		ms->button &= ~MOUSE_BUTTON5DOWN;
3167	} else if (ms->button & MOUSE_BUTTON6DOWN) {
3168		*z = -2;
3169		ms->button &= ~MOUSE_BUTTON6DOWN;
3170	} else if (ms->button & MOUSE_BUTTON7DOWN) {
3171		*z = 2;
3172		ms->button &= ~MOUSE_BUTTON7DOWN;
3173	} else
3174		*z = 0;
3175
3176	return (0);
3177}
3178
3179static void
3180proc_versapad(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
3181    int *x, int *y, int *z)
3182{
3183	static int butmap_versapad[8] = {
3184		0,
3185		MOUSE_BUTTON3DOWN,
3186		0,
3187		MOUSE_BUTTON3DOWN,
3188		MOUSE_BUTTON1DOWN,
3189		MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
3190		MOUSE_BUTTON1DOWN,
3191		MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
3192	};
3193	int c, x0, y0;
3194
3195	/* VersaPad PS/2 absolute mode message format
3196	 *
3197	 * [packet1]     7   6   5   4   3   2   1   0(LSB)
3198	 *  ipacket[0]:  1   1   0   A   1   L   T   R
3199	 *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
3200	 *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
3201	 *  ipacket[3]:  1   1   1   A   1   L   T   R
3202	 *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
3203	 *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
3204	 *
3205	 * [note]
3206	 *  R: right physical mouse button (1=on)
3207	 *  T: touch pad virtual button (1=tapping)
3208	 *  L: left physical mouse button (1=on)
3209	 *  A: position data is valid (1=valid)
3210	 *  H: horizontal data (12bit signed integer. H11 is sign bit.)
3211	 *  V: vertical data (12bit signed integer. V11 is sign bit.)
3212	 *  P: pressure data
3213	 *
3214	 * Tapping is mapped to MOUSE_BUTTON4.
3215	 */
3216	c = pb->ipacket[0];
3217	*x = *y = 0;
3218	ms->button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
3219	ms->button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
3220	if (c & MOUSE_PS2VERSA_IN_USE) {
3221		x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
3222		y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
3223		if (x0 & 0x800)
3224			x0 -= 0x1000;
3225		if (y0 & 0x800)
3226			y0 -= 0x1000;
3227		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
3228			*x = sc->xold - x0;
3229			*y = y0 - sc->yold;
3230			if (*x < 0)	/* XXX */
3231				++*x;
3232			else if (*x)
3233				--*x;
3234			if (*y < 0)
3235				++*y;
3236			else if (*y)
3237				--*y;
3238		} else
3239			sc->flags |= PSM_FLAGS_FINGERDOWN;
3240		sc->xold = x0;
3241		sc->yold = y0;
3242	} else
3243		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
3244}
3245
3246static void
3247psmsoftintr(void *arg)
3248{
3249	/*
3250	 * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
3251	 * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
3252	 */
3253	static int butmap[8] = {
3254		0,
3255		MOUSE_BUTTON1DOWN,
3256		MOUSE_BUTTON3DOWN,
3257		MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
3258		MOUSE_BUTTON2DOWN,
3259		MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
3260		MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
3261		MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
3262	};
3263	struct psm_softc *sc = arg;
3264	mousestatus_t ms;
3265	packetbuf_t *pb;
3266	int x, y, z, c, l, s;
3267
3268	getmicrouptime(&sc->lastsoftintr);
3269
3270	s = spltty();
3271
3272	do {
3273		pb = &sc->pqueue[sc->pqueue_start];
3274
3275		if (sc->mode.level == PSM_LEVEL_NATIVE)
3276			goto next_native;
3277
3278		c = pb->ipacket[0];
3279		/*
3280		 * A kludge for Kensington device!
3281		 * The MSB of the horizontal count appears to be stored in
3282		 * a strange place.
3283		 */
3284		if (sc->hw.model == MOUSE_MODEL_THINK)
3285			pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
3286
3287		/* ignore the overflow bits... */
3288		x = (c & MOUSE_PS2_XNEG) ?
3289		    pb->ipacket[1] - 256 : pb->ipacket[1];
3290		y = (c & MOUSE_PS2_YNEG) ?
3291		    pb->ipacket[2] - 256 : pb->ipacket[2];
3292		z = 0;
3293		ms.obutton = sc->button;	  /* previous button state */
3294		ms.button = butmap[c & MOUSE_PS2_BUTTONS];
3295		/* `tapping' action */
3296		if (sc->config & PSM_CONFIG_FORCETAP)
3297			ms.button |= ((c & MOUSE_PS2_TAP)) ?
3298			    0 : MOUSE_BUTTON4DOWN;
3299
3300		switch (sc->hw.model) {
3301
3302		case MOUSE_MODEL_EXPLORER:
3303			/*
3304			 *          b7 b6 b5 b4 b3 b2 b1 b0
3305			 * byte 1:  oy ox sy sx 1  M  R  L
3306			 * byte 2:  x  x  x  x  x  x  x  x
3307			 * byte 3:  y  y  y  y  y  y  y  y
3308			 * byte 4:  *  *  S2 S1 s  d2 d1 d0
3309			 *
3310			 * L, M, R, S1, S2: left, middle, right and side buttons
3311			 * s: wheel data sign bit
3312			 * d2-d0: wheel data
3313			 */
3314			z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG) ?
3315			    (pb->ipacket[3] & 0x0f) - 16 :
3316			    (pb->ipacket[3] & 0x0f);
3317			ms.button |=
3318			    (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN) ?
3319			    MOUSE_BUTTON4DOWN : 0;
3320			ms.button |=
3321			    (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN) ?
3322			    MOUSE_BUTTON5DOWN : 0;
3323			break;
3324
3325		case MOUSE_MODEL_INTELLI:
3326		case MOUSE_MODEL_NET:
3327			/* wheel data is in the fourth byte */
3328			z = (char)pb->ipacket[3];
3329			/*
3330			 * XXX some mice may send 7 when there is no Z movement?			 */
3331			if ((z >= 7) || (z <= -7))
3332				z = 0;
3333			/* some compatible mice have additional buttons */
3334			ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN) ?
3335			    MOUSE_BUTTON4DOWN : 0;
3336			ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN) ?
3337			    MOUSE_BUTTON5DOWN : 0;
3338			break;
3339
3340		case MOUSE_MODEL_MOUSEMANPLUS:
3341			proc_mmanplus(sc, pb, &ms, &x, &y, &z);
3342			break;
3343
3344		case MOUSE_MODEL_GLIDEPOINT:
3345			/* `tapping' action */
3346			ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 :
3347			    MOUSE_BUTTON4DOWN;
3348			break;
3349
3350		case MOUSE_MODEL_NETSCROLL:
3351			/*
3352			 * three addtional bytes encode buttons and
3353			 * wheel events
3354			 */
3355			ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN) ?
3356			    MOUSE_BUTTON4DOWN : 0;
3357			ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN) ?
3358			    MOUSE_BUTTON5DOWN : 0;
3359			z = (pb->ipacket[3] & MOUSE_PS2_XNEG) ?
3360			    pb->ipacket[4] - 256 : pb->ipacket[4];
3361			break;
3362
3363		case MOUSE_MODEL_THINK:
3364			/* the fourth button state in the first byte */
3365			ms.button |= (c & MOUSE_PS2_TAP) ?
3366			    MOUSE_BUTTON4DOWN : 0;
3367			break;
3368
3369		case MOUSE_MODEL_VERSAPAD:
3370			proc_versapad(sc, pb, &ms, &x, &y, &z);
3371			c = ((x < 0) ? MOUSE_PS2_XNEG : 0) |
3372			    ((y < 0) ? MOUSE_PS2_YNEG : 0);
3373			break;
3374
3375		case MOUSE_MODEL_4D:
3376			/*
3377			 *          b7 b6 b5 b4 b3 b2 b1 b0
3378			 * byte 1:  s2 d2 s1 d1 1  M  R  L
3379			 * byte 2:  sx x  x  x  x  x  x  x
3380			 * byte 3:  sy y  y  y  y  y  y  y
3381			 *
3382			 * s1: wheel 1 direction
3383			 * d1: wheel 1 data
3384			 * s2: wheel 2 direction
3385			 * d2: wheel 2 data
3386			 */
3387			x = (pb->ipacket[1] & 0x80) ?
3388			    pb->ipacket[1] - 256 : pb->ipacket[1];
3389			y = (pb->ipacket[2] & 0x80) ?
3390			    pb->ipacket[2] - 256 : pb->ipacket[2];
3391			switch (c & MOUSE_4D_WHEELBITS) {
3392			case 0x10:
3393				z = 1;
3394				break;
3395			case 0x30:
3396				z = -1;
3397				break;
3398			case 0x40:	/* XXX 2nd wheel turning right */
3399				z = 2;
3400				break;
3401			case 0xc0:	/* XXX 2nd wheel turning left */
3402				z = -2;
3403				break;
3404			}
3405			break;
3406
3407		case MOUSE_MODEL_4DPLUS:
3408			if ((x < 16 - 256) && (y < 16 - 256)) {
3409				/*
3410				 *          b7 b6 b5 b4 b3 b2 b1 b0
3411				 * byte 1:  0  0  1  1  1  M  R  L
3412				 * byte 2:  0  0  0  0  1  0  0  0
3413				 * byte 3:  0  0  0  0  S  s  d1 d0
3414				 *
3415				 * L, M, R, S: left, middle, right,
3416				 *             and side buttons
3417				 * s: wheel data sign bit
3418				 * d1-d0: wheel data
3419				 */
3420				x = y = 0;
3421				if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
3422					ms.button |= MOUSE_BUTTON4DOWN;
3423				z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG) ?
3424				    ((pb->ipacket[2] & 0x07) - 8) :
3425				    (pb->ipacket[2] & 0x07) ;
3426			} else {
3427				/* preserve previous button states */
3428				ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
3429			}
3430			break;
3431
3432		case MOUSE_MODEL_SYNAPTICS:
3433			if (proc_synaptics(sc, pb, &ms, &x, &y, &z) != 0)
3434				goto next;
3435			break;
3436
3437		case MOUSE_MODEL_GENERIC:
3438		default:
3439			break;
3440		}
3441
3442	/* scale values */
3443	if (sc->mode.accelfactor >= 1) {
3444		if (x != 0) {
3445			x = x * x / sc->mode.accelfactor;
3446			if (x == 0)
3447				x = 1;
3448			if (c & MOUSE_PS2_XNEG)
3449				x = -x;
3450		}
3451		if (y != 0) {
3452			y = y * y / sc->mode.accelfactor;
3453			if (y == 0)
3454				y = 1;
3455			if (c & MOUSE_PS2_YNEG)
3456				y = -y;
3457		}
3458	}
3459
3460	ms.dx = x;
3461	ms.dy = y;
3462	ms.dz = z;
3463	ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0) |
3464	    (ms.obutton ^ ms.button);
3465
3466	pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);
3467
3468	sc->status.flags |= ms.flags;
3469	sc->status.dx += ms.dx;
3470	sc->status.dy += ms.dy;
3471	sc->status.dz += ms.dz;
3472	sc->status.button = ms.button;
3473	sc->button = ms.button;
3474
3475next_native:
3476	sc->watchdog = FALSE;
3477
3478	/* queue data */
3479	if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
3480		l = imin(pb->inputbytes,
3481		    sizeof(sc->queue.buf) - sc->queue.tail);
3482		bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
3483		if (pb->inputbytes > l)
3484			bcopy(&pb->ipacket[l], &sc->queue.buf[0],
3485			    pb->inputbytes - l);
3486		sc->queue.tail = (sc->queue.tail + pb->inputbytes) %
3487		    sizeof(sc->queue.buf);
3488		sc->queue.count += pb->inputbytes;
3489	}
3490	pb->inputbytes = 0;
3491
3492next:
3493	if (++sc->pqueue_start >= PSM_PACKETQUEUE)
3494		sc->pqueue_start = 0;
3495	} while (sc->pqueue_start != sc->pqueue_end);
3496
3497	if (sc->state & PSM_ASLP) {
3498		sc->state &= ~PSM_ASLP;
3499		wakeup(sc);
3500	}
3501	selwakeuppri(&sc->rsel, PZERO);
3502	if (sc->async != NULL) {
3503		pgsigio(&sc->async, SIGIO, 0);
3504	}
3505	sc->state &= ~PSM_SOFTARMED;
3506	splx(s);
3507}
3508
3509static int
3510psmpoll(struct cdev *dev, int events, struct thread *td)
3511{
3512	struct psm_softc *sc = dev->si_drv1;
3513	int s;
3514	int revents = 0;
3515
3516	/* Return true if a mouse event available */
3517	s = spltty();
3518	if (events & (POLLIN | POLLRDNORM)) {
3519		if (sc->queue.count > 0)
3520			revents |= events & (POLLIN | POLLRDNORM);
3521		else
3522			selrecord(td, &sc->rsel);
3523	}
3524	splx(s);
3525
3526	return (revents);
3527}
3528
3529/* vendor/model specific routines */
3530
3531static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
3532{
3533	if (set_mouse_resolution(kbdc, res) != res)
3534		return (FALSE);
3535	if (set_mouse_scaling(kbdc, scale) &&
3536	    set_mouse_scaling(kbdc, scale) &&
3537	    set_mouse_scaling(kbdc, scale) &&
3538	    (get_mouse_status(kbdc, status, 0, 3) >= 3))
3539		return (TRUE);
3540	return (FALSE);
3541}
3542
3543static int
3544mouse_ext_command(KBDC kbdc, int command)
3545{
3546	int c;
3547
3548	c = (command >> 6) & 0x03;
3549	if (set_mouse_resolution(kbdc, c) != c)
3550		return (FALSE);
3551	c = (command >> 4) & 0x03;
3552	if (set_mouse_resolution(kbdc, c) != c)
3553		return (FALSE);
3554	c = (command >> 2) & 0x03;
3555	if (set_mouse_resolution(kbdc, c) != c)
3556		return (FALSE);
3557	c = (command >> 0) & 0x03;
3558	if (set_mouse_resolution(kbdc, c) != c)
3559		return (FALSE);
3560	return (TRUE);
3561}
3562
3563#ifdef notyet
3564/* Logitech MouseMan Cordless II */
3565static int
3566enable_lcordless(KDBC kbdc, struct psm_softc *sc)
3567{
3568	int status[3];
3569	int ch;
3570
3571	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 2, status))
3572		return (FALSE);
3573	if (status[1] == PSMD_RES_HIGH)
3574		return (FALSE);
3575	ch = (status[0] & 0x07) - 1;	/* channel # */
3576	if ((ch <= 0) || (ch > 4))
3577		return (FALSE);
3578	/*
3579	 * status[1]: always one?
3580	 * status[2]: battery status? (0-100)
3581	 */
3582	return (TRUE);
3583}
3584#endif /* notyet */
3585
3586/* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
3587static int
3588enable_groller(KBDC kbdc, struct psm_softc *sc)
3589{
3590	int status[3];
3591
3592	/*
3593	 * The special sequence to enable the fourth button and the
3594	 * roller. Immediately after this sequence check status bytes.
3595	 * if the mouse is NetScroll, the second and the third bytes are
3596	 * '3' and 'D'.
3597	 */
3598
3599	/*
3600	 * If the mouse is an ordinary PS/2 mouse, the status bytes should
3601	 * look like the following.
3602	 *
3603	 * byte 1 bit 7 always 0
3604	 *        bit 6 stream mode (0)
3605	 *        bit 5 disabled (0)
3606	 *        bit 4 1:1 scaling (0)
3607	 *        bit 3 always 0
3608	 *        bit 0-2 button status
3609	 * byte 2 resolution (PSMD_RES_HIGH)
3610	 * byte 3 report rate (?)
3611	 */
3612
3613	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
3614		return (FALSE);
3615	if ((status[1] != '3') || (status[2] != 'D'))
3616		return (FALSE);
3617	/* FIXME: SmartScroll Mouse has 5 buttons! XXX */
3618	if (sc != NULL)
3619		sc->hw.buttons = 4;
3620	return (TRUE);
3621}
3622
3623/* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
3624static int
3625enable_gmouse(KBDC kbdc, struct psm_softc *sc)
3626{
3627	int status[3];
3628
3629	/*
3630	 * The special sequence to enable the middle, "rubber" button.
3631	 * Immediately after this sequence check status bytes.
3632	 * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
3633	 * the second and the third bytes are '3' and 'U'.
3634	 * NOTE: NetMouse reports that it has three buttons although it has
3635	 * two buttons and a rubber button. NetMouse Pro and MIE Mouse
3636	 * say they have three buttons too and they do have a button on the
3637	 * side...
3638	 */
3639	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
3640		return (FALSE);
3641	if ((status[1] != '3') || (status[2] != 'U'))
3642		return (FALSE);
3643	return (TRUE);
3644}
3645
3646/* ALPS GlidePoint */
3647static int
3648enable_aglide(KBDC kbdc, struct psm_softc *sc)
3649{
3650	int status[3];
3651
3652	/*
3653	 * The special sequence to obtain ALPS GlidePoint specific
3654	 * information. Immediately after this sequence, status bytes will
3655	 * contain something interesting.
3656	 * NOTE: ALPS produces several models of GlidePoint. Some of those
3657	 * do not respond to this sequence, thus, cannot be detected this way.
3658	 */
3659	if (set_mouse_sampling_rate(kbdc, 100) != 100)
3660		return (FALSE);
3661	if (!mouse_id_proc1(kbdc, PSMD_RES_LOW, 2, status))
3662		return (FALSE);
3663	if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
3664		return (FALSE);
3665	return (TRUE);
3666}
3667
3668/* Kensington ThinkingMouse/Trackball */
3669static int
3670enable_kmouse(KBDC kbdc, struct psm_softc *sc)
3671{
3672	static u_char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
3673	int status[3];
3674	int id1;
3675	int id2;
3676	int i;
3677
3678	id1 = get_aux_id(kbdc);
3679	if (set_mouse_sampling_rate(kbdc, 10) != 10)
3680		return (FALSE);
3681	/*
3682	 * The device is now in the native mode? It returns a different
3683	 * ID value...
3684	 */
3685	id2 = get_aux_id(kbdc);
3686	if ((id1 == id2) || (id2 != 2))
3687		return (FALSE);
3688
3689	if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
3690		return (FALSE);
3691#if PSM_DEBUG >= 2
3692	/* at this point, resolution is LOW, sampling rate is 10/sec */
3693	if (get_mouse_status(kbdc, status, 0, 3) < 3)
3694		return (FALSE);
3695#endif
3696
3697	/*
3698	 * The special sequence to enable the third and fourth buttons.
3699	 * Otherwise they behave like the first and second buttons.
3700	 */
3701	for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3702		if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3703			return (FALSE);
3704
3705	/*
3706	 * At this point, the device is using default resolution and
3707	 * sampling rate for the native mode.
3708	 */
3709	if (get_mouse_status(kbdc, status, 0, 3) < 3)
3710		return (FALSE);
3711	if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
3712		return (FALSE);
3713
3714	/* the device appears be enabled by this sequence, diable it for now */
3715	disable_aux_dev(kbdc);
3716	empty_aux_buffer(kbdc, 5);
3717
3718	return (TRUE);
3719}
3720
3721/* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
3722static int
3723enable_mmanplus(KBDC kbdc, struct psm_softc *sc)
3724{
3725	int data[3];
3726
3727	/* the special sequence to enable the fourth button and the roller. */
3728	/*
3729	 * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
3730	 * must be called exactly three times since the last RESET command
3731	 * before this sequence. XXX
3732	 */
3733	if (!set_mouse_scaling(kbdc, 1))
3734		return (FALSE);
3735	if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
3736		return (FALSE);
3737	if (get_mouse_status(kbdc, data, 1, 3) < 3)
3738		return (FALSE);
3739
3740	/*
3741	 * PS2++ protocol, packet type 0
3742	 *
3743	 *          b7 b6 b5 b4 b3 b2 b1 b0
3744	 * byte 1:  *  1  p3 p2 1  *  *  *
3745	 * byte 2:  1  1  p1 p0 m1 m0 1  0
3746	 * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
3747	 *
3748	 * p3-p0: packet type: 0
3749	 * m7-m0: model ID: MouseMan+:0x50,
3750	 *		    FirstMouse+:0x51,
3751	 *		    ScrollPoint:0x58...
3752	 */
3753	/* check constant bits */
3754	if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
3755		return (FALSE);
3756	if ((data[1] & 0xc3) != 0xc2)
3757		return (FALSE);
3758	/* check d3-d0 in byte 2 */
3759	if (!MOUSE_PS2PLUS_CHECKBITS(data))
3760		return (FALSE);
3761	/* check p3-p0 */
3762	if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
3763		return (FALSE);
3764
3765	if (sc != NULL) {
3766		sc->hw.hwid &= 0x00ff;
3767		sc->hw.hwid |= data[2] << 8;	/* save model ID */
3768	}
3769
3770	/*
3771	 * MouseMan+ (or FirstMouse+) is now in its native mode, in which
3772	 * the wheel and the fourth button events are encoded in the
3773	 * special data packet. The mouse may be put in the IntelliMouse mode
3774	 * if it is initialized by the IntelliMouse's method.
3775	 */
3776	return (TRUE);
3777}
3778
3779/* MS IntelliMouse Explorer */
3780static int
3781enable_msexplorer(KBDC kbdc, struct psm_softc *sc)
3782{
3783	static u_char rate0[] = { 200, 100, 80, };
3784	static u_char rate1[] = { 200, 200, 80, };
3785	int id;
3786	int i;
3787
3788	/*
3789	 * This is needed for at least A4Tech X-7xx mice - they do not go
3790	 * straight to Explorer mode, but need to be set to Intelli mode
3791	 * first.
3792	 */
3793	enable_msintelli(kbdc, sc);
3794
3795	/* the special sequence to enable the extra buttons and the roller. */
3796	for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i)
3797		if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
3798			return (FALSE);
3799	/* the device will give the genuine ID only after the above sequence */
3800	id = get_aux_id(kbdc);
3801	if (id != PSM_EXPLORER_ID)
3802		return (FALSE);
3803
3804	if (sc != NULL) {
3805		sc->hw.buttons = 5;	/* IntelliMouse Explorer XXX */
3806		sc->hw.hwid = id;
3807	}
3808
3809	/*
3810	 * XXX: this is a kludge to fool some KVM switch products
3811	 * which think they are clever enough to know the 4-byte IntelliMouse
3812	 * protocol, and assume any other protocols use 3-byte packets.
3813	 * They don't convey 4-byte data packets from the IntelliMouse Explorer
3814	 * correctly to the host computer because of this!
3815	 * The following sequence is actually IntelliMouse's "wake up"
3816	 * sequence; it will make the KVM think the mouse is IntelliMouse
3817	 * when it is in fact IntelliMouse Explorer.
3818	 */
3819	for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i)
3820		if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
3821			break;
3822	get_aux_id(kbdc);
3823
3824	return (TRUE);
3825}
3826
3827/* MS IntelliMouse */
3828static int
3829enable_msintelli(KBDC kbdc, struct psm_softc *sc)
3830{
3831	/*
3832	 * Logitech MouseMan+ and FirstMouse+ will also respond to this
3833	 * probe routine and act like IntelliMouse.
3834	 */
3835
3836	static u_char rate[] = { 200, 100, 80, };
3837	int id;
3838	int i;
3839
3840	/* the special sequence to enable the third button and the roller. */
3841	for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3842		if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3843			return (FALSE);
3844	/* the device will give the genuine ID only after the above sequence */
3845	id = get_aux_id(kbdc);
3846	if (id != PSM_INTELLI_ID)
3847		return (FALSE);
3848
3849	if (sc != NULL) {
3850		sc->hw.buttons = 3;
3851		sc->hw.hwid = id;
3852	}
3853
3854	return (TRUE);
3855}
3856
3857/* A4 Tech 4D Mouse */
3858static int
3859enable_4dmouse(KBDC kbdc, struct psm_softc *sc)
3860{
3861	/*
3862	 * Newer wheel mice from A4 Tech may use the 4D+ protocol.
3863	 */
3864
3865	static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
3866	int id;
3867	int i;
3868
3869	for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3870		if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3871			return (FALSE);
3872	id = get_aux_id(kbdc);
3873	/*
3874	 * WinEasy 4D, 4 Way Scroll 4D: 6
3875	 * Cable-Free 4D: 8 (4DPLUS)
3876	 * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
3877	 */
3878	if (id != PSM_4DMOUSE_ID)
3879		return (FALSE);
3880
3881	if (sc != NULL) {
3882		sc->hw.buttons = 3;	/* XXX some 4D mice have 4? */
3883		sc->hw.hwid = id;
3884	}
3885
3886	return (TRUE);
3887}
3888
3889/* A4 Tech 4D+ Mouse */
3890static int
3891enable_4dplus(KBDC kbdc, struct psm_softc *sc)
3892{
3893	/*
3894	 * Newer wheel mice from A4 Tech seem to use this protocol.
3895	 * Older models are recognized as either 4D Mouse or IntelliMouse.
3896	 */
3897	int id;
3898
3899	/*
3900	 * enable_4dmouse() already issued the following ID sequence...
3901	static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
3902	int i;
3903
3904	for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3905		if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3906			return (FALSE);
3907	*/
3908
3909	id = get_aux_id(kbdc);
3910	switch (id) {
3911	case PSM_4DPLUS_ID:
3912		break;
3913	case PSM_4DPLUS_RFSW35_ID:
3914		break;
3915	default:
3916		return (FALSE);
3917	}
3918
3919	if (sc != NULL) {
3920		sc->hw.buttons = (id == PSM_4DPLUS_ID) ? 4 : 3;
3921		sc->hw.hwid = id;
3922	}
3923
3924	return (TRUE);
3925}
3926
3927/* Synaptics Touchpad */
3928static int
3929synaptics_sysctl(SYSCTL_HANDLER_ARGS)
3930{
3931	int error, arg;
3932
3933	/* Read the current value. */
3934	arg = *(int *)oidp->oid_arg1;
3935	error = sysctl_handle_int(oidp, &arg, 0, req);
3936
3937	/* Sanity check. */
3938	if (error || !req->newptr)
3939		return (error);
3940
3941	/*
3942	 * Check that the new value is in the concerned node's range
3943	 * of values.
3944	 */
3945	switch (oidp->oid_arg2) {
3946	case SYNAPTICS_SYSCTL_MIN_PRESSURE:
3947	case SYNAPTICS_SYSCTL_MAX_PRESSURE:
3948		if (arg < 0 || arg > 255)
3949			return (EINVAL);
3950		break;
3951	case SYNAPTICS_SYSCTL_MAX_WIDTH:
3952		if (arg < 4 || arg > 15)
3953			return (EINVAL);
3954		break;
3955	case SYNAPTICS_SYSCTL_MARGIN_TOP:
3956	case SYNAPTICS_SYSCTL_MARGIN_RIGHT:
3957	case SYNAPTICS_SYSCTL_MARGIN_BOTTOM:
3958	case SYNAPTICS_SYSCTL_MARGIN_LEFT:
3959	case SYNAPTICS_SYSCTL_NA_TOP:
3960	case SYNAPTICS_SYSCTL_NA_RIGHT:
3961	case SYNAPTICS_SYSCTL_NA_BOTTOM:
3962	case SYNAPTICS_SYSCTL_NA_LEFT:
3963		if (arg < 0 || arg > 6143)
3964			return (EINVAL);
3965		break;
3966	case SYNAPTICS_SYSCTL_WINDOW_MIN:
3967	case SYNAPTICS_SYSCTL_WINDOW_MAX:
3968	case SYNAPTICS_SYSCTL_TAP_MIN_QUEUE:
3969		if (arg < 1 || arg > SYNAPTICS_PACKETQUEUE)
3970			return (EINVAL);
3971		break;
3972	case SYNAPTICS_SYSCTL_MULTIPLICATOR:
3973	case SYNAPTICS_SYSCTL_WEIGHT_CURRENT:
3974	case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS:
3975	case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA:
3976	case SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED:
3977	case SYNAPTICS_SYSCTL_DIV_MIN:
3978	case SYNAPTICS_SYSCTL_DIV_MAX:
3979	case SYNAPTICS_SYSCTL_DIV_MAX_NA:
3980	case SYNAPTICS_SYSCTL_DIV_LEN:
3981	case SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN:
3982	case SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX:
3983		if (arg < 1)
3984			return (EINVAL);
3985		break;
3986	case SYNAPTICS_SYSCTL_TAP_MAX_DELTA:
3987	case SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT:
3988	case SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA:
3989		if (arg < 0)
3990			return (EINVAL);
3991		break;
3992	case SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA:
3993	case SYNAPTICS_SYSCTL_VSCROLL_VER_AREA:
3994		if (arg < -6143 || arg > 6143)
3995			return (EINVAL);
3996		break;
3997	default:
3998		return (EINVAL);
3999	}
4000
4001	/* Update. */
4002	*(int *)oidp->oid_arg1 = arg;
4003
4004	return (error);
4005}
4006
4007static void
4008synaptics_sysctl_create_tree(struct psm_softc *sc)
4009{
4010
4011	if (sc->syninfo.sysctl_tree != NULL)
4012		return;
4013
4014	/* Attach extra synaptics sysctl nodes under hw.psm.synaptics */
4015	sysctl_ctx_init(&sc->syninfo.sysctl_ctx);
4016	sc->syninfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->syninfo.sysctl_ctx,
4017	    SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "synaptics", CTLFLAG_RD,
4018	    0, "Synaptics TouchPad");
4019
4020	/* hw.psm.synaptics.directional_scrolls. */
4021	sc->syninfo.directional_scrolls = 1;
4022	SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
4023	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4024	    "directional_scrolls", CTLFLAG_RW|CTLFLAG_ANYBODY,
4025	    &sc->syninfo.directional_scrolls, 0,
4026	    "Enable hardware scrolling pad (if non-zero) or register it as "
4027	    "a middle-click (if 0)");
4028
4029	/* hw.psm.synaptics.min_pressure. */
4030	sc->syninfo.min_pressure = 16;
4031	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4032	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4033	    "min_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4034	    &sc->syninfo.min_pressure, SYNAPTICS_SYSCTL_MIN_PRESSURE,
4035	    synaptics_sysctl, "I",
4036	    "Minimum pressure required to start an action");
4037
4038	/* hw.psm.synaptics.max_pressure. */
4039	sc->syninfo.max_pressure = 220;
4040	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4041	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4042	    "max_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4043	    &sc->syninfo.max_pressure, SYNAPTICS_SYSCTL_MAX_PRESSURE,
4044	    synaptics_sysctl, "I",
4045	    "Maximum pressure to detect palm");
4046
4047	/* hw.psm.synaptics.max_width. */
4048	sc->syninfo.max_width = 10;
4049	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4050	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4051	    "max_width", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4052	    &sc->syninfo.max_width, SYNAPTICS_SYSCTL_MAX_WIDTH,
4053	    synaptics_sysctl, "I",
4054	    "Maximum finger width to detect palm");
4055
4056	/* hw.psm.synaptics.top_margin. */
4057	sc->syninfo.margin_top = 200;
4058	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4059	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4060	    "margin_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4061	    &sc->syninfo.margin_top, SYNAPTICS_SYSCTL_MARGIN_TOP,
4062	    synaptics_sysctl, "I",
4063	    "Top margin");
4064
4065	/* hw.psm.synaptics.right_margin. */
4066	sc->syninfo.margin_right = 200;
4067	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4068	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4069	    "margin_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4070	    &sc->syninfo.margin_right, SYNAPTICS_SYSCTL_MARGIN_RIGHT,
4071	    synaptics_sysctl, "I",
4072	    "Right margin");
4073
4074	/* hw.psm.synaptics.bottom_margin. */
4075	sc->syninfo.margin_bottom = 200;
4076	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4077	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4078	    "margin_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4079	    &sc->syninfo.margin_bottom, SYNAPTICS_SYSCTL_MARGIN_BOTTOM,
4080	    synaptics_sysctl, "I",
4081	    "Bottom margin");
4082
4083	/* hw.psm.synaptics.left_margin. */
4084	sc->syninfo.margin_left = 200;
4085	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4086	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4087	    "margin_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4088	    &sc->syninfo.margin_left, SYNAPTICS_SYSCTL_MARGIN_LEFT,
4089	    synaptics_sysctl, "I",
4090	    "Left margin");
4091
4092	/* hw.psm.synaptics.na_top. */
4093	sc->syninfo.na_top = 1783;
4094	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4095	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4096	    "na_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4097	    &sc->syninfo.na_top, SYNAPTICS_SYSCTL_NA_TOP,
4098	    synaptics_sysctl, "I",
4099	    "Top noisy area, where weight_previous_na is used instead "
4100	    "of weight_previous");
4101
4102	/* hw.psm.synaptics.na_right. */
4103	sc->syninfo.na_right = 563;
4104	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4105	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4106	    "na_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4107	    &sc->syninfo.na_right, SYNAPTICS_SYSCTL_NA_RIGHT,
4108	    synaptics_sysctl, "I",
4109	    "Right noisy area, where weight_previous_na is used instead "
4110	    "of weight_previous");
4111
4112	/* hw.psm.synaptics.na_bottom. */
4113	sc->syninfo.na_bottom = 1408;
4114	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4115	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4116	    "na_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4117	    &sc->syninfo.na_bottom, SYNAPTICS_SYSCTL_NA_BOTTOM,
4118	    synaptics_sysctl, "I",
4119	    "Bottom noisy area, where weight_previous_na is used instead "
4120	    "of weight_previous");
4121
4122	/* hw.psm.synaptics.na_left. */
4123	sc->syninfo.na_left = 1600;
4124	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4125	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4126	    "na_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4127	    &sc->syninfo.na_left, SYNAPTICS_SYSCTL_NA_LEFT,
4128	    synaptics_sysctl, "I",
4129	    "Left noisy area, where weight_previous_na is used instead "
4130	    "of weight_previous");
4131
4132	/* hw.psm.synaptics.window_min. */
4133	sc->syninfo.window_min = 4;
4134	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4135	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4136	    "window_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4137	    &sc->syninfo.window_min, SYNAPTICS_SYSCTL_WINDOW_MIN,
4138	    synaptics_sysctl, "I",
4139	    "Minimum window size to start an action");
4140
4141	/* hw.psm.synaptics.window_max. */
4142	sc->syninfo.window_max = 10;
4143	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4144	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4145	    "window_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4146	    &sc->syninfo.window_max, SYNAPTICS_SYSCTL_WINDOW_MAX,
4147	    synaptics_sysctl, "I",
4148	    "Maximum window size");
4149
4150	/* hw.psm.synaptics.multiplicator. */
4151	sc->syninfo.multiplicator = 10000;
4152	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4153	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4154	    "multiplicator", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4155	    &sc->syninfo.multiplicator, SYNAPTICS_SYSCTL_MULTIPLICATOR,
4156	    synaptics_sysctl, "I",
4157	    "Multiplicator to increase precision in averages and divisions");
4158
4159	/* hw.psm.synaptics.weight_current. */
4160	sc->syninfo.weight_current = 3;
4161	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4162	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4163	    "weight_current", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4164	    &sc->syninfo.weight_current, SYNAPTICS_SYSCTL_WEIGHT_CURRENT,
4165	    synaptics_sysctl, "I",
4166	    "Weight of the current movement in the new average");
4167
4168	/* hw.psm.synaptics.weight_previous. */
4169	sc->syninfo.weight_previous = 6;
4170	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4171	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4172	    "weight_previous", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4173	    &sc->syninfo.weight_previous, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS,
4174	    synaptics_sysctl, "I",
4175	    "Weight of the previous average");
4176
4177	/* hw.psm.synaptics.weight_previous_na. */
4178	sc->syninfo.weight_previous_na = 20;
4179	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4180	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4181	    "weight_previous_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4182	    &sc->syninfo.weight_previous_na,
4183	    SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA,
4184	    synaptics_sysctl, "I",
4185	    "Weight of the previous average (inside the noisy area)");
4186
4187	/* hw.psm.synaptics.weight_len_squared. */
4188	sc->syninfo.weight_len_squared = 2000;
4189	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4190	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4191	    "weight_len_squared", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4192	    &sc->syninfo.weight_len_squared,
4193	    SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED,
4194	    synaptics_sysctl, "I",
4195	    "Length (squared) of segments where weight_previous "
4196	    "starts to decrease");
4197
4198	/* hw.psm.synaptics.div_min. */
4199	sc->syninfo.div_min = 9;
4200	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4201	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4202	    "div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4203	    &sc->syninfo.div_min, SYNAPTICS_SYSCTL_DIV_MIN,
4204	    synaptics_sysctl, "I",
4205	    "Divisor for fast movements");
4206
4207	/* hw.psm.synaptics.div_max. */
4208	sc->syninfo.div_max = 17;
4209	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4210	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4211	    "div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4212	    &sc->syninfo.div_max, SYNAPTICS_SYSCTL_DIV_MAX,
4213	    synaptics_sysctl, "I",
4214	    "Divisor for slow movements");
4215
4216	/* hw.psm.synaptics.div_max_na. */
4217	sc->syninfo.div_max_na = 30;
4218	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4219	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4220	    "div_max_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4221	    &sc->syninfo.div_max_na, SYNAPTICS_SYSCTL_DIV_MAX_NA,
4222	    synaptics_sysctl, "I",
4223	    "Divisor with slow movements (inside the noisy area)");
4224
4225	/* hw.psm.synaptics.div_len. */
4226	sc->syninfo.div_len = 100;
4227	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4228	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4229	    "div_len", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4230	    &sc->syninfo.div_len, SYNAPTICS_SYSCTL_DIV_LEN,
4231	    synaptics_sysctl, "I",
4232	    "Length of segments where div_max starts to decrease");
4233
4234	/* hw.psm.synaptics.tap_max_delta. */
4235	sc->syninfo.tap_max_delta = 80;
4236	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4237	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4238	    "tap_max_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4239	    &sc->syninfo.tap_max_delta, SYNAPTICS_SYSCTL_TAP_MAX_DELTA,
4240	    synaptics_sysctl, "I",
4241	    "Length of segments above which a tap is ignored");
4242
4243	/* hw.psm.synaptics.tap_min_queue. */
4244	sc->syninfo.tap_min_queue = 2;
4245	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4246	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4247	    "tap_min_queue", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4248	    &sc->syninfo.tap_min_queue, SYNAPTICS_SYSCTL_TAP_MIN_QUEUE,
4249	    synaptics_sysctl, "I",
4250	    "Number of packets required to consider a tap");
4251
4252	/* hw.psm.synaptics.taphold_timeout. */
4253	sc->synaction.in_taphold = 0;
4254	sc->syninfo.taphold_timeout = tap_timeout;
4255	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4256	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4257	    "taphold_timeout", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4258	    &sc->syninfo.taphold_timeout, SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT,
4259	    synaptics_sysctl, "I",
4260	    "Maximum elapsed time between two taps to consider a tap-hold "
4261	    "action");
4262
4263	/* hw.psm.synaptics.vscroll_hor_area. */
4264	sc->syninfo.vscroll_hor_area = 0; /* 1300 */
4265	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4266	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4267	    "vscroll_hor_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4268	    &sc->syninfo.vscroll_hor_area, SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA,
4269	    synaptics_sysctl, "I",
4270	    "Area reserved for horizontal virtual scrolling");
4271
4272	/* hw.psm.synaptics.vscroll_ver_area. */
4273	sc->syninfo.vscroll_ver_area = -600;
4274	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4275	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4276	    "vscroll_ver_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4277	    &sc->syninfo.vscroll_ver_area, SYNAPTICS_SYSCTL_VSCROLL_VER_AREA,
4278	    synaptics_sysctl, "I",
4279	    "Area reserved for vertical virtual scrolling");
4280
4281	/* hw.psm.synaptics.vscroll_min_delta. */
4282	sc->syninfo.vscroll_min_delta = 50;
4283	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4284	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4285	    "vscroll_min_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4286	    &sc->syninfo.vscroll_min_delta,
4287	    SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA,
4288	    synaptics_sysctl, "I",
4289	    "Minimum movement to consider virtual scrolling");
4290
4291	/* hw.psm.synaptics.vscroll_div_min. */
4292	sc->syninfo.vscroll_div_min = 100;
4293	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4294	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4295	    "vscroll_div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4296	    &sc->syninfo.vscroll_div_min, SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN,
4297	    synaptics_sysctl, "I",
4298	    "Divisor for fast scrolling");
4299
4300	/* hw.psm.synaptics.vscroll_div_min. */
4301	sc->syninfo.vscroll_div_max = 150;
4302	SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4303	    SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4304	    "vscroll_div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4305	    &sc->syninfo.vscroll_div_max, SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX,
4306	    synaptics_sysctl, "I",
4307	    "Divisor for slow scrolling");
4308}
4309
4310static int
4311enable_synaptics(KBDC kbdc, struct psm_softc *sc)
4312{
4313	synapticshw_t synhw;
4314	int status[3];
4315	int buttons;
4316
4317	VLOG(3, (LOG_DEBUG, "synaptics: BEGIN init\n"));
4318
4319	/*
4320	 * Just to be on the safe side: this avoids troubles with
4321	 * following mouse_ext_command() when the previous command
4322	 * was PSMC_SET_RESOLUTION. Set Scaling has no effect on
4323	 * Synaptics Touchpad behaviour.
4324	 */
4325	set_mouse_scaling(kbdc, 1);
4326
4327	/* Identify the Touchpad version. */
4328	if (mouse_ext_command(kbdc, 0) == 0)
4329		return (FALSE);
4330	if (get_mouse_status(kbdc, status, 0, 3) != 3)
4331		return (FALSE);
4332	if (status[1] != 0x47)
4333		return (FALSE);
4334
4335	bzero(&synhw, sizeof(synhw));
4336	synhw.infoMinor = status[0];
4337	synhw.infoMajor = status[2] & 0x0f;
4338
4339	if (verbose >= 2)
4340		printf("Synaptics Touchpad v%d.%d\n", synhw.infoMajor,
4341		    synhw.infoMinor);
4342
4343	if (synhw.infoMajor < 4) {
4344		printf("  Unsupported (pre-v4) Touchpad detected\n");
4345		return (FALSE);
4346	}
4347
4348	/* Get the Touchpad model information. */
4349	if (mouse_ext_command(kbdc, 3) == 0)
4350		return (FALSE);
4351	if (get_mouse_status(kbdc, status, 0, 3) != 3)
4352		return (FALSE);
4353	if ((status[1] & 0x01) != 0) {
4354		printf("  Failed to read model information\n");
4355		return (FALSE);
4356	}
4357
4358	synhw.infoRot180   = (status[0] & 0x80) != 0;
4359	synhw.infoPortrait = (status[0] & 0x40) != 0;
4360	synhw.infoSensor   =  status[0] & 0x3f;
4361	synhw.infoHardware = (status[1] & 0xfe) >> 1;
4362	synhw.infoNewAbs   = (status[2] & 0x80) != 0;
4363	synhw.capPen       = (status[2] & 0x40) != 0;
4364	synhw.infoSimplC   = (status[2] & 0x20) != 0;
4365	synhw.infoGeometry =  status[2] & 0x0f;
4366
4367	if (verbose >= 2) {
4368		printf("  Model information:\n");
4369		printf("   infoRot180: %d\n", synhw.infoRot180);
4370		printf("   infoPortrait: %d\n", synhw.infoPortrait);
4371		printf("   infoSensor: %d\n", synhw.infoSensor);
4372		printf("   infoHardware: %d\n", synhw.infoHardware);
4373		printf("   infoNewAbs: %d\n", synhw.infoNewAbs);
4374		printf("   capPen: %d\n", synhw.capPen);
4375		printf("   infoSimplC: %d\n", synhw.infoSimplC);
4376		printf("   infoGeometry: %d\n", synhw.infoGeometry);
4377	}
4378
4379	/* Read the extended capability bits. */
4380	if (mouse_ext_command(kbdc, 2) == 0)
4381		return (FALSE);
4382	if (get_mouse_status(kbdc, status, 0, 3) != 3)
4383		return (FALSE);
4384	if (status[1] != 0x47) {
4385		printf("  Failed to read extended capability bits\n");
4386		return (FALSE);
4387	}
4388
4389	/* Set the different capabilities when they exist. */
4390	buttons = 0;
4391	synhw.capExtended = (status[0] & 0x80) != 0;
4392	if (synhw.capExtended) {
4393		synhw.capPassthrough = (status[2] & 0x80) != 0;
4394		synhw.capSleep       = (status[2] & 0x10) != 0;
4395		synhw.capFourButtons = (status[2] & 0x08) != 0;
4396		synhw.capMultiFinger = (status[2] & 0x02) != 0;
4397		synhw.capPalmDetect  = (status[2] & 0x01) != 0;
4398
4399		if (verbose >= 2) {
4400			printf("  Extended capabilities:\n");
4401			printf("   capExtended: %d\n", synhw.capExtended);
4402			printf("   capPassthrough: %d\n", synhw.capPassthrough);
4403			printf("   capSleep: %d\n", synhw.capSleep);
4404			printf("   capFourButtons: %d\n", synhw.capFourButtons);
4405			printf("   capMultiFinger: %d\n", synhw.capMultiFinger);
4406			printf("   capPalmDetect: %d\n", synhw.capPalmDetect);
4407		}
4408
4409		/*
4410		 * If we have bits set in status[0] & 0x70, then we can load
4411		 * more information about buttons using query 0x09.
4412		 */
4413		if ((status[0] & 0x70) != 0) {
4414			if (mouse_ext_command(kbdc, 0x09) == 0)
4415				return (FALSE);
4416			if (get_mouse_status(kbdc, status, 0, 3) != 3)
4417				return (FALSE);
4418			buttons = (status[1] & 0xf0) >> 4;
4419		} else
4420			buttons = synhw.capFourButtons ? 1 : 0;
4421	}
4422	if (verbose >= 2) {
4423		if (synhw.capExtended)
4424			printf("  Additional Buttons: %d\n", buttons);
4425		else
4426			printf("  No extended capabilities\n");
4427	}
4428
4429	/*
4430	 * Read the mode byte.
4431	 *
4432	 * XXX: Note the Synaptics documentation also defines the first
4433	 * byte of the response to this query to be a constant 0x3b, this
4434	 * does not appear to be true for Touchpads with guest devices.
4435	 */
4436	if (mouse_ext_command(kbdc, 1) == 0)
4437		return (FALSE);
4438	if (get_mouse_status(kbdc, status, 0, 3) != 3)
4439		return (FALSE);
4440	if (status[1] != 0x47) {
4441		printf("  Failed to read mode byte\n");
4442		return (FALSE);
4443	}
4444
4445	if (sc != NULL)
4446		sc->synhw = synhw;
4447	if (!synaptics_support)
4448		return (FALSE);
4449
4450	/* Set the mode byte; request wmode where available. */
4451	mouse_ext_command(kbdc, synhw.capExtended ? 0xc1 : 0xc0);
4452
4453	/* "Commit" the Set Mode Byte command sent above. */
4454	set_mouse_sampling_rate(kbdc, 20);
4455
4456	buttons += 3;
4457	VLOG(3, (LOG_DEBUG, "synaptics: END init (%d buttons)\n", buttons));
4458
4459	if (sc != NULL) {
4460		/* Create sysctl tree. */
4461		synaptics_sysctl_create_tree(sc);
4462
4463		sc->hw.buttons = buttons;
4464	}
4465
4466	return (TRUE);
4467}
4468
4469/* Interlink electronics VersaPad */
4470static int
4471enable_versapad(KBDC kbdc, struct psm_softc *sc)
4472{
4473	int data[3];
4474
4475	set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
4476	set_mouse_sampling_rate(kbdc, 100);		/* set rate 100 */
4477	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
4478	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
4479	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
4480	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
4481	if (get_mouse_status(kbdc, data, 0, 3) < 3)	/* get status */
4482		return (FALSE);
4483	if (data[2] != 0xa || data[1] != 0 )	/* rate == 0xa && res. == 0 */
4484		return (FALSE);
4485	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
4486
4487	return (TRUE);				/* PS/2 absolute mode */
4488}
4489
4490/*
4491 * Return true if 'now' is earlier than (start + (secs.usecs)).
4492 * Now may be NULL and the function will fetch the current time from
4493 * getmicrouptime(), or a cached 'now' can be passed in.
4494 * All values should be numbers derived from getmicrouptime().
4495 */
4496static int
4497timeelapsed(start, secs, usecs, now)
4498	const struct timeval *start, *now;
4499	int secs, usecs;
4500{
4501	struct timeval snow, tv;
4502
4503	/* if there is no 'now' passed in, the get it as a convience. */
4504	if (now == NULL) {
4505		getmicrouptime(&snow);
4506		now = &snow;
4507	}
4508
4509	tv.tv_sec = secs;
4510	tv.tv_usec = usecs;
4511	timevaladd(&tv, start);
4512	return (timevalcmp(&tv, now, <));
4513}
4514
4515static int
4516psmresume(device_t dev)
4517{
4518	struct psm_softc *sc = device_get_softc(dev);
4519	int unit = device_get_unit(dev);
4520	int err;
4521
4522	VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit));
4523
4524	if ((sc->config &
4525	    (PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND)) == 0)
4526		return (0);
4527
4528	err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
4529
4530	if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
4531		/*
4532		 * Release the blocked process; it must be notified that
4533		 * the device cannot be accessed anymore.
4534		 */
4535		sc->state &= ~PSM_ASLP;
4536		wakeup(sc);
4537	}
4538
4539	VLOG(2, (LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit));
4540
4541	return (err);
4542}
4543
4544DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
4545
4546#ifdef DEV_ISA
4547
4548/*
4549 * This sucks up assignments from PNPBIOS and ACPI.
4550 */
4551
4552/*
4553 * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
4554 * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
4555 * can be probed and attached only after the AT keyboard controller is
4556 * attached, we shall quietly reserve the IRQ resource for later use.
4557 * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
4558 * copy the IRQ resource to the PS/2 mouse device instance hanging
4559 * under the keyboard controller, then probe and attach it.
4560 */
4561
4562static	devclass_t			psmcpnp_devclass;
4563
4564static	device_probe_t			psmcpnp_probe;
4565static	device_attach_t			psmcpnp_attach;
4566
4567static device_method_t psmcpnp_methods[] = {
4568	DEVMETHOD(device_probe,		psmcpnp_probe),
4569	DEVMETHOD(device_attach,	psmcpnp_attach),
4570
4571	{ 0, 0 }
4572};
4573
4574static driver_t psmcpnp_driver = {
4575	PSMCPNP_DRIVER_NAME,
4576	psmcpnp_methods,
4577	1,			/* no softc */
4578};
4579
4580static struct isa_pnp_id psmcpnp_ids[] = {
4581	{ 0x030fd041, "PS/2 mouse port" },		/* PNP0F03 */
4582	{ 0x0e0fd041, "PS/2 mouse port" },		/* PNP0F0E */
4583	{ 0x120fd041, "PS/2 mouse port" },		/* PNP0F12 */
4584	{ 0x130fd041, "PS/2 mouse port" },		/* PNP0F13 */
4585	{ 0x1303d041, "PS/2 port" },			/* PNP0313, XXX */
4586	{ 0x02002e4f, "Dell PS/2 mouse port" },		/* Lat. X200, Dell */
4587	{ 0x0002a906, "ALPS Glide Point" },		/* ALPS Glide Point */
4588	{ 0x80374d24, "IBM PS/2 mouse port" },		/* IBM3780, ThinkPad */
4589	{ 0x81374d24, "IBM PS/2 mouse port" },		/* IBM3781, ThinkPad */
4590	{ 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
4591	{ 0x0290d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9002, Vaio */
4592	{ 0x0390d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9003, Vaio */
4593	{ 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
4594	{ 0 }
4595};
4596
4597static int
4598create_a_copy(device_t atkbdc, device_t me)
4599{
4600	device_t psm;
4601	u_long irq;
4602
4603	/* find the PS/2 mouse device instance under the keyboard controller */
4604	psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
4605	    device_get_unit(atkbdc));
4606	if (psm == NULL)
4607		return (ENXIO);
4608	if (device_get_state(psm) != DS_NOTPRESENT)
4609		return (0);
4610
4611	/* move our resource to the found device */
4612	irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
4613	bus_delete_resource(me, SYS_RES_IRQ, 0);
4614	bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
4615
4616	/* ...then probe and attach it */
4617	return (device_probe_and_attach(psm));
4618}
4619
4620static int
4621psmcpnp_probe(device_t dev)
4622{
4623	struct resource *res;
4624	u_long irq;
4625	int rid;
4626
4627	if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids))
4628		return (ENXIO);
4629
4630	/*
4631	 * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
4632	 * to the PS/2 mouse device node. But, some buggy PnP BIOS
4633	 * declares the PS/2 mouse device node without an IRQ resource!
4634	 * If this happens, we shall refer to device hints.
4635	 * If we still don't find it there, use a hardcoded value... XXX
4636	 */
4637	rid = 0;
4638	irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
4639	if (irq <= 0) {
4640		if (resource_long_value(PSM_DRIVER_NAME,
4641		    device_get_unit(dev),"irq", &irq) != 0)
4642			irq = 12;	/* XXX */
4643		device_printf(dev, "irq resource info is missing; "
4644		    "assuming irq %ld\n", irq);
4645		bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
4646	}
4647	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, 0);
4648	bus_release_resource(dev, SYS_RES_IRQ, rid, res);
4649
4650	/* keep quiet */
4651	if (!bootverbose)
4652		device_quiet(dev);
4653
4654	return ((res == NULL) ? ENXIO : 0);
4655}
4656
4657static int
4658psmcpnp_attach(device_t dev)
4659{
4660	device_t atkbdc;
4661
4662	/* find the keyboard controller, which may be on acpi* or isa* bus */
4663	atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
4664	    device_get_unit(dev));
4665	if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED))
4666		create_a_copy(atkbdc, dev);
4667
4668	return (0);
4669}
4670
4671DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
4672DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
4673
4674#endif /* DEV_ISA */
4675