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