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