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