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