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