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