xref: /freebsd/sys/dev/atkbdc/psm.c (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
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  * $FreeBSD$
24  */
25 
26 /*
27  *  Ported to 386bsd Oct 17, 1992
28  *  Sandi Donno, Computer Science, University of Cape Town, South Africa
29  *  Please send bug reports to sandi@cs.uct.ac.za
30  *
31  *  Thanks are also due to Rick Macklem, rick@snowhite.cis.uoguelph.ca -
32  *  although I was only partially successful in getting the alpha release
33  *  of his "driver for the Logitech and ATI Inport Bus mice for use with
34  *  386bsd and the X386 port" to work with my Microsoft mouse, I nevertheless
35  *  found his code to be an invaluable reference when porting this driver
36  *  to 386bsd.
37  *
38  *  Further modifications for latest 386BSD+patchkit and port to NetBSD,
39  *  Andrew Herbert <andrew@werple.apana.org.au> - 8 June 1993
40  *
41  *  Cloned from the Microsoft Bus Mouse driver, also by Erik Forsberg, by
42  *  Andrew Herbert - 12 June 1993
43  *
44  *  Modified for PS/2 mouse by Charles Hannum <mycroft@ai.mit.edu>
45  *  - 13 June 1993
46  *
47  *  Modified for PS/2 AUX mouse by Shoji Yuen <yuen@nuie.nagoya-u.ac.jp>
48  *  - 24 October 1993
49  *
50  *  Hardware access routines and probe logic rewritten by
51  *  Kazutaka Yokota <yokota@zodiac.mech.utsunomiya-u.ac.jp>
52  *  - 3, 14, 22 October 1996.
53  *  - 12 November 1996. IOCTLs and rearranging `psmread', `psmioctl'...
54  *  - 14, 30 November 1996. Uses `kbdio.c'.
55  *  - 13 December 1996. Uses queuing version of `kbdio.c'.
56  *  - January/February 1997. Tweaked probe logic for
57  *    HiNote UltraII/Latitude/Armada laptops.
58  *  - 30 July 1997. Added APM support.
59  *  - 5 March 1997. Defined driver configuration flags (PSM_CONFIG_XXX).
60  *    Improved sync check logic.
61  *    Vendor specific support routines.
62  */
63 
64 #include "opt_psm.h"
65 
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/kernel.h>
69 #include <sys/module.h>
70 #include <sys/bus.h>
71 #include <sys/conf.h>
72 #include <sys/poll.h>
73 #include <sys/syslog.h>
74 #include <machine/bus.h>
75 #include <sys/rman.h>
76 #include <sys/select.h>
77 #include <sys/uio.h>
78 
79 #include <machine/limits.h>
80 #include <sys/mouse.h>
81 #include <machine/resource.h>
82 
83 #include <isa/isavar.h>
84 #include <dev/kbd/atkbdcreg.h>
85 
86 /*
87  * Driver specific options: the following options may be set by
88  * `options' statements in the kernel configuration file.
89  */
90 
91 /* debugging */
92 #ifndef PSM_DEBUG
93 #define PSM_DEBUG	0	/* logging: 0: none, 1: brief, 2: verbose */
94 #endif
95 
96 /* end of driver specific options */
97 
98 /* input queue */
99 #define PSM_BUFSIZE		960
100 #define PSM_SMALLBUFSIZE	240
101 
102 /* operation levels */
103 #define PSM_LEVEL_BASE		0
104 #define PSM_LEVEL_STANDARD	1
105 #define PSM_LEVEL_NATIVE	2
106 #define PSM_LEVEL_MIN		PSM_LEVEL_BASE
107 #define PSM_LEVEL_MAX		PSM_LEVEL_NATIVE
108 
109 /* Logitech PS2++ protocol */
110 #define MOUSE_PS2PLUS_CHECKBITS(b)	\
111 				((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
112 #define MOUSE_PS2PLUS_PACKET_TYPE(b)	\
113 				(((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
114 
115 /* some macros */
116 #define PSM_UNIT(dev)		(minor(dev) >> 1)
117 #define PSM_NBLOCKIO(dev)	(minor(dev) & 1)
118 #define PSM_MKMINOR(unit,block)	(((unit) << 1) | ((block) ? 0:1))
119 
120 #ifndef max
121 #define max(x,y)		((x) > (y) ? (x) : (y))
122 #endif
123 #ifndef min
124 #define min(x,y)		((x) < (y) ? (x) : (y))
125 #endif
126 
127 #define abs(x)			(((x) < 0) ? -(x) : (x))
128 
129 /* ring buffer */
130 typedef struct ringbuf {
131     int           count;	/* # of valid elements in the buffer */
132     int           head;		/* head pointer */
133     int           tail;		/* tail poiner */
134     unsigned char buf[PSM_BUFSIZE];
135 } ringbuf_t;
136 
137 /* driver control block */
138 struct psm_softc {		/* Driver status information */
139     struct selinfo rsel;	/* Process selecting for Input */
140     unsigned char state;	/* Mouse driver state */
141     int           config;	/* driver configuration flags */
142     int           flags;	/* other flags */
143     KBDC          kbdc;		/* handle to access the keyboard controller */
144     struct resource *intr;	/* IRQ resource */
145     void	  *ih;		/* interrupt handle */
146     mousehw_t     hw;		/* hardware information */
147     mousemode_t   mode;		/* operation mode */
148     mousemode_t   dflt_mode;	/* default operation mode */
149     mousestatus_t status;	/* accumulated mouse movement */
150     ringbuf_t     queue;	/* mouse status queue */
151     unsigned char ipacket[16];	/* interim input buffer */
152     int           inputbytes;	/* # of bytes in the input buffer */
153     int           button;	/* the latest button state */
154     int		  xold;	/* previous absolute X position */
155     int		  yold;	/* previous absolute Y position */
156     int		  watchdog;	/* watchdog timer flag */
157     struct callout_handle callout;	/* watchdog timer call out */
158     dev_t	  dev;
159     dev_t	  bdev;
160 };
161 devclass_t psm_devclass;
162 #define PSM_SOFTC(unit)	((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
163 
164 /* driver state flags (state) */
165 #define PSM_VALID		0x80
166 #define PSM_OPEN		1	/* Device is open */
167 #define PSM_ASLP		2	/* Waiting for mouse data */
168 
169 /* driver configuration flags (config) */
170 #define PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
171 #define PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
172 #define PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
173 #define PSM_CONFIG_NOIDPROBE	0x0200  /* disable mouse model probe */
174 #define PSM_CONFIG_NORESET	0x0400  /* don't reset the mouse */
175 #define PSM_CONFIG_FORCETAP	0x0800  /* assume `tap' action exists */
176 #define PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
177 #define PSM_CONFIG_HOOKRESUME	0x2000	/* hook the system resume event */
178 #define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
179 
180 #define PSM_CONFIG_FLAGS	(PSM_CONFIG_RESOLUTION 		\
181 				    | PSM_CONFIG_ACCEL		\
182 				    | PSM_CONFIG_NOCHECKSYNC	\
183 				    | PSM_CONFIG_NOIDPROBE	\
184 				    | PSM_CONFIG_NORESET	\
185 				    | PSM_CONFIG_FORCETAP	\
186 				    | PSM_CONFIG_IGNPORTERROR	\
187 				    | PSM_CONFIG_HOOKRESUME	\
188 				    | PSM_CONFIG_INITAFTERSUSPEND)
189 
190 /* other flags (flags) */
191 #define PSM_FLAGS_FINGERDOWN	0x0001 /* VersaPad finger down */
192 
193 /* for backward compatibility */
194 #define OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
195 #define OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
196 #define OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)
197 
198 typedef struct old_mousehw {
199     int buttons;
200     int iftype;
201     int type;
202     int hwid;
203 } old_mousehw_t;
204 
205 typedef struct old_mousemode {
206     int protocol;
207     int rate;
208     int resolution;
209     int accelfactor;
210 } old_mousemode_t;
211 
212 /* packet formatting function */
213 typedef int packetfunc_t __P((struct psm_softc *, unsigned char *,
214 			      int *, int, mousestatus_t *));
215 
216 /* function prototypes */
217 static int psmprobe __P((device_t));
218 static int psmattach __P((device_t));
219 static int psmdetach __P((device_t));
220 static int psmresume __P((device_t));
221 
222 static d_open_t psmopen;
223 static d_close_t psmclose;
224 static d_read_t psmread;
225 static d_ioctl_t psmioctl;
226 static d_poll_t psmpoll;
227 
228 static int enable_aux_dev __P((KBDC));
229 static int disable_aux_dev __P((KBDC));
230 static int get_mouse_status __P((KBDC, int *, int, int));
231 static int get_aux_id __P((KBDC));
232 static int set_mouse_sampling_rate __P((KBDC, int));
233 static int set_mouse_scaling __P((KBDC, int));
234 static int set_mouse_resolution __P((KBDC, int));
235 static int set_mouse_mode __P((KBDC));
236 static int get_mouse_buttons __P((KBDC));
237 static int is_a_mouse __P((int));
238 static void recover_from_error __P((KBDC));
239 static int restore_controller __P((KBDC, int));
240 static int reinitialize __P((int, mousemode_t *));
241 static int doopen __P((int, int));
242 static char *model_name __P((int));
243 static void psmintr __P((void *));
244 static void psmtimeout __P((void *));
245 
246 /* vendor specific features */
247 typedef int probefunc_t __P((struct psm_softc *));
248 
249 static int mouse_id_proc1 __P((KBDC, int, int, int *));
250 static probefunc_t enable_groller;
251 static probefunc_t enable_gmouse;
252 static probefunc_t enable_aglide;
253 static probefunc_t enable_kmouse;
254 static probefunc_t enable_msexplorer;
255 static probefunc_t enable_msintelli;
256 static probefunc_t enable_4dmouse;
257 static probefunc_t enable_4dplus;
258 static probefunc_t enable_mmanplus;
259 static probefunc_t enable_versapad;
260 static int tame_mouse __P((struct psm_softc *, mousestatus_t *, unsigned char *));
261 
262 static struct {
263     int                 model;
264     unsigned char	syncmask;
265     int 		packetsize;
266     probefunc_t 	*probefunc;
267 } vendortype[] = {
268     /*
269      * WARNING: the order of probe is very important.  Don't mess it
270      * unless you know what you are doing.
271      */
272     { MOUSE_MODEL_NET,			/* Genius NetMouse */
273       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse, },
274     { MOUSE_MODEL_NETSCROLL,		/* Genius NetScroll */
275       0xc8, 6, enable_groller, },
276     { MOUSE_MODEL_MOUSEMANPLUS,		/* Logitech MouseMan+ */
277       0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus, },
278     { MOUSE_MODEL_EXPLORER,		/* Microsoft IntelliMouse Explorer */
279       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer, },
280     { MOUSE_MODEL_4D,			/* A4 Tech 4D Mouse */
281       0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse, },
282     { MOUSE_MODEL_4DPLUS,		/* A4 Tech 4D+ Mouse */
283       0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus, },
284     { MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
285       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli, },
286     { MOUSE_MODEL_GLIDEPOINT,		/* ALPS GlidePoint */
287       0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide, },
288     { MOUSE_MODEL_THINK,		/* Kensignton ThinkingMouse */
289       0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse, },
290     { MOUSE_MODEL_VERSAPAD,		/* Interlink electronics VersaPad */
291       0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad, },
292     { MOUSE_MODEL_GENERIC,
293       0xc0, MOUSE_PS2_PACKETSIZE, NULL, },
294 };
295 #define GENERIC_MOUSE_ENTRY	((sizeof(vendortype) / sizeof(*vendortype)) - 1)
296 
297 /* device driver declarateion */
298 static device_method_t psm_methods[] = {
299 	/* Device interface */
300 	DEVMETHOD(device_probe,		psmprobe),
301 	DEVMETHOD(device_attach,	psmattach),
302 	DEVMETHOD(device_detach,	psmdetach),
303 	DEVMETHOD(device_resume,	psmresume),
304 
305 	{ 0, 0 }
306 };
307 
308 static driver_t psm_driver = {
309     "psm",
310     psm_methods,
311     sizeof(struct psm_softc),
312 };
313 
314 #if notyet
315 static struct isa_pnp_id psm_ids[] = {
316     { 0x130fd041, "PS/2 mouse port" },			/* PNP0F13 */
317     { 0x1303d041, "PS/2 port" },			/* PNP0313, XXX */
318     { 0 }
319 };
320 #endif
321 
322 #define CDEV_MAJOR        21
323 
324 static struct cdevsw psm_cdevsw = {
325 	/* open */	psmopen,
326 	/* close */	psmclose,
327 	/* read */	psmread,
328 	/* write */	nowrite,
329 	/* ioctl */	psmioctl,
330 	/* poll */	psmpoll,
331 	/* mmap */	nommap,
332 	/* strategy */	nostrategy,
333 	/* name */	"psm",
334 	/* maj */	CDEV_MAJOR,
335 	/* dump */	nodump,
336 	/* psize */	nopsize,
337 	/* flags */	0,
338 	/* bmaj */	-1
339 };
340 
341 /* debug message level */
342 static int verbose = PSM_DEBUG;
343 
344 /* device I/O routines */
345 static int
346 enable_aux_dev(KBDC kbdc)
347 {
348     int res;
349 
350     res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
351     if (verbose >= 2)
352         log(LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res);
353 
354     return (res == PSM_ACK);
355 }
356 
357 static int
358 disable_aux_dev(KBDC kbdc)
359 {
360     int res;
361 
362     res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
363     if (verbose >= 2)
364         log(LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res);
365 
366     return (res == PSM_ACK);
367 }
368 
369 static int
370 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
371 {
372     int cmd;
373     int res;
374     int i;
375 
376     switch (flag) {
377     case 0:
378     default:
379 	cmd = PSMC_SEND_DEV_STATUS;
380 	break;
381     case 1:
382 	cmd = PSMC_SEND_DEV_DATA;
383 	break;
384     }
385     empty_aux_buffer(kbdc, 5);
386     res = send_aux_command(kbdc, cmd);
387     if (verbose >= 2)
388         log(LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
389 	    (flag == 1) ? "DATA" : "STATUS", res);
390     if (res != PSM_ACK)
391         return 0;
392 
393     for (i = 0; i < len; ++i) {
394         status[i] = read_aux_data(kbdc);
395 	if (status[i] < 0)
396 	    break;
397     }
398 
399     if (verbose) {
400         log(LOG_DEBUG, "psm: %s %02x %02x %02x\n",
401             (flag == 1) ? "data" : "status", status[0], status[1], status[2]);
402     }
403 
404     return i;
405 }
406 
407 static int
408 get_aux_id(KBDC kbdc)
409 {
410     int res;
411     int id;
412 
413     empty_aux_buffer(kbdc, 5);
414     res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
415     if (verbose >= 2)
416         log(LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res);
417     if (res != PSM_ACK)
418 	return (-1);
419 
420     /* 10ms delay */
421     DELAY(10000);
422 
423     id = read_aux_data(kbdc);
424     if (verbose >= 2)
425         log(LOG_DEBUG, "psm: device ID: %04x\n", id);
426 
427     return id;
428 }
429 
430 static int
431 set_mouse_sampling_rate(KBDC kbdc, int rate)
432 {
433     int res;
434 
435     res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
436     if (verbose >= 2)
437         log(LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res);
438 
439     return ((res == PSM_ACK) ? rate : -1);
440 }
441 
442 static int
443 set_mouse_scaling(KBDC kbdc, int scale)
444 {
445     int res;
446 
447     switch (scale) {
448     case 1:
449     default:
450 	scale = PSMC_SET_SCALING11;
451 	break;
452     case 2:
453 	scale = PSMC_SET_SCALING21;
454 	break;
455     }
456     res = send_aux_command(kbdc, scale);
457     if (verbose >= 2)
458         log(LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
459 	    (scale == PSMC_SET_SCALING21) ? "21" : "11", res);
460 
461     return (res == PSM_ACK);
462 }
463 
464 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
465 static int
466 set_mouse_resolution(KBDC kbdc, int val)
467 {
468     int res;
469 
470     res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
471     if (verbose >= 2)
472         log(LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res);
473 
474     return ((res == PSM_ACK) ? val : -1);
475 }
476 
477 /*
478  * NOTE: once `set_mouse_mode()' is called, the mouse device must be
479  * re-enabled by calling `enable_aux_dev()'
480  */
481 static int
482 set_mouse_mode(KBDC kbdc)
483 {
484     int res;
485 
486     res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
487     if (verbose >= 2)
488         log(LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res);
489 
490     return (res == PSM_ACK);
491 }
492 
493 static int
494 get_mouse_buttons(KBDC kbdc)
495 {
496     int c = 2;		/* assume two buttons by default */
497     int status[3];
498 
499     /*
500      * NOTE: a special sequence to obtain Logitech Mouse specific
501      * information: set resolution to 25 ppi, set scaling to 1:1, set
502      * scaling to 1:1, set scaling to 1:1. Then the second byte of the
503      * mouse status bytes is the number of available buttons.
504      * Some manufactures also support this sequence.
505      */
506     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
507         return c;
508     if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1)
509         && set_mouse_scaling(kbdc, 1)
510 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3)) {
511         if (status[1] != 0)
512             return status[1];
513     }
514     return c;
515 }
516 
517 /* misc subroutines */
518 /*
519  * Someday, I will get the complete list of valid pointing devices and
520  * their IDs... XXX
521  */
522 static int
523 is_a_mouse(int id)
524 {
525 #if 0
526     static int valid_ids[] = {
527         PSM_MOUSE_ID,		/* mouse */
528         PSM_BALLPOINT_ID,	/* ballpoint device */
529         PSM_INTELLI_ID,		/* Intellimouse */
530         PSM_EXPLORER_ID,	/* Intellimouse Explorer */
531         -1			/* end of table */
532     };
533     int i;
534 
535     for (i = 0; valid_ids[i] >= 0; ++i)
536         if (valid_ids[i] == id)
537             return TRUE;
538     return FALSE;
539 #else
540     return TRUE;
541 #endif
542 }
543 
544 static char *
545 model_name(int model)
546 {
547     static struct {
548 	int model_code;
549 	char *model_name;
550     } models[] = {
551         { MOUSE_MODEL_NETSCROLL,	"NetScroll" },
552         { MOUSE_MODEL_NET,		"NetMouse/NetScroll Optical" },
553         { MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
554         { MOUSE_MODEL_THINK,		"ThinkingMouse" },
555         { MOUSE_MODEL_INTELLI,		"IntelliMouse" },
556         { MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
557         { MOUSE_MODEL_VERSAPAD,		"VersaPad" },
558         { MOUSE_MODEL_EXPLORER,		"IntelliMouse Explorer" },
559         { MOUSE_MODEL_4D,		"4D Mouse" },
560         { MOUSE_MODEL_4DPLUS,		"4D+ Mouse" },
561         { MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
562         { MOUSE_MODEL_UNKNOWN,		NULL },
563     };
564     int i;
565 
566     for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i) {
567 	if (models[i].model_code == model)
568 	    return models[i].model_name;
569     }
570     return "Unknown";
571 }
572 
573 static void
574 recover_from_error(KBDC kbdc)
575 {
576     /* discard anything left in the output buffer */
577     empty_both_buffers(kbdc, 10);
578 
579 #if 0
580     /*
581      * NOTE: KBDC_RESET_KBD may not restore the communication between the
582      * keyboard and the controller.
583      */
584     reset_kbd(kbdc);
585 #else
586     /*
587      * NOTE: somehow diagnostic and keyboard port test commands bring the
588      * keyboard back.
589      */
590     if (!test_controller(kbdc))
591         log(LOG_ERR, "psm: keyboard controller failed.\n");
592     /* if there isn't a keyboard in the system, the following error is OK */
593     if (test_kbd_port(kbdc) != 0) {
594 	if (verbose)
595 	    log(LOG_ERR, "psm: keyboard port failed.\n");
596     }
597 #endif
598 }
599 
600 static int
601 restore_controller(KBDC kbdc, int command_byte)
602 {
603     empty_both_buffers(kbdc, 10);
604 
605     if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
606 	log(LOG_ERR, "psm: failed to restore the keyboard controller "
607 		     "command byte.\n");
608 	empty_both_buffers(kbdc, 10);
609 	return FALSE;
610     } else {
611 	empty_both_buffers(kbdc, 10);
612 	return TRUE;
613     }
614 }
615 
616 /*
617  * Re-initialize the aux port and device. The aux port must be enabled
618  * and its interrupt must be disabled before calling this routine.
619  * The aux device will be disabled before returning.
620  * The keyboard controller must be locked via `kbdc_lock()' before
621  * calling this routine.
622  */
623 static int
624 reinitialize(int unit, mousemode_t *mode)
625 {
626     struct psm_softc *sc = PSM_SOFTC(unit);
627     KBDC kbdc = sc->kbdc;
628     int stat[3];
629     int i;
630 
631     switch((i = test_aux_port(kbdc))) {
632     case 1:	/* ignore this error */
633     case PSM_ACK:
634 	if (verbose)
635 	    log(LOG_DEBUG, "psm%d: strange result for test aux port (%d).\n",
636 	        unit, i);
637 	/* fall though */
638     case 0:	/* no error */
639     	break;
640     case -1: 	/* time out */
641     default: 	/* error */
642     	recover_from_error(kbdc);
643 	if (sc->config & PSM_CONFIG_IGNPORTERROR)
644 	    break;
645     	log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
646     	    unit, i);
647     	return FALSE;
648     }
649 
650     if (sc->config & PSM_CONFIG_NORESET) {
651 	/*
652 	 * Don't try to reset the pointing device.  It may possibly be
653 	 * left in the unknown state, though...
654 	 */
655     } else {
656 	/*
657 	 * NOTE: some controllers appears to hang the `keyboard' when
658 	 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
659 	 */
660 	if (!reset_aux_dev(kbdc)) {
661             recover_from_error(kbdc);
662             log(LOG_ERR, "psm%d: failed to reset the aux device.\n", unit);
663             return FALSE;
664 	}
665     }
666 
667     /*
668      * both the aux port and the aux device is functioning, see
669      * if the device can be enabled.
670      */
671     if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
672         log(LOG_ERR, "psm%d: failed to enable the aux device.\n", unit);
673         return FALSE;
674     }
675     empty_both_buffers(kbdc, 10);	/* remove stray data if any */
676 
677     if (sc->config & PSM_CONFIG_NOIDPROBE) {
678 	i = GENERIC_MOUSE_ENTRY;
679     } else {
680 	/* FIXME: hardware ID, mouse buttons? */
681 
682 	/* other parameters */
683 	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
684 	    if ((*vendortype[i].probefunc)(sc)) {
685 		if (verbose >= 2)
686 		    log(LOG_ERR, "psm%d: found %s\n",
687 			unit, model_name(vendortype[i].model));
688 		break;
689 	    }
690 	}
691     }
692 
693     sc->hw.model = vendortype[i].model;
694     sc->mode.packetsize = vendortype[i].packetsize;
695 
696     /* set mouse parameters */
697     if (mode != (mousemode_t *)NULL) {
698 	if (mode->rate > 0)
699             mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
700 	if (mode->resolution >= 0)
701             mode->resolution = set_mouse_resolution(kbdc, mode->resolution);
702         set_mouse_scaling(kbdc, 1);
703         set_mouse_mode(kbdc);
704     }
705 
706     /* request a data packet and extract sync. bits */
707     if (get_mouse_status(kbdc, stat, 1, 3) < 3) {
708         log(LOG_DEBUG, "psm%d: failed to get data (reinitialize).\n", unit);
709         sc->mode.syncmask[0] = 0;
710     } else {
711         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
712 	/* the NetScroll Mouse will send three more bytes... Ignore them */
713 	empty_aux_buffer(kbdc, 5);
714     }
715 
716     /* just check the status of the mouse */
717     if (get_mouse_status(kbdc, stat, 0, 3) < 3)
718         log(LOG_DEBUG, "psm%d: failed to get status (reinitialize).\n", unit);
719 
720     return TRUE;
721 }
722 
723 static int
724 doopen(int unit, int command_byte)
725 {
726     struct psm_softc *sc = PSM_SOFTC(unit);
727     int stat[3];
728 
729     /* enable the mouse device */
730     if (!enable_aux_dev(sc->kbdc)) {
731 	/* MOUSE ERROR: failed to enable the mouse because:
732 	 * 1) the mouse is faulty,
733 	 * 2) the mouse has been removed(!?)
734 	 * In the latter case, the keyboard may have hung, and need
735 	 * recovery procedure...
736 	 */
737 	recover_from_error(sc->kbdc);
738 #if 0
739 	/* FIXME: we could reset the mouse here and try to enable
740 	 * it again. But it will take long time and it's not a good
741 	 * idea to disable the keyboard that long...
742 	 */
743 	if (!reinitialize(unit, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
744 	    recover_from_error(sc->kbdc);
745 #else
746         {
747 #endif
748             restore_controller(sc->kbdc, command_byte);
749 	    /* mark this device is no longer available */
750 	    sc->state &= ~PSM_VALID;
751 	    log(LOG_ERR, "psm%d: failed to enable the device (doopen).\n",
752 		unit);
753 	    return (EIO);
754 	}
755     }
756 
757     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
758         log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n", unit);
759 
760     /* enable the aux port and interrupt */
761     if (!set_controller_command_byte(sc->kbdc,
762 	    kbdc_get_device_mask(sc->kbdc),
763 	    (command_byte & KBD_KBD_CONTROL_BITS)
764 		| KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
765 	/* CONTROLLER ERROR */
766 	disable_aux_dev(sc->kbdc);
767         restore_controller(sc->kbdc, command_byte);
768 	log(LOG_ERR, "psm%d: failed to enable the aux interrupt (doopen).\n",
769 	    unit);
770 	return (EIO);
771     }
772 
773     /* start the watchdog timer */
774     sc->watchdog = FALSE;
775     sc->callout = timeout(psmtimeout, (void *)(uintptr_t)unit, hz*2);
776 
777     return (0);
778 }
779 
780 /* psm driver entry points */
781 
782 #define endprobe(v)	{   if (bootverbose) 				\
783 				--verbose;   				\
784                             kbdc_set_device_mask(sc->kbdc, mask);	\
785 			    kbdc_lock(sc->kbdc, FALSE);			\
786 			    return (v);	     				\
787 			}
788 
789 static int
790 psmprobe(device_t dev)
791 {
792     int unit = device_get_unit(dev);
793     struct psm_softc *sc = device_get_softc(dev);
794     uintptr_t irq;
795     uintptr_t flags;
796     int stat[3];
797     int command_byte;
798     int mask;
799     int rid;
800     int i;
801 
802 #if 0
803     kbdc_debug(TRUE);
804 #endif
805 
806 #if notyet
807     /* check PnP IDs */
808     if (XXX_PNP_PROBE(device_get_parent(dev), dev, psm_ids) == ENXIO)
809 	return ENXIO;
810 #endif
811 
812     BUS_READ_IVAR(device_get_parent(dev), dev, KBDC_IVAR_IRQ, &irq);
813     BUS_READ_IVAR(device_get_parent(dev), dev, KBDC_IVAR_FLAGS, &flags);
814 
815     sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
816     sc->config = flags & PSM_CONFIG_FLAGS;
817     /* XXX: for backward compatibility */
818 #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
819     sc->config |=
820 #ifdef PSM_RESETAFTERSUSPEND
821 	PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
822 #else
823 	PSM_CONFIG_HOOKRESUME;
824 #endif
825 #endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
826     sc->flags = 0;
827     if (bootverbose)
828         ++verbose;
829 
830     device_set_desc(dev, "PS/2 Mouse");
831 
832     if (!kbdc_lock(sc->kbdc, TRUE)) {
833         printf("psm%d: unable to lock the controller.\n", unit);
834         if (bootverbose)
835             --verbose;
836 	return (ENXIO);
837     }
838 
839     /*
840      * NOTE: two bits in the command byte controls the operation of the
841      * aux port (mouse port): the aux port disable bit (bit 5) and the aux
842      * port interrupt (IRQ 12) enable bit (bit 2).
843      */
844 
845     /* discard anything left after the keyboard initialization */
846     empty_both_buffers(sc->kbdc, 10);
847 
848     /* save the current command byte; it will be used later */
849     mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
850     command_byte = get_controller_command_byte(sc->kbdc);
851     if (verbose)
852         printf("psm%d: current command byte:%04x\n", unit, command_byte);
853     if (command_byte == -1) {
854         /* CONTROLLER ERROR */
855         printf("psm%d: unable to get the current command byte value.\n",
856             unit);
857         endprobe(ENXIO);
858     }
859 
860     /*
861      * disable the keyboard port while probing the aux port, which must be
862      * enabled during this routine
863      */
864     if (!set_controller_command_byte(sc->kbdc,
865 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
866   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
867                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
868         /*
869 	 * this is CONTROLLER ERROR; I don't know how to recover
870          * from this error...
871 	 */
872         restore_controller(sc->kbdc, command_byte);
873         printf("psm%d: unable to set the command byte.\n", unit);
874         endprobe(ENXIO);
875     }
876     write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
877 
878     /*
879      * NOTE: `test_aux_port()' is designed to return with zero if the aux
880      * port exists and is functioning. However, some controllers appears
881      * to respond with zero even when the aux port doesn't exist. (It may
882      * be that this is only the case when the controller DOES have the aux
883      * port but the port is not wired on the motherboard.) The keyboard
884      * controllers without the port, such as the original AT, are
885      * supporsed to return with an error code or simply time out. In any
886      * case, we have to continue probing the port even when the controller
887      * passes this test.
888      *
889      * XXX: some controllers erroneously return the error code 1 when
890      * it has the perfectly functional aux port. We have to ignore this
891      * error code. Even if the controller HAS error with the aux port,
892      * it will be detected later...
893      * XXX: another incompatible controller returns PSM_ACK (0xfa)...
894      */
895     switch ((i = test_aux_port(sc->kbdc))) {
896     case 1:	   /* ignore this error */
897     case PSM_ACK:
898         if (verbose)
899 	    printf("psm%d: strange result for test aux port (%d).\n",
900 	        unit, i);
901 	/* fall though */
902     case 0:        /* no error */
903         break;
904     case -1:        /* time out */
905     default:        /* error */
906         recover_from_error(sc->kbdc);
907 	if (sc->config & PSM_CONFIG_IGNPORTERROR)
908 	    break;
909         restore_controller(sc->kbdc, command_byte);
910         if (verbose)
911             printf("psm%d: the aux port is not functioning (%d).\n",
912                 unit, i);
913         endprobe(ENXIO);
914     }
915 
916     if (sc->config & PSM_CONFIG_NORESET) {
917 	/*
918 	 * Don't try to reset the pointing device.  It may possibly be
919 	 * left in the unknown state, though...
920 	 */
921     } else {
922 	/*
923 	 * NOTE: some controllers appears to hang the `keyboard' when the aux
924 	 * port doesn't exist and `PSMC_RESET_DEV' is issued.
925 	 */
926 	if (!reset_aux_dev(sc->kbdc)) {
927             recover_from_error(sc->kbdc);
928             restore_controller(sc->kbdc, command_byte);
929             if (verbose)
930         	printf("psm%d: failed to reset the aux device.\n", unit);
931             endprobe(ENXIO);
932 	}
933     }
934 
935     /*
936      * both the aux port and the aux device is functioning, see if the
937      * device can be enabled. NOTE: when enabled, the device will start
938      * sending data; we shall immediately disable the device once we know
939      * the device can be enabled.
940      */
941     if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
942         /* MOUSE ERROR */
943 	recover_from_error(sc->kbdc);
944 	restore_controller(sc->kbdc, command_byte);
945 	if (verbose)
946 	    printf("psm%d: failed to enable the aux device.\n", unit);
947         endprobe(ENXIO);
948     }
949 
950     /* save the default values after reset */
951     if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
952 	sc->dflt_mode.rate = sc->mode.rate = stat[2];
953 	sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
954     } else {
955 	sc->dflt_mode.rate = sc->mode.rate = -1;
956 	sc->dflt_mode.resolution = sc->mode.resolution = -1;
957     }
958 
959     /* hardware information */
960     sc->hw.iftype = MOUSE_IF_PS2;
961 
962     /* verify the device is a mouse */
963     sc->hw.hwid = get_aux_id(sc->kbdc);
964     if (!is_a_mouse(sc->hw.hwid)) {
965         restore_controller(sc->kbdc, command_byte);
966         if (verbose)
967             printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid);
968         endprobe(ENXIO);
969     }
970     switch (sc->hw.hwid) {
971     case PSM_BALLPOINT_ID:
972         sc->hw.type = MOUSE_TRACKBALL;
973         break;
974     case PSM_MOUSE_ID:
975     case PSM_INTELLI_ID:
976     case PSM_EXPLORER_ID:
977     case PSM_4DMOUSE_ID:
978     case PSM_4DPLUS_ID:
979         sc->hw.type = MOUSE_MOUSE;
980         break;
981     default:
982         sc->hw.type = MOUSE_UNKNOWN;
983         break;
984     }
985 
986     if (sc->config & PSM_CONFIG_NOIDPROBE) {
987 	sc->hw.buttons = 2;
988 	i = GENERIC_MOUSE_ENTRY;
989     } else {
990 	/* # of buttons */
991 	sc->hw.buttons = get_mouse_buttons(sc->kbdc);
992 
993 	/* other parameters */
994 	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
995 	    if ((*vendortype[i].probefunc)(sc)) {
996 		if (verbose >= 2)
997 		    printf("psm%d: found %s\n",
998 			   unit, model_name(vendortype[i].model));
999 		break;
1000 	    }
1001 	}
1002     }
1003 
1004     sc->hw.model = vendortype[i].model;
1005 
1006     sc->dflt_mode.level = PSM_LEVEL_BASE;
1007     sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1008     sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1009     if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1010         sc->dflt_mode.syncmask[0] = 0;
1011     else
1012         sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1013     if (sc->config & PSM_CONFIG_FORCETAP)
1014         sc->mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1015     sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
1016     sc->mode = sc->dflt_mode;
1017     sc->mode.packetsize = vendortype[i].packetsize;
1018 
1019     /* set mouse parameters */
1020 #if 0
1021     /*
1022      * A version of Logitech FirstMouse+ won't report wheel movement,
1023      * if SET_DEFAULTS is sent...  Don't use this command.
1024      * This fix was found by Takashi Nishida.
1025      */
1026     i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1027     if (verbose >= 2)
1028 	printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1029 #endif
1030     if (sc->config & PSM_CONFIG_RESOLUTION) {
1031         sc->mode.resolution
1032 	    = set_mouse_resolution(sc->kbdc,
1033 				   (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1034     } else if (sc->mode.resolution >= 0) {
1035 	sc->mode.resolution
1036 	    = set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1037     }
1038     if (sc->mode.rate > 0) {
1039 	sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1040     }
1041     set_mouse_scaling(sc->kbdc, 1);
1042 
1043     /* request a data packet and extract sync. bits */
1044     if (get_mouse_status(sc->kbdc, stat, 1, 3) < 3) {
1045         printf("psm%d: failed to get data.\n", unit);
1046         sc->mode.syncmask[0] = 0;
1047     } else {
1048         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
1049 	/* the NetScroll Mouse will send three more bytes... Ignore them */
1050 	empty_aux_buffer(sc->kbdc, 5);
1051     }
1052 
1053     /* just check the status of the mouse */
1054     /*
1055      * NOTE: XXX there are some arcane controller/mouse combinations out
1056      * there, which hung the controller unless there is data transmission
1057      * after ACK from the mouse.
1058      */
1059     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) {
1060         printf("psm%d: failed to get status.\n", unit);
1061     } else {
1062 	/*
1063 	 * When in its native mode, some mice operate with different
1064 	 * default parameters than in the PS/2 compatible mode.
1065 	 */
1066         sc->dflt_mode.rate = sc->mode.rate = stat[2];
1067         sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1068      }
1069 
1070     /* disable the aux port for now... */
1071     if (!set_controller_command_byte(sc->kbdc,
1072 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1073             (command_byte & KBD_KBD_CONTROL_BITS)
1074                 | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1075         /*
1076 	 * this is CONTROLLER ERROR; I don't know the proper way to
1077          * recover from this error...
1078 	 */
1079         restore_controller(sc->kbdc, command_byte);
1080         printf("psm%d: unable to set the command byte.\n", unit);
1081         endprobe(ENXIO);
1082     }
1083 
1084     /* see if IRQ is available */
1085     rid = 0;
1086     sc->intr = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, irq, irq, 1,
1087 				  RF_ACTIVE);
1088     if (sc->intr == NULL) {
1089         printf("psm%d: unable to allocate the IRQ resource (%d).\n",
1090 	       unit, (int)irq);
1091         endprobe(ENXIO);
1092     } else {
1093 	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1094     }
1095 
1096     /* done */
1097     kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1098     kbdc_lock(sc->kbdc, FALSE);
1099     return (0);
1100 }
1101 
1102 static int
1103 psmattach(device_t dev)
1104 {
1105     int unit = device_get_unit(dev);
1106     struct psm_softc *sc = device_get_softc(dev);
1107     uintptr_t irq;
1108     int error;
1109     int rid;
1110 
1111     if (sc == NULL)    /* shouldn't happen */
1112 	return (ENXIO);
1113 
1114     /* Setup initial state */
1115     sc->state = PSM_VALID;
1116     callout_handle_init(&sc->callout);
1117 
1118     /* Setup our interrupt handler */
1119     rid = 0;
1120     BUS_READ_IVAR(device_get_parent(dev), dev, KBDC_IVAR_IRQ, &irq);
1121     sc->intr = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, irq, irq, 1,
1122 				  RF_ACTIVE);
1123     if (sc->intr == NULL)
1124 	return (ENXIO);
1125     error = BUS_SETUP_INTR(device_get_parent(dev), dev, sc->intr,
1126 			   INTR_TYPE_TTY, psmintr, sc, &sc->ih);
1127     if (error) {
1128 	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1129 	return (error);
1130     }
1131 
1132     /* Done */
1133     sc->dev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, FALSE), 0, 0, 0666,
1134 		       "psm%d", unit);
1135     sc->bdev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, TRUE), 0, 0, 0666,
1136 			"bpsm%d", unit);
1137 
1138     if (!verbose) {
1139         printf("psm%d: model %s, device ID %d\n",
1140 	    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1141     } else {
1142         printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1143 	    unit, model_name(sc->hw.model),
1144 	    sc->hw.hwid & 0x00ff, sc->hw.hwid >> 8, sc->hw.buttons);
1145 	printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1146 	    unit, sc->config, sc->flags, sc->mode.packetsize);
1147 	printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1148 	    unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1149     }
1150 
1151     if (bootverbose)
1152         --verbose;
1153 
1154     return (0);
1155 }
1156 
1157 static int
1158 psmdetach(device_t dev)
1159 {
1160     struct psm_softc *sc;
1161     int rid;
1162 
1163     sc = device_get_softc(dev);
1164     if (sc->state & PSM_OPEN)
1165 	return EBUSY;
1166 
1167     rid = 0;
1168     BUS_TEARDOWN_INTR(device_get_parent(dev), dev, sc->intr, sc->ih);
1169     bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1170 
1171     destroy_dev(sc->dev);
1172     destroy_dev(sc->bdev);
1173 
1174     return 0;
1175 }
1176 
1177 static int
1178 psmopen(dev_t dev, int flag, int fmt, struct proc *p)
1179 {
1180     int unit = PSM_UNIT(dev);
1181     struct psm_softc *sc;
1182     int command_byte;
1183     int err;
1184     int s;
1185 
1186     /* Get device data */
1187     sc = PSM_SOFTC(unit);
1188     if ((sc == NULL) || (sc->state & PSM_VALID) == 0)
1189 	/* the device is no longer valid/functioning */
1190         return (ENXIO);
1191 
1192     /* Disallow multiple opens */
1193     if (sc->state & PSM_OPEN)
1194         return (EBUSY);
1195 
1196     device_busy(devclass_get_device(psm_devclass, unit));
1197 
1198     /* Initialize state */
1199     sc->rsel.si_flags = 0;
1200     sc->rsel.si_pid = 0;
1201     sc->mode.level = sc->dflt_mode.level;
1202     sc->mode.protocol = sc->dflt_mode.protocol;
1203     sc->watchdog = FALSE;
1204 
1205     /* flush the event queue */
1206     sc->queue.count = 0;
1207     sc->queue.head = 0;
1208     sc->queue.tail = 0;
1209     sc->status.flags = 0;
1210     sc->status.button = 0;
1211     sc->status.obutton = 0;
1212     sc->status.dx = 0;
1213     sc->status.dy = 0;
1214     sc->status.dz = 0;
1215     sc->button = 0;
1216 
1217     /* empty input buffer */
1218     bzero(sc->ipacket, sizeof(sc->ipacket));
1219     sc->inputbytes = 0;
1220 
1221     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1222     if (!kbdc_lock(sc->kbdc, TRUE))
1223 	return (EIO);
1224 
1225     /* save the current controller command byte */
1226     s = spltty();
1227     command_byte = get_controller_command_byte(sc->kbdc);
1228 
1229     /* enable the aux port and temporalily disable the keyboard */
1230     if ((command_byte == -1)
1231         || !set_controller_command_byte(sc->kbdc,
1232 	    kbdc_get_device_mask(sc->kbdc),
1233   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1234 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1235         /* CONTROLLER ERROR; do you know how to get out of this? */
1236         kbdc_lock(sc->kbdc, FALSE);
1237 	splx(s);
1238 	log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n",
1239 	    unit);
1240 	return (EIO);
1241     }
1242     /*
1243      * Now that the keyboard controller is told not to generate
1244      * the keyboard and mouse interrupts, call `splx()' to allow
1245      * the other tty interrupts. The clock interrupt may also occur,
1246      * but timeout routines will be blocked by the poll flag set
1247      * via `kbdc_lock()'
1248      */
1249     splx(s);
1250 
1251     /* enable the mouse device */
1252     err = doopen(unit, command_byte);
1253 
1254     /* done */
1255     if (err == 0)
1256         sc->state |= PSM_OPEN;
1257     kbdc_lock(sc->kbdc, FALSE);
1258     return (err);
1259 }
1260 
1261 static int
1262 psmclose(dev_t dev, int flag, int fmt, struct proc *p)
1263 {
1264     int unit = PSM_UNIT(dev);
1265     struct psm_softc *sc = PSM_SOFTC(unit);
1266     int stat[3];
1267     int command_byte;
1268     int s;
1269 
1270     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1271     if (!kbdc_lock(sc->kbdc, TRUE))
1272 	return (EIO);
1273 
1274     /* save the current controller command byte */
1275     s = spltty();
1276     command_byte = get_controller_command_byte(sc->kbdc);
1277     if (command_byte == -1) {
1278         kbdc_lock(sc->kbdc, FALSE);
1279 	splx(s);
1280 	return (EIO);
1281     }
1282 
1283     /* disable the aux interrupt and temporalily disable the keyboard */
1284     if (!set_controller_command_byte(sc->kbdc,
1285 	    kbdc_get_device_mask(sc->kbdc),
1286   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1287 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1288 	log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n",
1289 	    unit);
1290 	/* CONTROLLER ERROR;
1291 	 * NOTE: we shall force our way through. Because the only
1292 	 * ill effect we shall see is that we may not be able
1293 	 * to read ACK from the mouse, and it doesn't matter much
1294 	 * so long as the mouse will accept the DISABLE command.
1295 	 */
1296     }
1297     splx(s);
1298 
1299     /* stop the watchdog timer */
1300     untimeout(psmtimeout, (void *)(uintptr_t)unit, sc->callout);
1301     callout_handle_init(&sc->callout);
1302 
1303     /* remove anything left in the output buffer */
1304     empty_aux_buffer(sc->kbdc, 10);
1305 
1306     /* disable the aux device, port and interrupt */
1307     if (sc->state & PSM_VALID) {
1308         if (!disable_aux_dev(sc->kbdc)) {
1309 	    /* MOUSE ERROR;
1310 	     * NOTE: we don't return error and continue, pretending
1311 	     * we have successfully disabled the device. It's OK because
1312 	     * the interrupt routine will discard any data from the mouse
1313 	     * hereafter.
1314 	     */
1315 	    log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n",
1316 		unit);
1317         }
1318 
1319         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1320             log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n",
1321 		unit);
1322     }
1323 
1324     if (!set_controller_command_byte(sc->kbdc,
1325 	    kbdc_get_device_mask(sc->kbdc),
1326 	    (command_byte & KBD_KBD_CONTROL_BITS)
1327 	        | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1328 	/* CONTROLLER ERROR;
1329 	 * we shall ignore this error; see the above comment.
1330 	 */
1331 	log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n",
1332 	    unit);
1333     }
1334 
1335     /* remove anything left in the output buffer */
1336     empty_aux_buffer(sc->kbdc, 10);
1337 
1338     /* close is almost always successful */
1339     sc->state &= ~PSM_OPEN;
1340     kbdc_lock(sc->kbdc, FALSE);
1341     device_unbusy(devclass_get_device(psm_devclass, unit));
1342     return (0);
1343 }
1344 
1345 static int
1346 tame_mouse(struct psm_softc *sc, mousestatus_t *status, unsigned char *buf)
1347 {
1348     static unsigned char butmapps2[8] = {
1349         0,
1350         MOUSE_PS2_BUTTON1DOWN,
1351         MOUSE_PS2_BUTTON2DOWN,
1352         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1353         MOUSE_PS2_BUTTON3DOWN,
1354         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1355         MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1356         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1357     };
1358     static unsigned char butmapmsc[8] = {
1359         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1360         MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1361         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1362         MOUSE_MSC_BUTTON3UP,
1363         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1364         MOUSE_MSC_BUTTON2UP,
1365         MOUSE_MSC_BUTTON1UP,
1366         0,
1367     };
1368     int mapped;
1369     int i;
1370 
1371     if (sc->mode.level == PSM_LEVEL_BASE) {
1372         mapped = status->button & ~MOUSE_BUTTON4DOWN;
1373         if (status->button & MOUSE_BUTTON4DOWN)
1374 	    mapped |= MOUSE_BUTTON1DOWN;
1375         status->button = mapped;
1376         buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1377         i = max(min(status->dx, 255), -256);
1378 	if (i < 0)
1379 	    buf[0] |= MOUSE_PS2_XNEG;
1380         buf[1] = i;
1381         i = max(min(status->dy, 255), -256);
1382 	if (i < 0)
1383 	    buf[0] |= MOUSE_PS2_YNEG;
1384         buf[2] = i;
1385 	return MOUSE_PS2_PACKETSIZE;
1386     } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1387         buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS];
1388         i = max(min(status->dx, 255), -256);
1389         buf[1] = i >> 1;
1390         buf[3] = i - buf[1];
1391         i = max(min(status->dy, 255), -256);
1392         buf[2] = i >> 1;
1393         buf[4] = i - buf[2];
1394         i = max(min(status->dz, 127), -128);
1395         buf[5] = (i >> 1) & 0x7f;
1396         buf[6] = (i - (i >> 1)) & 0x7f;
1397         buf[7] = (~status->button >> 3) & 0x7f;
1398 	return MOUSE_SYS_PACKETSIZE;
1399     }
1400     return sc->inputbytes;;
1401 }
1402 
1403 static int
1404 psmread(dev_t dev, struct uio *uio, int flag)
1405 {
1406     register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1407     unsigned char buf[PSM_SMALLBUFSIZE];
1408     int error = 0;
1409     int s;
1410     int l;
1411 
1412     if ((sc->state & PSM_VALID) == 0)
1413 	return EIO;
1414 
1415     /* block until mouse activity occured */
1416     s = spltty();
1417     while (sc->queue.count <= 0) {
1418         if (PSM_NBLOCKIO(dev)) {
1419             splx(s);
1420             return EWOULDBLOCK;
1421         }
1422         sc->state |= PSM_ASLP;
1423         error = tsleep((caddr_t) sc, PZERO | PCATCH, "psmrea", 0);
1424         sc->state &= ~PSM_ASLP;
1425         if (error) {
1426             splx(s);
1427             return error;
1428         } else if ((sc->state & PSM_VALID) == 0) {
1429             /* the device disappeared! */
1430             splx(s);
1431             return EIO;
1432 	}
1433     }
1434     splx(s);
1435 
1436     /* copy data to the user land */
1437     while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1438         s = spltty();
1439 	l = min(sc->queue.count, uio->uio_resid);
1440 	if (l > sizeof(buf))
1441 	    l = sizeof(buf);
1442 	if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1443 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1444 		sizeof(sc->queue.buf) - sc->queue.head);
1445 	    bcopy(&sc->queue.buf[0],
1446 		&buf[sizeof(sc->queue.buf) - sc->queue.head],
1447 		l - (sizeof(sc->queue.buf) - sc->queue.head));
1448 	} else {
1449 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1450 	}
1451 	sc->queue.count -= l;
1452 	sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1453         splx(s);
1454         error = uiomove(buf, l, uio);
1455         if (error)
1456 	    break;
1457     }
1458 
1459     return error;
1460 }
1461 
1462 static int
1463 block_mouse_data(struct psm_softc *sc, int *c)
1464 {
1465     int s;
1466 
1467     if (!kbdc_lock(sc->kbdc, TRUE))
1468 	return EIO;
1469 
1470     s = spltty();
1471     *c = get_controller_command_byte(sc->kbdc);
1472     if ((*c == -1)
1473 	|| !set_controller_command_byte(sc->kbdc,
1474 	    kbdc_get_device_mask(sc->kbdc),
1475             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1476                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1477         /* this is CONTROLLER ERROR */
1478 	splx(s);
1479         kbdc_lock(sc->kbdc, FALSE);
1480 	return EIO;
1481     }
1482 
1483     /*
1484      * The device may be in the middle of status data transmission.
1485      * The transmission will be interrupted, thus, incomplete status
1486      * data must be discarded. Although the aux interrupt is disabled
1487      * at the keyboard controller level, at most one aux interrupt
1488      * may have already been pending and a data byte is in the
1489      * output buffer; throw it away. Note that the second argument
1490      * to `empty_aux_buffer()' is zero, so that the call will just
1491      * flush the internal queue.
1492      * `psmintr()' will be invoked after `splx()' if an interrupt is
1493      * pending; it will see no data and returns immediately.
1494      */
1495     empty_aux_buffer(sc->kbdc, 0);	/* flush the queue */
1496     read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
1497     sc->inputbytes = 0;
1498     splx(s);
1499 
1500     return 0;
1501 }
1502 
1503 static int
1504 unblock_mouse_data(struct psm_softc *sc, int c)
1505 {
1506     int error = 0;
1507 
1508     /*
1509      * We may have seen a part of status data during `set_mouse_XXX()'.
1510      * they have been queued; flush it.
1511      */
1512     empty_aux_buffer(sc->kbdc, 0);
1513 
1514     /* restore ports and interrupt */
1515     if (!set_controller_command_byte(sc->kbdc,
1516             kbdc_get_device_mask(sc->kbdc),
1517 	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1518         /* CONTROLLER ERROR; this is serious, we may have
1519          * been left with the inaccessible keyboard and
1520          * the disabled mouse interrupt.
1521          */
1522         error = EIO;
1523     }
1524 
1525     kbdc_lock(sc->kbdc, FALSE);
1526     return error;
1527 }
1528 
1529 static int
1530 psmioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1531 {
1532     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1533     mousemode_t mode;
1534     mousestatus_t status;
1535 #if (defined(MOUSE_GETVARS))
1536     mousevar_t *var;
1537 #endif
1538     mousedata_t *data;
1539     int stat[3];
1540     int command_byte;
1541     int error = 0;
1542     int s;
1543 
1544     /* Perform IOCTL command */
1545     switch (cmd) {
1546 
1547     case OLD_MOUSE_GETHWINFO:
1548 	s = spltty();
1549         ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1550         ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1551         ((old_mousehw_t *)addr)->type = sc->hw.type;
1552         ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
1553 	splx(s);
1554         break;
1555 
1556     case MOUSE_GETHWINFO:
1557 	s = spltty();
1558         *(mousehw_t *)addr = sc->hw;
1559 	if (sc->mode.level == PSM_LEVEL_BASE)
1560 	    ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1561 	splx(s);
1562         break;
1563 
1564     case OLD_MOUSE_GETMODE:
1565 	s = spltty();
1566 	switch (sc->mode.level) {
1567 	case PSM_LEVEL_BASE:
1568 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1569 	    break;
1570 	case PSM_LEVEL_STANDARD:
1571 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1572 	    break;
1573 	case PSM_LEVEL_NATIVE:
1574 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1575 	    break;
1576 	}
1577         ((old_mousemode_t *)addr)->rate = sc->mode.rate;
1578         ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1579         ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1580 	splx(s);
1581         break;
1582 
1583     case MOUSE_GETMODE:
1584 	s = spltty();
1585         *(mousemode_t *)addr = sc->mode;
1586         ((mousemode_t *)addr)->resolution =
1587 	    MOUSE_RES_LOW - sc->mode.resolution;
1588 	switch (sc->mode.level) {
1589 	case PSM_LEVEL_BASE:
1590 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1591 	    ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE;
1592 	    break;
1593 	case PSM_LEVEL_STANDARD:
1594 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1595 	    ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE;
1596 	    ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1597 	    ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
1598 	    break;
1599 	case PSM_LEVEL_NATIVE:
1600 	    /* FIXME: this isn't quite correct... XXX */
1601 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1602 	    break;
1603 	}
1604 	splx(s);
1605         break;
1606 
1607     case OLD_MOUSE_SETMODE:
1608     case MOUSE_SETMODE:
1609 	if (cmd == OLD_MOUSE_SETMODE) {
1610 	    mode.rate = ((old_mousemode_t *)addr)->rate;
1611 	    /*
1612 	     * resolution  old I/F   new I/F
1613 	     * default        0         0
1614 	     * low            1        -2
1615 	     * medium low     2        -3
1616 	     * medium high    3        -4
1617 	     * high           4        -5
1618 	     */
1619 	    if (((old_mousemode_t *)addr)->resolution > 0)
1620 	        mode.resolution = -((old_mousemode_t *)addr)->resolution - 1;
1621 	    mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor;
1622 	    mode.level = -1;
1623 	} else {
1624 	    mode = *(mousemode_t *)addr;
1625 	}
1626 
1627 	/* adjust and validate parameters. */
1628 	if (mode.rate > UCHAR_MAX)
1629 	    return EINVAL;
1630         if (mode.rate == 0)
1631             mode.rate = sc->dflt_mode.rate;
1632 	else if (mode.rate == -1)
1633 	    /* don't change the current setting */
1634 	    ;
1635 	else if (mode.rate < 0)
1636 	    return EINVAL;
1637 	if (mode.resolution >= UCHAR_MAX)
1638 	    return EINVAL;
1639 	if (mode.resolution >= 200)
1640 	    mode.resolution = MOUSE_RES_HIGH;
1641 	else if (mode.resolution >= 100)
1642 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1643 	else if (mode.resolution >= 50)
1644 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1645 	else if (mode.resolution > 0)
1646 	    mode.resolution = MOUSE_RES_LOW;
1647         if (mode.resolution == MOUSE_RES_DEFAULT)
1648             mode.resolution = sc->dflt_mode.resolution;
1649         else if (mode.resolution == -1)
1650 	    /* don't change the current setting */
1651 	    ;
1652         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1653             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1654 	if (mode.level == -1)
1655 	    /* don't change the current setting */
1656 	    mode.level = sc->mode.level;
1657 	else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX))
1658 	    return EINVAL;
1659         if (mode.accelfactor == -1)
1660 	    /* don't change the current setting */
1661 	    mode.accelfactor = sc->mode.accelfactor;
1662         else if (mode.accelfactor < 0)
1663 	    return EINVAL;
1664 
1665 	/* don't allow anybody to poll the keyboard controller */
1666 	error = block_mouse_data(sc, &command_byte);
1667 	if (error)
1668             return error;
1669 
1670         /* set mouse parameters */
1671 	if (mode.rate > 0)
1672 	    mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1673 	if (mode.resolution >= 0)
1674 	    mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1675 	set_mouse_scaling(sc->kbdc, 1);
1676 	get_mouse_status(sc->kbdc, stat, 0, 3);
1677 
1678         s = spltty();
1679     	sc->mode.rate = mode.rate;
1680     	sc->mode.resolution = mode.resolution;
1681     	sc->mode.accelfactor = mode.accelfactor;
1682     	sc->mode.level = mode.level;
1683         splx(s);
1684 
1685 	unblock_mouse_data(sc, command_byte);
1686         break;
1687 
1688     case MOUSE_GETLEVEL:
1689 	*(int *)addr = sc->mode.level;
1690         break;
1691 
1692     case MOUSE_SETLEVEL:
1693 	if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX))
1694 	    return EINVAL;
1695 	sc->mode.level = *(int *)addr;
1696         break;
1697 
1698     case MOUSE_GETSTATUS:
1699         s = spltty();
1700 	status = sc->status;
1701 	sc->status.flags = 0;
1702 	sc->status.obutton = sc->status.button;
1703 	sc->status.button = 0;
1704 	sc->status.dx = 0;
1705 	sc->status.dy = 0;
1706 	sc->status.dz = 0;
1707         splx(s);
1708         *(mousestatus_t *)addr = status;
1709         break;
1710 
1711 #if (defined(MOUSE_GETVARS))
1712     case MOUSE_GETVARS:
1713 	var = (mousevar_t *)addr;
1714 	bzero(var, sizeof(*var));
1715 	s = spltty();
1716         var->var[0] = MOUSE_VARS_PS2_SIG;
1717         var->var[1] = sc->config;
1718         var->var[2] = sc->flags;
1719 	splx(s);
1720         break;
1721 
1722     case MOUSE_SETVARS:
1723 	return ENODEV;
1724 #endif /* MOUSE_GETVARS */
1725 
1726     case MOUSE_READSTATE:
1727     case MOUSE_READDATA:
1728 	data = (mousedata_t *)addr;
1729 	if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
1730 	    return EINVAL;
1731 
1732 	error = block_mouse_data(sc, &command_byte);
1733 	if (error)
1734             return error;
1735         if ((data->len = get_mouse_status(sc->kbdc, data->buf,
1736 		(cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
1737             error = EIO;
1738 	unblock_mouse_data(sc, command_byte);
1739 	break;
1740 
1741 #if (defined(MOUSE_SETRESOLUTION))
1742     case MOUSE_SETRESOLUTION:
1743 	mode.resolution = *(int *)addr;
1744 	if (mode.resolution >= UCHAR_MAX)
1745 	    return EINVAL;
1746 	else if (mode.resolution >= 200)
1747 	    mode.resolution = MOUSE_RES_HIGH;
1748 	else if (mode.resolution >= 100)
1749 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1750 	else if (mode.resolution >= 50)
1751 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1752 	else if (mode.resolution > 0)
1753 	    mode.resolution = MOUSE_RES_LOW;
1754         if (mode.resolution == MOUSE_RES_DEFAULT)
1755             mode.resolution = sc->dflt_mode.resolution;
1756         else if (mode.resolution == -1)
1757 	    mode.resolution = sc->mode.resolution;
1758         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1759             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1760 
1761 	error = block_mouse_data(sc, &command_byte);
1762 	if (error)
1763             return error;
1764         sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1765 	if (sc->mode.resolution != mode.resolution)
1766 	    error = EIO;
1767 	unblock_mouse_data(sc, command_byte);
1768         break;
1769 #endif /* MOUSE_SETRESOLUTION */
1770 
1771 #if (defined(MOUSE_SETRATE))
1772     case MOUSE_SETRATE:
1773 	mode.rate = *(int *)addr;
1774 	if (mode.rate > UCHAR_MAX)
1775 	    return EINVAL;
1776         if (mode.rate == 0)
1777             mode.rate = sc->dflt_mode.rate;
1778 	else if (mode.rate < 0)
1779 	    mode.rate = sc->mode.rate;
1780 
1781 	error = block_mouse_data(sc, &command_byte);
1782 	if (error)
1783             return error;
1784         sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1785 	if (sc->mode.rate != mode.rate)
1786 	    error = EIO;
1787 	unblock_mouse_data(sc, command_byte);
1788         break;
1789 #endif /* MOUSE_SETRATE */
1790 
1791 #if (defined(MOUSE_SETSCALING))
1792     case MOUSE_SETSCALING:
1793 	if ((*(int *)addr <= 0) || (*(int *)addr > 2))
1794 	    return EINVAL;
1795 
1796 	error = block_mouse_data(sc, &command_byte);
1797 	if (error)
1798             return error;
1799         if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
1800 	    error = EIO;
1801 	unblock_mouse_data(sc, command_byte);
1802         break;
1803 #endif /* MOUSE_SETSCALING */
1804 
1805 #if (defined(MOUSE_GETHWID))
1806     case MOUSE_GETHWID:
1807 	error = block_mouse_data(sc, &command_byte);
1808 	if (error)
1809             return error;
1810         sc->hw.hwid &= ~0x00ff;
1811         sc->hw.hwid |= get_aux_id(sc->kbdc);
1812 	*(int *)addr = sc->hw.hwid & 0x00ff;
1813 	unblock_mouse_data(sc, command_byte);
1814         break;
1815 #endif /* MOUSE_GETHWID */
1816 
1817     default:
1818 	return ENOTTY;
1819     }
1820 
1821     return error;
1822 }
1823 
1824 static void
1825 psmtimeout(void *arg)
1826 {
1827     struct psm_softc *sc;
1828     int unit;
1829     int s;
1830 
1831     unit = (int)(uintptr_t)arg;
1832     sc = devclass_get_softc(psm_devclass, unit);
1833     s = spltty();
1834     if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
1835 	if (verbose >= 4)
1836 	    log(LOG_DEBUG, "psm%d: lost interrupt?\n", unit);
1837 	psmintr(sc);
1838 	kbdc_lock(sc->kbdc, FALSE);
1839     }
1840     sc->watchdog = TRUE;
1841     splx(s);
1842     sc->callout = timeout(psmtimeout, (void *)(uintptr_t)unit, hz);
1843 }
1844 
1845 static void
1846 psmintr(void *arg)
1847 {
1848     /*
1849      * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
1850      * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
1851      */
1852     static int butmap[8] = {
1853         0,
1854 	MOUSE_BUTTON1DOWN,
1855 	MOUSE_BUTTON3DOWN,
1856 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1857 	MOUSE_BUTTON2DOWN,
1858 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1859 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1860         MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1861     };
1862     static int butmap_versapad[8] = {
1863 	0,
1864 	MOUSE_BUTTON3DOWN,
1865 	0,
1866 	MOUSE_BUTTON3DOWN,
1867 	MOUSE_BUTTON1DOWN,
1868 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1869 	MOUSE_BUTTON1DOWN,
1870 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
1871     };
1872     register struct psm_softc *sc = arg;
1873     mousestatus_t ms;
1874     int x, y, z;
1875     int c;
1876     int l;
1877     int x0, y0;
1878 
1879     /* read until there is nothing to read */
1880     while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
1881 
1882         /* discard the byte if the device is not open */
1883         if ((sc->state & PSM_OPEN) == 0)
1884             continue;
1885 
1886         sc->ipacket[sc->inputbytes++] = c;
1887         if (sc->inputbytes < sc->mode.packetsize)
1888 	    continue;
1889 
1890 #if 0
1891         log(LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
1892 	    sc->ipacket[0], sc->ipacket[1], sc->ipacket[2],
1893 	    sc->ipacket[3], sc->ipacket[4], sc->ipacket[5]);
1894 #endif
1895 
1896 	c = sc->ipacket[0];
1897 
1898 	if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
1899             log(LOG_DEBUG, "psmintr: out of sync (%04x != %04x).\n",
1900 		c & sc->mode.syncmask[0], sc->mode.syncmask[1]);
1901 	    sc->inputbytes = 0;
1902             continue;
1903 	}
1904 
1905 	/*
1906 	 * A kludge for Kensington device!
1907 	 * The MSB of the horizontal count appears to be stored in
1908 	 * a strange place.
1909 	 */
1910 	if (sc->hw.model == MOUSE_MODEL_THINK)
1911 	    sc->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
1912 
1913         /* ignore the overflow bits... */
1914         x = (c & MOUSE_PS2_XNEG) ?  sc->ipacket[1] - 256 : sc->ipacket[1];
1915         y = (c & MOUSE_PS2_YNEG) ?  sc->ipacket[2] - 256 : sc->ipacket[2];
1916 	z = 0;
1917         ms.obutton = sc->button;		  /* previous button state */
1918         ms.button = butmap[c & MOUSE_PS2_BUTTONS];
1919 	/* `tapping' action */
1920 	if (sc->config & PSM_CONFIG_FORCETAP)
1921 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
1922 
1923 	switch (sc->hw.model) {
1924 
1925 	case MOUSE_MODEL_EXPLORER:
1926 	    /*
1927 	     *          b7 b6 b5 b4 b3 b2 b1 b0
1928 	     * byte 1:  oy ox sy sx 1  M  R  L
1929 	     * byte 2:  x  x  x  x  x  x  x  x
1930 	     * byte 3:  y  y  y  y  y  y  y  y
1931 	     * byte 4:  *  *  S2 S1 s  d2 d1 d0
1932 	     *
1933 	     * L, M, R, S1, S2: left, middle, right and side buttons
1934 	     * s: wheel data sign bit
1935 	     * d2-d0: wheel data
1936 	     */
1937 	    z = (sc->ipacket[3] & MOUSE_EXPLORER_ZNEG)
1938 		? (sc->ipacket[3] & 0x0f) - 16 : (sc->ipacket[3] & 0x0f);
1939 	    ms.button |= (sc->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN)
1940 		? MOUSE_BUTTON4DOWN : 0;
1941 	    ms.button |= (sc->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN)
1942 		? MOUSE_BUTTON5DOWN : 0;
1943 	    break;
1944 
1945 	case MOUSE_MODEL_INTELLI:
1946 	case MOUSE_MODEL_NET:
1947 	    /* wheel data is in the fourth byte */
1948 	    z = (char)sc->ipacket[3];
1949 	    /* some mice may send 7 when there is no Z movement?! XXX */
1950 	    if ((z >= 7) || (z <= -7))
1951 		z = 0;
1952 	    /* some compatible mice have additional buttons */
1953 	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN)
1954 		? MOUSE_BUTTON4DOWN : 0;
1955 	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN)
1956 		? MOUSE_BUTTON5DOWN : 0;
1957 	    break;
1958 
1959 	case MOUSE_MODEL_MOUSEMANPLUS:
1960 	    /*
1961 	     * PS2++ protocl packet
1962 	     *
1963 	     *          b7 b6 b5 b4 b3 b2 b1 b0
1964 	     * byte 1:  *  1  p3 p2 1  *  *  *
1965 	     * byte 2:  c1 c2 p1 p0 d1 d0 1  0
1966 	     *
1967 	     * p3-p0: packet type
1968 	     * c1, c2: c1 & c2 == 1, if p2 == 0
1969 	     *         c1 & c2 == 0, if p2 == 1
1970 	     *
1971 	     * packet type: 0 (device type)
1972 	     * See comments in enable_mmanplus() below.
1973 	     *
1974 	     * packet type: 1 (wheel data)
1975 	     *
1976 	     *          b7 b6 b5 b4 b3 b2 b1 b0
1977 	     * byte 3:  h  *  B5 B4 s  d2 d1 d0
1978 	     *
1979 	     * h: 1, if horizontal roller data
1980 	     *    0, if vertical roller data
1981 	     * B4, B5: button 4 and 5
1982 	     * s: sign bit
1983 	     * d2-d0: roller data
1984 	     *
1985 	     * packet type: 2 (reserved)
1986 	     */
1987 	    if (((c & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
1988 		    && (abs(x) > 191)
1989 		    && MOUSE_PS2PLUS_CHECKBITS(sc->ipacket)) {
1990 		/* the extended data packet encodes button and wheel events */
1991 		switch (MOUSE_PS2PLUS_PACKET_TYPE(sc->ipacket)) {
1992 		case 1:
1993 		    /* wheel data packet */
1994 		    x = y = 0;
1995 		    if (sc->ipacket[2] & 0x80) {
1996 			/* horizontal roller count - ignore it XXX*/
1997 		    } else {
1998 			/* vertical roller count */
1999 			z = (sc->ipacket[2] & MOUSE_PS2PLUS_ZNEG)
2000 			    ? (sc->ipacket[2] & 0x0f) - 16
2001 			    : (sc->ipacket[2] & 0x0f);
2002 		    }
2003 		    ms.button |= (sc->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
2004 			? MOUSE_BUTTON4DOWN : 0;
2005 		    ms.button |= (sc->ipacket[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
2006 			? MOUSE_BUTTON5DOWN : 0;
2007 		    break;
2008 		case 2:
2009 		    /* this packet type is reserved by Logitech... */
2010 		    /*
2011 		     * IBM ScrollPoint Mouse uses this packet type to
2012 		     * encode both vertical and horizontal scroll movement.
2013 		     */
2014 		    x = y = 0;
2015 		    /* horizontal count */
2016 		    if (sc->ipacket[2] & 0x0f)
2017 			z = (sc->ipacket[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
2018 		    /* vertical count */
2019 		    if (sc->ipacket[2] & 0xf0)
2020 			z = (sc->ipacket[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
2021 #if 0
2022 		    /* vertical count */
2023 		    z = (sc->ipacket[2] & MOUSE_SPOINT_ZNEG)
2024 			? ((sc->ipacket[2] >> 4) & 0x0f) - 16
2025 			: ((sc->ipacket[2] >> 4) & 0x0f);
2026 		    /* horizontal count */
2027 		    w = (sc->ipacket[2] & MOUSE_SPOINT_WNEG)
2028 			? (sc->ipacket[2] & 0x0f) - 16
2029 			: (sc->ipacket[2] & 0x0f);
2030 #endif
2031 		    break;
2032 		case 0:
2033 		    /* device type packet - shouldn't happen */
2034 		    /* FALL THROUGH */
2035 		default:
2036 		    x = y = 0;
2037 		    ms.button = ms.obutton;
2038 		    if (bootverbose)
2039 			log(LOG_DEBUG, "psmintr: unknown PS2++ packet type %d: "
2040 				       "0x%02x 0x%02x 0x%02x\n",
2041 			    MOUSE_PS2PLUS_PACKET_TYPE(sc->ipacket),
2042 			    sc->ipacket[0], sc->ipacket[1], sc->ipacket[2]);
2043 		    break;
2044 		}
2045 	    } else {
2046 		/* preserve button states */
2047 		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2048 	    }
2049 	    break;
2050 
2051 	case MOUSE_MODEL_GLIDEPOINT:
2052 	    /* `tapping' action */
2053 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2054 	    break;
2055 
2056 	case MOUSE_MODEL_NETSCROLL:
2057 	    /* three addtional bytes encode buttons and wheel events */
2058 	    ms.button |= (sc->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
2059 		? MOUSE_BUTTON4DOWN : 0;
2060 	    ms.button |= (sc->ipacket[3] & MOUSE_PS2_BUTTON1DOWN)
2061 		? MOUSE_BUTTON5DOWN : 0;
2062 	    z = (sc->ipacket[3] & MOUSE_PS2_XNEG)
2063 		? sc->ipacket[4] - 256 : sc->ipacket[4];
2064 	    break;
2065 
2066 	case MOUSE_MODEL_THINK:
2067 	    /* the fourth button state in the first byte */
2068 	    ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
2069 	    break;
2070 
2071 	case MOUSE_MODEL_VERSAPAD:
2072 	    /* VersaPad PS/2 absolute mode message format
2073 	     *
2074 	     * [packet1]     7   6   5   4   3   2   1   0(LSB)
2075 	     *  ipacket[0]:  1   1   0   A   1   L   T   R
2076 	     *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
2077 	     *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
2078 	     *  ipacket[3]:  1   1   1   A   1   L   T   R
2079 	     *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
2080 	     *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
2081 	     *
2082 	     * [note]
2083 	     *  R: right physical mouse button (1=on)
2084 	     *  T: touch pad virtual button (1=tapping)
2085 	     *  L: left physical mouse button (1=on)
2086 	     *  A: position data is valid (1=valid)
2087 	     *  H: horizontal data (12bit signed integer. H11 is sign bit.)
2088 	     *  V: vertical data (12bit signed integer. V11 is sign bit.)
2089 	     *  P: pressure data
2090 	     *
2091 	     * Tapping is mapped to MOUSE_BUTTON4.
2092 	     */
2093 	    ms.button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
2094 	    ms.button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2095 	    x = y = 0;
2096 	    if (c & MOUSE_PS2VERSA_IN_USE) {
2097 		x0 = sc->ipacket[1] | (((sc->ipacket[4]) & 0x0f) << 8);
2098 		y0 = sc->ipacket[2] | (((sc->ipacket[4]) & 0xf0) << 4);
2099 		if (x0 & 0x800)
2100 		    x0 -= 0x1000;
2101 		if (y0 & 0x800)
2102 		    y0 -= 0x1000;
2103 		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2104 		    x = sc->xold - x0;
2105 		    y = y0 - sc->yold;
2106 		    if (x < 0)	/* XXX */
2107 			x++;
2108 		    else if (x)
2109 			x--;
2110 		    if (y < 0)
2111 			y++;
2112 		    else if (y)
2113 			y--;
2114 		} else {
2115 		    sc->flags |= PSM_FLAGS_FINGERDOWN;
2116 		}
2117 		sc->xold = x0;
2118 		sc->yold = y0;
2119 	    } else {
2120 		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2121 	    }
2122 	    c = ((x < 0) ? MOUSE_PS2_XNEG : 0)
2123 		| ((y < 0) ? MOUSE_PS2_YNEG : 0);
2124 	    break;
2125 
2126 	case MOUSE_MODEL_4D:
2127 	    /*
2128 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2129 	     * byte 1:  s2 d2 s1 d1 1  M  R  L
2130 	     * byte 2:  sx x  x  x  x  x  x  x
2131 	     * byte 3:  sy y  y  y  y  y  y  y
2132 	     *
2133 	     * s1: wheel 1 direction
2134 	     * d1: wheel 1 data
2135 	     * s2: wheel 2 direction
2136 	     * d2: wheel 2 data
2137 	     */
2138 	    x = (sc->ipacket[1] & 0x80) ? sc->ipacket[1] - 256 : sc->ipacket[1];
2139 	    y = (sc->ipacket[2] & 0x80) ? sc->ipacket[2] - 256 : sc->ipacket[2];
2140 	    switch (c & MOUSE_4D_WHEELBITS) {
2141 	    case 0x10:
2142 		z = 1;
2143 		break;
2144 	    case 0x30:
2145 		z = -1;
2146 		break;
2147 	    case 0x40:	/* 2nd wheel turning right XXX */
2148 		z = 2;
2149 		break;
2150 	    case 0xc0:	/* 2nd wheel turning left XXX */
2151 		z = -2;
2152 		break;
2153 	    }
2154 	    break;
2155 
2156 	case MOUSE_MODEL_4DPLUS:
2157 	    if ((x < 16 - 256) && (y < 16 - 256)) {
2158 		/*
2159 		 *          b7 b6 b5 b4 b3 b2 b1 b0
2160 		 * byte 1:  0  0  1  1  1  M  R  L
2161 		 * byte 2:  0  0  0  0  1  0  0  0
2162 		 * byte 3:  0  0  0  0  S  s  d1 d0
2163 		 *
2164 		 * L, M, R, S: left, middle, right and side buttons
2165 		 * s: wheel data sign bit
2166 		 * d1-d0: wheel data
2167 		 */
2168 		x = y = 0;
2169 		if (sc->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2170 		    ms.button |= MOUSE_BUTTON4DOWN;
2171 		z = (sc->ipacket[2] & MOUSE_4DPLUS_ZNEG)
2172 			? ((sc->ipacket[2] & 0x07) - 8)
2173 			: (sc->ipacket[2] & 0x07) ;
2174 	    } else {
2175 		/* preserve previous button states */
2176 		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2177 	    }
2178 	    break;
2179 
2180 	case MOUSE_MODEL_GENERIC:
2181 	default:
2182 	    break;
2183 	}
2184 
2185         /* scale values */
2186         if (sc->mode.accelfactor >= 1) {
2187             if (x != 0) {
2188                 x = x * x / sc->mode.accelfactor;
2189                 if (x == 0)
2190                     x = 1;
2191                 if (c & MOUSE_PS2_XNEG)
2192                     x = -x;
2193             }
2194             if (y != 0) {
2195                 y = y * y / sc->mode.accelfactor;
2196                 if (y == 0)
2197                     y = 1;
2198                 if (c & MOUSE_PS2_YNEG)
2199                     y = -y;
2200             }
2201         }
2202 
2203         ms.dx = x;
2204         ms.dy = y;
2205         ms.dz = z;
2206         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0)
2207 	    | (ms.obutton ^ ms.button);
2208 
2209 	if (sc->mode.level < PSM_LEVEL_NATIVE)
2210 	    sc->inputbytes = tame_mouse(sc, &ms, sc->ipacket);
2211 
2212         sc->status.flags |= ms.flags;
2213         sc->status.dx += ms.dx;
2214         sc->status.dy += ms.dy;
2215         sc->status.dz += ms.dz;
2216         sc->status.button = ms.button;
2217         sc->button = ms.button;
2218 
2219 	sc->watchdog = FALSE;
2220 
2221         /* queue data */
2222         if (sc->queue.count + sc->inputbytes < sizeof(sc->queue.buf)) {
2223 	    l = min(sc->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
2224 	    bcopy(&sc->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
2225 	    if (sc->inputbytes > l)
2226 	        bcopy(&sc->ipacket[l], &sc->queue.buf[0], sc->inputbytes - l);
2227             sc->queue.tail =
2228 		(sc->queue.tail + sc->inputbytes) % sizeof(sc->queue.buf);
2229             sc->queue.count += sc->inputbytes;
2230 	}
2231         sc->inputbytes = 0;
2232 
2233         if (sc->state & PSM_ASLP) {
2234             sc->state &= ~PSM_ASLP;
2235             wakeup((caddr_t) sc);
2236     	}
2237         selwakeup(&sc->rsel);
2238     }
2239 }
2240 
2241 static int
2242 psmpoll(dev_t dev, int events, struct proc *p)
2243 {
2244     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
2245     int s;
2246     int revents = 0;
2247 
2248     /* Return true if a mouse event available */
2249     s = spltty();
2250     if (events & (POLLIN | POLLRDNORM)) {
2251 	if (sc->queue.count > 0)
2252 	    revents |= events & (POLLIN | POLLRDNORM);
2253 	else
2254 	    selrecord(p, &sc->rsel);
2255     }
2256     splx(s);
2257 
2258     return (revents);
2259 }
2260 
2261 /* vendor/model specific routines */
2262 
2263 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
2264 {
2265     if (set_mouse_resolution(kbdc, res) != res)
2266         return FALSE;
2267     if (set_mouse_scaling(kbdc, scale)
2268 	&& set_mouse_scaling(kbdc, scale)
2269 	&& set_mouse_scaling(kbdc, scale)
2270 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3))
2271 	return TRUE;
2272     return FALSE;
2273 }
2274 
2275 #if notyet
2276 /* Logitech MouseMan Cordless II */
2277 static int
2278 enable_lcordless(struct psm_softc *sc)
2279 {
2280     int status[3];
2281     int ch;
2282 
2283     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
2284         return FALSE;
2285     if (status[1] == PSMD_RES_HIGH)
2286 	return FALSE;
2287     ch = (status[0] & 0x07) - 1;	/* channel # */
2288     if ((ch <= 0) || (ch > 4))
2289 	return FALSE;
2290     /*
2291      * status[1]: always one?
2292      * status[2]: battery status? (0-100)
2293      */
2294     return TRUE;
2295 }
2296 #endif /* notyet */
2297 
2298 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
2299 static int
2300 enable_groller(struct psm_softc *sc)
2301 {
2302     int status[3];
2303 
2304     /*
2305      * The special sequence to enable the fourth button and the
2306      * roller. Immediately after this sequence check status bytes.
2307      * if the mouse is NetScroll, the second and the third bytes are
2308      * '3' and 'D'.
2309      */
2310 
2311     /*
2312      * If the mouse is an ordinary PS/2 mouse, the status bytes should
2313      * look like the following.
2314      *
2315      * byte 1 bit 7 always 0
2316      *        bit 6 stream mode (0)
2317      *        bit 5 disabled (0)
2318      *        bit 4 1:1 scaling (0)
2319      *        bit 3 always 0
2320      *        bit 0-2 button status
2321      * byte 2 resolution (PSMD_RES_HIGH)
2322      * byte 3 report rate (?)
2323      */
2324 
2325     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2326         return FALSE;
2327     if ((status[1] != '3') || (status[2] != 'D'))
2328         return FALSE;
2329     /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
2330     sc->hw.buttons = 4;
2331     return TRUE;
2332 }
2333 
2334 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
2335 static int
2336 enable_gmouse(struct psm_softc *sc)
2337 {
2338     int status[3];
2339 
2340     /*
2341      * The special sequence to enable the middle, "rubber" button.
2342      * Immediately after this sequence check status bytes.
2343      * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
2344      * the second and the third bytes are '3' and 'U'.
2345      * NOTE: NetMouse reports that it has three buttons although it has
2346      * two buttons and a rubber button. NetMouse Pro and MIE Mouse
2347      * say they have three buttons too and they do have a button on the
2348      * side...
2349      */
2350     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2351         return FALSE;
2352     if ((status[1] != '3') || (status[2] != 'U'))
2353         return FALSE;
2354     return TRUE;
2355 }
2356 
2357 /* ALPS GlidePoint */
2358 static int
2359 enable_aglide(struct psm_softc *sc)
2360 {
2361     int status[3];
2362 
2363     /*
2364      * The special sequence to obtain ALPS GlidePoint specific
2365      * information. Immediately after this sequence, status bytes will
2366      * contain something interesting.
2367      * NOTE: ALPS produces several models of GlidePoint. Some of those
2368      * do not respond to this sequence, thus, cannot be detected this way.
2369      */
2370     if (set_mouse_sampling_rate(sc->kbdc, 100) != 100)
2371 	return FALSE;
2372     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
2373         return FALSE;
2374     if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
2375         return FALSE;
2376     return TRUE;
2377 }
2378 
2379 /* Kensington ThinkingMouse/Trackball */
2380 static int
2381 enable_kmouse(struct psm_softc *sc)
2382 {
2383     static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
2384     KBDC kbdc = sc->kbdc;
2385     int status[3];
2386     int id1;
2387     int id2;
2388     int i;
2389 
2390     id1 = get_aux_id(kbdc);
2391     if (set_mouse_sampling_rate(kbdc, 10) != 10)
2392 	return FALSE;
2393     /*
2394      * The device is now in the native mode? It returns a different
2395      * ID value...
2396      */
2397     id2 = get_aux_id(kbdc);
2398     if ((id1 == id2) || (id2 != 2))
2399 	return FALSE;
2400 
2401     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
2402         return FALSE;
2403 #if PSM_DEBUG >= 2
2404     /* at this point, resolution is LOW, sampling rate is 10/sec */
2405     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2406         return FALSE;
2407 #endif
2408 
2409     /*
2410      * The special sequence to enable the third and fourth buttons.
2411      * Otherwise they behave like the first and second buttons.
2412      */
2413     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2414         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2415 	    return FALSE;
2416     }
2417 
2418     /*
2419      * At this point, the device is using default resolution and
2420      * sampling rate for the native mode.
2421      */
2422     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2423         return FALSE;
2424     if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
2425         return FALSE;
2426 
2427     /* the device appears be enabled by this sequence, diable it for now */
2428     disable_aux_dev(kbdc);
2429     empty_aux_buffer(kbdc, 5);
2430 
2431     return TRUE;
2432 }
2433 
2434 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
2435 static int
2436 enable_mmanplus(struct psm_softc *sc)
2437 {
2438     static char res[] = {
2439 	-1, PSMD_RES_LOW, PSMD_RES_HIGH, PSMD_RES_MEDIUM_HIGH,
2440 	PSMD_RES_MEDIUM_LOW, -1, PSMD_RES_HIGH, PSMD_RES_MEDIUM_LOW,
2441 	PSMD_RES_MEDIUM_HIGH, PSMD_RES_HIGH,
2442     };
2443     KBDC kbdc = sc->kbdc;
2444     int data[3];
2445     int i;
2446 
2447     /* the special sequence to enable the fourth button and the roller. */
2448     /*
2449      * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
2450      * must be called exactly three times since the last RESET command
2451      * before this sequence. XXX
2452      */
2453     for (i = 0; i < sizeof(res)/sizeof(res[0]); ++i) {
2454 	if (res[i] < 0) {
2455 	    if (!set_mouse_scaling(kbdc, 1))
2456 		return FALSE;
2457 	} else {
2458 	    if (set_mouse_resolution(kbdc, res[i]) != res[i])
2459 		return FALSE;
2460 	}
2461     }
2462 
2463     if (get_mouse_status(kbdc, data, 1, 3) < 3)
2464         return FALSE;
2465 
2466     /*
2467      * PS2++ protocl, packet type 0
2468      *
2469      *          b7 b6 b5 b4 b3 b2 b1 b0
2470      * byte 1:  *  1  p3 p2 1  *  *  *
2471      * byte 2:  1  1  p1 p0 m1 m0 1  0
2472      * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
2473      *
2474      * p3-p0: packet type: 0
2475      * m7-m0: model ID: MouseMan+:0x50, FirstMouse+:0x51, ScrollPoint:0x58...
2476      */
2477     /* check constant bits */
2478     if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
2479         return FALSE;
2480     if ((data[1] & 0xc3) != 0xc2)
2481         return FALSE;
2482     /* check d3-d0 in byte 2 */
2483     if (!MOUSE_PS2PLUS_CHECKBITS(data))
2484         return FALSE;
2485     /* check p3-p0 */
2486     if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
2487         return FALSE;
2488 
2489     sc->hw.hwid &= 0x00ff;
2490     sc->hw.hwid |= data[2] << 8;	/* save model ID */
2491 
2492     /*
2493      * MouseMan+ (or FirstMouse+) is now in its native mode, in which
2494      * the wheel and the fourth button events are encoded in the
2495      * special data packet. The mouse may be put in the IntelliMouse mode
2496      * if it is initialized by the IntelliMouse's method.
2497      */
2498     return TRUE;
2499 }
2500 
2501 /* MS IntelliMouse Explorer */
2502 static int
2503 enable_msexplorer(struct psm_softc *sc)
2504 {
2505     static unsigned char rate0[] = { 200, 100, 80, };
2506     static unsigned char rate1[] = { 200, 200, 80, };
2507     KBDC kbdc = sc->kbdc;
2508     int id;
2509     int i;
2510 
2511     /*
2512      * XXX: this is a kludge to fool some KVM switch products
2513      * which think they are clever enough to know the 4-byte IntelliMouse
2514      * protocol, and assume any other protocols use 3-byte packets.
2515      * They don't convey 4-byte data packets from the IntelliMouse Explorer
2516      * correctly to the host computer because of this!
2517      * The following sequence is actually IntelliMouse's "wake up"
2518      * sequence; it will make the KVM think the mouse is IntelliMouse
2519      * when it is in fact IntelliMouse Explorer.
2520      */
2521     for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i) {
2522         if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
2523 	    return FALSE;
2524     }
2525     id = get_aux_id(kbdc);
2526 
2527     /* the special sequence to enable the extra buttons and the roller. */
2528     for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i) {
2529         if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
2530 	    return FALSE;
2531     }
2532     /* the device will give the genuine ID only after the above sequence */
2533     id = get_aux_id(kbdc);
2534     if (id != PSM_EXPLORER_ID)
2535 	return FALSE;
2536 
2537     sc->hw.hwid = id;
2538     sc->hw.buttons = 5;		/* IntelliMouse Explorer XXX */
2539 
2540     return TRUE;
2541 }
2542 
2543 /* MS IntelliMouse */
2544 static int
2545 enable_msintelli(struct psm_softc *sc)
2546 {
2547     /*
2548      * Logitech MouseMan+ and FirstMouse+ will also respond to this
2549      * probe routine and act like IntelliMouse.
2550      */
2551 
2552     static unsigned char rate[] = { 200, 100, 80, };
2553     KBDC kbdc = sc->kbdc;
2554     int id;
2555     int i;
2556 
2557     /* the special sequence to enable the third button and the roller. */
2558     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2559         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2560 	    return FALSE;
2561     }
2562     /* the device will give the genuine ID only after the above sequence */
2563     id = get_aux_id(kbdc);
2564     if (id != PSM_INTELLI_ID)
2565 	return FALSE;
2566 
2567     sc->hw.hwid = id;
2568     sc->hw.buttons = 3;
2569 
2570     return TRUE;
2571 }
2572 
2573 /* A4 Tech 4D Mouse */
2574 static int
2575 enable_4dmouse(struct psm_softc *sc)
2576 {
2577     /*
2578      * Newer wheel mice from A4 Tech may use the 4D+ protocol.
2579      */
2580 
2581     static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
2582     KBDC kbdc = sc->kbdc;
2583     int id;
2584     int i;
2585 
2586     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2587         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2588 	    return FALSE;
2589     }
2590     id = get_aux_id(kbdc);
2591     /*
2592      * WinEasy 4D, 4 Way Scroll 4D: 6
2593      * Cable-Free 4D: 8 (4DPLUS)
2594      * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
2595      */
2596     if (id != PSM_4DMOUSE_ID)
2597 	return FALSE;
2598 
2599     sc->hw.hwid = id;
2600     sc->hw.buttons = 3;		/* XXX some 4D mice have 4? */
2601 
2602     return TRUE;
2603 }
2604 
2605 /* A4 Tech 4D+ Mouse */
2606 static int
2607 enable_4dplus(struct psm_softc *sc)
2608 {
2609     /*
2610      * Newer wheel mice from A4 Tech seem to use this protocol.
2611      * Older models are recognized as either 4D Mouse or IntelliMouse.
2612      */
2613     KBDC kbdc = sc->kbdc;
2614     int id;
2615 
2616     /*
2617      * enable_4dmouse() already issued the following ID sequence...
2618     static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
2619     int i;
2620 
2621     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2622         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2623 	    return FALSE;
2624     }
2625     */
2626 
2627     id = get_aux_id(kbdc);
2628     if (id != PSM_4DPLUS_ID)
2629 	return FALSE;
2630 
2631     sc->hw.hwid = id;
2632     sc->hw.buttons = 4;		/* XXX */
2633 
2634     return TRUE;
2635 }
2636 
2637 /* Interlink electronics VersaPad */
2638 static int
2639 enable_versapad(struct psm_softc *sc)
2640 {
2641     KBDC kbdc = sc->kbdc;
2642     int data[3];
2643 
2644     set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
2645     set_mouse_sampling_rate(kbdc, 100);		/* set rate 100 */
2646     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2647     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2648     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2649     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2650     if (get_mouse_status(kbdc, data, 0, 3) < 3)	/* get status */
2651 	return FALSE;
2652     if (data[2] != 0xa || data[1] != 0 )	/* rate == 0xa && res. == 0 */
2653 	return FALSE;
2654     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2655 
2656     sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
2657 
2658     return TRUE;				/* PS/2 absolute mode */
2659 }
2660 
2661 static int
2662 psmresume(device_t dev)
2663 {
2664     struct psm_softc *sc = device_get_softc(dev);
2665     int unit = device_get_unit(dev);
2666     int err = 0;
2667     int s;
2668     int c;
2669 
2670     if (verbose >= 2)
2671         log(LOG_NOTICE, "psm%d: system resume hook called.\n", unit);
2672 
2673     if (!(sc->config & PSM_CONFIG_HOOKRESUME))
2674 	return (0);
2675 
2676     /* don't let anybody mess with the aux device */
2677     if (!kbdc_lock(sc->kbdc, TRUE))
2678 	return (EIO);
2679     s = spltty();
2680 
2681     /* block our watchdog timer */
2682     sc->watchdog = FALSE;
2683     untimeout(psmtimeout, (void *)(uintptr_t)unit, sc->callout);
2684     callout_handle_init(&sc->callout);
2685 
2686     /* save the current controller command byte */
2687     empty_both_buffers(sc->kbdc, 10);
2688     c = get_controller_command_byte(sc->kbdc);
2689     if (verbose >= 2)
2690         log(LOG_DEBUG, "psm%d: current command byte: %04x (psmresume).\n",
2691 	    unit, c);
2692 
2693     /* enable the aux port but disable the aux interrupt and the keyboard */
2694     if ((c == -1) || !set_controller_command_byte(sc->kbdc,
2695 	    kbdc_get_device_mask(sc->kbdc),
2696   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
2697 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2698         /* CONTROLLER ERROR */
2699 	splx(s);
2700         kbdc_lock(sc->kbdc, FALSE);
2701 	log(LOG_ERR, "psm%d: unable to set the command byte (psmresume).\n",
2702 	    unit);
2703 	return (EIO);
2704     }
2705 
2706     /* flush any data */
2707     if (sc->state & PSM_VALID) {
2708 	disable_aux_dev(sc->kbdc);	/* this may fail; but never mind... */
2709 	empty_aux_buffer(sc->kbdc, 10);
2710     }
2711     sc->inputbytes = 0;
2712 
2713     /* try to detect the aux device; are you still there? */
2714     if (sc->config & PSM_CONFIG_INITAFTERSUSPEND) {
2715 	if (reinitialize(unit, &sc->mode)) {
2716 	    /* yes */
2717 	    sc->state |= PSM_VALID;
2718 	} else {
2719 	    /* the device has gone! */
2720 	    restore_controller(sc->kbdc, c);
2721 	    sc->state &= ~PSM_VALID;
2722 	    log(LOG_ERR, "psm%d: the aux device has gone! (psmresume).\n",
2723 		unit);
2724 	    err = ENXIO;
2725 	}
2726     }
2727     splx(s);
2728 
2729     /* restore the driver state */
2730     if ((sc->state & PSM_OPEN) && (err == 0)) {
2731         /* enable the aux device and the port again */
2732 	err = doopen(unit, c);
2733 	if (err != 0)
2734 	    log(LOG_ERR, "psm%d: failed to enable the device (psmresume).\n",
2735 		unit);
2736     } else {
2737         /* restore the keyboard port and disable the aux port */
2738         if (!set_controller_command_byte(sc->kbdc,
2739                 kbdc_get_device_mask(sc->kbdc),
2740                 (c & KBD_KBD_CONTROL_BITS)
2741                     | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2742             /* CONTROLLER ERROR */
2743             log(LOG_ERR, "psm%d: failed to disable the aux port (psmresume).\n",
2744                 unit);
2745             err = EIO;
2746 	}
2747     }
2748 
2749     /* done */
2750     kbdc_lock(sc->kbdc, FALSE);
2751     if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
2752 	/*
2753 	 * Release the blocked process; it must be notified that the device
2754 	 * cannot be accessed anymore.
2755 	 */
2756         sc->state &= ~PSM_ASLP;
2757         wakeup((caddr_t)sc);
2758     }
2759 
2760     if (verbose >= 2)
2761         log(LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit);
2762 
2763     return (err);
2764 }
2765 
2766 DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
2767