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