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