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