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