xref: /freebsd/sys/dev/atkbdc/psm.c (revision 87569f75a91f298c52a71823c04d41cf53c88889)
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/poll.h>
74 #include <sys/syslog.h>
75 #include <machine/bus.h>
76 #include <sys/rman.h>
77 #include <sys/selinfo.h>
78 #include <sys/sysctl.h>
79 #include <sys/time.h>
80 #include <sys/uio.h>
81 
82 #include <sys/limits.h>
83 #include <sys/mouse.h>
84 #include <machine/resource.h>
85 
86 #ifdef DEV_ISA
87 #include <isa/isavar.h>
88 #endif
89 
90 #include <dev/atkbdc/atkbdcreg.h>
91 #include <dev/atkbdc/psm.h>
92 
93 /*
94  * Driver specific options: the following options may be set by
95  * `options' statements in the kernel configuration file.
96  */
97 
98 /* debugging */
99 #ifndef PSM_DEBUG
100 #define PSM_DEBUG	0	/*
101 				 * logging: 0: none, 1: brief, 2: verbose
102 				 *          3: sync errors, 4: all packets
103 				 */
104 #endif
105 #define VLOG(level, args) 	\
106 do {				\
107 	if (verbose >= level)	\
108 		log args;	\
109 } while (0)
110 
111 #ifndef PSM_INPUT_TIMEOUT
112 #define PSM_INPUT_TIMEOUT	2000000	/* 2 sec */
113 #endif
114 
115 #ifndef PSM_TAP_TIMEOUT
116 #define PSM_TAP_TIMEOUT		125000
117 #endif
118 
119 #ifndef PSM_TAP_THRESHOLD
120 #define PSM_TAP_THRESHOLD	25
121 #endif
122 
123 /* end of driver specific options */
124 
125 #define PSMCPNP_DRIVER_NAME	"psmcpnp"
126 
127 /* input queue */
128 #define PSM_BUFSIZE		960
129 #define PSM_SMALLBUFSIZE	240
130 
131 /* operation levels */
132 #define PSM_LEVEL_BASE		0
133 #define PSM_LEVEL_STANDARD	1
134 #define PSM_LEVEL_NATIVE	2
135 #define PSM_LEVEL_MIN		PSM_LEVEL_BASE
136 #define PSM_LEVEL_MAX		PSM_LEVEL_NATIVE
137 
138 /* Logitech PS2++ protocol */
139 #define MOUSE_PS2PLUS_CHECKBITS(b)	\
140 				((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
141 #define MOUSE_PS2PLUS_PACKET_TYPE(b)	\
142 				(((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
143 
144 /* some macros */
145 #define PSM_UNIT(dev)		(minor(dev) >> 1)
146 #define PSM_NBLOCKIO(dev)	(minor(dev) & 1)
147 #define PSM_MKMINOR(unit,block)	(((unit) << 1) | ((block) ? 0:1))
148 
149 /* ring buffer */
150 typedef struct ringbuf {
151     int           count;	/* # of valid elements in the buffer */
152     int           head;		/* head pointer */
153     int           tail;		/* tail poiner */
154     unsigned char buf[PSM_BUFSIZE];
155 } ringbuf_t;
156 
157 /* data buffer */
158 typedef struct packetbuf {
159     unsigned char ipacket[16];	/* interim input buffer */
160     int           inputbytes;	/* # of bytes in the input buffer */
161 } packetbuf_t;
162 
163 #ifndef PSM_PACKETQUEUE
164 #define PSM_PACKETQUEUE	128
165 #endif
166 
167 typedef struct synapticsinfo {
168     struct sysctl_ctx_list	sysctl_ctx;
169     struct sysctl_oid		*sysctl_tree;
170     int				directional_scrolls;
171     int				low_speed_threshold;
172     int				min_movement;
173     int				squelch_level;
174 } synapticsinfo_t;
175 
176 /* driver control block */
177 struct psm_softc {		/* Driver status information */
178     int		  unit;
179     struct selinfo rsel;	/* Process selecting for Input */
180     unsigned char state;	/* Mouse driver state */
181     int           config;	/* driver configuration flags */
182     int           flags;	/* other flags */
183     KBDC          kbdc;		/* handle to access the keyboard controller */
184     struct resource *intr;	/* IRQ resource */
185     void	  *ih;		/* interrupt handle */
186     mousehw_t     hw;		/* hardware information */
187     synapticshw_t synhw;	/* Synaptics-specific hardware information */
188     synapticsinfo_t syninfo;	/* Synaptics-specific configuration */
189     mousemode_t   mode;		/* operation mode */
190     mousemode_t   dflt_mode;	/* default operation mode */
191     mousestatus_t status;	/* accumulated mouse movement */
192     ringbuf_t     queue;	/* mouse status queue */
193     packetbuf_t   pqueue[PSM_PACKETQUEUE];	/* mouse data queue */
194     int           pqueue_start; /* start of data in queue */
195     int           pqueue_end;   /* end of data in queue */
196     int           button;	/* the latest button state */
197     int		  xold;		/* previous absolute X position */
198     int		  yold;		/* previous absolute Y position */
199     int		  xaverage;	/* average X position */
200     int		  yaverage;	/* average Y position */
201     int		  squelch;	/* level to filter movement data at low speed */
202     int		  zmax;		/* maximum pressure value for touchpads */
203     int		  syncerrors;	/* # of bytes discarded searching for sync */
204     int		  pkterrors;	/* # of packets failed during quaranteen. */
205     struct timeval inputtimeout;
206     struct timeval lastsoftintr;	/* time of last soft interrupt */
207     struct timeval lastinputerr;	/* time last sync error happened */
208     struct timeval taptimeout;		/* tap timeout for touchpads */
209     int		  watchdog;		/* watchdog timer flag */
210     struct callout_handle callout;	/* watchdog timer call out */
211     struct callout_handle softcallout;	/* buffer timer call out */
212     struct cdev *dev;
213     struct cdev *bdev;
214     int           lasterr;
215     int           cmdcount;
216 };
217 static devclass_t psm_devclass;
218 #define PSM_SOFTC(unit)	((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
219 
220 /* driver state flags (state) */
221 #define PSM_VALID		0x80
222 #define PSM_OPEN		1	/* Device is open */
223 #define PSM_ASLP		2	/* Waiting for mouse data */
224 #define PSM_SOFTARMED		4	/* Software interrupt armed */
225 #define PSM_NEED_SYNCBITS	8	/* Set syncbits using next data pkt */
226 
227 /* driver configuration flags (config) */
228 #define PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
229 #define PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
230 #define PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
231 #define PSM_CONFIG_NOIDPROBE	0x0200  /* disable mouse model probe */
232 #define PSM_CONFIG_NORESET	0x0400  /* don't reset the mouse */
233 #define PSM_CONFIG_FORCETAP	0x0800  /* assume `tap' action exists */
234 #define PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
235 #define PSM_CONFIG_HOOKRESUME	0x2000	/* hook the system resume event */
236 #define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
237 #define PSM_CONFIG_SYNCHACK	0x8000 /* enable `out-of-sync' hack */
238 
239 #define PSM_CONFIG_FLAGS	(PSM_CONFIG_RESOLUTION 		\
240 				    | PSM_CONFIG_ACCEL		\
241 				    | PSM_CONFIG_NOCHECKSYNC	\
242 				    | PSM_CONFIG_SYNCHACK	\
243 				    | PSM_CONFIG_NOIDPROBE	\
244 				    | PSM_CONFIG_NORESET	\
245 				    | PSM_CONFIG_FORCETAP	\
246 				    | PSM_CONFIG_IGNPORTERROR	\
247 				    | PSM_CONFIG_HOOKRESUME	\
248 				    | PSM_CONFIG_INITAFTERSUSPEND)
249 
250 /* other flags (flags) */
251 #define PSM_FLAGS_FINGERDOWN	0x0001 /* VersaPad finger down */
252 
253 /* Tunables */
254 static int synaptics_support = 0;
255 TUNABLE_INT("hw.psm.synaptics_support", &synaptics_support);
256 
257 static int verbose = PSM_DEBUG;
258 TUNABLE_INT("debug.psm.loglevel", &verbose);
259 
260 /* for backward compatibility */
261 #define OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
262 #define OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
263 #define OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)
264 
265 typedef struct old_mousehw {
266     int buttons;
267     int iftype;
268     int type;
269     int hwid;
270 } old_mousehw_t;
271 
272 typedef struct old_mousemode {
273     int protocol;
274     int rate;
275     int resolution;
276     int accelfactor;
277 } old_mousemode_t;
278 
279 /* packet formatting function */
280 typedef int packetfunc_t(struct psm_softc *, unsigned char *,
281 			      int *, int, mousestatus_t *);
282 
283 /* function prototypes */
284 static void psmidentify(driver_t *, device_t);
285 static int psmprobe(device_t);
286 static int psmattach(device_t);
287 static int psmdetach(device_t);
288 static int psmresume(device_t);
289 
290 static d_open_t psmopen;
291 static d_close_t psmclose;
292 static d_read_t psmread;
293 static d_ioctl_t psmioctl;
294 static d_poll_t psmpoll;
295 
296 static int enable_aux_dev(KBDC);
297 static int disable_aux_dev(KBDC);
298 static int get_mouse_status(KBDC, int *, int, int);
299 static int get_aux_id(KBDC);
300 static int set_mouse_sampling_rate(KBDC, int);
301 static int set_mouse_scaling(KBDC, int);
302 static int set_mouse_resolution(KBDC, int);
303 static int set_mouse_mode(KBDC);
304 static int get_mouse_buttons(KBDC);
305 static int is_a_mouse(int);
306 static void recover_from_error(KBDC);
307 static int restore_controller(KBDC, int);
308 static int doinitialize(struct psm_softc *, mousemode_t *);
309 static int doopen(struct psm_softc *, int);
310 static int reinitialize(struct psm_softc *, int);
311 static char *model_name(int);
312 static void psmsoftintr(void *);
313 static void psmintr(void *);
314 static void psmtimeout(void *);
315 static int timeelapsed(const struct timeval *,
316     int, int, const struct timeval *);
317 static void dropqueue(struct psm_softc *);
318 static void flushpackets(struct psm_softc *);
319 
320 /* vendor specific features */
321 typedef int probefunc_t(struct psm_softc *);
322 
323 static int mouse_id_proc1(KBDC, int, int, int *);
324 static int mouse_ext_command(KBDC, int);
325 static probefunc_t enable_groller;
326 static probefunc_t enable_gmouse;
327 static probefunc_t enable_aglide;
328 static probefunc_t enable_kmouse;
329 static probefunc_t enable_msexplorer;
330 static probefunc_t enable_msintelli;
331 static probefunc_t enable_4dmouse;
332 static probefunc_t enable_4dplus;
333 static probefunc_t enable_mmanplus;
334 static probefunc_t enable_synaptics;
335 static probefunc_t enable_versapad;
336 static int tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *, unsigned char *);
337 
338 static struct {
339     int                 model;
340     unsigned char	syncmask;
341     int 		packetsize;
342     probefunc_t 	*probefunc;
343 } vendortype[] = {
344     /*
345      * WARNING: the order of probe is very important.  Don't mess it
346      * unless you know what you are doing.
347      */
348     { MOUSE_MODEL_NET,			/* Genius NetMouse */
349       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse, },
350     { MOUSE_MODEL_NETSCROLL,		/* Genius NetScroll */
351       0xc8, 6, enable_groller, },
352     { MOUSE_MODEL_MOUSEMANPLUS,		/* Logitech MouseMan+ */
353       0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus, },
354     { MOUSE_MODEL_EXPLORER,		/* Microsoft IntelliMouse Explorer */
355       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer, },
356     { MOUSE_MODEL_4D,			/* A4 Tech 4D Mouse */
357       0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse, },
358     { MOUSE_MODEL_4DPLUS,		/* A4 Tech 4D+ Mouse */
359       0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus, },
360     { MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
361       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli, },
362     { MOUSE_MODEL_GLIDEPOINT,		/* ALPS GlidePoint */
363       0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide, },
364     { MOUSE_MODEL_THINK,		/* Kensignton ThinkingMouse */
365       0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse, },
366     { MOUSE_MODEL_VERSAPAD,		/* Interlink electronics VersaPad */
367       0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad, },
368     { MOUSE_MODEL_SYNAPTICS,		/* Synaptics Touchpad */
369       0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics, },
370     { MOUSE_MODEL_GENERIC,
371       0xc0, MOUSE_PS2_PACKETSIZE, NULL, },
372 };
373 #define GENERIC_MOUSE_ENTRY	((sizeof(vendortype) / sizeof(*vendortype)) - 1)
374 
375 /* device driver declarateion */
376 static device_method_t psm_methods[] = {
377 	/* Device interface */
378 	DEVMETHOD(device_identify,	psmidentify),
379 	DEVMETHOD(device_probe,		psmprobe),
380 	DEVMETHOD(device_attach,	psmattach),
381 	DEVMETHOD(device_detach,	psmdetach),
382 	DEVMETHOD(device_resume,	psmresume),
383 
384 	{ 0, 0 }
385 };
386 
387 static driver_t psm_driver = {
388     PSM_DRIVER_NAME,
389     psm_methods,
390     sizeof(struct psm_softc),
391 };
392 
393 
394 static struct cdevsw psm_cdevsw = {
395 	.d_version =	D_VERSION,
396 	.d_flags =	D_NEEDGIANT,
397 	.d_open =	psmopen,
398 	.d_close =	psmclose,
399 	.d_read =	psmread,
400 	.d_ioctl =	psmioctl,
401 	.d_poll =	psmpoll,
402 	.d_name =	PSM_DRIVER_NAME,
403 };
404 
405 /* device I/O routines */
406 static int
407 enable_aux_dev(KBDC kbdc)
408 {
409     int res;
410 
411     res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
412     VLOG(2, (LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res));
413 
414     return (res == PSM_ACK);
415 }
416 
417 static int
418 disable_aux_dev(KBDC kbdc)
419 {
420     int res;
421 
422     res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
423     VLOG(2, (LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res));
424 
425     return (res == PSM_ACK);
426 }
427 
428 static int
429 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
430 {
431     int cmd;
432     int res;
433     int i;
434 
435     switch (flag) {
436     case 0:
437     default:
438 	cmd = PSMC_SEND_DEV_STATUS;
439 	break;
440     case 1:
441 	cmd = PSMC_SEND_DEV_DATA;
442 	break;
443     }
444     empty_aux_buffer(kbdc, 5);
445     res = send_aux_command(kbdc, cmd);
446     VLOG(2, (LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
447 	 (flag == 1) ? "DATA" : "STATUS", res));
448     if (res != PSM_ACK)
449         return 0;
450 
451     for (i = 0; i < len; ++i) {
452         status[i] = read_aux_data(kbdc);
453 	if (status[i] < 0)
454 	    break;
455     }
456 
457     VLOG(1, (LOG_DEBUG, "psm: %s %02x %02x %02x\n",
458          (flag == 1) ? "data" : "status", status[0], status[1], status[2]));
459 
460     return i;
461 }
462 
463 static int
464 get_aux_id(KBDC kbdc)
465 {
466     int res;
467     int id;
468 
469     empty_aux_buffer(kbdc, 5);
470     res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
471     VLOG(2, (LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res));
472     if (res != PSM_ACK)
473 	return (-1);
474 
475     /* 10ms delay */
476     DELAY(10000);
477 
478     id = read_aux_data(kbdc);
479     VLOG(2, (LOG_DEBUG, "psm: device ID: %04x\n", id));
480 
481     return id;
482 }
483 
484 static int
485 set_mouse_sampling_rate(KBDC kbdc, int rate)
486 {
487     int res;
488 
489     res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
490     VLOG(2, (LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res));
491 
492     return ((res == PSM_ACK) ? rate : -1);
493 }
494 
495 static int
496 set_mouse_scaling(KBDC kbdc, int scale)
497 {
498     int res;
499 
500     switch (scale) {
501     case 1:
502     default:
503 	scale = PSMC_SET_SCALING11;
504 	break;
505     case 2:
506 	scale = PSMC_SET_SCALING21;
507 	break;
508     }
509     res = send_aux_command(kbdc, scale);
510     VLOG(2, (LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
511 	 (scale == PSMC_SET_SCALING21) ? "21" : "11", res));
512 
513     return (res == PSM_ACK);
514 }
515 
516 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
517 static int
518 set_mouse_resolution(KBDC kbdc, int val)
519 {
520     int res;
521 
522     res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
523     VLOG(2, (LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res));
524 
525     return ((res == PSM_ACK) ? val : -1);
526 }
527 
528 /*
529  * NOTE: once `set_mouse_mode()' is called, the mouse device must be
530  * re-enabled by calling `enable_aux_dev()'
531  */
532 static int
533 set_mouse_mode(KBDC kbdc)
534 {
535     int res;
536 
537     res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
538     VLOG(2, (LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res));
539 
540     return (res == PSM_ACK);
541 }
542 
543 static int
544 get_mouse_buttons(KBDC kbdc)
545 {
546     int c = 2;		/* assume two buttons by default */
547     int status[3];
548 
549     /*
550      * NOTE: a special sequence to obtain Logitech Mouse specific
551      * information: set resolution to 25 ppi, set scaling to 1:1, set
552      * scaling to 1:1, set scaling to 1:1. Then the second byte of the
553      * mouse status bytes is the number of available buttons.
554      * Some manufactures also support this sequence.
555      */
556     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
557         return c;
558     if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1)
559         && set_mouse_scaling(kbdc, 1)
560 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3)) {
561         if (status[1] != 0)
562             return status[1];
563     }
564     return c;
565 }
566 
567 /* misc subroutines */
568 /*
569  * Someday, I will get the complete list of valid pointing devices and
570  * their IDs... XXX
571  */
572 static int
573 is_a_mouse(int id)
574 {
575 #if 0
576     static int valid_ids[] = {
577         PSM_MOUSE_ID,		/* mouse */
578         PSM_BALLPOINT_ID,	/* ballpoint device */
579         PSM_INTELLI_ID,		/* Intellimouse */
580         PSM_EXPLORER_ID,	/* Intellimouse Explorer */
581         -1			/* end of table */
582     };
583     int i;
584 
585     for (i = 0; valid_ids[i] >= 0; ++i)
586         if (valid_ids[i] == id)
587             return TRUE;
588     return FALSE;
589 #else
590     return TRUE;
591 #endif
592 }
593 
594 static char *
595 model_name(int model)
596 {
597     static struct {
598 	int model_code;
599 	char *model_name;
600     } models[] = {
601         { MOUSE_MODEL_NETSCROLL,	"NetScroll" },
602         { MOUSE_MODEL_NET,		"NetMouse/NetScroll Optical" },
603         { MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
604         { MOUSE_MODEL_THINK,		"ThinkingMouse" },
605         { MOUSE_MODEL_INTELLI,		"IntelliMouse" },
606         { MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
607         { MOUSE_MODEL_VERSAPAD,		"VersaPad" },
608         { MOUSE_MODEL_EXPLORER,		"IntelliMouse Explorer" },
609         { MOUSE_MODEL_4D,		"4D Mouse" },
610         { MOUSE_MODEL_4DPLUS,		"4D+ Mouse" },
611         { MOUSE_MODEL_SYNAPTICS,	"Synaptics Touchpad" },
612         { MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
613         { MOUSE_MODEL_UNKNOWN,		NULL },
614     };
615     int i;
616 
617     for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i) {
618 	if (models[i].model_code == model)
619 	    return models[i].model_name;
620     }
621     return "Unknown";
622 }
623 
624 static void
625 recover_from_error(KBDC kbdc)
626 {
627     /* discard anything left in the output buffer */
628     empty_both_buffers(kbdc, 10);
629 
630 #if 0
631     /*
632      * NOTE: KBDC_RESET_KBD may not restore the communication between the
633      * keyboard and the controller.
634      */
635     reset_kbd(kbdc);
636 #else
637     /*
638      * NOTE: somehow diagnostic and keyboard port test commands bring the
639      * keyboard back.
640      */
641     if (!test_controller(kbdc))
642         log(LOG_ERR, "psm: keyboard controller failed.\n");
643     /* if there isn't a keyboard in the system, the following error is OK */
644     if (test_kbd_port(kbdc) != 0)
645 	VLOG(1, (LOG_ERR, "psm: keyboard port failed.\n"));
646 #endif
647 }
648 
649 static int
650 restore_controller(KBDC kbdc, int command_byte)
651 {
652     empty_both_buffers(kbdc, 10);
653 
654     if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
655 	log(LOG_ERR, "psm: failed to restore the keyboard controller "
656 		     "command byte.\n");
657 	empty_both_buffers(kbdc, 10);
658 	return FALSE;
659     } else {
660 	empty_both_buffers(kbdc, 10);
661 	return TRUE;
662     }
663 }
664 
665 /*
666  * Re-initialize the aux port and device. The aux port must be enabled
667  * and its interrupt must be disabled before calling this routine.
668  * The aux device will be disabled before returning.
669  * The keyboard controller must be locked via `kbdc_lock()' before
670  * calling this routine.
671  */
672 static int
673 doinitialize(struct psm_softc *sc, mousemode_t *mode)
674 {
675     KBDC kbdc = sc->kbdc;
676     int stat[3];
677     int i;
678 
679     switch((i = test_aux_port(kbdc))) {
680     case 1:	/* ignore these errors */
681     case 2:
682     case 3:
683     case PSM_ACK:
684 	if (verbose)
685 	    log(LOG_DEBUG, "psm%d: strange result for test aux port (%d).\n",
686 	        sc->unit, i);
687 	/* FALLTHROUGH */
688     case 0:	/* no error */
689     	break;
690     case -1: 	/* time out */
691     default: 	/* error */
692     	recover_from_error(kbdc);
693 	if (sc->config & PSM_CONFIG_IGNPORTERROR)
694 	    break;
695     	log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
696     	    sc->unit, i);
697     	return FALSE;
698     }
699 
700     if (sc->config & PSM_CONFIG_NORESET) {
701 	/*
702 	 * Don't try to reset the pointing device.  It may possibly be
703 	 * left in the unknown state, though...
704 	 */
705     } else {
706 	/*
707 	 * NOTE: some controllers appears to hang the `keyboard' when
708 	 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
709 	 */
710 	if (!reset_aux_dev(kbdc)) {
711             recover_from_error(kbdc);
712             log(LOG_ERR, "psm%d: failed to reset the aux device.\n", sc->unit);
713             return FALSE;
714 	}
715     }
716 
717     /*
718      * both the aux port and the aux device is functioning, see
719      * if the device can be enabled.
720      */
721     if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
722         log(LOG_ERR, "psm%d: failed to enable the aux device.\n", sc->unit);
723         return FALSE;
724     }
725     empty_both_buffers(kbdc, 10);	/* remove stray data if any */
726 
727     if (sc->config & PSM_CONFIG_NOIDPROBE) {
728 	i = GENERIC_MOUSE_ENTRY;
729     } else {
730 	/* FIXME: hardware ID, mouse buttons? */
731 
732 	/* other parameters */
733 	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
734 	    if ((*vendortype[i].probefunc)(sc)) {
735 		if (verbose >= 2)
736 		    log(LOG_ERR, "psm%d: found %s\n",
737 			sc->unit, model_name(vendortype[i].model));
738 		break;
739 	    }
740 	}
741     }
742 
743     sc->hw.model = vendortype[i].model;
744     sc->mode.packetsize = vendortype[i].packetsize;
745 
746     /* set mouse parameters */
747     if (mode != (mousemode_t *)NULL) {
748 	if (mode->rate > 0)
749             mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
750 	if (mode->resolution >= 0)
751             mode->resolution = set_mouse_resolution(kbdc, mode->resolution);
752         set_mouse_scaling(kbdc, 1);
753         set_mouse_mode(kbdc);
754     }
755 
756     /* Record sync on the next data packet we see. */
757     sc->flags |= PSM_NEED_SYNCBITS;
758 
759     /* just check the status of the mouse */
760     if (get_mouse_status(kbdc, stat, 0, 3) < 3)
761         log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
762 	    sc->unit);
763 
764     return TRUE;
765 }
766 
767 static int
768 doopen(struct psm_softc *sc, int command_byte)
769 {
770     int stat[3];
771 
772     /* enable the mouse device */
773     if (!enable_aux_dev(sc->kbdc)) {
774 	/* MOUSE ERROR: failed to enable the mouse because:
775 	 * 1) the mouse is faulty,
776 	 * 2) the mouse has been removed(!?)
777 	 * In the latter case, the keyboard may have hung, and need
778 	 * recovery procedure...
779 	 */
780 	recover_from_error(sc->kbdc);
781 #if 0
782 	/* FIXME: we could reset the mouse here and try to enable
783 	 * it again. But it will take long time and it's not a good
784 	 * idea to disable the keyboard that long...
785 	 */
786 	if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
787 	    recover_from_error(sc->kbdc);
788 #else
789         {
790 #endif
791             restore_controller(sc->kbdc, command_byte);
792 	    /* mark this device is no longer available */
793 	    sc->state &= ~PSM_VALID;
794 	    log(LOG_ERR, "psm%d: failed to enable the device (doopen).\n",
795 		sc->unit);
796 	    return (EIO);
797 	}
798     }
799 
800     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
801         log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n", sc->unit);
802 
803     /* enable the aux port and interrupt */
804     if (!set_controller_command_byte(sc->kbdc,
805 	    kbdc_get_device_mask(sc->kbdc),
806 	    (command_byte & KBD_KBD_CONTROL_BITS)
807 		| KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
808 	/* CONTROLLER ERROR */
809 	disable_aux_dev(sc->kbdc);
810         restore_controller(sc->kbdc, command_byte);
811 	log(LOG_ERR, "psm%d: failed to enable the aux interrupt (doopen).\n",
812 	    sc->unit);
813 	return (EIO);
814     }
815 
816     /* start the watchdog timer */
817     sc->watchdog = FALSE;
818     sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz*2);
819 
820     return (0);
821 }
822 
823 static int
824 reinitialize(struct psm_softc *sc, int doinit)
825 {
826     int err;
827     int c;
828     int s;
829 
830     /* don't let anybody mess with the aux device */
831     if (!kbdc_lock(sc->kbdc, TRUE))
832 	return (EIO);
833     s = spltty();
834 
835     /* block our watchdog timer */
836     sc->watchdog = FALSE;
837     untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
838     callout_handle_init(&sc->callout);
839 
840     /* save the current controller command byte */
841     empty_both_buffers(sc->kbdc, 10);
842     c = get_controller_command_byte(sc->kbdc);
843     VLOG(2, (LOG_DEBUG, "psm%d: current command byte: %04x (reinitialize).\n",
844 	 sc->unit, c));
845 
846     /* enable the aux port but disable the aux interrupt and the keyboard */
847     if ((c == -1) || !set_controller_command_byte(sc->kbdc,
848 	    kbdc_get_device_mask(sc->kbdc),
849   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
850 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
851         /* CONTROLLER ERROR */
852 	splx(s);
853         kbdc_lock(sc->kbdc, FALSE);
854 	log(LOG_ERR, "psm%d: unable to set the command byte (reinitialize).\n",
855 	    sc->unit);
856 	return (EIO);
857     }
858 
859     /* flush any data */
860     if (sc->state & PSM_VALID) {
861 	disable_aux_dev(sc->kbdc);	/* this may fail; but never mind... */
862 	empty_aux_buffer(sc->kbdc, 10);
863     }
864     flushpackets(sc);
865     sc->syncerrors = 0;
866     sc->pkterrors = 0;
867     memset(&sc->lastinputerr, 0, sizeof(sc->lastinputerr));
868 
869     /* try to detect the aux device; are you still there? */
870     err = 0;
871     if (doinit) {
872 	if (doinitialize(sc, &sc->mode)) {
873 	    /* yes */
874 	    sc->state |= PSM_VALID;
875 	} else {
876 	    /* the device has gone! */
877 	    restore_controller(sc->kbdc, c);
878 	    sc->state &= ~PSM_VALID;
879 	    log(LOG_ERR, "psm%d: the aux device has gone! (reinitialize).\n",
880 		sc->unit);
881 	    err = ENXIO;
882 	}
883     }
884     splx(s);
885 
886     /* restore the driver state */
887     if ((sc->state & PSM_OPEN) && (err == 0)) {
888         /* enable the aux device and the port again */
889 	err = doopen(sc, c);
890 	if (err != 0)
891 	    log(LOG_ERR, "psm%d: failed to enable the device (reinitialize).\n",
892 		sc->unit);
893     } else {
894         /* restore the keyboard port and disable the aux port */
895         if (!set_controller_command_byte(sc->kbdc,
896                 kbdc_get_device_mask(sc->kbdc),
897                 (c & KBD_KBD_CONTROL_BITS)
898                     | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
899             /* CONTROLLER ERROR */
900             log(LOG_ERR,
901                 "psm%d: failed to disable the aux port (reinitialize).\n",
902                 sc->unit);
903             err = EIO;
904 	}
905     }
906 
907     kbdc_lock(sc->kbdc, FALSE);
908     return (err);
909 }
910 
911 /* psm driver entry points */
912 
913 static void
914 psmidentify(driver_t *driver, device_t parent)
915 {
916     device_t psmc;
917     device_t psm;
918     u_long irq;
919     int unit;
920 
921     unit = device_get_unit(parent);
922 
923     /* always add at least one child */
924     psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
925     if (psm == NULL)
926 	return;
927 
928     irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
929     if (irq > 0)
930 	return;
931 
932     /*
933      * If the PS/2 mouse device has already been reported by ACPI or
934      * PnP BIOS, obtain the IRQ resource from it.
935      * (See psmcpnp_attach() below.)
936      */
937     psmc = device_find_child(device_get_parent(parent),
938 			     PSMCPNP_DRIVER_NAME, unit);
939     if (psmc == NULL)
940 	return;
941     irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
942     if (irq <= 0)
943 	return;
944     bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
945 }
946 
947 #define endprobe(v)	do {   if (bootverbose)				\
948 				--verbose;   				\
949                             kbdc_set_device_mask(sc->kbdc, mask);	\
950 			    kbdc_lock(sc->kbdc, FALSE);			\
951 			    return (v);	     				\
952 			} while (0)
953 
954 static int
955 psmprobe(device_t dev)
956 {
957     int unit = device_get_unit(dev);
958     struct psm_softc *sc = device_get_softc(dev);
959     int stat[3];
960     int command_byte;
961     int mask;
962     int rid;
963     int i;
964 
965 #if 0
966     kbdc_debug(TRUE);
967 #endif
968 
969     /* see if IRQ is available */
970     rid = KBDC_RID_AUX;
971     sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
972 				      RF_SHAREABLE | RF_ACTIVE);
973     if (sc->intr == NULL) {
974 	if (bootverbose)
975             device_printf(dev, "unable to allocate IRQ\n");
976         return (ENXIO);
977     }
978     bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
979 
980     sc->unit = unit;
981     sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
982     sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
983     /* XXX: for backward compatibility */
984 #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
985     sc->config |=
986 #ifdef PSM_RESETAFTERSUSPEND
987 	PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
988 #else
989 	PSM_CONFIG_HOOKRESUME;
990 #endif
991 #endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
992     sc->flags = 0;
993     if (bootverbose)
994         ++verbose;
995 
996     device_set_desc(dev, "PS/2 Mouse");
997 
998     if (!kbdc_lock(sc->kbdc, TRUE)) {
999         printf("psm%d: unable to lock the controller.\n", unit);
1000         if (bootverbose)
1001             --verbose;
1002 	return (ENXIO);
1003     }
1004 
1005     /*
1006      * NOTE: two bits in the command byte controls the operation of the
1007      * aux port (mouse port): the aux port disable bit (bit 5) and the aux
1008      * port interrupt (IRQ 12) enable bit (bit 2).
1009      */
1010 
1011     /* discard anything left after the keyboard initialization */
1012     empty_both_buffers(sc->kbdc, 10);
1013 
1014     /* save the current command byte; it will be used later */
1015     mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
1016     command_byte = get_controller_command_byte(sc->kbdc);
1017     if (verbose)
1018         printf("psm%d: current command byte:%04x\n", unit, command_byte);
1019     if (command_byte == -1) {
1020         /* CONTROLLER ERROR */
1021         printf("psm%d: unable to get the current command byte value.\n",
1022             unit);
1023         endprobe(ENXIO);
1024     }
1025 
1026     /*
1027      * disable the keyboard port while probing the aux port, which must be
1028      * enabled during this routine
1029      */
1030     if (!set_controller_command_byte(sc->kbdc,
1031 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1032   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1033                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1034         /*
1035 	 * this is CONTROLLER ERROR; I don't know how to recover
1036          * from this error...
1037 	 */
1038         restore_controller(sc->kbdc, command_byte);
1039         printf("psm%d: unable to set the command byte.\n", unit);
1040         endprobe(ENXIO);
1041     }
1042     write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
1043 
1044     /*
1045      * NOTE: `test_aux_port()' is designed to return with zero if the aux
1046      * port exists and is functioning. However, some controllers appears
1047      * to respond with zero even when the aux port doesn't exist. (It may
1048      * be that this is only the case when the controller DOES have the aux
1049      * port but the port is not wired on the motherboard.) The keyboard
1050      * controllers without the port, such as the original AT, are
1051      * supporsed to return with an error code or simply time out. In any
1052      * case, we have to continue probing the port even when the controller
1053      * passes this test.
1054      *
1055      * XXX: some controllers erroneously return the error code 1, 2 or 3
1056      * when it has the perfectly functional aux port. We have to ignore
1057      * this error code. Even if the controller HAS error with the aux
1058      * port, it will be detected later...
1059      * XXX: another incompatible controller returns PSM_ACK (0xfa)...
1060      */
1061     switch ((i = test_aux_port(sc->kbdc))) {
1062     case 1:	   /* ignore these errors */
1063     case 2:
1064     case 3:
1065     case PSM_ACK:
1066         if (verbose)
1067 	    printf("psm%d: strange result for test aux port (%d).\n",
1068 	        unit, i);
1069 	/* FALLTHROUGH */
1070     case 0:        /* no error */
1071         break;
1072     case -1:        /* time out */
1073     default:        /* error */
1074         recover_from_error(sc->kbdc);
1075 	if (sc->config & PSM_CONFIG_IGNPORTERROR)
1076 	    break;
1077         restore_controller(sc->kbdc, command_byte);
1078         if (verbose)
1079             printf("psm%d: the aux port is not functioning (%d).\n",
1080                 unit, i);
1081         endprobe(ENXIO);
1082     }
1083 
1084     if (sc->config & PSM_CONFIG_NORESET) {
1085 	/*
1086 	 * Don't try to reset the pointing device.  It may possibly be
1087 	 * left in the unknown state, though...
1088 	 */
1089     } else {
1090 	/*
1091 	 * NOTE: some controllers appears to hang the `keyboard' when the aux
1092 	 * port doesn't exist and `PSMC_RESET_DEV' is issued.
1093 	 *
1094 	 * Attempt to reset the controller twice -- this helps
1095 	 * pierce through some KVM switches. The second reset
1096 	 * is non-fatal.
1097 	 */
1098 	if (!reset_aux_dev(sc->kbdc)) {
1099             recover_from_error(sc->kbdc);
1100             restore_controller(sc->kbdc, command_byte);
1101             if (verbose)
1102         	printf("psm%d: failed to reset the aux device.\n", unit);
1103             endprobe(ENXIO);
1104 	} else if (!reset_aux_dev(sc->kbdc)) {
1105 	    recover_from_error(sc->kbdc);
1106 	    if (verbose >= 2)
1107         	printf("psm%d: failed to reset the aux device (2).\n",
1108         	    unit);
1109 	}
1110     }
1111 
1112     /*
1113      * both the aux port and the aux device is functioning, see if the
1114      * device can be enabled. NOTE: when enabled, the device will start
1115      * sending data; we shall immediately disable the device once we know
1116      * the device can be enabled.
1117      */
1118     if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1119         /* MOUSE ERROR */
1120 	recover_from_error(sc->kbdc);
1121 	restore_controller(sc->kbdc, command_byte);
1122 	if (verbose)
1123 	    printf("psm%d: failed to enable the aux device.\n", unit);
1124         endprobe(ENXIO);
1125     }
1126 
1127     /* save the default values after reset */
1128     if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1129 	sc->dflt_mode.rate = sc->mode.rate = stat[2];
1130 	sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1131     } else {
1132 	sc->dflt_mode.rate = sc->mode.rate = -1;
1133 	sc->dflt_mode.resolution = sc->mode.resolution = -1;
1134     }
1135 
1136     /* hardware information */
1137     sc->hw.iftype = MOUSE_IF_PS2;
1138 
1139     /* verify the device is a mouse */
1140     sc->hw.hwid = get_aux_id(sc->kbdc);
1141     if (!is_a_mouse(sc->hw.hwid)) {
1142         restore_controller(sc->kbdc, command_byte);
1143         if (verbose)
1144             printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid);
1145         endprobe(ENXIO);
1146     }
1147     switch (sc->hw.hwid) {
1148     case PSM_BALLPOINT_ID:
1149         sc->hw.type = MOUSE_TRACKBALL;
1150         break;
1151     case PSM_MOUSE_ID:
1152     case PSM_INTELLI_ID:
1153     case PSM_EXPLORER_ID:
1154     case PSM_4DMOUSE_ID:
1155     case PSM_4DPLUS_ID:
1156         sc->hw.type = MOUSE_MOUSE;
1157         break;
1158     default:
1159         sc->hw.type = MOUSE_UNKNOWN;
1160         break;
1161     }
1162 
1163     if (sc->config & PSM_CONFIG_NOIDPROBE) {
1164 	sc->hw.buttons = 2;
1165 	i = GENERIC_MOUSE_ENTRY;
1166     } else {
1167 	/* # of buttons */
1168 	sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1169 
1170 	/* other parameters */
1171 	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
1172 	    if ((*vendortype[i].probefunc)(sc)) {
1173 		if (verbose >= 2)
1174 		    printf("psm%d: found %s\n",
1175 			   unit, model_name(vendortype[i].model));
1176 		break;
1177 	    }
1178 	}
1179     }
1180 
1181     sc->hw.model = vendortype[i].model;
1182 
1183     sc->dflt_mode.level = PSM_LEVEL_BASE;
1184     sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1185     sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1186     if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1187         sc->dflt_mode.syncmask[0] = 0;
1188     else
1189         sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1190     if (sc->config & PSM_CONFIG_FORCETAP)
1191         sc->dflt_mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1192     sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
1193     sc->mode = sc->dflt_mode;
1194     sc->mode.packetsize = vendortype[i].packetsize;
1195 
1196     /* set mouse parameters */
1197 #if 0
1198     /*
1199      * A version of Logitech FirstMouse+ won't report wheel movement,
1200      * if SET_DEFAULTS is sent...  Don't use this command.
1201      * This fix was found by Takashi Nishida.
1202      */
1203     i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1204     if (verbose >= 2)
1205 	printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1206 #endif
1207     if (sc->config & PSM_CONFIG_RESOLUTION) {
1208         sc->mode.resolution
1209 	    = set_mouse_resolution(sc->kbdc,
1210 				   (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1211     } else if (sc->mode.resolution >= 0) {
1212 	sc->mode.resolution
1213 	    = set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1214     }
1215     if (sc->mode.rate > 0) {
1216 	sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1217     }
1218     set_mouse_scaling(sc->kbdc, 1);
1219 
1220     /* Record sync on the next data packet we see. */
1221     sc->flags |= PSM_NEED_SYNCBITS;
1222 
1223     /* just check the status of the mouse */
1224     /*
1225      * NOTE: XXX there are some arcane controller/mouse combinations out
1226      * there, which hung the controller unless there is data transmission
1227      * after ACK from the mouse.
1228      */
1229     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) {
1230         printf("psm%d: failed to get status.\n", unit);
1231     } else {
1232 	/*
1233 	 * When in its native mode, some mice operate with different
1234 	 * default parameters than in the PS/2 compatible mode.
1235 	 */
1236         sc->dflt_mode.rate = sc->mode.rate = stat[2];
1237         sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1238      }
1239 
1240     /* disable the aux port for now... */
1241     if (!set_controller_command_byte(sc->kbdc,
1242 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1243             (command_byte & KBD_KBD_CONTROL_BITS)
1244                 | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1245         /*
1246 	 * this is CONTROLLER ERROR; I don't know the proper way to
1247          * recover from this error...
1248 	 */
1249         restore_controller(sc->kbdc, command_byte);
1250         printf("psm%d: unable to set the command byte.\n", unit);
1251         endprobe(ENXIO);
1252     }
1253 
1254     /* done */
1255     kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1256     kbdc_lock(sc->kbdc, FALSE);
1257     return (0);
1258 }
1259 
1260 static int
1261 psmattach(device_t dev)
1262 {
1263     int unit = device_get_unit(dev);
1264     struct psm_softc *sc = device_get_softc(dev);
1265     int error;
1266     int rid;
1267 
1268     /* Setup initial state */
1269     sc->state = PSM_VALID;
1270     callout_handle_init(&sc->callout);
1271 
1272     /* Setup our interrupt handler */
1273     rid = KBDC_RID_AUX;
1274     sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1275 				      RF_SHAREABLE | RF_ACTIVE);
1276     if (sc->intr == NULL)
1277 	return (ENXIO);
1278     error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, psmintr, sc, &sc->ih);
1279     if (error) {
1280 	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1281 	return (error);
1282     }
1283 
1284     /* Done */
1285     sc->dev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, FALSE), 0, 0, 0666,
1286 		       "psm%d", unit);
1287     sc->bdev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, TRUE), 0, 0, 0666,
1288 			"bpsm%d", unit);
1289 
1290     if (!verbose) {
1291         printf("psm%d: model %s, device ID %d\n",
1292 	    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1293     } else {
1294         printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1295 	    unit, model_name(sc->hw.model),
1296 	    sc->hw.hwid & 0x00ff, sc->hw.hwid >> 8, sc->hw.buttons);
1297 	printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1298 	    unit, sc->config, sc->flags, sc->mode.packetsize);
1299 	printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1300 	    unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1301     }
1302 
1303     if (bootverbose)
1304         --verbose;
1305 
1306     return (0);
1307 }
1308 
1309 static int
1310 psmdetach(device_t dev)
1311 {
1312     struct psm_softc *sc;
1313     int rid;
1314 
1315     sc = device_get_softc(dev);
1316     if (sc->state & PSM_OPEN)
1317 	return EBUSY;
1318 
1319     rid = KBDC_RID_AUX;
1320     bus_teardown_intr(dev, sc->intr, sc->ih);
1321     bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1322 
1323     destroy_dev(sc->dev);
1324     destroy_dev(sc->bdev);
1325 
1326     return 0;
1327 }
1328 
1329 static int
1330 psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
1331 {
1332     int unit = PSM_UNIT(dev);
1333     struct psm_softc *sc;
1334     int command_byte;
1335     int err;
1336     int s;
1337 
1338     /* Get device data */
1339     sc = PSM_SOFTC(unit);
1340     if ((sc == NULL) || (sc->state & PSM_VALID) == 0)
1341 	/* the device is no longer valid/functioning */
1342         return (ENXIO);
1343 
1344     /* Disallow multiple opens */
1345     if (sc->state & PSM_OPEN)
1346         return (EBUSY);
1347 
1348     device_busy(devclass_get_device(psm_devclass, unit));
1349 
1350     /* Initialize state */
1351     sc->mode.level = sc->dflt_mode.level;
1352     sc->mode.protocol = sc->dflt_mode.protocol;
1353     sc->watchdog = FALSE;
1354 
1355     /* flush the event queue */
1356     sc->queue.count = 0;
1357     sc->queue.head = 0;
1358     sc->queue.tail = 0;
1359     sc->status.flags = 0;
1360     sc->status.button = 0;
1361     sc->status.obutton = 0;
1362     sc->status.dx = 0;
1363     sc->status.dy = 0;
1364     sc->status.dz = 0;
1365     sc->button = 0;
1366     sc->pqueue_start = 0;
1367     sc->pqueue_end = 0;
1368 
1369     /* empty input buffer */
1370     flushpackets(sc);
1371     sc->syncerrors = 0;
1372     sc->pkterrors = 0;
1373 
1374     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1375     if (!kbdc_lock(sc->kbdc, TRUE))
1376 	return (EIO);
1377 
1378     /* save the current controller command byte */
1379     s = spltty();
1380     command_byte = get_controller_command_byte(sc->kbdc);
1381 
1382     /* enable the aux port and temporalily disable the keyboard */
1383     if ((command_byte == -1)
1384         || !set_controller_command_byte(sc->kbdc,
1385 	    kbdc_get_device_mask(sc->kbdc),
1386   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1387 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1388         /* CONTROLLER ERROR; do you know how to get out of this? */
1389         kbdc_lock(sc->kbdc, FALSE);
1390 	splx(s);
1391 	log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n",
1392 	    unit);
1393 	return (EIO);
1394     }
1395     /*
1396      * Now that the keyboard controller is told not to generate
1397      * the keyboard and mouse interrupts, call `splx()' to allow
1398      * the other tty interrupts. The clock interrupt may also occur,
1399      * but timeout routines will be blocked by the poll flag set
1400      * via `kbdc_lock()'
1401      */
1402     splx(s);
1403 
1404     /* enable the mouse device */
1405     err = doopen(sc, command_byte);
1406 
1407     /* done */
1408     if (err == 0)
1409         sc->state |= PSM_OPEN;
1410     kbdc_lock(sc->kbdc, FALSE);
1411     return (err);
1412 }
1413 
1414 static int
1415 psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
1416 {
1417     int unit = PSM_UNIT(dev);
1418     struct psm_softc *sc = PSM_SOFTC(unit);
1419     int stat[3];
1420     int command_byte;
1421     int s;
1422 
1423     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1424     if (!kbdc_lock(sc->kbdc, TRUE))
1425 	return (EIO);
1426 
1427     /* save the current controller command byte */
1428     s = spltty();
1429     command_byte = get_controller_command_byte(sc->kbdc);
1430     if (command_byte == -1) {
1431         kbdc_lock(sc->kbdc, FALSE);
1432 	splx(s);
1433 	return (EIO);
1434     }
1435 
1436     /* disable the aux interrupt and temporalily disable the keyboard */
1437     if (!set_controller_command_byte(sc->kbdc,
1438 	    kbdc_get_device_mask(sc->kbdc),
1439   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1440 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1441 	log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n",
1442 	    unit);
1443 	/* CONTROLLER ERROR;
1444 	 * NOTE: we shall force our way through. Because the only
1445 	 * ill effect we shall see is that we may not be able
1446 	 * to read ACK from the mouse, and it doesn't matter much
1447 	 * so long as the mouse will accept the DISABLE command.
1448 	 */
1449     }
1450     splx(s);
1451 
1452     /* stop the watchdog timer */
1453     untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
1454     callout_handle_init(&sc->callout);
1455 
1456     /* remove anything left in the output buffer */
1457     empty_aux_buffer(sc->kbdc, 10);
1458 
1459     /* disable the aux device, port and interrupt */
1460     if (sc->state & PSM_VALID) {
1461         if (!disable_aux_dev(sc->kbdc)) {
1462 	    /* MOUSE ERROR;
1463 	     * NOTE: we don't return error and continue, pretending
1464 	     * we have successfully disabled the device. It's OK because
1465 	     * the interrupt routine will discard any data from the mouse
1466 	     * hereafter.
1467 	     */
1468 	    log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n",
1469 		unit);
1470         }
1471 
1472         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1473             log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n", unit);
1474     }
1475 
1476     if (!set_controller_command_byte(sc->kbdc,
1477 	    kbdc_get_device_mask(sc->kbdc),
1478 	    (command_byte & KBD_KBD_CONTROL_BITS)
1479 	        | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1480 	/* CONTROLLER ERROR;
1481 	 * we shall ignore this error; see the above comment.
1482 	 */
1483 	log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n",
1484 	    unit);
1485     }
1486 
1487     /* remove anything left in the output buffer */
1488     empty_aux_buffer(sc->kbdc, 10);
1489 
1490     /* close is almost always successful */
1491     sc->state &= ~PSM_OPEN;
1492     kbdc_lock(sc->kbdc, FALSE);
1493     device_unbusy(devclass_get_device(psm_devclass, unit));
1494     return (0);
1495 }
1496 
1497 static int
1498 tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status, unsigned char *buf)
1499 {
1500     static unsigned char butmapps2[8] = {
1501         0,
1502         MOUSE_PS2_BUTTON1DOWN,
1503         MOUSE_PS2_BUTTON2DOWN,
1504         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1505         MOUSE_PS2_BUTTON3DOWN,
1506         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1507         MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1508         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1509     };
1510     static unsigned char butmapmsc[8] = {
1511         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1512         MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1513         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1514         MOUSE_MSC_BUTTON3UP,
1515         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1516         MOUSE_MSC_BUTTON2UP,
1517         MOUSE_MSC_BUTTON1UP,
1518         0,
1519     };
1520     int mapped;
1521     int i;
1522 
1523     if (sc->mode.level == PSM_LEVEL_BASE) {
1524         mapped = status->button & ~MOUSE_BUTTON4DOWN;
1525         if (status->button & MOUSE_BUTTON4DOWN)
1526 	    mapped |= MOUSE_BUTTON1DOWN;
1527         status->button = mapped;
1528         buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1529         i = imax(imin(status->dx, 255), -256);
1530 	if (i < 0)
1531 	    buf[0] |= MOUSE_PS2_XNEG;
1532         buf[1] = i;
1533         i = imax(imin(status->dy, 255), -256);
1534 	if (i < 0)
1535 	    buf[0] |= MOUSE_PS2_YNEG;
1536         buf[2] = i;
1537 	return MOUSE_PS2_PACKETSIZE;
1538     } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1539         buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS];
1540         i = imax(imin(status->dx, 255), -256);
1541         buf[1] = i >> 1;
1542         buf[3] = i - buf[1];
1543         i = imax(imin(status->dy, 255), -256);
1544         buf[2] = i >> 1;
1545         buf[4] = i - buf[2];
1546         i = imax(imin(status->dz, 127), -128);
1547         buf[5] = (i >> 1) & 0x7f;
1548         buf[6] = (i - (i >> 1)) & 0x7f;
1549         buf[7] = (~status->button >> 3) & 0x7f;
1550 	return MOUSE_SYS_PACKETSIZE;
1551     }
1552     return pb->inputbytes;
1553 }
1554 
1555 static int
1556 psmread(struct cdev *dev, struct uio *uio, int flag)
1557 {
1558     register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1559     unsigned char buf[PSM_SMALLBUFSIZE];
1560     int error = 0;
1561     int s;
1562     int l;
1563 
1564     if ((sc->state & PSM_VALID) == 0)
1565 	return EIO;
1566 
1567     /* block until mouse activity occured */
1568     s = spltty();
1569     while (sc->queue.count <= 0) {
1570         if (PSM_NBLOCKIO(dev)) {
1571             splx(s);
1572             return EWOULDBLOCK;
1573         }
1574         sc->state |= PSM_ASLP;
1575         error = tsleep( sc, PZERO | PCATCH, "psmrea", 0);
1576         sc->state &= ~PSM_ASLP;
1577         if (error) {
1578             splx(s);
1579             return error;
1580         } else if ((sc->state & PSM_VALID) == 0) {
1581             /* the device disappeared! */
1582             splx(s);
1583             return EIO;
1584 	}
1585     }
1586     splx(s);
1587 
1588     /* copy data to the user land */
1589     while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1590         s = spltty();
1591 	l = imin(sc->queue.count, uio->uio_resid);
1592 	if (l > sizeof(buf))
1593 	    l = sizeof(buf);
1594 	if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1595 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1596 		sizeof(sc->queue.buf) - sc->queue.head);
1597 	    bcopy(&sc->queue.buf[0],
1598 		&buf[sizeof(sc->queue.buf) - sc->queue.head],
1599 		l - (sizeof(sc->queue.buf) - sc->queue.head));
1600 	} else {
1601 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1602 	}
1603 	sc->queue.count -= l;
1604 	sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1605         splx(s);
1606         error = uiomove(buf, l, uio);
1607         if (error)
1608 	    break;
1609     }
1610 
1611     return error;
1612 }
1613 
1614 static int
1615 block_mouse_data(struct psm_softc *sc, int *c)
1616 {
1617     int s;
1618 
1619     if (!kbdc_lock(sc->kbdc, TRUE))
1620 	return EIO;
1621 
1622     s = spltty();
1623     *c = get_controller_command_byte(sc->kbdc);
1624     if ((*c == -1)
1625 	|| !set_controller_command_byte(sc->kbdc,
1626 	    kbdc_get_device_mask(sc->kbdc),
1627             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1628                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1629         /* this is CONTROLLER ERROR */
1630 	splx(s);
1631         kbdc_lock(sc->kbdc, FALSE);
1632 	return EIO;
1633     }
1634 
1635     /*
1636      * The device may be in the middle of status data transmission.
1637      * The transmission will be interrupted, thus, incomplete status
1638      * data must be discarded. Although the aux interrupt is disabled
1639      * at the keyboard controller level, at most one aux interrupt
1640      * may have already been pending and a data byte is in the
1641      * output buffer; throw it away. Note that the second argument
1642      * to `empty_aux_buffer()' is zero, so that the call will just
1643      * flush the internal queue.
1644      * `psmintr()' will be invoked after `splx()' if an interrupt is
1645      * pending; it will see no data and returns immediately.
1646      */
1647     empty_aux_buffer(sc->kbdc, 0);	/* flush the queue */
1648     read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
1649     flushpackets(sc);
1650     splx(s);
1651 
1652     return 0;
1653 }
1654 
1655 static void
1656 dropqueue(struct psm_softc *sc)
1657 {
1658 
1659     	sc->queue.count = 0;
1660    	sc->queue.head = 0;
1661     	sc->queue.tail = 0;
1662 	if ((sc->state & PSM_SOFTARMED) != 0) {
1663 		sc->state &= ~PSM_SOFTARMED;
1664 		untimeout(psmsoftintr, (void *)(uintptr_t)sc, sc->softcallout);
1665 	}
1666 	sc->pqueue_start = sc->pqueue_end;
1667 }
1668 
1669 static void
1670 flushpackets(struct psm_softc *sc)
1671 {
1672 
1673 	dropqueue(sc);
1674 	bzero(&sc->pqueue, sizeof(sc->pqueue));
1675 }
1676 
1677 static int
1678 unblock_mouse_data(struct psm_softc *sc, int c)
1679 {
1680     int error = 0;
1681 
1682     /*
1683      * We may have seen a part of status data during `set_mouse_XXX()'.
1684      * they have been queued; flush it.
1685      */
1686     empty_aux_buffer(sc->kbdc, 0);
1687 
1688     /* restore ports and interrupt */
1689     if (!set_controller_command_byte(sc->kbdc,
1690             kbdc_get_device_mask(sc->kbdc),
1691 	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1692         /* CONTROLLER ERROR; this is serious, we may have
1693          * been left with the inaccessible keyboard and
1694          * the disabled mouse interrupt.
1695          */
1696         error = EIO;
1697     }
1698 
1699     kbdc_lock(sc->kbdc, FALSE);
1700     return error;
1701 }
1702 
1703 static int
1704 psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1705 {
1706     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1707     mousemode_t mode;
1708     mousestatus_t status;
1709 #if (defined(MOUSE_GETVARS))
1710     mousevar_t *var;
1711 #endif
1712     mousedata_t *data;
1713     int stat[3];
1714     int command_byte;
1715     int error = 0;
1716     int s;
1717 
1718     /* Perform IOCTL command */
1719     switch (cmd) {
1720 
1721     case OLD_MOUSE_GETHWINFO:
1722 	s = spltty();
1723         ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1724         ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1725         ((old_mousehw_t *)addr)->type = sc->hw.type;
1726         ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
1727 	splx(s);
1728         break;
1729 
1730     case MOUSE_GETHWINFO:
1731 	s = spltty();
1732         *(mousehw_t *)addr = sc->hw;
1733 	if (sc->mode.level == PSM_LEVEL_BASE)
1734 	    ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1735 	splx(s);
1736         break;
1737 
1738     case MOUSE_SYN_GETHWINFO:
1739 	s = spltty();
1740 	if (synaptics_support && sc->hw.model == MOUSE_MODEL_SYNAPTICS)
1741 	    *(synapticshw_t *)addr = sc->synhw;
1742 	else
1743 	    error = EINVAL;
1744 	splx(s);
1745 	break;
1746 
1747     case OLD_MOUSE_GETMODE:
1748 	s = spltty();
1749 	switch (sc->mode.level) {
1750 	case PSM_LEVEL_BASE:
1751 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1752 	    break;
1753 	case PSM_LEVEL_STANDARD:
1754 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1755 	    break;
1756 	case PSM_LEVEL_NATIVE:
1757 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1758 	    break;
1759 	}
1760         ((old_mousemode_t *)addr)->rate = sc->mode.rate;
1761         ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1762         ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1763 	splx(s);
1764         break;
1765 
1766     case MOUSE_GETMODE:
1767 	s = spltty();
1768         *(mousemode_t *)addr = sc->mode;
1769 	if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
1770 	    ((mousemode_t *)addr)->syncmask[0] = 0;
1771 	    ((mousemode_t *)addr)->syncmask[1] = 0;
1772 	}
1773         ((mousemode_t *)addr)->resolution =
1774 	    MOUSE_RES_LOW - sc->mode.resolution;
1775 	switch (sc->mode.level) {
1776 	case PSM_LEVEL_BASE:
1777 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1778 	    ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE;
1779 	    break;
1780 	case PSM_LEVEL_STANDARD:
1781 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1782 	    ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE;
1783 	    ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1784 	    ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
1785 	    break;
1786 	case PSM_LEVEL_NATIVE:
1787 	    /* FIXME: this isn't quite correct... XXX */
1788 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1789 	    break;
1790 	}
1791 	splx(s);
1792         break;
1793 
1794     case OLD_MOUSE_SETMODE:
1795     case MOUSE_SETMODE:
1796 	if (cmd == OLD_MOUSE_SETMODE) {
1797 	    mode.rate = ((old_mousemode_t *)addr)->rate;
1798 	    /*
1799 	     * resolution  old I/F   new I/F
1800 	     * default        0         0
1801 	     * low            1        -2
1802 	     * medium low     2        -3
1803 	     * medium high    3        -4
1804 	     * high           4        -5
1805 	     */
1806 	    if (((old_mousemode_t *)addr)->resolution > 0)
1807 	        mode.resolution = -((old_mousemode_t *)addr)->resolution - 1;
1808 	    mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor;
1809 	    mode.level = -1;
1810 	} else {
1811 	    mode = *(mousemode_t *)addr;
1812 	}
1813 
1814 	/* adjust and validate parameters. */
1815 	if (mode.rate > UCHAR_MAX)
1816 	    return EINVAL;
1817         if (mode.rate == 0)
1818             mode.rate = sc->dflt_mode.rate;
1819 	else if (mode.rate == -1)
1820 	    /* don't change the current setting */
1821 	    ;
1822 	else if (mode.rate < 0)
1823 	    return EINVAL;
1824 	if (mode.resolution >= UCHAR_MAX)
1825 	    return EINVAL;
1826 	if (mode.resolution >= 200)
1827 	    mode.resolution = MOUSE_RES_HIGH;
1828 	else if (mode.resolution >= 100)
1829 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1830 	else if (mode.resolution >= 50)
1831 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1832 	else if (mode.resolution > 0)
1833 	    mode.resolution = MOUSE_RES_LOW;
1834         if (mode.resolution == MOUSE_RES_DEFAULT)
1835             mode.resolution = sc->dflt_mode.resolution;
1836         else if (mode.resolution == -1)
1837 	    /* don't change the current setting */
1838 	    ;
1839         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1840             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1841 	if (mode.level == -1)
1842 	    /* don't change the current setting */
1843 	    mode.level = sc->mode.level;
1844 	else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX))
1845 	    return EINVAL;
1846         if (mode.accelfactor == -1)
1847 	    /* don't change the current setting */
1848 	    mode.accelfactor = sc->mode.accelfactor;
1849         else if (mode.accelfactor < 0)
1850 	    return EINVAL;
1851 
1852 	/* don't allow anybody to poll the keyboard controller */
1853 	error = block_mouse_data(sc, &command_byte);
1854 	if (error)
1855             return error;
1856 
1857         /* set mouse parameters */
1858 	if (mode.rate > 0)
1859 	    mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1860 	if (mode.resolution >= 0)
1861 	    mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1862 	set_mouse_scaling(sc->kbdc, 1);
1863 	get_mouse_status(sc->kbdc, stat, 0, 3);
1864 
1865         s = spltty();
1866     	sc->mode.rate = mode.rate;
1867     	sc->mode.resolution = mode.resolution;
1868     	sc->mode.accelfactor = mode.accelfactor;
1869     	sc->mode.level = mode.level;
1870         splx(s);
1871 
1872 	unblock_mouse_data(sc, command_byte);
1873         break;
1874 
1875     case MOUSE_GETLEVEL:
1876 	*(int *)addr = sc->mode.level;
1877         break;
1878 
1879     case MOUSE_SETLEVEL:
1880 	if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX))
1881 	    return EINVAL;
1882 	sc->mode.level = *(int *)addr;
1883         break;
1884 
1885     case MOUSE_GETSTATUS:
1886         s = spltty();
1887 	status = sc->status;
1888 	sc->status.flags = 0;
1889 	sc->status.obutton = sc->status.button;
1890 	sc->status.button = 0;
1891 	sc->status.dx = 0;
1892 	sc->status.dy = 0;
1893 	sc->status.dz = 0;
1894         splx(s);
1895         *(mousestatus_t *)addr = status;
1896         break;
1897 
1898 #if (defined(MOUSE_GETVARS))
1899     case MOUSE_GETVARS:
1900 	var = (mousevar_t *)addr;
1901 	bzero(var, sizeof(*var));
1902 	s = spltty();
1903         var->var[0] = MOUSE_VARS_PS2_SIG;
1904         var->var[1] = sc->config;
1905         var->var[2] = sc->flags;
1906 	splx(s);
1907         break;
1908 
1909     case MOUSE_SETVARS:
1910 	return ENODEV;
1911 #endif /* MOUSE_GETVARS */
1912 
1913     case MOUSE_READSTATE:
1914     case MOUSE_READDATA:
1915 	data = (mousedata_t *)addr;
1916 	if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
1917 	    return EINVAL;
1918 
1919 	error = block_mouse_data(sc, &command_byte);
1920 	if (error)
1921             return error;
1922         if ((data->len = get_mouse_status(sc->kbdc, data->buf,
1923 		(cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
1924             error = EIO;
1925 	unblock_mouse_data(sc, command_byte);
1926 	break;
1927 
1928 #if (defined(MOUSE_SETRESOLUTION))
1929     case MOUSE_SETRESOLUTION:
1930 	mode.resolution = *(int *)addr;
1931 	if (mode.resolution >= UCHAR_MAX)
1932 	    return EINVAL;
1933 	else if (mode.resolution >= 200)
1934 	    mode.resolution = MOUSE_RES_HIGH;
1935 	else if (mode.resolution >= 100)
1936 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1937 	else if (mode.resolution >= 50)
1938 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1939 	else if (mode.resolution > 0)
1940 	    mode.resolution = MOUSE_RES_LOW;
1941         if (mode.resolution == MOUSE_RES_DEFAULT)
1942             mode.resolution = sc->dflt_mode.resolution;
1943         else if (mode.resolution == -1)
1944 	    mode.resolution = sc->mode.resolution;
1945         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1946             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1947 
1948 	error = block_mouse_data(sc, &command_byte);
1949 	if (error)
1950             return error;
1951         sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1952 	if (sc->mode.resolution != mode.resolution)
1953 	    error = EIO;
1954 	unblock_mouse_data(sc, command_byte);
1955         break;
1956 #endif /* MOUSE_SETRESOLUTION */
1957 
1958 #if (defined(MOUSE_SETRATE))
1959     case MOUSE_SETRATE:
1960 	mode.rate = *(int *)addr;
1961 	if (mode.rate > UCHAR_MAX)
1962 	    return EINVAL;
1963         if (mode.rate == 0)
1964             mode.rate = sc->dflt_mode.rate;
1965 	else if (mode.rate < 0)
1966 	    mode.rate = sc->mode.rate;
1967 
1968 	error = block_mouse_data(sc, &command_byte);
1969 	if (error)
1970             return error;
1971         sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1972 	if (sc->mode.rate != mode.rate)
1973 	    error = EIO;
1974 	unblock_mouse_data(sc, command_byte);
1975         break;
1976 #endif /* MOUSE_SETRATE */
1977 
1978 #if (defined(MOUSE_SETSCALING))
1979     case MOUSE_SETSCALING:
1980 	if ((*(int *)addr <= 0) || (*(int *)addr > 2))
1981 	    return EINVAL;
1982 
1983 	error = block_mouse_data(sc, &command_byte);
1984 	if (error)
1985             return error;
1986         if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
1987 	    error = EIO;
1988 	unblock_mouse_data(sc, command_byte);
1989         break;
1990 #endif /* MOUSE_SETSCALING */
1991 
1992 #if (defined(MOUSE_GETHWID))
1993     case MOUSE_GETHWID:
1994 	error = block_mouse_data(sc, &command_byte);
1995 	if (error)
1996             return error;
1997         sc->hw.hwid &= ~0x00ff;
1998         sc->hw.hwid |= get_aux_id(sc->kbdc);
1999 	*(int *)addr = sc->hw.hwid & 0x00ff;
2000 	unblock_mouse_data(sc, command_byte);
2001         break;
2002 #endif /* MOUSE_GETHWID */
2003 
2004     default:
2005 	return ENOTTY;
2006     }
2007 
2008     return error;
2009 }
2010 
2011 static void
2012 psmtimeout(void *arg)
2013 {
2014     struct psm_softc *sc;
2015     int s;
2016 
2017     sc = (struct psm_softc *)arg;
2018     s = spltty();
2019     if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
2020 	VLOG(4, (LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit));
2021 	psmintr(sc);
2022 	kbdc_lock(sc->kbdc, FALSE);
2023     }
2024     sc->watchdog = TRUE;
2025     splx(s);
2026     sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz);
2027 }
2028 
2029 /* Add all sysctls under the debug.psm and hw.psm nodes */
2030 SYSCTL_NODE(_debug, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2031 SYSCTL_NODE(_hw, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2032 
2033 SYSCTL_INT(_debug_psm, OID_AUTO, loglevel, CTLFLAG_RW, &verbose, 0, "");
2034 
2035 static int psmhz = 20;
2036 SYSCTL_INT(_debug_psm, OID_AUTO, hz, CTLFLAG_RW, &psmhz, 0, "");
2037 static int psmerrsecs = 2;
2038 SYSCTL_INT(_debug_psm, OID_AUTO, errsecs, CTLFLAG_RW, &psmerrsecs, 0, "");
2039 static int psmerrusecs = 0;
2040 SYSCTL_INT(_debug_psm, OID_AUTO, errusecs, CTLFLAG_RW, &psmerrusecs, 0, "");
2041 static int psmsecs = 0;
2042 SYSCTL_INT(_debug_psm, OID_AUTO, secs, CTLFLAG_RW, &psmsecs, 0, "");
2043 static int psmusecs = 500000;
2044 SYSCTL_INT(_debug_psm, OID_AUTO, usecs, CTLFLAG_RW, &psmusecs, 0, "");
2045 static int pkterrthresh = 2;
2046 SYSCTL_INT(_debug_psm, OID_AUTO, pkterrthresh, CTLFLAG_RW, &pkterrthresh, 0, "");
2047 
2048 static int tap_threshold = PSM_TAP_THRESHOLD;
2049 SYSCTL_INT(_hw_psm, OID_AUTO, tap_threshold, CTLFLAG_RW, &tap_threshold, 0, "");
2050 static int tap_timeout = PSM_TAP_TIMEOUT;
2051 SYSCTL_INT(_hw_psm, OID_AUTO, tap_timeout, CTLFLAG_RW, &tap_timeout, 0, "");
2052 
2053 static void
2054 psmintr(void *arg)
2055 {
2056     struct psm_softc *sc = arg;
2057     struct timeval now;
2058     int c;
2059     packetbuf_t *pb;
2060 
2061 
2062     /* read until there is nothing to read */
2063     while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
2064 
2065         pb = &sc->pqueue[sc->pqueue_end];
2066         /* discard the byte if the device is not open */
2067         if ((sc->state & PSM_OPEN) == 0)
2068             continue;
2069 
2070 	getmicrouptime(&now);
2071 	if ((pb->inputbytes > 0) && timevalcmp(&now, &sc->inputtimeout, >)) {
2072 	    VLOG(3, (LOG_DEBUG, "psmintr: delay too long; "
2073 		 "resetting byte count\n"));
2074 	    pb->inputbytes = 0;
2075 	    sc->syncerrors = 0;
2076 	    sc->pkterrors = 0;
2077 	}
2078 	sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT/1000000;
2079 	sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT%1000000;
2080 	timevaladd(&sc->inputtimeout, &now);
2081 
2082         pb->ipacket[pb->inputbytes++] = c;
2083         if (pb->inputbytes < sc->mode.packetsize)
2084 	    continue;
2085 
2086 	VLOG(4, (LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
2087 	     pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
2088 	     pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
2089 
2090 	c = pb->ipacket[0];
2091 
2092 	if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2093 	    sc->mode.syncmask[1] = (c & sc->mode.syncmask[0]);
2094 	    sc->flags &= ~PSM_NEED_SYNCBITS;
2095 	    VLOG(2, (LOG_DEBUG, "psmintr: Sync bytes now %04x,%04x\n",
2096 	    	 sc->mode.syncmask[0], sc->mode.syncmask[0]));
2097 	} else if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
2098 	    VLOG(3, (LOG_DEBUG, "psmintr: out of sync (%04x != %04x) %d"
2099 		 " cmds since last error.\n",
2100 		 c & sc->mode.syncmask[0], sc->mode.syncmask[1],
2101 		 sc->cmdcount - sc->lasterr));
2102 	    sc->lasterr = sc->cmdcount;
2103 	    /*
2104 	     * The sync byte test is a weak measure of packet
2105 	     * validity.  Conservatively discard any input yet
2106 	     * to be seen by userland when we detect a sync
2107 	     * error since there is a good chance some of
2108 	     * the queued packets have undetected errors.
2109 	     */
2110 	    dropqueue(sc);
2111 	    if (sc->syncerrors == 0)
2112 		sc->pkterrors++;
2113 	    ++sc->syncerrors;
2114 	    sc->lastinputerr = now;
2115 	    if (sc->syncerrors >= sc->mode.packetsize * 2 ||
2116 	        sc->pkterrors >= pkterrthresh) {
2117 
2118 		/*
2119 		 * If we've failed to find a single sync byte in 2
2120 		 * packets worth of data, or we've seen persistent
2121 		 * packet errors during the validation period,
2122 		 * reinitialize the mouse in hopes of returning it
2123 		 * to the expected mode.
2124 		 */
2125 		VLOG(3, (LOG_DEBUG, "psmintr: reset the mouse.\n"));
2126 		reinitialize(sc, TRUE);
2127 	    } else if (sc->syncerrors == sc->mode.packetsize) {
2128 
2129 		/*
2130 		 * Try a soft reset after searching for a sync
2131 		 * byte through a packet length of bytes.
2132 		 */
2133 		VLOG(3, (LOG_DEBUG, "psmintr: re-enable the mouse.\n"));
2134 		pb->inputbytes = 0;
2135 		disable_aux_dev(sc->kbdc);
2136 		enable_aux_dev(sc->kbdc);
2137 	    } else {
2138 		VLOG(3, (LOG_DEBUG, "psmintr: discard a byte (%d)\n",
2139 		     sc->syncerrors));
2140 		pb->inputbytes--;
2141 		bcopy(&pb->ipacket[1], &pb->ipacket[0], pb->inputbytes);
2142 	    }
2143 	    continue;
2144 	}
2145 
2146 	/*
2147 	 * We have what appears to be a valid packet.
2148 	 * Reset the error counters.
2149 	 */
2150 	sc->syncerrors = 0;
2151 
2152 	/*
2153 	 * Drop even good packets if they occur within a timeout
2154 	 * period of a sync error.  This allows the detection of
2155 	 * a change in the mouse's packet mode without exposing
2156 	 * erratic mouse behavior to the user.  Some KVMs forget
2157 	 * enhanced mouse modes during switch events.
2158 	 */
2159 	if (!timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs, &now)) {
2160 		pb->inputbytes = 0;
2161 		continue;
2162 	}
2163 
2164 	/*
2165 	 * Now that we're out of the validation period, reset
2166 	 * the packet error count.
2167 	 */
2168 	sc->pkterrors = 0;
2169 
2170 	sc->cmdcount++;
2171 	if (++sc->pqueue_end >= PSM_PACKETQUEUE)
2172 		sc->pqueue_end = 0;
2173 	/*
2174 	 * If we've filled the queue then call the softintr ourselves,
2175 	 * otherwise schedule the interrupt for later.
2176 	 */
2177 	if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
2178 	    (sc->pqueue_end == sc->pqueue_start)) {
2179     		if ((sc->state & PSM_SOFTARMED) != 0) {
2180 			sc->state &= ~PSM_SOFTARMED;
2181 			untimeout(psmsoftintr, arg, sc->softcallout);
2182 		}
2183 		psmsoftintr(arg);
2184 	} else if ((sc->state & PSM_SOFTARMED) == 0) {
2185 		sc->state |= PSM_SOFTARMED;
2186 		sc->softcallout = timeout(psmsoftintr, arg,
2187 		    psmhz < 1 ? 1 : (hz/psmhz));
2188 	}
2189     }
2190 }
2191 
2192 static void
2193 psmsoftintr(void *arg)
2194 {
2195     /*
2196      * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
2197      * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
2198      */
2199     static int butmap[8] = {
2200         0,
2201 	MOUSE_BUTTON1DOWN,
2202 	MOUSE_BUTTON3DOWN,
2203 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
2204 	MOUSE_BUTTON2DOWN,
2205 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
2206 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
2207         MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
2208     };
2209     static int butmap_versapad[8] = {
2210 	0,
2211 	MOUSE_BUTTON3DOWN,
2212 	0,
2213 	MOUSE_BUTTON3DOWN,
2214 	MOUSE_BUTTON1DOWN,
2215 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
2216 	MOUSE_BUTTON1DOWN,
2217 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
2218     };
2219     static int touchpad_buttons;
2220     static int guest_buttons;
2221     register struct psm_softc *sc = arg;
2222     mousestatus_t ms;
2223     int w, x, y, z;
2224     int c;
2225     int l;
2226     int x0, y0, xavg, yavg, xsensitivity, ysensitivity, sensitivity = 0;
2227     int s;
2228     packetbuf_t *pb;
2229 
2230     getmicrouptime(&sc->lastsoftintr);
2231 
2232     s = spltty();
2233 
2234     do {
2235 
2236 	pb = &sc->pqueue[sc->pqueue_start];
2237 	c = pb->ipacket[0];
2238 	/*
2239 	 * A kludge for Kensington device!
2240 	 * The MSB of the horizontal count appears to be stored in
2241 	 * a strange place.
2242 	 */
2243 	if (sc->hw.model == MOUSE_MODEL_THINK)
2244 	    pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
2245 
2246         /* ignore the overflow bits... */
2247         x = (c & MOUSE_PS2_XNEG) ?  pb->ipacket[1] - 256 : pb->ipacket[1];
2248         y = (c & MOUSE_PS2_YNEG) ?  pb->ipacket[2] - 256 : pb->ipacket[2];
2249 	z = 0;
2250         ms.obutton = sc->button;		  /* previous button state */
2251         ms.button = butmap[c & MOUSE_PS2_BUTTONS];
2252 	/* `tapping' action */
2253 	if (sc->config & PSM_CONFIG_FORCETAP)
2254 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2255 
2256 	switch (sc->hw.model) {
2257 
2258 	case MOUSE_MODEL_EXPLORER:
2259 	    /*
2260 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2261 	     * byte 1:  oy ox sy sx 1  M  R  L
2262 	     * byte 2:  x  x  x  x  x  x  x  x
2263 	     * byte 3:  y  y  y  y  y  y  y  y
2264 	     * byte 4:  *  *  S2 S1 s  d2 d1 d0
2265 	     *
2266 	     * L, M, R, S1, S2: left, middle, right and side buttons
2267 	     * s: wheel data sign bit
2268 	     * d2-d0: wheel data
2269 	     */
2270 	    z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG)
2271 		? (pb->ipacket[3] & 0x0f) - 16 : (pb->ipacket[3] & 0x0f);
2272 	    ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN)
2273 		? MOUSE_BUTTON4DOWN : 0;
2274 	    ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN)
2275 		? MOUSE_BUTTON5DOWN : 0;
2276 	    break;
2277 
2278 	case MOUSE_MODEL_INTELLI:
2279 	case MOUSE_MODEL_NET:
2280 	    /* wheel data is in the fourth byte */
2281 	    z = (char)pb->ipacket[3];
2282 	    /* some mice may send 7 when there is no Z movement?! XXX */
2283 	    if ((z >= 7) || (z <= -7))
2284 		z = 0;
2285 	    /* some compatible mice have additional buttons */
2286 	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN)
2287 		? MOUSE_BUTTON4DOWN : 0;
2288 	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN)
2289 		? MOUSE_BUTTON5DOWN : 0;
2290 	    break;
2291 
2292 	case MOUSE_MODEL_MOUSEMANPLUS:
2293 	    /*
2294 	     * PS2++ protocl packet
2295 	     *
2296 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2297 	     * byte 1:  *  1  p3 p2 1  *  *  *
2298 	     * byte 2:  c1 c2 p1 p0 d1 d0 1  0
2299 	     *
2300 	     * p3-p0: packet type
2301 	     * c1, c2: c1 & c2 == 1, if p2 == 0
2302 	     *         c1 & c2 == 0, if p2 == 1
2303 	     *
2304 	     * packet type: 0 (device type)
2305 	     * See comments in enable_mmanplus() below.
2306 	     *
2307 	     * packet type: 1 (wheel data)
2308 	     *
2309 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2310 	     * byte 3:  h  *  B5 B4 s  d2 d1 d0
2311 	     *
2312 	     * h: 1, if horizontal roller data
2313 	     *    0, if vertical roller data
2314 	     * B4, B5: button 4 and 5
2315 	     * s: sign bit
2316 	     * d2-d0: roller data
2317 	     *
2318 	     * packet type: 2 (reserved)
2319 	     */
2320 	    if (((c & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
2321 		    && (abs(x) > 191)
2322 		    && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
2323 		/* the extended data packet encodes button and wheel events */
2324 		switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
2325 		case 1:
2326 		    /* wheel data packet */
2327 		    x = y = 0;
2328 		    if (pb->ipacket[2] & 0x80) {
2329 			/* horizontal roller count - ignore it XXX*/
2330 		    } else {
2331 			/* vertical roller count */
2332 			z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG)
2333 			    ? (pb->ipacket[2] & 0x0f) - 16
2334 			    : (pb->ipacket[2] & 0x0f);
2335 		    }
2336 		    ms.button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
2337 			? MOUSE_BUTTON4DOWN : 0;
2338 		    ms.button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
2339 			? MOUSE_BUTTON5DOWN : 0;
2340 		    break;
2341 		case 2:
2342 		    /* this packet type is reserved by Logitech... */
2343 		    /*
2344 		     * IBM ScrollPoint Mouse uses this packet type to
2345 		     * encode both vertical and horizontal scroll movement.
2346 		     */
2347 		    x = y = 0;
2348 		    /* horizontal count */
2349 		    if (pb->ipacket[2] & 0x0f)
2350 			z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
2351 		    /* vertical count */
2352 		    if (pb->ipacket[2] & 0xf0)
2353 			z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
2354 #if 0
2355 		    /* vertical count */
2356 		    z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG)
2357 			? ((pb->ipacket[2] >> 4) & 0x0f) - 16
2358 			: ((pb->ipacket[2] >> 4) & 0x0f);
2359 		    /* horizontal count */
2360 		    w = (pb->ipacket[2] & MOUSE_SPOINT_WNEG)
2361 			? (pb->ipacket[2] & 0x0f) - 16
2362 			: (pb->ipacket[2] & 0x0f);
2363 #endif
2364 		    break;
2365 		case 0:
2366 		    /* device type packet - shouldn't happen */
2367 		    /* FALLTHROUGH */
2368 		default:
2369 		    x = y = 0;
2370 		    ms.button = ms.obutton;
2371 		    VLOG(1, (LOG_DEBUG, "psmintr: unknown PS2++ packet type %d:"
2372 		         " 0x%02x 0x%02x 0x%02x\n",
2373 			 MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
2374 			 pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]));
2375 		    break;
2376 		}
2377 	    } else {
2378 		/* preserve button states */
2379 		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2380 	    }
2381 	    break;
2382 
2383 	case MOUSE_MODEL_GLIDEPOINT:
2384 	    /* `tapping' action */
2385 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2386 	    break;
2387 
2388 	case MOUSE_MODEL_NETSCROLL:
2389 	    /* three addtional bytes encode buttons and wheel events */
2390 	    ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
2391 		? MOUSE_BUTTON4DOWN : 0;
2392 	    ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN)
2393 		? MOUSE_BUTTON5DOWN : 0;
2394 	    z = (pb->ipacket[3] & MOUSE_PS2_XNEG)
2395 		? pb->ipacket[4] - 256 : pb->ipacket[4];
2396 	    break;
2397 
2398 	case MOUSE_MODEL_THINK:
2399 	    /* the fourth button state in the first byte */
2400 	    ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
2401 	    break;
2402 
2403 	case MOUSE_MODEL_VERSAPAD:
2404 	    /* VersaPad PS/2 absolute mode message format
2405 	     *
2406 	     * [packet1]     7   6   5   4   3   2   1   0(LSB)
2407 	     *  ipacket[0]:  1   1   0   A   1   L   T   R
2408 	     *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
2409 	     *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
2410 	     *  ipacket[3]:  1   1   1   A   1   L   T   R
2411 	     *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
2412 	     *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
2413 	     *
2414 	     * [note]
2415 	     *  R: right physical mouse button (1=on)
2416 	     *  T: touch pad virtual button (1=tapping)
2417 	     *  L: left physical mouse button (1=on)
2418 	     *  A: position data is valid (1=valid)
2419 	     *  H: horizontal data (12bit signed integer. H11 is sign bit.)
2420 	     *  V: vertical data (12bit signed integer. V11 is sign bit.)
2421 	     *  P: pressure data
2422 	     *
2423 	     * Tapping is mapped to MOUSE_BUTTON4.
2424 	     */
2425 	    ms.button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
2426 	    ms.button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2427 	    x = y = 0;
2428 	    if (c & MOUSE_PS2VERSA_IN_USE) {
2429 		x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
2430 		y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
2431 		if (x0 & 0x800)
2432 		    x0 -= 0x1000;
2433 		if (y0 & 0x800)
2434 		    y0 -= 0x1000;
2435 		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2436 		    x = sc->xold - x0;
2437 		    y = y0 - sc->yold;
2438 		    if (x < 0)	/* XXX */
2439 			x++;
2440 		    else if (x)
2441 			x--;
2442 		    if (y < 0)
2443 			y++;
2444 		    else if (y)
2445 			y--;
2446 		} else {
2447 		    sc->flags |= PSM_FLAGS_FINGERDOWN;
2448 		}
2449 		sc->xold = x0;
2450 		sc->yold = y0;
2451 	    } else {
2452 		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2453 	    }
2454 	    c = ((x < 0) ? MOUSE_PS2_XNEG : 0)
2455 		| ((y < 0) ? MOUSE_PS2_YNEG : 0);
2456 	    break;
2457 
2458 	case MOUSE_MODEL_4D:
2459 	    /*
2460 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2461 	     * byte 1:  s2 d2 s1 d1 1  M  R  L
2462 	     * byte 2:  sx x  x  x  x  x  x  x
2463 	     * byte 3:  sy y  y  y  y  y  y  y
2464 	     *
2465 	     * s1: wheel 1 direction
2466 	     * d1: wheel 1 data
2467 	     * s2: wheel 2 direction
2468 	     * d2: wheel 2 data
2469 	     */
2470 	    x = (pb->ipacket[1] & 0x80) ? pb->ipacket[1] - 256 : pb->ipacket[1];
2471 	    y = (pb->ipacket[2] & 0x80) ? pb->ipacket[2] - 256 : pb->ipacket[2];
2472 	    switch (c & MOUSE_4D_WHEELBITS) {
2473 	    case 0x10:
2474 		z = 1;
2475 		break;
2476 	    case 0x30:
2477 		z = -1;
2478 		break;
2479 	    case 0x40:	/* 2nd wheel turning right XXX */
2480 		z = 2;
2481 		break;
2482 	    case 0xc0:	/* 2nd wheel turning left XXX */
2483 		z = -2;
2484 		break;
2485 	    }
2486 	    break;
2487 
2488 	case MOUSE_MODEL_4DPLUS:
2489 	    if ((x < 16 - 256) && (y < 16 - 256)) {
2490 		/*
2491 		 *          b7 b6 b5 b4 b3 b2 b1 b0
2492 		 * byte 1:  0  0  1  1  1  M  R  L
2493 		 * byte 2:  0  0  0  0  1  0  0  0
2494 		 * byte 3:  0  0  0  0  S  s  d1 d0
2495 		 *
2496 		 * L, M, R, S: left, middle, right and side buttons
2497 		 * s: wheel data sign bit
2498 		 * d1-d0: wheel data
2499 		 */
2500 		x = y = 0;
2501 		if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2502 		    ms.button |= MOUSE_BUTTON4DOWN;
2503 		z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG)
2504 			? ((pb->ipacket[2] & 0x07) - 8)
2505 			: (pb->ipacket[2] & 0x07) ;
2506 	    } else {
2507 		/* preserve previous button states */
2508 		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2509 	    }
2510 	    break;
2511 
2512 	case MOUSE_MODEL_SYNAPTICS:
2513 	    /* TouchPad PS/2 absolute mode message format
2514 	     *
2515 	     *  Bits:        7   6   5   4   3   2   1   0 (LSB)
2516 	     *  ------------------------------------------------
2517 	     *  ipacket[0]:  1   0  W3  W2   0  W1   R   L
2518 	     *  ipacket[1]: Yb  Ya  Y9  Y8  Xb  Xa  X9  X8
2519 	     *  ipacket[2]: Z7  Z6  Z5  Z4  Z3  Z2  Z1  Z0
2520 	     *  ipacket[3]:  1   1  Yc  Xc   0  W0   D   U
2521 	     *  ipacket[4]: X7  X6  X5  X4  X3  X2  X1  X0
2522 	     *  ipacket[5]: Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
2523 	     *
2524 	     * Legend:
2525 	     *  L: left physical mouse button
2526 	     *  R: right physical mouse button
2527 	     *  D: down button
2528 	     *  U: up button
2529 	     *  W: "wrist" value
2530 	     *  X: x position
2531 	     *  Y: x position
2532 	     *  Z: pressure
2533 	     *
2534 	     * Absolute reportable limits:    0 - 6143.
2535 	     * Typical bezel limits:       1472 - 5472.
2536 	     * Typical edge marings:       1632 - 5312.
2537 	     *
2538 	     * w = 3 Passthrough Packet
2539 	     *
2540 	     * Byte 2,5,6 == Byte 1,2,3 of "Guest"
2541 	     */
2542 
2543 	    if (!synaptics_support)
2544 		break;
2545 
2546 	    /* Sanity check for out of sync packets. */
2547 	    if ((pb->ipacket[0] & 0xc8) != 0x80 ||
2548 		(pb->ipacket[3] & 0xc8) != 0xc0)
2549 		goto NEXT;
2550 
2551 	    x = y = x0 = y0 = 0;
2552 
2553 	    /* Pressure value. */
2554 	    z = pb->ipacket[2];
2555 
2556 	    /* Finger width value */
2557 	    if (sc->synhw.capExtended) {
2558 		w = ((pb->ipacket[0] & 0x30) >> 2) |
2559 		    ((pb->ipacket[0] & 0x04) >> 1) |
2560 		    ((pb->ipacket[3] & 0x04) >> 2);
2561 	    } else {
2562 		/* Assume a finger of regular width */
2563 		w = 4;
2564 	    }
2565 
2566 	    /* Handle packets from the guest device */
2567 	    if (w == 3 && sc->synhw.capPassthrough) {
2568 		x = ((pb->ipacket[1] & 0x10) ?
2569 		    pb->ipacket[4] - 256 : pb->ipacket[4]);
2570 		y = ((pb->ipacket[1] & 0x20) ?
2571 		    pb->ipacket[5] - 256 : pb->ipacket[5]);
2572 		z = 0;
2573 
2574 		guest_buttons = 0;
2575 		if (pb->ipacket[1] & 0x01)
2576 		    guest_buttons |= MOUSE_BUTTON1DOWN;
2577 		if (pb->ipacket[1] & 0x04)
2578 		    guest_buttons |= MOUSE_BUTTON2DOWN;
2579 		if (pb->ipacket[1] & 0x02)
2580 		    guest_buttons |= MOUSE_BUTTON3DOWN;
2581 
2582 		ms.button = touchpad_buttons | guest_buttons;
2583 		break;
2584 	    }
2585 
2586 	    /* Button presses */
2587 	    touchpad_buttons = 0;
2588 	    if (pb->ipacket[0] & 0x01)
2589 		  touchpad_buttons |= MOUSE_BUTTON1DOWN;
2590 	    if (pb->ipacket[0] & 0x02)
2591 		  touchpad_buttons |= MOUSE_BUTTON3DOWN;
2592 
2593 	    if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
2594 		if ((pb->ipacket[3] & 0x01) && (pb->ipacket[0] & 0x01) == 0)
2595 		    touchpad_buttons |= MOUSE_BUTTON4DOWN;
2596 		if ((pb->ipacket[3] & 0x02) && (pb->ipacket[0] & 0x02) == 0)
2597 		    touchpad_buttons |= MOUSE_BUTTON5DOWN;
2598 	    }
2599 
2600 	    /*
2601 	     * In newer pads - bit 0x02 in the third byte of
2602 	     * the packet indicates that we have an extended
2603 	     * button press.
2604 	     */
2605 	    if (pb->ipacket[3] & 0x02) {
2606 	        /*
2607 		 * if directional_scrolls is not 1, we treat
2608 	     	 * any of the scrolling directions as middle-click.
2609 	     	 */
2610 		if (sc->syninfo.directional_scrolls) {
2611 		    if (pb->ipacket[4] & 0x01)
2612 			touchpad_buttons |= MOUSE_BUTTON4DOWN;
2613 		    if (pb->ipacket[5] & 0x01)
2614 			touchpad_buttons |= MOUSE_BUTTON5DOWN;
2615 		    if (pb->ipacket[4] & 0x02)
2616 			touchpad_buttons |= MOUSE_BUTTON6DOWN;
2617    		    if (pb->ipacket[5] & 0x02)
2618 			touchpad_buttons |= MOUSE_BUTTON7DOWN;
2619 		} else {
2620 		    if ((pb->ipacket[4] & 0x0F) || (pb->ipacket[5] & 0x0F))
2621 			touchpad_buttons |= MOUSE_BUTTON2DOWN;
2622 		}
2623 
2624 	    }
2625 
2626 	    ms.button = touchpad_buttons | guest_buttons;
2627 
2628 	    /* There is a finger on the pad. */
2629 	    if ((w >= 4 && w <= 7) && (z >= 16 && z < 200)) {
2630 		x0 = ((pb->ipacket[3] & 0x10) << 8) |
2631 		    ((pb->ipacket[1] & 0x0f) << 8) |
2632 		    pb->ipacket[4];
2633 		y0 = ((pb->ipacket[3] & 0x20) << 7) |
2634 		    ((pb->ipacket[1] & 0xf0) << 4) |
2635 		    pb->ipacket[5];
2636 
2637 		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2638 		    x = x0 - sc->xold;
2639 		    y = y0 - sc->yold;
2640 
2641 		    /* we compute averages of x and y movement */
2642 		    if (sc->xaverage == 0)
2643 			sc->xaverage=x;
2644 
2645 		    if (sc->yaverage == 0)
2646 			sc->yaverage=y;
2647 
2648                     xavg = sc->xaverage;
2649                     yavg = sc->yaverage;
2650 
2651 		    sc->xaverage = (xavg + x) >> 1;
2652 		    sc->yaverage = (yavg + y) >> 1;
2653 
2654 		    /*
2655 		     * then use the averages to compute a sensitivity level
2656 		     * in each dimension
2657 		     */
2658 		    xsensitivity = (sc->xaverage - xavg);
2659 		    if (xsensitivity < 0)
2660 			xsensitivity = -xsensitivity;
2661 
2662 		    ysensitivity = (sc->yaverage - yavg);
2663 		    if (ysensitivity < 0)
2664 			ysensitivity = -ysensitivity;
2665 
2666 		    /*
2667 		     * The sensitivity level is higher the faster the finger
2668 		     * is moving. It also tends to be higher in the middle
2669 		     * of a touchpad motion than on either end
2670 		     *
2671 		     * Note - sensitivity gets to 0 when moving slowly - so
2672 		     * we add 1 to it to give it a meaningful value in that case.
2673 		     */
2674 		    sensitivity = (xsensitivity & ysensitivity)+1;
2675 
2676 		    /*
2677 		     * If either our x or y change is greater than our
2678 		     * hi/low speed threshold - we do the high-speed
2679 		     * absolute to relative calculation otherwise we
2680 		     * do the low-speed calculation.
2681 		     */
2682 		    if ((x>sc->syninfo.low_speed_threshold ||
2683 			 x<-sc->syninfo.low_speed_threshold) ||
2684 			(y>sc->syninfo.low_speed_threshold ||
2685 			 y<-sc->syninfo.low_speed_threshold)) {
2686 		    x0 = (x0 + sc->xold * 3) / 4;
2687 		    y0 = (y0 + sc->yold * 3) / 4;
2688 		    x = (x0 - sc->xold) * 10 / 85;
2689 		    y = (y0 - sc->yold) * 10 / 85;
2690 		} else {
2691 			/*
2692 			 * This is the low speed calculation.
2693 			 * We simply check to see if our movement
2694 			 * is more than our minimum movement threshold
2695 			 * and if it is - set the movement to 1 in the
2696 			 * correct direction.
2697 			 * NOTE - Normally this would result in pointer
2698 			 * movement that was WAY too fast.  This works
2699 			 * due to the movement squelch we do later.
2700 			 */
2701 			if (x < -sc->syninfo.min_movement)
2702 		   	    x = -1;
2703 			else if (x > sc->syninfo.min_movement)
2704 			    x = 1;
2705 			else
2706 			   x = 0;
2707 			if (y < -sc->syninfo.min_movement)
2708 			   y = -1;
2709 			else if (y > sc->syninfo.min_movement)
2710 			   y = 1;
2711 			else
2712 			   y = 0;
2713 
2714 		    }
2715 		} else {
2716 		    sc->flags |= PSM_FLAGS_FINGERDOWN;
2717 		}
2718 
2719 		/*
2720 		 * ok - the squelch process.  Take our sensitivity value
2721 		 * and add it to the current squelch value - if squelch
2722 		 * is less than our squelch threshold we kill the movement,
2723 		 * otherwise we reset squelch and pass the movement through.
2724 		 * Since squelch is cumulative - when mouse movement is slow
2725 		 * (around sensitivity 1) the net result is that only
2726 		 * 1 out of every squelch_level packets is
2727 		 * delivered, effectively slowing down the movement.
2728 		 */
2729 		sc->squelch += sensitivity;
2730 		if (sc->squelch < sc->syninfo.squelch_level) {
2731 		    x = 0;
2732 		    y = 0;
2733 		} else
2734 		    sc->squelch = 0;
2735 
2736 		sc->xold = x0;
2737 		sc->yold = y0;
2738 		sc->zmax = imax(z, sc->zmax);
2739 	    } else {
2740 		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2741 
2742 		if (sc->zmax > tap_threshold &&
2743 		    timevalcmp(&sc->lastsoftintr, &sc->taptimeout, <=)) {
2744 			if (w == 0)
2745 			    ms.button |= MOUSE_BUTTON3DOWN;
2746 			else if (w == 1)
2747 			    ms.button |= MOUSE_BUTTON2DOWN;
2748 			else
2749 			    ms.button |= MOUSE_BUTTON1DOWN;
2750 		}
2751 
2752 		sc->zmax = 0;
2753 		sc->taptimeout.tv_sec = tap_timeout / 1000000;
2754 		sc->taptimeout.tv_usec = tap_timeout % 1000000;
2755 		timevaladd(&sc->taptimeout, &sc->lastsoftintr);
2756 	    }
2757 
2758 	    /* Use the extra buttons as a scrollwheel */
2759 	    if (ms.button & MOUSE_BUTTON4DOWN)
2760 		z = -1;
2761 	    else if (ms.button & MOUSE_BUTTON5DOWN)
2762 		z = 1;
2763 	    else
2764 		z = 0;
2765 
2766 	    break;
2767 
2768 	case MOUSE_MODEL_GENERIC:
2769 	default:
2770 	    break;
2771 	}
2772 
2773         /* scale values */
2774         if (sc->mode.accelfactor >= 1) {
2775             if (x != 0) {
2776                 x = x * x / sc->mode.accelfactor;
2777                 if (x == 0)
2778                     x = 1;
2779                 if (c & MOUSE_PS2_XNEG)
2780                     x = -x;
2781             }
2782             if (y != 0) {
2783                 y = y * y / sc->mode.accelfactor;
2784                 if (y == 0)
2785                     y = 1;
2786                 if (c & MOUSE_PS2_YNEG)
2787                     y = -y;
2788             }
2789         }
2790 
2791         ms.dx = x;
2792         ms.dy = y;
2793         ms.dz = z;
2794         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0)
2795 	    | (ms.obutton ^ ms.button);
2796 
2797 	if (sc->mode.level < PSM_LEVEL_NATIVE)
2798 	    pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);
2799 
2800         sc->status.flags |= ms.flags;
2801         sc->status.dx += ms.dx;
2802         sc->status.dy += ms.dy;
2803         sc->status.dz += ms.dz;
2804         sc->status.button = ms.button;
2805         sc->button = ms.button;
2806 
2807 	sc->watchdog = FALSE;
2808 
2809         /* queue data */
2810         if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
2811 	    l = imin(pb->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
2812 	    bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
2813 	    if (pb->inputbytes > l)
2814 	        bcopy(&pb->ipacket[l], &sc->queue.buf[0], pb->inputbytes - l);
2815             sc->queue.tail =
2816 		(sc->queue.tail + pb->inputbytes) % sizeof(sc->queue.buf);
2817             sc->queue.count += pb->inputbytes;
2818 	}
2819         pb->inputbytes = 0;
2820 
2821 NEXT:
2822 	if (++sc->pqueue_start >= PSM_PACKETQUEUE)
2823 		sc->pqueue_start = 0;
2824     } while (sc->pqueue_start != sc->pqueue_end);
2825     if (sc->state & PSM_ASLP) {
2826         sc->state &= ~PSM_ASLP;
2827         wakeup( sc);
2828     }
2829     selwakeuppri(&sc->rsel, PZERO);
2830     sc->state &= ~PSM_SOFTARMED;
2831     splx(s);
2832 }
2833 
2834 static int
2835 psmpoll(struct cdev *dev, int events, struct thread *td)
2836 {
2837     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
2838     int s;
2839     int revents = 0;
2840 
2841     /* Return true if a mouse event available */
2842     s = spltty();
2843     if (events & (POLLIN | POLLRDNORM)) {
2844 	if (sc->queue.count > 0)
2845 	    revents |= events & (POLLIN | POLLRDNORM);
2846 	else
2847 	    selrecord(td, &sc->rsel);
2848     }
2849     splx(s);
2850 
2851     return (revents);
2852 }
2853 
2854 /* vendor/model specific routines */
2855 
2856 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
2857 {
2858     if (set_mouse_resolution(kbdc, res) != res)
2859         return FALSE;
2860     if (set_mouse_scaling(kbdc, scale)
2861 	&& set_mouse_scaling(kbdc, scale)
2862 	&& set_mouse_scaling(kbdc, scale)
2863 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3))
2864 	return TRUE;
2865     return FALSE;
2866 }
2867 
2868 static int
2869 mouse_ext_command(KBDC kbdc, int command)
2870 {
2871     int c;
2872 
2873     c = (command >> 6) & 0x03;
2874     if (set_mouse_resolution(kbdc, c) != c)
2875 	return FALSE;
2876     c = (command >> 4) & 0x03;
2877     if (set_mouse_resolution(kbdc, c) != c)
2878 	return FALSE;
2879     c = (command >> 2) & 0x03;
2880     if (set_mouse_resolution(kbdc, c) != c)
2881 	return FALSE;
2882     c = (command >> 0) & 0x03;
2883     if (set_mouse_resolution(kbdc, c) != c)
2884 	return FALSE;
2885     return TRUE;
2886 }
2887 
2888 #ifdef notyet
2889 /* Logitech MouseMan Cordless II */
2890 static int
2891 enable_lcordless(struct psm_softc *sc)
2892 {
2893     int status[3];
2894     int ch;
2895 
2896     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
2897         return FALSE;
2898     if (status[1] == PSMD_RES_HIGH)
2899 	return FALSE;
2900     ch = (status[0] & 0x07) - 1;	/* channel # */
2901     if ((ch <= 0) || (ch > 4))
2902 	return FALSE;
2903     /*
2904      * status[1]: always one?
2905      * status[2]: battery status? (0-100)
2906      */
2907     return TRUE;
2908 }
2909 #endif /* notyet */
2910 
2911 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
2912 static int
2913 enable_groller(struct psm_softc *sc)
2914 {
2915     int status[3];
2916 
2917     /*
2918      * The special sequence to enable the fourth button and the
2919      * roller. Immediately after this sequence check status bytes.
2920      * if the mouse is NetScroll, the second and the third bytes are
2921      * '3' and 'D'.
2922      */
2923 
2924     /*
2925      * If the mouse is an ordinary PS/2 mouse, the status bytes should
2926      * look like the following.
2927      *
2928      * byte 1 bit 7 always 0
2929      *        bit 6 stream mode (0)
2930      *        bit 5 disabled (0)
2931      *        bit 4 1:1 scaling (0)
2932      *        bit 3 always 0
2933      *        bit 0-2 button status
2934      * byte 2 resolution (PSMD_RES_HIGH)
2935      * byte 3 report rate (?)
2936      */
2937 
2938     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2939         return FALSE;
2940     if ((status[1] != '3') || (status[2] != 'D'))
2941         return FALSE;
2942     /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
2943     sc->hw.buttons = 4;
2944     return TRUE;
2945 }
2946 
2947 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
2948 static int
2949 enable_gmouse(struct psm_softc *sc)
2950 {
2951     int status[3];
2952 
2953     /*
2954      * The special sequence to enable the middle, "rubber" button.
2955      * Immediately after this sequence check status bytes.
2956      * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
2957      * the second and the third bytes are '3' and 'U'.
2958      * NOTE: NetMouse reports that it has three buttons although it has
2959      * two buttons and a rubber button. NetMouse Pro and MIE Mouse
2960      * say they have three buttons too and they do have a button on the
2961      * side...
2962      */
2963     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2964         return FALSE;
2965     if ((status[1] != '3') || (status[2] != 'U'))
2966         return FALSE;
2967     return TRUE;
2968 }
2969 
2970 /* ALPS GlidePoint */
2971 static int
2972 enable_aglide(struct psm_softc *sc)
2973 {
2974     int status[3];
2975 
2976     /*
2977      * The special sequence to obtain ALPS GlidePoint specific
2978      * information. Immediately after this sequence, status bytes will
2979      * contain something interesting.
2980      * NOTE: ALPS produces several models of GlidePoint. Some of those
2981      * do not respond to this sequence, thus, cannot be detected this way.
2982      */
2983     if (set_mouse_sampling_rate(sc->kbdc, 100) != 100)
2984 	return FALSE;
2985     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
2986         return FALSE;
2987     if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
2988         return FALSE;
2989     return TRUE;
2990 }
2991 
2992 /* Kensington ThinkingMouse/Trackball */
2993 static int
2994 enable_kmouse(struct psm_softc *sc)
2995 {
2996     static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
2997     KBDC kbdc = sc->kbdc;
2998     int status[3];
2999     int id1;
3000     int id2;
3001     int i;
3002 
3003     id1 = get_aux_id(kbdc);
3004     if (set_mouse_sampling_rate(kbdc, 10) != 10)
3005 	return FALSE;
3006     /*
3007      * The device is now in the native mode? It returns a different
3008      * ID value...
3009      */
3010     id2 = get_aux_id(kbdc);
3011     if ((id1 == id2) || (id2 != 2))
3012 	return FALSE;
3013 
3014     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
3015         return FALSE;
3016 #if PSM_DEBUG >= 2
3017     /* at this point, resolution is LOW, sampling rate is 10/sec */
3018     if (get_mouse_status(kbdc, status, 0, 3) < 3)
3019         return FALSE;
3020 #endif
3021 
3022     /*
3023      * The special sequence to enable the third and fourth buttons.
3024      * Otherwise they behave like the first and second buttons.
3025      */
3026     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
3027         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3028 	    return FALSE;
3029     }
3030 
3031     /*
3032      * At this point, the device is using default resolution and
3033      * sampling rate for the native mode.
3034      */
3035     if (get_mouse_status(kbdc, status, 0, 3) < 3)
3036         return FALSE;
3037     if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
3038         return FALSE;
3039 
3040     /* the device appears be enabled by this sequence, diable it for now */
3041     disable_aux_dev(kbdc);
3042     empty_aux_buffer(kbdc, 5);
3043 
3044     return TRUE;
3045 }
3046 
3047 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
3048 static int
3049 enable_mmanplus(struct psm_softc *sc)
3050 {
3051     KBDC kbdc = sc->kbdc;
3052     int data[3];
3053 
3054     /* the special sequence to enable the fourth button and the roller. */
3055     /*
3056      * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
3057      * must be called exactly three times since the last RESET command
3058      * before this sequence. XXX
3059      */
3060     if (!set_mouse_scaling(kbdc, 1))
3061 	return FALSE;
3062     if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
3063 	return FALSE;
3064     if (get_mouse_status(kbdc, data, 1, 3) < 3)
3065         return FALSE;
3066 
3067     /*
3068      * PS2++ protocl, packet type 0
3069      *
3070      *          b7 b6 b5 b4 b3 b2 b1 b0
3071      * byte 1:  *  1  p3 p2 1  *  *  *
3072      * byte 2:  1  1  p1 p0 m1 m0 1  0
3073      * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
3074      *
3075      * p3-p0: packet type: 0
3076      * m7-m0: model ID: MouseMan+:0x50, FirstMouse+:0x51, ScrollPoint:0x58...
3077      */
3078     /* check constant bits */
3079     if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
3080         return FALSE;
3081     if ((data[1] & 0xc3) != 0xc2)
3082         return FALSE;
3083     /* check d3-d0 in byte 2 */
3084     if (!MOUSE_PS2PLUS_CHECKBITS(data))
3085         return FALSE;
3086     /* check p3-p0 */
3087     if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
3088         return FALSE;
3089 
3090     sc->hw.hwid &= 0x00ff;
3091     sc->hw.hwid |= data[2] << 8;	/* save model ID */
3092 
3093     /*
3094      * MouseMan+ (or FirstMouse+) is now in its native mode, in which
3095      * the wheel and the fourth button events are encoded in the
3096      * special data packet. The mouse may be put in the IntelliMouse mode
3097      * if it is initialized by the IntelliMouse's method.
3098      */
3099     return TRUE;
3100 }
3101 
3102 /* MS IntelliMouse Explorer */
3103 static int
3104 enable_msexplorer(struct psm_softc *sc)
3105 {
3106     static unsigned char rate0[] = { 200, 100, 80, };
3107     static unsigned char rate1[] = { 200, 200, 80, };
3108     KBDC kbdc = sc->kbdc;
3109     int id;
3110     int i;
3111 
3112     /* the special sequence to enable the extra buttons and the roller. */
3113     for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i) {
3114         if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
3115 	    return FALSE;
3116     }
3117     /* the device will give the genuine ID only after the above sequence */
3118     id = get_aux_id(kbdc);
3119     if (id != PSM_EXPLORER_ID)
3120 	return FALSE;
3121 
3122     sc->hw.hwid = id;
3123     sc->hw.buttons = 5;		/* IntelliMouse Explorer XXX */
3124 
3125     /*
3126      * XXX: this is a kludge to fool some KVM switch products
3127      * which think they are clever enough to know the 4-byte IntelliMouse
3128      * protocol, and assume any other protocols use 3-byte packets.
3129      * They don't convey 4-byte data packets from the IntelliMouse Explorer
3130      * correctly to the host computer because of this!
3131      * The following sequence is actually IntelliMouse's "wake up"
3132      * sequence; it will make the KVM think the mouse is IntelliMouse
3133      * when it is in fact IntelliMouse Explorer.
3134      */
3135     for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i) {
3136         if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
3137 	    break;
3138     }
3139     id = get_aux_id(kbdc);
3140 
3141     return TRUE;
3142 }
3143 
3144 /* MS IntelliMouse */
3145 static int
3146 enable_msintelli(struct psm_softc *sc)
3147 {
3148     /*
3149      * Logitech MouseMan+ and FirstMouse+ will also respond to this
3150      * probe routine and act like IntelliMouse.
3151      */
3152 
3153     static unsigned char rate[] = { 200, 100, 80, };
3154     KBDC kbdc = sc->kbdc;
3155     int id;
3156     int i;
3157 
3158     /* the special sequence to enable the third button and the roller. */
3159     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
3160         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3161 	    return FALSE;
3162     }
3163     /* the device will give the genuine ID only after the above sequence */
3164     id = get_aux_id(kbdc);
3165     if (id != PSM_INTELLI_ID)
3166 	return FALSE;
3167 
3168     sc->hw.hwid = id;
3169     sc->hw.buttons = 3;
3170 
3171     return TRUE;
3172 }
3173 
3174 /* A4 Tech 4D Mouse */
3175 static int
3176 enable_4dmouse(struct psm_softc *sc)
3177 {
3178     /*
3179      * Newer wheel mice from A4 Tech may use the 4D+ protocol.
3180      */
3181 
3182     static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
3183     KBDC kbdc = sc->kbdc;
3184     int id;
3185     int i;
3186 
3187     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
3188         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3189 	    return FALSE;
3190     }
3191     id = get_aux_id(kbdc);
3192     /*
3193      * WinEasy 4D, 4 Way Scroll 4D: 6
3194      * Cable-Free 4D: 8 (4DPLUS)
3195      * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
3196      */
3197     if (id != PSM_4DMOUSE_ID)
3198 	return FALSE;
3199 
3200     sc->hw.hwid = id;
3201     sc->hw.buttons = 3;		/* XXX some 4D mice have 4? */
3202 
3203     return TRUE;
3204 }
3205 
3206 /* A4 Tech 4D+ Mouse */
3207 static int
3208 enable_4dplus(struct psm_softc *sc)
3209 {
3210     /*
3211      * Newer wheel mice from A4 Tech seem to use this protocol.
3212      * Older models are recognized as either 4D Mouse or IntelliMouse.
3213      */
3214     KBDC kbdc = sc->kbdc;
3215     int id;
3216 
3217     /*
3218      * enable_4dmouse() already issued the following ID sequence...
3219     static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
3220     int i;
3221 
3222     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
3223         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3224 	    return FALSE;
3225     }
3226     */
3227 
3228     id = get_aux_id(kbdc);
3229     switch (id) {
3230     case PSM_4DPLUS_ID:
3231 	    sc->hw.buttons = 4;
3232 	    break;
3233     case PSM_4DPLUS_RFSW35_ID:
3234 	    sc->hw.buttons = 3;
3235 	    break;
3236     default:
3237 	    return FALSE;
3238     }
3239 
3240     sc->hw.hwid = id;
3241 
3242     return TRUE;
3243 }
3244 
3245 /* Synaptics Touchpad */
3246 static int
3247 enable_synaptics(struct psm_softc *sc)
3248 {
3249     int status[3];
3250     KBDC kbdc;
3251 
3252     if (!synaptics_support)
3253 	return (FALSE);
3254 
3255     /* Attach extra synaptics sysctl nodes under hw.psm.synaptics */
3256     sysctl_ctx_init(&sc->syninfo.sysctl_ctx);
3257     sc->syninfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->syninfo.sysctl_ctx,
3258 	SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "synaptics",
3259 	CTLFLAG_RD, 0, "Synaptics TouchPad");
3260 
3261     /*
3262      * synaptics_directional_scrolls - if non-zero, the directional
3263      * pad scrolls, otherwise it registers as a middle-click.
3264      */
3265     sc->syninfo.directional_scrolls = 1;
3266     SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3267 	SYSCTL_CHILDREN(sc->syninfo.sysctl_tree),
3268 	OID_AUTO, "directional_scrolls", CTLFLAG_RW,
3269 	&sc->syninfo.directional_scrolls, 0,
3270 	"directional pad scrolls (1=yes  0=3rd button)");
3271 
3272     /*
3273      * Synaptics_low_speed_threshold - the number of touchpad units
3274      * below-which we go into low-speed tracking mode.
3275      */
3276     sc->syninfo.low_speed_threshold = 20;
3277     SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3278 	SYSCTL_CHILDREN(sc->syninfo.sysctl_tree),
3279 	OID_AUTO, "low_speed_threshold", CTLFLAG_RW,
3280 	&sc->syninfo.low_speed_threshold, 0,
3281 	"threshold between low and hi speed positioning");
3282 
3283     /*
3284      * Synaptics_min_movement - the number of touchpad units below
3285      * which we ignore altogether.
3286      */
3287     sc->syninfo.min_movement = 2;
3288     SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3289 	SYSCTL_CHILDREN(sc->syninfo.sysctl_tree),
3290 	OID_AUTO, "min_movement", CTLFLAG_RW,
3291 	&sc->syninfo.min_movement, 0,
3292 	"ignore touchpad movements less than this");
3293 
3294     /*
3295      * Synaptics_squelch_level - level at which we squelch movement
3296      * packets.
3297      *
3298      * This effectively sends 1 out of every synaptics_squelch_level
3299      * packets when * running in low-speed mode.
3300      */
3301     sc->syninfo.squelch_level=3;
3302     SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3303 	SYSCTL_CHILDREN(sc->syninfo.sysctl_tree),
3304 	OID_AUTO, "squelch_level", CTLFLAG_RW,
3305 	&sc->syninfo.squelch_level, 0,
3306 	"squelch level for synaptics touchpads");
3307 
3308     kbdc = sc->kbdc;
3309     disable_aux_dev(kbdc);
3310     sc->hw.buttons = 3;
3311     sc->squelch = 0;
3312 
3313     /* Just to be on the safe side */
3314     set_mouse_scaling(kbdc, 1);
3315 
3316     /* Identify the Touchpad version */
3317     if (mouse_ext_command(kbdc, 0) == 0)
3318 	return (FALSE);
3319     if (get_mouse_status(kbdc, status, 0, 3) != 3)
3320 	return (FALSE);
3321     if (status[1] != 0x47)
3322 	return (FALSE);
3323 
3324     sc->synhw.infoMinor = status[0];
3325     sc->synhw.infoMajor = status[2] & 0x0f;
3326 
3327     if (verbose >= 2)
3328 	printf("Synaptics Touchpad v%d.%d\n",
3329 	    sc->synhw.infoMajor, sc->synhw.infoMinor);
3330 
3331     if (sc->synhw.infoMajor < 4) {
3332 	printf("  Unsupported (pre-v4) Touchpad detected\n");
3333 	return (FALSE);
3334     }
3335 
3336     /* Get the Touchpad model information */
3337     if (mouse_ext_command(kbdc, 3) == 0)
3338 	return (FALSE);
3339     if (get_mouse_status(kbdc, status, 0, 3) != 3)
3340 	return (FALSE);
3341     if ((status[1] & 0x01) != 0) {
3342 	printf("  Failed to read model information\n");
3343 	return (FALSE);
3344     }
3345 
3346     sc->synhw.infoRot180   = (status[0] & 0x80) >> 7;
3347     sc->synhw.infoPortrait = (status[0] & 0x40) >> 6;
3348     sc->synhw.infoSensor   =  status[0] & 0x3f;
3349     sc->synhw.infoHardware = (status[1] & 0xfe) >> 1;
3350     sc->synhw.infoNewAbs   = (status[2] & 0x80) >> 7;
3351     sc->synhw.capPen       = (status[2] & 0x40) >> 6;
3352     sc->synhw.infoSimplC   = (status[2] & 0x20) >> 5;
3353     sc->synhw.infoGeometry =  status[2] & 0x0f;
3354 
3355     if (verbose >= 2) {
3356 	printf("  Model information:\n");
3357 	printf("   infoRot180: %d\n", sc->synhw.infoRot180);
3358 	printf("   infoPortrait: %d\n", sc->synhw.infoPortrait);
3359 	printf("   infoSensor: %d\n", sc->synhw.infoSensor);
3360 	printf("   infoHardware: %d\n", sc->synhw.infoHardware);
3361 	printf("   infoNewAbs: %d\n", sc->synhw.infoNewAbs);
3362 	printf("   capPen: %d\n", sc->synhw.capPen);
3363 	printf("   infoSimplC: %d\n", sc->synhw.infoSimplC);
3364 	printf("   infoGeometry: %d\n", sc->synhw.infoGeometry);
3365     }
3366 
3367     /* Read the extended capability bits */
3368     if (mouse_ext_command(kbdc, 2) == 0)
3369 	return (FALSE);
3370     if (get_mouse_status(kbdc, status, 0, 3) != 3)
3371 	return (FALSE);
3372     if (status[1] != 0x47) {
3373 	printf("  Failed to read extended capability bits\n");
3374 	return (FALSE);
3375     }
3376 
3377     /* Set the different capabilities when they exist */
3378     if ((status[0] & 0x80) >> 7) {
3379 	sc->synhw.capExtended    = (status[0] & 0x80) >> 7;
3380     	sc->synhw.capPassthrough = (status[2] & 0x80) >> 7;
3381     	sc->synhw.capSleep       = (status[2] & 0x10) >> 4;
3382     	sc->synhw.capFourButtons = (status[2] & 0x08) >> 3;
3383     	sc->synhw.capMultiFinger = (status[2] & 0x02) >> 1;
3384     	sc->synhw.capPalmDetect  = (status[2] & 0x01);
3385 
3386 	if (verbose >= 2) {
3387 	    printf("  Extended capabilities:\n");
3388 	    printf("   capExtended: %d\n", sc->synhw.capExtended);
3389 	    printf("   capPassthrough: %d\n", sc->synhw.capPassthrough);
3390 	    printf("   capSleep: %d\n", sc->synhw.capSleep);
3391 	    printf("   capFourButtons: %d\n", sc->synhw.capFourButtons);
3392 	    printf("   capMultiFinger: %d\n", sc->synhw.capMultiFinger);
3393 	    printf("   capPalmDetect: %d\n", sc->synhw.capPalmDetect);
3394 	}
3395 
3396 	/*
3397 	 * if we have bits set in status[0] & 0x70 - then we can load
3398 	 * more information about buttons using query 0x09
3399 	 */
3400         if (status[0] & 0x70) {
3401     	    if (mouse_ext_command(kbdc, 0x09) == 0)
3402 		return (FALSE);
3403 	    if (get_mouse_status(kbdc, status, 0, 3) != 3)
3404 		return (FALSE);
3405 	    sc->hw.buttons = ((status[1] & 0xf0) >> 4) + 3;
3406 	    if (verbose >= 2)
3407 	       printf("  Additional Buttons: %d\n", sc->hw.buttons -3);
3408 	}
3409 
3410     } else {
3411 	sc->synhw.capExtended = 0;
3412 
3413 	if (verbose >= 2)
3414 	    printf("  No extended capabilities\n");
3415     }
3416 
3417     /*
3418      * Read the mode byte
3419      *
3420      * XXX: Note the Synaptics documentation also defines the first
3421      * byte of the response to this query to be a constant 0x3b, this
3422      * does not appear to be true for Touchpads with guest devices.
3423      */
3424     if (mouse_ext_command(kbdc, 1) == 0)
3425 	return (FALSE);
3426     if (get_mouse_status(kbdc, status, 0, 3) != 3)
3427 	return (FALSE);
3428     if (status[1] != 0x47) {
3429 	printf("  Failed to read mode byte\n");
3430 	return (FALSE);
3431     }
3432 
3433     /* Set the mode byte -- request wmode where available */
3434     if (sc->synhw.capExtended)
3435 	mouse_ext_command(kbdc, 0xc1);
3436     else
3437 	mouse_ext_command(kbdc, 0xc0);
3438 
3439     /* Reset the sampling rate */
3440     set_mouse_sampling_rate(kbdc, 20);
3441 
3442     /*
3443      * Report the correct number of buttons
3444      *
3445      * XXX: I'm not sure this is used anywhere.
3446      */
3447     if (sc->synhw.capExtended && sc->synhw.capFourButtons)
3448 	sc->hw.buttons = 4;
3449 
3450     return (TRUE);
3451 }
3452 
3453 /* Interlink electronics VersaPad */
3454 static int
3455 enable_versapad(struct psm_softc *sc)
3456 {
3457     KBDC kbdc = sc->kbdc;
3458     int data[3];
3459 
3460     set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
3461     set_mouse_sampling_rate(kbdc, 100);		/* set rate 100 */
3462     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3463     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3464     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3465     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3466     if (get_mouse_status(kbdc, data, 0, 3) < 3)	/* get status */
3467 	return FALSE;
3468     if (data[2] != 0xa || data[1] != 0 )	/* rate == 0xa && res. == 0 */
3469 	return FALSE;
3470     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3471 
3472     sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
3473 
3474     return TRUE;				/* PS/2 absolute mode */
3475 }
3476 
3477 /*
3478  * Return true if 'now' is earlier than (start + (secs.usecs)).
3479  * Now may be NULL and the function will fetch the current time from
3480  * getmicrouptime(), or a cached 'now' can be passed in.
3481  * All values should be numbers derived from getmicrouptime().
3482  */
3483 static int
3484 timeelapsed(start, secs, usecs, now)
3485 	const struct timeval *start, *now;
3486 	int secs, usecs;
3487 {
3488 	struct timeval snow, tv;
3489 
3490 	/* if there is no 'now' passed in, the get it as a convience. */
3491 	if (now == NULL) {
3492 		getmicrouptime(&snow);
3493 		now = &snow;
3494 	}
3495 
3496 	tv.tv_sec = secs;
3497 	tv.tv_usec = usecs;
3498 	timevaladd(&tv, start);
3499 	return (timevalcmp(&tv, now, <));
3500 }
3501 
3502 static int
3503 psmresume(device_t dev)
3504 {
3505     struct psm_softc *sc = device_get_softc(dev);
3506     int unit = device_get_unit(dev);
3507     int err;
3508 
3509     VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit));
3510 
3511     if (!(sc->config & PSM_CONFIG_HOOKRESUME))
3512 	return (0);
3513 
3514     err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
3515 
3516     if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
3517 	/*
3518 	 * Release the blocked process; it must be notified that the device
3519 	 * cannot be accessed anymore.
3520 	 */
3521         sc->state &= ~PSM_ASLP;
3522         wakeup(sc);
3523     }
3524 
3525     VLOG(2, (LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit));
3526 
3527     return (err);
3528 }
3529 
3530 DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
3531 
3532 #ifdef DEV_ISA
3533 
3534 /*
3535  * This sucks up assignments from PNPBIOS and ACPI.
3536  */
3537 
3538 /*
3539  * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
3540  * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
3541  * can be probed and attached only after the AT keyboard controller is
3542  * attached, we shall quietly reserve the IRQ resource for later use.
3543  * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
3544  * copy the IRQ resource to the PS/2 mouse device instance hanging
3545  * under the keyboard controller, then probe and attach it.
3546  */
3547 
3548 static	devclass_t			psmcpnp_devclass;
3549 
3550 static	device_probe_t			psmcpnp_probe;
3551 static	device_attach_t			psmcpnp_attach;
3552 
3553 static device_method_t psmcpnp_methods[] = {
3554 	DEVMETHOD(device_probe,		psmcpnp_probe),
3555 	DEVMETHOD(device_attach,	psmcpnp_attach),
3556 
3557 	{ 0, 0 }
3558 };
3559 
3560 static driver_t psmcpnp_driver = {
3561 	PSMCPNP_DRIVER_NAME,
3562 	psmcpnp_methods,
3563 	1,			/* no softc */
3564 };
3565 
3566 static struct isa_pnp_id psmcpnp_ids[] = {
3567 	{ 0x030fd041, "PS/2 mouse port" },		/* PNP0F03 */
3568 	{ 0x0e0fd041, "PS/2 mouse port" },		/* PNP0F0E */
3569 	{ 0x120fd041, "PS/2 mouse port" },		/* PNP0F12 */
3570 	{ 0x130fd041, "PS/2 mouse port" },		/* PNP0F13 */
3571 	{ 0x1303d041, "PS/2 port" },			/* PNP0313, XXX */
3572 	{ 0x02002e4f, "Dell PS/2 mouse port" },		/* Lat. X200, Dell */
3573 	{ 0x0002a906, "ALPS Glide Point" },		/* ALPS Glide Point */
3574 	{ 0x80374d24, "IBM PS/2 mouse port" },		/* IBM3780, ThinkPad */
3575 	{ 0x81374d24, "IBM PS/2 mouse port" },		/* IBM3781, ThinkPad */
3576 	{ 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
3577 	{ 0x0290d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9002, Vaio */
3578 	{ 0x0390d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9003, Vaio */
3579 	{ 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
3580 	{ 0 }
3581 };
3582 
3583 static int
3584 create_a_copy(device_t atkbdc, device_t me)
3585 {
3586 	device_t psm;
3587 	u_long irq;
3588 
3589 	/* find the PS/2 mouse device instance under the keyboard controller */
3590 	psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
3591 				device_get_unit(atkbdc));
3592 	if (psm == NULL)
3593 		return ENXIO;
3594 	if (device_get_state(psm) != DS_NOTPRESENT)
3595 		return 0;
3596 
3597 	/* move our resource to the found device */
3598 	irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
3599 	bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
3600 
3601 	/* ...then probe and attach it */
3602 	return device_probe_and_attach(psm);
3603 }
3604 
3605 static int
3606 psmcpnp_probe(device_t dev)
3607 {
3608 	struct resource *res;
3609 	u_long irq;
3610 	int rid;
3611 
3612 	if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids))
3613 		return ENXIO;
3614 
3615 	/*
3616 	 * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
3617 	 * to the PS/2 mouse device node. But, some buggy PnP BIOS
3618 	 * declares the PS/2 mouse device node without an IRQ resource!
3619 	 * If this happens, we shall refer to device hints.
3620 	 * If we still don't find it there, use a hardcoded value... XXX
3621 	 */
3622 	rid = 0;
3623 	irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
3624 	if (irq <= 0) {
3625 		if (resource_long_value(PSM_DRIVER_NAME,
3626 					device_get_unit(dev), "irq", &irq) != 0)
3627 			irq = 12;	/* XXX */
3628 		device_printf(dev, "irq resource info is missing; "
3629 			      "assuming irq %ld\n", irq);
3630 		bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
3631 	}
3632 	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
3633 				     RF_SHAREABLE);
3634 	bus_release_resource(dev, SYS_RES_IRQ, rid, res);
3635 
3636 	/* keep quiet */
3637 	if (!bootverbose)
3638 		device_quiet(dev);
3639 
3640 	return ((res == NULL) ? ENXIO : 0);
3641 }
3642 
3643 static int
3644 psmcpnp_attach(device_t dev)
3645 {
3646 	device_t atkbdc;
3647 	int rid;
3648 
3649 	/* find the keyboard controller, which may be on acpi* or isa* bus */
3650 	atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
3651 				     device_get_unit(dev));
3652 	if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED)) {
3653 		create_a_copy(atkbdc, dev);
3654 	} else {
3655 		/*
3656 		 * If we don't have the AT keyboard controller yet,
3657 		 * just reserve the IRQ for later use...
3658 		 * (See psmidentify() above.)
3659 		 */
3660 		rid = 0;
3661 		bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_SHAREABLE);
3662 	}
3663 
3664 	return 0;
3665 }
3666 
3667 DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
3668 DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
3669 
3670 #endif /* DEV_ISA */
3671