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