psm.c revision 66229
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 66229 2000-09-22 08:40:05Z jhb $
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	((sizeof(vendortype) / sizeof(*vendortype)) - 1)
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 *)(uintptr_t)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, (int)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 *)(uintptr_t)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    int s;
1831
1832    unit = (int)(uintptr_t)arg;
1833    sc = devclass_get_softc(psm_devclass, unit);
1834    s = spltty();
1835    if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
1836	if (verbose >= 4)
1837	    log(LOG_DEBUG, "psm%d: lost interrupt?\n", unit);
1838	psmintr(sc);
1839	kbdc_lock(sc->kbdc, FALSE);
1840    }
1841    sc->watchdog = TRUE;
1842    splx(s);
1843    sc->callout = timeout(psmtimeout, (void *)(uintptr_t)unit, hz);
1844}
1845
1846static void
1847psmintr(void *arg)
1848{
1849    /*
1850     * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
1851     * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
1852     */
1853    static int butmap[8] = {
1854        0,
1855	MOUSE_BUTTON1DOWN,
1856	MOUSE_BUTTON3DOWN,
1857	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1858	MOUSE_BUTTON2DOWN,
1859	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1860	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1861        MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1862    };
1863    static int butmap_versapad[8] = {
1864	0,
1865	MOUSE_BUTTON3DOWN,
1866	0,
1867	MOUSE_BUTTON3DOWN,
1868	MOUSE_BUTTON1DOWN,
1869	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1870	MOUSE_BUTTON1DOWN,
1871	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
1872    };
1873    register struct psm_softc *sc = arg;
1874    mousestatus_t ms;
1875    int x, y, z;
1876    int c;
1877    int l;
1878    int x0, y0;
1879
1880    /* read until there is nothing to read */
1881    while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
1882
1883        /* discard the byte if the device is not open */
1884        if ((sc->state & PSM_OPEN) == 0)
1885            continue;
1886
1887        sc->ipacket[sc->inputbytes++] = c;
1888        if (sc->inputbytes < sc->mode.packetsize)
1889	    continue;
1890
1891#if 0
1892        log(LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
1893	    sc->ipacket[0], sc->ipacket[1], sc->ipacket[2],
1894	    sc->ipacket[3], sc->ipacket[4], sc->ipacket[5]);
1895#endif
1896
1897	c = sc->ipacket[0];
1898
1899	if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
1900            log(LOG_DEBUG, "psmintr: out of sync (%04x != %04x).\n",
1901		c & sc->mode.syncmask[0], sc->mode.syncmask[1]);
1902	    sc->inputbytes = 0;
1903            continue;
1904	}
1905
1906	/*
1907	 * A kludge for Kensington device!
1908	 * The MSB of the horizontal count appears to be stored in
1909	 * a strange place.
1910	 */
1911	if (sc->hw.model == MOUSE_MODEL_THINK)
1912	    sc->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
1913
1914        /* ignore the overflow bits... */
1915        x = (c & MOUSE_PS2_XNEG) ?  sc->ipacket[1] - 256 : sc->ipacket[1];
1916        y = (c & MOUSE_PS2_YNEG) ?  sc->ipacket[2] - 256 : sc->ipacket[2];
1917	z = 0;
1918        ms.obutton = sc->button;		  /* previous button state */
1919        ms.button = butmap[c & MOUSE_PS2_BUTTONS];
1920	/* `tapping' action */
1921	if (sc->config & PSM_CONFIG_FORCETAP)
1922	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
1923
1924	switch (sc->hw.model) {
1925
1926	case MOUSE_MODEL_EXPLORER:
1927	    /*
1928	     *          b7 b6 b5 b4 b3 b2 b1 b0
1929	     * byte 1:  oy ox sy sx 1  M  R  L
1930	     * byte 2:  x  x  x  x  x  x  x  x
1931	     * byte 3:  y  y  y  y  y  y  y  y
1932	     * byte 4:  *  *  S2 S1 s  d2 d1 d0
1933	     *
1934	     * L, M, R, S1, S2: left, middle, right and side buttons
1935	     * s: wheel data sign bit
1936	     * d2-d0: wheel data
1937	     */
1938	    z = (sc->ipacket[3] & MOUSE_EXPLORER_ZNEG)
1939		? (sc->ipacket[3] & 0x0f) - 16 : (sc->ipacket[3] & 0x0f);
1940	    ms.button |= (sc->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN)
1941		? MOUSE_BUTTON4DOWN : 0;
1942	    ms.button |= (sc->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN)
1943		? MOUSE_BUTTON5DOWN : 0;
1944	    break;
1945
1946	case MOUSE_MODEL_INTELLI:
1947	case MOUSE_MODEL_NET:
1948	    /* wheel data is in the fourth byte */
1949	    z = (char)sc->ipacket[3];
1950	    /* some mice may send 7 when there is no Z movement?! XXX */
1951	    if ((z >= 7) || (z <= -7))
1952		z = 0;
1953	    /* some compatible mice have additional buttons */
1954	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN)
1955		? MOUSE_BUTTON4DOWN : 0;
1956	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN)
1957		? MOUSE_BUTTON5DOWN : 0;
1958	    break;
1959
1960	case MOUSE_MODEL_MOUSEMANPLUS:
1961	    /*
1962	     * PS2++ protocl packet
1963	     *
1964	     *          b7 b6 b5 b4 b3 b2 b1 b0
1965	     * byte 1:  *  1  p3 p2 1  *  *  *
1966	     * byte 2:  c1 c2 p1 p0 d1 d0 1  0
1967	     *
1968	     * p3-p0: packet type
1969	     * c1, c2: c1 & c2 == 1, if p2 == 0
1970	     *         c1 & c2 == 0, if p2 == 1
1971	     *
1972	     * packet type: 0 (device type)
1973	     * See comments in enable_mmanplus() below.
1974	     *
1975	     * packet type: 1 (wheel data)
1976	     *
1977	     *          b7 b6 b5 b4 b3 b2 b1 b0
1978	     * byte 3:  h  *  B5 B4 s  d2 d1 d0
1979	     *
1980	     * h: 1, if horizontal roller data
1981	     *    0, if vertical roller data
1982	     * B4, B5: button 4 and 5
1983	     * s: sign bit
1984	     * d2-d0: roller data
1985	     *
1986	     * packet type: 2 (reserved)
1987	     */
1988	    if (((c & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
1989		    && (abs(x) > 191)
1990		    && MOUSE_PS2PLUS_CHECKBITS(sc->ipacket)) {
1991		/* the extended data packet encodes button and wheel events */
1992		switch (MOUSE_PS2PLUS_PACKET_TYPE(sc->ipacket)) {
1993		case 1:
1994		    /* wheel data packet */
1995		    x = y = 0;
1996		    if (sc->ipacket[2] & 0x80) {
1997			/* horizontal roller count - ignore it XXX*/
1998		    } else {
1999			/* vertical roller count */
2000			z = (sc->ipacket[2] & MOUSE_PS2PLUS_ZNEG)
2001			    ? (sc->ipacket[2] & 0x0f) - 16
2002			    : (sc->ipacket[2] & 0x0f);
2003		    }
2004		    ms.button |= (sc->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
2005			? MOUSE_BUTTON4DOWN : 0;
2006		    ms.button |= (sc->ipacket[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
2007			? MOUSE_BUTTON5DOWN : 0;
2008		    break;
2009		case 2:
2010		    /* this packet type is reserved by Logitech... */
2011		    /*
2012		     * IBM ScrollPoint Mouse uses this packet type to
2013		     * encode both vertical and horizontal scroll movement.
2014		     */
2015		    x = y = 0;
2016		    /* horizontal count */
2017		    if (sc->ipacket[2] & 0x0f)
2018			z = (sc->ipacket[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
2019		    /* vertical count */
2020		    if (sc->ipacket[2] & 0xf0)
2021			z = (sc->ipacket[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
2022#if 0
2023		    /* vertical count */
2024		    z = (sc->ipacket[2] & MOUSE_SPOINT_ZNEG)
2025			? ((sc->ipacket[2] >> 4) & 0x0f) - 16
2026			: ((sc->ipacket[2] >> 4) & 0x0f);
2027		    /* horizontal count */
2028		    w = (sc->ipacket[2] & MOUSE_SPOINT_WNEG)
2029			? (sc->ipacket[2] & 0x0f) - 16
2030			: (sc->ipacket[2] & 0x0f);
2031#endif
2032		    break;
2033		case 0:
2034		    /* device type packet - shouldn't happen */
2035		    /* FALL THROUGH */
2036		default:
2037		    x = y = 0;
2038		    ms.button = ms.obutton;
2039		    if (bootverbose)
2040			log(LOG_DEBUG, "psmintr: unknown PS2++ packet type %d: "
2041				       "0x%02x 0x%02x 0x%02x\n",
2042			    MOUSE_PS2PLUS_PACKET_TYPE(sc->ipacket),
2043			    sc->ipacket[0], sc->ipacket[1], sc->ipacket[2]);
2044		    break;
2045		}
2046	    } else {
2047		/* preserve button states */
2048		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2049	    }
2050	    break;
2051
2052	case MOUSE_MODEL_GLIDEPOINT:
2053	    /* `tapping' action */
2054	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2055	    break;
2056
2057	case MOUSE_MODEL_NETSCROLL:
2058	    /* three addtional bytes encode buttons and wheel events */
2059	    ms.button |= (sc->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
2060		? MOUSE_BUTTON4DOWN : 0;
2061	    ms.button |= (sc->ipacket[3] & MOUSE_PS2_BUTTON1DOWN)
2062		? MOUSE_BUTTON5DOWN : 0;
2063	    z = (sc->ipacket[3] & MOUSE_PS2_XNEG)
2064		? sc->ipacket[4] - 256 : sc->ipacket[4];
2065	    break;
2066
2067	case MOUSE_MODEL_THINK:
2068	    /* the fourth button state in the first byte */
2069	    ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
2070	    break;
2071
2072	case MOUSE_MODEL_VERSAPAD:
2073	    /* VersaPad PS/2 absolute mode message format
2074	     *
2075	     * [packet1]     7   6   5   4   3   2   1   0(LSB)
2076	     *  ipacket[0]:  1   1   0   A   1   L   T   R
2077	     *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
2078	     *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
2079	     *  ipacket[3]:  1   1   1   A   1   L   T   R
2080	     *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
2081	     *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
2082	     *
2083	     * [note]
2084	     *  R: right physical mouse button (1=on)
2085	     *  T: touch pad virtual button (1=tapping)
2086	     *  L: left physical mouse button (1=on)
2087	     *  A: position data is valid (1=valid)
2088	     *  H: horizontal data (12bit signed integer. H11 is sign bit.)
2089	     *  V: vertical data (12bit signed integer. V11 is sign bit.)
2090	     *  P: pressure data
2091	     *
2092	     * Tapping is mapped to MOUSE_BUTTON4.
2093	     */
2094	    ms.button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
2095	    ms.button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2096	    x = y = 0;
2097	    if (c & MOUSE_PS2VERSA_IN_USE) {
2098		x0 = sc->ipacket[1] | (((sc->ipacket[4]) & 0x0f) << 8);
2099		y0 = sc->ipacket[2] | (((sc->ipacket[4]) & 0xf0) << 4);
2100		if (x0 & 0x800)
2101		    x0 -= 0x1000;
2102		if (y0 & 0x800)
2103		    y0 -= 0x1000;
2104		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2105		    x = sc->xold - x0;
2106		    y = y0 - sc->yold;
2107		    if (x < 0)	/* XXX */
2108			x++;
2109		    else if (x)
2110			x--;
2111		    if (y < 0)
2112			y++;
2113		    else if (y)
2114			y--;
2115		} else {
2116		    sc->flags |= PSM_FLAGS_FINGERDOWN;
2117		}
2118		sc->xold = x0;
2119		sc->yold = y0;
2120	    } else {
2121		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2122	    }
2123	    c = ((x < 0) ? MOUSE_PS2_XNEG : 0)
2124		| ((y < 0) ? MOUSE_PS2_YNEG : 0);
2125	    break;
2126
2127	case MOUSE_MODEL_4D:
2128	    /*
2129	     *          b7 b6 b5 b4 b3 b2 b1 b0
2130	     * byte 1:  s2 d2 s1 d1 1  M  R  L
2131	     * byte 2:  sx x  x  x  x  x  x  x
2132	     * byte 3:  sy y  y  y  y  y  y  y
2133	     *
2134	     * s1: wheel 1 direction
2135	     * d1: wheel 1 data
2136	     * s2: wheel 2 direction
2137	     * d2: wheel 2 data
2138	     */
2139	    x = (sc->ipacket[1] & 0x80) ? sc->ipacket[1] - 256 : sc->ipacket[1];
2140	    y = (sc->ipacket[2] & 0x80) ? sc->ipacket[2] - 256 : sc->ipacket[2];
2141	    switch (c & MOUSE_4D_WHEELBITS) {
2142	    case 0x10:
2143		z = 1;
2144		break;
2145	    case 0x30:
2146		z = -1;
2147		break;
2148	    case 0x40:	/* 2nd wheel turning right XXX */
2149		z = 2;
2150		break;
2151	    case 0xc0:	/* 2nd wheel turning left XXX */
2152		z = -2;
2153		break;
2154	    }
2155	    break;
2156
2157	case MOUSE_MODEL_4DPLUS:
2158	    if ((x < 16 - 256) && (y < 16 - 256)) {
2159		/*
2160		 *          b7 b6 b5 b4 b3 b2 b1 b0
2161		 * byte 1:  0  0  1  1  1  M  R  L
2162		 * byte 2:  0  0  0  0  1  0  0  0
2163		 * byte 3:  0  0  0  0  S  s  d1 d0
2164		 *
2165		 * L, M, R, S: left, middle, right and side buttons
2166		 * s: wheel data sign bit
2167		 * d1-d0: wheel data
2168		 */
2169		x = y = 0;
2170		if (sc->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2171		    ms.button |= MOUSE_BUTTON4DOWN;
2172		z = (sc->ipacket[2] & MOUSE_4DPLUS_ZNEG)
2173			? ((sc->ipacket[2] & 0x07) - 8)
2174			: (sc->ipacket[2] & 0x07) ;
2175	    } else {
2176		/* preserve previous button states */
2177		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2178	    }
2179	    break;
2180
2181	case MOUSE_MODEL_GENERIC:
2182	default:
2183	    break;
2184	}
2185
2186        /* scale values */
2187        if (sc->mode.accelfactor >= 1) {
2188            if (x != 0) {
2189                x = x * x / sc->mode.accelfactor;
2190                if (x == 0)
2191                    x = 1;
2192                if (c & MOUSE_PS2_XNEG)
2193                    x = -x;
2194            }
2195            if (y != 0) {
2196                y = y * y / sc->mode.accelfactor;
2197                if (y == 0)
2198                    y = 1;
2199                if (c & MOUSE_PS2_YNEG)
2200                    y = -y;
2201            }
2202        }
2203
2204        ms.dx = x;
2205        ms.dy = y;
2206        ms.dz = z;
2207        ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0)
2208	    | (ms.obutton ^ ms.button);
2209
2210	if (sc->mode.level < PSM_LEVEL_NATIVE)
2211	    sc->inputbytes = tame_mouse(sc, &ms, sc->ipacket);
2212
2213        sc->status.flags |= ms.flags;
2214        sc->status.dx += ms.dx;
2215        sc->status.dy += ms.dy;
2216        sc->status.dz += ms.dz;
2217        sc->status.button = ms.button;
2218        sc->button = ms.button;
2219
2220	sc->watchdog = FALSE;
2221
2222        /* queue data */
2223        if (sc->queue.count + sc->inputbytes < sizeof(sc->queue.buf)) {
2224	    l = min(sc->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
2225	    bcopy(&sc->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
2226	    if (sc->inputbytes > l)
2227	        bcopy(&sc->ipacket[l], &sc->queue.buf[0], sc->inputbytes - l);
2228            sc->queue.tail =
2229		(sc->queue.tail + sc->inputbytes) % sizeof(sc->queue.buf);
2230            sc->queue.count += sc->inputbytes;
2231	}
2232        sc->inputbytes = 0;
2233
2234        if (sc->state & PSM_ASLP) {
2235            sc->state &= ~PSM_ASLP;
2236            wakeup((caddr_t) sc);
2237    	}
2238        selwakeup(&sc->rsel);
2239    }
2240}
2241
2242static int
2243psmpoll(dev_t dev, int events, struct proc *p)
2244{
2245    struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
2246    int s;
2247    int revents = 0;
2248
2249    /* Return true if a mouse event available */
2250    s = spltty();
2251    if (events & (POLLIN | POLLRDNORM)) {
2252	if (sc->queue.count > 0)
2253	    revents |= events & (POLLIN | POLLRDNORM);
2254	else
2255	    selrecord(p, &sc->rsel);
2256    }
2257    splx(s);
2258
2259    return (revents);
2260}
2261
2262/* vendor/model specific routines */
2263
2264static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
2265{
2266    if (set_mouse_resolution(kbdc, res) != res)
2267        return FALSE;
2268    if (set_mouse_scaling(kbdc, scale)
2269	&& set_mouse_scaling(kbdc, scale)
2270	&& set_mouse_scaling(kbdc, scale)
2271	&& (get_mouse_status(kbdc, status, 0, 3) >= 3))
2272	return TRUE;
2273    return FALSE;
2274}
2275
2276#if notyet
2277/* Logitech MouseMan Cordless II */
2278static int
2279enable_lcordless(struct psm_softc *sc)
2280{
2281    int status[3];
2282    int ch;
2283
2284    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
2285        return FALSE;
2286    if (status[1] == PSMD_RES_HIGH)
2287	return FALSE;
2288    ch = (status[0] & 0x07) - 1;	/* channel # */
2289    if ((ch <= 0) || (ch > 4))
2290	return FALSE;
2291    /*
2292     * status[1]: always one?
2293     * status[2]: battery status? (0-100)
2294     */
2295    return TRUE;
2296}
2297#endif /* notyet */
2298
2299/* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
2300static int
2301enable_groller(struct psm_softc *sc)
2302{
2303    int status[3];
2304
2305    /*
2306     * The special sequence to enable the fourth button and the
2307     * roller. Immediately after this sequence check status bytes.
2308     * if the mouse is NetScroll, the second and the third bytes are
2309     * '3' and 'D'.
2310     */
2311
2312    /*
2313     * If the mouse is an ordinary PS/2 mouse, the status bytes should
2314     * look like the following.
2315     *
2316     * byte 1 bit 7 always 0
2317     *        bit 6 stream mode (0)
2318     *        bit 5 disabled (0)
2319     *        bit 4 1:1 scaling (0)
2320     *        bit 3 always 0
2321     *        bit 0-2 button status
2322     * byte 2 resolution (PSMD_RES_HIGH)
2323     * byte 3 report rate (?)
2324     */
2325
2326    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2327        return FALSE;
2328    if ((status[1] != '3') || (status[2] != 'D'))
2329        return FALSE;
2330    /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
2331    sc->hw.buttons = 4;
2332    return TRUE;
2333}
2334
2335/* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
2336static int
2337enable_gmouse(struct psm_softc *sc)
2338{
2339    int status[3];
2340
2341    /*
2342     * The special sequence to enable the middle, "rubber" button.
2343     * Immediately after this sequence check status bytes.
2344     * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
2345     * the second and the third bytes are '3' and 'U'.
2346     * NOTE: NetMouse reports that it has three buttons although it has
2347     * two buttons and a rubber button. NetMouse Pro and MIE Mouse
2348     * say they have three buttons too and they do have a button on the
2349     * side...
2350     */
2351    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2352        return FALSE;
2353    if ((status[1] != '3') || (status[2] != 'U'))
2354        return FALSE;
2355    return TRUE;
2356}
2357
2358/* ALPS GlidePoint */
2359static int
2360enable_aglide(struct psm_softc *sc)
2361{
2362    int status[3];
2363
2364    /*
2365     * The special sequence to obtain ALPS GlidePoint specific
2366     * information. Immediately after this sequence, status bytes will
2367     * contain something interesting.
2368     * NOTE: ALPS produces several models of GlidePoint. Some of those
2369     * do not respond to this sequence, thus, cannot be detected this way.
2370     */
2371    if (set_mouse_sampling_rate(sc->kbdc, 100) != 100)
2372	return FALSE;
2373    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
2374        return FALSE;
2375    if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
2376        return FALSE;
2377    return TRUE;
2378}
2379
2380/* Kensington ThinkingMouse/Trackball */
2381static int
2382enable_kmouse(struct psm_softc *sc)
2383{
2384    static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
2385    KBDC kbdc = sc->kbdc;
2386    int status[3];
2387    int id1;
2388    int id2;
2389    int i;
2390
2391    id1 = get_aux_id(kbdc);
2392    if (set_mouse_sampling_rate(kbdc, 10) != 10)
2393	return FALSE;
2394    /*
2395     * The device is now in the native mode? It returns a different
2396     * ID value...
2397     */
2398    id2 = get_aux_id(kbdc);
2399    if ((id1 == id2) || (id2 != 2))
2400	return FALSE;
2401
2402    if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
2403        return FALSE;
2404#if PSM_DEBUG >= 2
2405    /* at this point, resolution is LOW, sampling rate is 10/sec */
2406    if (get_mouse_status(kbdc, status, 0, 3) < 3)
2407        return FALSE;
2408#endif
2409
2410    /*
2411     * The special sequence to enable the third and fourth buttons.
2412     * Otherwise they behave like the first and second buttons.
2413     */
2414    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2415        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2416	    return FALSE;
2417    }
2418
2419    /*
2420     * At this point, the device is using default resolution and
2421     * sampling rate for the native mode.
2422     */
2423    if (get_mouse_status(kbdc, status, 0, 3) < 3)
2424        return FALSE;
2425    if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
2426        return FALSE;
2427
2428    /* the device appears be enabled by this sequence, diable it for now */
2429    disable_aux_dev(kbdc);
2430    empty_aux_buffer(kbdc, 5);
2431
2432    return TRUE;
2433}
2434
2435/* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
2436static int
2437enable_mmanplus(struct psm_softc *sc)
2438{
2439    static char res[] = {
2440	-1, PSMD_RES_LOW, PSMD_RES_HIGH, PSMD_RES_MEDIUM_HIGH,
2441	PSMD_RES_MEDIUM_LOW, -1, PSMD_RES_HIGH, PSMD_RES_MEDIUM_LOW,
2442	PSMD_RES_MEDIUM_HIGH, PSMD_RES_HIGH,
2443    };
2444    KBDC kbdc = sc->kbdc;
2445    int data[3];
2446    int i;
2447
2448    /* the special sequence to enable the fourth button and the roller. */
2449    /*
2450     * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
2451     * must be called exactly three times since the last RESET command
2452     * before this sequence. XXX
2453     */
2454    for (i = 0; i < sizeof(res)/sizeof(res[0]); ++i) {
2455	if (res[i] < 0) {
2456	    if (!set_mouse_scaling(kbdc, 1))
2457		return FALSE;
2458	} else {
2459	    if (set_mouse_resolution(kbdc, res[i]) != res[i])
2460		return FALSE;
2461	}
2462    }
2463
2464    if (get_mouse_status(kbdc, data, 1, 3) < 3)
2465        return FALSE;
2466
2467    /*
2468     * PS2++ protocl, packet type 0
2469     *
2470     *          b7 b6 b5 b4 b3 b2 b1 b0
2471     * byte 1:  *  1  p3 p2 1  *  *  *
2472     * byte 2:  1  1  p1 p0 m1 m0 1  0
2473     * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
2474     *
2475     * p3-p0: packet type: 0
2476     * m7-m0: model ID: MouseMan+:0x50, FirstMouse+:0x51, ScrollPoint:0x58...
2477     */
2478    /* check constant bits */
2479    if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
2480        return FALSE;
2481    if ((data[1] & 0xc3) != 0xc2)
2482        return FALSE;
2483    /* check d3-d0 in byte 2 */
2484    if (!MOUSE_PS2PLUS_CHECKBITS(data))
2485        return FALSE;
2486    /* check p3-p0 */
2487    if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
2488        return FALSE;
2489
2490    sc->hw.hwid &= 0x00ff;
2491    sc->hw.hwid |= data[2] << 8;	/* save model ID */
2492
2493    /*
2494     * MouseMan+ (or FirstMouse+) is now in its native mode, in which
2495     * the wheel and the fourth button events are encoded in the
2496     * special data packet. The mouse may be put in the IntelliMouse mode
2497     * if it is initialized by the IntelliMouse's method.
2498     */
2499    return TRUE;
2500}
2501
2502/* MS IntelliMouse Explorer */
2503static int
2504enable_msexplorer(struct psm_softc *sc)
2505{
2506    static unsigned char rate0[] = { 200, 100, 80, };
2507    static unsigned char rate1[] = { 200, 200, 80, };
2508    KBDC kbdc = sc->kbdc;
2509    int id;
2510    int i;
2511
2512    /*
2513     * XXX: this is a kludge to fool some KVM switch products
2514     * which think they are clever enough to know the 4-byte IntelliMouse
2515     * protocol, and assume any other protocols use 3-byte packets.
2516     * They don't convey 4-byte data packets from the IntelliMouse Explorer
2517     * correctly to the host computer because of this!
2518     * The following sequence is actually IntelliMouse's "wake up"
2519     * sequence; it will make the KVM think the mouse is IntelliMouse
2520     * when it is in fact IntelliMouse Explorer.
2521     */
2522    for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i) {
2523        if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
2524	    return FALSE;
2525    }
2526    id = get_aux_id(kbdc);
2527
2528    /* the special sequence to enable the extra buttons and the roller. */
2529    for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i) {
2530        if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
2531	    return FALSE;
2532    }
2533    /* the device will give the genuine ID only after the above sequence */
2534    id = get_aux_id(kbdc);
2535    if (id != PSM_EXPLORER_ID)
2536	return FALSE;
2537
2538    sc->hw.hwid = id;
2539    sc->hw.buttons = 5;		/* IntelliMouse Explorer XXX */
2540
2541    return TRUE;
2542}
2543
2544/* MS IntelliMouse */
2545static int
2546enable_msintelli(struct psm_softc *sc)
2547{
2548    /*
2549     * Logitech MouseMan+ and FirstMouse+ will also respond to this
2550     * probe routine and act like IntelliMouse.
2551     */
2552
2553    static unsigned char rate[] = { 200, 100, 80, };
2554    KBDC kbdc = sc->kbdc;
2555    int id;
2556    int i;
2557
2558    /* the special sequence to enable the third button and the roller. */
2559    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2560        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2561	    return FALSE;
2562    }
2563    /* the device will give the genuine ID only after the above sequence */
2564    id = get_aux_id(kbdc);
2565    if (id != PSM_INTELLI_ID)
2566	return FALSE;
2567
2568    sc->hw.hwid = id;
2569    sc->hw.buttons = 3;
2570
2571    return TRUE;
2572}
2573
2574/* A4 Tech 4D Mouse */
2575static int
2576enable_4dmouse(struct psm_softc *sc)
2577{
2578    /*
2579     * Newer wheel mice from A4 Tech may use the 4D+ protocol.
2580     */
2581
2582    static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
2583    KBDC kbdc = sc->kbdc;
2584    int id;
2585    int i;
2586
2587    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2588        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2589	    return FALSE;
2590    }
2591    id = get_aux_id(kbdc);
2592    /*
2593     * WinEasy 4D, 4 Way Scroll 4D: 6
2594     * Cable-Free 4D: 8 (4DPLUS)
2595     * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
2596     */
2597    if (id != PSM_4DMOUSE_ID)
2598	return FALSE;
2599
2600    sc->hw.hwid = id;
2601    sc->hw.buttons = 3;		/* XXX some 4D mice have 4? */
2602
2603    return TRUE;
2604}
2605
2606/* A4 Tech 4D+ Mouse */
2607static int
2608enable_4dplus(struct psm_softc *sc)
2609{
2610    /*
2611     * Newer wheel mice from A4 Tech seem to use this protocol.
2612     * Older models are recognized as either 4D Mouse or IntelliMouse.
2613     */
2614    KBDC kbdc = sc->kbdc;
2615    int id;
2616
2617    /*
2618     * enable_4dmouse() already issued the following ID sequence...
2619    static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
2620    int i;
2621
2622    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2623        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2624	    return FALSE;
2625    }
2626    */
2627
2628    id = get_aux_id(kbdc);
2629    if (id != PSM_4DPLUS_ID)
2630	return FALSE;
2631
2632    sc->hw.hwid = id;
2633    sc->hw.buttons = 4;		/* XXX */
2634
2635    return TRUE;
2636}
2637
2638/* Interlink electronics VersaPad */
2639static int
2640enable_versapad(struct psm_softc *sc)
2641{
2642    KBDC kbdc = sc->kbdc;
2643    int data[3];
2644
2645    set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
2646    set_mouse_sampling_rate(kbdc, 100);		/* set rate 100 */
2647    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2648    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2649    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2650    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2651    if (get_mouse_status(kbdc, data, 0, 3) < 3)	/* get status */
2652	return FALSE;
2653    if (data[2] != 0xa || data[1] != 0 )	/* rate == 0xa && res. == 0 */
2654	return FALSE;
2655    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
2656
2657    sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
2658
2659    return TRUE;				/* PS/2 absolute mode */
2660}
2661
2662static int
2663psmresume(device_t dev)
2664{
2665    struct psm_softc *sc = device_get_softc(dev);
2666    int unit = device_get_unit(dev);
2667    int err = 0;
2668    int s;
2669    int c;
2670
2671    if (verbose >= 2)
2672        log(LOG_NOTICE, "psm%d: system resume hook called.\n", unit);
2673
2674    if (!(sc->config & PSM_CONFIG_HOOKRESUME))
2675	return (0);
2676
2677    /* don't let anybody mess with the aux device */
2678    if (!kbdc_lock(sc->kbdc, TRUE))
2679	return (EIO);
2680    s = spltty();
2681
2682    /* block our watchdog timer */
2683    sc->watchdog = FALSE;
2684    untimeout(psmtimeout, (void *)(uintptr_t)unit, sc->callout);
2685    callout_handle_init(&sc->callout);
2686
2687    /* save the current controller command byte */
2688    empty_both_buffers(sc->kbdc, 10);
2689    c = get_controller_command_byte(sc->kbdc);
2690    if (verbose >= 2)
2691        log(LOG_DEBUG, "psm%d: current command byte: %04x (psmresume).\n",
2692	    unit, c);
2693
2694    /* enable the aux port but disable the aux interrupt and the keyboard */
2695    if ((c == -1) || !set_controller_command_byte(sc->kbdc,
2696	    kbdc_get_device_mask(sc->kbdc),
2697  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
2698	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2699        /* CONTROLLER ERROR */
2700	splx(s);
2701        kbdc_lock(sc->kbdc, FALSE);
2702	log(LOG_ERR, "psm%d: unable to set the command byte (psmresume).\n",
2703	    unit);
2704	return (EIO);
2705    }
2706
2707    /* flush any data */
2708    if (sc->state & PSM_VALID) {
2709	disable_aux_dev(sc->kbdc);	/* this may fail; but never mind... */
2710	empty_aux_buffer(sc->kbdc, 10);
2711    }
2712    sc->inputbytes = 0;
2713
2714    /* try to detect the aux device; are you still there? */
2715    if (sc->config & PSM_CONFIG_INITAFTERSUSPEND) {
2716	if (reinitialize(unit, &sc->mode)) {
2717	    /* yes */
2718	    sc->state |= PSM_VALID;
2719	} else {
2720	    /* the device has gone! */
2721	    restore_controller(sc->kbdc, c);
2722	    sc->state &= ~PSM_VALID;
2723	    log(LOG_ERR, "psm%d: the aux device has gone! (psmresume).\n",
2724		unit);
2725	    err = ENXIO;
2726	}
2727    }
2728    splx(s);
2729
2730    /* restore the driver state */
2731    if ((sc->state & PSM_OPEN) && (err == 0)) {
2732        /* enable the aux device and the port again */
2733	err = doopen(unit, c);
2734	if (err != 0)
2735	    log(LOG_ERR, "psm%d: failed to enable the device (psmresume).\n",
2736		unit);
2737    } else {
2738        /* restore the keyboard port and disable the aux port */
2739        if (!set_controller_command_byte(sc->kbdc,
2740                kbdc_get_device_mask(sc->kbdc),
2741                (c & KBD_KBD_CONTROL_BITS)
2742                    | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2743            /* CONTROLLER ERROR */
2744            log(LOG_ERR, "psm%d: failed to disable the aux port (psmresume).\n",
2745                unit);
2746            err = EIO;
2747	}
2748    }
2749
2750    /* done */
2751    kbdc_lock(sc->kbdc, FALSE);
2752    if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
2753	/*
2754	 * Release the blocked process; it must be notified that the device
2755	 * cannot be accessed anymore.
2756	 */
2757        sc->state &= ~PSM_ASLP;
2758        wakeup((caddr_t)sc);
2759    }
2760
2761    if (verbose >= 2)
2762        log(LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit);
2763
2764    return (err);
2765}
2766
2767DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
2768