96fc16d85547aededd0798fa9774180f57e3a6aa
[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.6 2002/03/27 16:53:35 pb Exp $
24  * $DragonFly: src/sys/dev/misc/psm/psm.c,v 1.3 2003/06/23 17:55:40 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 <isa/isavar.h>
88 #include <dev/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) << 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     dev_t         dev;
177     dev_t         bdev;
178 };
179 devclass_t psm_devclass;
180 #define PSM_SOFTC(unit) ((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
181
182 /* driver state flags (state) */
183 #define PSM_VALID               0x80
184 #define PSM_OPEN                1       /* Device is open */
185 #define PSM_ASLP                2       /* Waiting for mouse data */
186
187 /* driver configuration flags (config) */
188 #define PSM_CONFIG_RESOLUTION   0x000f  /* resolution */
189 #define PSM_CONFIG_ACCEL        0x00f0  /* acceleration factor */
190 #define PSM_CONFIG_NOCHECKSYNC  0x0100  /* disable sync. test */
191 #define PSM_CONFIG_NOIDPROBE    0x0200  /* disable mouse model probe */
192 #define PSM_CONFIG_NORESET      0x0400  /* don't reset the mouse */
193 #define PSM_CONFIG_FORCETAP     0x0800  /* assume `tap' action exists */
194 #define PSM_CONFIG_IGNPORTERROR 0x1000  /* ignore error in aux port test */
195 #define PSM_CONFIG_HOOKRESUME   0x2000  /* hook the system resume event */
196 #define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
197 #define PSM_CONFIG_SYNCHACK     0x8000 /* enable `out-of-sync' hack */
198
199 #define PSM_CONFIG_FLAGS        (PSM_CONFIG_RESOLUTION          \
200                                     | PSM_CONFIG_ACCEL          \
201                                     | PSM_CONFIG_NOCHECKSYNC    \
202                                     | PSM_CONFIG_SYNCHACK       \
203                                     | PSM_CONFIG_NOIDPROBE      \
204                                     | PSM_CONFIG_NORESET        \
205                                     | PSM_CONFIG_FORCETAP       \
206                                     | PSM_CONFIG_IGNPORTERROR   \
207                                     | PSM_CONFIG_HOOKRESUME     \
208                                     | PSM_CONFIG_INITAFTERSUSPEND)
209
210 /* other flags (flags) */
211 #define PSM_FLAGS_FINGERDOWN    0x0001 /* VersaPad finger down */
212
213 /* for backward compatibility */
214 #define OLD_MOUSE_GETHWINFO     _IOR('M', 1, old_mousehw_t)
215 #define OLD_MOUSE_GETMODE       _IOR('M', 2, old_mousemode_t)
216 #define OLD_MOUSE_SETMODE       _IOW('M', 3, old_mousemode_t)
217
218 typedef struct old_mousehw {
219     int buttons;
220     int iftype;
221     int type;
222     int hwid;
223 } old_mousehw_t;
224
225 typedef struct old_mousemode {
226     int protocol;
227     int rate;
228     int resolution;
229     int accelfactor;
230 } old_mousemode_t;
231
232 /* packet formatting function */
233 typedef int packetfunc_t __P((struct psm_softc *, unsigned char *,
234                               int *, int, mousestatus_t *));
235
236 /* function prototypes */
237 static int psmprobe __P((device_t));
238 static int psmattach __P((device_t));
239 static int psmdetach __P((device_t));
240 static int psmresume __P((device_t));
241
242 static d_open_t psmopen;
243 static d_close_t psmclose;
244 static d_read_t psmread;
245 static d_ioctl_t psmioctl;
246 static d_poll_t psmpoll;
247
248 static int enable_aux_dev __P((KBDC));
249 static int disable_aux_dev __P((KBDC));
250 static int get_mouse_status __P((KBDC, int *, int, int));
251 static int get_aux_id __P((KBDC));
252 static int set_mouse_sampling_rate __P((KBDC, int));
253 static int set_mouse_scaling __P((KBDC, int));
254 static int set_mouse_resolution __P((KBDC, int));
255 static int set_mouse_mode __P((KBDC));
256 static int get_mouse_buttons __P((KBDC));
257 static int is_a_mouse __P((int));
258 static void recover_from_error __P((KBDC));
259 static int restore_controller __P((KBDC, int));
260 static int doinitialize __P((struct psm_softc *, mousemode_t *));
261 static int doopen __P((struct psm_softc *, int));
262 static int reinitialize __P((struct psm_softc *, int));
263 static char *model_name __P((int));
264 static void psmintr __P((void *));
265 static void psmtimeout __P((void *));
266
267 /* vendor specific features */
268 typedef int probefunc_t __P((struct psm_softc *));
269
270 static int mouse_id_proc1 __P((KBDC, int, int, int *));
271 static int mouse_ext_command __P((KBDC, int));
272 static probefunc_t enable_groller;
273 static probefunc_t enable_gmouse;
274 static probefunc_t enable_aglide; 
275 static probefunc_t enable_kmouse;
276 static probefunc_t enable_msexplorer;
277 static probefunc_t enable_msintelli;
278 static probefunc_t enable_4dmouse;
279 static probefunc_t enable_4dplus;
280 static probefunc_t enable_mmanplus;
281 static probefunc_t enable_versapad;
282 static int tame_mouse __P((struct psm_softc *, mousestatus_t *, unsigned char *));
283
284 static struct {
285     int                 model;
286     unsigned char       syncmask;
287     int                 packetsize;
288     probefunc_t         *probefunc;
289 } vendortype[] = {
290     /*
291      * WARNING: the order of probe is very important.  Don't mess it
292      * unless you know what you are doing.
293      */
294     { MOUSE_MODEL_NET,                  /* Genius NetMouse */
295       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse, },
296     { MOUSE_MODEL_NETSCROLL,            /* Genius NetScroll */
297       0xc8, 6, enable_groller, },
298     { MOUSE_MODEL_MOUSEMANPLUS,         /* Logitech MouseMan+ */
299       0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus, },
300     { MOUSE_MODEL_EXPLORER,             /* Microsoft IntelliMouse Explorer */
301       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer, },
302     { MOUSE_MODEL_4D,                   /* A4 Tech 4D Mouse */
303       0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse, },
304     { MOUSE_MODEL_4DPLUS,               /* A4 Tech 4D+ Mouse */
305       0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus, },
306     { MOUSE_MODEL_INTELLI,              /* Microsoft IntelliMouse */
307       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli, },
308     { MOUSE_MODEL_GLIDEPOINT,           /* ALPS GlidePoint */
309       0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide, },
310     { MOUSE_MODEL_THINK,                /* Kensignton ThinkingMouse */
311       0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse, },
312     { MOUSE_MODEL_VERSAPAD,             /* Interlink electronics VersaPad */
313       0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad, },
314     { MOUSE_MODEL_GENERIC,
315       0xc0, MOUSE_PS2_PACKETSIZE, NULL, },
316 };
317 #define GENERIC_MOUSE_ENTRY     ((sizeof(vendortype) / sizeof(*vendortype)) - 1)
318
319 /* device driver declarateion */
320 static device_method_t psm_methods[] = {
321         /* Device interface */
322         DEVMETHOD(device_probe,         psmprobe),
323         DEVMETHOD(device_attach,        psmattach),
324         DEVMETHOD(device_detach,        psmdetach),
325         DEVMETHOD(device_resume,        psmresume),
326
327         { 0, 0 }
328 };
329
330 static driver_t psm_driver = {
331     PSM_DRIVER_NAME,
332     psm_methods,
333     sizeof(struct psm_softc),
334 };
335
336 #if notyet
337 static struct isa_pnp_id psm_ids[] = {
338     { 0x130fd041, "PS/2 mouse port" },                  /* PNP0F13 */
339     { 0x1303d041, "PS/2 port" },                        /* PNP0313, XXX */
340     { 0 }
341 };
342 #endif
343
344 #define CDEV_MAJOR        21
345
346 static struct cdevsw psm_cdevsw = {
347         /* open */      psmopen,
348         /* close */     psmclose,
349         /* read */      psmread,
350         /* write */     nowrite,
351         /* ioctl */     psmioctl,
352         /* poll */      psmpoll,
353         /* mmap */      nommap,
354         /* strategy */  nostrategy,
355         /* name */      PSM_DRIVER_NAME,
356         /* maj */       CDEV_MAJOR,
357         /* dump */      nodump,
358         /* psize */     nopsize,
359         /* flags */     0,
360         /* bmaj */      -1
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         if (!reset_aux_dev(sc->kbdc)) {
1036             recover_from_error(sc->kbdc);
1037             restore_controller(sc->kbdc, command_byte);
1038             if (verbose)
1039                 printf("psm%d: failed to reset the aux device.\n", unit);
1040             endprobe(ENXIO);
1041         }
1042     }
1043
1044     /*
1045      * both the aux port and the aux device is functioning, see if the
1046      * device can be enabled. NOTE: when enabled, the device will start
1047      * sending data; we shall immediately disable the device once we know
1048      * the device can be enabled.
1049      */
1050     if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1051         /* MOUSE ERROR */
1052         recover_from_error(sc->kbdc);
1053         restore_controller(sc->kbdc, command_byte);
1054         if (verbose)
1055             printf("psm%d: failed to enable the aux device.\n", unit);
1056         endprobe(ENXIO);
1057     }
1058
1059     /* save the default values after reset */
1060     if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1061         sc->dflt_mode.rate = sc->mode.rate = stat[2];
1062         sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1063     } else {
1064         sc->dflt_mode.rate = sc->mode.rate = -1;
1065         sc->dflt_mode.resolution = sc->mode.resolution = -1;
1066     }
1067
1068     /* hardware information */
1069     sc->hw.iftype = MOUSE_IF_PS2;
1070
1071     /* verify the device is a mouse */
1072     sc->hw.hwid = get_aux_id(sc->kbdc);
1073     if (!is_a_mouse(sc->hw.hwid)) {
1074         restore_controller(sc->kbdc, command_byte);
1075         if (verbose)
1076             printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid);
1077         endprobe(ENXIO);
1078     }
1079     switch (sc->hw.hwid) {
1080     case PSM_BALLPOINT_ID:
1081         sc->hw.type = MOUSE_TRACKBALL;
1082         break;
1083     case PSM_MOUSE_ID:
1084     case PSM_INTELLI_ID:
1085     case PSM_EXPLORER_ID:
1086     case PSM_4DMOUSE_ID:
1087     case PSM_4DPLUS_ID:
1088         sc->hw.type = MOUSE_MOUSE;
1089         break;
1090     default:
1091         sc->hw.type = MOUSE_UNKNOWN;
1092         break;
1093     }
1094
1095     if (sc->config & PSM_CONFIG_NOIDPROBE) {
1096         sc->hw.buttons = 2;
1097         i = GENERIC_MOUSE_ENTRY;
1098     } else {
1099         /* # of buttons */
1100         sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1101
1102         /* other parameters */
1103         for (i = 0; vendortype[i].probefunc != NULL; ++i) {
1104             if ((*vendortype[i].probefunc)(sc)) {
1105                 if (verbose >= 2)
1106                     printf("psm%d: found %s\n",
1107                            unit, model_name(vendortype[i].model));
1108                 break;
1109             }
1110         }
1111     }
1112
1113     sc->hw.model = vendortype[i].model;
1114
1115     sc->dflt_mode.level = PSM_LEVEL_BASE;
1116     sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1117     sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1118     if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1119         sc->dflt_mode.syncmask[0] = 0;
1120     else
1121         sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1122     if (sc->config & PSM_CONFIG_FORCETAP)
1123         sc->mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1124     sc->dflt_mode.syncmask[1] = 0;      /* syncbits */
1125     sc->mode = sc->dflt_mode;
1126     sc->mode.packetsize = vendortype[i].packetsize;
1127
1128     /* set mouse parameters */
1129 #if 0
1130     /* 
1131      * A version of Logitech FirstMouse+ won't report wheel movement,
1132      * if SET_DEFAULTS is sent...  Don't use this command.
1133      * This fix was found by Takashi Nishida.
1134      */
1135     i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1136     if (verbose >= 2)
1137         printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1138 #endif
1139     if (sc->config & PSM_CONFIG_RESOLUTION) {
1140         sc->mode.resolution
1141             = set_mouse_resolution(sc->kbdc, 
1142                                    (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1143     } else if (sc->mode.resolution >= 0) {
1144         sc->mode.resolution
1145             = set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1146     }
1147     if (sc->mode.rate > 0) {
1148         sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1149     }
1150     set_mouse_scaling(sc->kbdc, 1);
1151
1152     /* request a data packet and extract sync. bits */
1153     if (get_mouse_status(sc->kbdc, stat, 1, 3) < 3) {
1154         printf("psm%d: failed to get data.\n", unit);
1155         sc->mode.syncmask[0] = 0;
1156     } else {
1157         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];  /* syncbits */
1158         /* the NetScroll Mouse will send three more bytes... Ignore them */
1159         empty_aux_buffer(sc->kbdc, 5);
1160     }
1161
1162     /* just check the status of the mouse */
1163     /* 
1164      * NOTE: XXX there are some arcane controller/mouse combinations out 
1165      * there, which hung the controller unless there is data transmission 
1166      * after ACK from the mouse.
1167      */
1168     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) {
1169         printf("psm%d: failed to get status.\n", unit);
1170     } else {
1171         /* 
1172          * When in its native mode, some mice operate with different 
1173          * default parameters than in the PS/2 compatible mode.
1174          */
1175         sc->dflt_mode.rate = sc->mode.rate = stat[2];
1176         sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1177      }
1178
1179     /* disable the aux port for now... */
1180     if (!set_controller_command_byte(sc->kbdc, 
1181             KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1182             (command_byte & KBD_KBD_CONTROL_BITS)
1183                 | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1184         /* 
1185          * this is CONTROLLER ERROR; I don't know the proper way to 
1186          * recover from this error... 
1187          */
1188         restore_controller(sc->kbdc, command_byte);
1189         printf("psm%d: unable to set the command byte.\n", unit);
1190         endprobe(ENXIO);
1191     }
1192
1193     /* see if IRQ is available */
1194     rid = 0;
1195     sc->intr = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, irq, irq, 1,
1196                                   RF_ACTIVE);
1197     if (sc->intr == NULL) {
1198         printf("psm%d: unable to allocate the IRQ resource (%d).\n",
1199                unit, irq);
1200         endprobe(ENXIO);
1201     } else {
1202         bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1203     }
1204
1205     /* done */
1206     kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1207     kbdc_lock(sc->kbdc, FALSE);
1208     return (0);
1209 }
1210
1211 static int
1212 psmattach(device_t dev)
1213 {
1214     int unit = device_get_unit(dev);
1215     struct psm_softc *sc = device_get_softc(dev);
1216     uintptr_t irq;
1217     int error;
1218     int rid;
1219
1220     if (sc == NULL)    /* shouldn't happen */
1221         return (ENXIO);
1222
1223     /* Setup initial state */
1224     sc->state = PSM_VALID;
1225     callout_handle_init(&sc->callout);
1226
1227     /* Setup our interrupt handler */
1228     rid = 0;
1229     BUS_READ_IVAR(device_get_parent(dev), dev, KBDC_IVAR_IRQ, &irq);
1230     sc->intr = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, irq, irq, 1,
1231                                   RF_ACTIVE);
1232     if (sc->intr == NULL)
1233         return (ENXIO);
1234     error = BUS_SETUP_INTR(device_get_parent(dev), dev, sc->intr,
1235                            INTR_TYPE_TTY, psmintr, sc, &sc->ih);
1236     if (error) {
1237         bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1238         return (error);
1239     }
1240
1241     /* Done */
1242     sc->dev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, FALSE), 0, 0, 0666,
1243                        "psm%d", unit);
1244     sc->bdev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, TRUE), 0, 0, 0666,
1245                         "bpsm%d", unit);
1246
1247     if (!verbose) {
1248         printf("psm%d: model %s, device ID %d\n", 
1249             unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1250     } else {
1251         printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1252             unit, model_name(sc->hw.model),
1253             sc->hw.hwid & 0x00ff, sc->hw.hwid >> 8, sc->hw.buttons);
1254         printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1255             unit, sc->config, sc->flags, sc->mode.packetsize);
1256         printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1257             unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1258     }
1259
1260     if (bootverbose)
1261         --verbose;
1262
1263     return (0);
1264 }
1265
1266 static int
1267 psmdetach(device_t dev)
1268 {
1269     struct psm_softc *sc;
1270     int rid;
1271
1272     sc = device_get_softc(dev);
1273     if (sc->state & PSM_OPEN)
1274         return EBUSY;
1275
1276     rid = 0;
1277     BUS_TEARDOWN_INTR(device_get_parent(dev), dev, sc->intr, sc->ih);
1278     bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1279
1280     destroy_dev(sc->dev);
1281     destroy_dev(sc->bdev);
1282
1283     return 0;
1284 }
1285
1286 static int
1287 psmopen(dev_t dev, int flag, int fmt, struct thread *td)
1288 {
1289     int unit = PSM_UNIT(dev);
1290     struct psm_softc *sc;
1291     int command_byte;
1292     int err;
1293     int s;
1294
1295     /* Get device data */
1296     sc = PSM_SOFTC(unit);
1297     if ((sc == NULL) || (sc->state & PSM_VALID) == 0)
1298         /* the device is no longer valid/functioning */
1299         return (ENXIO);
1300
1301     /* Disallow multiple opens */
1302     if (sc->state & PSM_OPEN)
1303         return (EBUSY);
1304
1305     device_busy(devclass_get_device(psm_devclass, unit));
1306
1307     /* Initialize state */
1308     sc->rsel.si_flags = 0;
1309     sc->rsel.si_pid = 0;
1310     sc->mode.level = sc->dflt_mode.level;
1311     sc->mode.protocol = sc->dflt_mode.protocol;
1312     sc->watchdog = FALSE;
1313
1314     /* flush the event queue */
1315     sc->queue.count = 0;
1316     sc->queue.head = 0;
1317     sc->queue.tail = 0;
1318     sc->status.flags = 0;
1319     sc->status.button = 0;
1320     sc->status.obutton = 0;
1321     sc->status.dx = 0;
1322     sc->status.dy = 0;
1323     sc->status.dz = 0;
1324     sc->button = 0;
1325
1326     /* empty input buffer */
1327     bzero(sc->ipacket, sizeof(sc->ipacket));
1328     sc->inputbytes = 0;
1329     sc->syncerrors = 0;
1330
1331     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1332     if (!kbdc_lock(sc->kbdc, TRUE))
1333         return (EIO);
1334
1335     /* save the current controller command byte */
1336     s = spltty();
1337     command_byte = get_controller_command_byte(sc->kbdc);
1338
1339     /* enable the aux port and temporalily disable the keyboard */
1340     if ((command_byte == -1) 
1341         || !set_controller_command_byte(sc->kbdc,
1342             kbdc_get_device_mask(sc->kbdc),
1343             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1344                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1345         /* CONTROLLER ERROR; do you know how to get out of this? */
1346         kbdc_lock(sc->kbdc, FALSE);
1347         splx(s);
1348         log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n",
1349             unit);
1350         return (EIO);
1351     }
1352     /* 
1353      * Now that the keyboard controller is told not to generate 
1354      * the keyboard and mouse interrupts, call `splx()' to allow 
1355      * the other tty interrupts. The clock interrupt may also occur, 
1356      * but timeout routines will be blocked by the poll flag set 
1357      * via `kbdc_lock()'
1358      */
1359     splx(s);
1360   
1361     /* enable the mouse device */
1362     err = doopen(sc, command_byte);
1363
1364     /* done */
1365     if (err == 0) 
1366         sc->state |= PSM_OPEN;
1367     kbdc_lock(sc->kbdc, FALSE);
1368     return (err);
1369 }
1370
1371 static int
1372 psmclose(dev_t dev, int flag, int fmt, struct thread *td)
1373 {
1374     int unit = PSM_UNIT(dev);
1375     struct psm_softc *sc = PSM_SOFTC(unit);
1376     int stat[3];
1377     int command_byte;
1378     int s;
1379
1380     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1381     if (!kbdc_lock(sc->kbdc, TRUE))
1382         return (EIO);
1383
1384     /* save the current controller command byte */
1385     s = spltty();
1386     command_byte = get_controller_command_byte(sc->kbdc);
1387     if (command_byte == -1) {
1388         kbdc_lock(sc->kbdc, FALSE);
1389         splx(s);
1390         return (EIO);
1391     }
1392
1393     /* disable the aux interrupt and temporalily disable the keyboard */
1394     if (!set_controller_command_byte(sc->kbdc, 
1395             kbdc_get_device_mask(sc->kbdc),
1396             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1397                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1398         log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n",
1399             unit);
1400         /* CONTROLLER ERROR;
1401          * NOTE: we shall force our way through. Because the only
1402          * ill effect we shall see is that we may not be able
1403          * to read ACK from the mouse, and it doesn't matter much 
1404          * so long as the mouse will accept the DISABLE command.
1405          */
1406     }
1407     splx(s);
1408
1409     /* stop the watchdog timer */
1410     untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
1411     callout_handle_init(&sc->callout);
1412
1413     /* remove anything left in the output buffer */
1414     empty_aux_buffer(sc->kbdc, 10);
1415
1416     /* disable the aux device, port and interrupt */
1417     if (sc->state & PSM_VALID) {
1418         if (!disable_aux_dev(sc->kbdc)) {
1419             /* MOUSE ERROR; 
1420              * NOTE: we don't return error and continue, pretending 
1421              * we have successfully disabled the device. It's OK because 
1422              * the interrupt routine will discard any data from the mouse
1423              * hereafter. 
1424              */
1425             log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n",
1426                 unit);
1427         }
1428
1429         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1430             log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n", 
1431                 unit);
1432     }
1433
1434     if (!set_controller_command_byte(sc->kbdc, 
1435             kbdc_get_device_mask(sc->kbdc),
1436             (command_byte & KBD_KBD_CONTROL_BITS)
1437                 | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1438         /* CONTROLLER ERROR; 
1439          * we shall ignore this error; see the above comment.
1440          */
1441         log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n",
1442             unit);
1443     }
1444
1445     /* remove anything left in the output buffer */
1446     empty_aux_buffer(sc->kbdc, 10);
1447
1448     /* close is almost always successful */
1449     sc->state &= ~PSM_OPEN;
1450     kbdc_lock(sc->kbdc, FALSE);
1451     device_unbusy(devclass_get_device(psm_devclass, unit));
1452     return (0);
1453 }
1454
1455 static int
1456 tame_mouse(struct psm_softc *sc, mousestatus_t *status, unsigned char *buf)
1457 {
1458     static unsigned char butmapps2[8] = {
1459         0,
1460         MOUSE_PS2_BUTTON1DOWN, 
1461         MOUSE_PS2_BUTTON2DOWN,
1462         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1463         MOUSE_PS2_BUTTON3DOWN,
1464         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1465         MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1466         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1467     };
1468     static unsigned char butmapmsc[8] = {
1469         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1470         MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1471         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1472         MOUSE_MSC_BUTTON3UP,
1473         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1474         MOUSE_MSC_BUTTON2UP,
1475         MOUSE_MSC_BUTTON1UP, 
1476         0,
1477     };
1478     int mapped;
1479     int i;
1480
1481     if (sc->mode.level == PSM_LEVEL_BASE) {
1482         mapped = status->button & ~MOUSE_BUTTON4DOWN;
1483         if (status->button & MOUSE_BUTTON4DOWN) 
1484             mapped |= MOUSE_BUTTON1DOWN;
1485         status->button = mapped;
1486         buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1487         i = max(min(status->dx, 255), -256);
1488         if (i < 0)
1489             buf[0] |= MOUSE_PS2_XNEG;
1490         buf[1] = i;
1491         i = max(min(status->dy, 255), -256);
1492         if (i < 0)
1493             buf[0] |= MOUSE_PS2_YNEG;
1494         buf[2] = i;
1495         return MOUSE_PS2_PACKETSIZE;
1496     } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1497         buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS];
1498         i = max(min(status->dx, 255), -256);
1499         buf[1] = i >> 1;
1500         buf[3] = i - buf[1];
1501         i = max(min(status->dy, 255), -256);
1502         buf[2] = i >> 1;
1503         buf[4] = i - buf[2];
1504         i = max(min(status->dz, 127), -128);
1505         buf[5] = (i >> 1) & 0x7f;
1506         buf[6] = (i - (i >> 1)) & 0x7f;
1507         buf[7] = (~status->button >> 3) & 0x7f;
1508         return MOUSE_SYS_PACKETSIZE;
1509     }
1510     return sc->inputbytes;;
1511 }
1512
1513 static int
1514 psmread(dev_t dev, struct uio *uio, int flag)
1515 {
1516     register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1517     unsigned char buf[PSM_SMALLBUFSIZE];
1518     int error = 0;
1519     int s;
1520     int l;
1521
1522     if ((sc->state & PSM_VALID) == 0)
1523         return EIO;
1524
1525     /* block until mouse activity occured */
1526     s = spltty();
1527     while (sc->queue.count <= 0) {
1528         if (PSM_NBLOCKIO(dev)) {
1529             splx(s);
1530             return EWOULDBLOCK;
1531         }
1532         sc->state |= PSM_ASLP;
1533         error = tsleep((caddr_t) sc, PZERO | PCATCH, "psmrea", 0);
1534         sc->state &= ~PSM_ASLP;
1535         if (error) {
1536             splx(s);
1537             return error;
1538         } else if ((sc->state & PSM_VALID) == 0) {
1539             /* the device disappeared! */
1540             splx(s);
1541             return EIO;
1542         }
1543     }
1544     splx(s);
1545
1546     /* copy data to the user land */
1547     while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1548         s = spltty();
1549         l = min(sc->queue.count, uio->uio_resid);
1550         if (l > sizeof(buf))
1551             l = sizeof(buf);
1552         if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1553             bcopy(&sc->queue.buf[sc->queue.head], &buf[0], 
1554                 sizeof(sc->queue.buf) - sc->queue.head);
1555             bcopy(&sc->queue.buf[0], 
1556                 &buf[sizeof(sc->queue.buf) - sc->queue.head],
1557                 l - (sizeof(sc->queue.buf) - sc->queue.head));
1558         } else {
1559             bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1560         }
1561         sc->queue.count -= l;
1562         sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1563         splx(s);
1564         error = uiomove(buf, l, uio);
1565         if (error)
1566             break;
1567     }
1568
1569     return error;
1570 }
1571
1572 static int
1573 block_mouse_data(struct psm_softc *sc, int *c)
1574 {
1575     int s;
1576
1577     if (!kbdc_lock(sc->kbdc, TRUE)) 
1578         return EIO;
1579
1580     s = spltty();
1581     *c = get_controller_command_byte(sc->kbdc);
1582     if ((*c == -1) 
1583         || !set_controller_command_byte(sc->kbdc, 
1584             kbdc_get_device_mask(sc->kbdc),
1585             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1586                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1587         /* this is CONTROLLER ERROR */
1588         splx(s);
1589         kbdc_lock(sc->kbdc, FALSE);
1590         return EIO;
1591     }
1592
1593     /* 
1594      * The device may be in the middle of status data transmission.
1595      * The transmission will be interrupted, thus, incomplete status 
1596      * data must be discarded. Although the aux interrupt is disabled 
1597      * at the keyboard controller level, at most one aux interrupt 
1598      * may have already been pending and a data byte is in the 
1599      * output buffer; throw it away. Note that the second argument 
1600      * to `empty_aux_buffer()' is zero, so that the call will just 
1601      * flush the internal queue.
1602      * `psmintr()' will be invoked after `splx()' if an interrupt is
1603      * pending; it will see no data and returns immediately.
1604      */
1605     empty_aux_buffer(sc->kbdc, 0);      /* flush the queue */
1606     read_aux_data_no_wait(sc->kbdc);    /* throw away data if any */
1607     sc->inputbytes = 0;
1608     splx(s);
1609
1610     return 0;
1611 }
1612
1613 static int
1614 unblock_mouse_data(struct psm_softc *sc, int c)
1615 {
1616     int error = 0;
1617
1618     /* 
1619      * We may have seen a part of status data during `set_mouse_XXX()'.
1620      * they have been queued; flush it.
1621      */
1622     empty_aux_buffer(sc->kbdc, 0);
1623
1624     /* restore ports and interrupt */
1625     if (!set_controller_command_byte(sc->kbdc, 
1626             kbdc_get_device_mask(sc->kbdc),
1627             c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1628         /* CONTROLLER ERROR; this is serious, we may have
1629          * been left with the inaccessible keyboard and
1630          * the disabled mouse interrupt. 
1631          */
1632         error = EIO;
1633     }
1634
1635     kbdc_lock(sc->kbdc, FALSE);
1636     return error;
1637 }
1638
1639 static int
1640 psmioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1641 {
1642     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1643     mousemode_t mode;
1644     mousestatus_t status;
1645 #if (defined(MOUSE_GETVARS))
1646     mousevar_t *var;
1647 #endif
1648     mousedata_t *data;
1649     int stat[3];
1650     int command_byte;
1651     int error = 0;
1652     int s;
1653
1654     /* Perform IOCTL command */
1655     switch (cmd) {
1656
1657     case OLD_MOUSE_GETHWINFO:
1658         s = spltty();
1659         ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1660         ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1661         ((old_mousehw_t *)addr)->type = sc->hw.type;
1662         ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
1663         splx(s);
1664         break;
1665
1666     case MOUSE_GETHWINFO:
1667         s = spltty();
1668         *(mousehw_t *)addr = sc->hw;
1669         if (sc->mode.level == PSM_LEVEL_BASE)
1670             ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1671         splx(s);
1672         break;
1673
1674     case OLD_MOUSE_GETMODE:
1675         s = spltty();
1676         switch (sc->mode.level) {
1677         case PSM_LEVEL_BASE:
1678             ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1679             break;
1680         case PSM_LEVEL_STANDARD:
1681             ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1682             break;
1683         case PSM_LEVEL_NATIVE:
1684             ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1685             break;
1686         }
1687         ((old_mousemode_t *)addr)->rate = sc->mode.rate;
1688         ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1689         ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1690         splx(s);
1691         break;
1692
1693     case MOUSE_GETMODE:
1694         s = spltty();
1695         *(mousemode_t *)addr = sc->mode;
1696         ((mousemode_t *)addr)->resolution = 
1697             MOUSE_RES_LOW - sc->mode.resolution;
1698         switch (sc->mode.level) {
1699         case PSM_LEVEL_BASE:
1700             ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1701             ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE;
1702             break;
1703         case PSM_LEVEL_STANDARD:
1704             ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1705             ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE;
1706             ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1707             ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
1708             break;
1709         case PSM_LEVEL_NATIVE:
1710             /* FIXME: this isn't quite correct... XXX */
1711             ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1712             break;
1713         }
1714         splx(s);
1715         break;
1716
1717     case OLD_MOUSE_SETMODE:
1718     case MOUSE_SETMODE:
1719         if (cmd == OLD_MOUSE_SETMODE) {
1720             mode.rate = ((old_mousemode_t *)addr)->rate;
1721             /*
1722              * resolution  old I/F   new I/F
1723              * default        0         0
1724              * low            1        -2
1725              * medium low     2        -3
1726              * medium high    3        -4
1727              * high           4        -5
1728              */
1729             if (((old_mousemode_t *)addr)->resolution > 0)
1730                 mode.resolution = -((old_mousemode_t *)addr)->resolution - 1;
1731             mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor;
1732             mode.level = -1;
1733         } else {
1734             mode = *(mousemode_t *)addr;
1735         }
1736
1737         /* adjust and validate parameters. */
1738         if (mode.rate > UCHAR_MAX)
1739             return EINVAL;
1740         if (mode.rate == 0)
1741             mode.rate = sc->dflt_mode.rate;
1742         else if (mode.rate == -1)
1743             /* don't change the current setting */
1744             ;
1745         else if (mode.rate < 0)
1746             return EINVAL;
1747         if (mode.resolution >= UCHAR_MAX)
1748             return EINVAL;
1749         if (mode.resolution >= 200)
1750             mode.resolution = MOUSE_RES_HIGH;
1751         else if (mode.resolution >= 100)
1752             mode.resolution = MOUSE_RES_MEDIUMHIGH;
1753         else if (mode.resolution >= 50)
1754             mode.resolution = MOUSE_RES_MEDIUMLOW;
1755         else if (mode.resolution > 0)
1756             mode.resolution = MOUSE_RES_LOW;
1757         if (mode.resolution == MOUSE_RES_DEFAULT)
1758             mode.resolution = sc->dflt_mode.resolution;
1759         else if (mode.resolution == -1)
1760             /* don't change the current setting */
1761             ;
1762         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1763             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1764         if (mode.level == -1)
1765             /* don't change the current setting */
1766             mode.level = sc->mode.level;
1767         else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX))
1768             return EINVAL;
1769         if (mode.accelfactor == -1)
1770             /* don't change the current setting */
1771             mode.accelfactor = sc->mode.accelfactor;
1772         else if (mode.accelfactor < 0)
1773             return EINVAL;
1774
1775         /* don't allow anybody to poll the keyboard controller */
1776         error = block_mouse_data(sc, &command_byte);
1777         if (error)
1778             return error;
1779
1780         /* set mouse parameters */
1781         if (mode.rate > 0)
1782             mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1783         if (mode.resolution >= 0)
1784             mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1785         set_mouse_scaling(sc->kbdc, 1);
1786         get_mouse_status(sc->kbdc, stat, 0, 3);
1787
1788         s = spltty();
1789         sc->mode.rate = mode.rate;
1790         sc->mode.resolution = mode.resolution;
1791         sc->mode.accelfactor = mode.accelfactor;
1792         sc->mode.level = mode.level;
1793         splx(s);
1794
1795         unblock_mouse_data(sc, command_byte);
1796         break;
1797
1798     case MOUSE_GETLEVEL:
1799         *(int *)addr = sc->mode.level;
1800         break;
1801
1802     case MOUSE_SETLEVEL:
1803         if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX))
1804             return EINVAL;
1805         sc->mode.level = *(int *)addr;
1806         break;
1807
1808     case MOUSE_GETSTATUS:
1809         s = spltty();
1810         status = sc->status;
1811         sc->status.flags = 0;
1812         sc->status.obutton = sc->status.button;
1813         sc->status.button = 0;
1814         sc->status.dx = 0;
1815         sc->status.dy = 0;
1816         sc->status.dz = 0;
1817         splx(s);
1818         *(mousestatus_t *)addr = status;
1819         break;
1820
1821 #if (defined(MOUSE_GETVARS))
1822     case MOUSE_GETVARS:
1823         var = (mousevar_t *)addr;
1824         bzero(var, sizeof(*var));
1825         s = spltty();
1826         var->var[0] = MOUSE_VARS_PS2_SIG;
1827         var->var[1] = sc->config;
1828         var->var[2] = sc->flags;
1829         splx(s);
1830         break;
1831
1832     case MOUSE_SETVARS:
1833         return ENODEV;
1834 #endif /* MOUSE_GETVARS */
1835
1836     case MOUSE_READSTATE:
1837     case MOUSE_READDATA:
1838         data = (mousedata_t *)addr;
1839         if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
1840             return EINVAL;
1841
1842         error = block_mouse_data(sc, &command_byte);
1843         if (error)
1844             return error;
1845         if ((data->len = get_mouse_status(sc->kbdc, data->buf, 
1846                 (cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
1847             error = EIO;
1848         unblock_mouse_data(sc, command_byte);
1849         break;
1850
1851 #if (defined(MOUSE_SETRESOLUTION))
1852     case MOUSE_SETRESOLUTION:
1853         mode.resolution = *(int *)addr;
1854         if (mode.resolution >= UCHAR_MAX)
1855             return EINVAL;
1856         else if (mode.resolution >= 200)
1857             mode.resolution = MOUSE_RES_HIGH;
1858         else if (mode.resolution >= 100)
1859             mode.resolution = MOUSE_RES_MEDIUMHIGH;
1860         else if (mode.resolution >= 50)
1861             mode.resolution = MOUSE_RES_MEDIUMLOW;
1862         else if (mode.resolution > 0)
1863             mode.resolution = MOUSE_RES_LOW;
1864         if (mode.resolution == MOUSE_RES_DEFAULT)
1865             mode.resolution = sc->dflt_mode.resolution;
1866         else if (mode.resolution == -1)
1867             mode.resolution = sc->mode.resolution;
1868         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1869             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1870
1871         error = block_mouse_data(sc, &command_byte);
1872         if (error)
1873             return error;
1874         sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1875         if (sc->mode.resolution != mode.resolution)
1876             error = EIO;
1877         unblock_mouse_data(sc, command_byte);
1878         break;
1879 #endif /* MOUSE_SETRESOLUTION */
1880
1881 #if (defined(MOUSE_SETRATE))
1882     case MOUSE_SETRATE:
1883         mode.rate = *(int *)addr;
1884         if (mode.rate > UCHAR_MAX)
1885             return EINVAL;
1886         if (mode.rate == 0)
1887             mode.rate = sc->dflt_mode.rate;
1888         else if (mode.rate < 0)
1889             mode.rate = sc->mode.rate;
1890
1891         error = block_mouse_data(sc, &command_byte);
1892         if (error)
1893             return error;
1894         sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1895         if (sc->mode.rate != mode.rate)
1896             error = EIO;
1897         unblock_mouse_data(sc, command_byte);
1898         break;
1899 #endif /* MOUSE_SETRATE */
1900
1901 #if (defined(MOUSE_SETSCALING))
1902     case MOUSE_SETSCALING:
1903         if ((*(int *)addr <= 0) || (*(int *)addr > 2))
1904             return EINVAL;
1905
1906         error = block_mouse_data(sc, &command_byte);
1907         if (error)
1908             return error;
1909         if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
1910             error = EIO;
1911         unblock_mouse_data(sc, command_byte);
1912         break;
1913 #endif /* MOUSE_SETSCALING */
1914
1915 #if (defined(MOUSE_GETHWID))
1916     case MOUSE_GETHWID:
1917         error = block_mouse_data(sc, &command_byte);
1918         if (error)
1919             return error;
1920         sc->hw.hwid &= ~0x00ff;
1921         sc->hw.hwid |= get_aux_id(sc->kbdc);
1922         *(int *)addr = sc->hw.hwid & 0x00ff;
1923         unblock_mouse_data(sc, command_byte);
1924         break;
1925 #endif /* MOUSE_GETHWID */
1926
1927     default:
1928         return ENOTTY;
1929     }
1930
1931     return error;
1932 }
1933
1934 static void
1935 psmtimeout(void *arg)
1936 {
1937     struct psm_softc *sc;
1938     int s;
1939
1940     sc = (struct psm_softc *)arg;
1941     s = spltty();
1942     if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
1943         if (verbose >= 4)
1944             log(LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit);
1945         psmintr(sc);
1946         kbdc_lock(sc->kbdc, FALSE);
1947     }
1948     sc->watchdog = TRUE;
1949     splx(s);
1950     sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz);
1951 }
1952
1953 static void
1954 psmintr(void *arg)
1955 {
1956     /*
1957      * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
1958      * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
1959      */
1960     static int butmap[8] = {
1961         0, 
1962         MOUSE_BUTTON1DOWN, 
1963         MOUSE_BUTTON3DOWN, 
1964         MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, 
1965         MOUSE_BUTTON2DOWN, 
1966         MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN, 
1967         MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1968         MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1969     };
1970     static int butmap_versapad[8] = {
1971         0, 
1972         MOUSE_BUTTON3DOWN, 
1973         0, 
1974         MOUSE_BUTTON3DOWN, 
1975         MOUSE_BUTTON1DOWN, 
1976         MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, 
1977         MOUSE_BUTTON1DOWN,
1978         MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
1979     };
1980     register struct psm_softc *sc = arg;
1981     mousestatus_t ms;
1982     struct timeval tv;
1983     int x, y, z;
1984     int c;
1985     int l;
1986     int x0, y0;
1987
1988     /* read until there is nothing to read */
1989     while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
1990     
1991         /* discard the byte if the device is not open */
1992         if ((sc->state & PSM_OPEN) == 0)
1993             continue;
1994     
1995         getmicrouptime(&tv);
1996         if ((sc->inputbytes > 0) && timevalcmp(&tv, &sc->inputtimeout, >)) {
1997             log(LOG_DEBUG, "psmintr: delay too long; resetting byte count\n");
1998             sc->inputbytes = 0;
1999             sc->syncerrors = 0;
2000         }
2001         sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT/1000000;
2002         sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT%1000000;
2003         timevaladd(&sc->inputtimeout, &tv);
2004
2005         sc->ipacket[sc->inputbytes++] = c;
2006         if (sc->inputbytes < sc->mode.packetsize) 
2007             continue;
2008
2009 #if 0
2010         log(LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
2011             sc->ipacket[0], sc->ipacket[1], sc->ipacket[2],
2012             sc->ipacket[3], sc->ipacket[4], sc->ipacket[5]);
2013 #endif
2014
2015         c = sc->ipacket[0];
2016
2017         if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
2018             log(LOG_DEBUG, "psmintr: out of sync (%04x != %04x).\n", 
2019                 c & sc->mode.syncmask[0], sc->mode.syncmask[1]);
2020             ++sc->syncerrors;
2021             if (sc->syncerrors < sc->mode.packetsize) {
2022                 log(LOG_DEBUG, "psmintr: discard a byte (%d).\n", sc->syncerrors);
2023                 --sc->inputbytes;
2024                 bcopy(&sc->ipacket[1], &sc->ipacket[0], sc->inputbytes);
2025             } else if (sc->syncerrors == sc->mode.packetsize) {
2026                 log(LOG_DEBUG, "psmintr: re-enable the mouse.\n");
2027                 sc->inputbytes = 0;
2028                 disable_aux_dev(sc->kbdc);
2029                 enable_aux_dev(sc->kbdc);
2030             } else if (sc->syncerrors < PSM_SYNCERR_THRESHOLD1) {
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 >= PSM_SYNCERR_THRESHOLD1) {
2035                 log(LOG_DEBUG, "psmintr: reset the mouse.\n");
2036                 reinitialize(sc, TRUE);
2037             }
2038             continue;
2039         }
2040
2041         /* 
2042          * A kludge for Kensington device! 
2043          * The MSB of the horizontal count appears to be stored in 
2044          * a strange place.
2045          */
2046         if (sc->hw.model == MOUSE_MODEL_THINK)
2047             sc->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
2048
2049         /* ignore the overflow bits... */
2050         x = (c & MOUSE_PS2_XNEG) ?  sc->ipacket[1] - 256 : sc->ipacket[1];
2051         y = (c & MOUSE_PS2_YNEG) ?  sc->ipacket[2] - 256 : sc->ipacket[2];
2052         z = 0;
2053         ms.obutton = sc->button;                  /* previous button state */
2054         ms.button = butmap[c & MOUSE_PS2_BUTTONS];
2055         /* `tapping' action */
2056         if (sc->config & PSM_CONFIG_FORCETAP)
2057             ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2058
2059         switch (sc->hw.model) {
2060
2061         case MOUSE_MODEL_EXPLORER:
2062             /*
2063              *          b7 b6 b5 b4 b3 b2 b1 b0
2064              * byte 1:  oy ox sy sx 1  M  R  L
2065              * byte 2:  x  x  x  x  x  x  x  x
2066              * byte 3:  y  y  y  y  y  y  y  y
2067              * byte 4:  *  *  S2 S1 s  d2 d1 d0
2068              *
2069              * L, M, R, S1, S2: left, middle, right and side buttons
2070              * s: wheel data sign bit
2071              * d2-d0: wheel data
2072              */
2073             z = (sc->ipacket[3] & MOUSE_EXPLORER_ZNEG)
2074                 ? (sc->ipacket[3] & 0x0f) - 16 : (sc->ipacket[3] & 0x0f);
2075             ms.button |= (sc->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN)
2076                 ? MOUSE_BUTTON4DOWN : 0;
2077             ms.button |= (sc->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN)
2078                 ? MOUSE_BUTTON5DOWN : 0;
2079             break;
2080
2081         case MOUSE_MODEL_INTELLI:
2082         case MOUSE_MODEL_NET:
2083             /* wheel data is in the fourth byte */
2084             z = (char)sc->ipacket[3];
2085             /* some mice may send 7 when there is no Z movement?! XXX */
2086             if ((z >= 7) || (z <= -7))
2087                 z = 0;
2088             /* some compatible mice have additional buttons */
2089             ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN)
2090                 ? MOUSE_BUTTON4DOWN : 0;
2091             ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN)
2092                 ? MOUSE_BUTTON5DOWN : 0;
2093             break;
2094
2095         case MOUSE_MODEL_MOUSEMANPLUS:
2096             /*
2097              * PS2++ protocl packet
2098              *
2099              *          b7 b6 b5 b4 b3 b2 b1 b0
2100              * byte 1:  *  1  p3 p2 1  *  *  *
2101              * byte 2:  c1 c2 p1 p0 d1 d0 1  0
2102              *
2103              * p3-p0: packet type
2104              * c1, c2: c1 & c2 == 1, if p2 == 0
2105              *         c1 & c2 == 0, if p2 == 1
2106              *
2107              * packet type: 0 (device type)
2108              * See comments in enable_mmanplus() below.
2109              * 
2110              * packet type: 1 (wheel data)
2111              *
2112              *          b7 b6 b5 b4 b3 b2 b1 b0
2113              * byte 3:  h  *  B5 B4 s  d2 d1 d0
2114              *
2115              * h: 1, if horizontal roller data
2116              *    0, if vertical roller data
2117              * B4, B5: button 4 and 5
2118              * s: sign bit
2119              * d2-d0: roller data
2120              *
2121              * packet type: 2 (reserved)
2122              */
2123             if (((c & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
2124                     && (abs(x) > 191)
2125                     && MOUSE_PS2PLUS_CHECKBITS(sc->ipacket)) {
2126                 /* the extended data packet encodes button and wheel events */
2127                 switch (MOUSE_PS2PLUS_PACKET_TYPE(sc->ipacket)) {
2128                 case 1:
2129                     /* wheel data packet */
2130                     x = y = 0;
2131                     if (sc->ipacket[2] & 0x80) {
2132                         /* horizontal roller count - ignore it XXX*/
2133                     } else {
2134                         /* vertical roller count */
2135                         z = (sc->ipacket[2] & MOUSE_PS2PLUS_ZNEG)
2136                             ? (sc->ipacket[2] & 0x0f) - 16
2137                             : (sc->ipacket[2] & 0x0f);
2138                     }
2139                     ms.button |= (sc->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
2140                         ? MOUSE_BUTTON4DOWN : 0;
2141                     ms.button |= (sc->ipacket[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
2142                         ? MOUSE_BUTTON5DOWN : 0;
2143                     break;
2144                 case 2:
2145                     /* this packet type is reserved by Logitech... */
2146                     /*
2147                      * IBM ScrollPoint Mouse uses this packet type to
2148                      * encode both vertical and horizontal scroll movement.
2149                      */
2150                     x = y = 0;
2151                     /* horizontal count */
2152                     if (sc->ipacket[2] & 0x0f)
2153                         z = (sc->ipacket[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
2154                     /* vertical count */
2155                     if (sc->ipacket[2] & 0xf0)
2156                         z = (sc->ipacket[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
2157 #if 0
2158                     /* vertical count */
2159                     z = (sc->ipacket[2] & MOUSE_SPOINT_ZNEG)
2160                         ? ((sc->ipacket[2] >> 4) & 0x0f) - 16
2161                         : ((sc->ipacket[2] >> 4) & 0x0f);
2162                     /* horizontal count */
2163                     w = (sc->ipacket[2] & MOUSE_SPOINT_WNEG)
2164                         ? (sc->ipacket[2] & 0x0f) - 16
2165                         : (sc->ipacket[2] & 0x0f);
2166 #endif
2167                     break;
2168                 case 0:
2169                     /* device type packet - shouldn't happen */
2170                     /* FALL THROUGH */
2171                 default:
2172                     x = y = 0;
2173                     ms.button = ms.obutton;
2174                     if (bootverbose)
2175                         log(LOG_DEBUG, "psmintr: unknown PS2++ packet type %d: "
2176                                        "0x%02x 0x%02x 0x%02x\n",
2177                             MOUSE_PS2PLUS_PACKET_TYPE(sc->ipacket),
2178                             sc->ipacket[0], sc->ipacket[1], sc->ipacket[2]);
2179                     break;
2180                 }
2181             } else {
2182                 /* preserve button states */
2183                 ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2184             }
2185             break;
2186
2187         case MOUSE_MODEL_GLIDEPOINT:
2188             /* `tapping' action */
2189             ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2190             break;
2191
2192         case MOUSE_MODEL_NETSCROLL:
2193             /* three addtional bytes encode buttons and wheel events */
2194             ms.button |= (sc->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
2195                 ? MOUSE_BUTTON4DOWN : 0;
2196             ms.button |= (sc->ipacket[3] & MOUSE_PS2_BUTTON1DOWN)
2197                 ? MOUSE_BUTTON5DOWN : 0;
2198             z = (sc->ipacket[3] & MOUSE_PS2_XNEG) 
2199                 ? sc->ipacket[4] - 256 : sc->ipacket[4];
2200             break;
2201
2202         case MOUSE_MODEL_THINK:
2203             /* the fourth button state in the first byte */
2204             ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
2205             break;
2206
2207         case MOUSE_MODEL_VERSAPAD:
2208             /* VersaPad PS/2 absolute mode message format
2209              *
2210              * [packet1]     7   6   5   4   3   2   1   0(LSB)
2211              *  ipacket[0]:  1   1   0   A   1   L   T   R
2212              *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
2213              *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
2214              *  ipacket[3]:  1   1   1   A   1   L   T   R
2215              *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
2216              *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
2217              *
2218              * [note]
2219              *  R: right physical mouse button (1=on)
2220              *  T: touch pad virtual button (1=tapping)
2221              *  L: left physical mouse button (1=on)
2222              *  A: position data is valid (1=valid)
2223              *  H: horizontal data (12bit signed integer. H11 is sign bit.)
2224              *  V: vertical data (12bit signed integer. V11 is sign bit.)
2225              *  P: pressure data
2226              *
2227              * Tapping is mapped to MOUSE_BUTTON4.
2228              */
2229             ms.button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
2230             ms.button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2231             x = y = 0;
2232             if (c & MOUSE_PS2VERSA_IN_USE) {
2233                 x0 = sc->ipacket[1] | (((sc->ipacket[4]) & 0x0f) << 8);
2234                 y0 = sc->ipacket[2] | (((sc->ipacket[4]) & 0xf0) << 4);
2235                 if (x0 & 0x800)
2236                     x0 -= 0x1000;
2237                 if (y0 & 0x800)
2238                     y0 -= 0x1000;
2239                 if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2240                     x = sc->xold - x0;
2241                     y = y0 - sc->yold;
2242                     if (x < 0)  /* XXX */
2243                         x++;
2244                     else if (x)
2245                         x--;
2246                     if (y < 0)
2247                         y++;
2248                     else if (y)
2249                         y--;
2250                 } else {
2251                     sc->flags |= PSM_FLAGS_FINGERDOWN;
2252                 }
2253                 sc->xold = x0;
2254                 sc->yold = y0;
2255             } else {
2256                 sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2257             }
2258             c = ((x < 0) ? MOUSE_PS2_XNEG : 0)
2259                 | ((y < 0) ? MOUSE_PS2_YNEG : 0);
2260             break;
2261
2262         case MOUSE_MODEL_4D:
2263             /*
2264              *          b7 b6 b5 b4 b3 b2 b1 b0
2265              * byte 1:  s2 d2 s1 d1 1  M  R  L
2266              * byte 2:  sx x  x  x  x  x  x  x
2267              * byte 3:  sy y  y  y  y  y  y  y
2268              *
2269              * s1: wheel 1 direction
2270              * d1: wheel 1 data
2271              * s2: wheel 2 direction
2272              * d2: wheel 2 data
2273              */
2274             x = (sc->ipacket[1] & 0x80) ? sc->ipacket[1] - 256 : sc->ipacket[1];
2275             y = (sc->ipacket[2] & 0x80) ? sc->ipacket[2] - 256 : sc->ipacket[2];
2276             switch (c & MOUSE_4D_WHEELBITS) {
2277             case 0x10:
2278                 z = 1;
2279                 break;
2280             case 0x30:
2281                 z = -1;
2282                 break;
2283             case 0x40:  /* 2nd wheel turning right XXX */
2284                 z = 2;
2285                 break;
2286             case 0xc0:  /* 2nd wheel turning left XXX */
2287                 z = -2;
2288                 break;
2289             }
2290             break;
2291
2292         case MOUSE_MODEL_4DPLUS:
2293             if ((x < 16 - 256) && (y < 16 - 256)) {
2294                 /*
2295                  *          b7 b6 b5 b4 b3 b2 b1 b0
2296                  * byte 1:  0  0  1  1  1  M  R  L
2297                  * byte 2:  0  0  0  0  1  0  0  0
2298                  * byte 3:  0  0  0  0  S  s  d1 d0
2299                  *
2300                  * L, M, R, S: left, middle, right and side buttons
2301                  * s: wheel data sign bit
2302                  * d1-d0: wheel data
2303                  */
2304                 x = y = 0;
2305                 if (sc->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2306                     ms.button |= MOUSE_BUTTON4DOWN;
2307                 z = (sc->ipacket[2] & MOUSE_4DPLUS_ZNEG)
2308                         ? ((sc->ipacket[2] & 0x07) - 8)
2309                         : (sc->ipacket[2] & 0x07) ;
2310             } else {
2311                 /* preserve previous button states */
2312                 ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2313             }
2314             break;
2315
2316         case MOUSE_MODEL_GENERIC:
2317         default:
2318             break;
2319         }
2320
2321         /* scale values */
2322         if (sc->mode.accelfactor >= 1) {
2323             if (x != 0) {
2324                 x = x * x / sc->mode.accelfactor;
2325                 if (x == 0)
2326                     x = 1;
2327                 if (c & MOUSE_PS2_XNEG)
2328                     x = -x;
2329             }
2330             if (y != 0) {
2331                 y = y * y / sc->mode.accelfactor;
2332                 if (y == 0)
2333                     y = 1;
2334                 if (c & MOUSE_PS2_YNEG)
2335                     y = -y;
2336             }
2337         }
2338
2339         ms.dx = x;
2340         ms.dy = y;
2341         ms.dz = z;
2342         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0) 
2343             | (ms.obutton ^ ms.button);
2344
2345         if (sc->mode.level < PSM_LEVEL_NATIVE)
2346             sc->inputbytes = tame_mouse(sc, &ms, sc->ipacket);
2347
2348         sc->status.flags |= ms.flags;
2349         sc->status.dx += ms.dx;
2350         sc->status.dy += ms.dy;
2351         sc->status.dz += ms.dz;
2352         sc->status.button = ms.button;
2353         sc->button = ms.button;
2354
2355         sc->watchdog = FALSE;
2356
2357         /* queue data */
2358         if (sc->queue.count + sc->inputbytes < sizeof(sc->queue.buf)) {
2359             l = min(sc->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
2360             bcopy(&sc->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
2361             if (sc->inputbytes > l)
2362                 bcopy(&sc->ipacket[l], &sc->queue.buf[0], sc->inputbytes - l);
2363             sc->queue.tail = 
2364                 (sc->queue.tail + sc->inputbytes) % sizeof(sc->queue.buf);
2365             sc->queue.count += sc->inputbytes;
2366         }
2367         sc->inputbytes = 0;
2368
2369         if (sc->state & PSM_ASLP) {
2370             sc->state &= ~PSM_ASLP;
2371             wakeup((caddr_t) sc);
2372         }
2373         selwakeup(&sc->rsel);
2374     }
2375 }
2376
2377 static int
2378 psmpoll(dev_t dev, int events, struct thread *td)
2379 {
2380     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
2381     int s;
2382     int revents = 0;
2383
2384     /* Return true if a mouse event available */
2385     s = spltty();
2386     if (events & (POLLIN | POLLRDNORM)) {
2387         if (sc->queue.count > 0)
2388             revents |= events & (POLLIN | POLLRDNORM);
2389         else
2390             selrecord(td, &sc->rsel);
2391     }
2392     splx(s);
2393
2394     return (revents);
2395 }
2396
2397 /* vendor/model specific routines */
2398
2399 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
2400 {
2401     if (set_mouse_resolution(kbdc, res) != res)
2402         return FALSE;
2403     if (set_mouse_scaling(kbdc, scale)
2404         && set_mouse_scaling(kbdc, scale)
2405         && set_mouse_scaling(kbdc, scale) 
2406         && (get_mouse_status(kbdc, status, 0, 3) >= 3)) 
2407         return TRUE;
2408     return FALSE;
2409 }
2410
2411 static int 
2412 mouse_ext_command(KBDC kbdc, int command)
2413 {
2414     int c;
2415
2416     c = (command >> 6) & 0x03;
2417     if (set_mouse_resolution(kbdc, c) != c)
2418         return FALSE;
2419     c = (command >> 4) & 0x03;
2420     if (set_mouse_resolution(kbdc, c) != c)
2421         return FALSE;
2422     c = (command >> 2) & 0x03;
2423     if (set_mouse_resolution(kbdc, c) != c)
2424         return FALSE;
2425     c = (command >> 0) & 0x03;
2426     if (set_mouse_resolution(kbdc, c) != c)
2427         return FALSE;
2428     return TRUE;
2429 }
2430
2431 #if notyet
2432 /* Logitech MouseMan Cordless II */
2433 static int
2434 enable_lcordless(struct psm_softc *sc)
2435 {
2436     int status[3];
2437     int ch;
2438
2439     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
2440         return FALSE;
2441     if (status[1] == PSMD_RES_HIGH)
2442         return FALSE;
2443     ch = (status[0] & 0x07) - 1;        /* channel # */
2444     if ((ch <= 0) || (ch > 4))
2445         return FALSE;
2446     /* 
2447      * status[1]: always one?
2448      * status[2]: battery status? (0-100)
2449      */
2450     return TRUE;
2451 }
2452 #endif /* notyet */
2453
2454 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
2455 static int
2456 enable_groller(struct psm_softc *sc)
2457 {
2458     int status[3];
2459
2460     /*
2461      * The special sequence to enable the fourth button and the
2462      * roller. Immediately after this sequence check status bytes.
2463      * if the mouse is NetScroll, the second and the third bytes are 
2464      * '3' and 'D'.
2465      */
2466
2467     /*
2468      * If the mouse is an ordinary PS/2 mouse, the status bytes should
2469      * look like the following.
2470      * 
2471      * byte 1 bit 7 always 0
2472      *        bit 6 stream mode (0)
2473      *        bit 5 disabled (0)
2474      *        bit 4 1:1 scaling (0)
2475      *        bit 3 always 0
2476      *        bit 0-2 button status
2477      * byte 2 resolution (PSMD_RES_HIGH)
2478      * byte 3 report rate (?)
2479      */
2480
2481     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2482         return FALSE;
2483     if ((status[1] != '3') || (status[2] != 'D'))
2484         return FALSE;
2485     /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
2486     sc->hw.buttons = 4;
2487     return TRUE;
2488 }
2489
2490 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
2491 static int
2492 enable_gmouse(struct psm_softc *sc)
2493 {
2494     int status[3];
2495
2496     /*
2497      * The special sequence to enable the middle, "rubber" button. 
2498      * Immediately after this sequence check status bytes.
2499      * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse, 
2500      * the second and the third bytes are '3' and 'U'.
2501      * NOTE: NetMouse reports that it has three buttons although it has
2502      * two buttons and a rubber button. NetMouse Pro and MIE Mouse
2503      * say they have three buttons too and they do have a button on the
2504      * side...
2505      */
2506     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2507         return FALSE;
2508     if ((status[1] != '3') || (status[2] != 'U'))
2509         return FALSE;
2510     return TRUE;
2511 }
2512
2513 /* ALPS GlidePoint */
2514 static int
2515 enable_aglide(struct psm_softc *sc)
2516 {
2517     int status[3];
2518
2519     /*
2520      * The special sequence to obtain ALPS GlidePoint specific
2521      * information. Immediately after this sequence, status bytes will 
2522      * contain something interesting.
2523      * NOTE: ALPS produces several models of GlidePoint. Some of those
2524      * do not respond to this sequence, thus, cannot be detected this way.
2525      */
2526     if (set_mouse_sampling_rate(sc->kbdc, 100) != 100)
2527         return FALSE;
2528     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
2529         return FALSE;
2530     if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
2531         return FALSE;
2532     return TRUE;
2533 }
2534
2535 /* Kensington ThinkingMouse/Trackball */
2536 static int
2537 enable_kmouse(struct psm_softc *sc)
2538 {
2539     static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
2540     KBDC kbdc = sc->kbdc;
2541     int status[3];
2542     int id1;
2543     int id2;
2544     int i;
2545
2546     id1 = get_aux_id(kbdc);
2547     if (set_mouse_sampling_rate(kbdc, 10) != 10)
2548         return FALSE;
2549     /* 
2550      * The device is now in the native mode? It returns a different
2551      * ID value...
2552      */
2553     id2 = get_aux_id(kbdc);
2554     if ((id1 == id2) || (id2 != 2))
2555         return FALSE;
2556
2557     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
2558         return FALSE;
2559 #if PSM_DEBUG >= 2
2560     /* at this point, resolution is LOW, sampling rate is 10/sec */
2561     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2562         return FALSE;
2563 #endif
2564
2565     /*
2566      * The special sequence to enable the third and fourth buttons.
2567      * Otherwise they behave like the first and second buttons.
2568      */
2569     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2570         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2571             return FALSE;
2572     }
2573
2574     /* 
2575      * At this point, the device is using default resolution and
2576      * sampling rate for the native mode. 
2577      */
2578     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2579         return FALSE;
2580     if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
2581         return FALSE;
2582
2583     /* the device appears be enabled by this sequence, diable it for now */
2584     disable_aux_dev(kbdc);
2585     empty_aux_buffer(kbdc, 5);
2586
2587     return TRUE;
2588 }
2589
2590 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
2591 static int
2592 enable_mmanplus(struct psm_softc *sc)
2593 {
2594     KBDC kbdc = sc->kbdc;
2595     int data[3];
2596
2597     /* the special sequence to enable the fourth button and the roller. */
2598     /*
2599      * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
2600      * must be called exactly three times since the last RESET command
2601      * before this sequence. XXX
2602      */
2603     if (!set_mouse_scaling(kbdc, 1))
2604         return FALSE;
2605     if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
2606         return FALSE;
2607     if (get_mouse_status(kbdc, data, 1, 3) < 3)
2608         return FALSE;
2609
2610     /*
2611      * PS2++ protocl, packet type 0
2612      *
2613      *          b7 b6 b5 b4 b3 b2 b1 b0
2614      * byte 1:  *  1  p3 p2 1  *  *  *
2615      * byte 2:  1  1  p1 p0 m1 m0 1  0
2616      * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
2617      *
2618      * p3-p0: packet type: 0
2619      * m7-m0: model ID: MouseMan+:0x50, FirstMouse+:0x51, ScrollPoint:0x58...
2620      */
2621     /* check constant bits */
2622     if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
2623         return FALSE;
2624     if ((data[1] & 0xc3) != 0xc2)
2625         return FALSE;
2626     /* check d3-d0 in byte 2 */
2627     if (!MOUSE_PS2PLUS_CHECKBITS(data))
2628         return FALSE;
2629     /* check p3-p0 */
2630     if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
2631         return FALSE;
2632
2633     sc->hw.hwid &= 0x00ff;
2634     sc->hw.hwid |= data[2] << 8;        /* save model ID */
2635
2636     /*
2637      * MouseMan+ (or FirstMouse+) is now in its native mode, in which
2638      * the wheel and the fourth button events are encoded in the
2639      * special data packet. The mouse may be put in the IntelliMouse mode
2640      * if it is initialized by the IntelliMouse's method.
2641      */
2642     return TRUE;
2643 }
2644
2645 /* MS IntelliMouse Explorer */
2646 static int
2647 enable_msexplorer(struct psm_softc *sc)
2648 {
2649     static unsigned char rate0[] = { 200, 100, 80, };
2650     static unsigned char rate1[] = { 200, 200, 80, };
2651     KBDC kbdc = sc->kbdc;
2652     int id;
2653     int i;
2654
2655     /* the special sequence to enable the extra buttons and the roller. */
2656     for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i) {
2657         if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
2658             return FALSE;
2659     }
2660     /* the device will give the genuine ID only after the above sequence */
2661     id = get_aux_id(kbdc);
2662     if (id != PSM_EXPLORER_ID)
2663         return FALSE;
2664
2665     sc->hw.hwid = id;
2666     sc->hw.buttons = 5;         /* IntelliMouse Explorer XXX */
2667
2668     /*
2669      * XXX: this is a kludge to fool some KVM switch products
2670      * which think they are clever enough to know the 4-byte IntelliMouse
2671      * protocol, and assume any other protocols use 3-byte packets.
2672      * They don't convey 4-byte data packets from the IntelliMouse Explorer 
2673      * correctly to the host computer because of this!
2674      * The following sequence is actually IntelliMouse's "wake up"
2675      * sequence; it will make the KVM think the mouse is IntelliMouse
2676      * when it is in fact IntelliMouse Explorer.
2677      */
2678     for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i) {
2679         if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
2680             break;
2681     }
2682     id = get_aux_id(kbdc);
2683
2684     return TRUE;
2685 }
2686
2687 /* MS IntelliMouse */
2688 static int
2689 enable_msintelli(struct psm_softc *sc)
2690 {
2691     /*
2692      * Logitech MouseMan+ and FirstMouse+ will also respond to this
2693      * probe routine and act like IntelliMouse.
2694      */
2695
2696     static unsigned char rate[] = { 200, 100, 80, };
2697     KBDC kbdc = sc->kbdc;
2698     int id;
2699     int i;
2700
2701     /* the special sequence to enable the third button and the roller. */
2702     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2703         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2704             return FALSE;
2705     }
2706     /* the device will give the genuine ID only after the above sequence */
2707     id = get_aux_id(kbdc);
2708     if (id != PSM_INTELLI_ID)
2709         return FALSE;
2710
2711     sc->hw.hwid = id;
2712     sc->hw.buttons = 3;
2713
2714     return TRUE;
2715 }
2716
2717 /* A4 Tech 4D Mouse */
2718 static int
2719 enable_4dmouse(struct psm_softc *sc)
2720 {
2721     /*
2722      * Newer wheel mice from A4 Tech may use the 4D+ protocol.
2723      */
2724
2725     static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
2726     KBDC kbdc = sc->kbdc;
2727     int id;
2728     int i;
2729
2730     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2731         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2732             return FALSE;
2733     }
2734     id = get_aux_id(kbdc);
2735     /*
2736      * WinEasy 4D, 4 Way Scroll 4D: 6
2737      * Cable-Free 4D: 8 (4DPLUS)
2738      * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
2739      */
2740     if (id != PSM_4DMOUSE_ID)
2741         return FALSE;
2742
2743     sc->hw.hwid = id;
2744     sc->hw.buttons = 3;         /* XXX some 4D mice have 4? */
2745
2746     return TRUE;
2747 }
2748
2749 /* A4 Tech 4D+ Mouse */
2750 static int
2751 enable_4dplus(struct psm_softc *sc)
2752 {
2753     /*
2754      * Newer wheel mice from A4 Tech seem to use this protocol.
2755      * Older models are recognized as either 4D Mouse or IntelliMouse.
2756      */
2757     KBDC kbdc = sc->kbdc;
2758     int id;
2759
2760     /*
2761      * enable_4dmouse() already issued the following ID sequence...
2762     static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
2763     int i;
2764
2765     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2766         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2767             return FALSE;
2768     }
2769     */
2770
2771     id = get_aux_id(kbdc);
2772     if (id != PSM_4DPLUS_ID)
2773         return FALSE;
2774
2775     sc->hw.hwid = id;
2776     sc->hw.buttons = 4;         /* XXX */
2777
2778     return TRUE;
2779 }
2780
2781 /* Interlink electronics VersaPad */
2782 static int
2783 enable_versapad(struct psm_softc *sc)
2784 {
2785     KBDC kbdc = sc->kbdc;
2786     int data[3];
2787
2788     set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
2789     set_mouse_sampling_rate(kbdc, 100);         /* set rate 100 */
2790     set_mouse_scaling(kbdc, 1);                 /* set scale 1:1 */
2791     set_mouse_scaling(kbdc, 1);                 /* set scale 1:1 */
2792     set_mouse_scaling(kbdc, 1);                 /* set scale 1:1 */
2793     set_mouse_scaling(kbdc, 1);                 /* set scale 1:1 */
2794     if (get_mouse_status(kbdc, data, 0, 3) < 3) /* get status */
2795         return FALSE;
2796     if (data[2] != 0xa || data[1] != 0 )        /* rate == 0xa && res. == 0 */
2797         return FALSE;
2798     set_mouse_scaling(kbdc, 1);                 /* set scale 1:1 */
2799
2800     sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
2801
2802     return TRUE;                                /* PS/2 absolute mode */
2803 }
2804
2805 static int
2806 psmresume(device_t dev)
2807 {
2808     struct psm_softc *sc = device_get_softc(dev);
2809     int unit = device_get_unit(dev);
2810     int err;
2811
2812     if (verbose >= 2)
2813         log(LOG_NOTICE, "psm%d: system resume hook called.\n", unit);
2814
2815     if (!(sc->config & PSM_CONFIG_HOOKRESUME))
2816         return (0);
2817
2818     err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
2819
2820     if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
2821         /* 
2822          * Release the blocked process; it must be notified that the device
2823          * cannot be accessed anymore.
2824          */
2825         sc->state &= ~PSM_ASLP;
2826         wakeup((caddr_t)sc);
2827     }
2828
2829     if (verbose >= 2)
2830         log(LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit);
2831
2832     return (err);
2833 }
2834
2835 DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);