xref: /freebsd/sys/dev/atkbdc/psm.c (revision 6e8394b8baa7d5d9153ab90de6824bcd19b3b4e1)
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  * $Id: psm.c,v 1.10 1999/05/30 16:52:47 phk Exp $
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 "psm.h"
65 #ifdef __i386__
66 #include "apm.h"
67 #endif
68 #include "opt_devfs.h"
69 #include "opt_psm.h"
70 
71 #if NPSM > 0
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/kernel.h>
76 #include <sys/module.h>
77 #include <sys/bus.h>
78 #include <sys/conf.h>
79 #include <sys/poll.h>
80 #include <sys/syslog.h>
81 #include <sys/malloc.h>
82 #include <machine/bus.h>
83 #include <sys/rman.h>
84 #ifdef DEVFS
85 #include <sys/devfsext.h>
86 #endif
87 #include <sys/select.h>
88 #include <sys/uio.h>
89 
90 #ifdef __i386__
91 #include <machine/apm_bios.h>
92 #endif
93 #include <machine/clock.h>
94 #include <machine/limits.h>
95 #include <machine/mouse.h>
96 #include <machine/resource.h>
97 
98 #include <isa/isareg.h>
99 #include <isa/isavar.h>
100 #include <dev/kbd/atkbdcreg.h>
101 
102 /*
103  * Driver specific options: the following options may be set by
104  * `options' statements in the kernel configuration file.
105  */
106 
107 /* debugging */
108 #ifndef PSM_DEBUG
109 #define PSM_DEBUG	0	/* logging: 0: none, 1: brief, 2: verbose */
110 #endif
111 
112 /* features */
113 
114 /* #define PSM_HOOKAPM	   	   hook the APM resume event */
115 /* #define PSM_RESETAFTERSUSPEND   reset the device at the resume event */
116 
117 #if NAPM <= 0
118 #undef PSM_HOOKAPM
119 #endif /* NAPM */
120 
121 #ifndef PSM_HOOKAPM
122 #undef PSM_RESETAFTERSUSPEND
123 #endif /* PSM_HOOKAPM */
124 
125 /* end of driver specific options */
126 
127 /* input queue */
128 #define PSM_BUFSIZE		960
129 #define PSM_SMALLBUFSIZE	240
130 
131 /* operation levels */
132 #define PSM_LEVEL_BASE		0
133 #define PSM_LEVEL_STANDARD	1
134 #define PSM_LEVEL_NATIVE	2
135 #define PSM_LEVEL_MIN		PSM_LEVEL_BASE
136 #define PSM_LEVEL_MAX		PSM_LEVEL_NATIVE
137 
138 /* some macros */
139 #define PSM_UNIT(dev)		(minor(dev) >> 1)
140 #define PSM_NBLOCKIO(dev)	(minor(dev) & 1)
141 #define PSM_MKMINOR(unit,block)	(((unit) << 1) | ((block) ? 0:1))
142 
143 #ifndef max
144 #define max(x,y)		((x) > (y) ? (x) : (y))
145 #endif
146 #ifndef min
147 #define min(x,y)		((x) < (y) ? (x) : (y))
148 #endif
149 
150 /* ring buffer */
151 typedef struct ringbuf {
152     int           count;	/* # of valid elements in the buffer */
153     int           head;		/* head pointer */
154     int           tail;		/* tail poiner */
155     unsigned char buf[PSM_BUFSIZE];
156 } ringbuf_t;
157 
158 /* driver control block */
159 struct psm_softc {		/* Driver status information */
160     struct selinfo rsel;	/* Process selecting for Input */
161     unsigned char state;	/* Mouse driver state */
162     int           config;	/* driver configuration flags */
163     int           flags;	/* other flags */
164     KBDC          kbdc;		/* handle to access the keyboard controller */
165     int           addr;		/* I/O port address */
166     mousehw_t     hw;		/* hardware information */
167     mousemode_t   mode;		/* operation mode */
168     mousemode_t   dflt_mode;	/* default operation mode */
169     mousestatus_t status;	/* accumulated mouse movement */
170     ringbuf_t     queue;	/* mouse status queue */
171     unsigned char ipacket[16];	/* interim input buffer */
172     int           inputbytes;	/* # of bytes in the input buffer */
173     int           button;	/* the latest button state */
174 #ifdef DEVFS
175     void          *devfs_token;
176     void          *b_devfs_token;
177 #endif
178 #ifdef PSM_HOOKAPM
179     struct apmhook resumehook;
180 #endif
181 };
182 devclass_t psm_devclass;
183 #define PSM_SOFTC(unit)	((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
184 
185 /* driver state flags (state) */
186 #define PSM_VALID		0x80
187 #define PSM_OPEN		1	/* Device is open */
188 #define PSM_ASLP		2	/* Waiting for mouse data */
189 
190 /* driver configuration flags (config) */
191 #define PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
192 #define PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
193 #define PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
194 #define PSM_CONFIG_NOIDPROBE	0x0200  /* disable mouse model probe */
195 #define PSM_CONFIG_NORESET	0x0400  /* don't reset the mouse */
196 #define PSM_CONFIG_FORCETAP	0x0800  /* assume `tap' action exists */
197 #define PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
198 
199 #define PSM_CONFIG_FLAGS	(PSM_CONFIG_RESOLUTION 		\
200 				    | PSM_CONFIG_ACCEL		\
201 				    | PSM_CONFIG_NOCHECKSYNC	\
202 				    | PSM_CONFIG_NOIDPROBE	\
203 				    | PSM_CONFIG_NORESET	\
204 				    | PSM_CONFIG_FORCETAP	\
205 				    | PSM_CONFIG_IGNPORTERROR)
206 
207 /* other flags (flags) */
208 
209 /* for backward compatibility */
210 #define OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
211 #define OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
212 #define OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)
213 
214 typedef struct old_mousehw {
215     int buttons;
216     int iftype;
217     int type;
218     int hwid;
219 } old_mousehw_t;
220 
221 typedef struct old_mousemode {
222     int protocol;
223     int rate;
224     int resolution;
225     int accelfactor;
226 } old_mousemode_t;
227 
228 /* packet formatting function */
229 typedef int packetfunc_t __P((struct psm_softc *, unsigned char *,
230 			      int *, int, mousestatus_t *));
231 
232 /* function prototypes */
233 static int psmprobe __P((device_t));
234 static int psmattach __P((device_t));
235 #ifdef PSM_HOOKAPM
236 static int psmresume __P((void *));
237 #endif
238 
239 static d_open_t psmopen;
240 static d_close_t psmclose;
241 static d_read_t psmread;
242 static d_ioctl_t psmioctl;
243 static d_poll_t psmpoll;
244 
245 static int enable_aux_dev __P((KBDC));
246 static int disable_aux_dev __P((KBDC));
247 static int get_mouse_status __P((KBDC, int *, int, int));
248 static int get_aux_id __P((KBDC));
249 static int set_mouse_sampling_rate __P((KBDC, int));
250 static int set_mouse_scaling __P((KBDC, int));
251 static int set_mouse_resolution __P((KBDC, int));
252 #ifdef PSM_RESETAFTERSUSPEND
253 static int set_mouse_mode __P((KBDC));
254 #endif /* PSM_RESETAFTERSUSPEND */
255 static int get_mouse_buttons __P((KBDC));
256 static int is_a_mouse __P((int));
257 static void recover_from_error __P((KBDC));
258 static int restore_controller __P((KBDC, int));
259 #ifdef PSM_RESETAFTERSUSPEND
260 static int reinitialize __P((int, mousemode_t *));
261 #endif
262 static int doopen __P((int, int));
263 static char *model_name(int);
264 static void psmintr(void*);
265 
266 /* vendor specific features */
267 typedef int probefunc_t __P((struct psm_softc *));
268 
269 static int mouse_id_proc1 __P((KBDC, int, int, int *));
270 static probefunc_t enable_groller;
271 static probefunc_t enable_gmouse;
272 static probefunc_t enable_aglide;
273 static probefunc_t enable_kmouse;
274 static probefunc_t enable_msintelli;
275 static probefunc_t enable_mmanplus;
276 static int tame_mouse __P((struct psm_softc *, mousestatus_t *, unsigned char *));
277 
278 static struct {
279     int                 model;
280     unsigned char	syncmask;
281     int 		packetsize;
282     probefunc_t 	*probefunc;
283 } vendortype[] = {
284     { MOUSE_MODEL_NET,			/* Genius NetMouse */
285       0xc8, MOUSE_INTELLI_PACKETSIZE, enable_gmouse, },
286     { MOUSE_MODEL_NETSCROLL,		/* Genius NetScroll */
287       0xc8, 6, enable_groller, },
288     { MOUSE_MODEL_GLIDEPOINT,		/* ALPS GlidePoint */
289       0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide, },
290     { MOUSE_MODEL_MOUSEMANPLUS,		/* Logitech MouseMan+ */
291       0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus, },
292     { MOUSE_MODEL_THINK,		/* Kensignton ThinkingMouse */
293       0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse, },
294     { MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
295       0xc8, MOUSE_INTELLI_PACKETSIZE, enable_msintelli, },
296     { MOUSE_MODEL_GENERIC,
297       0xc0, MOUSE_PS2_PACKETSIZE, NULL, },
298 };
299 #define GENERIC_MOUSE_ENTRY	6
300 
301 /* device driver declarateion */
302 static device_method_t psm_methods[] = {
303 	/* Device interface */
304 	DEVMETHOD(device_probe,		psmprobe),
305 	DEVMETHOD(device_attach,	psmattach),
306 
307 	{ 0, 0 }
308 };
309 
310 static driver_t psm_driver = {
311     "psm",
312     psm_methods,
313     sizeof(struct psm_softc),
314 };
315 
316 #define CDEV_MAJOR        21
317 
318 static struct cdevsw psm_cdevsw = {
319 	/* open */	psmopen,
320 	/* close */	psmclose,
321 	/* read */	psmread,
322 	/* write */	nowrite,
323 	/* ioctl */	psmioctl,
324 	/* stop */	nostop,
325 	/* reset */	noreset,
326 	/* devtotty */	nodevtotty,
327 	/* poll */	psmpoll,
328 	/* mmap */	nommap,
329 	/* strategy */	nostrategy,
330 	/* name */	"psm",
331 	/* parms */	noparms,
332 	/* maj */	CDEV_MAJOR,
333 	/* dump */	nodump,
334 	/* psize */	nopsize,
335 	/* flags */	0,
336 	/* maxio */	0,
337 	/* bmaj */	-1
338 };
339 
340 /* debug message level */
341 static int verbose = PSM_DEBUG;
342 
343 /* device I/O routines */
344 static int
345 enable_aux_dev(KBDC kbdc)
346 {
347     int res;
348 
349     res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
350     if (verbose >= 2)
351         log(LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res);
352 
353     return (res == PSM_ACK);
354 }
355 
356 static int
357 disable_aux_dev(KBDC kbdc)
358 {
359     int res;
360 
361     res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
362     if (verbose >= 2)
363         log(LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res);
364 
365     return (res == PSM_ACK);
366 }
367 
368 static int
369 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
370 {
371     int cmd;
372     int res;
373     int i;
374 
375     switch (flag) {
376     case 0:
377     default:
378 	cmd = PSMC_SEND_DEV_STATUS;
379 	break;
380     case 1:
381 	cmd = PSMC_SEND_DEV_DATA;
382 	break;
383     }
384     empty_aux_buffer(kbdc, 5);
385     res = send_aux_command(kbdc, cmd);
386     if (verbose >= 2)
387         log(LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
388 	    (flag == 1) ? "DATA" : "STATUS", res);
389     if (res != PSM_ACK)
390         return 0;
391 
392     for (i = 0; i < len; ++i) {
393         status[i] = read_aux_data(kbdc);
394 	if (status[i] < 0)
395 	    break;
396     }
397 
398     if (verbose) {
399         log(LOG_DEBUG, "psm: %s %02x %02x %02x\n",
400             (flag == 1) ? "data" : "status", status[0], status[1], status[2]);
401     }
402 
403     return i;
404 }
405 
406 static int
407 get_aux_id(KBDC kbdc)
408 {
409     int res;
410     int id;
411 
412     empty_aux_buffer(kbdc, 5);
413     res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
414     if (verbose >= 2)
415         log(LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res);
416     if (res != PSM_ACK)
417 	return (-1);
418 
419     /* 10ms delay */
420     DELAY(10000);
421 
422     id = read_aux_data(kbdc);
423     if (verbose >= 2)
424         log(LOG_DEBUG, "psm: device ID: %04x\n", id);
425 
426     return id;
427 }
428 
429 static int
430 set_mouse_sampling_rate(KBDC kbdc, int rate)
431 {
432     int res;
433 
434     res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
435     if (verbose >= 2)
436         log(LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res);
437 
438     return ((res == PSM_ACK) ? rate : -1);
439 }
440 
441 static int
442 set_mouse_scaling(KBDC kbdc, int scale)
443 {
444     int res;
445 
446     switch (scale) {
447     case 1:
448     default:
449 	scale = PSMC_SET_SCALING11;
450 	break;
451     case 2:
452 	scale = PSMC_SET_SCALING21;
453 	break;
454     }
455     res = send_aux_command(kbdc, scale);
456     if (verbose >= 2)
457         log(LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
458 	    (scale == PSMC_SET_SCALING21) ? "21" : "11", res);
459 
460     return (res == PSM_ACK);
461 }
462 
463 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
464 static int
465 set_mouse_resolution(KBDC kbdc, int val)
466 {
467     int res;
468 
469     res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
470     if (verbose >= 2)
471         log(LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res);
472 
473     return ((res == PSM_ACK) ? val : -1);
474 }
475 
476 #ifdef PSM_RESETAFTERSUSPEND
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 #endif /* PSM_RESETAFTERSUSPEND */
493 
494 
495 static int
496 get_mouse_buttons(KBDC kbdc)
497 {
498     int c = 2;		/* assume two buttons by default */
499     int status[3];
500 
501     /*
502      * NOTE: a special sequence to obtain Logitech Mouse specific
503      * information: set resolution to 25 ppi, set scaling to 1:1, set
504      * scaling to 1:1, set scaling to 1:1. Then the second byte of the
505      * mouse status bytes is the number of available buttons.
506      * Some manufactures also support this sequence.
507      */
508     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
509         return c;
510     if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1)
511         && set_mouse_scaling(kbdc, 1)
512 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3)) {
513         if (status[1] != 0)
514             return status[1];
515     }
516     return c;
517 }
518 
519 /* misc subroutines */
520 /*
521  * Someday, I will get the complete list of valid pointing devices and
522  * their IDs... XXX
523  */
524 static int
525 is_a_mouse(int id)
526 {
527 #if 0
528     static int valid_ids[] = {
529         PSM_MOUSE_ID,		/* mouse */
530         PSM_BALLPOINT_ID,	/* ballpoint device */
531         PSM_INTELLI_ID,		/* Intellimouse */
532         -1			/* end of table */
533     };
534     int i;
535 
536     for (i = 0; valid_ids[i] >= 0; ++i)
537         if (valid_ids[i] == id)
538             return TRUE;
539     return FALSE;
540 #else
541     return TRUE;
542 #endif
543 }
544 
545 static char *
546 model_name(int model)
547 {
548     static struct {
549 	int model_code;
550 	char *model_name;
551     } models[] = {
552         { MOUSE_MODEL_NETSCROLL,	"NetScroll Mouse" },
553         { MOUSE_MODEL_NET,		"NetMouse" },
554         { MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
555         { MOUSE_MODEL_THINK,		"ThinkingMouse" },
556         { MOUSE_MODEL_INTELLI,		"IntelliMouse" },
557         { MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
558         { MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
559         { MOUSE_MODEL_UNKNOWN,		NULL },
560     };
561     int i;
562 
563     for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i) {
564 	if (models[i].model_code == model)
565 	    return models[i].model_name;
566     }
567     return "Unknown";
568 }
569 
570 static void
571 recover_from_error(KBDC kbdc)
572 {
573     /* discard anything left in the output buffer */
574     empty_both_buffers(kbdc, 10);
575 
576 #if 0
577     /*
578      * NOTE: KBDC_RESET_KBD may not restore the communication between the
579      * keyboard and the controller.
580      */
581     reset_kbd(kbdc);
582 #else
583     /*
584      * NOTE: somehow diagnostic and keyboard port test commands bring the
585      * keyboard back.
586      */
587     if (!test_controller(kbdc))
588         log(LOG_ERR, "psm: keyboard controller failed.\n");
589     /* if there isn't a keyboard in the system, the following error is OK */
590     if (test_kbd_port(kbdc) != 0) {
591 	if (verbose)
592 	    log(LOG_ERR, "psm: keyboard port failed.\n");
593     }
594 #endif
595 }
596 
597 static int
598 restore_controller(KBDC kbdc, int command_byte)
599 {
600     empty_both_buffers(kbdc, 10);
601 
602     if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
603 	log(LOG_ERR, "psm: failed to restore the keyboard controller "
604 		     "command byte.\n");
605 	return FALSE;
606     } else {
607 	return TRUE;
608     }
609 }
610 
611 #ifdef PSM_RESETAFTERSUSPEND
612 /*
613  * Re-initialize the aux port and device. The aux port must be enabled
614  * and its interrupt must be disabled before calling this routine.
615  * The aux device will be disabled before returning.
616  * The keyboard controller must be locked via `kbdc_lock()' before
617  * calling this routine.
618  */
619 static int
620 reinitialize(int unit, mousemode_t *mode)
621 {
622     struct psm_softc *sc = PSM_SOFTC(unit);
623     KBDC kbdc = sc->kbdc;
624     int stat[3];
625     int i;
626 
627     switch((i = test_aux_port(kbdc))) {
628     case 1:	/* ignore this error */
629     case PSM_ACK:
630 	if (verbose)
631 	    log(LOG_DEBUG, "psm%d: strange result for test aux port (%d).\n",
632 	        unit, i);
633 	/* fall though */
634     case 0:	/* no error */
635     	break;
636     case -1: 	/* time out */
637     default: 	/* error */
638     	recover_from_error(kbdc);
639 	if (sc->config & PSM_CONFIG_IGNPORTERROR)
640 	    break;
641     	log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
642     	    unit, i);
643     	return FALSE;
644     }
645 
646     if (sc->config & PSM_CONFIG_NORESET) {
647 	/*
648 	 * Don't try to reset the pointing device.  It may possibly be
649 	 * left in the unknown state, though...
650 	 */
651     } else {
652 	/*
653 	 * NOTE: some controllers appears to hang the `keyboard' when
654 	 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
655 	 */
656 	if (!reset_aux_dev(kbdc)) {
657             recover_from_error(kbdc);
658             log(LOG_ERR, "psm%d: failed to reset the aux device.\n", unit);
659             return FALSE;
660 	}
661     }
662 
663     /*
664      * both the aux port and the aux device is functioning, see
665      * if the device can be enabled.
666      */
667     if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
668         log(LOG_ERR, "psm%d: failed to enable the aux device.\n", unit);
669         return FALSE;
670     }
671     empty_both_buffers(kbdc, 10);	/* remove stray data if any */
672 
673     if (sc->config & PSM_CONFIG_NOIDPROBE) {
674 	i = GENERIC_MOUSE_ENTRY;
675     } else {
676 	/* FIXME: hardware ID, mouse buttons? */
677 
678 	/* other parameters */
679 	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
680 	    if ((*vendortype[i].probefunc)(sc)) {
681 		if (verbose >= 2)
682 		    log(LOG_ERR, "psm%d: found %s\n",
683 			unit, model_name(vendortype[i].model));
684 		break;
685 	    }
686 	}
687     }
688 
689     sc->hw.model = vendortype[i].model;
690     sc->mode.packetsize = vendortype[i].packetsize;
691 
692     /* set mouse parameters */
693     if (mode != (mousemode_t *)NULL) {
694 	if (mode->rate > 0)
695             mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
696 	if (mode->resolution >= 0)
697             mode->resolution = set_mouse_resolution(kbdc, mode->resolution);
698         set_mouse_scaling(kbdc, 1);
699         set_mouse_mode(kbdc);
700     }
701 
702     /* request a data packet and extract sync. bits */
703     if (get_mouse_status(kbdc, stat, 1, 3) < 3) {
704         log(LOG_DEBUG, "psm%d: failed to get data (reinitialize).\n", unit);
705         sc->mode.syncmask[0] = 0;
706     } else {
707         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
708 	/* the NetScroll Mouse will send three more bytes... Ignore them */
709 	empty_aux_buffer(kbdc, 5);
710     }
711 
712     /* just check the status of the mouse */
713     if (get_mouse_status(kbdc, stat, 0, 3) < 3)
714         log(LOG_DEBUG, "psm%d: failed to get status (reinitialize).\n", unit);
715 
716     return TRUE;
717 }
718 #endif /* PSM_RESETAFTERSUSPEND */
719 
720 static int
721 doopen(int unit, int command_byte)
722 {
723     struct psm_softc *sc = PSM_SOFTC(unit);
724     int stat[3];
725 
726     /* enable the mouse device */
727     if (!enable_aux_dev(sc->kbdc)) {
728 	/* MOUSE ERROR: failed to enable the mouse because:
729 	 * 1) the mouse is faulty,
730 	 * 2) the mouse has been removed(!?)
731 	 * In the latter case, the keyboard may have hung, and need
732 	 * recovery procedure...
733 	 */
734 	recover_from_error(sc->kbdc);
735 #if 0
736 	/* FIXME: we could reset the mouse here and try to enable
737 	 * it again. But it will take long time and it's not a good
738 	 * idea to disable the keyboard that long...
739 	 */
740 	if (!reinitialize(unit, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
741 	    recover_from_error(sc->kbdc);
742 #else
743         {
744 #endif
745             restore_controller(sc->kbdc, command_byte);
746 	    /* mark this device is no longer available */
747 	    sc->state &= ~PSM_VALID;
748 	    log(LOG_ERR, "psm%d: failed to enable the device (doopen).\n",
749 		unit);
750 	    return (EIO);
751 	}
752     }
753 
754     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
755         log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n", unit);
756 
757     /* enable the aux port and interrupt */
758     if (!set_controller_command_byte(sc->kbdc,
759 	    kbdc_get_device_mask(sc->kbdc),
760 	    (command_byte & KBD_KBD_CONTROL_BITS)
761 		| KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
762 	/* CONTROLLER ERROR */
763 	disable_aux_dev(sc->kbdc);
764         restore_controller(sc->kbdc, command_byte);
765 	log(LOG_ERR, "psm%d: failed to enable the aux interrupt (doopen).\n",
766 	    unit);
767 	return (EIO);
768     }
769 
770     return (0);
771 }
772 
773 /* psm driver entry points */
774 
775 #define endprobe(v)	{   if (bootverbose) 				\
776 				--verbose;   				\
777                             kbdc_set_device_mask(sc->kbdc, mask);	\
778 			    kbdc_lock(sc->kbdc, FALSE);			\
779  	                    free(sc, M_DEVBUF);                         \
780 			    return (v);	     				\
781 			}
782 
783 static int
784 psmprobe(device_t dev)
785 {
786     int unit = device_get_unit(dev);
787     struct psm_softc *sc = device_get_softc(dev);
788     uintptr_t port;
789     uintptr_t flags;
790     int stat[3];
791     int command_byte;
792     int mask;
793     int i;
794 
795 #if 0
796     kbdc_debug(TRUE);
797 #endif
798     BUS_READ_IVAR(device_get_parent(dev), dev, KBDC_IVAR_PORT, &port);
799     BUS_READ_IVAR(device_get_parent(dev), dev, KBDC_IVAR_FLAGS, &flags);
800 
801     sc->addr = port;
802     sc->kbdc = kbdc_open(sc->addr);
803     sc->config = flags & PSM_CONFIG_FLAGS;
804     sc->flags = 0;
805     if (bootverbose)
806         ++verbose;
807 
808     device_set_desc(dev, "PS/2 Mouse");
809 
810     if (!kbdc_lock(sc->kbdc, TRUE)) {
811         printf("psm%d: unable to lock the controller.\n", unit);
812         if (bootverbose)
813             --verbose;
814 	return (ENXIO);
815     }
816 
817     /*
818      * NOTE: two bits in the command byte controls the operation of the
819      * aux port (mouse port): the aux port disable bit (bit 5) and the aux
820      * port interrupt (IRQ 12) enable bit (bit 2).
821      */
822 
823     /* discard anything left after the keyboard initialization */
824     empty_both_buffers(sc->kbdc, 10);
825 
826     /* save the current command byte; it will be used later */
827     mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
828     command_byte = get_controller_command_byte(sc->kbdc);
829     if (verbose)
830         printf("psm%d: current command byte:%04x\n", unit, command_byte);
831     if (command_byte == -1) {
832         /* CONTROLLER ERROR */
833         printf("psm%d: unable to get the current command byte value.\n",
834             unit);
835         endprobe(ENXIO);
836     }
837 
838     /*
839      * disable the keyboard port while probing the aux port, which must be
840      * enabled during this routine
841      */
842     if (!set_controller_command_byte(sc->kbdc,
843 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
844   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
845                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
846         /*
847 	 * this is CONTROLLER ERROR; I don't know how to recover
848          * from this error...
849 	 */
850         restore_controller(sc->kbdc, command_byte);
851         printf("psm%d: unable to set the command byte.\n", unit);
852         endprobe(ENXIO);
853     }
854     write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
855 
856     /*
857      * NOTE: `test_aux_port()' is designed to return with zero if the aux
858      * port exists and is functioning. However, some controllers appears
859      * to respond with zero even when the aux port doesn't exist. (It may
860      * be that this is only the case when the controller DOES have the aux
861      * port but the port is not wired on the motherboard.) The keyboard
862      * controllers without the port, such as the original AT, are
863      * supporsed to return with an error code or simply time out. In any
864      * case, we have to continue probing the port even when the controller
865      * passes this test.
866      *
867      * XXX: some controllers erroneously return the error code 1 when
868      * it has the perfectly functional aux port. We have to ignore this
869      * error code. Even if the controller HAS error with the aux port,
870      * it will be detected later...
871      * XXX: another incompatible controller returns PSM_ACK (0xfa)...
872      */
873     switch ((i = test_aux_port(sc->kbdc))) {
874     case 1:	   /* ignore this error */
875     case PSM_ACK:
876         if (verbose)
877 	    printf("psm%d: strange result for test aux port (%d).\n",
878 	        unit, i);
879 	/* fall though */
880     case 0:        /* no error */
881         break;
882     case -1:        /* time out */
883     default:        /* error */
884         recover_from_error(sc->kbdc);
885 	if (sc->config & PSM_CONFIG_IGNPORTERROR)
886 	    break;
887         restore_controller(sc->kbdc, command_byte);
888         if (verbose)
889             printf("psm%d: the aux port is not functioning (%d).\n",
890                 unit, i);
891         endprobe(ENXIO);
892     }
893 
894     if (sc->config & PSM_CONFIG_NORESET) {
895 	/*
896 	 * Don't try to reset the pointing device.  It may possibly be
897 	 * left in the unknown state, though...
898 	 */
899     } else {
900 	/*
901 	 * NOTE: some controllers appears to hang the `keyboard' when the aux
902 	 * port doesn't exist and `PSMC_RESET_DEV' is issued.
903 	 */
904 	if (!reset_aux_dev(sc->kbdc)) {
905             recover_from_error(sc->kbdc);
906             restore_controller(sc->kbdc, command_byte);
907             if (verbose)
908         	printf("psm%d: failed to reset the aux device.\n", unit);
909             endprobe(ENXIO);
910 	}
911     }
912 
913     /*
914      * both the aux port and the aux device is functioning, see if the
915      * device can be enabled. NOTE: when enabled, the device will start
916      * sending data; we shall immediately disable the device once we know
917      * the device can be enabled.
918      */
919     if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
920         /* MOUSE ERROR */
921 	recover_from_error(sc->kbdc);
922 	restore_controller(sc->kbdc, command_byte);
923 	if (verbose)
924 	    printf("psm%d: failed to enable the aux device.\n", unit);
925         endprobe(ENXIO);
926     }
927 
928     /* save the default values after reset */
929     if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
930 	sc->dflt_mode.rate = sc->mode.rate = stat[2];
931 	sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
932     } else {
933 	sc->dflt_mode.rate = sc->mode.rate = -1;
934 	sc->dflt_mode.resolution = sc->mode.resolution = -1;
935     }
936 
937     /* hardware information */
938     sc->hw.iftype = MOUSE_IF_PS2;
939 
940     /* verify the device is a mouse */
941     sc->hw.hwid = get_aux_id(sc->kbdc);
942     if (!is_a_mouse(sc->hw.hwid)) {
943         restore_controller(sc->kbdc, command_byte);
944         if (verbose)
945             printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid);
946         endprobe(ENXIO);
947     }
948     switch (sc->hw.hwid) {
949     case PSM_BALLPOINT_ID:
950         sc->hw.type = MOUSE_TRACKBALL;
951         break;
952     case PSM_MOUSE_ID:
953     case PSM_INTELLI_ID:
954         sc->hw.type = MOUSE_MOUSE;
955         break;
956     default:
957         sc->hw.type = MOUSE_UNKNOWN;
958         break;
959     }
960 
961     if (sc->config & PSM_CONFIG_NOIDPROBE) {
962 	sc->hw.buttons = 2;
963 	i = GENERIC_MOUSE_ENTRY;
964     } else {
965 	/* # of buttons */
966 	sc->hw.buttons = get_mouse_buttons(sc->kbdc);
967 
968 	/* other parameters */
969 	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
970 	    if ((*vendortype[i].probefunc)(sc)) {
971 		if (verbose >= 2)
972 		    printf("psm%d: found %s\n",
973 			   unit, model_name(vendortype[i].model));
974 		break;
975 	    }
976 	}
977     }
978 
979     sc->hw.model = vendortype[i].model;
980 
981     sc->dflt_mode.level = PSM_LEVEL_BASE;
982     sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
983     sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
984     if (sc->config & PSM_CONFIG_NOCHECKSYNC)
985         sc->dflt_mode.syncmask[0] = 0;
986     else
987         sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
988     if (sc->config & PSM_CONFIG_FORCETAP)
989         sc->mode.syncmask[0] &= ~MOUSE_PS2_TAP;
990     sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
991     sc->mode = sc->dflt_mode;
992     sc->mode.packetsize = vendortype[i].packetsize;
993 
994     /* set mouse parameters */
995     i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
996     if (verbose >= 2)
997 	printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
998     if (sc->config & PSM_CONFIG_RESOLUTION) {
999         sc->mode.resolution
1000 	    = set_mouse_resolution(sc->kbdc,
1001 	        (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1002     }
1003 
1004     /* request a data packet and extract sync. bits */
1005     if (get_mouse_status(sc->kbdc, stat, 1, 3) < 3) {
1006         printf("psm%d: failed to get data.\n", unit);
1007         sc->mode.syncmask[0] = 0;
1008     } else {
1009         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
1010 	/* the NetScroll Mouse will send three more bytes... Ignore them */
1011 	empty_aux_buffer(sc->kbdc, 5);
1012     }
1013 
1014     /* just check the status of the mouse */
1015     /*
1016      * NOTE: XXX there are some arcane controller/mouse combinations out
1017      * there, which hung the controller unless there is data transmission
1018      * after ACK from the mouse.
1019      */
1020     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) {
1021         printf("psm%d: failed to get status.\n", unit);
1022     } else {
1023 	/*
1024 	 * When in its native mode, some mice operate with different
1025 	 * default parameters than in the PS/2 compatible mode.
1026 	 */
1027         sc->dflt_mode.rate = sc->mode.rate = stat[2];
1028         sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1029      }
1030 
1031     /* disable the aux port for now... */
1032     if (!set_controller_command_byte(sc->kbdc,
1033 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1034             (command_byte & KBD_KBD_CONTROL_BITS)
1035                 | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1036         /*
1037 	 * this is CONTROLLER ERROR; I don't know the proper way to
1038          * recover from this error...
1039 	 */
1040         restore_controller(sc->kbdc, command_byte);
1041         printf("psm%d: unable to set the command byte.\n", unit);
1042         endprobe(ENXIO);
1043     }
1044 
1045     /* done */
1046     kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1047     kbdc_lock(sc->kbdc, FALSE);
1048     return (0);
1049 }
1050 
1051 static int
1052 psmattach(device_t dev)
1053 {
1054     int unit = device_get_unit(dev);
1055     struct psm_softc *sc = device_get_softc(dev);
1056     void *ih;
1057     struct resource *res;
1058     uintptr_t irq;
1059     int zero = 0;
1060 
1061     if (sc == NULL)    /* shouldn't happen */
1062 	return (ENXIO);
1063 
1064     /* Setup initial state */
1065     sc->state = PSM_VALID;
1066 
1067     /* Done */
1068 #ifdef    DEVFS
1069     sc->devfs_token =
1070         devfs_add_devswf(&psm_cdevsw, PSM_MKMINOR(unit, FALSE),
1071         DV_CHR, 0, 0, 0666, "psm%d", unit);
1072     sc->b_devfs_token =
1073         devfs_add_devswf(&psm_cdevsw, PSM_MKMINOR(unit, TRUE),
1074         DV_CHR, 0, 0, 0666, "bpsm%d", unit);
1075 #endif /* DEVFS */
1076 
1077 #ifdef PSM_HOOKAPM
1078     sc->resumehook.ah_name = "PS/2 mouse";
1079     sc->resumehook.ah_fun = psmresume;
1080     sc->resumehook.ah_arg = (void *)unit;
1081     sc->resumehook.ah_order = APM_MID_ORDER;
1082     apm_hook_establish(APM_HOOK_RESUME , &sc->resumehook);
1083     if (verbose)
1084         printf("psm%d: APM hooks installed.\n", unit);
1085 #endif /* PSM_HOOKAPM */
1086 
1087     if (!verbose) {
1088         printf("psm%d: model %s, device ID %d\n",
1089 	    unit, model_name(sc->hw.model), sc->hw.hwid);
1090     } else {
1091         printf("psm%d: model %s, device ID %d, %d buttons\n",
1092 	    unit, model_name(sc->hw.model), sc->hw.hwid, sc->hw.buttons);
1093 	printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1094 	    unit, sc->config, sc->flags, sc->mode.packetsize);
1095 	printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1096 	    unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1097     }
1098 
1099     if (bootverbose)
1100         --verbose;
1101 
1102     BUS_READ_IVAR(device_get_parent(dev), dev, KBDC_IVAR_IRQ, &irq);
1103     res = bus_alloc_resource(dev, SYS_RES_IRQ, &zero, irq, irq, 1,
1104 			     RF_SHAREABLE | RF_ACTIVE);
1105     BUS_SETUP_INTR(device_get_parent(dev), dev, res, INTR_TYPE_TTY,
1106 		   psmintr, sc, &ih);
1107 
1108     return (0);
1109 }
1110 
1111 static int
1112 psmopen(dev_t dev, int flag, int fmt, struct proc *p)
1113 {
1114     int unit = PSM_UNIT(dev);
1115     struct psm_softc *sc;
1116     int command_byte;
1117     int err;
1118     int s;
1119 
1120     /* Validate unit number */
1121     if (unit >= NPSM)
1122         return (ENXIO);
1123 
1124     /* Get device data */
1125     sc = PSM_SOFTC(unit);
1126     if ((sc == NULL) || (sc->state & PSM_VALID) == 0)
1127 	/* the device is no longer valid/functioning */
1128         return (ENXIO);
1129 
1130     /* Disallow multiple opens */
1131     if (sc->state & PSM_OPEN)
1132         return (EBUSY);
1133 
1134     device_busy(devclass_get_device(psm_devclass, unit));
1135 
1136     /* Initialize state */
1137     sc->rsel.si_flags = 0;
1138     sc->rsel.si_pid = 0;
1139     sc->mode.level = sc->dflt_mode.level;
1140     sc->mode.protocol = sc->dflt_mode.protocol;
1141 
1142     /* flush the event queue */
1143     sc->queue.count = 0;
1144     sc->queue.head = 0;
1145     sc->queue.tail = 0;
1146     sc->status.flags = 0;
1147     sc->status.button = 0;
1148     sc->status.obutton = 0;
1149     sc->status.dx = 0;
1150     sc->status.dy = 0;
1151     sc->status.dz = 0;
1152     sc->button = 0;
1153 
1154     /* empty input buffer */
1155     bzero(sc->ipacket, sizeof(sc->ipacket));
1156     sc->inputbytes = 0;
1157 
1158     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1159     if (!kbdc_lock(sc->kbdc, TRUE))
1160 	return (EIO);
1161 
1162     /* save the current controller command byte */
1163     s = spltty();
1164     command_byte = get_controller_command_byte(sc->kbdc);
1165 
1166     /* enable the aux port and temporalily disable the keyboard */
1167     if ((command_byte == -1)
1168         || !set_controller_command_byte(sc->kbdc,
1169 	    kbdc_get_device_mask(sc->kbdc),
1170   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1171 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1172         /* CONTROLLER ERROR; do you know how to get out of this? */
1173         kbdc_lock(sc->kbdc, FALSE);
1174 	splx(s);
1175 	log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n",
1176 	    unit);
1177 	return (EIO);
1178     }
1179     /*
1180      * Now that the keyboard controller is told not to generate
1181      * the keyboard and mouse interrupts, call `splx()' to allow
1182      * the other tty interrupts. The clock interrupt may also occur,
1183      * but timeout routines will be blocked by the poll flag set
1184      * via `kbdc_lock()'
1185      */
1186     splx(s);
1187 
1188     /* enable the mouse device */
1189     err = doopen(unit, command_byte);
1190 
1191     /* done */
1192     if (err == 0)
1193         sc->state |= PSM_OPEN;
1194     kbdc_lock(sc->kbdc, FALSE);
1195     return (err);
1196 }
1197 
1198 static int
1199 psmclose(dev_t dev, int flag, int fmt, struct proc *p)
1200 {
1201     int unit = PSM_UNIT(dev);
1202     struct psm_softc *sc = PSM_SOFTC(unit);
1203     int stat[3];
1204     int command_byte;
1205     int s;
1206 
1207     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1208     if (!kbdc_lock(sc->kbdc, TRUE))
1209 	return (EIO);
1210 
1211     /* save the current controller command byte */
1212     s = spltty();
1213     command_byte = get_controller_command_byte(sc->kbdc);
1214     if (command_byte == -1) {
1215         kbdc_lock(sc->kbdc, FALSE);
1216 	splx(s);
1217 	return (EIO);
1218     }
1219 
1220     /* disable the aux interrupt and temporalily disable the keyboard */
1221     if (!set_controller_command_byte(sc->kbdc,
1222 	    kbdc_get_device_mask(sc->kbdc),
1223   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1224 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1225 	log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n",
1226 	    PSM_UNIT(dev));
1227 	/* CONTROLLER ERROR;
1228 	 * NOTE: we shall force our way through. Because the only
1229 	 * ill effect we shall see is that we may not be able
1230 	 * to read ACK from the mouse, and it doesn't matter much
1231 	 * so long as the mouse will accept the DISABLE command.
1232 	 */
1233     }
1234     splx(s);
1235 
1236     /* remove anything left in the output buffer */
1237     empty_aux_buffer(sc->kbdc, 10);
1238 
1239     /* disable the aux device, port and interrupt */
1240     if (sc->state & PSM_VALID) {
1241         if (!disable_aux_dev(sc->kbdc)) {
1242 	    /* MOUSE ERROR;
1243 	     * NOTE: we don't return error and continue, pretending
1244 	     * we have successfully disabled the device. It's OK because
1245 	     * the interrupt routine will discard any data from the mouse
1246 	     * hereafter.
1247 	     */
1248 	    log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n",
1249 	        PSM_UNIT(dev));
1250         }
1251 
1252         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1253             log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n",
1254 	        PSM_UNIT(dev));
1255     }
1256 
1257     if (!set_controller_command_byte(sc->kbdc,
1258 	    kbdc_get_device_mask(sc->kbdc),
1259 	    (command_byte & KBD_KBD_CONTROL_BITS)
1260 	        | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1261 	/* CONTROLLER ERROR;
1262 	 * we shall ignore this error; see the above comment.
1263 	 */
1264 	log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n",
1265 	    PSM_UNIT(dev));
1266     }
1267 
1268     /* remove anything left in the output buffer */
1269     empty_aux_buffer(sc->kbdc, 10);
1270 
1271     /* close is almost always successful */
1272     sc->state &= ~PSM_OPEN;
1273     kbdc_lock(sc->kbdc, FALSE);
1274     device_unbusy(devclass_get_device(psm_devclass, unit));
1275     return (0);
1276 }
1277 
1278 static int
1279 tame_mouse(struct psm_softc *sc, mousestatus_t *status, unsigned char *buf)
1280 {
1281     static unsigned char butmapps2[8] = {
1282         0,
1283         MOUSE_PS2_BUTTON1DOWN,
1284         MOUSE_PS2_BUTTON2DOWN,
1285         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1286         MOUSE_PS2_BUTTON3DOWN,
1287         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1288         MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1289         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1290     };
1291     static unsigned char butmapmsc[8] = {
1292         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1293         MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1294         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1295         MOUSE_MSC_BUTTON3UP,
1296         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1297         MOUSE_MSC_BUTTON2UP,
1298         MOUSE_MSC_BUTTON1UP,
1299         0,
1300     };
1301     int mapped;
1302     int i;
1303 
1304     if (sc->mode.level == PSM_LEVEL_BASE) {
1305         mapped = status->button & ~MOUSE_BUTTON4DOWN;
1306         if (status->button & MOUSE_BUTTON4DOWN)
1307 	    mapped |= MOUSE_BUTTON1DOWN;
1308         status->button = mapped;
1309         buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1310         i = max(min(status->dx, 255), -256);
1311 	if (i < 0)
1312 	    buf[0] |= MOUSE_PS2_XNEG;
1313         buf[1] = i;
1314         i = max(min(status->dy, 255), -256);
1315 	if (i < 0)
1316 	    buf[0] |= MOUSE_PS2_YNEG;
1317         buf[2] = i;
1318 	return MOUSE_PS2_PACKETSIZE;
1319     } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1320         buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS];
1321         i = max(min(status->dx, 255), -256);
1322         buf[1] = i >> 1;
1323         buf[3] = i - buf[1];
1324         i = max(min(status->dy, 255), -256);
1325         buf[2] = i >> 1;
1326         buf[4] = i - buf[2];
1327         i = max(min(status->dz, 127), -128);
1328         buf[5] = (i >> 1) & 0x7f;
1329         buf[6] = (i - (i >> 1)) & 0x7f;
1330         buf[7] = (~status->button >> 3) & 0x7f;
1331 	return MOUSE_SYS_PACKETSIZE;
1332     }
1333     return sc->inputbytes;;
1334 }
1335 
1336 static int
1337 psmread(dev_t dev, struct uio *uio, int flag)
1338 {
1339     register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1340     unsigned char buf[PSM_SMALLBUFSIZE];
1341     int error = 0;
1342     int s;
1343     int l;
1344 
1345     if ((sc->state & PSM_VALID) == 0)
1346 	return EIO;
1347 
1348     /* block until mouse activity occured */
1349     s = spltty();
1350     while (sc->queue.count <= 0) {
1351         if (PSM_NBLOCKIO(dev)) {
1352             splx(s);
1353             return EWOULDBLOCK;
1354         }
1355         sc->state |= PSM_ASLP;
1356         error = tsleep((caddr_t) sc, PZERO | PCATCH, "psmrea", 0);
1357         sc->state &= ~PSM_ASLP;
1358         if (error) {
1359             splx(s);
1360             return error;
1361         } else if ((sc->state & PSM_VALID) == 0) {
1362             /* the device disappeared! */
1363             splx(s);
1364             return EIO;
1365 	}
1366     }
1367     splx(s);
1368 
1369     /* copy data to the user land */
1370     while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1371         s = spltty();
1372 	l = min(sc->queue.count, uio->uio_resid);
1373 	if (l > sizeof(buf))
1374 	    l = sizeof(buf);
1375 	if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1376 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1377 		sizeof(sc->queue.buf) - sc->queue.head);
1378 	    bcopy(&sc->queue.buf[0],
1379 		&buf[sizeof(sc->queue.buf) - sc->queue.head],
1380 		l - (sizeof(sc->queue.buf) - sc->queue.head));
1381 	} else {
1382 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1383 	}
1384 	sc->queue.count -= l;
1385 	sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1386         splx(s);
1387         error = uiomove(buf, l, uio);
1388         if (error)
1389 	    break;
1390     }
1391 
1392     return error;
1393 }
1394 
1395 static int
1396 block_mouse_data(struct psm_softc *sc, int *c)
1397 {
1398     int s;
1399 
1400     if (!kbdc_lock(sc->kbdc, TRUE))
1401 	return EIO;
1402 
1403     s = spltty();
1404     *c = get_controller_command_byte(sc->kbdc);
1405     if ((*c == -1)
1406 	|| !set_controller_command_byte(sc->kbdc,
1407 	    kbdc_get_device_mask(sc->kbdc),
1408             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1409                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1410         /* this is CONTROLLER ERROR */
1411 	splx(s);
1412         kbdc_lock(sc->kbdc, FALSE);
1413 	return EIO;
1414     }
1415 
1416     /*
1417      * The device may be in the middle of status data transmission.
1418      * The transmission will be interrupted, thus, incomplete status
1419      * data must be discarded. Although the aux interrupt is disabled
1420      * at the keyboard controller level, at most one aux interrupt
1421      * may have already been pending and a data byte is in the
1422      * output buffer; throw it away. Note that the second argument
1423      * to `empty_aux_buffer()' is zero, so that the call will just
1424      * flush the internal queue.
1425      * `psmintr()' will be invoked after `splx()' if an interrupt is
1426      * pending; it will see no data and returns immediately.
1427      */
1428     empty_aux_buffer(sc->kbdc, 0);	/* flush the queue */
1429     read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
1430     sc->inputbytes = 0;
1431     splx(s);
1432 
1433     return 0;
1434 }
1435 
1436 static int
1437 unblock_mouse_data(struct psm_softc *sc, int c)
1438 {
1439     int error = 0;
1440 
1441     /*
1442      * We may have seen a part of status data during `set_mouse_XXX()'.
1443      * they have been queued; flush it.
1444      */
1445     empty_aux_buffer(sc->kbdc, 0);
1446 
1447     /* restore ports and interrupt */
1448     if (!set_controller_command_byte(sc->kbdc,
1449             kbdc_get_device_mask(sc->kbdc),
1450 	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1451         /* CONTROLLER ERROR; this is serious, we may have
1452          * been left with the inaccessible keyboard and
1453          * the disabled mouse interrupt.
1454          */
1455         error = EIO;
1456     }
1457 
1458     kbdc_lock(sc->kbdc, FALSE);
1459     return error;
1460 }
1461 
1462 static int
1463 psmioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1464 {
1465     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1466     mousemode_t mode;
1467     mousestatus_t status;
1468 #if (defined(MOUSE_GETVARS))
1469     mousevar_t *var;
1470 #endif
1471     mousedata_t *data;
1472     int stat[3];
1473     int command_byte;
1474     int error = 0;
1475     int s;
1476 
1477     /* Perform IOCTL command */
1478     switch (cmd) {
1479 
1480     case OLD_MOUSE_GETHWINFO:
1481 	s = spltty();
1482         ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1483         ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1484         ((old_mousehw_t *)addr)->type = sc->hw.type;
1485         ((old_mousehw_t *)addr)->hwid = sc->hw.hwid;
1486 	splx(s);
1487         break;
1488 
1489     case MOUSE_GETHWINFO:
1490 	s = spltty();
1491         *(mousehw_t *)addr = sc->hw;
1492 	if (sc->mode.level == PSM_LEVEL_BASE)
1493 	    ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1494 	splx(s);
1495         break;
1496 
1497     case OLD_MOUSE_GETMODE:
1498 	s = spltty();
1499 	switch (sc->mode.level) {
1500 	case PSM_LEVEL_BASE:
1501 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1502 	    break;
1503 	case PSM_LEVEL_STANDARD:
1504 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1505 	    break;
1506 	case PSM_LEVEL_NATIVE:
1507 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1508 	    break;
1509 	}
1510         ((old_mousemode_t *)addr)->rate = sc->mode.rate;
1511         ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1512         ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1513 	splx(s);
1514         break;
1515 
1516     case MOUSE_GETMODE:
1517 	s = spltty();
1518         *(mousemode_t *)addr = sc->mode;
1519         ((mousemode_t *)addr)->resolution =
1520 	    MOUSE_RES_LOW - sc->mode.resolution;
1521 	switch (sc->mode.level) {
1522 	case PSM_LEVEL_BASE:
1523 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1524 	    ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE;
1525 	    break;
1526 	case PSM_LEVEL_STANDARD:
1527 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1528 	    ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE;
1529 	    ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1530 	    ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
1531 	    break;
1532 	case PSM_LEVEL_NATIVE:
1533 	    /* FIXME: this isn't quite correct... XXX */
1534 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1535 	    break;
1536 	}
1537 	splx(s);
1538         break;
1539 
1540     case OLD_MOUSE_SETMODE:
1541     case MOUSE_SETMODE:
1542 	if (cmd == OLD_MOUSE_SETMODE) {
1543 	    mode.rate = ((old_mousemode_t *)addr)->rate;
1544 	    /*
1545 	     * resolution  old I/F   new I/F
1546 	     * default        0         0
1547 	     * low            1        -2
1548 	     * medium low     2        -3
1549 	     * medium high    3        -4
1550 	     * high           4        -5
1551 	     */
1552 	    if (((old_mousemode_t *)addr)->resolution > 0)
1553 	        mode.resolution = -((old_mousemode_t *)addr)->resolution - 1;
1554 	    mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor;
1555 	    mode.level = -1;
1556 	} else {
1557 	    mode = *(mousemode_t *)addr;
1558 	}
1559 
1560 	/* adjust and validate parameters. */
1561 	if (mode.rate > UCHAR_MAX)
1562 	    return EINVAL;
1563         if (mode.rate == 0)
1564             mode.rate = sc->dflt_mode.rate;
1565 	else if (mode.rate == -1)
1566 	    /* don't change the current setting */
1567 	    ;
1568 	else if (mode.rate < 0)
1569 	    return EINVAL;
1570 	if (mode.resolution >= UCHAR_MAX)
1571 	    return EINVAL;
1572 	if (mode.resolution >= 200)
1573 	    mode.resolution = MOUSE_RES_HIGH;
1574 	else if (mode.resolution >= 100)
1575 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1576 	else if (mode.resolution >= 50)
1577 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1578 	else if (mode.resolution > 0)
1579 	    mode.resolution = MOUSE_RES_LOW;
1580         if (mode.resolution == MOUSE_RES_DEFAULT)
1581             mode.resolution = sc->dflt_mode.resolution;
1582         else if (mode.resolution == -1)
1583 	    /* don't change the current setting */
1584 	    ;
1585         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1586             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1587 	if (mode.level == -1)
1588 	    /* don't change the current setting */
1589 	    mode.level = sc->mode.level;
1590 	else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX))
1591 	    return EINVAL;
1592         if (mode.accelfactor == -1)
1593 	    /* don't change the current setting */
1594 	    mode.accelfactor = sc->mode.accelfactor;
1595         else if (mode.accelfactor < 0)
1596 	    return EINVAL;
1597 
1598 	/* don't allow anybody to poll the keyboard controller */
1599 	error = block_mouse_data(sc, &command_byte);
1600 	if (error)
1601             return error;
1602 
1603         /* set mouse parameters */
1604 	if (mode.rate > 0)
1605 	    mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1606 	if (mode.resolution >= 0)
1607 	    mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1608 	set_mouse_scaling(sc->kbdc, 1);
1609 	get_mouse_status(sc->kbdc, stat, 0, 3);
1610 
1611         s = spltty();
1612     	sc->mode.rate = mode.rate;
1613     	sc->mode.resolution = mode.resolution;
1614     	sc->mode.accelfactor = mode.accelfactor;
1615     	sc->mode.level = mode.level;
1616         splx(s);
1617 
1618 	unblock_mouse_data(sc, command_byte);
1619         break;
1620 
1621     case MOUSE_GETLEVEL:
1622 	*(int *)addr = sc->mode.level;
1623         break;
1624 
1625     case MOUSE_SETLEVEL:
1626 	if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX))
1627 	    return EINVAL;
1628 	sc->mode.level = *(int *)addr;
1629         break;
1630 
1631     case MOUSE_GETSTATUS:
1632         s = spltty();
1633 	status = sc->status;
1634 	sc->status.flags = 0;
1635 	sc->status.obutton = sc->status.button;
1636 	sc->status.button = 0;
1637 	sc->status.dx = 0;
1638 	sc->status.dy = 0;
1639 	sc->status.dz = 0;
1640         splx(s);
1641         *(mousestatus_t *)addr = status;
1642         break;
1643 
1644 #if (defined(MOUSE_GETVARS))
1645     case MOUSE_GETVARS:
1646 	var = (mousevar_t *)addr;
1647 	bzero(var, sizeof(*var));
1648 	s = spltty();
1649         var->var[0] = MOUSE_VARS_PS2_SIG;
1650         var->var[1] = sc->config;
1651         var->var[2] = sc->flags;
1652 	splx(s);
1653         break;
1654 
1655     case MOUSE_SETVARS:
1656 	return ENODEV;
1657 #endif /* MOUSE_GETVARS */
1658 
1659     case MOUSE_READSTATE:
1660     case MOUSE_READDATA:
1661 	data = (mousedata_t *)addr;
1662 	if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
1663 	    return EINVAL;
1664 
1665 	error = block_mouse_data(sc, &command_byte);
1666 	if (error)
1667             return error;
1668         if ((data->len = get_mouse_status(sc->kbdc, data->buf,
1669 		(cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
1670             error = EIO;
1671 	unblock_mouse_data(sc, command_byte);
1672 	break;
1673 
1674 #if (defined(MOUSE_SETRESOLUTION))
1675     case MOUSE_SETRESOLUTION:
1676 	mode.resolution = *(int *)addr;
1677 	if (mode.resolution >= UCHAR_MAX)
1678 	    return EINVAL;
1679 	else if (mode.resolution >= 200)
1680 	    mode.resolution = MOUSE_RES_HIGH;
1681 	else if (mode.resolution >= 100)
1682 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1683 	else if (mode.resolution >= 50)
1684 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1685 	else if (mode.resolution > 0)
1686 	    mode.resolution = MOUSE_RES_LOW;
1687         if (mode.resolution == MOUSE_RES_DEFAULT)
1688             mode.resolution = sc->dflt_mode.resolution;
1689         else if (mode.resolution == -1)
1690 	    mode.resolution = sc->mode.resolution;
1691         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1692             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1693 
1694 	error = block_mouse_data(sc, &command_byte);
1695 	if (error)
1696             return error;
1697         sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1698 	if (sc->mode.resolution != mode.resolution)
1699 	    error = EIO;
1700 	unblock_mouse_data(sc, command_byte);
1701         break;
1702 #endif /* MOUSE_SETRESOLUTION */
1703 
1704 #if (defined(MOUSE_SETRATE))
1705     case MOUSE_SETRATE:
1706 	mode.rate = *(int *)addr;
1707 	if (mode.rate > UCHAR_MAX)
1708 	    return EINVAL;
1709         if (mode.rate == 0)
1710             mode.rate = sc->dflt_mode.rate;
1711 	else if (mode.rate < 0)
1712 	    mode.rate = sc->mode.rate;
1713 
1714 	error = block_mouse_data(sc, &command_byte);
1715 	if (error)
1716             return error;
1717         sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1718 	if (sc->mode.rate != mode.rate)
1719 	    error = EIO;
1720 	unblock_mouse_data(sc, command_byte);
1721         break;
1722 #endif /* MOUSE_SETRATE */
1723 
1724 #if (defined(MOUSE_SETSCALING))
1725     case MOUSE_SETSCALING:
1726 	if ((*(int *)addr <= 0) || (*(int *)addr > 2))
1727 	    return EINVAL;
1728 
1729 	error = block_mouse_data(sc, &command_byte);
1730 	if (error)
1731             return error;
1732         if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
1733 	    error = EIO;
1734 	unblock_mouse_data(sc, command_byte);
1735         break;
1736 #endif /* MOUSE_SETSCALING */
1737 
1738 #if (defined(MOUSE_GETHWID))
1739     case MOUSE_GETHWID:
1740 	error = block_mouse_data(sc, &command_byte);
1741 	if (error)
1742             return error;
1743         sc->hw.hwid = get_aux_id(sc->kbdc);
1744 	*(int *)addr = sc->hw.hwid;
1745 	unblock_mouse_data(sc, command_byte);
1746         break;
1747 #endif /* MOUSE_GETHWID */
1748 
1749     default:
1750 	return ENOTTY;
1751     }
1752 
1753     return error;
1754 }
1755 
1756 static void
1757 psmintr(void *arg)
1758 {
1759     /*
1760      * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
1761      * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
1762      */
1763     static int butmap[8] = {
1764         0,
1765 	MOUSE_BUTTON1DOWN,
1766 	MOUSE_BUTTON3DOWN,
1767 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1768 	MOUSE_BUTTON2DOWN,
1769 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1770 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1771         MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1772     };
1773     register struct psm_softc *sc = arg;
1774     mousestatus_t ms;
1775     int x, y, z;
1776     int c;
1777     int l;
1778 
1779     /* read until there is nothing to read */
1780     while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
1781 
1782         /* discard the byte if the device is not open */
1783         if ((sc->state & PSM_OPEN) == 0)
1784             continue;
1785 
1786         /*
1787 	 * Check sync bits. We check for overflow bits and the bit 3
1788 	 * for most mice. True, the code doesn't work if overflow
1789 	 * condition occurs. But we expect it rarely happens...
1790 	 */
1791 	if ((sc->inputbytes == 0)
1792 		&& ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1])) {
1793             log(LOG_DEBUG, "psmintr: out of sync (%04x != %04x).\n",
1794 		c & sc->mode.syncmask[0], sc->mode.syncmask[1]);
1795             continue;
1796 	}
1797 
1798         sc->ipacket[sc->inputbytes++] = c;
1799         if (sc->inputbytes < sc->mode.packetsize)
1800 	    continue;
1801 
1802 #if 0
1803         log(LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
1804 	    sc->ipacket[0], sc->ipacket[1], sc->ipacket[2],
1805 	    sc->ipacket[3], sc->ipacket[4], sc->ipacket[5]);
1806 #endif
1807 
1808 	c = sc->ipacket[0];
1809 
1810         /*
1811 	 * A kludge for Kensington device!
1812 	 * The MSB of the horizontal count appears to be stored in
1813 	 * a strange place. This kludge doesn't affect other mice
1814 	 * because the bit is the overflow bit which is, in most cases,
1815 	 * expected to be zero when we reach here. XXX
1816 	 */
1817         sc->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
1818 
1819         /* ignore the overflow bits... */
1820         x = (c & MOUSE_PS2_XNEG) ?  sc->ipacket[1] - 256 : sc->ipacket[1];
1821         y = (c & MOUSE_PS2_YNEG) ?  sc->ipacket[2] - 256 : sc->ipacket[2];
1822 	z = 0;
1823         ms.obutton = sc->button;		  /* previous button state */
1824         ms.button = butmap[c & MOUSE_PS2_BUTTONS];
1825 	/* `tapping' action */
1826 	if (sc->config & PSM_CONFIG_FORCETAP)
1827 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
1828 
1829 	switch (sc->hw.model) {
1830 
1831 	case MOUSE_MODEL_INTELLI:
1832 	case MOUSE_MODEL_NET:
1833 	    /* wheel data is in the fourth byte */
1834 	    z = (char)sc->ipacket[3];
1835 	    break;
1836 
1837 	case MOUSE_MODEL_MOUSEMANPLUS:
1838 	    if ((c & ~MOUSE_PS2_BUTTONS) == 0xc8) {
1839 		/* the extended data packet encodes button and wheel events */
1840 		x = y = 0;
1841 		z = (sc->ipacket[2] & MOUSE_PS2PLUS_ZNEG)
1842 		    ? (sc->ipacket[2] & 0x0f) - 16 : (sc->ipacket[2] & 0x0f);
1843 		ms.button |= (sc->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
1844 		    ? MOUSE_BUTTON4DOWN : 0;
1845 	    } else {
1846 		/* preserve button states */
1847 		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
1848 	    }
1849 	    break;
1850 
1851 	case MOUSE_MODEL_GLIDEPOINT:
1852 	    /* `tapping' action */
1853 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
1854 	    break;
1855 
1856 	case MOUSE_MODEL_NETSCROLL:
1857 	    /* three addtional bytes encode button and wheel events */
1858 	    ms.button |= (sc->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
1859 		? MOUSE_BUTTON4DOWN : 0;
1860 	    z = (sc->ipacket[3] & MOUSE_PS2_XNEG)
1861 		? sc->ipacket[4] - 256 : sc->ipacket[4];
1862 	    break;
1863 
1864 	case MOUSE_MODEL_THINK:
1865 	    /* the fourth button state in the first byte */
1866 	    ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
1867 	    break;
1868 
1869 	case MOUSE_MODEL_GENERIC:
1870 	default:
1871 	    break;
1872 	}
1873 
1874         /* scale values */
1875         if (sc->mode.accelfactor >= 1) {
1876             if (x != 0) {
1877                 x = x * x / sc->mode.accelfactor;
1878                 if (x == 0)
1879                     x = 1;
1880                 if (c & MOUSE_PS2_XNEG)
1881                     x = -x;
1882             }
1883             if (y != 0) {
1884                 y = y * y / sc->mode.accelfactor;
1885                 if (y == 0)
1886                     y = 1;
1887                 if (c & MOUSE_PS2_YNEG)
1888                     y = -y;
1889             }
1890         }
1891 
1892         ms.dx = x;
1893         ms.dy = y;
1894         ms.dz = z;
1895         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0)
1896 	    | (ms.obutton ^ ms.button);
1897 
1898 	if (sc->mode.level < PSM_LEVEL_NATIVE)
1899 	    sc->inputbytes = tame_mouse(sc, &ms, sc->ipacket);
1900 
1901         sc->status.flags |= ms.flags;
1902         sc->status.dx += ms.dx;
1903         sc->status.dy += ms.dy;
1904         sc->status.dz += ms.dz;
1905         sc->status.button = ms.button;
1906         sc->button = ms.button;
1907 
1908         /* queue data */
1909         if (sc->queue.count + sc->inputbytes < sizeof(sc->queue.buf)) {
1910 	    l = min(sc->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
1911 	    bcopy(&sc->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
1912 	    if (sc->inputbytes > l)
1913 	        bcopy(&sc->ipacket[l], &sc->queue.buf[0], sc->inputbytes - l);
1914             sc->queue.tail =
1915 		(sc->queue.tail + sc->inputbytes) % sizeof(sc->queue.buf);
1916             sc->queue.count += sc->inputbytes;
1917 	}
1918         sc->inputbytes = 0;
1919 
1920         if (sc->state & PSM_ASLP) {
1921             sc->state &= ~PSM_ASLP;
1922             wakeup((caddr_t) sc);
1923     	}
1924         selwakeup(&sc->rsel);
1925     }
1926 }
1927 
1928 static int
1929 psmpoll(dev_t dev, int events, struct proc *p)
1930 {
1931     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1932     int s;
1933     int revents = 0;
1934 
1935     /* Return true if a mouse event available */
1936     s = spltty();
1937     if (events & (POLLIN | POLLRDNORM)) {
1938 	if (sc->queue.count > 0)
1939 	    revents |= events & (POLLIN | POLLRDNORM);
1940 	else
1941 	    selrecord(p, &sc->rsel);
1942     }
1943     splx(s);
1944 
1945     return (revents);
1946 }
1947 
1948 /* vendor/model specific routines */
1949 
1950 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
1951 {
1952     if (set_mouse_resolution(kbdc, res) != res)
1953         return FALSE;
1954     if (set_mouse_scaling(kbdc, scale)
1955 	&& set_mouse_scaling(kbdc, scale)
1956 	&& set_mouse_scaling(kbdc, scale)
1957 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3))
1958 	return TRUE;
1959     return FALSE;
1960 }
1961 
1962 #if notyet
1963 /* Logitech MouseMan Cordless II */
1964 static int
1965 enable_lcordless(struct psm_softc *sc)
1966 {
1967     int status[3];
1968     int ch;
1969 
1970     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
1971         return FALSE;
1972     if (status[1] == PSMD_RES_HIGH)
1973 	return FALSE;
1974     ch = (status[0] & 0x07) - 1;	/* channel # */
1975     if ((ch <= 0) || (ch > 4))
1976 	return FALSE;
1977     /*
1978      * status[1]: always one?
1979      * status[2]: battery status? (0-100)
1980      */
1981     return TRUE;
1982 }
1983 #endif /* notyet */
1984 
1985 /* Genius NetScroll Mouse */
1986 static int
1987 enable_groller(struct psm_softc *sc)
1988 {
1989     int status[3];
1990 
1991     /*
1992      * The special sequence to enable the fourth button and the
1993      * roller. Immediately after this sequence check status bytes.
1994      * if the mouse is NetScroll, the second and the third bytes are
1995      * '3' and 'D'.
1996      */
1997 
1998     /*
1999      * If the mouse is an ordinary PS/2 mouse, the status bytes should
2000      * look like the following.
2001      *
2002      * byte 1 bit 7 always 0
2003      *        bit 6 stream mode (0)
2004      *        bit 5 disabled (0)
2005      *        bit 4 1:1 scaling (0)
2006      *        bit 3 always 0
2007      *        bit 0-2 button status
2008      * byte 2 resolution (PSMD_RES_HIGH)
2009      * byte 3 report rate (?)
2010      */
2011 
2012     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2013         return FALSE;
2014     if ((status[1] != '3') || (status[2] != 'D'))
2015         return FALSE;
2016     /* FIXME!! */
2017     sc->hw.buttons = get_mouse_buttons(sc->kbdc);
2018     sc->hw.buttons = 4;
2019     return TRUE;
2020 }
2021 
2022 /* Genius NetMouse/NetMouse Pro */
2023 static int
2024 enable_gmouse(struct psm_softc *sc)
2025 {
2026     int status[3];
2027 
2028     /*
2029      * The special sequence to enable the middle, "rubber" button.
2030      * Immediately after this sequence check status bytes.
2031      * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
2032      * the second and the third bytes are '3' and 'U'.
2033      * NOTE: NetMouse reports that it has three buttons although it has
2034      * two buttons and a rubber button. NetMouse Pro and MIE Mouse
2035      * say they have three buttons too and they do have a button on the
2036      * side...
2037      */
2038     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2039         return FALSE;
2040     if ((status[1] != '3') || (status[2] != 'U'))
2041         return FALSE;
2042     return TRUE;
2043 }
2044 
2045 /* ALPS GlidePoint */
2046 static int
2047 enable_aglide(struct psm_softc *sc)
2048 {
2049     int status[3];
2050 
2051     /*
2052      * The special sequence to obtain ALPS GlidePoint specific
2053      * information. Immediately after this sequence, status bytes will
2054      * contain something interesting.
2055      * NOTE: ALPS produces several models of GlidePoint. Some of those
2056      * do not respond to this sequence, thus, cannot be detected this way.
2057      */
2058     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
2059         return FALSE;
2060     if ((status[0] & 0x10) || (status[1] == PSMD_RES_LOW))
2061         return FALSE;
2062     return TRUE;
2063 }
2064 
2065 /* Kensington ThinkingMouse/Trackball */
2066 static int
2067 enable_kmouse(struct psm_softc *sc)
2068 {
2069     static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
2070     KBDC kbdc = sc->kbdc;
2071     int status[3];
2072     int id1;
2073     int id2;
2074     int i;
2075 
2076     id1 = get_aux_id(kbdc);
2077     if (set_mouse_sampling_rate(kbdc, 10) != 10)
2078 	return FALSE;
2079     /*
2080      * The device is now in the native mode? It returns a different
2081      * ID value...
2082      */
2083     id2 = get_aux_id(kbdc);
2084     if ((id1 == id2) || (id2 != 2))
2085 	return FALSE;
2086 
2087     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
2088         return FALSE;
2089 #if PSM_DEBUG >= 2
2090     /* at this point, resolution is LOW, sampling rate is 10/sec */
2091     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2092         return FALSE;
2093 #endif
2094 
2095     /*
2096      * The special sequence to enable the third and fourth buttons.
2097      * Otherwise they behave like the first and second buttons.
2098      */
2099     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2100         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2101 	    return FALSE;
2102     }
2103 
2104     /*
2105      * At this point, the device is using default resolution and
2106      * sampling rate for the native mode.
2107      */
2108     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2109         return FALSE;
2110     if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
2111         return FALSE;
2112 
2113     /* the device appears be enabled by this sequence, diable it for now */
2114     disable_aux_dev(kbdc);
2115     empty_aux_buffer(kbdc, 5);
2116 
2117     return TRUE;
2118 }
2119 
2120 /* Logitech MouseMan+/FirstMouse+ */
2121 static int
2122 enable_mmanplus(struct psm_softc *sc)
2123 {
2124     static char res[] = {
2125 	-1, PSMD_RES_LOW, PSMD_RES_HIGH, PSMD_RES_MEDIUM_HIGH,
2126 	PSMD_RES_MEDIUM_LOW, -1, PSMD_RES_HIGH, PSMD_RES_MEDIUM_LOW,
2127 	PSMD_RES_MEDIUM_HIGH, PSMD_RES_HIGH,
2128     };
2129     KBDC kbdc = sc->kbdc;
2130     int data[3];
2131     int i;
2132 
2133     /* the special sequence to enable the fourth button and the roller. */
2134     for (i = 0; i < sizeof(res)/sizeof(res[0]); ++i) {
2135 	if (res[i] < 0) {
2136 	    if (!set_mouse_scaling(kbdc, 1))
2137 		return FALSE;
2138 	} else {
2139 	    if (set_mouse_resolution(kbdc, res[i]) != res[i])
2140 		return FALSE;
2141 	}
2142     }
2143 
2144     if (get_mouse_status(kbdc, data, 1, 3) < 3)
2145         return FALSE;
2146 
2147     /*
2148      * MouseMan+ and FirstMouse+ return following data.
2149      *
2150      * byte 1 0xc8
2151      * byte 2 ?? (MouseMan+:0xc2, FirstMouse+:0xc6)
2152      * byte 3 model ID? MouseMan+:0x50, FirstMouse+:0x51
2153      */
2154     if ((data[0] & ~MOUSE_PS2_BUTTONS) != 0xc8)
2155         return FALSE;
2156 
2157     /*
2158      * MouseMan+ (or FirstMouse+) is now in its native mode, in which
2159      * the wheel and the fourth button events are encoded in the
2160      * special data packet. The mouse may be put in the IntelliMouse mode
2161      * if it is initialized by the IntelliMouse's method.
2162      */
2163     return TRUE;
2164 }
2165 
2166 /* MS IntelliMouse */
2167 static int
2168 enable_msintelli(struct psm_softc *sc)
2169 {
2170     /*
2171      * Logitech MouseMan+ and FirstMouse+ will also respond to this
2172      * probe routine and act like IntelliMouse.
2173      */
2174 
2175     static unsigned char rate[] = { 200, 100, 80, };
2176     KBDC kbdc = sc->kbdc;
2177     int id;
2178     int i;
2179 
2180     /* the special sequence to enable the third button and the roller. */
2181     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2182         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2183 	    return FALSE;
2184     }
2185     /* the device will give the genuine ID only after the above sequence */
2186     id = get_aux_id(kbdc);
2187     if (id != PSM_INTELLI_ID)
2188 	return FALSE;
2189 
2190     sc->hw.hwid = id;
2191     sc->hw.buttons = 3;
2192 
2193     return TRUE;
2194 }
2195 
2196 #ifdef PSM_HOOKAPM
2197 static int
2198 psmresume(void *dummy)
2199 {
2200     struct psm_softc *sc = PSM_SOFTC((int)dummy);
2201     int unit = (int)dummy;
2202     int err = 0;
2203     int s;
2204     int c;
2205 
2206     if (verbose >= 2)
2207         log(LOG_NOTICE, "psm%d: APM resume hook called.\n", unit);
2208 
2209     /* don't let anybody mess with the aux device */
2210     if (!kbdc_lock(sc->kbdc, TRUE))
2211 	return (EIO);
2212     s = spltty();
2213 
2214     /* save the current controller command byte */
2215     empty_both_buffers(sc->kbdc, 10);
2216     c = get_controller_command_byte(sc->kbdc);
2217     if (verbose >= 2)
2218         log(LOG_DEBUG, "psm%d: current command byte: %04x (psmresume).\n",
2219 	    unit, c);
2220 
2221     /* enable the aux port but disable the aux interrupt and the keyboard */
2222     if ((c == -1) || !set_controller_command_byte(sc->kbdc,
2223 	    kbdc_get_device_mask(sc->kbdc),
2224   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
2225 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2226         /* CONTROLLER ERROR */
2227 	splx(s);
2228         kbdc_lock(sc->kbdc, FALSE);
2229 	log(LOG_ERR, "psm%d: unable to set the command byte (psmresume).\n",
2230 	    unit);
2231 	return (EIO);
2232     }
2233 
2234     /* flush any data */
2235     if (sc->state & PSM_VALID) {
2236 	disable_aux_dev(sc->kbdc);	/* this may fail; but never mind... */
2237 	empty_aux_buffer(sc->kbdc, 10);
2238     }
2239     sc->inputbytes = 0;
2240 
2241 #ifdef PSM_RESETAFTERSUSPEND
2242     /* try to detect the aux device; are you still there? */
2243     if (reinitialize(unit, &sc->mode)) {
2244 	/* yes */
2245 	sc->state |= PSM_VALID;
2246     } else {
2247 	/* the device has gone! */
2248         restore_controller(sc->kbdc, c);
2249 	sc->state &= ~PSM_VALID;
2250 	log(LOG_ERR, "psm%d: the aux device has gone! (psmresume).\n",
2251 	    unit);
2252 	err = ENXIO;
2253     }
2254 #endif /* PSM_RESETAFTERSUSPEND */
2255     splx(s);
2256 
2257     /* restore the driver state */
2258     if ((sc->state & PSM_OPEN) && (err == 0)) {
2259         /* enable the aux device and the port again */
2260 	err = doopen(unit, c);
2261 	if (err != 0)
2262 	    log(LOG_ERR, "psm%d: failed to enable the device (psmresume).\n",
2263 		unit);
2264     } else {
2265         /* restore the keyboard port and disable the aux port */
2266         if (!set_controller_command_byte(sc->kbdc,
2267                 kbdc_get_device_mask(sc->kbdc),
2268                 (c & KBD_KBD_CONTROL_BITS)
2269                     | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2270             /* CONTROLLER ERROR */
2271             log(LOG_ERR, "psm%d: failed to disable the aux port (psmresume).\n",
2272                 unit);
2273             err = EIO;
2274 	}
2275     }
2276 
2277     /* done */
2278     kbdc_lock(sc->kbdc, FALSE);
2279     if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
2280 	/*
2281 	 * Release the blocked process; it must be notified that the device
2282 	 * cannot be accessed anymore.
2283 	 */
2284         sc->state &= ~PSM_ASLP;
2285         wakeup((caddr_t)sc);
2286     }
2287 
2288     if (verbose >= 2)
2289         log(LOG_DEBUG, "psm%d: APM resume hook exiting.\n", unit);
2290 
2291     return (err);
2292 }
2293 #endif /* PSM_HOOKAPM */
2294 
2295 DEV_DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass,
2296 		   CDEV_MAJOR, NOMAJ, psm_cdevsw, 0, 0);
2297 
2298 #endif /* NPSM > 0 */
2299