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