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