]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/dev/atkbdc/psm.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / sys / dev / atkbdc / psm.c
1 /*-
2  * Copyright (c) 1992, 1993 Erik Forsberg.
3  * Copyright (c) 1996, 1997 Kazutaka YOKOTA.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY EXPRESS OR IMPLIED
13  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
15  * NO EVENT SHALL I BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
16  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
17  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
18  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
19  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
20  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
21  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22  */
23 /*
24  *  Ported to 386bsd Oct 17, 1992
25  *  Sandi Donno, Computer Science, University of Cape Town, South Africa
26  *  Please send bug reports to sandi@cs.uct.ac.za
27  *
28  *  Thanks are also due to Rick Macklem, rick@snowhite.cis.uoguelph.ca -
29  *  although I was only partially successful in getting the alpha release
30  *  of his "driver for the Logitech and ATI Inport Bus mice for use with
31  *  386bsd and the X386 port" to work with my Microsoft mouse, I nevertheless
32  *  found his code to be an invaluable reference when porting this driver
33  *  to 386bsd.
34  *
35  *  Further modifications for latest 386BSD+patchkit and port to NetBSD,
36  *  Andrew Herbert <andrew@werple.apana.org.au> - 8 June 1993
37  *
38  *  Cloned from the Microsoft Bus Mouse driver, also by Erik Forsberg, by
39  *  Andrew Herbert - 12 June 1993
40  *
41  *  Modified for PS/2 mouse by Charles Hannum <mycroft@ai.mit.edu>
42  *  - 13 June 1993
43  *
44  *  Modified for PS/2 AUX mouse by Shoji Yuen <yuen@nuie.nagoya-u.ac.jp>
45  *  - 24 October 1993
46  *
47  *  Hardware access routines and probe logic rewritten by
48  *  Kazutaka Yokota <yokota@zodiac.mech.utsunomiya-u.ac.jp>
49  *  - 3, 14, 22 October 1996.
50  *  - 12 November 1996. IOCTLs and rearranging `psmread', `psmioctl'...
51  *  - 14, 30 November 1996. Uses `kbdio.c'.
52  *  - 13 December 1996. Uses queuing version of `kbdio.c'.
53  *  - January/February 1997. Tweaked probe logic for
54  *    HiNote UltraII/Latitude/Armada laptops.
55  *  - 30 July 1997. Added APM support.
56  *  - 5 March 1997. Defined driver configuration flags (PSM_CONFIG_XXX).
57  *    Improved sync check logic.
58  *    Vendor specific support routines.
59  */
60
61 #include <sys/cdefs.h>
62 __FBSDID("$FreeBSD$");
63
64 #include "opt_isa.h"
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/filio.h>
74 #include <sys/poll.h>
75 #include <sys/sigio.h>
76 #include <sys/signalvar.h>
77 #include <sys/syslog.h>
78 #include <machine/bus.h>
79 #include <sys/rman.h>
80 #include <sys/selinfo.h>
81 #include <sys/sysctl.h>
82 #include <sys/time.h>
83 #include <sys/uio.h>
84
85 #include <sys/limits.h>
86 #include <sys/mouse.h>
87 #include <machine/resource.h>
88
89 #ifdef DEV_ISA
90 #include <isa/isavar.h>
91 #endif
92
93 #include <dev/atkbdc/atkbdcreg.h>
94 #include <dev/atkbdc/psm.h>
95
96 /*
97  * Driver specific options: the following options may be set by
98  * `options' statements in the kernel configuration file.
99  */
100
101 /* debugging */
102 #ifndef PSM_DEBUG
103 #define PSM_DEBUG       0       /*
104                                  * logging: 0: none, 1: brief, 2: verbose
105                                  *          3: sync errors, 4: all packets
106                                  */
107 #endif
108 #define VLOG(level, args)       do {    \
109         if (verbose >= level)           \
110                 log args;               \
111 } while (0)
112
113 #ifndef PSM_INPUT_TIMEOUT
114 #define PSM_INPUT_TIMEOUT       2000000 /* 2 sec */
115 #endif
116
117 #ifndef PSM_TAP_TIMEOUT
118 #define PSM_TAP_TIMEOUT         125000
119 #endif
120
121 #ifndef PSM_TAP_THRESHOLD
122 #define PSM_TAP_THRESHOLD       25
123 #endif
124
125 /* end of driver specific options */
126
127 #define PSMCPNP_DRIVER_NAME     "psmcpnp"
128
129 /* input queue */
130 #define PSM_BUFSIZE             960
131 #define PSM_SMALLBUFSIZE        240
132
133 /* operation levels */
134 #define PSM_LEVEL_BASE          0
135 #define PSM_LEVEL_STANDARD      1
136 #define PSM_LEVEL_NATIVE        2
137 #define PSM_LEVEL_MIN           PSM_LEVEL_BASE
138 #define PSM_LEVEL_MAX           PSM_LEVEL_NATIVE
139
140 /* Logitech PS2++ protocol */
141 #define MOUSE_PS2PLUS_CHECKBITS(b)      \
142     ((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
143 #define MOUSE_PS2PLUS_PACKET_TYPE(b)    \
144     (((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
145
146 /* some macros */
147 #define PSM_UNIT(dev)           (dev2unit(dev) >> 1)
148 #define PSM_NBLOCKIO(dev)       (dev2unit(dev) & 1)
149 #define PSM_MKMINOR(unit,block) (((unit) << 1) | ((block) ? 0:1))
150
151 /* ring buffer */
152 typedef struct ringbuf {
153         int             count;  /* # of valid elements in the buffer */
154         int             head;   /* head pointer */
155         int             tail;   /* tail poiner */
156         u_char buf[PSM_BUFSIZE];
157 } ringbuf_t;
158
159 /* data buffer */
160 typedef struct packetbuf {
161         u_char  ipacket[16];    /* interim input buffer */
162         int     inputbytes;     /* # of bytes in the input buffer */
163 } packetbuf_t;
164
165 #ifndef PSM_PACKETQUEUE
166 #define PSM_PACKETQUEUE 128
167 #endif
168
169 enum {
170         SYNAPTICS_SYSCTL_MIN_PRESSURE,
171         SYNAPTICS_SYSCTL_MAX_PRESSURE,
172         SYNAPTICS_SYSCTL_MAX_WIDTH,
173         SYNAPTICS_SYSCTL_MARGIN_TOP,
174         SYNAPTICS_SYSCTL_MARGIN_RIGHT,
175         SYNAPTICS_SYSCTL_MARGIN_BOTTOM,
176         SYNAPTICS_SYSCTL_MARGIN_LEFT,
177         SYNAPTICS_SYSCTL_NA_TOP,
178         SYNAPTICS_SYSCTL_NA_RIGHT,
179         SYNAPTICS_SYSCTL_NA_BOTTOM,
180         SYNAPTICS_SYSCTL_NA_LEFT,
181         SYNAPTICS_SYSCTL_WINDOW_MIN,
182         SYNAPTICS_SYSCTL_WINDOW_MAX,
183         SYNAPTICS_SYSCTL_MULTIPLICATOR,
184         SYNAPTICS_SYSCTL_WEIGHT_CURRENT,
185         SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS,
186         SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA,
187         SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED,
188         SYNAPTICS_SYSCTL_DIV_MIN,
189         SYNAPTICS_SYSCTL_DIV_MAX,
190         SYNAPTICS_SYSCTL_DIV_MAX_NA,
191         SYNAPTICS_SYSCTL_DIV_LEN,
192         SYNAPTICS_SYSCTL_TAP_MAX_DELTA,
193         SYNAPTICS_SYSCTL_TAP_MIN_QUEUE,
194         SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT,
195         SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA,
196         SYNAPTICS_SYSCTL_VSCROLL_VER_AREA,
197         SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA,
198         SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN,
199         SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX
200 };
201
202 typedef struct synapticsinfo {
203         struct sysctl_ctx_list   sysctl_ctx;
204         struct sysctl_oid       *sysctl_tree;
205         int                      directional_scrolls;
206         int                      min_pressure;
207         int                      max_pressure;
208         int                      max_width;
209         int                      margin_top;
210         int                      margin_right;
211         int                      margin_bottom;
212         int                      margin_left;
213         int                      na_top;
214         int                      na_right;
215         int                      na_bottom;
216         int                      na_left;
217         int                      window_min;
218         int                      window_max;
219         int                      multiplicator;
220         int                      weight_current;
221         int                      weight_previous;
222         int                      weight_previous_na;
223         int                      weight_len_squared;
224         int                      div_min;
225         int                      div_max;
226         int                      div_max_na;
227         int                      div_len;
228         int                      tap_max_delta;
229         int                      tap_min_queue;
230         int                      taphold_timeout;
231         int                      vscroll_ver_area;
232         int                      vscroll_hor_area;
233         int                      vscroll_min_delta;
234         int                      vscroll_div_min;
235         int                      vscroll_div_max;
236 } synapticsinfo_t;
237
238 typedef struct synapticspacket {
239         int                     x;
240         int                     y;
241 } synapticspacket_t;
242
243 #define SYNAPTICS_PACKETQUEUE 10
244 #define SYNAPTICS_QUEUE_CURSOR(x)                                       \
245         (x + SYNAPTICS_PACKETQUEUE) % SYNAPTICS_PACKETQUEUE
246
247 typedef struct synapticsaction {
248         synapticspacket_t       queue[SYNAPTICS_PACKETQUEUE];
249         int                     queue_len;
250         int                     queue_cursor;
251         int                     window_min;
252         int                     start_x;
253         int                     start_y;
254         int                     avg_dx;
255         int                     avg_dy;
256         int                     squelch_x;
257         int                     squelch_y;
258         int                     fingers_nb;
259         int                     tap_button;
260         int                     in_taphold;
261         int                     in_vscroll;
262 } synapticsaction_t;
263
264 /* driver control block */
265 struct psm_softc {              /* Driver status information */
266         int             unit;
267         struct selinfo  rsel;           /* Process selecting for Input */
268         u_char          state;          /* Mouse driver state */
269         int             config;         /* driver configuration flags */
270         int             flags;          /* other flags */
271         KBDC            kbdc;           /* handle to access kbd controller */
272         struct resource *intr;          /* IRQ resource */
273         void            *ih;            /* interrupt handle */
274         mousehw_t       hw;             /* hardware information */
275         synapticshw_t   synhw;          /* Synaptics hardware information */
276         synapticsinfo_t syninfo;        /* Synaptics configuration */
277         synapticsaction_t synaction;    /* Synaptics action context */
278         mousemode_t     mode;           /* operation mode */
279         mousemode_t     dflt_mode;      /* default operation mode */
280         mousestatus_t   status;         /* accumulated mouse movement */
281         ringbuf_t       queue;          /* mouse status queue */
282         packetbuf_t     pqueue[PSM_PACKETQUEUE]; /* mouse data queue */
283         int             pqueue_start;   /* start of data in queue */
284         int             pqueue_end;     /* end of data in queue */
285         int             button;         /* the latest button state */
286         int             xold;           /* previous absolute X position */
287         int             yold;           /* previous absolute Y position */
288         int             xaverage;       /* average X position */
289         int             yaverage;       /* average Y position */
290         int             squelch; /* level to filter movement at low speed */
291         int             zmax;   /* maximum pressure value for touchpads */
292         int             syncerrors; /* # of bytes discarded to synchronize */
293         int             pkterrors;  /* # of packets failed during quaranteen. */
294         struct timeval  inputtimeout;
295         struct timeval  lastsoftintr;   /* time of last soft interrupt */
296         struct timeval  lastinputerr;   /* time last sync error happened */
297         struct timeval  taptimeout;     /* tap timeout for touchpads */
298         int             watchdog;       /* watchdog timer flag */
299         struct callout_handle callout;  /* watchdog timer call out */
300         struct callout_handle softcallout; /* buffer timer call out */
301         struct cdev     *dev;
302         struct cdev     *bdev;
303         int             lasterr;
304         int             cmdcount;
305         struct sigio    *async;         /* Processes waiting for SIGIO */
306 };
307 static devclass_t psm_devclass;
308 #define PSM_SOFTC(unit) \
309     ((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
310
311 /* driver state flags (state) */
312 #define PSM_VALID               0x80
313 #define PSM_OPEN                1       /* Device is open */
314 #define PSM_ASLP                2       /* Waiting for mouse data */
315 #define PSM_SOFTARMED           4       /* Software interrupt armed */
316 #define PSM_NEED_SYNCBITS       8       /* Set syncbits using next data pkt */
317
318 /* driver configuration flags (config) */
319 #define PSM_CONFIG_RESOLUTION   0x000f  /* resolution */
320 #define PSM_CONFIG_ACCEL        0x00f0  /* acceleration factor */
321 #define PSM_CONFIG_NOCHECKSYNC  0x0100  /* disable sync. test */
322 #define PSM_CONFIG_NOIDPROBE    0x0200  /* disable mouse model probe */
323 #define PSM_CONFIG_NORESET      0x0400  /* don't reset the mouse */
324 #define PSM_CONFIG_FORCETAP     0x0800  /* assume `tap' action exists */
325 #define PSM_CONFIG_IGNPORTERROR 0x1000  /* ignore error in aux port test */
326 #define PSM_CONFIG_HOOKRESUME   0x2000  /* hook the system resume event */
327 #define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
328 #define PSM_CONFIG_SYNCHACK     0x8000  /* enable `out-of-sync' hack */
329
330 #define PSM_CONFIG_FLAGS        \
331     (PSM_CONFIG_RESOLUTION |    \
332     PSM_CONFIG_ACCEL |          \
333     PSM_CONFIG_NOCHECKSYNC |    \
334     PSM_CONFIG_SYNCHACK |       \
335     PSM_CONFIG_NOIDPROBE |      \
336     PSM_CONFIG_NORESET |        \
337     PSM_CONFIG_FORCETAP |       \
338     PSM_CONFIG_IGNPORTERROR |   \
339     PSM_CONFIG_HOOKRESUME |     \
340     PSM_CONFIG_INITAFTERSUSPEND)
341
342 /* other flags (flags) */
343 #define PSM_FLAGS_FINGERDOWN    0x0001  /* VersaPad finger down */
344
345 /* Tunables */
346 static int synaptics_support = 0;
347 TUNABLE_INT("hw.psm.synaptics_support", &synaptics_support);
348
349 static int verbose = PSM_DEBUG;
350 TUNABLE_INT("debug.psm.loglevel", &verbose);
351
352 /* for backward compatibility */
353 #define OLD_MOUSE_GETHWINFO     _IOR('M', 1, old_mousehw_t)
354 #define OLD_MOUSE_GETMODE       _IOR('M', 2, old_mousemode_t)
355 #define OLD_MOUSE_SETMODE       _IOW('M', 3, old_mousemode_t)
356
357 typedef struct old_mousehw {
358         int     buttons;
359         int     iftype;
360         int     type;
361         int     hwid;
362 } old_mousehw_t;
363
364 typedef struct old_mousemode {
365         int     protocol;
366         int     rate;
367         int     resolution;
368         int     accelfactor;
369 } old_mousemode_t;
370
371 /* packet formatting function */
372 typedef int     packetfunc_t(struct psm_softc *, u_char *, int *, int,
373     mousestatus_t *);
374
375 /* function prototypes */
376 static void     psmidentify(driver_t *, device_t);
377 static int      psmprobe(device_t);
378 static int      psmattach(device_t);
379 static int      psmdetach(device_t);
380 static int      psmresume(device_t);
381
382 static d_open_t         psmopen;
383 static d_close_t        psmclose;
384 static d_read_t         psmread;
385 static d_write_t        psmwrite;
386 static d_ioctl_t        psmioctl;
387 static d_poll_t         psmpoll;
388
389 static int      enable_aux_dev(KBDC);
390 static int      disable_aux_dev(KBDC);
391 static int      get_mouse_status(KBDC, int *, int, int);
392 static int      get_aux_id(KBDC);
393 static int      set_mouse_sampling_rate(KBDC, int);
394 static int      set_mouse_scaling(KBDC, int);
395 static int      set_mouse_resolution(KBDC, int);
396 static int      set_mouse_mode(KBDC);
397 static int      get_mouse_buttons(KBDC);
398 static int      is_a_mouse(int);
399 static void     recover_from_error(KBDC);
400 static int      restore_controller(KBDC, int);
401 static int      doinitialize(struct psm_softc *, mousemode_t *);
402 static int      doopen(struct psm_softc *, int);
403 static int      reinitialize(struct psm_softc *, int);
404 static char     *model_name(int);
405 static void     psmsoftintr(void *);
406 static void     psmintr(void *);
407 static void     psmtimeout(void *);
408 static int      timeelapsed(const struct timeval *, int, int,
409                     const struct timeval *);
410 static void     dropqueue(struct psm_softc *);
411 static void     flushpackets(struct psm_softc *);
412 static void     proc_mmanplus(struct psm_softc *, packetbuf_t *,
413                     mousestatus_t *, int *, int *, int *);
414 static int      proc_synaptics(struct psm_softc *, packetbuf_t *,
415                     mousestatus_t *, int *, int *, int *);
416 static void     proc_versapad(struct psm_softc *, packetbuf_t *,
417                     mousestatus_t *, int *, int *, int *);
418 static int      tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *,
419                     u_char *);
420
421 /* vendor specific features */
422 typedef int     probefunc_t(struct psm_softc *);
423
424 static int      mouse_id_proc1(KBDC, int, int, int *);
425 static int      mouse_ext_command(KBDC, int);
426
427 static probefunc_t      enable_groller;
428 static probefunc_t      enable_gmouse;
429 static probefunc_t      enable_aglide;
430 static probefunc_t      enable_kmouse;
431 static probefunc_t      enable_msexplorer;
432 static probefunc_t      enable_msintelli;
433 static probefunc_t      enable_4dmouse;
434 static probefunc_t      enable_4dplus;
435 static probefunc_t      enable_mmanplus;
436 static probefunc_t      enable_synaptics;
437 static probefunc_t      enable_versapad;
438
439 static struct {
440         int             model;
441         u_char          syncmask;
442         int             packetsize;
443         probefunc_t     *probefunc;
444 } vendortype[] = {
445         /*
446          * WARNING: the order of probe is very important.  Don't mess it
447          * unless you know what you are doing.
448          */
449         { MOUSE_MODEL_NET,              /* Genius NetMouse */
450           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse },
451         { MOUSE_MODEL_NETSCROLL,        /* Genius NetScroll */
452           0xc8, 6, enable_groller },
453         { MOUSE_MODEL_MOUSEMANPLUS,     /* Logitech MouseMan+ */
454           0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus },
455         { MOUSE_MODEL_EXPLORER,         /* Microsoft IntelliMouse Explorer */
456           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer },
457         { MOUSE_MODEL_4D,               /* A4 Tech 4D Mouse */
458           0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse },
459         { MOUSE_MODEL_4DPLUS,           /* A4 Tech 4D+ Mouse */
460           0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus },
461         { MOUSE_MODEL_SYNAPTICS,        /* Synaptics Touchpad */
462           0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics },
463         { MOUSE_MODEL_INTELLI,          /* Microsoft IntelliMouse */
464           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli },
465         { MOUSE_MODEL_GLIDEPOINT,       /* ALPS GlidePoint */
466           0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide },
467         { MOUSE_MODEL_THINK,            /* Kensington ThinkingMouse */
468           0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse },
469         { MOUSE_MODEL_VERSAPAD,         /* Interlink electronics VersaPad */
470           0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad },
471         { MOUSE_MODEL_GENERIC,
472           0xc0, MOUSE_PS2_PACKETSIZE, NULL },
473 };
474 #define GENERIC_MOUSE_ENTRY     \
475     ((sizeof(vendortype) / sizeof(*vendortype)) - 1)
476
477 /* device driver declarateion */
478 static device_method_t psm_methods[] = {
479         /* Device interface */
480         DEVMETHOD(device_identify,      psmidentify),
481         DEVMETHOD(device_probe,         psmprobe),
482         DEVMETHOD(device_attach,        psmattach),
483         DEVMETHOD(device_detach,        psmdetach),
484         DEVMETHOD(device_resume,        psmresume),
485
486         { 0, 0 }
487 };
488
489 static driver_t psm_driver = {
490         PSM_DRIVER_NAME,
491         psm_methods,
492         sizeof(struct psm_softc),
493 };
494
495 static struct cdevsw psm_cdevsw = {
496         .d_version =    D_VERSION,
497         .d_flags =      D_NEEDGIANT,
498         .d_open =       psmopen,
499         .d_close =      psmclose,
500         .d_read =       psmread,
501         .d_write =      psmwrite,
502         .d_ioctl =      psmioctl,
503         .d_poll =       psmpoll,
504         .d_name =       PSM_DRIVER_NAME,
505 };
506
507 /* device I/O routines */
508 static int
509 enable_aux_dev(KBDC kbdc)
510 {
511         int res;
512
513         res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
514         VLOG(2, (LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res));
515
516         return (res == PSM_ACK);
517 }
518
519 static int
520 disable_aux_dev(KBDC kbdc)
521 {
522         int res;
523
524         res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
525         VLOG(2, (LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res));
526
527         return (res == PSM_ACK);
528 }
529
530 static int
531 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
532 {
533         int cmd;
534         int res;
535         int i;
536
537         switch (flag) {
538         case 0:
539         default:
540                 cmd = PSMC_SEND_DEV_STATUS;
541                 break;
542         case 1:
543                 cmd = PSMC_SEND_DEV_DATA;
544                 break;
545         }
546         empty_aux_buffer(kbdc, 5);
547         res = send_aux_command(kbdc, cmd);
548         VLOG(2, (LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
549             (flag == 1) ? "DATA" : "STATUS", res));
550         if (res != PSM_ACK)
551                 return (0);
552
553         for (i = 0; i < len; ++i) {
554                 status[i] = read_aux_data(kbdc);
555                 if (status[i] < 0)
556                         break;
557         }
558
559         VLOG(1, (LOG_DEBUG, "psm: %s %02x %02x %02x\n",
560             (flag == 1) ? "data" : "status", status[0], status[1], status[2]));
561
562         return (i);
563 }
564
565 static int
566 get_aux_id(KBDC kbdc)
567 {
568         int res;
569         int id;
570
571         empty_aux_buffer(kbdc, 5);
572         res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
573         VLOG(2, (LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res));
574         if (res != PSM_ACK)
575                 return (-1);
576
577         /* 10ms delay */
578         DELAY(10000);
579
580         id = read_aux_data(kbdc);
581         VLOG(2, (LOG_DEBUG, "psm: device ID: %04x\n", id));
582
583         return (id);
584 }
585
586 static int
587 set_mouse_sampling_rate(KBDC kbdc, int rate)
588 {
589         int res;
590
591         res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
592         VLOG(2, (LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res));
593
594         return ((res == PSM_ACK) ? rate : -1);
595 }
596
597 static int
598 set_mouse_scaling(KBDC kbdc, int scale)
599 {
600         int res;
601
602         switch (scale) {
603         case 1:
604         default:
605                 scale = PSMC_SET_SCALING11;
606                 break;
607         case 2:
608                 scale = PSMC_SET_SCALING21;
609                 break;
610         }
611         res = send_aux_command(kbdc, scale);
612         VLOG(2, (LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
613             (scale == PSMC_SET_SCALING21) ? "21" : "11", res));
614
615         return (res == PSM_ACK);
616 }
617
618 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
619 static int
620 set_mouse_resolution(KBDC kbdc, int val)
621 {
622         int res;
623
624         res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
625         VLOG(2, (LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res));
626
627         return ((res == PSM_ACK) ? val : -1);
628 }
629
630 /*
631  * NOTE: once `set_mouse_mode()' is called, the mouse device must be
632  * re-enabled by calling `enable_aux_dev()'
633  */
634 static int
635 set_mouse_mode(KBDC kbdc)
636 {
637         int res;
638
639         res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
640         VLOG(2, (LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res));
641
642         return (res == PSM_ACK);
643 }
644
645 static int
646 get_mouse_buttons(KBDC kbdc)
647 {
648         int c = 2;              /* assume two buttons by default */
649         int status[3];
650
651         /*
652          * NOTE: a special sequence to obtain Logitech Mouse specific
653          * information: set resolution to 25 ppi, set scaling to 1:1, set
654          * scaling to 1:1, set scaling to 1:1. Then the second byte of the
655          * mouse status bytes is the number of available buttons.
656          * Some manufactures also support this sequence.
657          */
658         if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
659                 return (c);
660         if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1) &&
661             set_mouse_scaling(kbdc, 1) &&
662             get_mouse_status(kbdc, status, 0, 3) >= 3 && status[1] != 0)
663                 return (status[1]);
664         return (c);
665 }
666
667 /* misc subroutines */
668 /*
669  * Someday, I will get the complete list of valid pointing devices and
670  * their IDs... XXX
671  */
672 static int
673 is_a_mouse(int id)
674 {
675 #if 0
676         static int valid_ids[] = {
677                 PSM_MOUSE_ID,           /* mouse */
678                 PSM_BALLPOINT_ID,       /* ballpoint device */
679                 PSM_INTELLI_ID,         /* Intellimouse */
680                 PSM_EXPLORER_ID,        /* Intellimouse Explorer */
681                 -1                      /* end of table */
682         };
683         int i;
684
685         for (i = 0; valid_ids[i] >= 0; ++i)
686         if (valid_ids[i] == id)
687                 return (TRUE);
688         return (FALSE);
689 #else
690         return (TRUE);
691 #endif
692 }
693
694 static char *
695 model_name(int model)
696 {
697         static struct {
698                 int     model_code;
699                 char    *model_name;
700         } models[] = {
701                 { MOUSE_MODEL_NETSCROLL,        "NetScroll" },
702                 { MOUSE_MODEL_NET,              "NetMouse/NetScroll Optical" },
703                 { MOUSE_MODEL_GLIDEPOINT,       "GlidePoint" },
704                 { MOUSE_MODEL_THINK,            "ThinkingMouse" },
705                 { MOUSE_MODEL_INTELLI,          "IntelliMouse" },
706                 { MOUSE_MODEL_MOUSEMANPLUS,     "MouseMan+" },
707                 { MOUSE_MODEL_VERSAPAD,         "VersaPad" },
708                 { MOUSE_MODEL_EXPLORER,         "IntelliMouse Explorer" },
709                 { MOUSE_MODEL_4D,               "4D Mouse" },
710                 { MOUSE_MODEL_4DPLUS,           "4D+ Mouse" },
711                 { MOUSE_MODEL_SYNAPTICS,        "Synaptics Touchpad" },
712                 { MOUSE_MODEL_GENERIC,          "Generic PS/2 mouse" },
713                 { MOUSE_MODEL_UNKNOWN,          "Unknown" },
714         };
715         int i;
716
717         for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i)
718                 if (models[i].model_code == model)
719                         break;
720         return (models[i].model_name);
721 }
722
723 static void
724 recover_from_error(KBDC kbdc)
725 {
726         /* discard anything left in the output buffer */
727         empty_both_buffers(kbdc, 10);
728
729 #if 0
730         /*
731          * NOTE: KBDC_RESET_KBD may not restore the communication between the
732          * keyboard and the controller.
733          */
734         reset_kbd(kbdc);
735 #else
736         /*
737          * NOTE: somehow diagnostic and keyboard port test commands bring the
738          * keyboard back.
739          */
740         if (!test_controller(kbdc))
741                 log(LOG_ERR, "psm: keyboard controller failed.\n");
742         /* if there isn't a keyboard in the system, the following error is OK */
743         if (test_kbd_port(kbdc) != 0)
744                 VLOG(1, (LOG_ERR, "psm: keyboard port failed.\n"));
745 #endif
746 }
747
748 static int
749 restore_controller(KBDC kbdc, int command_byte)
750 {
751         empty_both_buffers(kbdc, 10);
752
753         if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
754                 log(LOG_ERR, "psm: failed to restore the keyboard controller "
755                     "command byte.\n");
756                 empty_both_buffers(kbdc, 10);
757                 return (FALSE);
758         } else {
759                 empty_both_buffers(kbdc, 10);
760                 return (TRUE);
761         }
762 }
763
764 /*
765  * Re-initialize the aux port and device. The aux port must be enabled
766  * and its interrupt must be disabled before calling this routine.
767  * The aux device will be disabled before returning.
768  * The keyboard controller must be locked via `kbdc_lock()' before
769  * calling this routine.
770  */
771 static int
772 doinitialize(struct psm_softc *sc, mousemode_t *mode)
773 {
774         KBDC kbdc = sc->kbdc;
775         int stat[3];
776         int i;
777
778         switch((i = test_aux_port(kbdc))) {
779         case 1: /* ignore these errors */
780         case 2:
781         case 3:
782         case PSM_ACK:
783                 if (verbose)
784                         log(LOG_DEBUG,
785                             "psm%d: strange result for test aux port (%d).\n",
786                             sc->unit, i);
787                 /* FALLTHROUGH */
788         case 0:         /* no error */
789                 break;
790         case -1:        /* time out */
791         default:        /* error */
792                 recover_from_error(kbdc);
793                 if (sc->config & PSM_CONFIG_IGNPORTERROR)
794                         break;
795                 log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
796                     sc->unit, i);
797                 return (FALSE);
798         }
799
800         if (sc->config & PSM_CONFIG_NORESET) {
801                 /*
802                  * Don't try to reset the pointing device.  It may possibly
803                  * be left in the unknown state, though...
804                  */
805         } else {
806                 /*
807                  * NOTE: some controllers appears to hang the `keyboard' when
808                  * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
809                  */
810                 if (!reset_aux_dev(kbdc)) {
811                         recover_from_error(kbdc);
812                         log(LOG_ERR, "psm%d: failed to reset the aux device.\n",
813                             sc->unit);
814                         return (FALSE);
815                 }
816         }
817
818         /*
819          * both the aux port and the aux device is functioning, see
820          * if the device can be enabled.
821          */
822         if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
823                 log(LOG_ERR, "psm%d: failed to enable the aux device.\n",
824                     sc->unit);
825                 return (FALSE);
826         }
827         empty_both_buffers(kbdc, 10);   /* remove stray data if any */
828
829         if (sc->config & PSM_CONFIG_NOIDPROBE)
830                 i = GENERIC_MOUSE_ENTRY;
831         else {
832                 /* FIXME: hardware ID, mouse buttons? */
833
834                 /* other parameters */
835                 for (i = 0; vendortype[i].probefunc != NULL; ++i)
836                         if ((*vendortype[i].probefunc)(sc)) {
837                                 if (verbose >= 2)
838                                         log(LOG_ERR, "psm%d: found %s\n",
839                                             sc->unit,
840                                             model_name(vendortype[i].model));
841                                 break;
842                         }
843         }
844
845         sc->hw.model = vendortype[i].model;
846         sc->mode.packetsize = vendortype[i].packetsize;
847
848         /* set mouse parameters */
849         if (mode != (mousemode_t *)NULL) {
850                 if (mode->rate > 0)
851                         mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
852                 if (mode->resolution >= 0)
853                         mode->resolution =
854                             set_mouse_resolution(kbdc, mode->resolution);
855                 set_mouse_scaling(kbdc, 1);
856                 set_mouse_mode(kbdc);
857         }
858
859         /* Record sync on the next data packet we see. */
860         sc->flags |= PSM_NEED_SYNCBITS;
861
862         /* just check the status of the mouse */
863         if (get_mouse_status(kbdc, stat, 0, 3) < 3)
864                 log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
865                     sc->unit);
866
867         return (TRUE);
868 }
869
870 static int
871 doopen(struct psm_softc *sc, int command_byte)
872 {
873         int stat[3];
874
875         /*
876          * FIXME: Synaptics TouchPad seems to go back to Relative Mode with
877          * no obvious reason. Thus we check the current mode and restore the
878          * Absolute Mode if it was cleared.
879          *
880          * The previous hack at the end of psmprobe() wasn't efficient when
881          * moused(8) was restarted.
882          *
883          * A Reset (FF) or Set Defaults (F6) command would clear the
884          * Absolute Mode bit. But a verbose boot or debug.psm.loglevel=5
885          * doesn't show any evidence of such a command.
886          */
887         if (sc->hw.model == MOUSE_MODEL_SYNAPTICS) {
888                 mouse_ext_command(sc->kbdc, 1);
889                 get_mouse_status(sc->kbdc, stat, 0, 3);
890                 if (stat[1] == 0x47 && stat[2] == 0x40) {
891                         /* Set the mode byte -- request wmode where
892                          * available */
893                         if (sc->synhw.capExtended)
894                                 mouse_ext_command(sc->kbdc, 0xc1);
895                         else
896                                 mouse_ext_command(sc->kbdc, 0xc0);
897                         set_mouse_sampling_rate(sc->kbdc, 20);
898                         VLOG(5, (LOG_DEBUG, "psm%d: Synaptis Absolute Mode "
899                             "hopefully restored\n",
900                             sc->unit));
901                 }
902         }
903
904         /* enable the mouse device */
905         if (!enable_aux_dev(sc->kbdc)) {
906                 /* MOUSE ERROR: failed to enable the mouse because:
907                  * 1) the mouse is faulty,
908                  * 2) the mouse has been removed(!?)
909                  * In the latter case, the keyboard may have hung, and need
910                  * recovery procedure...
911                  */
912                 recover_from_error(sc->kbdc);
913 #if 0
914                 /* FIXME: we could reset the mouse here and try to enable
915                  * it again. But it will take long time and it's not a good
916                  * idea to disable the keyboard that long...
917                  */
918                 if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
919                         recover_from_error(sc->kbdc);
920 #else
921                 {
922 #endif
923                         restore_controller(sc->kbdc, command_byte);
924                         /* mark this device is no longer available */
925                         sc->state &= ~PSM_VALID;
926                         log(LOG_ERR,
927                             "psm%d: failed to enable the device (doopen).\n",
928                         sc->unit);
929                         return (EIO);
930                 }
931         }
932
933         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
934                 log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n",
935                     sc->unit);
936
937         /* enable the aux port and interrupt */
938         if (!set_controller_command_byte(sc->kbdc,
939             kbdc_get_device_mask(sc->kbdc),
940             (command_byte & KBD_KBD_CONTROL_BITS) |
941             KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
942                 /* CONTROLLER ERROR */
943                 disable_aux_dev(sc->kbdc);
944                 restore_controller(sc->kbdc, command_byte);
945                 log(LOG_ERR,
946                     "psm%d: failed to enable the aux interrupt (doopen).\n",
947                     sc->unit);
948                 return (EIO);
949         }
950
951         /* start the watchdog timer */
952         sc->watchdog = FALSE;
953         sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz*2);
954
955         return (0);
956 }
957
958 static int
959 reinitialize(struct psm_softc *sc, int doinit)
960 {
961         int err;
962         int c;
963         int s;
964
965         /* don't let anybody mess with the aux device */
966         if (!kbdc_lock(sc->kbdc, TRUE))
967                 return (EIO);
968         s = spltty();
969
970         /* block our watchdog timer */
971         sc->watchdog = FALSE;
972         untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
973         callout_handle_init(&sc->callout);
974
975         /* save the current controller command byte */
976         empty_both_buffers(sc->kbdc, 10);
977         c = get_controller_command_byte(sc->kbdc);
978         VLOG(2, (LOG_DEBUG,
979             "psm%d: current command byte: %04x (reinitialize).\n",
980             sc->unit, c));
981
982         /* enable the aux port but disable the aux interrupt and the keyboard */
983         if ((c == -1) || !set_controller_command_byte(sc->kbdc,
984             kbdc_get_device_mask(sc->kbdc),
985             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
986             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
987                 /* CONTROLLER ERROR */
988                 splx(s);
989                 kbdc_lock(sc->kbdc, FALSE);
990                 log(LOG_ERR,
991                     "psm%d: unable to set the command byte (reinitialize).\n",
992                     sc->unit);
993                 return (EIO);
994         }
995
996         /* flush any data */
997         if (sc->state & PSM_VALID) {
998                 /* this may fail; but never mind... */
999                 disable_aux_dev(sc->kbdc);
1000                 empty_aux_buffer(sc->kbdc, 10);
1001         }
1002         flushpackets(sc);
1003         sc->syncerrors = 0;
1004         sc->pkterrors = 0;
1005         memset(&sc->lastinputerr, 0, sizeof(sc->lastinputerr));
1006
1007         /* try to detect the aux device; are you still there? */
1008         err = 0;
1009         if (doinit) {
1010                 if (doinitialize(sc, &sc->mode)) {
1011                         /* yes */
1012                         sc->state |= PSM_VALID;
1013                 } else {
1014                         /* the device has gone! */
1015                         restore_controller(sc->kbdc, c);
1016                         sc->state &= ~PSM_VALID;
1017                         log(LOG_ERR,
1018                             "psm%d: the aux device has gone! (reinitialize).\n",
1019                             sc->unit);
1020                         err = ENXIO;
1021                 }
1022         }
1023         splx(s);
1024
1025         /* restore the driver state */
1026         if ((sc->state & PSM_OPEN) && (err == 0)) {
1027                 /* enable the aux device and the port again */
1028                 err = doopen(sc, c);
1029                 if (err != 0)
1030                         log(LOG_ERR, "psm%d: failed to enable the device "
1031                             "(reinitialize).\n", sc->unit);
1032         } else {
1033                 /* restore the keyboard port and disable the aux port */
1034                 if (!set_controller_command_byte(sc->kbdc,
1035                     kbdc_get_device_mask(sc->kbdc),
1036                     (c & KBD_KBD_CONTROL_BITS) |
1037                     KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1038                         /* CONTROLLER ERROR */
1039                         log(LOG_ERR, "psm%d: failed to disable the aux port "
1040                             "(reinitialize).\n", sc->unit);
1041                         err = EIO;
1042                 }
1043         }
1044
1045         kbdc_lock(sc->kbdc, FALSE);
1046         return (err);
1047 }
1048
1049 /* psm driver entry points */
1050
1051 static void
1052 psmidentify(driver_t *driver, device_t parent)
1053 {
1054         device_t psmc;
1055         device_t psm;
1056         u_long irq;
1057         int unit;
1058
1059         unit = device_get_unit(parent);
1060
1061         /* always add at least one child */
1062         psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
1063         if (psm == NULL)
1064                 return;
1065
1066         irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
1067         if (irq > 0)
1068                 return;
1069
1070         /*
1071          * If the PS/2 mouse device has already been reported by ACPI or
1072          * PnP BIOS, obtain the IRQ resource from it.
1073          * (See psmcpnp_attach() below.)
1074          */
1075         psmc = device_find_child(device_get_parent(parent),
1076             PSMCPNP_DRIVER_NAME, unit);
1077         if (psmc == NULL)
1078                 return;
1079         irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
1080         if (irq <= 0)
1081                 return;
1082         bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
1083 }
1084
1085 #define endprobe(v)     do {                    \
1086         if (bootverbose)                        \
1087                 --verbose;                      \
1088         kbdc_set_device_mask(sc->kbdc, mask);   \
1089         kbdc_lock(sc->kbdc, FALSE);             \
1090         return (v);                             \
1091 } while (0)
1092
1093 static int
1094 psmprobe(device_t dev)
1095 {
1096         int unit = device_get_unit(dev);
1097         struct psm_softc *sc = device_get_softc(dev);
1098         int stat[3];
1099         int command_byte;
1100         int mask;
1101         int rid;
1102         int i;
1103
1104 #if 0
1105         kbdc_debug(TRUE);
1106 #endif
1107
1108         /* see if IRQ is available */
1109         rid = KBDC_RID_AUX;
1110         sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1111             RF_SHAREABLE | RF_ACTIVE);
1112         if (sc->intr == NULL) {
1113                 if (bootverbose)
1114                         device_printf(dev, "unable to allocate IRQ\n");
1115                 return (ENXIO);
1116         }
1117         bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1118
1119         sc->unit = unit;
1120         sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
1121         sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
1122         /* XXX: for backward compatibility */
1123 #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
1124         sc->config |=
1125 #ifdef PSM_RESETAFTERSUSPEND
1126         PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
1127 #else
1128         PSM_CONFIG_HOOKRESUME;
1129 #endif
1130 #endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
1131         sc->flags = 0;
1132         if (bootverbose)
1133                 ++verbose;
1134
1135         device_set_desc(dev, "PS/2 Mouse");
1136
1137         if (!kbdc_lock(sc->kbdc, TRUE)) {
1138                 printf("psm%d: unable to lock the controller.\n", unit);
1139                 if (bootverbose)
1140                         --verbose;
1141                 return (ENXIO);
1142         }
1143
1144         /*
1145          * NOTE: two bits in the command byte controls the operation of the
1146          * aux port (mouse port): the aux port disable bit (bit 5) and the aux
1147          * port interrupt (IRQ 12) enable bit (bit 2).
1148          */
1149
1150         /* discard anything left after the keyboard initialization */
1151         empty_both_buffers(sc->kbdc, 10);
1152
1153         /* save the current command byte; it will be used later */
1154         mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
1155         command_byte = get_controller_command_byte(sc->kbdc);
1156         if (verbose)
1157                 printf("psm%d: current command byte:%04x\n", unit,
1158                     command_byte);
1159         if (command_byte == -1) {
1160                 /* CONTROLLER ERROR */
1161                 printf("psm%d: unable to get the current command byte value.\n",
1162                         unit);
1163                 endprobe(ENXIO);
1164         }
1165
1166         /*
1167          * disable the keyboard port while probing the aux port, which must be
1168          * enabled during this routine
1169          */
1170         if (!set_controller_command_byte(sc->kbdc,
1171             KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1172             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1173             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1174                 /*
1175                  * this is CONTROLLER ERROR; I don't know how to recover
1176                  * from this error...
1177                  */
1178                 restore_controller(sc->kbdc, command_byte);
1179                 printf("psm%d: unable to set the command byte.\n", unit);
1180                 endprobe(ENXIO);
1181         }
1182         write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
1183
1184         /*
1185          * NOTE: `test_aux_port()' is designed to return with zero if the aux
1186          * port exists and is functioning. However, some controllers appears
1187          * to respond with zero even when the aux port doesn't exist. (It may
1188          * be that this is only the case when the controller DOES have the aux
1189          * port but the port is not wired on the motherboard.) The keyboard
1190          * controllers without the port, such as the original AT, are
1191          * supporsed to return with an error code or simply time out. In any
1192          * case, we have to continue probing the port even when the controller
1193          * passes this test.
1194          *
1195          * XXX: some controllers erroneously return the error code 1, 2 or 3
1196          * when it has the perfectly functional aux port. We have to ignore
1197          * this error code. Even if the controller HAS error with the aux
1198          * port, it will be detected later...
1199          * XXX: another incompatible controller returns PSM_ACK (0xfa)...
1200          */
1201         switch ((i = test_aux_port(sc->kbdc))) {
1202         case 1:         /* ignore these errors */
1203         case 2:
1204         case 3:
1205         case PSM_ACK:
1206                 if (verbose)
1207                         printf("psm%d: strange result for test aux port "
1208                             "(%d).\n", unit, i);
1209                 /* FALLTHROUGH */
1210         case 0:         /* no error */
1211                 break;
1212         case -1:        /* time out */
1213         default:        /* error */
1214                 recover_from_error(sc->kbdc);
1215                 if (sc->config & PSM_CONFIG_IGNPORTERROR)
1216                         break;
1217                 restore_controller(sc->kbdc, command_byte);
1218                 if (verbose)
1219                         printf("psm%d: the aux port is not functioning (%d).\n",
1220                             unit, i);
1221                 endprobe(ENXIO);
1222         }
1223
1224         if (sc->config & PSM_CONFIG_NORESET) {
1225                 /*
1226                  * Don't try to reset the pointing device.  It may possibly be
1227                  * left in the unknown state, though...
1228                  */
1229         } else {
1230                 /*
1231                  * NOTE: some controllers appears to hang the `keyboard' when
1232                  * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
1233                  *
1234                  * Attempt to reset the controller twice -- this helps
1235                  * pierce through some KVM switches. The second reset
1236                  * is non-fatal.
1237                  */
1238                 if (!reset_aux_dev(sc->kbdc)) {
1239                         recover_from_error(sc->kbdc);
1240                         restore_controller(sc->kbdc, command_byte);
1241                         if (verbose)
1242                                 printf("psm%d: failed to reset the aux "
1243                                     "device.\n", unit);
1244                         endprobe(ENXIO);
1245                 } else if (!reset_aux_dev(sc->kbdc)) {
1246                         recover_from_error(sc->kbdc);
1247                         if (verbose >= 2)
1248                                 printf("psm%d: failed to reset the aux device "
1249                                     "(2).\n", unit);
1250                 }
1251         }
1252
1253         /*
1254          * both the aux port and the aux device is functioning, see if the
1255          * device can be enabled. NOTE: when enabled, the device will start
1256          * sending data; we shall immediately disable the device once we know
1257          * the device can be enabled.
1258          */
1259         if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1260                 /* MOUSE ERROR */
1261                 recover_from_error(sc->kbdc);
1262                 restore_controller(sc->kbdc, command_byte);
1263                 if (verbose)
1264                         printf("psm%d: failed to enable the aux device.\n",
1265                             unit);
1266                 endprobe(ENXIO);
1267         }
1268
1269         /* save the default values after reset */
1270         if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1271                 sc->dflt_mode.rate = sc->mode.rate = stat[2];
1272                 sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1273         } else {
1274                 sc->dflt_mode.rate = sc->mode.rate = -1;
1275                 sc->dflt_mode.resolution = sc->mode.resolution = -1;
1276         }
1277
1278         /* hardware information */
1279         sc->hw.iftype = MOUSE_IF_PS2;
1280
1281         /* verify the device is a mouse */
1282         sc->hw.hwid = get_aux_id(sc->kbdc);
1283         if (!is_a_mouse(sc->hw.hwid)) {
1284                 restore_controller(sc->kbdc, command_byte);
1285                 if (verbose)
1286                         printf("psm%d: unknown device type (%d).\n", unit,
1287                             sc->hw.hwid);
1288                 endprobe(ENXIO);
1289         }
1290         switch (sc->hw.hwid) {
1291         case PSM_BALLPOINT_ID:
1292                 sc->hw.type = MOUSE_TRACKBALL;
1293                 break;
1294         case PSM_MOUSE_ID:
1295         case PSM_INTELLI_ID:
1296         case PSM_EXPLORER_ID:
1297         case PSM_4DMOUSE_ID:
1298         case PSM_4DPLUS_ID:
1299                 sc->hw.type = MOUSE_MOUSE;
1300                 break;
1301         default:
1302                 sc->hw.type = MOUSE_UNKNOWN;
1303                 break;
1304         }
1305
1306         if (sc->config & PSM_CONFIG_NOIDPROBE) {
1307                 sc->hw.buttons = 2;
1308                 i = GENERIC_MOUSE_ENTRY;
1309         } else {
1310                 /* # of buttons */
1311                 sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1312
1313                 /* other parameters */
1314                 for (i = 0; vendortype[i].probefunc != NULL; ++i)
1315                         if ((*vendortype[i].probefunc)(sc)) {
1316                                 if (verbose >= 2)
1317                                         printf("psm%d: found %s\n", unit,
1318                                             model_name(vendortype[i].model));
1319                                 break;
1320                         }
1321         }
1322
1323         sc->hw.model = vendortype[i].model;
1324
1325         sc->dflt_mode.level = PSM_LEVEL_BASE;
1326         sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1327         sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1328         if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1329                 sc->dflt_mode.syncmask[0] = 0;
1330         else
1331                 sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1332         if (sc->config & PSM_CONFIG_FORCETAP)
1333                 sc->dflt_mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1334         sc->dflt_mode.syncmask[1] = 0;  /* syncbits */
1335         sc->mode = sc->dflt_mode;
1336         sc->mode.packetsize = vendortype[i].packetsize;
1337
1338         /* set mouse parameters */
1339 #if 0
1340         /*
1341          * A version of Logitech FirstMouse+ won't report wheel movement,
1342          * if SET_DEFAULTS is sent...  Don't use this command.
1343          * This fix was found by Takashi Nishida.
1344          */
1345         i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1346         if (verbose >= 2)
1347                 printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1348 #endif
1349         if (sc->config & PSM_CONFIG_RESOLUTION)
1350                 sc->mode.resolution =
1351                     set_mouse_resolution(sc->kbdc,
1352                     (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1353         else if (sc->mode.resolution >= 0)
1354                 sc->mode.resolution =
1355                     set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1356         if (sc->mode.rate > 0)
1357                 sc->mode.rate =
1358                     set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1359         set_mouse_scaling(sc->kbdc, 1);
1360
1361         /* Record sync on the next data packet we see. */
1362         sc->flags |= PSM_NEED_SYNCBITS;
1363
1364         /* just check the status of the mouse */
1365         /*
1366          * NOTE: XXX there are some arcane controller/mouse combinations out
1367          * there, which hung the controller unless there is data transmission
1368          * after ACK from the mouse.
1369          */
1370         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1371                 printf("psm%d: failed to get status.\n", unit);
1372         else {
1373                 /*
1374                  * When in its native mode, some mice operate with different
1375                  * default parameters than in the PS/2 compatible mode.
1376                  */
1377                 sc->dflt_mode.rate = sc->mode.rate = stat[2];
1378                 sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1379         }
1380
1381         /* disable the aux port for now... */
1382         if (!set_controller_command_byte(sc->kbdc,
1383             KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1384             (command_byte & KBD_KBD_CONTROL_BITS) |
1385             KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1386                 /*
1387                  * this is CONTROLLER ERROR; I don't know the proper way to
1388                  * recover from this error...
1389                  */
1390                 restore_controller(sc->kbdc, command_byte);
1391                 printf("psm%d: unable to set the command byte.\n", unit);
1392                 endprobe(ENXIO);
1393         }
1394
1395         /* done */
1396         kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1397         kbdc_lock(sc->kbdc, FALSE);
1398         return (0);
1399 }
1400
1401 static int
1402 psmattach(device_t dev)
1403 {
1404         int unit = device_get_unit(dev);
1405         struct psm_softc *sc = device_get_softc(dev);
1406         int error;
1407         int rid;
1408
1409         /* Setup initial state */
1410         sc->state = PSM_VALID;
1411         callout_handle_init(&sc->callout);
1412
1413         /* Setup our interrupt handler */
1414         rid = KBDC_RID_AUX;
1415         sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1416             RF_SHAREABLE | RF_ACTIVE);
1417         if (sc->intr == NULL)
1418                 return (ENXIO);
1419         error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, NULL, psmintr, sc,
1420             &sc->ih);
1421         if (error) {
1422                 bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1423                 return (error);
1424         }
1425
1426         /* Done */
1427         sc->dev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, FALSE), 0, 0, 0666,
1428             "psm%d", unit);
1429         sc->bdev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, TRUE), 0, 0, 0666,
1430             "bpsm%d", unit);
1431
1432         if (!verbose)
1433                 printf("psm%d: model %s, device ID %d\n",
1434                     unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1435         else {
1436                 printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1437                     unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff,
1438                     sc->hw.hwid >> 8, sc->hw.buttons);
1439                 printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1440                     unit, sc->config, sc->flags, sc->mode.packetsize);
1441                 printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1442                     unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1443         }
1444
1445         if (bootverbose)
1446                 --verbose;
1447
1448         return (0);
1449 }
1450
1451 static int
1452 psmdetach(device_t dev)
1453 {
1454         struct psm_softc *sc;
1455         int rid;
1456
1457         sc = device_get_softc(dev);
1458         if (sc->state & PSM_OPEN)
1459                 return (EBUSY);
1460
1461         rid = KBDC_RID_AUX;
1462         bus_teardown_intr(dev, sc->intr, sc->ih);
1463         bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1464
1465         destroy_dev(sc->dev);
1466         destroy_dev(sc->bdev);
1467
1468         return (0);
1469 }
1470
1471 static int
1472 psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
1473 {
1474         int unit = PSM_UNIT(dev);
1475         struct psm_softc *sc;
1476         int command_byte;
1477         int err;
1478         int s;
1479
1480         /* Get device data */
1481         sc = PSM_SOFTC(unit);
1482         if ((sc == NULL) || (sc->state & PSM_VALID) == 0) {
1483                 /* the device is no longer valid/functioning */
1484                 return (ENXIO);
1485         }
1486
1487         /* Disallow multiple opens */
1488         if (sc->state & PSM_OPEN)
1489                 return (EBUSY);
1490
1491         device_busy(devclass_get_device(psm_devclass, unit));
1492
1493         /* Initialize state */
1494         sc->mode.level = sc->dflt_mode.level;
1495         sc->mode.protocol = sc->dflt_mode.protocol;
1496         sc->watchdog = FALSE;
1497         sc->async = NULL;
1498
1499         /* flush the event queue */
1500         sc->queue.count = 0;
1501         sc->queue.head = 0;
1502         sc->queue.tail = 0;
1503         sc->status.flags = 0;
1504         sc->status.button = 0;
1505         sc->status.obutton = 0;
1506         sc->status.dx = 0;
1507         sc->status.dy = 0;
1508         sc->status.dz = 0;
1509         sc->button = 0;
1510         sc->pqueue_start = 0;
1511         sc->pqueue_end = 0;
1512
1513         /* empty input buffer */
1514         flushpackets(sc);
1515         sc->syncerrors = 0;
1516         sc->pkterrors = 0;
1517
1518         /* don't let timeout routines in the keyboard driver to poll the kbdc */
1519         if (!kbdc_lock(sc->kbdc, TRUE))
1520                 return (EIO);
1521
1522         /* save the current controller command byte */
1523         s = spltty();
1524         command_byte = get_controller_command_byte(sc->kbdc);
1525
1526         /* enable the aux port and temporalily disable the keyboard */
1527         if (command_byte == -1 || !set_controller_command_byte(sc->kbdc,
1528             kbdc_get_device_mask(sc->kbdc),
1529             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1530             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1531                 /* CONTROLLER ERROR; do you know how to get out of this? */
1532                 kbdc_lock(sc->kbdc, FALSE);
1533                 splx(s);
1534                 log(LOG_ERR,
1535                     "psm%d: unable to set the command byte (psmopen).\n", unit);
1536                 return (EIO);
1537         }
1538         /*
1539          * Now that the keyboard controller is told not to generate
1540          * the keyboard and mouse interrupts, call `splx()' to allow
1541          * the other tty interrupts. The clock interrupt may also occur,
1542          * but timeout routines will be blocked by the poll flag set
1543          * via `kbdc_lock()'
1544          */
1545         splx(s);
1546
1547         /* enable the mouse device */
1548         err = doopen(sc, command_byte);
1549
1550         /* done */
1551         if (err == 0)
1552                 sc->state |= PSM_OPEN;
1553         kbdc_lock(sc->kbdc, FALSE);
1554         return (err);
1555 }
1556
1557 static int
1558 psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
1559 {
1560         int unit = PSM_UNIT(dev);
1561         struct psm_softc *sc = PSM_SOFTC(unit);
1562         int stat[3];
1563         int command_byte;
1564         int s;
1565
1566         /* don't let timeout routines in the keyboard driver to poll the kbdc */
1567         if (!kbdc_lock(sc->kbdc, TRUE))
1568                 return (EIO);
1569
1570         /* save the current controller command byte */
1571         s = spltty();
1572         command_byte = get_controller_command_byte(sc->kbdc);
1573         if (command_byte == -1) {
1574                 kbdc_lock(sc->kbdc, FALSE);
1575                 splx(s);
1576                 return (EIO);
1577         }
1578
1579         /* disable the aux interrupt and temporalily disable the keyboard */
1580         if (!set_controller_command_byte(sc->kbdc,
1581             kbdc_get_device_mask(sc->kbdc),
1582             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1583             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1584                 log(LOG_ERR,
1585                     "psm%d: failed to disable the aux int (psmclose).\n", unit);
1586                 /* CONTROLLER ERROR;
1587                  * NOTE: we shall force our way through. Because the only
1588                  * ill effect we shall see is that we may not be able
1589                  * to read ACK from the mouse, and it doesn't matter much
1590                  * so long as the mouse will accept the DISABLE command.
1591                  */
1592         }
1593         splx(s);
1594
1595         /* stop the watchdog timer */
1596         untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
1597         callout_handle_init(&sc->callout);
1598
1599         /* remove anything left in the output buffer */
1600         empty_aux_buffer(sc->kbdc, 10);
1601
1602         /* disable the aux device, port and interrupt */
1603         if (sc->state & PSM_VALID) {
1604                 if (!disable_aux_dev(sc->kbdc)) {
1605                         /* MOUSE ERROR;
1606                          * NOTE: we don't return (error) and continue,
1607                          * pretending we have successfully disabled the device.
1608                          * It's OK because the interrupt routine will discard
1609                          * any data from the mouse hereafter.
1610                          */
1611                         log(LOG_ERR,
1612                             "psm%d: failed to disable the device (psmclose).\n",
1613                             unit);
1614                 }
1615
1616                 if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1617                         log(LOG_DEBUG,
1618                             "psm%d: failed to get status (psmclose).\n", unit);
1619         }
1620
1621         if (!set_controller_command_byte(sc->kbdc,
1622             kbdc_get_device_mask(sc->kbdc),
1623             (command_byte & KBD_KBD_CONTROL_BITS) |
1624             KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1625                 /*
1626                  * CONTROLLER ERROR;
1627                  * we shall ignore this error; see the above comment.
1628                  */
1629                 log(LOG_ERR,
1630                     "psm%d: failed to disable the aux port (psmclose).\n",
1631                     unit);
1632         }
1633
1634         /* remove anything left in the output buffer */
1635         empty_aux_buffer(sc->kbdc, 10);
1636
1637         /* clean up and sigio requests */
1638         if (sc->async != NULL) {
1639                 funsetown(&sc->async);
1640                 sc->async = NULL;
1641         }
1642
1643         /* close is almost always successful */
1644         sc->state &= ~PSM_OPEN;
1645         kbdc_lock(sc->kbdc, FALSE);
1646         device_unbusy(devclass_get_device(psm_devclass, unit));
1647         return (0);
1648 }
1649
1650 static int
1651 tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status,
1652     u_char *buf)
1653 {
1654         static u_char butmapps2[8] = {
1655                 0,
1656                 MOUSE_PS2_BUTTON1DOWN,
1657                 MOUSE_PS2_BUTTON2DOWN,
1658                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1659                 MOUSE_PS2_BUTTON3DOWN,
1660                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1661                 MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1662                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN |
1663                     MOUSE_PS2_BUTTON3DOWN,
1664         };
1665         static u_char butmapmsc[8] = {
1666                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP |
1667                     MOUSE_MSC_BUTTON3UP,
1668                 MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1669                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1670                 MOUSE_MSC_BUTTON3UP,
1671                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1672                 MOUSE_MSC_BUTTON2UP,
1673                 MOUSE_MSC_BUTTON1UP,
1674                 0,
1675         };
1676         int mapped;
1677         int i;
1678
1679         if (sc->mode.level == PSM_LEVEL_BASE) {
1680                 mapped = status->button & ~MOUSE_BUTTON4DOWN;
1681                 if (status->button & MOUSE_BUTTON4DOWN)
1682                         mapped |= MOUSE_BUTTON1DOWN;
1683                 status->button = mapped;
1684                 buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1685                 i = imax(imin(status->dx, 255), -256);
1686                 if (i < 0)
1687                         buf[0] |= MOUSE_PS2_XNEG;
1688                 buf[1] = i;
1689                 i = imax(imin(status->dy, 255), -256);
1690                 if (i < 0)
1691                         buf[0] |= MOUSE_PS2_YNEG;
1692                 buf[2] = i;
1693                 return (MOUSE_PS2_PACKETSIZE);
1694         } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1695                 buf[0] = MOUSE_MSC_SYNC |
1696                     butmapmsc[status->button & MOUSE_STDBUTTONS];
1697                 i = imax(imin(status->dx, 255), -256);
1698                 buf[1] = i >> 1;
1699                 buf[3] = i - buf[1];
1700                 i = imax(imin(status->dy, 255), -256);
1701                 buf[2] = i >> 1;
1702                 buf[4] = i - buf[2];
1703                 i = imax(imin(status->dz, 127), -128);
1704                 buf[5] = (i >> 1) & 0x7f;
1705                 buf[6] = (i - (i >> 1)) & 0x7f;
1706                 buf[7] = (~status->button >> 3) & 0x7f;
1707                 return (MOUSE_SYS_PACKETSIZE);
1708         }
1709         return (pb->inputbytes);
1710 }
1711
1712 static int
1713 psmread(struct cdev *dev, struct uio *uio, int flag)
1714 {
1715         register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1716         u_char buf[PSM_SMALLBUFSIZE];
1717         int error = 0;
1718         int s;
1719         int l;
1720
1721         if ((sc->state & PSM_VALID) == 0)
1722                 return (EIO);
1723
1724         /* block until mouse activity occured */
1725         s = spltty();
1726         while (sc->queue.count <= 0) {
1727                 if (PSM_NBLOCKIO(dev)) {
1728                         splx(s);
1729                         return (EWOULDBLOCK);
1730                 }
1731                 sc->state |= PSM_ASLP;
1732                 error = tsleep(sc, PZERO | PCATCH, "psmrea", 0);
1733                 sc->state &= ~PSM_ASLP;
1734                 if (error) {
1735                         splx(s);
1736                         return (error);
1737                 } else if ((sc->state & PSM_VALID) == 0) {
1738                         /* the device disappeared! */
1739                         splx(s);
1740                         return (EIO);
1741                 }
1742         }
1743         splx(s);
1744
1745         /* copy data to the user land */
1746         while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1747                 s = spltty();
1748                 l = imin(sc->queue.count, uio->uio_resid);
1749                 if (l > sizeof(buf))
1750                         l = sizeof(buf);
1751                 if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1752                         bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1753                             sizeof(sc->queue.buf) - sc->queue.head);
1754                         bcopy(&sc->queue.buf[0],
1755                             &buf[sizeof(sc->queue.buf) - sc->queue.head],
1756                             l - (sizeof(sc->queue.buf) - sc->queue.head));
1757                 } else
1758                         bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1759                 sc->queue.count -= l;
1760                 sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1761                 splx(s);
1762                 error = uiomove(buf, l, uio);
1763                 if (error)
1764                         break;
1765         }
1766
1767         return (error);
1768 }
1769
1770 static int
1771 block_mouse_data(struct psm_softc *sc, int *c)
1772 {
1773         int s;
1774
1775         if (!kbdc_lock(sc->kbdc, TRUE))
1776                 return (EIO);
1777
1778         s = spltty();
1779         *c = get_controller_command_byte(sc->kbdc);
1780         if ((*c == -1) || !set_controller_command_byte(sc->kbdc,
1781             kbdc_get_device_mask(sc->kbdc),
1782             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1783             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1784                 /* this is CONTROLLER ERROR */
1785                 splx(s);
1786                 kbdc_lock(sc->kbdc, FALSE);
1787                 return (EIO);
1788         }
1789
1790         /*
1791          * The device may be in the middle of status data transmission.
1792          * The transmission will be interrupted, thus, incomplete status
1793          * data must be discarded. Although the aux interrupt is disabled
1794          * at the keyboard controller level, at most one aux interrupt
1795          * may have already been pending and a data byte is in the
1796          * output buffer; throw it away. Note that the second argument
1797          * to `empty_aux_buffer()' is zero, so that the call will just
1798          * flush the internal queue.
1799          * `psmintr()' will be invoked after `splx()' if an interrupt is
1800          * pending; it will see no data and returns immediately.
1801          */
1802         empty_aux_buffer(sc->kbdc, 0);          /* flush the queue */
1803         read_aux_data_no_wait(sc->kbdc);        /* throw away data if any */
1804         flushpackets(sc);
1805         splx(s);
1806
1807         return (0);
1808 }
1809
1810 static void
1811 dropqueue(struct psm_softc *sc)
1812 {
1813
1814         sc->queue.count = 0;
1815         sc->queue.head = 0;
1816         sc->queue.tail = 0;
1817         if ((sc->state & PSM_SOFTARMED) != 0) {
1818                 sc->state &= ~PSM_SOFTARMED;
1819                 untimeout(psmsoftintr, (void *)(uintptr_t)sc, sc->softcallout);
1820         }
1821         sc->pqueue_start = sc->pqueue_end;
1822 }
1823
1824 static void
1825 flushpackets(struct psm_softc *sc)
1826 {
1827
1828         dropqueue(sc);
1829         bzero(&sc->pqueue, sizeof(sc->pqueue));
1830 }
1831
1832 static int
1833 unblock_mouse_data(struct psm_softc *sc, int c)
1834 {
1835         int error = 0;
1836
1837         /*
1838          * We may have seen a part of status data during `set_mouse_XXX()'.
1839          * they have been queued; flush it.
1840          */
1841         empty_aux_buffer(sc->kbdc, 0);
1842
1843         /* restore ports and interrupt */
1844         if (!set_controller_command_byte(sc->kbdc,
1845             kbdc_get_device_mask(sc->kbdc),
1846             c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1847                 /*
1848                  * CONTROLLER ERROR; this is serious, we may have
1849                  * been left with the inaccessible keyboard and
1850                  * the disabled mouse interrupt.
1851                  */
1852                 error = EIO;
1853         }
1854
1855         kbdc_lock(sc->kbdc, FALSE);
1856         return (error);
1857 }
1858
1859 static int
1860 psmwrite(struct cdev *dev, struct uio *uio, int flag)
1861 {
1862         register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1863         u_char buf[PSM_SMALLBUFSIZE];
1864         int error = 0, i, l;
1865
1866         if ((sc->state & PSM_VALID) == 0)
1867                 return (EIO);
1868
1869         if (sc->mode.level < PSM_LEVEL_NATIVE)
1870                 return (ENODEV);
1871
1872         /* copy data from the user land */
1873         while (uio->uio_resid > 0) {
1874                 l = imin(PSM_SMALLBUFSIZE, uio->uio_resid);
1875                 error = uiomove(buf, l, uio);
1876                 if (error)
1877                         break;
1878                 for (i = 0; i < l; i++) {
1879                         VLOG(4, (LOG_DEBUG, "psm: cmd 0x%x\n", buf[i]));
1880                         if (!write_aux_command(sc->kbdc, buf[i])) {
1881                                 VLOG(2, (LOG_DEBUG,
1882                                     "psm: cmd 0x%x failed.\n", buf[i]));
1883                                 return (reinitialize(sc, FALSE));
1884                         }
1885                 }
1886         }
1887
1888         return (error);
1889 }
1890
1891 static int
1892 psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
1893     struct thread *td)
1894 {
1895         struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1896         mousemode_t mode;
1897         mousestatus_t status;
1898 #if (defined(MOUSE_GETVARS))
1899         mousevar_t *var;
1900 #endif
1901         mousedata_t *data;
1902         int stat[3];
1903         int command_byte;
1904         int error = 0;
1905         int s;
1906
1907         /* Perform IOCTL command */
1908         switch (cmd) {
1909
1910         case OLD_MOUSE_GETHWINFO:
1911                 s = spltty();
1912                 ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1913                 ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1914                 ((old_mousehw_t *)addr)->type = sc->hw.type;
1915                 ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
1916                 splx(s);
1917                 break;
1918
1919         case MOUSE_GETHWINFO:
1920                 s = spltty();
1921                 *(mousehw_t *)addr = sc->hw;
1922                 if (sc->mode.level == PSM_LEVEL_BASE)
1923                         ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1924                 splx(s);
1925                 break;
1926
1927         case MOUSE_SYN_GETHWINFO:
1928                 s = spltty();
1929                 if (synaptics_support && sc->hw.model == MOUSE_MODEL_SYNAPTICS)
1930                         *(synapticshw_t *)addr = sc->synhw;
1931                 else
1932                         error = EINVAL;
1933                 splx(s);
1934                 break;
1935
1936         case OLD_MOUSE_GETMODE:
1937                 s = spltty();
1938                 switch (sc->mode.level) {
1939                 case PSM_LEVEL_BASE:
1940                         ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1941                         break;
1942                 case PSM_LEVEL_STANDARD:
1943                         ((old_mousemode_t *)addr)->protocol =
1944                             MOUSE_PROTO_SYSMOUSE;
1945                         break;
1946                 case PSM_LEVEL_NATIVE:
1947                         ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1948                         break;
1949                 }
1950                 ((old_mousemode_t *)addr)->rate = sc->mode.rate;
1951                 ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1952                 ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1953                 splx(s);
1954                 break;
1955
1956         case MOUSE_GETMODE:
1957                 s = spltty();
1958                 *(mousemode_t *)addr = sc->mode;
1959                 if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
1960                         ((mousemode_t *)addr)->syncmask[0] = 0;
1961                         ((mousemode_t *)addr)->syncmask[1] = 0;
1962                 }
1963                 ((mousemode_t *)addr)->resolution =
1964                         MOUSE_RES_LOW - sc->mode.resolution;
1965                 switch (sc->mode.level) {
1966                 case PSM_LEVEL_BASE:
1967                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1968                         ((mousemode_t *)addr)->packetsize =
1969                             MOUSE_PS2_PACKETSIZE;
1970                         break;
1971                 case PSM_LEVEL_STANDARD:
1972                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1973                         ((mousemode_t *)addr)->packetsize =
1974                             MOUSE_SYS_PACKETSIZE;
1975                         ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1976                         ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
1977                         break;
1978                 case PSM_LEVEL_NATIVE:
1979                         /* FIXME: this isn't quite correct... XXX */
1980                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1981                         break;
1982                 }
1983                 splx(s);
1984                 break;
1985
1986         case OLD_MOUSE_SETMODE:
1987         case MOUSE_SETMODE:
1988                 if (cmd == OLD_MOUSE_SETMODE) {
1989                         mode.rate = ((old_mousemode_t *)addr)->rate;
1990                         /*
1991                          * resolution  old I/F   new I/F
1992                          * default        0         0
1993                          * low            1        -2
1994                          * medium low     2        -3
1995                          * medium high    3        -4
1996                          * high           4        -5
1997                          */
1998                         if (((old_mousemode_t *)addr)->resolution > 0)
1999                                 mode.resolution =
2000                                     -((old_mousemode_t *)addr)->resolution - 1;
2001                         else
2002                                 mode.resolution = 0;
2003                         mode.accelfactor =
2004                             ((old_mousemode_t *)addr)->accelfactor;
2005                         mode.level = -1;
2006                 } else
2007                         mode = *(mousemode_t *)addr;
2008
2009                 /* adjust and validate parameters. */
2010                 if (mode.rate > UCHAR_MAX)
2011                         return (EINVAL);
2012                 if (mode.rate == 0)
2013                         mode.rate = sc->dflt_mode.rate;
2014                 else if (mode.rate == -1)
2015                         /* don't change the current setting */
2016                         ;
2017                 else if (mode.rate < 0)
2018                         return (EINVAL);
2019                 if (mode.resolution >= UCHAR_MAX)
2020                         return (EINVAL);
2021                 if (mode.resolution >= 200)
2022                         mode.resolution = MOUSE_RES_HIGH;
2023                 else if (mode.resolution >= 100)
2024                         mode.resolution = MOUSE_RES_MEDIUMHIGH;
2025                 else if (mode.resolution >= 50)
2026                         mode.resolution = MOUSE_RES_MEDIUMLOW;
2027                 else if (mode.resolution > 0)
2028                         mode.resolution = MOUSE_RES_LOW;
2029                 if (mode.resolution == MOUSE_RES_DEFAULT)
2030                         mode.resolution = sc->dflt_mode.resolution;
2031                 else if (mode.resolution == -1)
2032                         /* don't change the current setting */
2033                         ;
2034                 else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2035                         mode.resolution = MOUSE_RES_LOW - mode.resolution;
2036                 if (mode.level == -1)
2037                         /* don't change the current setting */
2038                         mode.level = sc->mode.level;
2039                 else if ((mode.level < PSM_LEVEL_MIN) ||
2040                     (mode.level > PSM_LEVEL_MAX))
2041                         return (EINVAL);
2042                 if (mode.accelfactor == -1)
2043                         /* don't change the current setting */
2044                         mode.accelfactor = sc->mode.accelfactor;
2045                 else if (mode.accelfactor < 0)
2046                         return (EINVAL);
2047
2048                 /* don't allow anybody to poll the keyboard controller */
2049                 error = block_mouse_data(sc, &command_byte);
2050                 if (error)
2051                         return (error);
2052
2053                 /* set mouse parameters */
2054                 if (mode.rate > 0)
2055                         mode.rate = set_mouse_sampling_rate(sc->kbdc,
2056                             mode.rate);
2057                 if (mode.resolution >= 0)
2058                         mode.resolution =
2059                             set_mouse_resolution(sc->kbdc, mode.resolution);
2060                 set_mouse_scaling(sc->kbdc, 1);
2061                 get_mouse_status(sc->kbdc, stat, 0, 3);
2062
2063                 s = spltty();
2064                 sc->mode.rate = mode.rate;
2065                 sc->mode.resolution = mode.resolution;
2066                 sc->mode.accelfactor = mode.accelfactor;
2067                 sc->mode.level = mode.level;
2068                 splx(s);
2069
2070                 unblock_mouse_data(sc, command_byte);
2071                 break;
2072
2073         case MOUSE_GETLEVEL:
2074                 *(int *)addr = sc->mode.level;
2075                 break;
2076
2077         case MOUSE_SETLEVEL:
2078                 if ((*(int *)addr < PSM_LEVEL_MIN) ||
2079                     (*(int *)addr > PSM_LEVEL_MAX))
2080                         return (EINVAL);
2081                 sc->mode.level = *(int *)addr;
2082                 break;
2083
2084         case MOUSE_GETSTATUS:
2085                 s = spltty();
2086                 status = sc->status;
2087                 sc->status.flags = 0;
2088                 sc->status.obutton = sc->status.button;
2089                 sc->status.button = 0;
2090                 sc->status.dx = 0;
2091                 sc->status.dy = 0;
2092                 sc->status.dz = 0;
2093                 splx(s);
2094                 *(mousestatus_t *)addr = status;
2095                 break;
2096
2097 #if (defined(MOUSE_GETVARS))
2098         case MOUSE_GETVARS:
2099                 var = (mousevar_t *)addr;
2100                 bzero(var, sizeof(*var));
2101                 s = spltty();
2102                 var->var[0] = MOUSE_VARS_PS2_SIG;
2103                 var->var[1] = sc->config;
2104                 var->var[2] = sc->flags;
2105                 splx(s);
2106                 break;
2107
2108         case MOUSE_SETVARS:
2109                 return (ENODEV);
2110 #endif /* MOUSE_GETVARS */
2111
2112         case MOUSE_READSTATE:
2113         case MOUSE_READDATA:
2114                 data = (mousedata_t *)addr;
2115                 if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
2116                         return (EINVAL);
2117
2118                 error = block_mouse_data(sc, &command_byte);
2119                 if (error)
2120                         return (error);
2121                 if ((data->len = get_mouse_status(sc->kbdc, data->buf,
2122                     (cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
2123                         error = EIO;
2124                 unblock_mouse_data(sc, command_byte);
2125                 break;
2126
2127 #if (defined(MOUSE_SETRESOLUTION))
2128         case MOUSE_SETRESOLUTION:
2129                 mode.resolution = *(int *)addr;
2130                 if (mode.resolution >= UCHAR_MAX)
2131                         return (EINVAL);
2132                 else if (mode.resolution >= 200)
2133                         mode.resolution = MOUSE_RES_HIGH;
2134                 else if (mode.resolution >= 100)
2135                         mode.resolution = MOUSE_RES_MEDIUMHIGH;
2136                 else if (mode.resolution >= 50)
2137                         mode.resolution = MOUSE_RES_MEDIUMLOW;
2138                 else if (mode.resolution > 0)
2139                         mode.resolution = MOUSE_RES_LOW;
2140                 if (mode.resolution == MOUSE_RES_DEFAULT)
2141                         mode.resolution = sc->dflt_mode.resolution;
2142                 else if (mode.resolution == -1)
2143                         mode.resolution = sc->mode.resolution;
2144                 else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2145                         mode.resolution = MOUSE_RES_LOW - mode.resolution;
2146
2147                 error = block_mouse_data(sc, &command_byte);
2148                 if (error)
2149                         return (error);
2150                 sc->mode.resolution =
2151                     set_mouse_resolution(sc->kbdc, mode.resolution);
2152                 if (sc->mode.resolution != mode.resolution)
2153                         error = EIO;
2154                 unblock_mouse_data(sc, command_byte);
2155                 break;
2156 #endif /* MOUSE_SETRESOLUTION */
2157
2158 #if (defined(MOUSE_SETRATE))
2159         case MOUSE_SETRATE:
2160                 mode.rate = *(int *)addr;
2161                 if (mode.rate > UCHAR_MAX)
2162                         return (EINVAL);
2163                 if (mode.rate == 0)
2164                         mode.rate = sc->dflt_mode.rate;
2165                 else if (mode.rate < 0)
2166                         mode.rate = sc->mode.rate;
2167
2168                 error = block_mouse_data(sc, &command_byte);
2169                 if (error)
2170                         return (error);
2171                 sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
2172                 if (sc->mode.rate != mode.rate)
2173                         error = EIO;
2174                 unblock_mouse_data(sc, command_byte);
2175                 break;
2176 #endif /* MOUSE_SETRATE */
2177
2178 #if (defined(MOUSE_SETSCALING))
2179         case MOUSE_SETSCALING:
2180                 if ((*(int *)addr <= 0) || (*(int *)addr > 2))
2181                         return (EINVAL);
2182
2183                 error = block_mouse_data(sc, &command_byte);
2184                 if (error)
2185                         return (error);
2186                 if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
2187                         error = EIO;
2188                 unblock_mouse_data(sc, command_byte);
2189                 break;
2190 #endif /* MOUSE_SETSCALING */
2191
2192 #if (defined(MOUSE_GETHWID))
2193         case MOUSE_GETHWID:
2194                 error = block_mouse_data(sc, &command_byte);
2195                 if (error)
2196                         return (error);
2197                 sc->hw.hwid &= ~0x00ff;
2198                 sc->hw.hwid |= get_aux_id(sc->kbdc);
2199                 *(int *)addr = sc->hw.hwid & 0x00ff;
2200                 unblock_mouse_data(sc, command_byte);
2201                 break;
2202 #endif /* MOUSE_GETHWID */
2203
2204         case FIONBIO:
2205         case FIOASYNC:
2206                 break;
2207         case FIOSETOWN:
2208                 error = fsetown(*(int *)addr, &sc->async);
2209                 break;
2210         case FIOGETOWN:
2211                 *(int *) addr = fgetown(&sc->async);
2212                 break;
2213         default:
2214                 return (ENOTTY);
2215         }
2216
2217         return (error);
2218 }
2219
2220 static void
2221 psmtimeout(void *arg)
2222 {
2223         struct psm_softc *sc;
2224         int s;
2225
2226         sc = (struct psm_softc *)arg;
2227         s = spltty();
2228         if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
2229                 VLOG(4, (LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit));
2230                 psmintr(sc);
2231                 kbdc_lock(sc->kbdc, FALSE);
2232         }
2233         sc->watchdog = TRUE;
2234         splx(s);
2235         sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz);
2236 }
2237
2238 /* Add all sysctls under the debug.psm and hw.psm nodes */
2239 SYSCTL_NODE(_debug, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2240 SYSCTL_NODE(_hw, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2241
2242 SYSCTL_INT(_debug_psm, OID_AUTO, loglevel, CTLFLAG_RW, &verbose, 0,
2243     "Verbosity level");
2244
2245 static int psmhz = 20;
2246 SYSCTL_INT(_debug_psm, OID_AUTO, hz, CTLFLAG_RW, &psmhz, 0,
2247     "Frequency of the softcallout (in hz)");
2248 static int psmerrsecs = 2;
2249 SYSCTL_INT(_debug_psm, OID_AUTO, errsecs, CTLFLAG_RW, &psmerrsecs, 0,
2250     "Number of seconds during which packets will dropped after a sync error");
2251 static int psmerrusecs = 0;
2252 SYSCTL_INT(_debug_psm, OID_AUTO, errusecs, CTLFLAG_RW, &psmerrusecs, 0,
2253     "Microseconds to add to psmerrsecs");
2254 static int psmsecs = 0;
2255 SYSCTL_INT(_debug_psm, OID_AUTO, secs, CTLFLAG_RW, &psmsecs, 0,
2256     "Max number of seconds between soft interrupts");
2257 static int psmusecs = 500000;
2258 SYSCTL_INT(_debug_psm, OID_AUTO, usecs, CTLFLAG_RW, &psmusecs, 0,
2259     "Microseconds to add to psmsecs");
2260 static int pkterrthresh = 2;
2261 SYSCTL_INT(_debug_psm, OID_AUTO, pkterrthresh, CTLFLAG_RW, &pkterrthresh, 0,
2262     "Number of error packets allowed before reinitializing the mouse");
2263
2264 static int tap_threshold = PSM_TAP_THRESHOLD;
2265 SYSCTL_INT(_hw_psm, OID_AUTO, tap_threshold, CTLFLAG_RW, &tap_threshold, 0,
2266     "Button tap threshold");
2267 static int tap_timeout = PSM_TAP_TIMEOUT;
2268 SYSCTL_INT(_hw_psm, OID_AUTO, tap_timeout, CTLFLAG_RW, &tap_timeout, 0,
2269     "Tap timeout for touchpads");
2270
2271 static void
2272 psmintr(void *arg)
2273 {
2274         struct psm_softc *sc = arg;
2275         struct timeval now;
2276         int c;
2277         packetbuf_t *pb;
2278
2279
2280         /* read until there is nothing to read */
2281         while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
2282                 pb = &sc->pqueue[sc->pqueue_end];
2283
2284                 /* discard the byte if the device is not open */
2285                 if ((sc->state & PSM_OPEN) == 0)
2286                         continue;
2287
2288                 getmicrouptime(&now);
2289                 if ((pb->inputbytes > 0) &&
2290                     timevalcmp(&now, &sc->inputtimeout, >)) {
2291                         VLOG(3, (LOG_DEBUG, "psmintr: delay too long; "
2292                             "resetting byte count\n"));
2293                         pb->inputbytes = 0;
2294                         sc->syncerrors = 0;
2295                         sc->pkterrors = 0;
2296                 }
2297                 sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT / 1000000;
2298                 sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT % 1000000;
2299                 timevaladd(&sc->inputtimeout, &now);
2300
2301                 pb->ipacket[pb->inputbytes++] = c;
2302
2303                 if (sc->mode.level == PSM_LEVEL_NATIVE) {
2304                         VLOG(4, (LOG_DEBUG, "psmintr: %02x\n", pb->ipacket[0]));
2305                         sc->syncerrors = 0;
2306                         sc->pkterrors = 0;
2307                         goto next;
2308                 } else {
2309                         if (pb->inputbytes < sc->mode.packetsize)
2310                                 continue;
2311
2312                         VLOG(4, (LOG_DEBUG,
2313                             "psmintr: %02x %02x %02x %02x %02x %02x\n",
2314                             pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
2315                             pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
2316                 }
2317
2318                 c = pb->ipacket[0];
2319
2320                 if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2321                         sc->mode.syncmask[1] = (c & sc->mode.syncmask[0]);
2322                         sc->flags &= ~PSM_NEED_SYNCBITS;
2323                         VLOG(2, (LOG_DEBUG,
2324                             "psmintr: Sync bytes now %04x,%04x\n",
2325                             sc->mode.syncmask[0], sc->mode.syncmask[0]));
2326                 } else if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
2327                         VLOG(3, (LOG_DEBUG, "psmintr: out of sync "
2328                             "(%04x != %04x) %d cmds since last error.\n",
2329                             c & sc->mode.syncmask[0], sc->mode.syncmask[1],
2330                             sc->cmdcount - sc->lasterr));
2331                         sc->lasterr = sc->cmdcount;
2332                         /*
2333                          * The sync byte test is a weak measure of packet
2334                          * validity.  Conservatively discard any input yet
2335                          * to be seen by userland when we detect a sync
2336                          * error since there is a good chance some of
2337                          * the queued packets have undetected errors.
2338                          */
2339                         dropqueue(sc);
2340                         if (sc->syncerrors == 0)
2341                                 sc->pkterrors++;
2342                         ++sc->syncerrors;
2343                         sc->lastinputerr = now;
2344                         if (sc->syncerrors >= sc->mode.packetsize * 2 ||
2345                             sc->pkterrors >= pkterrthresh) {
2346                                 /*
2347                                  * If we've failed to find a single sync byte
2348                                  * in 2 packets worth of data, or we've seen
2349                                  * persistent packet errors during the
2350                                  * validation period, reinitialize the mouse
2351                                  * in hopes of returning it to the expected
2352                                  * mode.
2353                                  */
2354                                 VLOG(3, (LOG_DEBUG,
2355                                     "psmintr: reset the mouse.\n"));
2356                                 reinitialize(sc, TRUE);
2357                         } else if (sc->syncerrors == sc->mode.packetsize) {
2358                                 /*
2359                                  * Try a soft reset after searching for a sync
2360                                  * byte through a packet length of bytes.
2361                                  */
2362                                 VLOG(3, (LOG_DEBUG,
2363                                     "psmintr: re-enable the mouse.\n"));
2364                                 pb->inputbytes = 0;
2365                                 disable_aux_dev(sc->kbdc);
2366                                 enable_aux_dev(sc->kbdc);
2367                         } else {
2368                                 VLOG(3, (LOG_DEBUG,
2369                                     "psmintr: discard a byte (%d)\n",
2370                                     sc->syncerrors));
2371                                 pb->inputbytes--;
2372                                 bcopy(&pb->ipacket[1], &pb->ipacket[0],
2373                                     pb->inputbytes);
2374                         }
2375                         continue;
2376                 }
2377
2378                 /*
2379                  * We have what appears to be a valid packet.
2380                  * Reset the error counters.
2381                  */
2382                 sc->syncerrors = 0;
2383
2384                 /*
2385                  * Drop even good packets if they occur within a timeout
2386                  * period of a sync error.  This allows the detection of
2387                  * a change in the mouse's packet mode without exposing
2388                  * erratic mouse behavior to the user.  Some KVMs forget
2389                  * enhanced mouse modes during switch events.
2390                  */
2391                 if (!timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs,
2392                     &now)) {
2393                         pb->inputbytes = 0;
2394                         continue;
2395                 }
2396
2397                 /*
2398                  * Now that we're out of the validation period, reset
2399                  * the packet error count.
2400                  */
2401                 sc->pkterrors = 0;
2402
2403                 sc->cmdcount++;
2404 next:
2405                 if (++sc->pqueue_end >= PSM_PACKETQUEUE)
2406                         sc->pqueue_end = 0;
2407                 /*
2408                  * If we've filled the queue then call the softintr ourselves,
2409                  * otherwise schedule the interrupt for later.
2410                  */
2411                 if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
2412                     (sc->pqueue_end == sc->pqueue_start)) {
2413                         if ((sc->state & PSM_SOFTARMED) != 0) {
2414                                 sc->state &= ~PSM_SOFTARMED;
2415                                 untimeout(psmsoftintr, arg, sc->softcallout);
2416                         }
2417                         psmsoftintr(arg);
2418                 } else if ((sc->state & PSM_SOFTARMED) == 0) {
2419                         sc->state |= PSM_SOFTARMED;
2420                         sc->softcallout = timeout(psmsoftintr, arg,
2421                             psmhz < 1 ? 1 : (hz/psmhz));
2422                 }
2423         }
2424 }
2425
2426 static void
2427 proc_mmanplus(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
2428     int *x, int *y, int *z)
2429 {
2430
2431         /*
2432          * PS2++ protocl packet
2433          *
2434          *          b7 b6 b5 b4 b3 b2 b1 b0
2435          * byte 1:  *  1  p3 p2 1  *  *  *
2436          * byte 2:  c1 c2 p1 p0 d1 d0 1  0
2437          *
2438          * p3-p0: packet type
2439          * c1, c2: c1 & c2 == 1, if p2 == 0
2440          *         c1 & c2 == 0, if p2 == 1
2441          *
2442          * packet type: 0 (device type)
2443          * See comments in enable_mmanplus() below.
2444          *
2445          * packet type: 1 (wheel data)
2446          *
2447          *          b7 b6 b5 b4 b3 b2 b1 b0
2448          * byte 3:  h  *  B5 B4 s  d2 d1 d0
2449          *
2450          * h: 1, if horizontal roller data
2451          *    0, if vertical roller data
2452          * B4, B5: button 4 and 5
2453          * s: sign bit
2454          * d2-d0: roller data
2455          *
2456          * packet type: 2 (reserved)
2457          */
2458         if (((pb->ipacket[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC) &&
2459             (abs(*x) > 191) && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
2460                 /*
2461                  * the extended data packet encodes button
2462                  * and wheel events
2463                  */
2464                 switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
2465                 case 1:
2466                         /* wheel data packet */
2467                         *x = *y = 0;
2468                         if (pb->ipacket[2] & 0x80) {
2469                                 /* XXX horizontal roller count - ignore it */
2470                                 ;
2471                         } else {
2472                                 /* vertical roller count */
2473                                 *z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG) ?
2474                                     (pb->ipacket[2] & 0x0f) - 16 :
2475                                     (pb->ipacket[2] & 0x0f);
2476                         }
2477                         ms->button |= (pb->ipacket[2] &
2478                             MOUSE_PS2PLUS_BUTTON4DOWN) ?
2479                             MOUSE_BUTTON4DOWN : 0;
2480                         ms->button |= (pb->ipacket[2] &
2481                             MOUSE_PS2PLUS_BUTTON5DOWN) ?
2482                             MOUSE_BUTTON5DOWN : 0;
2483                         break;
2484                 case 2:
2485                         /*
2486                          * this packet type is reserved by
2487                          * Logitech...
2488                          */
2489                         /*
2490                          * IBM ScrollPoint Mouse uses this
2491                          * packet type to encode both vertical
2492                          * and horizontal scroll movement.
2493                          */
2494                         *x = *y = 0;
2495                         /* horizontal count */
2496                         if (pb->ipacket[2] & 0x0f)
2497                                 *z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ?
2498                                     -2 : 2;
2499                         /* vertical count */
2500                         if (pb->ipacket[2] & 0xf0)
2501                                 *z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ?
2502                                     -1 : 1;
2503                         break;
2504                 case 0:
2505                         /* device type packet - shouldn't happen */
2506                         /* FALLTHROUGH */
2507                 default:
2508                         *x = *y = 0;
2509                         ms->button = ms->obutton;
2510                         VLOG(1, (LOG_DEBUG, "psmintr: unknown PS2++ packet "
2511                             "type %d: 0x%02x 0x%02x 0x%02x\n",
2512                             MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
2513                             pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]));
2514                         break;
2515                 }
2516         } else {
2517                 /* preserve button states */
2518                 ms->button |= ms->obutton & MOUSE_EXTBUTTONS;
2519         }
2520 }
2521
2522 static int
2523 proc_synaptics(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
2524     int *x, int *y, int *z)
2525 {
2526         static int touchpad_buttons;
2527         static int guest_buttons;
2528         int w, x0, y0;
2529
2530         /* TouchPad PS/2 absolute mode message format
2531          *
2532          *  Bits:        7   6   5   4   3   2   1   0 (LSB)
2533          *  ------------------------------------------------
2534          *  ipacket[0]:  1   0  W3  W2   0  W1   R   L
2535          *  ipacket[1]: Yb  Ya  Y9  Y8  Xb  Xa  X9  X8
2536          *  ipacket[2]: Z7  Z6  Z5  Z4  Z3  Z2  Z1  Z0
2537          *  ipacket[3]:  1   1  Yc  Xc   0  W0   D   U
2538          *  ipacket[4]: X7  X6  X5  X4  X3  X2  X1  X0
2539          *  ipacket[5]: Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
2540          *
2541          * Legend:
2542          *  L: left physical mouse button
2543          *  R: right physical mouse button
2544          *  D: down button
2545          *  U: up button
2546          *  W: "wrist" value
2547          *  X: x position
2548          *  Y: y position
2549          *  Z: pressure
2550          *
2551          * Absolute reportable limits:    0 - 6143.
2552          * Typical bezel limits:       1472 - 5472.
2553          * Typical edge marings:       1632 - 5312.
2554          *
2555          * w = 3 Passthrough Packet
2556          *
2557          * Byte 2,5,6 == Byte 1,2,3 of "Guest"
2558          */
2559
2560         if (!synaptics_support)
2561                 return (0);
2562
2563         /* Sanity check for out of sync packets. */
2564         if ((pb->ipacket[0] & 0xc8) != 0x80 ||
2565             (pb->ipacket[3] & 0xc8) != 0xc0)
2566                 return (-1);
2567
2568         *x = *y = 0;
2569
2570         /*
2571          * Pressure value.
2572          * Interpretation:
2573          *   z = 0      No finger contact
2574          *   z = 10     Finger hovering near the pad
2575          *   z = 30     Very light finger contact
2576          *   z = 80     Normal finger contact
2577          *   z = 110    Very heavy finger contact
2578          *   z = 200    Finger lying flat on pad surface
2579          *   z = 255    Maximum reportable Z
2580          */
2581         *z = pb->ipacket[2];
2582
2583         /*
2584          * Finger width value
2585          * Interpretation:
2586          *   w = 0      Two finger on the pad (capMultiFinger needed)
2587          *   w = 1      Three or more fingers (capMultiFinger needed)
2588          *   w = 2      Pen (instead of finger) (capPen needed)
2589          *   w = 3      Reserved (passthrough?)
2590          *   w = 4-7    Finger of normal width (capPalmDetect needed)
2591          *   w = 8-14   Very wide finger or palm (capPalmDetect needed)
2592          *   w = 15     Maximum reportable width (capPalmDetect needed)
2593          */
2594         /* XXX Is checking capExtended enough? */
2595         if (sc->synhw.capExtended)
2596                 w = ((pb->ipacket[0] & 0x30) >> 2) |
2597                     ((pb->ipacket[0] & 0x04) >> 1) |
2598                     ((pb->ipacket[3] & 0x04) >> 2);
2599         else {
2600                 /* Assume a finger of regular width. */
2601                 w = 4;
2602         }
2603
2604         /* Handle packets from the guest device */
2605         /* XXX Documentation? */
2606         if (w == 3 && sc->synhw.capPassthrough) {
2607                 *x = ((pb->ipacket[1] & 0x10) ?
2608                     pb->ipacket[4] - 256 : pb->ipacket[4]);
2609                 *y = ((pb->ipacket[1] & 0x20) ?
2610                     pb->ipacket[5] - 256 : pb->ipacket[5]);
2611                 *z = 0;
2612
2613                 guest_buttons = 0;
2614                 if (pb->ipacket[1] & 0x01)
2615                         guest_buttons |= MOUSE_BUTTON1DOWN;
2616                 if (pb->ipacket[1] & 0x04)
2617                         guest_buttons |= MOUSE_BUTTON2DOWN;
2618                 if (pb->ipacket[1] & 0x02)
2619                         guest_buttons |= MOUSE_BUTTON3DOWN;
2620
2621                 ms->button = touchpad_buttons | guest_buttons;
2622                 goto SYNAPTICS_END;
2623         }
2624
2625         /* Button presses */
2626         touchpad_buttons = 0;
2627         if (pb->ipacket[0] & 0x01)
2628                 touchpad_buttons |= MOUSE_BUTTON1DOWN;
2629         if (pb->ipacket[0] & 0x02)
2630                 touchpad_buttons |= MOUSE_BUTTON3DOWN;
2631
2632         if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
2633                 if ((pb->ipacket[3] & 0x01) && (pb->ipacket[0] & 0x01) == 0)
2634                         touchpad_buttons |= MOUSE_BUTTON4DOWN;
2635                 if ((pb->ipacket[3] & 0x02) && (pb->ipacket[0] & 0x02) == 0)
2636                         touchpad_buttons |= MOUSE_BUTTON5DOWN;
2637         }
2638
2639         /*
2640          * In newer pads - bit 0x02 in the third byte of
2641          * the packet indicates that we have an extended
2642          * button press.
2643          */
2644         /* XXX Documentation? */
2645         if (pb->ipacket[3] & 0x02) {
2646                 /*
2647                  * if directional_scrolls is not 1, we treat any of
2648                  * the scrolling directions as middle-click.
2649                  */
2650                 if (sc->syninfo.directional_scrolls) {
2651                         if (pb->ipacket[4] & 0x01)
2652                                 touchpad_buttons |= MOUSE_BUTTON4DOWN;
2653                         if (pb->ipacket[5] & 0x01)
2654                                 touchpad_buttons |= MOUSE_BUTTON5DOWN;
2655                         if (pb->ipacket[4] & 0x02)
2656                                 touchpad_buttons |= MOUSE_BUTTON6DOWN;
2657                         if (pb->ipacket[5] & 0x02)
2658                                 touchpad_buttons |= MOUSE_BUTTON7DOWN;
2659                 } else {
2660                         if ((pb->ipacket[4] & 0x0F) ||
2661                             (pb->ipacket[5] & 0x0F))
2662                                 touchpad_buttons |= MOUSE_BUTTON2DOWN;
2663                 }
2664         }
2665
2666         ms->button = touchpad_buttons | guest_buttons;
2667
2668         /* Check pressure to detect a real wanted action on the
2669          * touchpad. */
2670         if (*z >= sc->syninfo.min_pressure) {
2671                 synapticsaction_t *synaction;
2672                 int cursor, peer, window;
2673                 int dx, dy, dxp, dyp;
2674                 int max_width, max_pressure;
2675                 int margin_top, margin_right, margin_bottom, margin_left;
2676                 int na_top, na_right, na_bottom, na_left;
2677                 int window_min, window_max;
2678                 int multiplicator;
2679                 int weight_current, weight_previous, weight_len_squared;
2680                 int div_min, div_max, div_len;
2681                 int vscroll_hor_area, vscroll_ver_area;
2682
2683                 int len, weight_prev_x, weight_prev_y;
2684                 int div_max_x, div_max_y, div_x, div_y;
2685
2686                 /* Read sysctl. */
2687                 /* XXX Verify values? */
2688                 max_width = sc->syninfo.max_width;
2689                 max_pressure = sc->syninfo.max_pressure;
2690                 margin_top = sc->syninfo.margin_top;
2691                 margin_right = sc->syninfo.margin_right;
2692                 margin_bottom = sc->syninfo.margin_bottom;
2693                 margin_left = sc->syninfo.margin_left;
2694                 na_top = sc->syninfo.na_top;
2695                 na_right = sc->syninfo.na_right;
2696                 na_bottom = sc->syninfo.na_bottom;
2697                 na_left = sc->syninfo.na_left;
2698                 window_min = sc->syninfo.window_min;
2699                 window_max = sc->syninfo.window_max;
2700                 multiplicator = sc->syninfo.multiplicator;
2701                 weight_current = sc->syninfo.weight_current;
2702                 weight_previous = sc->syninfo.weight_previous;
2703                 weight_len_squared = sc->syninfo.weight_len_squared;
2704                 div_min = sc->syninfo.div_min;
2705                 div_max = sc->syninfo.div_max;
2706                 div_len = sc->syninfo.div_len;
2707                 vscroll_hor_area = sc->syninfo.vscroll_hor_area;
2708                 vscroll_ver_area = sc->syninfo.vscroll_ver_area;
2709
2710                 /* Palm detection. */
2711                 if (!(
2712                     (sc->synhw.capMultiFinger && (w == 0 || w == 1)) ||
2713                     (sc->synhw.capPalmDetect && w >= 4 && w <= max_width) ||
2714                     (!sc->synhw.capPalmDetect && *z <= max_pressure) ||
2715                     (sc->synhw.capPen && w == 2))) {
2716                         /*
2717                          * We consider the packet irrelevant for the current
2718                          * action when:
2719                          *  - the width isn't comprised in:
2720                          *    [4; max_width]
2721                          *  - the pressure isn't comprised in:
2722                          *    [min_pressure; max_pressure]
2723                          *  - pen aren't supported but w is 2
2724                          *
2725                          *  Note that this doesn't terminate the current action.
2726                          */
2727                         VLOG(2, (LOG_DEBUG,
2728                             "synaptics: palm detected! (%d)\n", w));
2729                         goto SYNAPTICS_END;
2730                 }
2731
2732                 /* Read current absolute position. */
2733                 x0 = ((pb->ipacket[3] & 0x10) << 8) |
2734                     ((pb->ipacket[1] & 0x0f) << 8) |
2735                     pb->ipacket[4];
2736                 y0 = ((pb->ipacket[3] & 0x20) << 7) |
2737                     ((pb->ipacket[1] & 0xf0) << 4) |
2738                     pb->ipacket[5];
2739
2740                 synaction = &(sc->synaction);
2741
2742                 /*
2743                  * If the action is just beginning, init the structure and
2744                  * compute tap timeout.
2745                  */
2746                 if (!(sc->flags & PSM_FLAGS_FINGERDOWN)) {
2747                         VLOG(3, (LOG_DEBUG, "synaptics: ----\n"));
2748
2749                         /* Store the first point of this action. */
2750                         synaction->start_x = x0;
2751                         synaction->start_y = y0;
2752                         dx = dy = 0;
2753
2754                         /* Initialize queue. */
2755                         synaction->queue_cursor = SYNAPTICS_PACKETQUEUE;
2756                         synaction->queue_len = 0;
2757                         synaction->window_min = window_min;
2758
2759                         /* Reset average. */
2760                         synaction->avg_dx = 0;
2761                         synaction->avg_dy = 0;
2762
2763                         /* Reset squelch. */
2764                         synaction->squelch_x = 0;
2765                         synaction->squelch_y = 0;
2766
2767                         /* Reset pressure peak. */
2768                         sc->zmax = 0;
2769
2770                         /* Reset fingers count. */
2771                         synaction->fingers_nb = 0;
2772
2773                         /* Reset virtual scrolling state. */
2774                         synaction->in_vscroll = 0;
2775
2776                         /* Compute tap timeout. */
2777                         sc->taptimeout.tv_sec  = tap_timeout / 1000000;
2778                         sc->taptimeout.tv_usec = tap_timeout % 1000000;
2779                         timevaladd(&sc->taptimeout, &sc->lastsoftintr);
2780
2781                         sc->flags |= PSM_FLAGS_FINGERDOWN;
2782                 } else {
2783                         /* Calculate the current delta. */
2784                         cursor = synaction->queue_cursor;
2785                         dx = x0 - synaction->queue[cursor].x;
2786                         dy = y0 - synaction->queue[cursor].y;
2787                 }
2788
2789                 /* If in tap-hold, add the recorded button. */
2790                 if (synaction->in_taphold)
2791                         ms->button |= synaction->tap_button;
2792
2793                 /*
2794                  * From now on, we can use the SYNAPTICS_END label to skip
2795                  * the current packet.
2796                  */
2797
2798                 /*
2799                  * Limit the coordinates to the specified margins because
2800                  * this area isn't very reliable.
2801                  */
2802                 if (x0 <= margin_left)
2803                         x0 = margin_left;
2804                 else if (x0 >= 6143 - margin_right)
2805                         x0 = 6143 - margin_right;
2806                 if (y0 <= margin_bottom)
2807                         y0 = margin_bottom;
2808                 else if (y0 >= 6143 - margin_top)
2809                         y0 = 6143 - margin_top;
2810
2811                 VLOG(3, (LOG_DEBUG, "synaptics: ipacket: [%d, %d], %d, %d\n",
2812                     x0, y0, *z, w));
2813
2814                 /* Queue this new packet. */
2815                 cursor = SYNAPTICS_QUEUE_CURSOR(synaction->queue_cursor - 1);
2816                 synaction->queue[cursor].x = x0;
2817                 synaction->queue[cursor].y = y0;
2818                 synaction->queue_cursor = cursor;
2819                 if (synaction->queue_len < SYNAPTICS_PACKETQUEUE)
2820                         synaction->queue_len++;
2821                 VLOG(5, (LOG_DEBUG,
2822                     "synaptics: cursor[%d]: x=%d, y=%d, dx=%d, dy=%d\n",
2823                     cursor, x0, y0, dx, dy));
2824
2825                 /*
2826                  * For tap, we keep the maximum number of fingers and the
2827                  * pressure peak. Also with multiple fingers, we increase
2828                  * the minimum window.
2829                  */
2830                 switch (w) {
2831                 case 1: /* Three or more fingers. */
2832                         synaction->fingers_nb = imax(3, synaction->fingers_nb);
2833                         synaction->window_min = window_max;
2834                         break;
2835                 case 0: /* Two fingers. */
2836                         synaction->fingers_nb = imax(2, synaction->fingers_nb);
2837                         synaction->window_min = window_max;
2838                         break;
2839                 default: /* One finger or undetectable. */
2840                         synaction->fingers_nb = imax(1, synaction->fingers_nb);
2841                 }
2842                 sc->zmax = imax(*z, sc->zmax);
2843
2844                 /* Do we have enough packets to consider this a movement? */
2845                 if (synaction->queue_len < synaction->window_min)
2846                         goto SYNAPTICS_END;
2847
2848                 /* Is a scrolling action occuring? */
2849                 if (!synaction->in_taphold && !synaction->in_vscroll) {
2850                         /*
2851                          * A scrolling action must not conflict with a tap
2852                          * action. Here are the conditions to consider a
2853                          * scrolling action:
2854                          *  - the action in a configurable area
2855                          *  - one of the following:
2856                          *     . the distance between the last packet and the
2857                          *       first should be above a configurable minimum
2858                          *     . tap timed out
2859                          */
2860                         dxp = abs(synaction->queue[synaction->queue_cursor].x -
2861                             synaction->start_x);
2862                         dyp = abs(synaction->queue[synaction->queue_cursor].y -
2863                             synaction->start_y);
2864
2865                         if (timevalcmp(&sc->lastsoftintr, &sc->taptimeout, >) ||
2866                             dxp >= sc->syninfo.vscroll_min_delta ||
2867                             dyp >= sc->syninfo.vscroll_min_delta) {
2868                                 /* Check for horizontal scrolling. */
2869                                 if ((vscroll_hor_area > 0 &&
2870                                     synaction->start_y <= vscroll_hor_area) ||
2871                                     (vscroll_hor_area < 0 &&
2872                                      synaction->start_y >=
2873                                      6143 + vscroll_hor_area))
2874                                         synaction->in_vscroll += 2;
2875
2876                                 /* Check for vertical scrolling. */
2877                                 if ((vscroll_ver_area > 0 &&
2878                                     synaction->start_x <= vscroll_ver_area) ||
2879                                     (vscroll_ver_area < 0 &&
2880                                      synaction->start_x >=
2881                                      6143 + vscroll_ver_area))
2882                                         synaction->in_vscroll += 1;
2883
2884                                 /* Avoid conflicts if area overlaps. */
2885                                 if (synaction->in_vscroll == 3)
2886                                         synaction->in_vscroll =
2887                                             (dxp > dyp) ? 2 : 1;
2888                         }
2889                         VLOG(5, (LOG_DEBUG,
2890                             "synaptics: virtual scrolling: %s "
2891                             "(direction=%d, dxp=%d, dyp=%d)\n",
2892                             synaction->in_vscroll ? "YES" : "NO",
2893                             synaction->in_vscroll, dxp, dyp));
2894                 }
2895
2896                 weight_prev_x = weight_prev_y = weight_previous;
2897                 div_max_x = div_max_y = div_max;
2898
2899                 if (synaction->in_vscroll) {
2900                         /* Dividers are different with virtual scrolling. */
2901                         div_min = sc->syninfo.vscroll_div_min;
2902                         div_max_x = div_max_y = sc->syninfo.vscroll_div_max;
2903                 } else {
2904                         /*
2905                          * There's a lot of noise in coordinates when
2906                          * the finger is on the touchpad's borders. When
2907                          * using this area, we apply a special weight and
2908                          * div.
2909                          */
2910                         if (x0 <= na_left || x0 >= 6143 - na_right) {
2911                                 weight_prev_x = sc->syninfo.weight_previous_na;
2912                                 div_max_x = sc->syninfo.div_max_na;
2913                         }
2914
2915                         if (y0 <= na_bottom || y0 >= 6143 - na_top) {
2916                                 weight_prev_y = sc->syninfo.weight_previous_na;
2917                                 div_max_y = sc->syninfo.div_max_na;
2918                         }
2919                 }
2920
2921                 /*
2922                  * Calculate weights for the average operands and
2923                  * the divisor. Both depend on the distance between
2924                  * the current packet and a previous one (based on the
2925                  * window width).
2926                  */
2927                 window = imin(synaction->queue_len, window_max);
2928                 peer = SYNAPTICS_QUEUE_CURSOR(cursor + window - 1);
2929                 dxp = abs(x0 - synaction->queue[peer].x) + 1;
2930                 dyp = abs(y0 - synaction->queue[peer].y) + 1;
2931                 len = (dxp * dxp) + (dyp * dyp);
2932                 weight_prev_x = imin(weight_prev_x,
2933                     weight_len_squared * weight_prev_x / len);
2934                 weight_prev_y = imin(weight_prev_y,
2935                     weight_len_squared * weight_prev_y / len);
2936
2937                 len = (dxp + dyp) / 2;
2938                 div_x = div_len * div_max_x / len;
2939                 div_x = imin(div_max_x, div_x);
2940                 div_x = imax(div_min, div_x);
2941                 div_y = div_len * div_max_y / len;
2942                 div_y = imin(div_max_y, div_y);
2943                 div_y = imax(div_min, div_y);
2944
2945                 VLOG(3, (LOG_DEBUG,
2946                     "synaptics: peer=%d, len=%d, weight=%d/%d, div=%d/%d\n",
2947                     peer, len, weight_prev_x, weight_prev_y, div_x, div_y));
2948
2949                 /* Compute averages. */
2950                 synaction->avg_dx =
2951                     (weight_current * dx * multiplicator +
2952                      weight_prev_x * synaction->avg_dx) /
2953                     (weight_current + weight_prev_x);
2954
2955                 synaction->avg_dy =
2956                     (weight_current * dy * multiplicator +
2957                      weight_prev_y * synaction->avg_dy) /
2958                     (weight_current + weight_prev_y);
2959
2960                 VLOG(5, (LOG_DEBUG,
2961                     "synaptics: avg_dx~=%d, avg_dy~=%d\n",
2962                     synaction->avg_dx / multiplicator,
2963                     synaction->avg_dy / multiplicator));
2964
2965                 /* Use these averages to calculate x & y. */
2966                 synaction->squelch_x += synaction->avg_dx;
2967                 *x = synaction->squelch_x / (div_x * multiplicator);
2968                 synaction->squelch_x = synaction->squelch_x %
2969                     (div_x * multiplicator);
2970
2971                 synaction->squelch_y += synaction->avg_dy;
2972                 *y = synaction->squelch_y / (div_y * multiplicator);
2973                 synaction->squelch_y = synaction->squelch_y %
2974                     (div_y * multiplicator);
2975
2976                 if (synaction->in_vscroll) {
2977                         switch(synaction->in_vscroll) {
2978                         case 1: /* Vertical scrolling. */
2979                                 if (*y != 0)
2980                                         ms->button |= (*y > 0) ?
2981                                             MOUSE_BUTTON4DOWN :
2982                                             MOUSE_BUTTON5DOWN;
2983                                 break;
2984                         case 2: /* Horizontal scrolling. */
2985                                 if (*x != 0)
2986                                         ms->button |= (*x > 0) ?
2987                                             MOUSE_BUTTON7DOWN :
2988                                             MOUSE_BUTTON6DOWN;
2989                                 break;
2990                         }
2991
2992                         /* The pointer is not moved. */
2993                         *x = *y = 0;
2994                 } else {
2995                         VLOG(3, (LOG_DEBUG, "synaptics: [%d, %d] -> [%d, %d]\n",
2996                             dx, dy, *x, *y));
2997                 }
2998         } else if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2999                 /*
3000                  * An action is currently taking place but the pressure
3001                  * dropped under the minimum, putting an end to it.
3002                  */
3003                 synapticsaction_t *synaction;
3004                 int taphold_timeout, dx, dy, tap_max_delta;
3005
3006                 synaction = &(sc->synaction);
3007                 dx = abs(synaction->queue[synaction->queue_cursor].x -
3008                     synaction->start_x);
3009                 dy = abs(synaction->queue[synaction->queue_cursor].y -
3010                     synaction->start_y);
3011
3012                 /* Max delta is disabled for multi-fingers tap. */
3013                 if (synaction->fingers_nb > 1)
3014                         tap_max_delta = imax(dx, dy);
3015                 else
3016                         tap_max_delta = sc->syninfo.tap_max_delta;
3017
3018                 sc->flags &= ~PSM_FLAGS_FINGERDOWN;
3019
3020                 /* Check for tap. */
3021                 VLOG(3, (LOG_DEBUG,
3022                     "synaptics: zmax=%d, dx=%d, dy=%d, "
3023                     "delta=%d, fingers=%d, queue=%d\n",
3024                     sc->zmax, dx, dy, tap_max_delta, synaction->fingers_nb,
3025                     synaction->queue_len));
3026                 if (!synaction->in_vscroll && sc->zmax >= tap_threshold &&
3027                     timevalcmp(&sc->lastsoftintr, &sc->taptimeout, <=) &&
3028                     dx <= tap_max_delta && dy <= tap_max_delta &&
3029                     synaction->queue_len >= sc->syninfo.tap_min_queue) {
3030                         /*
3031                          * We have a tap if:
3032                          *   - the maximum pressure went over tap_threshold
3033                          *   - the action ended before tap_timeout
3034                          *
3035                          * To handle tap-hold, we must delay any button push to
3036                          * the next action.
3037                          */
3038                         if (synaction->in_taphold) {
3039                                 /*
3040                                  * This is the second and last tap of a
3041                                  * double tap action, not a tap-hold.
3042                                  */
3043                                 synaction->in_taphold = 0;
3044
3045                                 /*
3046                                  * For double-tap to work:
3047                                  *   - no button press is emitted (to
3048                                  *     simulate a button release)
3049                                  *   - PSM_FLAGS_FINGERDOWN is set to
3050                                  *     force the next packet to emit a
3051                                  *     button press)
3052                                  */
3053                                 VLOG(2, (LOG_DEBUG,
3054                                     "synaptics: button RELEASE: %d\n",
3055                                     synaction->tap_button));
3056                                 sc->flags |= PSM_FLAGS_FINGERDOWN;
3057                         } else {
3058                                 /*
3059                                  * This is the first tap: we set the
3060                                  * tap-hold state and notify the button
3061                                  * down event.
3062                                  */
3063                                 synaction->in_taphold = 1;
3064                                 taphold_timeout = sc->syninfo.taphold_timeout;
3065                                 sc->taptimeout.tv_sec  = taphold_timeout /
3066                                     1000000;
3067                                 sc->taptimeout.tv_usec = taphold_timeout %
3068                                     1000000;
3069                                 timevaladd(&sc->taptimeout, &sc->lastsoftintr);
3070
3071                                 switch (synaction->fingers_nb) {
3072                                 case 3:
3073                                         synaction->tap_button =
3074                                             MOUSE_BUTTON2DOWN;
3075                                         break;
3076                                 case 2:
3077                                         synaction->tap_button =
3078                                             MOUSE_BUTTON3DOWN;
3079                                         break;
3080                                 default:
3081                                         synaction->tap_button =
3082                                             MOUSE_BUTTON1DOWN;
3083                                 }
3084                                 VLOG(2, (LOG_DEBUG,
3085                                     "synaptics: button PRESS: %d\n",
3086                                     synaction->tap_button));
3087                                 ms->button |= synaction->tap_button;
3088                         }
3089                 } else {
3090                         /*
3091                          * Not enough pressure or timeout: reset
3092                          * tap-hold state.
3093                          */
3094                         if (synaction->in_taphold) {
3095                                 VLOG(2, (LOG_DEBUG,
3096                                     "synaptics: button RELEASE: %d\n",
3097                                     synaction->tap_button));
3098                                 synaction->in_taphold = 0;
3099                         } else {
3100                                 VLOG(2, (LOG_DEBUG,
3101                                     "synaptics: not a tap-hold\n"));
3102                         }
3103                 }
3104         } else if (!(sc->flags & PSM_FLAGS_FINGERDOWN) &&
3105             sc->synaction.in_taphold) {
3106                 /*
3107                  * For a tap-hold to work, the button must remain down at
3108                  * least until timeout (where the in_taphold flags will be
3109                  * cleared) or during the next action.
3110                  */
3111                 if (timevalcmp(&sc->lastsoftintr, &sc->taptimeout, <=)) {
3112                         ms->button |= sc->synaction.tap_button;
3113                 } else {
3114                         VLOG(2, (LOG_DEBUG,
3115                             "synaptics: button RELEASE: %d\n",
3116                             sc->synaction.tap_button));
3117                         sc->synaction.in_taphold = 0;
3118                 }
3119         }
3120
3121 SYNAPTICS_END:
3122         /*
3123          * Use the extra buttons as a scrollwheel
3124          *
3125          * XXX X.Org uses the Z axis for vertical wheel only,
3126          * whereas moused(8) understands special values to differ
3127          * vertical and horizontal wheels.
3128          *
3129          * xf86-input-mouse needs therefore a small patch to
3130          * understand these special values. Without it, the
3131          * horizontal wheel acts as a vertical wheel in X.Org.
3132          *
3133          * That's why the horizontal wheel is disabled by
3134          * default for now.
3135          */
3136         if (ms->button & MOUSE_BUTTON4DOWN) {
3137                 *z = -1;
3138                 ms->button &= ~MOUSE_BUTTON4DOWN;
3139         } else if (ms->button & MOUSE_BUTTON5DOWN) {
3140                 *z = 1;
3141                 ms->button &= ~MOUSE_BUTTON5DOWN;
3142         } else if (ms->button & MOUSE_BUTTON6DOWN) {
3143                 *z = -2;
3144                 ms->button &= ~MOUSE_BUTTON6DOWN;
3145         } else if (ms->button & MOUSE_BUTTON7DOWN) {
3146                 *z = 2;
3147                 ms->button &= ~MOUSE_BUTTON7DOWN;
3148         } else
3149                 *z = 0;
3150
3151         return (0);
3152 }
3153
3154 static void
3155 proc_versapad(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
3156     int *x, int *y, int *z)
3157 {
3158         static int butmap_versapad[8] = {
3159                 0,
3160                 MOUSE_BUTTON3DOWN,
3161                 0,
3162                 MOUSE_BUTTON3DOWN,
3163                 MOUSE_BUTTON1DOWN,
3164                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
3165                 MOUSE_BUTTON1DOWN,
3166                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
3167         };
3168         int c, x0, y0;
3169
3170         /* VersaPad PS/2 absolute mode message format
3171          *
3172          * [packet1]     7   6   5   4   3   2   1   0(LSB)
3173          *  ipacket[0]:  1   1   0   A   1   L   T   R
3174          *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
3175          *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
3176          *  ipacket[3]:  1   1   1   A   1   L   T   R
3177          *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
3178          *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
3179          *
3180          * [note]
3181          *  R: right physical mouse button (1=on)
3182          *  T: touch pad virtual button (1=tapping)
3183          *  L: left physical mouse button (1=on)
3184          *  A: position data is valid (1=valid)
3185          *  H: horizontal data (12bit signed integer. H11 is sign bit.)
3186          *  V: vertical data (12bit signed integer. V11 is sign bit.)
3187          *  P: pressure data
3188          *
3189          * Tapping is mapped to MOUSE_BUTTON4.
3190          */
3191         c = pb->ipacket[0];
3192         *x = *y = 0;
3193         ms->button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
3194         ms->button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
3195         if (c & MOUSE_PS2VERSA_IN_USE) {
3196                 x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
3197                 y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
3198                 if (x0 & 0x800)
3199                         x0 -= 0x1000;
3200                 if (y0 & 0x800)
3201                         y0 -= 0x1000;
3202                 if (sc->flags & PSM_FLAGS_FINGERDOWN) {
3203                         *x = sc->xold - x0;
3204                         *y = y0 - sc->yold;
3205                         if (*x < 0)     /* XXX */
3206                                 ++*x;
3207                         else if (*x)
3208                                 --*x;
3209                         if (*y < 0)
3210                                 ++*y;
3211                         else if (*y)
3212                                 --*y;
3213                 } else
3214                         sc->flags |= PSM_FLAGS_FINGERDOWN;
3215                 sc->xold = x0;
3216                 sc->yold = y0;
3217         } else
3218                 sc->flags &= ~PSM_FLAGS_FINGERDOWN;
3219 }
3220
3221 static void
3222 psmsoftintr(void *arg)
3223 {
3224         /*
3225          * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
3226          * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
3227          */
3228         static int butmap[8] = {
3229                 0,
3230                 MOUSE_BUTTON1DOWN,
3231                 MOUSE_BUTTON3DOWN,
3232                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
3233                 MOUSE_BUTTON2DOWN,
3234                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
3235                 MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
3236                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
3237         };
3238         register struct psm_softc *sc = arg;
3239         mousestatus_t ms;
3240         packetbuf_t *pb;
3241         int x, y, z, c, l, s;
3242
3243         getmicrouptime(&sc->lastsoftintr);
3244
3245         s = spltty();
3246
3247         do {
3248                 pb = &sc->pqueue[sc->pqueue_start];
3249
3250                 if (sc->mode.level == PSM_LEVEL_NATIVE)
3251                         goto next_native;
3252
3253                 c = pb->ipacket[0];
3254                 /*
3255                  * A kludge for Kensington device!
3256                  * The MSB of the horizontal count appears to be stored in
3257                  * a strange place.
3258                  */
3259                 if (sc->hw.model == MOUSE_MODEL_THINK)
3260                         pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
3261
3262                 /* ignore the overflow bits... */
3263                 x = (c & MOUSE_PS2_XNEG) ?
3264                     pb->ipacket[1] - 256 : pb->ipacket[1];
3265                 y = (c & MOUSE_PS2_YNEG) ?
3266                     pb->ipacket[2] - 256 : pb->ipacket[2];
3267                 z = 0;
3268                 ms.obutton = sc->button;          /* previous button state */
3269                 ms.button = butmap[c & MOUSE_PS2_BUTTONS];
3270                 /* `tapping' action */
3271                 if (sc->config & PSM_CONFIG_FORCETAP)
3272                         ms.button |= ((c & MOUSE_PS2_TAP)) ?
3273                             0 : MOUSE_BUTTON4DOWN;
3274
3275                 switch (sc->hw.model) {
3276
3277                 case MOUSE_MODEL_EXPLORER:
3278                         /*
3279                          *          b7 b6 b5 b4 b3 b2 b1 b0
3280                          * byte 1:  oy ox sy sx 1  M  R  L
3281                          * byte 2:  x  x  x  x  x  x  x  x
3282                          * byte 3:  y  y  y  y  y  y  y  y
3283                          * byte 4:  *  *  S2 S1 s  d2 d1 d0
3284                          *
3285                          * L, M, R, S1, S2: left, middle, right and side buttons
3286                          * s: wheel data sign bit
3287                          * d2-d0: wheel data
3288                          */
3289                         z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG) ?
3290                             (pb->ipacket[3] & 0x0f) - 16 :
3291                             (pb->ipacket[3] & 0x0f);
3292                         ms.button |=
3293                             (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN) ?
3294                             MOUSE_BUTTON4DOWN : 0;
3295                         ms.button |=
3296                             (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN) ?
3297                             MOUSE_BUTTON5DOWN : 0;
3298                         break;
3299
3300                 case MOUSE_MODEL_INTELLI:
3301                 case MOUSE_MODEL_NET:
3302                         /* wheel data is in the fourth byte */
3303                         z = (char)pb->ipacket[3];
3304                         /*
3305                          * XXX some mice may send 7 when there is no Z movement?                         */
3306                         if ((z >= 7) || (z <= -7))
3307                                 z = 0;
3308                         /* some compatible mice have additional buttons */
3309                         ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN) ?
3310                             MOUSE_BUTTON4DOWN : 0;
3311                         ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN) ?
3312                             MOUSE_BUTTON5DOWN : 0;
3313                         break;
3314
3315                 case MOUSE_MODEL_MOUSEMANPLUS:
3316                         proc_mmanplus(sc, pb, &ms, &x, &y, &z);
3317                         break;
3318
3319                 case MOUSE_MODEL_GLIDEPOINT:
3320                         /* `tapping' action */
3321                         ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 :
3322                             MOUSE_BUTTON4DOWN;
3323                         break;
3324
3325                 case MOUSE_MODEL_NETSCROLL:
3326                         /*
3327                          * three addtional bytes encode buttons and
3328                          * wheel events
3329                          */
3330                         ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN) ?
3331                             MOUSE_BUTTON4DOWN : 0;
3332                         ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN) ?
3333                             MOUSE_BUTTON5DOWN : 0;
3334                         z = (pb->ipacket[3] & MOUSE_PS2_XNEG) ?
3335                             pb->ipacket[4] - 256 : pb->ipacket[4];
3336                         break;
3337
3338                 case MOUSE_MODEL_THINK:
3339                         /* the fourth button state in the first byte */
3340                         ms.button |= (c & MOUSE_PS2_TAP) ?
3341                             MOUSE_BUTTON4DOWN : 0;
3342                         break;
3343
3344                 case MOUSE_MODEL_VERSAPAD:
3345                         proc_versapad(sc, pb, &ms, &x, &y, &z);
3346                         c = ((x < 0) ? MOUSE_PS2_XNEG : 0) |
3347                             ((y < 0) ? MOUSE_PS2_YNEG : 0);
3348                         break;
3349         
3350                 case MOUSE_MODEL_4D:
3351                         /*
3352                          *          b7 b6 b5 b4 b3 b2 b1 b0
3353                          * byte 1:  s2 d2 s1 d1 1  M  R  L
3354                          * byte 2:  sx x  x  x  x  x  x  x
3355                          * byte 3:  sy y  y  y  y  y  y  y
3356                          *
3357                          * s1: wheel 1 direction
3358                          * d1: wheel 1 data
3359                          * s2: wheel 2 direction
3360                          * d2: wheel 2 data
3361                          */
3362                         x = (pb->ipacket[1] & 0x80) ?
3363                             pb->ipacket[1] - 256 : pb->ipacket[1];
3364                         y = (pb->ipacket[2] & 0x80) ?
3365                             pb->ipacket[2] - 256 : pb->ipacket[2];
3366                         switch (c & MOUSE_4D_WHEELBITS) {
3367                         case 0x10:
3368                                 z = 1;
3369                                 break;
3370                         case 0x30:
3371                                 z = -1;
3372                                 break;
3373                         case 0x40:      /* XXX 2nd wheel turning right */
3374                                 z = 2;
3375                                 break;
3376                         case 0xc0:      /* XXX 2nd wheel turning left */
3377                                 z = -2;
3378                                 break;
3379                         }
3380                         break;
3381
3382                 case MOUSE_MODEL_4DPLUS:
3383                         if ((x < 16 - 256) && (y < 16 - 256)) {
3384                                 /*
3385                                  *          b7 b6 b5 b4 b3 b2 b1 b0
3386                                  * byte 1:  0  0  1  1  1  M  R  L
3387                                  * byte 2:  0  0  0  0  1  0  0  0
3388                                  * byte 3:  0  0  0  0  S  s  d1 d0
3389                                  *
3390                                  * L, M, R, S: left, middle, right,
3391                                  *             and side buttons
3392                                  * s: wheel data sign bit
3393                                  * d1-d0: wheel data
3394                                  */
3395                                 x = y = 0;
3396                                 if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
3397                                         ms.button |= MOUSE_BUTTON4DOWN;
3398                                 z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG) ?
3399                                     ((pb->ipacket[2] & 0x07) - 8) :
3400                                     (pb->ipacket[2] & 0x07) ;
3401                         } else {
3402                                 /* preserve previous button states */
3403                                 ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
3404                         }
3405                         break;
3406
3407                 case MOUSE_MODEL_SYNAPTICS:
3408                         if (proc_synaptics(sc, pb, &ms, &x, &y, &z) != 0)
3409                                 goto next;
3410                         break;
3411
3412                 case MOUSE_MODEL_GENERIC:
3413                 default:
3414                         break;
3415                 }
3416
3417         /* scale values */
3418         if (sc->mode.accelfactor >= 1) {
3419                 if (x != 0) {
3420                         x = x * x / sc->mode.accelfactor;
3421                         if (x == 0)
3422                                 x = 1;
3423                         if (c & MOUSE_PS2_XNEG)
3424                                 x = -x;
3425                 }
3426                 if (y != 0) {
3427                         y = y * y / sc->mode.accelfactor;
3428                         if (y == 0)
3429                                 y = 1;
3430                         if (c & MOUSE_PS2_YNEG)
3431                                 y = -y;
3432                 }
3433         }
3434
3435         ms.dx = x;
3436         ms.dy = y;
3437         ms.dz = z;
3438         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0) |
3439             (ms.obutton ^ ms.button);
3440
3441         pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);
3442
3443         sc->status.flags |= ms.flags;
3444         sc->status.dx += ms.dx;
3445         sc->status.dy += ms.dy;
3446         sc->status.dz += ms.dz;
3447         sc->status.button = ms.button;
3448         sc->button = ms.button;
3449
3450 next_native:
3451         sc->watchdog = FALSE;
3452
3453         /* queue data */
3454         if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
3455                 l = imin(pb->inputbytes,
3456                     sizeof(sc->queue.buf) - sc->queue.tail);
3457                 bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
3458                 if (pb->inputbytes > l)
3459                         bcopy(&pb->ipacket[l], &sc->queue.buf[0],
3460                             pb->inputbytes - l);
3461                 sc->queue.tail = (sc->queue.tail + pb->inputbytes) %
3462                     sizeof(sc->queue.buf);
3463                 sc->queue.count += pb->inputbytes;
3464         }
3465         pb->inputbytes = 0;
3466
3467 next:
3468         if (++sc->pqueue_start >= PSM_PACKETQUEUE)
3469                 sc->pqueue_start = 0;
3470         } while (sc->pqueue_start != sc->pqueue_end);
3471
3472         if (sc->state & PSM_ASLP) {
3473                 sc->state &= ~PSM_ASLP;
3474                 wakeup(sc);
3475         }
3476         selwakeuppri(&sc->rsel, PZERO);
3477         if (sc->async != NULL) {
3478                 pgsigio(&sc->async, SIGIO, 0);
3479         }
3480         sc->state &= ~PSM_SOFTARMED;
3481         splx(s);
3482 }
3483
3484 static int
3485 psmpoll(struct cdev *dev, int events, struct thread *td)
3486 {
3487         struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
3488         int s;
3489         int revents = 0;
3490
3491         /* Return true if a mouse event available */
3492         s = spltty();
3493         if (events & (POLLIN | POLLRDNORM)) {
3494                 if (sc->queue.count > 0)
3495                         revents |= events & (POLLIN | POLLRDNORM);
3496                 else
3497                         selrecord(td, &sc->rsel);
3498         }
3499         splx(s);
3500
3501         return (revents);
3502 }
3503
3504 /* vendor/model specific routines */
3505
3506 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
3507 {
3508         if (set_mouse_resolution(kbdc, res) != res)
3509                 return (FALSE);
3510         if (set_mouse_scaling(kbdc, scale) &&
3511             set_mouse_scaling(kbdc, scale) &&
3512             set_mouse_scaling(kbdc, scale) &&
3513             (get_mouse_status(kbdc, status, 0, 3) >= 3))
3514                 return (TRUE);
3515         return (FALSE);
3516 }
3517
3518 static int
3519 mouse_ext_command(KBDC kbdc, int command)
3520 {
3521         int c;
3522
3523         c = (command >> 6) & 0x03;
3524         if (set_mouse_resolution(kbdc, c) != c)
3525                 return (FALSE);
3526         c = (command >> 4) & 0x03;
3527         if (set_mouse_resolution(kbdc, c) != c)
3528                 return (FALSE);
3529         c = (command >> 2) & 0x03;
3530         if (set_mouse_resolution(kbdc, c) != c)
3531                 return (FALSE);
3532         c = (command >> 0) & 0x03;
3533         if (set_mouse_resolution(kbdc, c) != c)
3534                 return (FALSE);
3535         return (TRUE);
3536 }
3537
3538 #ifdef notyet
3539 /* Logitech MouseMan Cordless II */
3540 static int
3541 enable_lcordless(struct psm_softc *sc)
3542 {
3543         int status[3];
3544         int ch;
3545
3546         if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
3547                 return (FALSE);
3548         if (status[1] == PSMD_RES_HIGH)
3549                 return (FALSE);
3550         ch = (status[0] & 0x07) - 1;    /* channel # */
3551         if ((ch <= 0) || (ch > 4))
3552                 return (FALSE);
3553         /*
3554          * status[1]: always one?
3555          * status[2]: battery status? (0-100)
3556          */
3557         return (TRUE);
3558 }
3559 #endif /* notyet */
3560
3561 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
3562 static int
3563 enable_groller(struct psm_softc *sc)
3564 {
3565         int status[3];
3566
3567         /*
3568          * The special sequence to enable the fourth button and the
3569          * roller. Immediately after this sequence check status bytes.
3570          * if the mouse is NetScroll, the second and the third bytes are
3571          * '3' and 'D'.
3572          */
3573
3574         /*
3575          * If the mouse is an ordinary PS/2 mouse, the status bytes should
3576          * look like the following.
3577          *
3578          * byte 1 bit 7 always 0
3579          *        bit 6 stream mode (0)
3580          *        bit 5 disabled (0)
3581          *        bit 4 1:1 scaling (0)
3582          *        bit 3 always 0
3583          *        bit 0-2 button status
3584          * byte 2 resolution (PSMD_RES_HIGH)
3585          * byte 3 report rate (?)
3586          */
3587
3588         if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
3589                 return (FALSE);
3590         if ((status[1] != '3') || (status[2] != 'D'))
3591                 return (FALSE);
3592         /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
3593         sc->hw.buttons = 4;
3594         return (TRUE);
3595 }
3596
3597 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
3598 static int
3599 enable_gmouse(struct psm_softc *sc)
3600 {
3601         int status[3];
3602
3603         /*
3604          * The special sequence to enable the middle, "rubber" button.
3605          * Immediately after this sequence check status bytes.
3606          * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
3607          * the second and the third bytes are '3' and 'U'.
3608          * NOTE: NetMouse reports that it has three buttons although it has
3609          * two buttons and a rubber button. NetMouse Pro and MIE Mouse
3610          * say they have three buttons too and they do have a button on the
3611          * side...
3612          */
3613         if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
3614                 return (FALSE);
3615         if ((status[1] != '3') || (status[2] != 'U'))
3616                 return (FALSE);
3617         return (TRUE);
3618 }
3619
3620 /* ALPS GlidePoint */
3621 static int
3622 enable_aglide(struct psm_softc *sc)
3623 {
3624         int status[3];
3625
3626         /*
3627          * The special sequence to obtain ALPS GlidePoint specific
3628          * information. Immediately after this sequence, status bytes will
3629          * contain something interesting.
3630          * NOTE: ALPS produces several models of GlidePoint. Some of those
3631          * do not respond to this sequence, thus, cannot be detected this way.
3632          */
3633         if (set_mouse_sampling_rate(sc->kbdc, 100) != 100)
3634                 return (FALSE);
3635         if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
3636                 return (FALSE);
3637         if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
3638                 return (FALSE);
3639         return (TRUE);
3640 }
3641
3642 /* Kensington ThinkingMouse/Trackball */
3643 static int
3644 enable_kmouse(struct psm_softc *sc)
3645 {
3646         static u_char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
3647         KBDC kbdc = sc->kbdc;
3648         int status[3];
3649         int id1;
3650         int id2;
3651         int i;
3652
3653         id1 = get_aux_id(kbdc);
3654         if (set_mouse_sampling_rate(kbdc, 10) != 10)
3655                 return (FALSE);
3656         /*
3657          * The device is now in the native mode? It returns a different
3658          * ID value...
3659          */
3660         id2 = get_aux_id(kbdc);
3661         if ((id1 == id2) || (id2 != 2))
3662                 return (FALSE);
3663
3664         if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
3665                 return (FALSE);
3666 #if PSM_DEBUG >= 2
3667         /* at this point, resolution is LOW, sampling rate is 10/sec */
3668         if (get_mouse_status(kbdc, status, 0, 3) < 3)
3669                 return (FALSE);
3670 #endif
3671
3672         /*
3673          * The special sequence to enable the third and fourth buttons.
3674          * Otherwise they behave like the first and second buttons.
3675          */
3676         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3677                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3678                         return (FALSE);
3679
3680         /*
3681          * At this point, the device is using default resolution and
3682          * sampling rate for the native mode.
3683          */
3684         if (get_mouse_status(kbdc, status, 0, 3) < 3)
3685                 return (FALSE);
3686         if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
3687                 return (FALSE);
3688
3689         /* the device appears be enabled by this sequence, diable it for now */
3690         disable_aux_dev(kbdc);
3691         empty_aux_buffer(kbdc, 5);
3692
3693         return (TRUE);
3694 }
3695
3696 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
3697 static int
3698 enable_mmanplus(struct psm_softc *sc)
3699 {
3700         KBDC kbdc = sc->kbdc;
3701         int data[3];
3702
3703         /* the special sequence to enable the fourth button and the roller. */
3704         /*
3705          * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
3706          * must be called exactly three times since the last RESET command
3707          * before this sequence. XXX
3708          */
3709         if (!set_mouse_scaling(kbdc, 1))
3710                 return (FALSE);
3711         if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
3712                 return (FALSE);
3713         if (get_mouse_status(kbdc, data, 1, 3) < 3)
3714                 return (FALSE);
3715
3716         /*
3717          * PS2++ protocl, packet type 0
3718          *
3719          *          b7 b6 b5 b4 b3 b2 b1 b0
3720          * byte 1:  *  1  p3 p2 1  *  *  *
3721          * byte 2:  1  1  p1 p0 m1 m0 1  0
3722          * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
3723          *
3724          * p3-p0: packet type: 0
3725          * m7-m0: model ID: MouseMan+:0x50,
3726          *                  FirstMouse+:0x51,
3727          *                  ScrollPoint:0x58...
3728          */
3729         /* check constant bits */
3730         if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
3731                 return (FALSE);
3732         if ((data[1] & 0xc3) != 0xc2)
3733                 return (FALSE);
3734         /* check d3-d0 in byte 2 */
3735         if (!MOUSE_PS2PLUS_CHECKBITS(data))
3736                 return (FALSE);
3737         /* check p3-p0 */
3738         if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
3739                 return (FALSE);
3740
3741         sc->hw.hwid &= 0x00ff;
3742         sc->hw.hwid |= data[2] << 8;    /* save model ID */
3743
3744         /*
3745          * MouseMan+ (or FirstMouse+) is now in its native mode, in which
3746          * the wheel and the fourth button events are encoded in the
3747          * special data packet. The mouse may be put in the IntelliMouse mode
3748          * if it is initialized by the IntelliMouse's method.
3749          */
3750         return (TRUE);
3751 }
3752
3753 /* MS IntelliMouse Explorer */
3754 static int
3755 enable_msexplorer(struct psm_softc *sc)
3756 {
3757         static u_char rate0[] = { 200, 100, 80, };
3758         static u_char rate1[] = { 200, 200, 80, };
3759         KBDC kbdc = sc->kbdc;
3760         int id;
3761         int i;
3762
3763         /*
3764          * This is needed for at least A4Tech X-7xx mice - they do not go
3765          * straight to Explorer mode, but need to be set to Intelli mode
3766          * first.
3767          */
3768         enable_msintelli(sc);
3769
3770         /* the special sequence to enable the extra buttons and the roller. */
3771         for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i)
3772                 if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
3773                         return (FALSE);
3774         /* the device will give the genuine ID only after the above sequence */
3775         id = get_aux_id(kbdc);
3776         if (id != PSM_EXPLORER_ID)
3777                 return (FALSE);
3778
3779         sc->hw.hwid = id;
3780         sc->hw.buttons = 5;             /* IntelliMouse Explorer XXX */
3781
3782         /*
3783          * XXX: this is a kludge to fool some KVM switch products
3784          * which think they are clever enough to know the 4-byte IntelliMouse
3785          * protocol, and assume any other protocols use 3-byte packets.
3786          * They don't convey 4-byte data packets from the IntelliMouse Explorer
3787          * correctly to the host computer because of this!
3788          * The following sequence is actually IntelliMouse's "wake up"
3789          * sequence; it will make the KVM think the mouse is IntelliMouse
3790          * when it is in fact IntelliMouse Explorer.
3791          */
3792         for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i)
3793                 if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
3794                         break;
3795         id = get_aux_id(kbdc);
3796
3797         return (TRUE);
3798 }
3799
3800 /* MS IntelliMouse */
3801 static int
3802 enable_msintelli(struct psm_softc *sc)
3803 {
3804         /*
3805          * Logitech MouseMan+ and FirstMouse+ will also respond to this
3806          * probe routine and act like IntelliMouse.
3807          */
3808
3809         static u_char rate[] = { 200, 100, 80, };
3810         KBDC kbdc = sc->kbdc;
3811         int id;
3812         int i;
3813
3814         /* the special sequence to enable the third button and the roller. */
3815         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3816                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3817                         return (FALSE);
3818         /* the device will give the genuine ID only after the above sequence */
3819         id = get_aux_id(kbdc);
3820         if (id != PSM_INTELLI_ID)
3821                 return (FALSE);
3822
3823         sc->hw.hwid = id;
3824         sc->hw.buttons = 3;
3825
3826         return (TRUE);
3827 }
3828
3829 /* A4 Tech 4D Mouse */
3830 static int
3831 enable_4dmouse(struct psm_softc *sc)
3832 {
3833         /*
3834          * Newer wheel mice from A4 Tech may use the 4D+ protocol.
3835          */
3836
3837         static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
3838         KBDC kbdc = sc->kbdc;
3839         int id;
3840         int i;
3841
3842         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3843                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3844                         return (FALSE);
3845         id = get_aux_id(kbdc);
3846         /*
3847          * WinEasy 4D, 4 Way Scroll 4D: 6
3848          * Cable-Free 4D: 8 (4DPLUS)
3849          * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
3850          */
3851         if (id != PSM_4DMOUSE_ID)
3852                 return (FALSE);
3853
3854         sc->hw.hwid = id;
3855         sc->hw.buttons = 3;             /* XXX some 4D mice have 4? */
3856
3857         return (TRUE);
3858 }
3859
3860 /* A4 Tech 4D+ Mouse */
3861 static int
3862 enable_4dplus(struct psm_softc *sc)
3863 {
3864         /*
3865          * Newer wheel mice from A4 Tech seem to use this protocol.
3866          * Older models are recognized as either 4D Mouse or IntelliMouse.
3867          */
3868         KBDC kbdc = sc->kbdc;
3869         int id;
3870
3871         /*
3872          * enable_4dmouse() already issued the following ID sequence...
3873         static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
3874         int i;
3875
3876         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3877                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3878                         return (FALSE);
3879         */
3880
3881         id = get_aux_id(kbdc);
3882         switch (id) {
3883         case PSM_4DPLUS_ID:
3884                 sc->hw.buttons = 4;
3885                 break;
3886         case PSM_4DPLUS_RFSW35_ID:
3887                 sc->hw.buttons = 3;
3888                 break;
3889         default:
3890                 return (FALSE);
3891         }
3892
3893         sc->hw.hwid = id;
3894
3895         return (TRUE);
3896 }
3897
3898 /* Synaptics Touchpad */
3899 static int
3900 synaptics_sysctl(SYSCTL_HANDLER_ARGS)
3901 {
3902         int error, arg;
3903
3904         /* Read the current value. */
3905         arg = *(int *)oidp->oid_arg1;
3906         error = sysctl_handle_int(oidp, &arg, 0, req);
3907
3908         /* Sanity check. */
3909         if (error || !req->newptr)
3910                 return (error);
3911
3912         /*
3913          * Check that the new value is in the concerned node's range
3914          * of values.
3915          */
3916         switch (oidp->oid_arg2) {
3917         case SYNAPTICS_SYSCTL_MIN_PRESSURE:
3918         case SYNAPTICS_SYSCTL_MAX_PRESSURE:
3919                 if (arg < 0 || arg > 255)
3920                         return (EINVAL);
3921                 break;
3922         case SYNAPTICS_SYSCTL_MAX_WIDTH:
3923                 if (arg < 4 || arg > 15)
3924                         return (EINVAL);
3925                 break;
3926         case SYNAPTICS_SYSCTL_MARGIN_TOP:
3927         case SYNAPTICS_SYSCTL_MARGIN_RIGHT:
3928         case SYNAPTICS_SYSCTL_MARGIN_BOTTOM:
3929         case SYNAPTICS_SYSCTL_MARGIN_LEFT:
3930         case SYNAPTICS_SYSCTL_NA_TOP:
3931         case SYNAPTICS_SYSCTL_NA_RIGHT:
3932         case SYNAPTICS_SYSCTL_NA_BOTTOM:
3933         case SYNAPTICS_SYSCTL_NA_LEFT:
3934                 if (arg < 0 || arg > 6143)
3935                         return (EINVAL);
3936                 break;
3937         case SYNAPTICS_SYSCTL_WINDOW_MIN:
3938         case SYNAPTICS_SYSCTL_WINDOW_MAX:
3939         case SYNAPTICS_SYSCTL_TAP_MIN_QUEUE:
3940                 if (arg < 1 || arg > SYNAPTICS_PACKETQUEUE)
3941                         return (EINVAL);
3942                 break;
3943         case SYNAPTICS_SYSCTL_MULTIPLICATOR:
3944         case SYNAPTICS_SYSCTL_WEIGHT_CURRENT:
3945         case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS:
3946         case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA:
3947         case SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED:
3948         case SYNAPTICS_SYSCTL_DIV_MIN:
3949         case SYNAPTICS_SYSCTL_DIV_MAX:
3950         case SYNAPTICS_SYSCTL_DIV_MAX_NA:
3951         case SYNAPTICS_SYSCTL_DIV_LEN:
3952         case SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN:
3953         case SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX:
3954                 if (arg < 1)
3955                         return (EINVAL);
3956                 break;
3957         case SYNAPTICS_SYSCTL_TAP_MAX_DELTA:
3958         case SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT:
3959         case SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA:
3960                 if (arg < 0)
3961                         return (EINVAL);
3962                 break;
3963         case SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA:
3964         case SYNAPTICS_SYSCTL_VSCROLL_VER_AREA:
3965                 if (arg < -6143 || arg > 6143)
3966                         return (EINVAL);
3967                 break;
3968         default:
3969                 return (EINVAL);
3970         }
3971
3972         /* Update. */
3973         *(int *)oidp->oid_arg1 = arg;
3974
3975         return (error);
3976 }
3977
3978 static void
3979 synaptics_sysctl_create_tree(struct psm_softc *sc)
3980 {
3981
3982         if (sc->syninfo.sysctl_tree != NULL)
3983                 return;
3984
3985         /* Attach extra synaptics sysctl nodes under hw.psm.synaptics */
3986         sysctl_ctx_init(&sc->syninfo.sysctl_ctx);
3987         sc->syninfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->syninfo.sysctl_ctx,
3988             SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "synaptics", CTLFLAG_RD,
3989             0, "Synaptics TouchPad");
3990
3991         /* hw.psm.synaptics.directional_scrolls. */
3992         sc->syninfo.directional_scrolls = 1;
3993         SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3994             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
3995             "directional_scrolls", CTLFLAG_RW|CTLFLAG_ANYBODY,
3996             &sc->syninfo.directional_scrolls, 0,
3997             "Enable hardware scrolling pad (if non-zero) or register it as "
3998             "a middle-click (if 0)");
3999
4000         /* hw.psm.synaptics.min_pressure. */
4001         sc->syninfo.min_pressure = 16;
4002         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4003             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4004             "min_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4005             &sc->syninfo.min_pressure, SYNAPTICS_SYSCTL_MIN_PRESSURE,
4006             synaptics_sysctl, "I",
4007             "Minimum pressure required to start an action");
4008
4009         /* hw.psm.synaptics.max_pressure. */
4010         sc->syninfo.max_pressure = 220;
4011         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4012             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4013             "max_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4014             &sc->syninfo.max_pressure, SYNAPTICS_SYSCTL_MAX_PRESSURE,
4015             synaptics_sysctl, "I",
4016             "Maximum pressure to detect palm");
4017
4018         /* hw.psm.synaptics.max_width. */
4019         sc->syninfo.max_width = 10;
4020         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4021             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4022             "max_width", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4023             &sc->syninfo.max_width, SYNAPTICS_SYSCTL_MAX_WIDTH,
4024             synaptics_sysctl, "I",
4025             "Maximum finger width to detect palm");
4026
4027         /* hw.psm.synaptics.top_margin. */
4028         sc->syninfo.margin_top = 200;
4029         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4030             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4031             "margin_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4032             &sc->syninfo.margin_top, SYNAPTICS_SYSCTL_MARGIN_TOP,
4033             synaptics_sysctl, "I",
4034             "Top margin");
4035
4036         /* hw.psm.synaptics.right_margin. */
4037         sc->syninfo.margin_right = 200;
4038         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4039             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4040             "margin_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4041             &sc->syninfo.margin_right, SYNAPTICS_SYSCTL_MARGIN_RIGHT,
4042             synaptics_sysctl, "I",
4043             "Right margin");
4044
4045         /* hw.psm.synaptics.bottom_margin. */
4046         sc->syninfo.margin_bottom = 200;
4047         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4048             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4049             "margin_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4050             &sc->syninfo.margin_bottom, SYNAPTICS_SYSCTL_MARGIN_BOTTOM,
4051             synaptics_sysctl, "I",
4052             "Bottom margin");
4053
4054         /* hw.psm.synaptics.left_margin. */
4055         sc->syninfo.margin_left = 200;
4056         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4057             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4058             "margin_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4059             &sc->syninfo.margin_left, SYNAPTICS_SYSCTL_MARGIN_LEFT,
4060             synaptics_sysctl, "I",
4061             "Left margin");
4062
4063         /* hw.psm.synaptics.na_top. */
4064         sc->syninfo.na_top = 1783;
4065         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4066             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4067             "na_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4068             &sc->syninfo.na_top, SYNAPTICS_SYSCTL_NA_TOP,
4069             synaptics_sysctl, "I",
4070             "Top noisy area, where weight_previous_na is used instead "
4071             "of weight_previous");
4072
4073         /* hw.psm.synaptics.na_right. */
4074         sc->syninfo.na_right = 563;
4075         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4076             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4077             "na_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4078             &sc->syninfo.na_right, SYNAPTICS_SYSCTL_NA_RIGHT,
4079             synaptics_sysctl, "I",
4080             "Right noisy area, where weight_previous_na is used instead "
4081             "of weight_previous");
4082
4083         /* hw.psm.synaptics.na_bottom. */
4084         sc->syninfo.na_bottom = 1408;
4085         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4086             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4087             "na_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4088             &sc->syninfo.na_bottom, SYNAPTICS_SYSCTL_NA_BOTTOM,
4089             synaptics_sysctl, "I",
4090             "Bottom noisy area, where weight_previous_na is used instead "
4091             "of weight_previous");
4092
4093         /* hw.psm.synaptics.na_left. */
4094         sc->syninfo.na_left = 1600;
4095         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4096             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4097             "na_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4098             &sc->syninfo.na_left, SYNAPTICS_SYSCTL_NA_LEFT,
4099             synaptics_sysctl, "I",
4100             "Left noisy area, where weight_previous_na is used instead "
4101             "of weight_previous");
4102
4103         /* hw.psm.synaptics.window_min. */
4104         sc->syninfo.window_min = 4;
4105         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4106             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4107             "window_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4108             &sc->syninfo.window_min, SYNAPTICS_SYSCTL_WINDOW_MIN,
4109             synaptics_sysctl, "I",
4110             "Minimum window size to start an action");
4111
4112         /* hw.psm.synaptics.window_max. */
4113         sc->syninfo.window_max = 10;
4114         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4115             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4116             "window_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4117             &sc->syninfo.window_max, SYNAPTICS_SYSCTL_WINDOW_MAX,
4118             synaptics_sysctl, "I",
4119             "Maximum window size");
4120
4121         /* hw.psm.synaptics.multiplicator. */
4122         sc->syninfo.multiplicator = 10000;
4123         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4124             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4125             "multiplicator", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4126             &sc->syninfo.multiplicator, SYNAPTICS_SYSCTL_MULTIPLICATOR,
4127             synaptics_sysctl, "I",
4128             "Multiplicator to increase precision in averages and divisions");
4129
4130         /* hw.psm.synaptics.weight_current. */
4131         sc->syninfo.weight_current = 3;
4132         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4133             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4134             "weight_current", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4135             &sc->syninfo.weight_current, SYNAPTICS_SYSCTL_WEIGHT_CURRENT,
4136             synaptics_sysctl, "I",
4137             "Weight of the current movement in the new average");
4138
4139         /* hw.psm.synaptics.weight_previous. */
4140         sc->syninfo.weight_previous = 6;
4141         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4142             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4143             "weight_previous", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4144             &sc->syninfo.weight_previous, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS,
4145             synaptics_sysctl, "I",
4146             "Weight of the previous average");
4147
4148         /* hw.psm.synaptics.weight_previous_na. */
4149         sc->syninfo.weight_previous_na = 20;
4150         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4151             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4152             "weight_previous_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4153             &sc->syninfo.weight_previous_na,
4154             SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA,
4155             synaptics_sysctl, "I",
4156             "Weight of the previous average (inside the noisy area)");
4157
4158         /* hw.psm.synaptics.weight_len_squared. */
4159         sc->syninfo.weight_len_squared = 2000;
4160         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4161             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4162             "weight_len_squared", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4163             &sc->syninfo.weight_len_squared,
4164             SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED,
4165             synaptics_sysctl, "I",
4166             "Length (squared) of segments where weight_previous "
4167             "starts to decrease");
4168
4169         /* hw.psm.synaptics.div_min. */
4170         sc->syninfo.div_min = 9;
4171         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4172             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4173             "div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4174             &sc->syninfo.div_min, SYNAPTICS_SYSCTL_DIV_MIN,
4175             synaptics_sysctl, "I",
4176             "Divisor for fast movements");
4177
4178         /* hw.psm.synaptics.div_max. */
4179         sc->syninfo.div_max = 17;
4180         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4181             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4182             "div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4183             &sc->syninfo.div_max, SYNAPTICS_SYSCTL_DIV_MAX,
4184             synaptics_sysctl, "I",
4185             "Divisor for slow movements");
4186
4187         /* hw.psm.synaptics.div_max_na. */
4188         sc->syninfo.div_max_na = 30;
4189         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4190             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4191             "div_max_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4192             &sc->syninfo.div_max_na, SYNAPTICS_SYSCTL_DIV_MAX_NA,
4193             synaptics_sysctl, "I",
4194             "Divisor with slow movements (inside the noisy area)");
4195
4196         /* hw.psm.synaptics.div_len. */
4197         sc->syninfo.div_len = 100;
4198         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4199             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4200             "div_len", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4201             &sc->syninfo.div_len, SYNAPTICS_SYSCTL_DIV_LEN,
4202             synaptics_sysctl, "I",
4203             "Length of segments where div_max starts to decrease");
4204
4205         /* hw.psm.synaptics.tap_max_delta. */
4206         sc->syninfo.tap_max_delta = 80;
4207         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4208             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4209             "tap_max_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4210             &sc->syninfo.tap_max_delta, SYNAPTICS_SYSCTL_TAP_MAX_DELTA,
4211             synaptics_sysctl, "I",
4212             "Length of segments above which a tap is ignored");
4213
4214         /* hw.psm.synaptics.tap_min_queue. */
4215         sc->syninfo.tap_min_queue = 2;
4216         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4217             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4218             "tap_min_queue", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4219             &sc->syninfo.tap_min_queue, SYNAPTICS_SYSCTL_TAP_MIN_QUEUE,
4220             synaptics_sysctl, "I",
4221             "Number of packets required to consider a tap");
4222
4223         /* hw.psm.synaptics.taphold_timeout. */
4224         sc->synaction.in_taphold = 0;
4225         sc->syninfo.taphold_timeout = tap_timeout;
4226         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4227             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4228             "taphold_timeout", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4229             &sc->syninfo.taphold_timeout, SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT,
4230             synaptics_sysctl, "I",
4231             "Maximum elapsed time between two taps to consider a tap-hold "
4232             "action");
4233
4234         /* hw.psm.synaptics.vscroll_hor_area. */
4235         sc->syninfo.vscroll_hor_area = 0; /* 1300 */
4236         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4237             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4238             "vscroll_hor_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4239             &sc->syninfo.vscroll_hor_area, SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA,
4240             synaptics_sysctl, "I",
4241             "Area reserved for horizontal virtual scrolling");
4242
4243         /* hw.psm.synaptics.vscroll_ver_area. */
4244         sc->syninfo.vscroll_ver_area = -600;
4245         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4246             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4247             "vscroll_ver_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4248             &sc->syninfo.vscroll_ver_area, SYNAPTICS_SYSCTL_VSCROLL_VER_AREA,
4249             synaptics_sysctl, "I",
4250             "Area reserved for vertical virtual scrolling");
4251
4252         /* hw.psm.synaptics.vscroll_min_delta. */
4253         sc->syninfo.vscroll_min_delta = 50;
4254         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4255             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4256             "vscroll_min_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4257             &sc->syninfo.vscroll_min_delta,
4258             SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA,
4259             synaptics_sysctl, "I",
4260             "Minimum movement to consider virtual scrolling");
4261
4262         /* hw.psm.synaptics.vscroll_div_min. */
4263         sc->syninfo.vscroll_div_min = 100;
4264         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4265             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4266             "vscroll_div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4267             &sc->syninfo.vscroll_div_min, SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN,
4268             synaptics_sysctl, "I",
4269             "Divisor for fast scrolling");
4270
4271         /* hw.psm.synaptics.vscroll_div_min. */
4272         sc->syninfo.vscroll_div_max = 150;
4273         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4274             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4275             "vscroll_div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4276             &sc->syninfo.vscroll_div_max, SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX,
4277             synaptics_sysctl, "I",
4278             "Divisor for slow scrolling");
4279 }
4280
4281 static int
4282 enable_synaptics(struct psm_softc *sc)
4283 {
4284         int status[3];
4285         KBDC kbdc;
4286
4287         if (!synaptics_support)
4288                 return (FALSE);
4289
4290         kbdc = sc->kbdc;
4291         VLOG(3, (LOG_DEBUG, "synaptics: BEGIN init\n"));
4292         sc->hw.buttons = 3;
4293         sc->squelch = 0;
4294
4295         /*
4296          * Just to be on the safe side: this avoids troubles with
4297          * following mouse_ext_command() when the previous command
4298          * was PSMC_SET_RESOLUTION. Set Scaling has no effect on
4299          * Synaptics Touchpad behaviour.
4300          */
4301         set_mouse_scaling(kbdc, 1);
4302
4303         /* Identify the Touchpad version. */
4304         if (mouse_ext_command(kbdc, 0) == 0)
4305                 return (FALSE);
4306         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4307                 return (FALSE);
4308         if (status[1] != 0x47)
4309                 return (FALSE);
4310
4311         sc->synhw.infoMinor = status[0];
4312         sc->synhw.infoMajor = status[2] & 0x0f;
4313
4314         if (verbose >= 2)
4315                 printf("Synaptics Touchpad v%d.%d\n", sc->synhw.infoMajor,
4316                     sc->synhw.infoMinor);
4317
4318         if (sc->synhw.infoMajor < 4) {
4319                 printf("  Unsupported (pre-v4) Touchpad detected\n");
4320                 return (FALSE);
4321         }
4322
4323         /* Get the Touchpad model information. */
4324         if (mouse_ext_command(kbdc, 3) == 0)
4325                 return (FALSE);
4326         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4327                 return (FALSE);
4328         if ((status[1] & 0x01) != 0) {
4329                 printf("  Failed to read model information\n");
4330                 return (FALSE);
4331         }
4332
4333         sc->synhw.infoRot180   = (status[0] & 0x80) >> 7;
4334         sc->synhw.infoPortrait = (status[0] & 0x40) >> 6;
4335         sc->synhw.infoSensor   =  status[0] & 0x3f;
4336         sc->synhw.infoHardware = (status[1] & 0xfe) >> 1;
4337         sc->synhw.infoNewAbs   = (status[2] & 0x80) >> 7;
4338         sc->synhw.capPen       = (status[2] & 0x40) >> 6;
4339         sc->synhw.infoSimplC   = (status[2] & 0x20) >> 5;
4340         sc->synhw.infoGeometry =  status[2] & 0x0f;
4341
4342         if (verbose >= 2) {
4343                 printf("  Model information:\n");
4344                 printf("   infoRot180: %d\n", sc->synhw.infoRot180);
4345                 printf("   infoPortrait: %d\n", sc->synhw.infoPortrait);
4346                 printf("   infoSensor: %d\n", sc->synhw.infoSensor);
4347                 printf("   infoHardware: %d\n", sc->synhw.infoHardware);
4348                 printf("   infoNewAbs: %d\n", sc->synhw.infoNewAbs);
4349                 printf("   capPen: %d\n", sc->synhw.capPen);
4350                 printf("   infoSimplC: %d\n", sc->synhw.infoSimplC);
4351                 printf("   infoGeometry: %d\n", sc->synhw.infoGeometry);
4352         }
4353
4354         /* Read the extended capability bits. */
4355         if (mouse_ext_command(kbdc, 2) == 0)
4356                 return (FALSE);
4357         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4358                 return (FALSE);
4359         if (status[1] != 0x47) {
4360                 printf("  Failed to read extended capability bits\n");
4361                 return (FALSE);
4362         }
4363
4364         /* Set the different capabilities when they exist. */
4365         if ((status[0] & 0x80) >> 7) {
4366                 sc->synhw.capExtended    = (status[0] & 0x80) >> 7;
4367                 sc->synhw.capPassthrough = (status[2] & 0x80) >> 7;
4368                 sc->synhw.capSleep       = (status[2] & 0x10) >> 4;
4369                 sc->synhw.capFourButtons = (status[2] & 0x08) >> 3;
4370                 sc->synhw.capMultiFinger = (status[2] & 0x02) >> 1;
4371                 sc->synhw.capPalmDetect  = (status[2] & 0x01);
4372
4373                 if (verbose >= 2) {
4374                         printf("  Extended capabilities:\n");
4375                         printf("   capExtended: %d\n", sc->synhw.capExtended);
4376                         printf("   capPassthrough: %d\n",
4377                             sc->synhw.capPassthrough);
4378                         printf("   capSleep: %d\n", sc->synhw.capSleep);
4379                         printf("   capFourButtons: %d\n",
4380                             sc->synhw.capFourButtons);
4381                         printf("   capMultiFinger: %d\n",
4382                             sc->synhw.capMultiFinger);
4383                         printf("   capPalmDetect: %d\n",
4384                             sc->synhw.capPalmDetect);
4385                 }
4386
4387                 /*
4388                  * If we have bits set in status[0] & 0x70, then we can load
4389                  * more information about buttons using query 0x09.
4390                  */
4391                 if (status[0] & 0x70) {
4392                         if (mouse_ext_command(kbdc, 0x09) == 0)
4393                                 return (FALSE);
4394                         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4395                                 return (FALSE);
4396                         sc->hw.buttons = ((status[1] & 0xf0) >> 4) + 3;
4397                         if (verbose >= 2)
4398                                 printf("  Additional Buttons: %d\n",
4399                                     sc->hw.buttons -3);
4400                 }
4401         } else {
4402                 sc->synhw.capExtended = 0;
4403
4404                 if (verbose >= 2)
4405                         printf("  No extended capabilities\n");
4406         }
4407
4408         /*
4409          * Read the mode byte.
4410          *
4411          * XXX: Note the Synaptics documentation also defines the first
4412          * byte of the response to this query to be a constant 0x3b, this
4413          * does not appear to be true for Touchpads with guest devices.
4414          */
4415         if (mouse_ext_command(kbdc, 1) == 0)
4416                 return (FALSE);
4417         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4418                 return (FALSE);
4419         if (status[1] != 0x47) {
4420                 printf("  Failed to read mode byte\n");
4421                 return (FALSE);
4422         }
4423
4424         /* Set the mode byte; request wmode where available. */
4425         if (sc->synhw.capExtended)
4426                 mouse_ext_command(kbdc, 0xc1);
4427         else
4428                 mouse_ext_command(kbdc, 0xc0);
4429
4430         /* "Commit" the Set Mode Byte command sent above. */
4431         set_mouse_sampling_rate(kbdc, 20);
4432
4433         /*
4434          * Report the correct number of buttons
4435          *
4436          * XXX: I'm not sure this is used anywhere.
4437          */
4438         if (sc->synhw.capExtended && sc->synhw.capFourButtons)
4439                 sc->hw.buttons = 4;
4440
4441         VLOG(3, (LOG_DEBUG, "synaptics: END init (%d buttons)\n",
4442             sc->hw.buttons));
4443
4444         /* Create sysctl tree. */
4445         synaptics_sysctl_create_tree(sc);
4446
4447         /*
4448          * The touchpad will have to be reinitialized after
4449          * suspend/resume.
4450          */
4451         sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
4452
4453         return (TRUE);
4454 }
4455
4456 /* Interlink electronics VersaPad */
4457 static int
4458 enable_versapad(struct psm_softc *sc)
4459 {
4460         KBDC kbdc = sc->kbdc;
4461         int data[3];
4462
4463         set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
4464         set_mouse_sampling_rate(kbdc, 100);             /* set rate 100 */
4465         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4466         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4467         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4468         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4469         if (get_mouse_status(kbdc, data, 0, 3) < 3)     /* get status */
4470                 return (FALSE);
4471         if (data[2] != 0xa || data[1] != 0 )    /* rate == 0xa && res. == 0 */
4472                 return (FALSE);
4473         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4474
4475         sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
4476
4477         return (TRUE);                          /* PS/2 absolute mode */
4478 }
4479
4480 /*
4481  * Return true if 'now' is earlier than (start + (secs.usecs)).
4482  * Now may be NULL and the function will fetch the current time from
4483  * getmicrouptime(), or a cached 'now' can be passed in.
4484  * All values should be numbers derived from getmicrouptime().
4485  */
4486 static int
4487 timeelapsed(start, secs, usecs, now)
4488         const struct timeval *start, *now;
4489         int secs, usecs;
4490 {
4491         struct timeval snow, tv;
4492
4493         /* if there is no 'now' passed in, the get it as a convience. */
4494         if (now == NULL) {
4495                 getmicrouptime(&snow);
4496                 now = &snow;
4497         }
4498
4499         tv.tv_sec = secs;
4500         tv.tv_usec = usecs;
4501         timevaladd(&tv, start);
4502         return (timevalcmp(&tv, now, <));
4503 }
4504
4505 static int
4506 psmresume(device_t dev)
4507 {
4508         struct psm_softc *sc = device_get_softc(dev);
4509         int unit = device_get_unit(dev);
4510         int err;
4511
4512         VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit));
4513
4514         if (!(sc->config & PSM_CONFIG_HOOKRESUME))
4515                 return (0);
4516
4517         err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
4518
4519         if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
4520                 /*
4521                  * Release the blocked process; it must be notified that
4522                  * the device cannot be accessed anymore.
4523                  */
4524                 sc->state &= ~PSM_ASLP;
4525                 wakeup(sc);
4526         }
4527
4528         VLOG(2, (LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit));
4529
4530         return (err);
4531 }
4532
4533 DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
4534
4535 #ifdef DEV_ISA
4536
4537 /*
4538  * This sucks up assignments from PNPBIOS and ACPI.
4539  */
4540
4541 /*
4542  * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
4543  * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
4544  * can be probed and attached only after the AT keyboard controller is
4545  * attached, we shall quietly reserve the IRQ resource for later use.
4546  * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
4547  * copy the IRQ resource to the PS/2 mouse device instance hanging
4548  * under the keyboard controller, then probe and attach it.
4549  */
4550
4551 static  devclass_t                      psmcpnp_devclass;
4552
4553 static  device_probe_t                  psmcpnp_probe;
4554 static  device_attach_t                 psmcpnp_attach;
4555
4556 static device_method_t psmcpnp_methods[] = {
4557         DEVMETHOD(device_probe,         psmcpnp_probe),
4558         DEVMETHOD(device_attach,        psmcpnp_attach),
4559
4560         { 0, 0 }
4561 };
4562
4563 static driver_t psmcpnp_driver = {
4564         PSMCPNP_DRIVER_NAME,
4565         psmcpnp_methods,
4566         1,                      /* no softc */
4567 };
4568
4569 static struct isa_pnp_id psmcpnp_ids[] = {
4570         { 0x030fd041, "PS/2 mouse port" },              /* PNP0F03 */
4571         { 0x0e0fd041, "PS/2 mouse port" },              /* PNP0F0E */
4572         { 0x120fd041, "PS/2 mouse port" },              /* PNP0F12 */
4573         { 0x130fd041, "PS/2 mouse port" },              /* PNP0F13 */
4574         { 0x1303d041, "PS/2 port" },                    /* PNP0313, XXX */
4575         { 0x02002e4f, "Dell PS/2 mouse port" },         /* Lat. X200, Dell */
4576         { 0x0002a906, "ALPS Glide Point" },             /* ALPS Glide Point */
4577         { 0x80374d24, "IBM PS/2 mouse port" },          /* IBM3780, ThinkPad */
4578         { 0x81374d24, "IBM PS/2 mouse port" },          /* IBM3781, ThinkPad */
4579         { 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
4580         { 0x0290d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9002, Vaio */
4581         { 0x0390d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9003, Vaio */
4582         { 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
4583         { 0 }
4584 };
4585
4586 static int
4587 create_a_copy(device_t atkbdc, device_t me)
4588 {
4589         device_t psm;
4590         u_long irq;
4591
4592         /* find the PS/2 mouse device instance under the keyboard controller */
4593         psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
4594             device_get_unit(atkbdc));
4595         if (psm == NULL)
4596                 return (ENXIO);
4597         if (device_get_state(psm) != DS_NOTPRESENT)
4598                 return (0);
4599
4600         /* move our resource to the found device */
4601         irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
4602         bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
4603
4604         /* ...then probe and attach it */
4605         return (device_probe_and_attach(psm));
4606 }
4607
4608 static int
4609 psmcpnp_probe(device_t dev)
4610 {
4611         struct resource *res;
4612         u_long irq;
4613         int rid;
4614
4615         if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids))
4616                 return (ENXIO);
4617
4618         /*
4619          * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
4620          * to the PS/2 mouse device node. But, some buggy PnP BIOS
4621          * declares the PS/2 mouse device node without an IRQ resource!
4622          * If this happens, we shall refer to device hints.
4623          * If we still don't find it there, use a hardcoded value... XXX
4624          */
4625         rid = 0;
4626         irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
4627         if (irq <= 0) {
4628                 if (resource_long_value(PSM_DRIVER_NAME,
4629                     device_get_unit(dev),"irq", &irq) != 0)
4630                         irq = 12;       /* XXX */
4631                 device_printf(dev, "irq resource info is missing; "
4632                     "assuming irq %ld\n", irq);
4633                 bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
4634         }
4635         res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_SHAREABLE);
4636         bus_release_resource(dev, SYS_RES_IRQ, rid, res);
4637
4638         /* keep quiet */
4639         if (!bootverbose)
4640                 device_quiet(dev);
4641
4642         return ((res == NULL) ? ENXIO : 0);
4643 }
4644
4645 static int
4646 psmcpnp_attach(device_t dev)
4647 {
4648         device_t atkbdc;
4649         int rid;
4650
4651         /* find the keyboard controller, which may be on acpi* or isa* bus */
4652         atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
4653             device_get_unit(dev));
4654         if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED))
4655                 create_a_copy(atkbdc, dev);
4656         else {
4657                 /*
4658                  * If we don't have the AT keyboard controller yet,
4659                  * just reserve the IRQ for later use...
4660                  * (See psmidentify() above.)
4661                  */
4662                 rid = 0;
4663                 bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_SHAREABLE);
4664         }
4665
4666         return (0);
4667 }
4668
4669 DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
4670 DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
4671
4672 #endif /* DEV_ISA */