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