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