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