]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/atkbdc/psm.c
Upgrade to version 3.1.4
[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 #include "opt_evdev.h"
67
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/kernel.h>
71 #include <sys/module.h>
72 #include <sys/bus.h>
73 #include <sys/conf.h>
74 #include <sys/filio.h>
75 #include <sys/mutex.h>
76 #include <sys/poll.h>
77 #include <sys/sigio.h>
78 #include <sys/signalvar.h>
79 #include <sys/syslog.h>
80 #include <machine/bus.h>
81 #include <sys/rman.h>
82 #include <sys/selinfo.h>
83 #include <sys/sysctl.h>
84 #include <sys/time.h>
85 #include <sys/uio.h>
86
87 #include <sys/limits.h>
88 #include <sys/mouse.h>
89 #include <machine/resource.h>
90
91 #ifdef DEV_ISA
92 #include <isa/isavar.h>
93 #endif
94
95 #ifdef EVDEV_SUPPORT
96 #include <dev/evdev/evdev.h>
97 #include <dev/evdev/input.h>
98 #endif
99
100 #include <dev/atkbdc/atkbdcreg.h>
101 #include <dev/atkbdc/psm.h>
102
103 /*
104  * Driver specific options: the following options may be set by
105  * `options' statements in the kernel configuration file.
106  */
107
108 /* debugging */
109 #ifndef PSM_DEBUG
110 #define PSM_DEBUG       0       /*
111                                  * logging: 0: none, 1: brief, 2: verbose
112                                  *          3: sync errors, 4: all packets
113                                  */
114 #endif
115 #define VLOG(level, args)       do {    \
116         if (verbose >= level)           \
117                 log args;               \
118 } while (0)
119
120 #ifndef PSM_INPUT_TIMEOUT
121 #define PSM_INPUT_TIMEOUT       2000000 /* 2 sec */
122 #endif
123
124 #ifndef PSM_TAP_TIMEOUT
125 #define PSM_TAP_TIMEOUT         125000
126 #endif
127
128 #ifndef PSM_TAP_THRESHOLD
129 #define PSM_TAP_THRESHOLD       25
130 #endif
131
132 /* end of driver specific options */
133
134 #define PSMCPNP_DRIVER_NAME     "psmcpnp"
135
136 struct psmcpnp_softc {
137         enum {
138                 PSMCPNP_GENERIC,
139                 PSMCPNP_FORCEPAD,
140                 PSMCPNP_TOPBUTTONPAD,
141         } type;         /* Based on PnP ID */
142 };
143
144 /* input queue */
145 #define PSM_BUFSIZE             960
146 #define PSM_SMALLBUFSIZE        240
147
148 /* operation levels */
149 #define PSM_LEVEL_BASE          0
150 #define PSM_LEVEL_STANDARD      1
151 #define PSM_LEVEL_NATIVE        2
152 #define PSM_LEVEL_MIN           PSM_LEVEL_BASE
153 #define PSM_LEVEL_MAX           PSM_LEVEL_NATIVE
154
155 /* Active PS/2 multiplexing */
156 #define PSM_NOMUX               (-1)
157
158 /* Logitech PS2++ protocol */
159 #define MOUSE_PS2PLUS_CHECKBITS(b)      \
160     ((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
161 #define MOUSE_PS2PLUS_PACKET_TYPE(b)    \
162     (((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
163
164 /* ring buffer */
165 typedef struct ringbuf {
166         int             count;  /* # of valid elements in the buffer */
167         int             head;   /* head pointer */
168         int             tail;   /* tail poiner */
169         u_char buf[PSM_BUFSIZE];
170 } ringbuf_t;
171
172 /* data buffer */
173 typedef struct packetbuf {
174         u_char  ipacket[16];    /* interim input buffer */
175         int     inputbytes;     /* # of bytes in the input buffer */
176 } packetbuf_t;
177
178 #ifndef PSM_PACKETQUEUE
179 #define PSM_PACKETQUEUE 128
180 #endif
181
182 /*
183  * Synaptics command definitions.
184  */
185 #define SYNAPTICS_READ_IDENTITY                 0x00
186 #define SYNAPTICS_READ_MODES                    0x01
187 #define SYNAPTICS_READ_CAPABILITIES             0x02
188 #define SYNAPTICS_READ_MODEL_ID                 0x03
189 #define SYNAPTICS_READ_SERIAL_PREFIX            0x06
190 #define SYNAPTICS_READ_SERIAL_SUFFIX            0x07
191 #define SYNAPTICS_READ_RESOLUTIONS              0x08
192 #define SYNAPTICS_READ_EXTENDED                 0x09
193 #define SYNAPTICS_READ_CAPABILITIES_CONT        0x0c
194 #define SYNAPTICS_READ_MAX_COORDS               0x0d
195 #define SYNAPTICS_READ_DELUXE_LED               0x0e
196 #define SYNAPTICS_READ_MIN_COORDS               0x0f
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         int                      softbuttons_y;
235         int                      softbutton2_x;
236         int                      softbutton3_x;
237         int                      max_x;
238         int                      max_y;
239         int                      three_finger_drag;
240         int                      natural_scroll;
241 } synapticsinfo_t;
242
243 typedef struct synapticspacket {
244         int                     x;
245         int                     y;
246 } synapticspacket_t;
247
248 #define SYNAPTICS_PACKETQUEUE 10
249 #define SYNAPTICS_QUEUE_CURSOR(x)                                       \
250         (x + SYNAPTICS_PACKETQUEUE) % SYNAPTICS_PACKETQUEUE
251
252 #define SYNAPTICS_VERSION_GE(synhw, major, minor)                       \
253     ((synhw).infoMajor > (major) ||                                     \
254      ((synhw).infoMajor == (major) && (synhw).infoMinor >= (minor)))
255
256 typedef struct smoother {
257         synapticspacket_t       queue[SYNAPTICS_PACKETQUEUE];
258         int                     queue_len;
259         int                     queue_cursor;
260         int                     start_x;
261         int                     start_y;
262         int                     avg_dx;
263         int                     avg_dy;
264         int                     squelch_x;
265         int                     squelch_y;
266         int                     is_fuzzy;
267         int                     active;
268 } smoother_t;
269
270 typedef struct gesture {
271         int                     window_min;
272         int                     fingers_nb;
273         int                     tap_button;
274         int                     in_taphold;
275         int                     in_vscroll;
276         int                     zmax;           /* maximum pressure value */
277         struct timeval          taptimeout;     /* tap timeout for touchpads */
278 } gesture_t;
279
280 enum {
281         TRACKPOINT_SYSCTL_SENSITIVITY,
282         TRACKPOINT_SYSCTL_NEGATIVE_INERTIA,
283         TRACKPOINT_SYSCTL_UPPER_PLATEAU,
284         TRACKPOINT_SYSCTL_BACKUP_RANGE,
285         TRACKPOINT_SYSCTL_DRAG_HYSTERESIS,
286         TRACKPOINT_SYSCTL_MINIMUM_DRAG,
287         TRACKPOINT_SYSCTL_UP_THRESHOLD,
288         TRACKPOINT_SYSCTL_THRESHOLD,
289         TRACKPOINT_SYSCTL_JENKS_CURVATURE,
290         TRACKPOINT_SYSCTL_Z_TIME,
291         TRACKPOINT_SYSCTL_PRESS_TO_SELECT,
292         TRACKPOINT_SYSCTL_SKIP_BACKUPS
293 };
294
295 typedef struct trackpointinfo {
296         struct sysctl_ctx_list sysctl_ctx;
297         struct sysctl_oid *sysctl_tree;
298         int     sensitivity;
299         int     inertia;
300         int     uplateau;
301         int     reach;
302         int     draghys;
303         int     mindrag;
304         int     upthresh;
305         int     threshold;
306         int     jenks;
307         int     ztime;
308         int     pts;
309         int     skipback;
310 } trackpointinfo_t;
311
312 typedef struct finger {
313         int                     x;
314         int                     y;
315         int                     p;
316         int                     w;
317         int                     flags;
318 } finger_t;
319 #define PSM_FINGERS             2       /* # of processed fingers */
320 #define PSM_FINGER_IS_PEN       (1<<0)
321 #define PSM_FINGER_FUZZY        (1<<1)
322 #define PSM_FINGER_DEFAULT_P    tap_threshold
323 #define PSM_FINGER_DEFAULT_W    1
324 #define PSM_FINGER_IS_SET(f) ((f).x != -1 && (f).y != -1 && (f).p != 0)
325 #define PSM_FINGER_RESET(f) do { \
326         (f) = (finger_t) { .x = -1, .y = -1, .p = 0, .w = 0, .flags = 0 }; \
327 } while (0)
328
329 typedef struct elantechhw {
330         int                     hwversion;
331         int                     fwversion;
332         int                     sizex;
333         int                     sizey;
334         int                     dpmmx;
335         int                     dpmmy;
336         int                     ntracesx;
337         int                     ntracesy;
338         int                     dptracex;
339         int                     dptracey;
340         int                     issemimt;
341         int                     isclickpad;
342         int                     hascrc;
343         int                     hastrackpoint;
344         int                     haspressure;
345 } elantechhw_t;
346
347 /* minimum versions supported by this driver */
348 #define ELANTECH_HW_IS_V1(fwver) ((fwver) < 0x020030 || (fwver) == 0x020600)
349
350 #define ELANTECH_MAGIC(magic)                           \
351         ((magic)[0] == 0x3c && (magic)[1] == 0x03 &&    \
352         ((magic)[2] == 0xc8 || (magic)[2] == 0x00))
353
354 #define ELANTECH_FW_ID          0x00
355 #define ELANTECH_FW_VERSION     0x01
356 #define ELANTECH_CAPABILITIES   0x02
357 #define ELANTECH_SAMPLE         0x03
358 #define ELANTECH_RESOLUTION     0x04
359 #define ELANTECH_REG_READ       0x10
360 #define ELANTECH_REG_WRITE      0x11
361 #define ELANTECH_REG_RDWR       0x00
362 #define ELANTECH_CUSTOM_CMD     0xf8
363
364 #ifdef EVDEV_SUPPORT
365 #define ELANTECH_MAX_FINGERS    5
366 #else
367 #define ELANTECH_MAX_FINGERS    PSM_FINGERS
368 #endif
369
370 #define ELANTECH_FINGER_MAX_P   255
371 #define ELANTECH_FINGER_MAX_W   15
372 #define ELANTECH_FINGER_SET_XYP(pb) (finger_t) {                        \
373     .x = (((pb)->ipacket[1] & 0x0f) << 8) | (pb)->ipacket[2],           \
374     .y = (((pb)->ipacket[4] & 0x0f) << 8) | (pb)->ipacket[5],           \
375     .p = ((pb)->ipacket[1] & 0xf0) | (((pb)->ipacket[4] >> 4) & 0x0f),  \
376     .w = PSM_FINGER_DEFAULT_W,                                          \
377     .flags = 0                                                          \
378 }
379
380 enum {
381         ELANTECH_PKT_NOP,
382         ELANTECH_PKT_TRACKPOINT,
383         ELANTECH_PKT_V2_COMMON,
384         ELANTECH_PKT_V2_2FINGER,
385         ELANTECH_PKT_V3,
386         ELANTECH_PKT_V4_STATUS,
387         ELANTECH_PKT_V4_HEAD,
388         ELANTECH_PKT_V4_MOTION
389 };
390
391 #define ELANTECH_PKT_IS_TRACKPOINT(pb) (((pb)->ipacket[3] & 0x0f) == 0x06)
392 #define ELANTECH_PKT_IS_DEBOUNCE(pb, hwversion) ((hwversion) == 4 ? 0 : \
393     (pb)->ipacket[0] == ((hwversion) == 2 ? 0x84 : 0xc4) &&             \
394     (pb)->ipacket[1] == 0xff && (pb)->ipacket[2] == 0xff &&             \
395     (pb)->ipacket[3] == 0x02 && (pb)->ipacket[4] == 0xff &&             \
396     (pb)->ipacket[5] == 0xff)
397 #define ELANTECH_PKT_IS_V2(pb)                                          \
398     (((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0x0f) == 0x02)
399 #define ELANTECH_PKT_IS_V3_HEAD(pb, hascrc) ((hascrc) ?                 \
400     ((pb)->ipacket[3] & 0x09) == 0x08 :                                 \
401     ((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0xcf) == 0x02)
402 #define ELANTECH_PKT_IS_V3_TAIL(pb, hascrc) ((hascrc) ?                 \
403     ((pb)->ipacket[3] & 0x09) == 0x09 :                                 \
404     ((pb)->ipacket[0] & 0x0c) == 0x0c && ((pb)->ipacket[3] & 0xce) == 0x0c)
405 #define ELANTECH_PKT_IS_V4(pb, hascrc) ((hascrc) ?                      \
406     ((pb)->ipacket[3] & 0x08) == 0x00 :                                 \
407     ((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0x1c) == 0x10)
408
409 typedef struct elantechaction {
410         finger_t                fingers[ELANTECH_MAX_FINGERS];
411         int                     mask;
412         int                     mask_v4wait;
413 } elantechaction_t;
414
415 /* driver control block */
416 struct psm_softc {              /* Driver status information */
417         int             unit;
418         struct selinfo  rsel;           /* Process selecting for Input */
419         u_char          state;          /* Mouse driver state */
420         int             config;         /* driver configuration flags */
421         int             flags;          /* other flags */
422         KBDC            kbdc;           /* handle to access kbd controller */
423         struct resource *intr;          /* IRQ resource */
424         void            *ih;            /* interrupt handle */
425         mousehw_t       hw;             /* hardware information */
426         synapticshw_t   synhw;          /* Synaptics hardware information */
427         synapticsinfo_t syninfo;        /* Synaptics configuration */
428         smoother_t      smoother[PSM_FINGERS];  /* Motion smoothing */
429         gesture_t       gesture;        /* Gesture context */
430         elantechhw_t    elanhw;         /* Elantech hardware information */
431         elantechaction_t elanaction;    /* Elantech action context */
432         int             tphw;           /* TrackPoint hardware information */
433         trackpointinfo_t tpinfo;        /* TrackPoint configuration */
434         mousemode_t     mode;           /* operation mode */
435         mousemode_t     dflt_mode;      /* default operation mode */
436         mousestatus_t   status;         /* accumulated mouse movement */
437         ringbuf_t       queue;          /* mouse status queue */
438         packetbuf_t     pqueue[PSM_PACKETQUEUE]; /* mouse data queue */
439         int             pqueue_start;   /* start of data in queue */
440         int             pqueue_end;     /* end of data in queue */
441         int             button;         /* the latest button state */
442         int             xold;           /* previous absolute X position */
443         int             yold;           /* previous absolute Y position */
444         int             xaverage;       /* average X position */
445         int             yaverage;       /* average Y position */
446         int             squelch; /* level to filter movement at low speed */
447         int             syncerrors; /* # of bytes discarded to synchronize */
448         int             pkterrors;  /* # of packets failed during quaranteen. */
449         int             fpcount;        /* forcePad valid packet counter */
450         struct timeval  inputtimeout;
451         struct timeval  lastsoftintr;   /* time of last soft interrupt */
452         struct timeval  lastinputerr;   /* time last sync error happened */
453         struct timeval  idletimeout;
454         packetbuf_t     idlepacket;     /* packet to send after idle timeout */
455         int             watchdog;       /* watchdog timer flag */
456         struct callout  callout;        /* watchdog timer call out */
457         struct callout  softcallout; /* buffer timer call out */
458         struct cdev     *dev;
459         struct cdev     *bdev;
460         int             lasterr;
461         int             cmdcount;
462         struct sigio    *async;         /* Processes waiting for SIGIO */
463         int             extended_buttons;
464         int             muxport;        /* MUX port with attached Synaptics */
465         u_char          muxsave[3];     /* 3->6 byte proto conversion buffer */
466         int             muxtpbuttons;   /* Touchpad button state */
467         int             muxmsbuttons;   /* Mouse (trackpoint) button state */
468         struct timeval  muxmidtimeout;  /* middle button supression timeout */
469 #ifdef EVDEV_SUPPORT
470         struct evdev_dev *evdev_a;      /* Absolute reporting device */
471         struct evdev_dev *evdev_r;      /* Relative reporting device */
472 #endif
473 };
474 static devclass_t psm_devclass;
475
476 /* driver state flags (state) */
477 #define PSM_VALID               0x80
478 #define PSM_OPEN                1       /* Device is open */
479 #define PSM_ASLP                2       /* Waiting for mouse data */
480 #define PSM_SOFTARMED           4       /* Software interrupt armed */
481 #define PSM_NEED_SYNCBITS       8       /* Set syncbits using next data pkt */
482 #define PSM_EV_OPEN_R           0x10    /* Relative evdev device is open */
483 #define PSM_EV_OPEN_A           0x20    /* Absolute evdev device is open */
484
485 /* driver configuration flags (config) */
486 #define PSM_CONFIG_RESOLUTION   0x000f  /* resolution */
487 #define PSM_CONFIG_ACCEL        0x00f0  /* acceleration factor */
488 #define PSM_CONFIG_NOCHECKSYNC  0x0100  /* disable sync. test */
489 #define PSM_CONFIG_NOIDPROBE    0x0200  /* disable mouse model probe */
490 #define PSM_CONFIG_NORESET      0x0400  /* don't reset the mouse */
491 #define PSM_CONFIG_FORCETAP     0x0800  /* assume `tap' action exists */
492 #define PSM_CONFIG_IGNPORTERROR 0x1000  /* ignore error in aux port test */
493 #define PSM_CONFIG_HOOKRESUME   0x2000  /* hook the system resume event */
494 #define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
495
496 #define PSM_CONFIG_FLAGS        \
497     (PSM_CONFIG_RESOLUTION |    \
498     PSM_CONFIG_ACCEL |          \
499     PSM_CONFIG_NOCHECKSYNC |    \
500     PSM_CONFIG_NOIDPROBE |      \
501     PSM_CONFIG_NORESET |        \
502     PSM_CONFIG_FORCETAP |       \
503     PSM_CONFIG_IGNPORTERROR |   \
504     PSM_CONFIG_HOOKRESUME |     \
505     PSM_CONFIG_INITAFTERSUSPEND)
506
507 /* other flags (flags) */
508 #define PSM_FLAGS_FINGERDOWN    0x0001  /* VersaPad finger down */
509
510 #define kbdcp(p)                        ((atkbdc_softc_t *)(p))
511 #define ALWAYS_RESTORE_CONTROLLER(kbdc) !(kbdcp(kbdc)->quirks \
512     & KBDC_QUIRK_KEEP_ACTIVATED)
513
514 /* Tunables */
515 static int tap_enabled = -1;
516 static int verbose = PSM_DEBUG;
517 static int synaptics_support = 1;
518 static int trackpoint_support = 1;
519 static int elantech_support = 1;
520 static int mux_disabled = 0;
521
522 /* for backward compatibility */
523 #define OLD_MOUSE_GETHWINFO     _IOR('M', 1, old_mousehw_t)
524 #define OLD_MOUSE_GETMODE       _IOR('M', 2, old_mousemode_t)
525 #define OLD_MOUSE_SETMODE       _IOW('M', 3, old_mousemode_t)
526
527 typedef struct old_mousehw {
528         int     buttons;
529         int     iftype;
530         int     type;
531         int     hwid;
532 } old_mousehw_t;
533
534 typedef struct old_mousemode {
535         int     protocol;
536         int     rate;
537         int     resolution;
538         int     accelfactor;
539 } old_mousemode_t;
540
541 #define SYN_OFFSET(field) offsetof(struct psm_softc, syninfo.field)
542 enum {
543         SYNAPTICS_SYSCTL_MIN_PRESSURE =         SYN_OFFSET(min_pressure),
544         SYNAPTICS_SYSCTL_MAX_PRESSURE =         SYN_OFFSET(max_pressure),
545         SYNAPTICS_SYSCTL_MAX_WIDTH =            SYN_OFFSET(max_width),
546         SYNAPTICS_SYSCTL_MARGIN_TOP =           SYN_OFFSET(margin_top),
547         SYNAPTICS_SYSCTL_MARGIN_RIGHT =         SYN_OFFSET(margin_right),
548         SYNAPTICS_SYSCTL_MARGIN_BOTTOM =        SYN_OFFSET(margin_bottom),
549         SYNAPTICS_SYSCTL_MARGIN_LEFT =          SYN_OFFSET(margin_left),
550         SYNAPTICS_SYSCTL_NA_TOP =               SYN_OFFSET(na_top),
551         SYNAPTICS_SYSCTL_NA_RIGHT =             SYN_OFFSET(na_right),
552         SYNAPTICS_SYSCTL_NA_BOTTOM =            SYN_OFFSET(na_bottom),
553         SYNAPTICS_SYSCTL_NA_LEFT =              SYN_OFFSET(na_left),
554         SYNAPTICS_SYSCTL_WINDOW_MIN =           SYN_OFFSET(window_min),
555         SYNAPTICS_SYSCTL_WINDOW_MAX =           SYN_OFFSET(window_max),
556         SYNAPTICS_SYSCTL_MULTIPLICATOR =        SYN_OFFSET(multiplicator),
557         SYNAPTICS_SYSCTL_WEIGHT_CURRENT =       SYN_OFFSET(weight_current),
558         SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS =      SYN_OFFSET(weight_previous),
559         SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA =   SYN_OFFSET(weight_previous_na),
560         SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED =   SYN_OFFSET(weight_len_squared),
561         SYNAPTICS_SYSCTL_DIV_MIN =              SYN_OFFSET(div_min),
562         SYNAPTICS_SYSCTL_DIV_MAX =              SYN_OFFSET(div_max),
563         SYNAPTICS_SYSCTL_DIV_MAX_NA =           SYN_OFFSET(div_max_na),
564         SYNAPTICS_SYSCTL_DIV_LEN =              SYN_OFFSET(div_len),
565         SYNAPTICS_SYSCTL_TAP_MAX_DELTA =        SYN_OFFSET(tap_max_delta),
566         SYNAPTICS_SYSCTL_TAP_MIN_QUEUE =        SYN_OFFSET(tap_min_queue),
567         SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT =      SYN_OFFSET(taphold_timeout),
568         SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA =     SYN_OFFSET(vscroll_hor_area),
569         SYNAPTICS_SYSCTL_VSCROLL_VER_AREA =     SYN_OFFSET(vscroll_ver_area),
570         SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA =    SYN_OFFSET(vscroll_min_delta),
571         SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN =      SYN_OFFSET(vscroll_div_min),
572         SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX =      SYN_OFFSET(vscroll_div_max),
573         SYNAPTICS_SYSCTL_TOUCHPAD_OFF =         SYN_OFFSET(touchpad_off),
574         SYNAPTICS_SYSCTL_SOFTBUTTONS_Y =        SYN_OFFSET(softbuttons_y),
575         SYNAPTICS_SYSCTL_SOFTBUTTON2_X =        SYN_OFFSET(softbutton2_x),
576         SYNAPTICS_SYSCTL_SOFTBUTTON3_X =        SYN_OFFSET(softbutton3_x),
577         SYNAPTICS_SYSCTL_THREE_FINGER_DRAG =    SYN_OFFSET(three_finger_drag),
578         SYNAPTICS_SYSCTL_NATURAL_SCROLL =       SYN_OFFSET(natural_scroll),
579 #define SYNAPTICS_SYSCTL_LAST   SYNAPTICS_SYSCTL_NATURAL_SCROLL
580 };
581
582 /* packet formatting function */
583 typedef int     packetfunc_t(struct psm_softc *, u_char *, int *, int,
584     mousestatus_t *);
585
586 /* function prototypes */
587 static void     psmidentify(driver_t *, device_t);
588 static int      psmprobe(device_t);
589 static int      psmattach(device_t);
590 static int      psmdetach(device_t);
591 static int      psmresume(device_t);
592
593 static d_open_t         psm_cdev_open;
594 static d_close_t        psm_cdev_close;
595 static d_read_t         psmread;
596 static d_write_t        psmwrite;
597 static d_ioctl_t        psmioctl;
598 static d_poll_t         psmpoll;
599
600 static int      psmopen(struct psm_softc *);
601 static int      psmclose(struct psm_softc *);
602
603 #ifdef EVDEV_SUPPORT
604 static evdev_open_t     psm_ev_open_r;
605 static evdev_close_t    psm_ev_close_r;
606 static evdev_open_t     psm_ev_open_a;
607 static evdev_close_t    psm_ev_close_a;
608 #endif
609
610 static int      enable_aux_dev(KBDC);
611 static int      disable_aux_dev(KBDC);
612 static int      get_mouse_status(KBDC, int *, int, int);
613 static int      get_aux_id(KBDC);
614 static int      set_mouse_sampling_rate(KBDC, int);
615 static int      set_mouse_scaling(KBDC, int);
616 static int      set_mouse_resolution(KBDC, int);
617 static int      set_mouse_mode(KBDC);
618 static int      get_mouse_buttons(KBDC);
619 static int      is_a_mouse(int);
620 static void     recover_from_error(KBDC);
621 static int      restore_controller(KBDC, int);
622 static int      doinitialize(struct psm_softc *, mousemode_t *);
623 static int      doopen(struct psm_softc *, int);
624 static int      reinitialize(struct psm_softc *, int);
625 static char     *model_name(int);
626 static void     psmsoftintr(void *);
627 static void     psmsoftintridle(void *);
628 static void     psmintr(void *);
629 static void     psmtimeout(void *);
630 static int      timeelapsed(const struct timeval *, int, int,
631                     const struct timeval *);
632 static void     dropqueue(struct psm_softc *);
633 static void     flushpackets(struct psm_softc *);
634 static void     proc_mmanplus(struct psm_softc *, packetbuf_t *,
635                     mousestatus_t *, int *, int *, int *);
636 static int      proc_synaptics(struct psm_softc *, packetbuf_t *,
637                     mousestatus_t *, int *, int *, int *);
638 static int      proc_synaptics_mux(struct psm_softc *, packetbuf_t *);
639 static void     proc_versapad(struct psm_softc *, packetbuf_t *,
640                     mousestatus_t *, int *, int *, int *);
641 static int      proc_elantech(struct psm_softc *, packetbuf_t *,
642                     mousestatus_t *, int *, int *, int *);
643 static int      psmpalmdetect(struct psm_softc *, finger_t *, int);
644 static void     psmgestures(struct psm_softc *, finger_t *, int,
645                     mousestatus_t *);
646 static void     psmsmoother(struct psm_softc *, finger_t *, int,
647                     mousestatus_t *, int *, int *);
648 static int      tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *,
649                     u_char *);
650
651 /* vendor specific features */
652 enum probearg { PROBE, REINIT };
653 typedef int     probefunc_t(struct psm_softc *, enum probearg);
654
655 static int      mouse_id_proc1(KBDC, int, int, int *);
656 static int      mouse_ext_command(KBDC, int);
657
658 static probefunc_t      enable_groller;
659 static probefunc_t      enable_gmouse;
660 static probefunc_t      enable_aglide;
661 static probefunc_t      enable_kmouse;
662 static probefunc_t      enable_msexplorer;
663 static probefunc_t      enable_msintelli;
664 static probefunc_t      enable_4dmouse;
665 static probefunc_t      enable_4dplus;
666 static probefunc_t      enable_mmanplus;
667 static probefunc_t      enable_synaptics;
668 static probefunc_t      enable_synaptics_mux;
669 static probefunc_t      enable_trackpoint;
670 static probefunc_t      enable_versapad;
671 static probefunc_t      enable_elantech;
672
673 static void set_trackpoint_parameters(struct psm_softc *sc);
674 static void synaptics_passthrough_on(struct psm_softc *sc);
675 static void synaptics_passthrough_off(struct psm_softc *sc);
676 static int synaptics_preferred_mode(struct psm_softc *sc);
677 static void synaptics_set_mode(struct psm_softc *sc, int mode_byte);
678
679 static struct {
680         int             model;
681         u_char          syncmask;
682         int             packetsize;
683         probefunc_t     *probefunc;
684 } vendortype[] = {
685         /*
686          * WARNING: the order of probe is very important.  Don't mess it
687          * unless you know what you are doing.
688          */
689         { MOUSE_MODEL_SYNAPTICS,        /* Synaptics Touchpad on Active Mux */
690           0x00, MOUSE_PS2_PACKETSIZE, enable_synaptics_mux },
691         { MOUSE_MODEL_NET,              /* Genius NetMouse */
692           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse },
693         { MOUSE_MODEL_NETSCROLL,        /* Genius NetScroll */
694           0xc8, 6, enable_groller },
695         { MOUSE_MODEL_MOUSEMANPLUS,     /* Logitech MouseMan+ */
696           0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus },
697         { MOUSE_MODEL_EXPLORER,         /* Microsoft IntelliMouse Explorer */
698           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer },
699         { MOUSE_MODEL_4D,               /* A4 Tech 4D Mouse */
700           0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse },
701         { MOUSE_MODEL_4DPLUS,           /* A4 Tech 4D+ Mouse */
702           0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus },
703         { MOUSE_MODEL_SYNAPTICS,        /* Synaptics Touchpad */
704           0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics },
705         { MOUSE_MODEL_ELANTECH,         /* Elantech Touchpad */
706           0x04, MOUSE_ELANTECH_PACKETSIZE, enable_elantech },
707         { MOUSE_MODEL_INTELLI,          /* Microsoft IntelliMouse */
708           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli },
709         { MOUSE_MODEL_GLIDEPOINT,       /* ALPS GlidePoint */
710           0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide },
711         { MOUSE_MODEL_THINK,            /* Kensington ThinkingMouse */
712           0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse },
713         { MOUSE_MODEL_VERSAPAD,         /* Interlink electronics VersaPad */
714           0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad },
715         { MOUSE_MODEL_TRACKPOINT,       /* IBM/Lenovo TrackPoint */
716           0xc0, MOUSE_PS2_PACKETSIZE, enable_trackpoint },
717         { MOUSE_MODEL_GENERIC,
718           0xc0, MOUSE_PS2_PACKETSIZE, NULL },
719 };
720 #define GENERIC_MOUSE_ENTRY (nitems(vendortype) - 1)
721
722 /* device driver declarateion */
723 static device_method_t psm_methods[] = {
724         /* Device interface */
725         DEVMETHOD(device_identify,      psmidentify),
726         DEVMETHOD(device_probe,         psmprobe),
727         DEVMETHOD(device_attach,        psmattach),
728         DEVMETHOD(device_detach,        psmdetach),
729         DEVMETHOD(device_resume,        psmresume),
730
731         { 0, 0 }
732 };
733
734 static driver_t psm_driver = {
735         PSM_DRIVER_NAME,
736         psm_methods,
737         sizeof(struct psm_softc),
738 };
739
740 static struct cdevsw psm_cdevsw = {
741         .d_version =    D_VERSION,
742         .d_flags =      D_NEEDGIANT,
743         .d_open =       psm_cdev_open,
744         .d_close =      psm_cdev_close,
745         .d_read =       psmread,
746         .d_write =      psmwrite,
747         .d_ioctl =      psmioctl,
748         .d_poll =       psmpoll,
749         .d_name =       PSM_DRIVER_NAME,
750 };
751
752 #ifdef EVDEV_SUPPORT
753 static const struct evdev_methods psm_ev_methods_r = {
754         .ev_open = psm_ev_open_r,
755         .ev_close = psm_ev_close_r,
756 };
757 static const struct evdev_methods psm_ev_methods_a = {
758         .ev_open = psm_ev_open_a,
759         .ev_close = psm_ev_close_a,
760 };
761 #endif
762
763 /* device I/O routines */
764 static int
765 enable_aux_dev(KBDC kbdc)
766 {
767         int res;
768
769         res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
770         VLOG(2, (LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res));
771
772         return (res == PSM_ACK);
773 }
774
775 static int
776 disable_aux_dev(KBDC kbdc)
777 {
778         int res;
779
780         res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
781         VLOG(2, (LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res));
782
783         return (res == PSM_ACK);
784 }
785
786 static int
787 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
788 {
789         int cmd;
790         int res;
791         int i;
792
793         switch (flag) {
794         case 0:
795         default:
796                 cmd = PSMC_SEND_DEV_STATUS;
797                 break;
798         case 1:
799                 cmd = PSMC_SEND_DEV_DATA;
800                 break;
801         }
802         empty_aux_buffer(kbdc, 5);
803         res = send_aux_command(kbdc, cmd);
804         VLOG(2, (LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
805             (flag == 1) ? "DATA" : "STATUS", res));
806         if (res != PSM_ACK)
807                 return (0);
808
809         for (i = 0; i < len; ++i) {
810                 status[i] = read_aux_data(kbdc);
811                 if (status[i] < 0)
812                         break;
813         }
814         if (len >= 3) {
815                 for (; i < 3; ++i)
816                         status[i] = 0;
817                 VLOG(1, (LOG_DEBUG, "psm: %s %02x %02x %02x\n",
818                     (flag == 1) ? "data" : "status", status[0], status[1], status[2]));
819         }
820
821         return (i);
822 }
823
824 static int
825 get_aux_id(KBDC kbdc)
826 {
827         int res;
828         int id;
829
830         empty_aux_buffer(kbdc, 5);
831         res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
832         VLOG(2, (LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res));
833         if (res != PSM_ACK)
834                 return (-1);
835
836         /* 10ms delay */
837         DELAY(10000);
838
839         id = read_aux_data(kbdc);
840         VLOG(2, (LOG_DEBUG, "psm: device ID: %04x\n", id));
841
842         return (id);
843 }
844
845 static int
846 set_mouse_sampling_rate(KBDC kbdc, int rate)
847 {
848         int res;
849
850         res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
851         VLOG(2, (LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res));
852
853         return ((res == PSM_ACK) ? rate : -1);
854 }
855
856 static int
857 set_mouse_scaling(KBDC kbdc, int scale)
858 {
859         int res;
860
861         switch (scale) {
862         case 1:
863         default:
864                 scale = PSMC_SET_SCALING11;
865                 break;
866         case 2:
867                 scale = PSMC_SET_SCALING21;
868                 break;
869         }
870         res = send_aux_command(kbdc, scale);
871         VLOG(2, (LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
872             (scale == PSMC_SET_SCALING21) ? "21" : "11", res));
873
874         return (res == PSM_ACK);
875 }
876
877 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
878 static int
879 set_mouse_resolution(KBDC kbdc, int val)
880 {
881         int res;
882
883         res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
884         VLOG(2, (LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res));
885
886         return ((res == PSM_ACK) ? val : -1);
887 }
888
889 /*
890  * NOTE: once `set_mouse_mode()' is called, the mouse device must be
891  * re-enabled by calling `enable_aux_dev()'
892  */
893 static int
894 set_mouse_mode(KBDC kbdc)
895 {
896         int res;
897
898         res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
899         VLOG(2, (LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res));
900
901         return (res == PSM_ACK);
902 }
903
904 static int
905 get_mouse_buttons(KBDC kbdc)
906 {
907         int c = 2;              /* assume two buttons by default */
908         int status[3];
909
910         /*
911          * NOTE: a special sequence to obtain Logitech Mouse specific
912          * information: set resolution to 25 ppi, set scaling to 1:1, set
913          * scaling to 1:1, set scaling to 1:1. Then the second byte of the
914          * mouse status bytes is the number of available buttons.
915          * Some manufactures also support this sequence.
916          */
917         if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
918                 return (c);
919         if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1) &&
920             set_mouse_scaling(kbdc, 1) &&
921             get_mouse_status(kbdc, status, 0, 3) >= 3 && status[1] != 0)
922                 return (status[1]);
923         return (c);
924 }
925
926 /* misc subroutines */
927 /*
928  * Someday, I will get the complete list of valid pointing devices and
929  * their IDs... XXX
930  */
931 static int
932 is_a_mouse(int id)
933 {
934 #if 0
935         static int valid_ids[] = {
936                 PSM_MOUSE_ID,           /* mouse */
937                 PSM_BALLPOINT_ID,       /* ballpoint device */
938                 PSM_INTELLI_ID,         /* Intellimouse */
939                 PSM_EXPLORER_ID,        /* Intellimouse Explorer */
940                 -1                      /* end of table */
941         };
942         int i;
943
944         for (i = 0; valid_ids[i] >= 0; ++i)
945         if (valid_ids[i] == id)
946                 return (TRUE);
947         return (FALSE);
948 #else
949         return (TRUE);
950 #endif
951 }
952
953 static char *
954 model_name(int model)
955 {
956         static struct {
957                 int     model_code;
958                 char    *model_name;
959         } models[] = {
960                 { MOUSE_MODEL_NETSCROLL,        "NetScroll" },
961                 { MOUSE_MODEL_NET,              "NetMouse/NetScroll Optical" },
962                 { MOUSE_MODEL_GLIDEPOINT,       "GlidePoint" },
963                 { MOUSE_MODEL_THINK,            "ThinkingMouse" },
964                 { MOUSE_MODEL_INTELLI,          "IntelliMouse" },
965                 { MOUSE_MODEL_MOUSEMANPLUS,     "MouseMan+" },
966                 { MOUSE_MODEL_VERSAPAD,         "VersaPad" },
967                 { MOUSE_MODEL_EXPLORER,         "IntelliMouse Explorer" },
968                 { MOUSE_MODEL_4D,               "4D Mouse" },
969                 { MOUSE_MODEL_4DPLUS,           "4D+ Mouse" },
970                 { MOUSE_MODEL_SYNAPTICS,        "Synaptics Touchpad" },
971                 { MOUSE_MODEL_TRACKPOINT,       "IBM/Lenovo TrackPoint" },
972                 { MOUSE_MODEL_ELANTECH,         "Elantech Touchpad" },
973                 { MOUSE_MODEL_GENERIC,          "Generic PS/2 mouse" },
974                 { MOUSE_MODEL_UNKNOWN,          "Unknown" },
975         };
976         int i;
977
978         for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i)
979                 if (models[i].model_code == model)
980                         break;
981         return (models[i].model_name);
982 }
983
984 static void
985 recover_from_error(KBDC kbdc)
986 {
987         /* discard anything left in the output buffer */
988         empty_both_buffers(kbdc, 10);
989
990 #if 0
991         /*
992          * NOTE: KBDC_RESET_KBD may not restore the communication between the
993          * keyboard and the controller.
994          */
995         reset_kbd(kbdc);
996 #else
997         /*
998          * NOTE: somehow diagnostic and keyboard port test commands bring the
999          * keyboard back.
1000          */
1001         if (!test_controller(kbdc))
1002                 log(LOG_ERR, "psm: keyboard controller failed.\n");
1003         /* if there isn't a keyboard in the system, the following error is OK */
1004         if (test_kbd_port(kbdc) != 0)
1005                 VLOG(1, (LOG_ERR, "psm: keyboard port failed.\n"));
1006 #endif
1007 }
1008
1009 static int
1010 restore_controller(KBDC kbdc, int command_byte)
1011 {
1012         empty_both_buffers(kbdc, 10);
1013
1014         if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
1015                 log(LOG_ERR, "psm: failed to restore the keyboard controller "
1016                     "command byte.\n");
1017                 empty_both_buffers(kbdc, 10);
1018                 return (FALSE);
1019         } else {
1020                 empty_both_buffers(kbdc, 10);
1021                 return (TRUE);
1022         }
1023 }
1024
1025 /*
1026  * Re-initialize the aux port and device. The aux port must be enabled
1027  * and its interrupt must be disabled before calling this routine.
1028  * The aux device will be disabled before returning.
1029  * The keyboard controller must be locked via `kbdc_lock()' before
1030  * calling this routine.
1031  */
1032 static int
1033 doinitialize(struct psm_softc *sc, mousemode_t *mode)
1034 {
1035         KBDC kbdc = sc->kbdc;
1036         int stat[3];
1037         int i;
1038
1039         switch((i = test_aux_port(kbdc))) {
1040         case 1: /* ignore these errors */
1041         case 2:
1042         case 3:
1043         case PSM_ACK:
1044                 if (verbose)
1045                         log(LOG_DEBUG,
1046                             "psm%d: strange result for test aux port (%d).\n",
1047                             sc->unit, i);
1048                 /* FALLTHROUGH */
1049         case 0:         /* no error */
1050                 break;
1051         case -1:        /* time out */
1052         default:        /* error */
1053                 recover_from_error(kbdc);
1054                 if (sc->config & PSM_CONFIG_IGNPORTERROR)
1055                         break;
1056                 log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
1057                     sc->unit, i);
1058                 return (FALSE);
1059         }
1060
1061         if (sc->config & PSM_CONFIG_NORESET) {
1062                 /*
1063                  * Don't try to reset the pointing device.  It may possibly
1064                  * be left in the unknown state, though...
1065                  */
1066         } else {
1067                 /*
1068                  * NOTE: some controllers appears to hang the `keyboard' when
1069                  * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
1070                  */
1071                 if (!reset_aux_dev(kbdc)) {
1072                         recover_from_error(kbdc);
1073                         log(LOG_ERR, "psm%d: failed to reset the aux device.\n",
1074                             sc->unit);
1075                         return (FALSE);
1076                 }
1077         }
1078
1079         /*
1080          * both the aux port and the aux device is functioning, see
1081          * if the device can be enabled.
1082          */
1083         if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
1084                 log(LOG_ERR, "psm%d: failed to enable the aux device.\n",
1085                     sc->unit);
1086                 return (FALSE);
1087         }
1088         empty_both_buffers(kbdc, 10);   /* remove stray data if any */
1089
1090         /* Re-enable the mouse. */
1091         for (i = 0; vendortype[i].probefunc != NULL; ++i)
1092                 if (vendortype[i].model == sc->hw.model)
1093                         (*vendortype[i].probefunc)(sc, REINIT);
1094
1095         /* set mouse parameters */
1096         if (mode != (mousemode_t *)NULL) {
1097                 if (mode->rate > 0)
1098                         mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
1099                 if (mode->resolution >= 0)
1100                         mode->resolution =
1101                             set_mouse_resolution(kbdc, mode->resolution);
1102                 set_mouse_scaling(kbdc, 1);
1103                 set_mouse_mode(kbdc);
1104         }
1105
1106         /* Record sync on the next data packet we see. */
1107         sc->flags |= PSM_NEED_SYNCBITS;
1108
1109         /* just check the status of the mouse */
1110         if (get_mouse_status(kbdc, stat, 0, 3) < 3)
1111                 log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
1112                     sc->unit);
1113
1114         return (TRUE);
1115 }
1116
1117 static int
1118 doopen(struct psm_softc *sc, int command_byte)
1119 {
1120         int stat[3];
1121         int mux_enabled = FALSE;
1122
1123         /*
1124          * FIXME: Synaptics TouchPad seems to go back to Relative Mode with
1125          * no obvious reason. Thus we check the current mode and restore the
1126          * Absolute Mode if it was cleared.
1127          *
1128          * The previous hack at the end of psmprobe() wasn't efficient when
1129          * moused(8) was restarted.
1130          *
1131          * A Reset (FF) or Set Defaults (F6) command would clear the
1132          * Absolute Mode bit. But a verbose boot or debug.psm.loglevel=5
1133          * doesn't show any evidence of such a command.
1134          */
1135         if (sc->hw.model == MOUSE_MODEL_SYNAPTICS) {
1136                 if (sc->muxport != PSM_NOMUX) {
1137                         mux_enabled = enable_aux_mux(sc->kbdc) >= 0;
1138                         if (mux_enabled)
1139                                 set_active_aux_mux_port(sc->kbdc, sc->muxport);
1140                         else
1141                                 log(LOG_ERR, "psm%d: failed to enable "
1142                                     "active multiplexing mode.\n",
1143                                     sc->unit);
1144                 }
1145                 mouse_ext_command(sc->kbdc, SYNAPTICS_READ_MODES);
1146                 get_mouse_status(sc->kbdc, stat, 0, 3);
1147                 if ((SYNAPTICS_VERSION_GE(sc->synhw, 7, 5) ||
1148                      stat[1] == 0x47) &&
1149                      stat[2] == 0x40) {
1150                         synaptics_set_mode(sc, synaptics_preferred_mode(sc));
1151                         VLOG(5, (LOG_DEBUG, "psm%d: Synaptis Absolute Mode "
1152                             "hopefully restored\n",
1153                             sc->unit));
1154                 }
1155                 if (mux_enabled)
1156                         disable_aux_mux(sc->kbdc);
1157         }
1158
1159         /*
1160          * A user may want to disable tap and drag gestures on a Synaptics
1161          * TouchPad when it operates in Relative Mode.
1162          */
1163         if (sc->hw.model == MOUSE_MODEL_GENERIC) {
1164                 if (tap_enabled > 0) {
1165                         VLOG(2, (LOG_DEBUG,
1166                             "psm%d: enable tap and drag gestures\n",
1167                             sc->unit));
1168                         synaptics_set_mode(sc, synaptics_preferred_mode(sc));
1169                 } else if (tap_enabled == 0) {
1170                         VLOG(2, (LOG_DEBUG,
1171                             "psm%d: disable tap and drag gestures\n",
1172                             sc->unit));
1173                         synaptics_set_mode(sc, synaptics_preferred_mode(sc));
1174                 }
1175         }
1176
1177         /* enable the mouse device */
1178         if (!enable_aux_dev(sc->kbdc)) {
1179                 /* MOUSE ERROR: failed to enable the mouse because:
1180                  * 1) the mouse is faulty,
1181                  * 2) the mouse has been removed(!?)
1182                  * In the latter case, the keyboard may have hung, and need
1183                  * recovery procedure...
1184                  */
1185                 recover_from_error(sc->kbdc);
1186 #if 0
1187                 /* FIXME: we could reset the mouse here and try to enable
1188                  * it again. But it will take long time and it's not a good
1189                  * idea to disable the keyboard that long...
1190                  */
1191                 if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
1192                         recover_from_error(sc->kbdc);
1193 #else
1194                 {
1195 #endif
1196                         restore_controller(sc->kbdc, command_byte);
1197                         /* mark this device is no longer available */
1198                         sc->state &= ~PSM_VALID;
1199                         log(LOG_ERR,
1200                             "psm%d: failed to enable the device (doopen).\n",
1201                         sc->unit);
1202                         return (EIO);
1203                 }
1204         }
1205
1206         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1207                 log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n",
1208                     sc->unit);
1209
1210         /* enable the aux port and interrupt */
1211         if (!set_controller_command_byte(sc->kbdc,
1212             kbdc_get_device_mask(sc->kbdc),
1213             (command_byte & KBD_KBD_CONTROL_BITS) |
1214             KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
1215                 /* CONTROLLER ERROR */
1216                 disable_aux_dev(sc->kbdc);
1217                 restore_controller(sc->kbdc, command_byte);
1218                 log(LOG_ERR,
1219                     "psm%d: failed to enable the aux interrupt (doopen).\n",
1220                     sc->unit);
1221                 return (EIO);
1222         }
1223
1224         /* start the watchdog timer */
1225         sc->watchdog = FALSE;
1226         callout_reset(&sc->callout, hz * 2, psmtimeout, sc);
1227
1228         return (0);
1229 }
1230
1231 static int
1232 reinitialize(struct psm_softc *sc, int doinit)
1233 {
1234         int err;
1235         int c;
1236         int s;
1237
1238         /* don't let anybody mess with the aux device */
1239         if (!kbdc_lock(sc->kbdc, TRUE))
1240                 return (EIO);
1241         s = spltty();
1242
1243         /* block our watchdog timer */
1244         sc->watchdog = FALSE;
1245         callout_stop(&sc->callout);
1246
1247         /* save the current controller command byte */
1248         empty_both_buffers(sc->kbdc, 10);
1249         c = get_controller_command_byte(sc->kbdc);
1250         VLOG(2, (LOG_DEBUG,
1251             "psm%d: current command byte: %04x (reinitialize).\n",
1252             sc->unit, c));
1253
1254         /* enable the aux port but disable the aux interrupt and the keyboard */
1255         if ((c == -1) || !set_controller_command_byte(sc->kbdc,
1256             kbdc_get_device_mask(sc->kbdc),
1257             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1258             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1259                 /* CONTROLLER ERROR */
1260                 splx(s);
1261                 kbdc_lock(sc->kbdc, FALSE);
1262                 log(LOG_ERR,
1263                     "psm%d: unable to set the command byte (reinitialize).\n",
1264                     sc->unit);
1265                 return (EIO);
1266         }
1267
1268         /* flush any data */
1269         if (sc->state & PSM_VALID) {
1270                 /* this may fail; but never mind... */
1271                 disable_aux_dev(sc->kbdc);
1272                 empty_aux_buffer(sc->kbdc, 10);
1273         }
1274         flushpackets(sc);
1275         sc->syncerrors = 0;
1276         sc->pkterrors = 0;
1277         memset(&sc->lastinputerr, 0, sizeof(sc->lastinputerr));
1278
1279         /* try to detect the aux device; are you still there? */
1280         err = 0;
1281         if (doinit) {
1282                 if (doinitialize(sc, &sc->mode)) {
1283                         /* yes */
1284                         sc->state |= PSM_VALID;
1285                 } else {
1286                         /* the device has gone! */
1287                         restore_controller(sc->kbdc, c);
1288                         sc->state &= ~PSM_VALID;
1289                         log(LOG_ERR,
1290                             "psm%d: the aux device has gone! (reinitialize).\n",
1291                             sc->unit);
1292                         err = ENXIO;
1293                 }
1294         }
1295         splx(s);
1296
1297         /* restore the driver state */
1298         if ((sc->state & (PSM_OPEN | PSM_EV_OPEN_R | PSM_EV_OPEN_A)) &&
1299             (err == 0)) {
1300                 /* enable the aux device and the port again */
1301                 err = doopen(sc, c);
1302                 if (err != 0)
1303                         log(LOG_ERR, "psm%d: failed to enable the device "
1304                             "(reinitialize).\n", sc->unit);
1305         } else {
1306                 /* restore the keyboard port and disable the aux port */
1307                 if (!set_controller_command_byte(sc->kbdc,
1308                     kbdc_get_device_mask(sc->kbdc),
1309                     (c & KBD_KBD_CONTROL_BITS) |
1310                     KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1311                         /* CONTROLLER ERROR */
1312                         log(LOG_ERR, "psm%d: failed to disable the aux port "
1313                             "(reinitialize).\n", sc->unit);
1314                         err = EIO;
1315                 }
1316         }
1317
1318         kbdc_lock(sc->kbdc, FALSE);
1319         return (err);
1320 }
1321
1322 /* psm driver entry points */
1323
1324 static void
1325 psmidentify(driver_t *driver, device_t parent)
1326 {
1327         device_t psmc;
1328         device_t psm;
1329         u_long irq;
1330         int unit;
1331
1332         unit = device_get_unit(parent);
1333
1334         /* always add at least one child */
1335         psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
1336         if (psm == NULL)
1337                 return;
1338
1339         irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
1340         if (irq > 0)
1341                 return;
1342
1343         /*
1344          * If the PS/2 mouse device has already been reported by ACPI or
1345          * PnP BIOS, obtain the IRQ resource from it.
1346          * (See psmcpnp_attach() below.)
1347          */
1348         psmc = device_find_child(device_get_parent(parent),
1349             PSMCPNP_DRIVER_NAME, unit);
1350         if (psmc == NULL)
1351                 return;
1352         irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
1353         if (irq <= 0)
1354                 return;
1355         bus_delete_resource(psmc, SYS_RES_IRQ, 0);
1356         bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
1357 }
1358
1359 #define endprobe(v)     do {                    \
1360         if (bootverbose)                        \
1361                 --verbose;                      \
1362         kbdc_set_device_mask(sc->kbdc, mask);   \
1363         kbdc_lock(sc->kbdc, FALSE);             \
1364         return (v);                             \
1365 } while (0)
1366
1367 static int
1368 psmprobe(device_t dev)
1369 {
1370         int unit = device_get_unit(dev);
1371         struct psm_softc *sc = device_get_softc(dev);
1372         int stat[3];
1373         int command_byte;
1374         int mask;
1375         int rid;
1376         int i;
1377
1378 #if 0
1379         kbdc_debug(TRUE);
1380 #endif
1381
1382         /* see if IRQ is available */
1383         rid = KBDC_RID_AUX;
1384         sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1385         if (sc->intr == NULL) {
1386                 if (bootverbose)
1387                         device_printf(dev, "unable to allocate IRQ\n");
1388                 return (ENXIO);
1389         }
1390         bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1391
1392         sc->unit = unit;
1393         sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
1394         if (sc->kbdc == NULL)
1395                 return (ENXIO);
1396         sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
1397         /* XXX: for backward compatibility */
1398 #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
1399         sc->config |=
1400 #ifdef PSM_RESETAFTERSUSPEND
1401         PSM_CONFIG_INITAFTERSUSPEND;
1402 #else
1403         PSM_CONFIG_HOOKRESUME;
1404 #endif
1405 #endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
1406         sc->flags = 0;
1407         sc->muxport = PSM_NOMUX;
1408         if (bootverbose)
1409                 ++verbose;
1410
1411         device_set_desc(dev, "PS/2 Mouse");
1412
1413         if (!kbdc_lock(sc->kbdc, TRUE)) {
1414                 printf("psm%d: unable to lock the controller.\n", unit);
1415                 if (bootverbose)
1416                         --verbose;
1417                 return (ENXIO);
1418         }
1419
1420         /*
1421          * NOTE: two bits in the command byte controls the operation of the
1422          * aux port (mouse port): the aux port disable bit (bit 5) and the aux
1423          * port interrupt (IRQ 12) enable bit (bit 2).
1424          */
1425
1426         /* discard anything left after the keyboard initialization */
1427         empty_both_buffers(sc->kbdc, 10);
1428
1429         /* save the current command byte; it will be used later */
1430         mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
1431         command_byte = get_controller_command_byte(sc->kbdc);
1432         if (verbose)
1433                 printf("psm%d: current command byte:%04x\n", unit,
1434                     command_byte);
1435         if (command_byte == -1) {
1436                 /* CONTROLLER ERROR */
1437                 printf("psm%d: unable to get the current command byte value.\n",
1438                         unit);
1439                 endprobe(ENXIO);
1440         }
1441
1442         /*
1443          * disable the keyboard port while probing the aux port, which must be
1444          * enabled during this routine
1445          */
1446         if (!set_controller_command_byte(sc->kbdc,
1447             KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1448             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1449             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1450                 /*
1451                  * this is CONTROLLER ERROR; I don't know how to recover
1452                  * from this error...
1453                  */
1454                 if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1455                         restore_controller(sc->kbdc, command_byte);
1456                 printf("psm%d: unable to set the command byte.\n", unit);
1457                 endprobe(ENXIO);
1458         }
1459         write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
1460
1461         /*
1462          * NOTE: `test_aux_port()' is designed to return with zero if the aux
1463          * port exists and is functioning. However, some controllers appears
1464          * to respond with zero even when the aux port doesn't exist. (It may
1465          * be that this is only the case when the controller DOES have the aux
1466          * port but the port is not wired on the motherboard.) The keyboard
1467          * controllers without the port, such as the original AT, are
1468          * supposed to return with an error code or simply time out. In any
1469          * case, we have to continue probing the port even when the controller
1470          * passes this test.
1471          *
1472          * XXX: some controllers erroneously return the error code 1, 2 or 3
1473          * when it has a perfectly functional aux port. We have to ignore
1474          * this error code. Even if the controller HAS error with the aux
1475          * port, it will be detected later...
1476          * XXX: another incompatible controller returns PSM_ACK (0xfa)...
1477          */
1478         switch ((i = test_aux_port(sc->kbdc))) {
1479         case 1:         /* ignore these errors */
1480         case 2:
1481         case 3:
1482         case PSM_ACK:
1483                 if (verbose)
1484                         printf("psm%d: strange result for test aux port "
1485                             "(%d).\n", unit, i);
1486                 /* FALLTHROUGH */
1487         case 0:         /* no error */
1488                 break;
1489         case -1:        /* time out */
1490         default:        /* error */
1491                 recover_from_error(sc->kbdc);
1492                 if (sc->config & PSM_CONFIG_IGNPORTERROR)
1493                         break;
1494                 if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1495                         restore_controller(sc->kbdc, command_byte);
1496                 if (verbose)
1497                         printf("psm%d: the aux port is not functioning (%d).\n",
1498                             unit, i);
1499                 endprobe(ENXIO);
1500         }
1501
1502         if (sc->config & PSM_CONFIG_NORESET) {
1503                 /*
1504                  * Don't try to reset the pointing device.  It may possibly be
1505                  * left in an unknown state, though...
1506                  */
1507         } else {
1508                 /*
1509                  * NOTE: some controllers appears to hang the `keyboard' when
1510                  * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
1511                  *
1512                  * Attempt to reset the controller twice -- this helps
1513                  * pierce through some KVM switches. The second reset
1514                  * is non-fatal.
1515                  */
1516                 if (!reset_aux_dev(sc->kbdc)) {
1517                         recover_from_error(sc->kbdc);
1518                         if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1519                                 restore_controller(sc->kbdc, command_byte);
1520                         if (verbose)
1521                                 printf("psm%d: failed to reset the aux "
1522                                     "device.\n", unit);
1523                         endprobe(ENXIO);
1524                 } else if (!reset_aux_dev(sc->kbdc)) {
1525                         recover_from_error(sc->kbdc);
1526                         if (verbose >= 2)
1527                                 printf("psm%d: failed to reset the aux device "
1528                                     "(2).\n", unit);
1529                 }
1530         }
1531
1532         /*
1533          * both the aux port and the aux device are functioning, see if the
1534          * device can be enabled. NOTE: when enabled, the device will start
1535          * sending data; we shall immediately disable the device once we know
1536          * the device can be enabled.
1537          */
1538         if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1539                 /* MOUSE ERROR */
1540                 recover_from_error(sc->kbdc);
1541                 if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1542                         restore_controller(sc->kbdc, command_byte);
1543                 if (verbose)
1544                         printf("psm%d: failed to enable the aux device.\n",
1545                             unit);
1546                 endprobe(ENXIO);
1547         }
1548
1549         /* save the default values after reset */
1550         if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1551                 sc->dflt_mode.rate = sc->mode.rate = stat[2];
1552                 sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1553         } else {
1554                 sc->dflt_mode.rate = sc->mode.rate = -1;
1555                 sc->dflt_mode.resolution = sc->mode.resolution = -1;
1556         }
1557
1558         /* hardware information */
1559         sc->hw.iftype = MOUSE_IF_PS2;
1560
1561         /* verify the device is a mouse */
1562         sc->hw.hwid = get_aux_id(sc->kbdc);
1563         if (!is_a_mouse(sc->hw.hwid)) {
1564                 if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1565                         restore_controller(sc->kbdc, command_byte);
1566                 if (verbose)
1567                         printf("psm%d: unknown device type (%d).\n", unit,
1568                             sc->hw.hwid);
1569                 endprobe(ENXIO);
1570         }
1571         switch (sc->hw.hwid) {
1572         case PSM_BALLPOINT_ID:
1573                 sc->hw.type = MOUSE_TRACKBALL;
1574                 break;
1575         case PSM_MOUSE_ID:
1576         case PSM_INTELLI_ID:
1577         case PSM_EXPLORER_ID:
1578         case PSM_4DMOUSE_ID:
1579         case PSM_4DPLUS_ID:
1580                 sc->hw.type = MOUSE_MOUSE;
1581                 break;
1582         default:
1583                 sc->hw.type = MOUSE_UNKNOWN;
1584                 break;
1585         }
1586
1587         if (sc->config & PSM_CONFIG_NOIDPROBE) {
1588                 sc->hw.buttons = 2;
1589                 i = GENERIC_MOUSE_ENTRY;
1590         } else {
1591                 /* # of buttons */
1592                 sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1593
1594                 /* other parameters */
1595                 for (i = 0; vendortype[i].probefunc != NULL; ++i)
1596                         if ((*vendortype[i].probefunc)(sc, PROBE)) {
1597                                 if (verbose >= 2)
1598                                         printf("psm%d: found %s\n", unit,
1599                                             model_name(vendortype[i].model));
1600                                 break;
1601                         }
1602         }
1603
1604         sc->hw.model = vendortype[i].model;
1605
1606         sc->dflt_mode.level = PSM_LEVEL_BASE;
1607         sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1608         sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1609         if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1610                 sc->dflt_mode.syncmask[0] = 0;
1611         else
1612                 sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1613         if (sc->config & PSM_CONFIG_FORCETAP)
1614                 sc->dflt_mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1615         sc->dflt_mode.syncmask[1] = 0;  /* syncbits */
1616         sc->mode = sc->dflt_mode;
1617         sc->mode.packetsize = vendortype[i].packetsize;
1618
1619         /* set mouse parameters */
1620 #if 0
1621         /*
1622          * A version of Logitech FirstMouse+ won't report wheel movement,
1623          * if SET_DEFAULTS is sent...  Don't use this command.
1624          * This fix was found by Takashi Nishida.
1625          */
1626         i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1627         if (verbose >= 2)
1628                 printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1629 #endif
1630         if (sc->config & PSM_CONFIG_RESOLUTION)
1631                 sc->mode.resolution =
1632                     set_mouse_resolution(sc->kbdc,
1633                     (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1634         else if (sc->mode.resolution >= 0)
1635                 sc->mode.resolution =
1636                     set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1637         if (sc->mode.rate > 0)
1638                 sc->mode.rate =
1639                     set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1640         set_mouse_scaling(sc->kbdc, 1);
1641
1642         /* Record sync on the next data packet we see. */
1643         sc->flags |= PSM_NEED_SYNCBITS;
1644
1645         /* just check the status of the mouse */
1646         /*
1647          * NOTE: XXX there are some arcane controller/mouse combinations out
1648          * there, which hung the controller unless there is data transmission
1649          * after ACK from the mouse.
1650          */
1651         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1652                 printf("psm%d: failed to get status.\n", unit);
1653         else {
1654                 /*
1655                  * When in its native mode, some mice operate with different
1656                  * default parameters than in the PS/2 compatible mode.
1657                  */
1658                 sc->dflt_mode.rate = sc->mode.rate = stat[2];
1659                 sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1660         }
1661
1662         /* disable the aux port for now... */
1663         if (!set_controller_command_byte(sc->kbdc,
1664             KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1665             (command_byte & KBD_KBD_CONTROL_BITS) |
1666             KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1667                 /*
1668                  * this is CONTROLLER ERROR; I don't know the proper way to
1669                  * recover from this error...
1670                  */
1671                 if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc))
1672                         restore_controller(sc->kbdc, command_byte);
1673                 printf("psm%d: unable to set the command byte.\n", unit);
1674                 endprobe(ENXIO);
1675         }
1676
1677         /* done */
1678         kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1679         kbdc_lock(sc->kbdc, FALSE);
1680         return (0);
1681 }
1682
1683 #ifdef EVDEV_SUPPORT
1684 /* Values are taken from Linux drivers for userland software compatibility */
1685 #define PS2_MOUSE_VENDOR                0x0002
1686 #define PS2_MOUSE_GENERIC_PRODUCT       0x0001
1687 #define PS2_MOUSE_SYNAPTICS_NAME        "SynPS/2 Synaptics TouchPad"
1688 #define PS2_MOUSE_SYNAPTICS_PRODUCT     0x0007
1689 #define PS2_MOUSE_TRACKPOINT_NAME       "TPPS/2 IBM TrackPoint"
1690 #define PS2_MOUSE_TRACKPOINT_PRODUCT    0x000A
1691 #define PS2_MOUSE_ELANTECH_NAME         "ETPS/2 Elantech Touchpad"
1692 #define PS2_MOUSE_ELANTECH_ST_NAME      "ETPS/2 Elantech TrackPoint"
1693 #define PS2_MOUSE_ELANTECH_PRODUCT      0x000E
1694
1695 #define ABSINFO_END     { ABS_CNT, 0, 0, 0 }
1696
1697 static void
1698 psm_support_abs_bulk(struct evdev_dev *evdev, const uint16_t info[][4])
1699 {
1700         size_t i;
1701
1702         for (i = 0; info[i][0] != ABS_CNT; i++)
1703                 evdev_support_abs(evdev, info[i][0], 0, info[i][1], info[i][2],
1704                     0, 0, info[i][3]);
1705 }
1706
1707 static void
1708 psm_push_mt_finger(struct psm_softc *sc, int id, const finger_t *f)
1709 {
1710         int y = sc->synhw.minimumYCoord + sc->synhw.maximumYCoord - f->y;
1711
1712         evdev_push_abs(sc->evdev_a, ABS_MT_SLOT, id);
1713         evdev_push_abs(sc->evdev_a, ABS_MT_TRACKING_ID, id);
1714         evdev_push_abs(sc->evdev_a, ABS_MT_POSITION_X, f->x);
1715         evdev_push_abs(sc->evdev_a, ABS_MT_POSITION_Y, y);
1716         evdev_push_abs(sc->evdev_a, ABS_MT_PRESSURE, f->p);
1717 }
1718
1719 static void
1720 psm_push_st_finger(struct psm_softc *sc, const finger_t *f)
1721 {
1722         int y = sc->synhw.minimumYCoord + sc->synhw.maximumYCoord - f->y;
1723
1724         evdev_push_abs(sc->evdev_a, ABS_X, f->x);
1725         evdev_push_abs(sc->evdev_a, ABS_Y, y);
1726         evdev_push_abs(sc->evdev_a, ABS_PRESSURE, f->p);
1727         if (sc->synhw.capPalmDetect)
1728                 evdev_push_abs(sc->evdev_a, ABS_TOOL_WIDTH, f->w);
1729 }
1730
1731 static void
1732 psm_release_mt_slot(struct evdev_dev *evdev, int32_t slot)
1733 {
1734
1735         evdev_push_abs(evdev, ABS_MT_SLOT, slot);
1736         evdev_push_abs(evdev, ABS_MT_TRACKING_ID, -1);
1737 }
1738
1739 static int
1740 psm_register(device_t dev, int model_code)
1741 {
1742         struct psm_softc *sc = device_get_softc(dev);
1743         struct evdev_dev *evdev_r;
1744         int error, i, nbuttons, nwheels, product;
1745         bool is_pointing_stick;
1746         const char *name;
1747
1748         name = model_name(model_code);
1749         nbuttons = sc->hw.buttons;
1750         product = PS2_MOUSE_GENERIC_PRODUCT;
1751         nwheels = 0;
1752         is_pointing_stick = false;
1753
1754         switch (model_code) {
1755         case MOUSE_MODEL_TRACKPOINT:
1756                 name = PS2_MOUSE_TRACKPOINT_NAME;
1757                 product = PS2_MOUSE_TRACKPOINT_PRODUCT;
1758                 nbuttons = 3;
1759                 is_pointing_stick = true;
1760                 break;
1761
1762         case MOUSE_MODEL_ELANTECH:
1763                 name = PS2_MOUSE_ELANTECH_ST_NAME;
1764                 product = PS2_MOUSE_ELANTECH_PRODUCT;
1765                 nbuttons = 3;
1766                 is_pointing_stick = true;
1767                 break;
1768
1769         case MOUSE_MODEL_MOUSEMANPLUS:
1770         case MOUSE_MODEL_4D:
1771                 nwheels = 2;
1772                 break;
1773
1774         case MOUSE_MODEL_EXPLORER:
1775         case MOUSE_MODEL_INTELLI:
1776         case MOUSE_MODEL_NET:
1777         case MOUSE_MODEL_NETSCROLL:
1778         case MOUSE_MODEL_4DPLUS:
1779                 nwheels = 1;
1780                 break;
1781         }
1782
1783         evdev_r = evdev_alloc();
1784         evdev_set_name(evdev_r, name);
1785         evdev_set_phys(evdev_r, device_get_nameunit(dev));
1786         evdev_set_id(evdev_r, BUS_I8042, PS2_MOUSE_VENDOR, product, 0);
1787         evdev_set_methods(evdev_r, sc, &psm_ev_methods_r);
1788
1789         evdev_support_prop(evdev_r, INPUT_PROP_POINTER);
1790         if (is_pointing_stick)
1791                 evdev_support_prop(evdev_r, INPUT_PROP_POINTING_STICK);
1792         evdev_support_event(evdev_r, EV_SYN);
1793         evdev_support_event(evdev_r, EV_KEY);
1794         evdev_support_event(evdev_r, EV_REL);
1795         evdev_support_rel(evdev_r, REL_X);
1796         evdev_support_rel(evdev_r, REL_Y);
1797         switch (nwheels) {
1798         case 2:
1799                 evdev_support_rel(evdev_r, REL_HWHEEL);
1800                 /* FALLTHROUGH */
1801         case 1:
1802                 evdev_support_rel(evdev_r, REL_WHEEL);
1803         }
1804         for (i = 0; i < nbuttons; i++)
1805                 evdev_support_key(evdev_r, BTN_MOUSE + i);
1806
1807         error = evdev_register_mtx(evdev_r, &Giant);
1808         if (error)
1809                 evdev_free(evdev_r);
1810         else
1811                 sc->evdev_r = evdev_r;
1812         return (error);
1813 }
1814
1815 static int
1816 psm_register_synaptics(device_t dev)
1817 {
1818         struct psm_softc *sc = device_get_softc(dev);
1819         const uint16_t synaptics_absinfo_st[][4] = {
1820                 { ABS_X,                sc->synhw.minimumXCoord,
1821                     sc->synhw.maximumXCoord, sc->synhw.infoXupmm },
1822                 { ABS_Y,                sc->synhw.minimumYCoord,
1823                     sc->synhw.maximumYCoord, sc->synhw.infoYupmm },
1824                 { ABS_PRESSURE,         0, ELANTECH_FINGER_MAX_P, 0 },
1825                 ABSINFO_END,
1826         };
1827         const uint16_t synaptics_absinfo_mt[][4] = {
1828                 { ABS_MT_SLOT,          0, PSM_FINGERS-1, 0},
1829                 { ABS_MT_TRACKING_ID,   -1, PSM_FINGERS-1, 0},
1830                 { ABS_MT_POSITION_X,    sc->synhw.minimumXCoord,
1831                     sc->synhw.maximumXCoord, sc->synhw.infoXupmm },
1832                 { ABS_MT_POSITION_Y,    sc->synhw.minimumYCoord,
1833                     sc->synhw.maximumYCoord, sc->synhw.infoYupmm },
1834                 { ABS_MT_PRESSURE,      0, ELANTECH_FINGER_MAX_P, 0 },
1835                 ABSINFO_END,
1836         };
1837         struct evdev_dev *evdev_a;
1838         int error, i, guest_model;
1839
1840         evdev_a = evdev_alloc();
1841         evdev_set_name(evdev_a, PS2_MOUSE_SYNAPTICS_NAME);
1842         evdev_set_phys(evdev_a, device_get_nameunit(dev));
1843         evdev_set_id(evdev_a, BUS_I8042, PS2_MOUSE_VENDOR,
1844             PS2_MOUSE_SYNAPTICS_PRODUCT, 0);
1845         evdev_set_methods(evdev_a, sc, &psm_ev_methods_a);
1846
1847         evdev_support_event(evdev_a, EV_SYN);
1848         evdev_support_event(evdev_a, EV_KEY);
1849         evdev_support_event(evdev_a, EV_ABS);
1850         evdev_support_prop(evdev_a, INPUT_PROP_POINTER);
1851         if (sc->synhw.capAdvancedGestures)
1852                 evdev_support_prop(evdev_a, INPUT_PROP_SEMI_MT);
1853         if (sc->synhw.capClickPad)
1854                 evdev_support_prop(evdev_a, INPUT_PROP_BUTTONPAD);
1855         if (sc->synhw.capClickPad && sc->synhw.topButtonPad)
1856                 evdev_support_prop(evdev_a, INPUT_PROP_TOPBUTTONPAD);
1857         evdev_support_key(evdev_a, BTN_TOUCH);
1858         evdev_support_nfingers(evdev_a, sc->synhw.capReportsV ? 5 : 3);
1859         psm_support_abs_bulk(evdev_a, synaptics_absinfo_st);
1860         if (sc->synhw.capAdvancedGestures || sc->synhw.capReportsV)
1861                 psm_support_abs_bulk(evdev_a, synaptics_absinfo_mt);
1862         if (sc->synhw.capPalmDetect)
1863                 evdev_support_abs(evdev_a, ABS_TOOL_WIDTH, 0, 0, 15, 0, 0, 0);
1864         evdev_support_key(evdev_a, BTN_LEFT);
1865         if (!sc->synhw.capClickPad) {
1866                 evdev_support_key(evdev_a, BTN_RIGHT);
1867                 if (sc->synhw.capExtended && sc->synhw.capMiddle)
1868                         evdev_support_key(evdev_a, BTN_MIDDLE);
1869         }
1870         if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
1871                 evdev_support_key(evdev_a, BTN_BACK);
1872                 evdev_support_key(evdev_a, BTN_FORWARD);
1873         }
1874         if (sc->synhw.capExtended && (sc->synhw.nExtendedButtons > 0))
1875                 for (i = 0; i < sc->synhw.nExtendedButtons; i++)
1876                         evdev_support_key(evdev_a, BTN_0 + i);
1877
1878         error = evdev_register_mtx(evdev_a, &Giant);
1879         if (!error && (sc->synhw.capPassthrough || sc->muxport != PSM_NOMUX)) {
1880                 guest_model = sc->tpinfo.sysctl_tree != NULL ?
1881                     MOUSE_MODEL_TRACKPOINT : MOUSE_MODEL_GENERIC;
1882                 error = psm_register(dev, guest_model);
1883         }
1884         if (error)
1885                 evdev_free(evdev_a);
1886         else
1887                 sc->evdev_a = evdev_a;
1888         return (error);
1889 }
1890
1891 static int
1892 psm_register_elantech(device_t dev)
1893 {
1894         struct psm_softc *sc = device_get_softc(dev);
1895         const uint16_t elantech_absinfo[][4] = {
1896                 { ABS_X,                0, sc->elanhw.sizex,
1897                                            sc->elanhw.dpmmx },
1898                 { ABS_Y,                0, sc->elanhw.sizey,
1899                                            sc->elanhw.dpmmy },
1900                 { ABS_PRESSURE,         0, ELANTECH_FINGER_MAX_P, 0 },
1901                 { ABS_TOOL_WIDTH,       0, ELANTECH_FINGER_MAX_W, 0 },
1902                 { ABS_MT_SLOT,          0, ELANTECH_MAX_FINGERS - 1, 0 },
1903                 { ABS_MT_TRACKING_ID,   -1, ELANTECH_MAX_FINGERS - 1, 0 },
1904                 { ABS_MT_POSITION_X,    0, sc->elanhw.sizex,
1905                                            sc->elanhw.dpmmx },
1906                 { ABS_MT_POSITION_Y,    0, sc->elanhw.sizey,
1907                                            sc->elanhw.dpmmy },
1908                 { ABS_MT_PRESSURE,      0, ELANTECH_FINGER_MAX_P, 0 },
1909                 { ABS_MT_TOUCH_MAJOR,   0, ELANTECH_FINGER_MAX_W *
1910                                            sc->elanhw.dptracex, 0 },
1911                 ABSINFO_END,
1912         };
1913         struct evdev_dev *evdev_a;
1914         int error;
1915
1916         evdev_a = evdev_alloc();
1917         evdev_set_name(evdev_a, PS2_MOUSE_ELANTECH_NAME);
1918         evdev_set_phys(evdev_a, device_get_nameunit(dev));
1919         evdev_set_id(evdev_a, BUS_I8042, PS2_MOUSE_VENDOR,
1920             PS2_MOUSE_ELANTECH_PRODUCT, 0);
1921         evdev_set_methods(evdev_a, sc, &psm_ev_methods_a);
1922
1923         evdev_support_event(evdev_a, EV_SYN);
1924         evdev_support_event(evdev_a, EV_KEY);
1925         evdev_support_event(evdev_a, EV_ABS);
1926         evdev_support_prop(evdev_a, INPUT_PROP_POINTER);
1927         if (sc->elanhw.issemimt)
1928                 evdev_support_prop(evdev_a, INPUT_PROP_SEMI_MT);
1929         if (sc->elanhw.isclickpad)
1930                 evdev_support_prop(evdev_a, INPUT_PROP_BUTTONPAD);
1931         evdev_support_key(evdev_a, BTN_TOUCH);
1932         evdev_support_nfingers(evdev_a, ELANTECH_MAX_FINGERS);
1933         evdev_support_key(evdev_a, BTN_LEFT);
1934         if (!sc->elanhw.isclickpad)
1935                 evdev_support_key(evdev_a, BTN_RIGHT);
1936         psm_support_abs_bulk(evdev_a, elantech_absinfo);
1937
1938         error = evdev_register_mtx(evdev_a, &Giant);
1939         if (!error && sc->elanhw.hastrackpoint)
1940                 error = psm_register(dev, MOUSE_MODEL_ELANTECH);
1941         if (error)
1942                 evdev_free(evdev_a);
1943         else
1944                 sc->evdev_a = evdev_a;
1945         return (error);
1946 }
1947 #endif
1948
1949 static int
1950 psmattach(device_t dev)
1951 {
1952         struct make_dev_args mda;
1953         int unit = device_get_unit(dev);
1954         struct psm_softc *sc = device_get_softc(dev);
1955         int error;
1956         int rid;
1957
1958         /* Setup initial state */
1959         sc->state = PSM_VALID;
1960         callout_init(&sc->callout, 0);
1961         callout_init(&sc->softcallout, 0);
1962
1963         /* Setup our interrupt handler */
1964         rid = KBDC_RID_AUX;
1965         sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1966         if (sc->intr == NULL)
1967                 return (ENXIO);
1968         error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, NULL, psmintr, sc,
1969             &sc->ih);
1970         if (error)
1971                 goto out;
1972
1973         /* Done */
1974         make_dev_args_init(&mda);
1975         mda.mda_devsw = &psm_cdevsw;
1976         mda.mda_mode = 0666;
1977         mda.mda_si_drv1 = sc;
1978
1979         if ((error = make_dev_s(&mda, &sc->dev, "psm%d", unit)) != 0)
1980                 goto out;
1981         if ((error = make_dev_s(&mda, &sc->bdev, "bpsm%d", unit)) != 0)
1982                 goto out;
1983
1984 #ifdef EVDEV_SUPPORT
1985         switch (sc->hw.model) {
1986         case MOUSE_MODEL_SYNAPTICS:
1987                 error = psm_register_synaptics(dev);
1988                 break;
1989
1990         case MOUSE_MODEL_ELANTECH:
1991                 error = psm_register_elantech(dev);
1992                 break;
1993
1994         default:
1995                 error = psm_register(dev, sc->hw.model);
1996         }
1997
1998         if (error)
1999                 goto out;
2000 #endif
2001
2002         /* Some touchpad devices need full reinitialization after suspend. */
2003         switch (sc->hw.model) {
2004         case MOUSE_MODEL_SYNAPTICS:
2005         case MOUSE_MODEL_GLIDEPOINT:
2006         case MOUSE_MODEL_VERSAPAD:
2007         case MOUSE_MODEL_ELANTECH:
2008                 sc->config |= PSM_CONFIG_INITAFTERSUSPEND;
2009                 break;
2010         default:
2011                 if (sc->synhw.infoMajor >= 4 || sc->tphw > 0)
2012                         sc->config |= PSM_CONFIG_INITAFTERSUSPEND;
2013                 break;
2014         }
2015
2016         /* Elantech trackpad`s sync bit differs from touchpad`s one */
2017         if (sc->hw.model == MOUSE_MODEL_ELANTECH &&
2018             (sc->elanhw.hascrc || sc->elanhw.hastrackpoint)) {
2019                 sc->config |= PSM_CONFIG_NOCHECKSYNC;
2020                 sc->flags &= ~PSM_NEED_SYNCBITS;
2021         }
2022
2023         if (!verbose)
2024                 printf("psm%d: model %s, device ID %d\n",
2025                     unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
2026         else {
2027                 printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
2028                     unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff,
2029                     sc->hw.hwid >> 8, sc->hw.buttons);
2030                 printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
2031                     unit, sc->config, sc->flags, sc->mode.packetsize);
2032                 printf("psm%d: syncmask:%02x, syncbits:%02x%s\n",
2033                     unit, sc->mode.syncmask[0], sc->mode.syncmask[1],
2034                     sc->config & PSM_CONFIG_NOCHECKSYNC ? " (sync not checked)" : "");
2035         }
2036
2037         if (bootverbose)
2038                 --verbose;
2039
2040 out:
2041         if (error != 0) {
2042                 bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
2043                 if (sc->dev != NULL)
2044                         destroy_dev(sc->dev);
2045                 if (sc->bdev != NULL)
2046                         destroy_dev(sc->bdev);
2047         }
2048         return (error);
2049 }
2050
2051 static int
2052 psmdetach(device_t dev)
2053 {
2054         struct psm_softc *sc;
2055         int rid;
2056
2057         sc = device_get_softc(dev);
2058         if (sc->state & PSM_OPEN)
2059                 return (EBUSY);
2060
2061 #ifdef EVDEV_SUPPORT
2062         evdev_free(sc->evdev_r);
2063         evdev_free(sc->evdev_a);
2064 #endif
2065
2066         rid = KBDC_RID_AUX;
2067         bus_teardown_intr(dev, sc->intr, sc->ih);
2068         bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
2069
2070         destroy_dev(sc->dev);
2071         destroy_dev(sc->bdev);
2072
2073         callout_drain(&sc->callout);
2074         callout_drain(&sc->softcallout);
2075
2076         return (0);
2077 }
2078
2079 #ifdef EVDEV_SUPPORT
2080 static int
2081 psm_ev_open_r(struct evdev_dev *evdev)
2082 {
2083         struct psm_softc *sc = evdev_get_softc(evdev);
2084         int err = 0;
2085
2086         /* Get device data */
2087         if ((sc->state & PSM_VALID) == 0) {
2088                 /* the device is no longer valid/functioning */
2089                 return (ENXIO);
2090         }
2091
2092         if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_A)))
2093                 err = psmopen(sc);
2094
2095         if (err == 0)
2096                 sc->state |= PSM_EV_OPEN_R;
2097
2098         return (err);
2099 }
2100
2101 static int
2102 psm_ev_close_r(struct evdev_dev *evdev)
2103 {
2104         struct psm_softc *sc = evdev_get_softc(evdev);
2105         int err = 0;
2106
2107         sc->state &= ~PSM_EV_OPEN_R;
2108
2109         if (sc->state & (PSM_OPEN | PSM_EV_OPEN_A))
2110                 return (0);
2111
2112         if (sc->state & PSM_VALID)
2113                 err = psmclose(sc);
2114
2115         return (err);
2116 }
2117
2118 static int
2119 psm_ev_open_a(struct evdev_dev *evdev)
2120 {
2121         struct psm_softc *sc = evdev_get_softc(evdev);
2122         int err = 0;
2123
2124         /* Get device data */
2125         if ((sc->state & PSM_VALID) == 0) {
2126                 /* the device is no longer valid/functioning */
2127                 return (ENXIO);
2128         }
2129
2130         if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_R)))
2131                 err = psmopen(sc);
2132
2133         if (err == 0)
2134                 sc->state |= PSM_EV_OPEN_A;
2135
2136         return (err);
2137 }
2138
2139 static int
2140 psm_ev_close_a(struct evdev_dev *evdev)
2141 {
2142         struct psm_softc *sc = evdev_get_softc(evdev);
2143         int err = 0;
2144
2145         sc->state &= ~PSM_EV_OPEN_A;
2146
2147         if (sc->state & (PSM_OPEN | PSM_EV_OPEN_R))
2148                 return (0);
2149
2150         if (sc->state & PSM_VALID)
2151                 err = psmclose(sc);
2152
2153         return (err);
2154 }
2155 #endif
2156
2157 static int
2158 psm_cdev_open(struct cdev *dev, int flag, int fmt, struct thread *td)
2159 {
2160         struct psm_softc *sc;
2161         int err = 0;
2162
2163         /* Get device data */
2164         sc = dev->si_drv1;
2165         if ((sc == NULL) || (sc->state & PSM_VALID) == 0) {
2166                 /* the device is no longer valid/functioning */
2167                 return (ENXIO);
2168         }
2169
2170         /* Disallow multiple opens */
2171         if (sc->state & PSM_OPEN)
2172                 return (EBUSY);
2173
2174         device_busy(devclass_get_device(psm_devclass, sc->unit));
2175
2176 #ifdef EVDEV_SUPPORT
2177         /* Already opened by evdev */
2178         if (!(sc->state & (PSM_EV_OPEN_R | PSM_EV_OPEN_A)))
2179 #endif
2180                 err = psmopen(sc);
2181
2182         if (err == 0)
2183                 sc->state |= PSM_OPEN;
2184         else
2185                 device_unbusy(devclass_get_device(psm_devclass, sc->unit));
2186
2187         return (err);
2188 }
2189
2190 static int
2191 psm_cdev_close(struct cdev *dev, int flag, int fmt, struct thread *td)
2192 {
2193         struct psm_softc *sc;
2194         int err = 0;
2195
2196         /* Get device data */
2197         sc = dev->si_drv1;
2198         if ((sc == NULL) || (sc->state & PSM_VALID) == 0) {
2199                 /* the device is no longer valid/functioning */
2200                 return (ENXIO);
2201         }
2202
2203 #ifdef EVDEV_SUPPORT
2204         /* Still opened by evdev */
2205         if (!(sc->state & (PSM_EV_OPEN_R | PSM_EV_OPEN_A)))
2206 #endif
2207                 err = psmclose(sc);
2208
2209         if (err == 0) {
2210                 sc->state &= ~PSM_OPEN;
2211                 /* clean up and sigio requests */
2212                 if (sc->async != NULL) {
2213                         funsetown(&sc->async);
2214                         sc->async = NULL;
2215                 }
2216                 device_unbusy(devclass_get_device(psm_devclass, sc->unit));
2217         }
2218
2219         return (err);
2220 }
2221
2222 static int
2223 psmopen(struct psm_softc *sc)
2224 {
2225         int command_byte;
2226         int err;
2227         int s;
2228
2229         /* Initialize state */
2230         sc->mode.level = sc->dflt_mode.level;
2231         sc->mode.protocol = sc->dflt_mode.protocol;
2232         sc->watchdog = FALSE;
2233         sc->async = NULL;
2234
2235         /* flush the event queue */
2236         sc->queue.count = 0;
2237         sc->queue.head = 0;
2238         sc->queue.tail = 0;
2239         sc->status.flags = 0;
2240         sc->status.button = 0;
2241         sc->status.obutton = 0;
2242         sc->status.dx = 0;
2243         sc->status.dy = 0;
2244         sc->status.dz = 0;
2245         sc->button = 0;
2246         sc->pqueue_start = 0;
2247         sc->pqueue_end = 0;
2248
2249         /* empty input buffer */
2250         flushpackets(sc);
2251         sc->syncerrors = 0;
2252         sc->pkterrors = 0;
2253
2254         /* don't let timeout routines in the keyboard driver to poll the kbdc */
2255         if (!kbdc_lock(sc->kbdc, TRUE))
2256                 return (EIO);
2257
2258         /* save the current controller command byte */
2259         s = spltty();
2260         command_byte = get_controller_command_byte(sc->kbdc);
2261
2262         /* enable the aux port and temporalily disable the keyboard */
2263         if (command_byte == -1 || !set_controller_command_byte(sc->kbdc,
2264             kbdc_get_device_mask(sc->kbdc),
2265             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
2266             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2267                 /* CONTROLLER ERROR; do you know how to get out of this? */
2268                 kbdc_lock(sc->kbdc, FALSE);
2269                 splx(s);
2270                 log(LOG_ERR,
2271                     "psm%d: unable to set the command byte (psmopen).\n",
2272                     sc->unit);
2273                 return (EIO);
2274         }
2275         /*
2276          * Now that the keyboard controller is told not to generate
2277          * the keyboard and mouse interrupts, call `splx()' to allow
2278          * the other tty interrupts. The clock interrupt may also occur,
2279          * but timeout routines will be blocked by the poll flag set
2280          * via `kbdc_lock()'
2281          */
2282         splx(s);
2283
2284         /* enable the mouse device */
2285         err = doopen(sc, command_byte);
2286
2287         /* done */
2288         kbdc_lock(sc->kbdc, FALSE);
2289         return (err);
2290 }
2291
2292 static int
2293 psmclose(struct psm_softc *sc)
2294 {
2295         int stat[3];
2296         int command_byte;
2297         int s;
2298
2299         /* don't let timeout routines in the keyboard driver to poll the kbdc */
2300         if (!kbdc_lock(sc->kbdc, TRUE))
2301                 return (EIO);
2302
2303         /* save the current controller command byte */
2304         s = spltty();
2305         command_byte = get_controller_command_byte(sc->kbdc);
2306         if (command_byte == -1) {
2307                 kbdc_lock(sc->kbdc, FALSE);
2308                 splx(s);
2309                 return (EIO);
2310         }
2311
2312         /* disable the aux interrupt and temporalily disable the keyboard */
2313         if (!set_controller_command_byte(sc->kbdc,
2314             kbdc_get_device_mask(sc->kbdc),
2315             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
2316             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2317                 log(LOG_ERR,
2318                     "psm%d: failed to disable the aux int (psmclose).\n",
2319                     sc->unit);
2320                 /* CONTROLLER ERROR;
2321                  * NOTE: we shall force our way through. Because the only
2322                  * ill effect we shall see is that we may not be able
2323                  * to read ACK from the mouse, and it doesn't matter much
2324                  * so long as the mouse will accept the DISABLE command.
2325                  */
2326         }
2327         splx(s);
2328
2329         /* stop the watchdog timer */
2330         callout_stop(&sc->callout);
2331
2332         /* remove anything left in the output buffer */
2333         empty_aux_buffer(sc->kbdc, 10);
2334
2335         /* disable the aux device, port and interrupt */
2336         if (sc->state & PSM_VALID) {
2337                 if (!disable_aux_dev(sc->kbdc)) {
2338                         /* MOUSE ERROR;
2339                          * NOTE: we don't return (error) and continue,
2340                          * pretending we have successfully disabled the device.
2341                          * It's OK because the interrupt routine will discard
2342                          * any data from the mouse hereafter.
2343                          */
2344                         log(LOG_ERR,
2345                             "psm%d: failed to disable the device (psmclose).\n",
2346                             sc->unit);
2347                 }
2348
2349                 if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
2350                         log(LOG_DEBUG,
2351                             "psm%d: failed to get status (psmclose).\n",
2352                             sc->unit);
2353         }
2354
2355         if (!set_controller_command_byte(sc->kbdc,
2356             kbdc_get_device_mask(sc->kbdc),
2357             (command_byte & KBD_KBD_CONTROL_BITS) |
2358             KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2359                 /*
2360                  * CONTROLLER ERROR;
2361                  * we shall ignore this error; see the above comment.
2362                  */
2363                 log(LOG_ERR,
2364                     "psm%d: failed to disable the aux port (psmclose).\n",
2365                     sc->unit);
2366         }
2367
2368         /* remove anything left in the output buffer */
2369         empty_aux_buffer(sc->kbdc, 10);
2370
2371         /* close is almost always successful */
2372         kbdc_lock(sc->kbdc, FALSE);
2373         return (0);
2374 }
2375
2376 static int
2377 tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status,
2378     u_char *buf)
2379 {
2380         static u_char butmapps2[8] = {
2381                 0,
2382                 MOUSE_PS2_BUTTON1DOWN,
2383                 MOUSE_PS2_BUTTON2DOWN,
2384                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
2385                 MOUSE_PS2_BUTTON3DOWN,
2386                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
2387                 MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
2388                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN |
2389                     MOUSE_PS2_BUTTON3DOWN,
2390         };
2391         static u_char butmapmsc[8] = {
2392                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP |
2393                     MOUSE_MSC_BUTTON3UP,
2394                 MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
2395                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
2396                 MOUSE_MSC_BUTTON3UP,
2397                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
2398                 MOUSE_MSC_BUTTON2UP,
2399                 MOUSE_MSC_BUTTON1UP,
2400                 0,
2401         };
2402         int mapped;
2403         int i;
2404
2405         if (sc->mode.level == PSM_LEVEL_BASE) {
2406                 mapped = status->button & ~MOUSE_BUTTON4DOWN;
2407                 if (status->button & MOUSE_BUTTON4DOWN)
2408                         mapped |= MOUSE_BUTTON1DOWN;
2409                 status->button = mapped;
2410                 buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
2411                 i = imax(imin(status->dx, 255), -256);
2412                 if (i < 0)
2413                         buf[0] |= MOUSE_PS2_XNEG;
2414                 buf[1] = i;
2415                 i = imax(imin(status->dy, 255), -256);
2416                 if (i < 0)
2417                         buf[0] |= MOUSE_PS2_YNEG;
2418                 buf[2] = i;
2419                 return (MOUSE_PS2_PACKETSIZE);
2420         } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
2421                 buf[0] = MOUSE_MSC_SYNC |
2422                     butmapmsc[status->button & MOUSE_STDBUTTONS];
2423                 i = imax(imin(status->dx, 255), -256);
2424                 buf[1] = i >> 1;
2425                 buf[3] = i - buf[1];
2426                 i = imax(imin(status->dy, 255), -256);
2427                 buf[2] = i >> 1;
2428                 buf[4] = i - buf[2];
2429                 i = imax(imin(status->dz, 127), -128);
2430                 buf[5] = (i >> 1) & 0x7f;
2431                 buf[6] = (i - (i >> 1)) & 0x7f;
2432                 buf[7] = (~status->button >> 3) & 0x7f;
2433                 return (MOUSE_SYS_PACKETSIZE);
2434         }
2435         return (pb->inputbytes);
2436 }
2437
2438 static int
2439 psmread(struct cdev *dev, struct uio *uio, int flag)
2440 {
2441         struct psm_softc *sc = dev->si_drv1;
2442         u_char buf[PSM_SMALLBUFSIZE];
2443         int error = 0;
2444         int s;
2445         int l;
2446
2447         if ((sc->state & PSM_VALID) == 0)
2448                 return (EIO);
2449
2450         /* block until mouse activity occurred */
2451         s = spltty();
2452         while (sc->queue.count <= 0) {
2453                 if (dev != sc->bdev) {
2454                         splx(s);
2455                         return (EWOULDBLOCK);
2456                 }
2457                 sc->state |= PSM_ASLP;
2458                 error = tsleep(sc, PZERO | PCATCH, "psmrea", 0);
2459                 sc->state &= ~PSM_ASLP;
2460                 if (error) {
2461                         splx(s);
2462                         return (error);
2463                 } else if ((sc->state & PSM_VALID) == 0) {
2464                         /* the device disappeared! */
2465                         splx(s);
2466                         return (EIO);
2467                 }
2468         }
2469         splx(s);
2470
2471         /* copy data to the user land */
2472         while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
2473                 s = spltty();
2474                 l = imin(sc->queue.count, uio->uio_resid);
2475                 if (l > sizeof(buf))
2476                         l = sizeof(buf);
2477                 if (l > sizeof(sc->queue.buf) - sc->queue.head) {
2478                         bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
2479                             sizeof(sc->queue.buf) - sc->queue.head);
2480                         bcopy(&sc->queue.buf[0],
2481                             &buf[sizeof(sc->queue.buf) - sc->queue.head],
2482                             l - (sizeof(sc->queue.buf) - sc->queue.head));
2483                 } else
2484                         bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
2485                 sc->queue.count -= l;
2486                 sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
2487                 splx(s);
2488                 error = uiomove(buf, l, uio);
2489                 if (error)
2490                         break;
2491         }
2492
2493         return (error);
2494 }
2495
2496 static int
2497 block_mouse_data(struct psm_softc *sc, int *c)
2498 {
2499         int s;
2500
2501         if (!kbdc_lock(sc->kbdc, TRUE))
2502                 return (EIO);
2503
2504         s = spltty();
2505         *c = get_controller_command_byte(sc->kbdc);
2506         if ((*c == -1) || !set_controller_command_byte(sc->kbdc,
2507             kbdc_get_device_mask(sc->kbdc),
2508             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
2509             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2510                 /* this is CONTROLLER ERROR */
2511                 splx(s);
2512                 kbdc_lock(sc->kbdc, FALSE);
2513                 return (EIO);
2514         }
2515
2516         /*
2517          * The device may be in the middle of status data transmission.
2518          * The transmission will be interrupted, thus, incomplete status
2519          * data must be discarded. Although the aux interrupt is disabled
2520          * at the keyboard controller level, at most one aux interrupt
2521          * may have already been pending and a data byte is in the
2522          * output buffer; throw it away. Note that the second argument
2523          * to `empty_aux_buffer()' is zero, so that the call will just
2524          * flush the internal queue.
2525          * `psmintr()' will be invoked after `splx()' if an interrupt is
2526          * pending; it will see no data and returns immediately.
2527          */
2528         empty_aux_buffer(sc->kbdc, 0);          /* flush the queue */
2529         read_aux_data_no_wait(sc->kbdc);        /* throw away data if any */
2530         flushpackets(sc);
2531         splx(s);
2532
2533         return (0);
2534 }
2535
2536 static void
2537 dropqueue(struct psm_softc *sc)
2538 {
2539
2540         sc->queue.count = 0;
2541         sc->queue.head = 0;
2542         sc->queue.tail = 0;
2543         if ((sc->state & PSM_SOFTARMED) != 0) {
2544                 sc->state &= ~PSM_SOFTARMED;
2545                 callout_stop(&sc->softcallout);
2546         }
2547         sc->pqueue_start = sc->pqueue_end;
2548 }
2549
2550 static void
2551 flushpackets(struct psm_softc *sc)
2552 {
2553
2554         dropqueue(sc);
2555         bzero(&sc->pqueue, sizeof(sc->pqueue));
2556 }
2557
2558 static int
2559 unblock_mouse_data(struct psm_softc *sc, int c)
2560 {
2561         int error = 0;
2562
2563         /*
2564          * We may have seen a part of status data during `set_mouse_XXX()'.
2565          * they have been queued; flush it.
2566          */
2567         empty_aux_buffer(sc->kbdc, 0);
2568
2569         /* restore ports and interrupt */
2570         if (!set_controller_command_byte(sc->kbdc,
2571             kbdc_get_device_mask(sc->kbdc),
2572             c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
2573                 /*
2574                  * CONTROLLER ERROR; this is serious, we may have
2575                  * been left with the inaccessible keyboard and
2576                  * the disabled mouse interrupt.
2577                  */
2578                 error = EIO;
2579         }
2580
2581         kbdc_lock(sc->kbdc, FALSE);
2582         return (error);
2583 }
2584
2585 static int
2586 psmwrite(struct cdev *dev, struct uio *uio, int flag)
2587 {
2588         struct psm_softc *sc = dev->si_drv1;
2589         u_char buf[PSM_SMALLBUFSIZE];
2590         int error = 0, i, l;
2591
2592         if ((sc->state & PSM_VALID) == 0)
2593                 return (EIO);
2594
2595         if (sc->mode.level < PSM_LEVEL_NATIVE)
2596                 return (ENODEV);
2597
2598         /* copy data from the user land */
2599         while (uio->uio_resid > 0) {
2600                 l = imin(PSM_SMALLBUFSIZE, uio->uio_resid);
2601                 error = uiomove(buf, l, uio);
2602                 if (error)
2603                         break;
2604                 for (i = 0; i < l; i++) {
2605                         VLOG(4, (LOG_DEBUG, "psm: cmd 0x%x\n", buf[i]));
2606                         if (!write_aux_command(sc->kbdc, buf[i])) {
2607                                 VLOG(2, (LOG_DEBUG,
2608                                     "psm: cmd 0x%x failed.\n", buf[i]));
2609                                 return (reinitialize(sc, FALSE));
2610                         }
2611                 }
2612         }
2613
2614         return (error);
2615 }
2616
2617 static int
2618 psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2619     struct thread *td)
2620 {
2621         struct psm_softc *sc = dev->si_drv1;
2622         mousemode_t mode;
2623         mousestatus_t status;
2624         mousedata_t *data;
2625         int stat[3];
2626         int command_byte;
2627         int error = 0;
2628         int s;
2629
2630         /* Perform IOCTL command */
2631         switch (cmd) {
2632
2633         case OLD_MOUSE_GETHWINFO:
2634                 s = spltty();
2635                 ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
2636                 ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
2637                 ((old_mousehw_t *)addr)->type = sc->hw.type;
2638                 ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
2639                 splx(s);
2640                 break;
2641
2642         case MOUSE_GETHWINFO:
2643                 s = spltty();
2644                 *(mousehw_t *)addr = sc->hw;
2645                 if (sc->mode.level == PSM_LEVEL_BASE)
2646                         ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
2647                 splx(s);
2648                 break;
2649
2650         case MOUSE_SYN_GETHWINFO:
2651                 s = spltty();
2652                 if (sc->synhw.infoMajor >= 4)
2653                         *(synapticshw_t *)addr = sc->synhw;
2654                 else
2655                         error = EINVAL;
2656                 splx(s);
2657                 break;
2658
2659         case OLD_MOUSE_GETMODE:
2660                 s = spltty();
2661                 switch (sc->mode.level) {
2662                 case PSM_LEVEL_BASE:
2663                         ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2664                         break;
2665                 case PSM_LEVEL_STANDARD:
2666                         ((old_mousemode_t *)addr)->protocol =
2667                             MOUSE_PROTO_SYSMOUSE;
2668                         break;
2669                 case PSM_LEVEL_NATIVE:
2670                         ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2671                         break;
2672                 }
2673                 ((old_mousemode_t *)addr)->rate = sc->mode.rate;
2674                 ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
2675                 ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
2676                 splx(s);
2677                 break;
2678
2679         case MOUSE_GETMODE:
2680                 s = spltty();
2681                 *(mousemode_t *)addr = sc->mode;
2682                 if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2683                         ((mousemode_t *)addr)->syncmask[0] = 0;
2684                         ((mousemode_t *)addr)->syncmask[1] = 0;
2685                 }
2686                 ((mousemode_t *)addr)->resolution =
2687                         MOUSE_RES_LOW - sc->mode.resolution;
2688                 switch (sc->mode.level) {
2689                 case PSM_LEVEL_BASE:
2690                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2691                         ((mousemode_t *)addr)->packetsize =
2692                             MOUSE_PS2_PACKETSIZE;
2693                         break;
2694                 case PSM_LEVEL_STANDARD:
2695                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
2696                         ((mousemode_t *)addr)->packetsize =
2697                             MOUSE_SYS_PACKETSIZE;
2698                         ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
2699                         ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
2700                         break;
2701                 case PSM_LEVEL_NATIVE:
2702                         /* FIXME: this isn't quite correct... XXX */
2703                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2704                         break;
2705                 }
2706                 splx(s);
2707                 break;
2708
2709         case OLD_MOUSE_SETMODE:
2710         case MOUSE_SETMODE:
2711                 if (cmd == OLD_MOUSE_SETMODE) {
2712                         mode.rate = ((old_mousemode_t *)addr)->rate;
2713                         /*
2714                          * resolution  old I/F   new I/F
2715                          * default        0         0
2716                          * low            1        -2
2717                          * medium low     2        -3
2718                          * medium high    3        -4
2719                          * high           4        -5
2720                          */
2721                         if (((old_mousemode_t *)addr)->resolution > 0)
2722                                 mode.resolution =
2723                                     -((old_mousemode_t *)addr)->resolution - 1;
2724                         else
2725                                 mode.resolution = 0;
2726                         mode.accelfactor =
2727                             ((old_mousemode_t *)addr)->accelfactor;
2728                         mode.level = -1;
2729                 } else
2730                         mode = *(mousemode_t *)addr;
2731
2732                 /* adjust and validate parameters. */
2733                 if (mode.rate > UCHAR_MAX)
2734                         return (EINVAL);
2735                 if (mode.rate == 0)
2736                         mode.rate = sc->dflt_mode.rate;
2737                 else if (mode.rate == -1)
2738                         /* don't change the current setting */
2739                         ;
2740                 else if (mode.rate < 0)
2741                         return (EINVAL);
2742                 if (mode.resolution >= UCHAR_MAX)
2743                         return (EINVAL);
2744                 if (mode.resolution >= 200)
2745                         mode.resolution = MOUSE_RES_HIGH;
2746                 else if (mode.resolution >= 100)
2747                         mode.resolution = MOUSE_RES_MEDIUMHIGH;
2748                 else if (mode.resolution >= 50)
2749                         mode.resolution = MOUSE_RES_MEDIUMLOW;
2750                 else if (mode.resolution > 0)
2751                         mode.resolution = MOUSE_RES_LOW;
2752                 if (mode.resolution == MOUSE_RES_DEFAULT)
2753                         mode.resolution = sc->dflt_mode.resolution;
2754                 else if (mode.resolution == -1)
2755                         /* don't change the current setting */
2756                         ;
2757                 else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2758                         mode.resolution = MOUSE_RES_LOW - mode.resolution;
2759                 if (mode.level == -1)
2760                         /* don't change the current setting */
2761                         mode.level = sc->mode.level;
2762                 else if ((mode.level < PSM_LEVEL_MIN) ||
2763                     (mode.level > PSM_LEVEL_MAX))
2764                         return (EINVAL);
2765                 if (mode.accelfactor == -1)
2766                         /* don't change the current setting */
2767                         mode.accelfactor = sc->mode.accelfactor;
2768                 else if (mode.accelfactor < 0)
2769                         return (EINVAL);
2770
2771                 /* don't allow anybody to poll the keyboard controller */
2772                 error = block_mouse_data(sc, &command_byte);
2773                 if (error)
2774                         return (error);
2775
2776                 /* set mouse parameters */
2777                 if (mode.rate > 0)
2778                         mode.rate = set_mouse_sampling_rate(sc->kbdc,
2779                             mode.rate);
2780                 if (mode.resolution >= 0)
2781                         mode.resolution =
2782                             set_mouse_resolution(sc->kbdc, mode.resolution);
2783                 set_mouse_scaling(sc->kbdc, 1);
2784                 get_mouse_status(sc->kbdc, stat, 0, 3);
2785
2786                 s = spltty();
2787                 sc->mode.rate = mode.rate;
2788                 sc->mode.resolution = mode.resolution;
2789                 sc->mode.accelfactor = mode.accelfactor;
2790                 sc->mode.level = mode.level;
2791                 splx(s);
2792
2793                 unblock_mouse_data(sc, command_byte);
2794                 break;
2795
2796         case MOUSE_GETLEVEL:
2797                 *(int *)addr = sc->mode.level;
2798                 break;
2799
2800         case MOUSE_SETLEVEL:
2801                 if ((*(int *)addr < PSM_LEVEL_MIN) ||
2802                     (*(int *)addr > PSM_LEVEL_MAX))
2803                         return (EINVAL);
2804                 sc->mode.level = *(int *)addr;
2805                 break;
2806
2807         case MOUSE_GETSTATUS:
2808                 s = spltty();
2809                 status = sc->status;
2810                 sc->status.flags = 0;
2811                 sc->status.obutton = sc->status.button;
2812                 sc->status.button = 0;
2813                 sc->status.dx = 0;
2814                 sc->status.dy = 0;
2815                 sc->status.dz = 0;
2816                 splx(s);
2817                 *(mousestatus_t *)addr = status;
2818                 break;
2819
2820         case MOUSE_READSTATE:
2821         case MOUSE_READDATA:
2822                 data = (mousedata_t *)addr;
2823                 if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
2824                         return (EINVAL);
2825
2826                 error = block_mouse_data(sc, &command_byte);
2827                 if (error)
2828                         return (error);
2829                 if ((data->len = get_mouse_status(sc->kbdc, data->buf,
2830                     (cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
2831                         error = EIO;
2832                 unblock_mouse_data(sc, command_byte);
2833                 break;
2834
2835 #if (defined(MOUSE_SETRESOLUTION))
2836         case MOUSE_SETRESOLUTION:
2837                 mode.resolution = *(int *)addr;
2838                 if (mode.resolution >= UCHAR_MAX)
2839                         return (EINVAL);
2840                 else if (mode.resolution >= 200)
2841                         mode.resolution = MOUSE_RES_HIGH;
2842                 else if (mode.resolution >= 100)
2843                         mode.resolution = MOUSE_RES_MEDIUMHIGH;
2844                 else if (mode.resolution >= 50)
2845                         mode.resolution = MOUSE_RES_MEDIUMLOW;
2846                 else if (mode.resolution > 0)
2847                         mode.resolution = MOUSE_RES_LOW;
2848                 if (mode.resolution == MOUSE_RES_DEFAULT)
2849                         mode.resolution = sc->dflt_mode.resolution;
2850                 else if (mode.resolution == -1)
2851                         mode.resolution = sc->mode.resolution;
2852                 else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2853                         mode.resolution = MOUSE_RES_LOW - mode.resolution;
2854
2855                 error = block_mouse_data(sc, &command_byte);
2856                 if (error)
2857                         return (error);
2858                 sc->mode.resolution =
2859                     set_mouse_resolution(sc->kbdc, mode.resolution);
2860                 if (sc->mode.resolution != mode.resolution)
2861                         error = EIO;
2862                 unblock_mouse_data(sc, command_byte);
2863                 break;
2864 #endif /* MOUSE_SETRESOLUTION */
2865
2866 #if (defined(MOUSE_SETRATE))
2867         case MOUSE_SETRATE:
2868                 mode.rate = *(int *)addr;
2869                 if (mode.rate > UCHAR_MAX)
2870                         return (EINVAL);
2871                 if (mode.rate == 0)
2872                         mode.rate = sc->dflt_mode.rate;
2873                 else if (mode.rate < 0)
2874                         mode.rate = sc->mode.rate;
2875
2876                 error = block_mouse_data(sc, &command_byte);
2877                 if (error)
2878                         return (error);
2879                 sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
2880                 if (sc->mode.rate != mode.rate)
2881                         error = EIO;
2882                 unblock_mouse_data(sc, command_byte);
2883                 break;
2884 #endif /* MOUSE_SETRATE */
2885
2886 #if (defined(MOUSE_SETSCALING))
2887         case MOUSE_SETSCALING:
2888                 if ((*(int *)addr <= 0) || (*(int *)addr > 2))
2889                         return (EINVAL);
2890
2891                 error = block_mouse_data(sc, &command_byte);
2892                 if (error)
2893                         return (error);
2894                 if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
2895                         error = EIO;
2896                 unblock_mouse_data(sc, command_byte);
2897                 break;
2898 #endif /* MOUSE_SETSCALING */
2899
2900 #if (defined(MOUSE_GETHWID))
2901         case MOUSE_GETHWID:
2902                 error = block_mouse_data(sc, &command_byte);
2903                 if (error)
2904                         return (error);
2905                 sc->hw.hwid &= ~0x00ff;
2906                 sc->hw.hwid |= get_aux_id(sc->kbdc);
2907                 *(int *)addr = sc->hw.hwid & 0x00ff;
2908                 unblock_mouse_data(sc, command_byte);
2909                 break;
2910 #endif /* MOUSE_GETHWID */
2911
2912         case FIONBIO:
2913         case FIOASYNC:
2914                 break;
2915         case FIOSETOWN:
2916                 error = fsetown(*(int *)addr, &sc->async);
2917                 break;
2918         case FIOGETOWN:
2919                 *(int *) addr = fgetown(&sc->async);
2920                 break;
2921         default:
2922                 return (ENOTTY);
2923         }
2924
2925         return (error);
2926 }
2927
2928 static void
2929 psmtimeout(void *arg)
2930 {
2931         struct psm_softc *sc;
2932         int s;
2933
2934         sc = (struct psm_softc *)arg;
2935         s = spltty();
2936         if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
2937                 VLOG(6, (LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit));
2938                 psmintr(sc);
2939                 kbdc_lock(sc->kbdc, FALSE);
2940         }
2941         sc->watchdog = TRUE;
2942         splx(s);
2943         callout_reset(&sc->callout, hz, psmtimeout, sc);
2944 }
2945
2946 /* Add all sysctls under the debug.psm and hw.psm nodes */
2947 static SYSCTL_NODE(_debug, OID_AUTO, psm, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2948     "ps/2 mouse");
2949 static SYSCTL_NODE(_hw, OID_AUTO, psm, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2950     "ps/2 mouse");
2951
2952 SYSCTL_INT(_debug_psm, OID_AUTO, loglevel, CTLFLAG_RWTUN, &verbose, 0,
2953     "Verbosity level");
2954
2955 static int psmhz = 20;
2956 SYSCTL_INT(_debug_psm, OID_AUTO, hz, CTLFLAG_RW, &psmhz, 0,
2957     "Frequency of the softcallout (in hz)");
2958 static int psmerrsecs = 2;
2959 SYSCTL_INT(_debug_psm, OID_AUTO, errsecs, CTLFLAG_RW, &psmerrsecs, 0,
2960     "Number of seconds during which packets will dropped after a sync error");
2961 static int psmerrusecs = 0;
2962 SYSCTL_INT(_debug_psm, OID_AUTO, errusecs, CTLFLAG_RW, &psmerrusecs, 0,
2963     "Microseconds to add to psmerrsecs");
2964 static int psmsecs = 0;
2965 SYSCTL_INT(_debug_psm, OID_AUTO, secs, CTLFLAG_RW, &psmsecs, 0,
2966     "Max number of seconds between soft interrupts");
2967 static int psmusecs = 500000;
2968 SYSCTL_INT(_debug_psm, OID_AUTO, usecs, CTLFLAG_RW, &psmusecs, 0,
2969     "Microseconds to add to psmsecs");
2970 static int pkterrthresh = 2;
2971 SYSCTL_INT(_debug_psm, OID_AUTO, pkterrthresh, CTLFLAG_RW, &pkterrthresh, 0,
2972     "Number of error packets allowed before reinitializing the mouse");
2973
2974 SYSCTL_INT(_hw_psm, OID_AUTO, tap_enabled, CTLFLAG_RWTUN, &tap_enabled, 0,
2975     "Enable tap and drag gestures");
2976 static int tap_threshold = PSM_TAP_THRESHOLD;
2977 SYSCTL_INT(_hw_psm, OID_AUTO, tap_threshold, CTLFLAG_RW, &tap_threshold, 0,
2978     "Button tap threshold");
2979 static int tap_timeout = PSM_TAP_TIMEOUT;
2980 SYSCTL_INT(_hw_psm, OID_AUTO, tap_timeout, CTLFLAG_RW, &tap_timeout, 0,
2981     "Tap timeout for touchpads");
2982
2983 /* Tunables */
2984 SYSCTL_INT(_hw_psm, OID_AUTO, synaptics_support, CTLFLAG_RDTUN,
2985     &synaptics_support, 0, "Enable support for Synaptics touchpads");
2986
2987 SYSCTL_INT(_hw_psm, OID_AUTO, trackpoint_support, CTLFLAG_RDTUN,
2988     &trackpoint_support, 0, "Enable support for IBM/Lenovo TrackPoint");
2989
2990 SYSCTL_INT(_hw_psm, OID_AUTO, elantech_support, CTLFLAG_RDTUN,
2991     &elantech_support, 0, "Enable support for Elantech touchpads");
2992
2993 SYSCTL_INT(_hw_psm, OID_AUTO, mux_disabled, CTLFLAG_RDTUN,
2994     &mux_disabled, 0, "Disable active multiplexing");
2995
2996 static void
2997 psmintr(void *arg)
2998 {
2999         struct psm_softc *sc = arg;
3000         struct timeval now;
3001         int c;
3002         packetbuf_t *pb;
3003
3004         if (aux_mux_is_enabled(sc->kbdc))
3005                 VLOG(2, (LOG_DEBUG, "psmintr: active multiplexing mode is not "
3006                     "supported!\n"));
3007
3008         /* read until there is nothing to read */
3009         while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
3010                 pb = &sc->pqueue[sc->pqueue_end];
3011
3012                 /* discard the byte if the device is not open */
3013                 if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_R | PSM_EV_OPEN_A)))
3014                         continue;
3015
3016                 getmicrouptime(&now);
3017                 if ((pb->inputbytes > 0) &&
3018                     timevalcmp(&now, &sc->inputtimeout, >)) {
3019                         VLOG(3, (LOG_DEBUG, "psmintr: delay too long; "
3020                             "resetting byte count\n"));
3021                         pb->inputbytes = 0;
3022                         sc->syncerrors = 0;
3023                         sc->pkterrors = 0;
3024                 }
3025                 sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT / 1000000;
3026                 sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT % 1000000;
3027                 timevaladd(&sc->inputtimeout, &now);
3028
3029                 pb->ipacket[pb->inputbytes++] = c;
3030
3031                 if (sc->mode.level == PSM_LEVEL_NATIVE) {
3032                         VLOG(4, (LOG_DEBUG, "psmintr: %02x\n", pb->ipacket[0]));
3033                         sc->syncerrors = 0;
3034                         sc->pkterrors = 0;
3035                         goto next;
3036                 } else {
3037                         if (pb->inputbytes < sc->mode.packetsize)
3038                                 continue;
3039
3040                         VLOG(4, (LOG_DEBUG,
3041                             "psmintr: %02x %02x %02x %02x %02x %02x\n",
3042                             pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
3043                             pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
3044                 }
3045
3046                 c = pb->ipacket[0];
3047
3048                 if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
3049                         sc->mode.syncmask[1] = (c & sc->mode.syncmask[0]);
3050                         sc->flags &= ~PSM_NEED_SYNCBITS;
3051                         VLOG(2, (LOG_DEBUG,
3052                             "psmintr: Sync bytes now %04x,%04x\n",
3053                             sc->mode.syncmask[0], sc->mode.syncmask[1]));
3054                 } else if ((sc->config & PSM_CONFIG_NOCHECKSYNC) == 0 &&
3055                     (c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
3056                         VLOG(3, (LOG_DEBUG, "psmintr: out of sync "
3057                             "(%04x != %04x) %d cmds since last error.\n",
3058                             c & sc->mode.syncmask[0], sc->mode.syncmask[1],
3059                             sc->cmdcount - sc->lasterr));
3060                         sc->lasterr = sc->cmdcount;
3061                         /*
3062                          * The sync byte test is a weak measure of packet
3063                          * validity.  Conservatively discard any input yet
3064                          * to be seen by userland when we detect a sync
3065                          * error since there is a good chance some of
3066                          * the queued packets have undetected errors.
3067                          */
3068                         dropqueue(sc);
3069                         if (sc->syncerrors == 0)
3070                                 sc->pkterrors++;
3071                         ++sc->syncerrors;
3072                         sc->lastinputerr = now;
3073                         if (sc->syncerrors >= sc->mode.packetsize * 2 ||
3074                             sc->pkterrors >= pkterrthresh) {
3075                                 /*
3076                                  * If we've failed to find a single sync byte
3077                                  * in 2 packets worth of data, or we've seen
3078                                  * persistent packet errors during the
3079                                  * validation period, reinitialize the mouse
3080                                  * in hopes of returning it to the expected
3081                                  * mode.
3082                                  */
3083                                 VLOG(3, (LOG_DEBUG,
3084                                     "psmintr: reset the mouse.\n"));
3085                                 reinitialize(sc, TRUE);
3086                         } else if (sc->syncerrors == sc->mode.packetsize) {
3087                                 /*
3088                                  * Try a soft reset after searching for a sync
3089                                  * byte through a packet length of bytes.
3090                                  */
3091                                 VLOG(3, (LOG_DEBUG,
3092                                     "psmintr: re-enable the mouse.\n"));
3093                                 pb->inputbytes = 0;
3094                                 disable_aux_dev(sc->kbdc);
3095                                 enable_aux_dev(sc->kbdc);
3096                         } else {
3097                                 VLOG(3, (LOG_DEBUG,
3098                                     "psmintr: discard a byte (%d)\n",
3099                                     sc->syncerrors));
3100                                 pb->inputbytes--;
3101                                 bcopy(&pb->ipacket[1], &pb->ipacket[0],
3102                                     pb->inputbytes);
3103                         }
3104                         continue;
3105                 }
3106
3107                 /*
3108                  * We have what appears to be a valid packet.
3109                  * Reset the error counters.
3110                  */
3111                 sc->syncerrors = 0;
3112
3113                 /*
3114                  * Drop even good packets if they occur within a timeout
3115                  * period of a sync error.  This allows the detection of
3116                  * a change in the mouse's packet mode without exposing
3117                  * erratic mouse behavior to the user.  Some KVMs forget
3118                  * enhanced mouse modes during switch events.
3119                  */
3120                 if (!timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs,
3121                     &now)) {
3122                         pb->inputbytes = 0;
3123                         continue;
3124                 }
3125
3126                 /*
3127                  * Now that we're out of the validation period, reset
3128                  * the packet error count.
3129                  */
3130                 sc->pkterrors = 0;
3131
3132                 sc->cmdcount++;
3133 next:
3134                 if (++sc->pqueue_end >= PSM_PACKETQUEUE)
3135                         sc->pqueue_end = 0;
3136                 /*
3137                  * If we've filled the queue then call the softintr ourselves,
3138                  * otherwise schedule the interrupt for later.
3139                  */
3140                 if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
3141                     (sc->pqueue_end == sc->pqueue_start)) {
3142                         if ((sc->state & PSM_SOFTARMED) != 0) {
3143                                 sc->state &= ~PSM_SOFTARMED;
3144                                 callout_stop(&sc->softcallout);
3145                         }
3146                         psmsoftintr(arg);
3147                 } else if ((sc->state & PSM_SOFTARMED) == 0) {
3148                         sc->state |= PSM_SOFTARMED;
3149                         callout_reset(&sc->softcallout,
3150                             psmhz < 1 ? 1 : (hz/psmhz), psmsoftintr, arg);
3151                 }
3152         }
3153 }
3154
3155 static void
3156 proc_mmanplus(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
3157     int *x, int *y, int *z)
3158 {
3159
3160         /*
3161          * PS2++ protocol packet
3162          *
3163          *          b7 b6 b5 b4 b3 b2 b1 b0
3164          * byte 1:  *  1  p3 p2 1  *  *  *
3165          * byte 2:  c1 c2 p1 p0 d1 d0 1  0
3166          *
3167          * p3-p0: packet type
3168          * c1, c2: c1 & c2 == 1, if p2 == 0
3169          *         c1 & c2 == 0, if p2 == 1
3170          *
3171          * packet type: 0 (device type)
3172          * See comments in enable_mmanplus() below.
3173          *
3174          * packet type: 1 (wheel data)
3175          *
3176          *          b7 b6 b5 b4 b3 b2 b1 b0
3177          * byte 3:  h  *  B5 B4 s  d2 d1 d0
3178          *
3179          * h: 1, if horizontal roller data
3180          *    0, if vertical roller data
3181          * B4, B5: button 4 and 5
3182          * s: sign bit
3183          * d2-d0: roller data
3184          *
3185          * packet type: 2 (reserved)
3186          */
3187         if (((pb->ipacket[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC) &&
3188             (abs(*x) > 191) && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
3189                 /*
3190                  * the extended data packet encodes button
3191                  * and wheel events
3192                  */
3193                 switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
3194                 case 1:
3195                         /* wheel data packet */
3196                         *x = *y = 0;
3197                         if (pb->ipacket[2] & 0x80) {
3198                                 /* XXX horizontal roller count - ignore it */
3199                                 ;
3200                         } else {
3201                                 /* vertical roller count */
3202                                 *z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG) ?
3203                                     (pb->ipacket[2] & 0x0f) - 16 :
3204                                     (pb->ipacket[2] & 0x0f);
3205                         }
3206                         ms->button |= (pb->ipacket[2] &
3207                             MOUSE_PS2PLUS_BUTTON4DOWN) ?
3208                             MOUSE_BUTTON4DOWN : 0;
3209                         ms->button |= (pb->ipacket[2] &
3210                             MOUSE_PS2PLUS_BUTTON5DOWN) ?
3211                             MOUSE_BUTTON5DOWN : 0;
3212                         break;
3213                 case 2:
3214                         /*
3215                          * this packet type is reserved by
3216                          * Logitech...
3217                          */
3218                         /*
3219                          * IBM ScrollPoint Mouse uses this
3220                          * packet type to encode both vertical
3221                          * and horizontal scroll movement.
3222                          */
3223                         *x = *y = 0;
3224                         /* horizontal count */
3225                         if (pb->ipacket[2] & 0x0f)
3226                                 *z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ?
3227                                     -2 : 2;
3228                         /* vertical count */
3229                         if (pb->ipacket[2] & 0xf0)
3230                                 *z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ?
3231                                     -1 : 1;
3232                         break;
3233                 case 0:
3234                         /* device type packet - shouldn't happen */
3235                         /* FALLTHROUGH */
3236                 default:
3237                         *x = *y = 0;
3238                         ms->button = ms->obutton;
3239                         VLOG(1, (LOG_DEBUG, "psmintr: unknown PS2++ packet "
3240                             "type %d: 0x%02x 0x%02x 0x%02x\n",
3241                             MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
3242                             pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]));
3243                         break;
3244                 }
3245         } else {
3246                 /* preserve button states */
3247                 ms->button |= ms->obutton & MOUSE_EXTBUTTONS;
3248         }
3249 }
3250
3251 static int
3252 proc_synaptics(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
3253     int *x, int *y, int *z)
3254 {
3255         static int touchpad_buttons;
3256         static int guest_buttons;
3257         static int ew_finger_count;
3258         static finger_t f[PSM_FINGERS];
3259         int w, id, nfingers, palm, ewcode, extended_buttons, clickpad_pressed;
3260
3261         extended_buttons = 0;
3262
3263         /* TouchPad PS/2 absolute mode message format with capFourButtons:
3264          *
3265          *  Bits:        7   6   5   4   3   2   1   0 (LSB)
3266          *  ------------------------------------------------
3267          *  ipacket[0]:  1   0  W3  W2   0  W1   R   L
3268          *  ipacket[1]: Yb  Ya  Y9  Y8  Xb  Xa  X9  X8
3269          *  ipacket[2]: Z7  Z6  Z5  Z4  Z3  Z2  Z1  Z0
3270          *  ipacket[3]:  1   1  Yc  Xc   0  W0 D^R U^L
3271          *  ipacket[4]: X7  X6  X5  X4  X3  X2  X1  X0
3272          *  ipacket[5]: Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
3273          *
3274          * Legend:
3275          *  L: left physical mouse button
3276          *  R: right physical mouse button
3277          *  D: down button
3278          *  U: up button
3279          *  W: "wrist" value
3280          *  X: x position
3281          *  Y: y position
3282          *  Z: pressure
3283          *
3284          * Without capFourButtons but with nExtendeButtons and/or capMiddle
3285          *
3286          *  Bits:        7   6   5   4      3      2      1      0 (LSB)
3287          *  ------------------------------------------------------
3288          *  ipacket[3]:  1   1  Yc  Xc      0     W0    E^R    M^L
3289          *  ipacket[4]: X7  X6  X5  X4  X3|b7  X2|b5  X1|b3  X0|b1
3290          *  ipacket[5]: Y7  Y6  Y5  Y4  Y3|b8  Y2|b6  Y1|b4  Y0|b2
3291          *
3292          * Legend:
3293          *  M: Middle physical mouse button
3294          *  E: Extended mouse buttons reported instead of low bits of X and Y
3295          *  b1-b8: Extended mouse buttons
3296          *    Only ((nExtendedButtons + 1) >> 1) bits are used in packet
3297          *    4 and 5, for reading X and Y value they should be zeroed.
3298          *
3299          * Absolute reportable limits:    0 - 6143.
3300          * Typical bezel limits:       1472 - 5472.
3301          * Typical edge marings:       1632 - 5312.
3302          *
3303          * w = 3 Passthrough Packet
3304          *
3305          * Byte 2,5,6 == Byte 1,2,3 of "Guest"
3306          */
3307
3308         if (!synaptics_support)
3309                 return (0);
3310
3311         /* Sanity check for out of sync packets. */
3312         if ((pb->ipacket[0] & 0xc8) != 0x80 ||
3313             (pb->ipacket[3] & 0xc8) != 0xc0)
3314                 return (-1);
3315
3316         *x = *y = 0;
3317         ms->button = ms->obutton;
3318
3319         /*
3320          * Pressure value.
3321          * Interpretation:
3322          *   z = 0      No finger contact
3323          *   z = 10     Finger hovering near the pad
3324          *   z = 30     Very light finger contact
3325          *   z = 80     Normal finger contact
3326          *   z = 110    Very heavy finger contact
3327          *   z = 200    Finger lying flat on pad surface
3328          *   z = 255    Maximum reportable Z
3329          */
3330         *z = pb->ipacket[2];
3331
3332         /*
3333          * Finger width value
3334          * Interpretation:
3335          *   w = 0      Two finger on the pad (capMultiFinger needed)
3336          *   w = 1      Three or more fingers (capMultiFinger needed)
3337          *   w = 2      Pen (instead of finger) (capPen needed)
3338          *   w = 3      Reserved (passthrough?)
3339          *   w = 4-7    Finger of normal width (capPalmDetect needed)
3340          *   w = 8-14   Very wide finger or palm (capPalmDetect needed)
3341          *   w = 15     Maximum reportable width (capPalmDetect needed)
3342          */
3343         /* XXX Is checking capExtended enough? */
3344         if (sc->synhw.capExtended)
3345                 w = ((pb->ipacket[0] & 0x30) >> 2) |
3346                     ((pb->ipacket[0] & 0x04) >> 1) |
3347                     ((pb->ipacket[3] & 0x04) >> 2);
3348         else {
3349                 /* Assume a finger of regular width. */
3350                 w = 4;
3351         }
3352
3353         switch (w) {
3354         case 3:
3355                 /*
3356                  * Handle packets from the guest device. See:
3357                  * Synaptics PS/2 TouchPad Interfacing Guide, Section 5.1
3358                  */
3359                 if (sc->synhw.capPassthrough || sc->muxport != PSM_NOMUX) {
3360                         *x = ((pb->ipacket[1] & 0x10) ?
3361                             pb->ipacket[4] - 256 : pb->ipacket[4]);
3362                         *y = ((pb->ipacket[1] & 0x20) ?
3363                             pb->ipacket[5] - 256 : pb->ipacket[5]);
3364                         *z = 0;
3365
3366                         guest_buttons = 0;
3367                         if (pb->ipacket[1] & 0x01)
3368                                 guest_buttons |= MOUSE_BUTTON1DOWN;
3369                         if (pb->ipacket[1] & 0x04)
3370                                 guest_buttons |= MOUSE_BUTTON2DOWN;
3371                         if (pb->ipacket[1] & 0x02)
3372                                 guest_buttons |= MOUSE_BUTTON3DOWN;
3373 #ifdef EVDEV_SUPPORT
3374                         if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
3375                                 evdev_push_rel(sc->evdev_r, REL_X, *x);
3376                                 evdev_push_rel(sc->evdev_r, REL_Y, -*y);
3377                                 evdev_push_mouse_btn(sc->evdev_r,
3378                                     guest_buttons | sc->extended_buttons);
3379                                 evdev_sync(sc->evdev_r);
3380                         }
3381 #endif
3382                         ms->button = touchpad_buttons | guest_buttons |
3383                             sc->extended_buttons;
3384                 }
3385                 goto SYNAPTICS_END;
3386
3387         case 2:
3388                 /* Handle Extended W mode packets */
3389                 ewcode = (pb->ipacket[5] & 0xf0) >> 4;
3390 #if PSM_FINGERS > 1
3391                 switch (ewcode) {
3392                 case 1:
3393                         /* Secondary finger */
3394                         if (sc->synhw.capAdvancedGestures)
3395                                 f[1] = (finger_t) {
3396                                         .x = (((pb->ipacket[4] & 0x0f) << 8) |
3397                                             pb->ipacket[1]) << 1,
3398                                         .y = (((pb->ipacket[4] & 0xf0) << 4) |
3399                                             pb->ipacket[2]) << 1,
3400                                         .p = ((pb->ipacket[3] & 0x30) |
3401                                             (pb->ipacket[5] & 0x0f)) << 1,
3402                                         .w = PSM_FINGER_DEFAULT_W,
3403                                         .flags = PSM_FINGER_FUZZY,
3404                                 };
3405                         else if (sc->synhw.capReportsV)
3406                                 f[1] = (finger_t) {
3407                                         .x = (((pb->ipacket[4] & 0x0f) << 8) |
3408                                             (pb->ipacket[1] & 0xfe)) << 1,
3409                                         .y = (((pb->ipacket[4] & 0xf0) << 4) |
3410                                             (pb->ipacket[2] & 0xfe)) << 1,
3411                                         .p = ((pb->ipacket[3] & 0x30) |
3412                                             (pb->ipacket[5] & 0x0e)) << 1,
3413                                         .w = (((pb->ipacket[5] & 0x01) << 2) |
3414                                             ((pb->ipacket[2] & 0x01) << 1) |
3415                                             (pb->ipacket[1] & 0x01)) + 8,
3416                                         .flags = PSM_FINGER_FUZZY,
3417                                 };
3418                         break;
3419                 case 2:
3420                         ew_finger_count = pb->ipacket[1] & 0x0f;
3421                 default:
3422                         break;
3423                 }
3424 #endif
3425                 goto SYNAPTICS_END;
3426
3427         case 1:
3428                 if (sc->synhw.capReportsV && ew_finger_count > 3) {
3429                         nfingers = ew_finger_count;
3430                         break;
3431                 }
3432                 /* FALLTHROUGH */
3433         case 0:
3434                 nfingers = w + 2;
3435                 break;
3436
3437         default:
3438                 nfingers = 1;
3439         }
3440
3441         if (sc->syninfo.touchpad_off)
3442                 goto SYNAPTICS_END;
3443
3444         /* Button presses */
3445         touchpad_buttons = 0;
3446         if (pb->ipacket[0] & 0x01)
3447                 touchpad_buttons |= MOUSE_BUTTON1DOWN;
3448         if (pb->ipacket[0] & 0x02)
3449                 touchpad_buttons |= MOUSE_BUTTON3DOWN;
3450
3451         if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
3452                 if ((pb->ipacket[3] ^ pb->ipacket[0]) & 0x01)
3453                         touchpad_buttons |= MOUSE_BUTTON4DOWN;
3454                 if ((pb->ipacket[3] ^ pb->ipacket[0]) & 0x02)
3455                         touchpad_buttons |= MOUSE_BUTTON5DOWN;
3456         } else if (sc->synhw.capExtended && sc->synhw.capMiddle &&
3457             !sc->synhw.capClickPad) {
3458                 /* Middle Button */
3459                 if ((pb->ipacket[0] ^ pb->ipacket[3]) & 0x01)
3460                         touchpad_buttons |= MOUSE_BUTTON2DOWN;
3461         } else if (sc->synhw.capExtended && (sc->synhw.nExtendedButtons > 0)) {
3462                 /* Extended Buttons */
3463                 if ((pb->ipacket[0] ^ pb->ipacket[3]) & 0x02) {
3464                         if (sc->syninfo.directional_scrolls) {
3465                                 if (pb->ipacket[4] & 0x01)
3466                                         extended_buttons |= MOUSE_BUTTON4DOWN;
3467                                 if (pb->ipacket[5] & 0x01)
3468                                         extended_buttons |= MOUSE_BUTTON5DOWN;
3469                                 if (pb->ipacket[4] & 0x02)
3470                                         extended_buttons |= MOUSE_BUTTON6DOWN;
3471                                 if (pb->ipacket[5] & 0x02)
3472                                         extended_buttons |= MOUSE_BUTTON7DOWN;
3473                         } else {
3474                                 if (pb->ipacket[4] & 0x01)
3475                                         extended_buttons |= MOUSE_BUTTON1DOWN;
3476                                 if (pb->ipacket[5] & 0x01)
3477                                         extended_buttons |= MOUSE_BUTTON3DOWN;
3478                                 if (pb->ipacket[4] & 0x02)
3479                                         extended_buttons |= MOUSE_BUTTON2DOWN;
3480                                 sc->extended_buttons = extended_buttons;
3481                         }
3482
3483                         /*
3484                          * Zero out bits used by extended buttons to avoid
3485                          * misinterpretation of the data absolute position.
3486                          *
3487                          * The bits represented by
3488                          *
3489                          *     (nExtendedButtons + 1) >> 1
3490                          *
3491                          * will be masked out in both bytes.
3492                          * The mask for n bits is computed with the formula
3493                          *
3494                          *     (1 << n) - 1
3495                          */
3496                         int maskedbits = 0;
3497                         int mask = 0;
3498                         maskedbits = (sc->synhw.nExtendedButtons + 1) >> 1;
3499                         mask = (1 << maskedbits) - 1;
3500 #ifdef EVDEV_SUPPORT
3501                         int i;
3502                         if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
3503                                 if (sc->synhw.capPassthrough) {
3504                                         evdev_push_mouse_btn(sc->evdev_r,
3505                                                 extended_buttons);
3506                                         evdev_sync(sc->evdev_r);
3507                                 }
3508                                 for (i = 0; i < maskedbits; i++) {
3509                                         evdev_push_key(sc->evdev_a,
3510                                             BTN_0 + i * 2,
3511                                             pb->ipacket[4] & (1 << i));
3512                                         evdev_push_key(sc->evdev_a,
3513                                             BTN_0 + i * 2 + 1,
3514                                             pb->ipacket[5] & (1 << i));
3515                                 }
3516                         }
3517 #endif
3518                         pb->ipacket[4] &= ~(mask);
3519                         pb->ipacket[5] &= ~(mask);
3520                 } else  if (!sc->syninfo.directional_scrolls &&
3521                     !sc->gesture.in_vscroll) {
3522                         /*
3523                          * Keep reporting MOUSE DOWN until we get a new packet
3524                          * indicating otherwise.
3525                          */
3526                         extended_buttons |= sc->extended_buttons;
3527                 }
3528         }
3529
3530         if (sc->synhw.capReportsV && nfingers > 1)
3531                 f[0] = (finger_t) {
3532                         .x = ((pb->ipacket[3] & 0x10) << 8) |
3533                             ((pb->ipacket[1] & 0x0f) << 8) |
3534                             (pb->ipacket[4] & 0xfd),
3535                         .y = ((pb->ipacket[3] & 0x20) << 7) |
3536                             ((pb->ipacket[1] & 0xf0) << 4) |
3537                             (pb->ipacket[5] & 0xfd),
3538                         .p = *z & 0xfe,
3539                         .w = (((pb->ipacket[2] & 0x01) << 2) |
3540                             (pb->ipacket[5] & 0x02) |
3541                             ((pb->ipacket[4] & 0x02) >> 1)) + 8,
3542                         .flags = PSM_FINGER_FUZZY,
3543                 };
3544         else
3545                 f[0] = (finger_t) {
3546                         .x = ((pb->ipacket[3] & 0x10) << 8) |
3547                             ((pb->ipacket[1] & 0x0f) << 8) |
3548                             pb->ipacket[4],
3549                         .y = ((pb->ipacket[3] & 0x20) << 7) |
3550                             ((pb->ipacket[1] & 0xf0) << 4) |
3551                             pb->ipacket[5],
3552                         .p = *z,
3553                         .w = w,
3554                         .flags = nfingers > 1 ? PSM_FINGER_FUZZY : 0,
3555                 };
3556
3557         /* Ignore hovering and unmeasurable touches */
3558         if (f[0].p < sc->syninfo.min_pressure || f[0].x < 2)
3559                 nfingers = 0;
3560
3561         /* Handle ClickPad */
3562         if (sc->synhw.capClickPad) {
3563                 clickpad_pressed = (pb->ipacket[0] ^ pb->ipacket[3]) & 0x01;
3564                 if (sc->synhw.forcePad) {
3565                         /*
3566                          * Forcepads erroneously report button click if there
3567                          * are 2 or more fingers on the touchpad breaking
3568                          * multifinger gestures. To workaround this start
3569                          * reporting a click only after 4 consecutive single
3570                          * touch packets has been received.
3571                          * Skip these packets in case more contacts appear.
3572                          */
3573                         switch (nfingers) {
3574                         case 0:
3575                                 sc->fpcount = 0;
3576                                 break;
3577                         case 1:
3578                                 if (clickpad_pressed && sc->fpcount < INT_MAX)
3579                                         ++sc->fpcount;
3580                                 /* FALLTHROUGH */
3581                         default:
3582                                 if (!clickpad_pressed)
3583                                         sc->fpcount = 0;
3584                                 if (sc->fpcount >= sc->syninfo.window_min)
3585                                         touchpad_buttons |= MOUSE_BUTTON1DOWN;
3586                         }
3587                 } else if (clickpad_pressed)
3588                         touchpad_buttons |= MOUSE_BUTTON1DOWN;
3589         }
3590
3591         for (id = 0; id < PSM_FINGERS; id++)
3592                 if (id >= nfingers)
3593                         PSM_FINGER_RESET(f[id]);
3594
3595 #ifdef EVDEV_SUPPORT
3596         if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
3597                 for (id = 0; id < PSM_FINGERS; id++) {
3598                         if (PSM_FINGER_IS_SET(f[id]))
3599                                 psm_push_mt_finger(sc, id, &f[id]);
3600                         else
3601                                 psm_release_mt_slot(sc->evdev_a, id);
3602                 }
3603                 evdev_push_key(sc->evdev_a, BTN_TOUCH, nfingers > 0);
3604                 evdev_push_nfingers(sc->evdev_a, nfingers);
3605                 if (nfingers > 0)
3606                         psm_push_st_finger(sc, &f[0]);
3607                 else
3608                         evdev_push_abs(sc->evdev_a, ABS_PRESSURE, 0);
3609                 evdev_push_mouse_btn(sc->evdev_a, touchpad_buttons);
3610                 if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
3611                         evdev_push_key(sc->evdev_a, BTN_FORWARD,
3612                             touchpad_buttons & MOUSE_BUTTON4DOWN);
3613                         evdev_push_key(sc->evdev_a, BTN_BACK,
3614                             touchpad_buttons & MOUSE_BUTTON5DOWN);
3615                 }
3616                 evdev_sync(sc->evdev_a);
3617         }
3618 #endif
3619
3620         ms->button = touchpad_buttons;
3621
3622         palm = psmpalmdetect(sc, &f[0], nfingers);
3623
3624         /* Palm detection doesn't terminate the current action. */
3625         if (!palm)
3626                 psmgestures(sc, &f[0], nfingers, ms);
3627
3628         for (id = 0; id < PSM_FINGERS; id++)
3629                 psmsmoother(sc, &f[id], id, ms, x, y);
3630
3631         if (palm) {
3632                 *x = *y = *z = 0;
3633                 ms->button = ms->obutton;
3634                 return (0);
3635         }
3636
3637         ms->button |= extended_buttons | guest_buttons;
3638
3639 SYNAPTICS_END:
3640         /*
3641          * Use the extra buttons as a scrollwheel
3642          *
3643          * XXX X.Org uses the Z axis for vertical wheel only,
3644          * whereas moused(8) understands special values to differ
3645          * vertical and horizontal wheels.
3646          *
3647          * xf86-input-mouse needs therefore a small patch to
3648          * understand these special values. Without it, the
3649          * horizontal wheel acts as a vertical wheel in X.Org.
3650          *
3651          * That's why the horizontal wheel is disabled by
3652          * default for now.
3653          */
3654         if (ms->button & MOUSE_BUTTON4DOWN)
3655                 *z = -1;
3656         else if (ms->button & MOUSE_BUTTON5DOWN)
3657                 *z = 1;
3658         else if (ms->button & MOUSE_BUTTON6DOWN)
3659                 *z = -2;
3660         else if (ms->button & MOUSE_BUTTON7DOWN)
3661                 *z = 2;
3662         else
3663                 *z = 0;
3664         ms->button &= ~(MOUSE_BUTTON4DOWN | MOUSE_BUTTON5DOWN |
3665             MOUSE_BUTTON6DOWN | MOUSE_BUTTON7DOWN);
3666
3667         return (0);
3668 }
3669
3670 static int
3671 proc_synaptics_mux(struct psm_softc *sc, packetbuf_t *pb)
3672 {
3673         int butt;
3674
3675         /*
3676          * Convert 3-byte interleaved mixture of Synaptics and generic mouse
3677          * packets into plain 6-byte Synaptics packet protocol.
3678          * While in hidden multiplexing mode KBC does some editing of the
3679          * packet stream. It remembers the button bits from the last packet
3680          * received from each device, and replaces the button bits of every
3681          * packet with the logical OR of all devices’ most recent button bits.
3682          * This button crosstalk should be filtered out as Synaptics and
3683          * generic mouse encode middle button presses in a different way.
3684          */
3685         switch (pb->ipacket[0] & 0xc0) {
3686         case 0x80:      /* First 3 bytes of Synaptics packet */
3687                 bcopy(pb->ipacket, sc->muxsave, 3);
3688                 /* Compute middle mouse button supression timeout. */
3689                 sc->muxmidtimeout.tv_sec  = 0;
3690                 sc->muxmidtimeout.tv_usec = 50000;      /* ~2-3 ints */
3691                 timevaladd(&sc->muxmidtimeout, &sc->lastsoftintr);
3692                 return (1);
3693
3694         case 0xc0:      /* Second 3 bytes of Synaptics packet */
3695                 /* Join two 3-bytes absolute packets */
3696                 bcopy(pb->ipacket, pb->ipacket + 3, 3);
3697                 bcopy(sc->muxsave, pb->ipacket, 3);
3698                 /* Prefer trackpoint buttons over touchpad's */
3699                 pb->ipacket[0] &= ~(0x08 | sc->muxmsbuttons);
3700                 pb->ipacket[3] &= ~(0x08 | sc->muxmsbuttons);
3701                 butt = (pb->ipacket[3] & 0x03) << 2 | (pb->ipacket[0] & 0x03);
3702                 /* Add hysteresis to remove spurious middle button events */
3703                 if (butt != sc->muxtpbuttons && sc->fpcount < 1) {
3704                         pb->ipacket[0] &= 0xfc;
3705                         pb->ipacket[0] |= sc->muxtpbuttons & 0x03;
3706                         pb->ipacket[3] &= 0xfc;
3707                         pb->ipacket[3] |= sc->muxtpbuttons >> 2 & 0x03;
3708                         ++sc->fpcount;
3709                 } else {
3710                         sc->fpcount = 0;
3711                         sc->muxtpbuttons = butt;
3712                 }
3713                 /* Filter out impossible w induced by middle trackpoint btn */
3714                 if (sc->synhw.capExtended && !sc->synhw.capPassthrough &&
3715                     (pb->ipacket[0] & 0x34) == 0x04 &&
3716                     (pb->ipacket[3] & 0x04) == 0x04) {
3717                         pb->ipacket[0] &= 0xfb;
3718                         pb->ipacket[3] &= 0xfb;
3719                 }
3720                 sc->muxsave[0] &= 0x30;
3721                 break;
3722
3723         default:        /* Generic mouse (Trackpoint) packet */
3724                 /* Filter out middle button events induced by some w values */
3725                 if (sc->muxmsbuttons & 0x03 || pb->ipacket[0] & 0x03 ||
3726                     (timevalcmp(&sc->lastsoftintr, &sc->muxmidtimeout, <=) &&
3727                      (sc->muxsave[0] & 0x30 || sc->muxsave[2] > 8)))
3728                         pb->ipacket[0] &= 0xfb;
3729                 sc->muxmsbuttons = pb->ipacket[0] & 0x07;
3730                 /* Convert to Synaptics pass-through protocol */
3731                 pb->ipacket[4] = pb->ipacket[1];
3732                 pb->ipacket[5] = pb->ipacket[2];
3733                 pb->ipacket[1] = pb->ipacket[0];
3734                 pb->ipacket[2] = 0;
3735                 pb->ipacket[0] = 0x84 | (sc->muxtpbuttons & 0x03);
3736                 pb->ipacket[3] = 0xc4 | (sc->muxtpbuttons >> 2 & 0x03);
3737         }
3738
3739         VLOG(4, (LOG_DEBUG, "synaptics: %02x %02x %02x %02x %02x %02x\n",
3740             pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
3741             pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
3742
3743         pb->inputbytes = MOUSE_SYNAPTICS_PACKETSIZE;
3744         return (0);
3745 }
3746
3747 static int
3748 psmpalmdetect(struct psm_softc *sc, finger_t *f, int nfingers)
3749 {
3750         if (!(
3751             ((sc->synhw.capMultiFinger || sc->synhw.capAdvancedGestures) &&
3752               !sc->synhw.capReportsV && nfingers > 1) ||
3753             (sc->synhw.capReportsV && nfingers > 2) ||
3754             (sc->synhw.capPalmDetect && f->w <= sc->syninfo.max_width) ||
3755             (!sc->synhw.capPalmDetect && f->p <= sc->syninfo.max_pressure) ||
3756             (sc->synhw.capPen && f->flags & PSM_FINGER_IS_PEN))) {
3757                 /*
3758                  * We consider the packet irrelevant for the current
3759                  * action when:
3760                  *  - the width isn't comprised in:
3761                  *    [1; max_width]
3762                  *  - the pressure isn't comprised in:
3763                  *    [min_pressure; max_pressure]
3764                  *  - pen aren't supported but PSM_FINGER_IS_PEN is set
3765                  */
3766                 VLOG(2, (LOG_DEBUG, "synaptics: palm detected! (%d)\n", f->w));
3767                 return (1);
3768         }
3769         return (0);
3770 }
3771
3772 static void
3773 psmgestures(struct psm_softc *sc, finger_t *fingers, int nfingers,
3774     mousestatus_t *ms)
3775 {
3776         smoother_t *smoother;
3777         gesture_t *gest;
3778         finger_t *f;
3779         int y_ok, center_button, center_x, right_button, right_x, i;
3780
3781         f = &fingers[0];
3782         smoother = &sc->smoother[0];
3783         gest = &sc->gesture;
3784
3785         /* Find first active finger. */
3786         if (nfingers > 0) {
3787                 for (i = 0; i < PSM_FINGERS; i++) {
3788                         if (PSM_FINGER_IS_SET(fingers[i])) {
3789                                 f = &fingers[i];
3790                                 smoother = &sc->smoother[i];
3791                                 break;
3792                         }
3793                 }
3794         }
3795
3796         /*
3797          * Check pressure to detect a real wanted action on the
3798          * touchpad.
3799          */
3800         if (f->p >= sc->syninfo.min_pressure) {
3801                 int x0, y0;
3802                 int dxp, dyp;
3803                 int start_x, start_y;
3804                 int queue_len;
3805                 int margin_top, margin_right, margin_bottom, margin_left;
3806                 int window_min, window_max;
3807                 int vscroll_hor_area, vscroll_ver_area;
3808                 int two_finger_scroll;
3809                 int max_x, max_y;
3810                 int three_finger_drag;
3811
3812                 /* Read sysctl. */
3813                 /* XXX Verify values? */
3814                 margin_top = sc->syninfo.margin_top;
3815                 margin_right = sc->syninfo.margin_right;
3816                 margin_bottom = sc->syninfo.margin_bottom;
3817                 margin_left = sc->syninfo.margin_left;
3818                 window_min = sc->syninfo.window_min;
3819                 window_max = sc->syninfo.window_max;
3820                 vscroll_hor_area = sc->syninfo.vscroll_hor_area;
3821                 vscroll_ver_area = sc->syninfo.vscroll_ver_area;
3822                 two_finger_scroll = sc->syninfo.two_finger_scroll;
3823                 max_x = sc->syninfo.max_x;
3824                 max_y = sc->syninfo.max_y;
3825                 three_finger_drag = sc->syninfo.three_finger_drag;
3826                 /* Read current absolute position. */
3827                 x0 = f->x;
3828                 y0 = f->y;
3829
3830                 /*
3831                  * Limit the coordinates to the specified margins because
3832                  * this area isn't very reliable.
3833                  */
3834                 if (x0 <= margin_left)
3835                         x0 = margin_left;
3836                 else if (x0 >= max_x - margin_right)
3837                         x0 = max_x - margin_right;
3838                 if (y0 <= margin_bottom)
3839                         y0 = margin_bottom;
3840                 else if (y0 >= max_y - margin_top)
3841                         y0 = max_y - margin_top;
3842
3843                 VLOG(3, (LOG_DEBUG, "synaptics: ipacket: [%d, %d], %d, %d\n",
3844                     x0, y0, f->p, f->w));
3845
3846                 /*
3847                  * If the action is just beginning, init the structure and
3848                  * compute tap timeout.
3849                  */
3850                 if (!(sc->flags & PSM_FLAGS_FINGERDOWN)) {
3851                         VLOG(3, (LOG_DEBUG, "synaptics: ----\n"));
3852
3853                         /* Initialize queue. */
3854                         gest->window_min = window_min;
3855
3856                         /* Reset pressure peak. */
3857                         gest->zmax = 0;
3858
3859                         /* Reset fingers count. */
3860                         gest->fingers_nb = 0;
3861
3862                         /* Reset virtual scrolling state. */
3863                         gest->in_vscroll = 0;
3864
3865                         /* Compute tap timeout. */
3866                         if (tap_enabled != 0) {
3867                                 gest->taptimeout = (struct timeval) {
3868                                         .tv_sec  = tap_timeout / 1000000,
3869                                         .tv_usec = tap_timeout % 1000000,
3870                                 };
3871                                 timevaladd(
3872                                     &gest->taptimeout, &sc->lastsoftintr);
3873                         } else
3874                                 timevalclear(&gest->taptimeout);
3875
3876                         sc->flags |= PSM_FLAGS_FINGERDOWN;
3877
3878                         /* Smoother has not been reset yet */
3879                         queue_len = 1;
3880                         start_x = x0;
3881                         start_y = y0;
3882                 } else {
3883                         queue_len = smoother->queue_len + 1;
3884                         start_x = smoother->start_x;
3885                         start_y = smoother->start_y;
3886                 }
3887
3888                 /* Process ClickPad softbuttons */
3889                 if (sc->synhw.capClickPad && ms->button & MOUSE_BUTTON1DOWN) {
3890                         y_ok = sc->syninfo.softbuttons_y >= 0 ?
3891                             start_y < sc->syninfo.softbuttons_y :
3892                             start_y > max_y + sc->syninfo.softbuttons_y;
3893
3894                         center_button = MOUSE_BUTTON2DOWN;
3895                         center_x = sc->syninfo.softbutton2_x;
3896                         right_button = MOUSE_BUTTON3DOWN;
3897                         right_x = sc->syninfo.softbutton3_x;
3898
3899                         if (center_x > 0 && right_x > 0 && center_x > right_x) {
3900                                 center_button = MOUSE_BUTTON3DOWN;
3901                                 center_x = sc->syninfo.softbutton3_x;
3902                                 right_button = MOUSE_BUTTON2DOWN;
3903                                 right_x = sc->syninfo.softbutton2_x;
3904                         }
3905
3906                         if (right_x > 0 && start_x > right_x && y_ok)
3907                                 ms->button = (ms->button &
3908                                     ~MOUSE_BUTTON1DOWN) | right_button;
3909                         else if (center_x > 0 && start_x > center_x && y_ok)
3910                                 ms->button = (ms->button &
3911                                     ~MOUSE_BUTTON1DOWN) | center_button;
3912                 }
3913
3914                 /* If in tap-hold or three fingers, add the recorded button. */
3915                 if (gest->in_taphold || (nfingers == 3 && three_finger_drag))
3916                         ms->button |= gest->tap_button;
3917
3918                 /*
3919                  * For tap, we keep the maximum number of fingers and the
3920                  * pressure peak. Also with multiple fingers, we increase
3921                  * the minimum window.
3922                  */
3923                 if (nfingers > 1)
3924                         gest->window_min = window_max;
3925                 gest->fingers_nb = imax(nfingers, gest->fingers_nb);
3926                 gest->zmax = imax(f->p, gest->zmax);
3927
3928                 /* Do we have enough packets to consider this a gesture? */
3929                 if (queue_len < gest->window_min)
3930                         return;
3931
3932                 dyp = -1;
3933                 dxp = -1;
3934
3935                 /* Is a scrolling action occurring? */
3936                 if (!gest->in_taphold && !ms->button &&
3937                     (!gest->in_vscroll || two_finger_scroll)) {
3938                         /*
3939                          * A scrolling action must not conflict with a tap
3940                          * action. Here are the conditions to consider a
3941                          * scrolling action:
3942                          *  - the action in a configurable area
3943                          *  - one of the following:
3944                          *     . the distance between the last packet and the
3945                          *       first should be above a configurable minimum
3946                          *     . tap timed out
3947                          */
3948                         dxp = abs(x0 - start_x);
3949                         dyp = abs(y0 - start_y);
3950
3951                         if (timevalcmp(&sc->lastsoftintr, &gest->taptimeout, >) ||
3952                             dxp >= sc->syninfo.vscroll_min_delta ||
3953                             dyp >= sc->syninfo.vscroll_min_delta) {
3954                                 /*
3955                                  * Handle two finger scrolling.
3956                                  * Note that we don't rely on fingers_nb
3957                                  * as that keeps the maximum number of fingers.
3958                                  */
3959                                 if (two_finger_scroll) {
3960                                         if (nfingers == 2) {
3961                                                 gest->in_vscroll +=
3962                                                     dyp ? 2 : 0;
3963                                                 gest->in_vscroll +=
3964                                                     dxp ? 1 : 0;
3965                                         }
3966                                 } else {
3967                                         /* Check for horizontal scrolling. */
3968                                         if ((vscroll_hor_area > 0 &&
3969                                             start_y <= vscroll_hor_area) ||
3970                                             (vscroll_hor_area < 0 &&
3971                                              start_y >=
3972                                              max_y + vscroll_hor_area))
3973                                                 gest->in_vscroll += 2;
3974
3975                                         /* Check for vertical scrolling. */
3976                                         if ((vscroll_ver_area > 0 &&
3977                                             start_x <= vscroll_ver_area) ||
3978                                             (vscroll_ver_area < 0 &&
3979                                              start_x >=
3980                                              max_x + vscroll_ver_area))
3981                                                 gest->in_vscroll += 1;
3982                                 }
3983
3984                                 /* Avoid conflicts if area overlaps. */
3985                                 if (gest->in_vscroll >= 3)
3986                                         gest->in_vscroll =
3987                                             (dxp > dyp) ? 2 : 1;
3988                         }
3989                 }
3990                 /*
3991                  * Reset two finger scrolling when the number of fingers
3992                  * is different from two or any button is pressed.
3993                  */
3994                 if (two_finger_scroll && gest->in_vscroll != 0 &&
3995                     (nfingers != 2 || ms->button))
3996                         gest->in_vscroll = 0;
3997
3998                 VLOG(5, (LOG_DEBUG,
3999                         "synaptics: virtual scrolling: %s "
4000                         "(direction=%d, dxp=%d, dyp=%d, fingers=%d)\n",
4001                         gest->in_vscroll ? "YES" : "NO",
4002                         gest->in_vscroll, dxp, dyp,
4003                         gest->fingers_nb));
4004
4005         } else if (sc->flags & PSM_FLAGS_FINGERDOWN) {
4006                 /*
4007                  * An action is currently taking place but the pressure
4008                  * dropped under the minimum, putting an end to it.
4009                  */
4010                 int taphold_timeout, dx, dy, tap_max_delta;
4011
4012                 dx = abs(smoother->queue[smoother->queue_cursor].x -
4013                     smoother->start_x);
4014                 dy = abs(smoother->queue[smoother->queue_cursor].y -
4015                     smoother->start_y);
4016
4017                 /* Max delta is disabled for multi-fingers tap. */
4018                 if (gest->fingers_nb > 1)
4019                         tap_max_delta = imax(dx, dy);
4020                 else
4021                         tap_max_delta = sc->syninfo.tap_max_delta;
4022
4023                 sc->flags &= ~PSM_FLAGS_FINGERDOWN;
4024
4025                 /* Check for tap. */
4026                 VLOG(3, (LOG_DEBUG,
4027                     "synaptics: zmax=%d, dx=%d, dy=%d, "
4028                     "delta=%d, fingers=%d, queue=%d\n",
4029                     gest->zmax, dx, dy, tap_max_delta, gest->fingers_nb,
4030                     smoother->queue_len));
4031                 if (!gest->in_vscroll && gest->zmax >= tap_threshold &&
4032                     timevalcmp(&sc->lastsoftintr, &gest->taptimeout, <=) &&
4033                     dx <= tap_max_delta && dy <= tap_max_delta &&
4034                     smoother->queue_len >= sc->syninfo.tap_min_queue) {
4035                         /*
4036                          * We have a tap if:
4037                          *   - the maximum pressure went over tap_threshold
4038                          *   - the action ended before tap_timeout
4039                          *
4040                          * To handle tap-hold, we must delay any button push to
4041                          * the next action.
4042                          */
4043                         if (gest->in_taphold) {
4044                                 /*
4045                                  * This is the second and last tap of a
4046                                  * double tap action, not a tap-hold.
4047                                  */
4048                                 gest->in_taphold = 0;
4049
4050                                 /*
4051                                  * For double-tap to work:
4052                                  *   - no button press is emitted (to
4053                                  *     simulate a button release)
4054                                  *   - PSM_FLAGS_FINGERDOWN is set to
4055                                  *     force the next packet to emit a
4056                                  *     button press)
4057                                  */
4058                                 VLOG(2, (LOG_DEBUG,
4059                                     "synaptics: button RELEASE: %d\n",
4060                                     gest->tap_button));
4061                                 sc->flags |= PSM_FLAGS_FINGERDOWN;
4062
4063                                 /* Schedule button press on next interrupt */
4064                                 sc->idletimeout.tv_sec  = psmhz > 1 ?
4065                                     0 : 1;
4066                                 sc->idletimeout.tv_usec = psmhz > 1 ?
4067                                     1000000 / psmhz : 0;
4068                         } else {
4069                                 /*
4070                                  * This is the first tap: we set the
4071                                  * tap-hold state and notify the button
4072                                  * down event.
4073                                  */
4074                                 gest->in_taphold = 1;
4075                                 taphold_timeout = sc->syninfo.taphold_timeout;
4076                                 gest->taptimeout.tv_sec  = taphold_timeout /
4077                                     1000000;
4078                                 gest->taptimeout.tv_usec = taphold_timeout %
4079                                     1000000;
4080                                 sc->idletimeout = gest->taptimeout;
4081                                 timevaladd(&gest->taptimeout,
4082                                     &sc->lastsoftintr);
4083
4084                                 switch (gest->fingers_nb) {
4085                                 case 3:
4086                                         gest->tap_button =
4087                                             MOUSE_BUTTON2DOWN;
4088                                         break;
4089                                 case 2:
4090                                         gest->tap_button =
4091                                             MOUSE_BUTTON3DOWN;
4092                                         break;
4093                                 default:
4094                                         gest->tap_button =
4095                                             MOUSE_BUTTON1DOWN;
4096                                 }
4097                                 VLOG(2, (LOG_DEBUG,
4098                                     "synaptics: button PRESS: %d\n",
4099                                     gest->tap_button));
4100                                 ms->button |= gest->tap_button;
4101                         }
4102                 } else {
4103                         /*
4104                          * Not enough pressure or timeout: reset
4105                          * tap-hold state.
4106                          */
4107                         if (gest->in_taphold) {
4108                                 VLOG(2, (LOG_DEBUG,
4109                                     "synaptics: button RELEASE: %d\n",
4110                                     gest->tap_button));
4111                                 gest->in_taphold = 0;
4112                         } else {
4113                                 VLOG(2, (LOG_DEBUG,
4114                                     "synaptics: not a tap-hold\n"));
4115                         }
4116                 }
4117         } else if (!(sc->flags & PSM_FLAGS_FINGERDOWN) && gest->in_taphold) {
4118                 /*
4119                  * For a tap-hold to work, the button must remain down at
4120                  * least until timeout (where the in_taphold flags will be
4121                  * cleared) or during the next action.
4122                  */
4123                 if (timevalcmp(&sc->lastsoftintr, &gest->taptimeout, <=)) {
4124                         ms->button |= gest->tap_button;
4125                 } else {
4126                         VLOG(2, (LOG_DEBUG, "synaptics: button RELEASE: %d\n",
4127                             gest->tap_button));
4128                         gest->in_taphold = 0;
4129                 }
4130         }
4131
4132         return;
4133 }
4134
4135 static void
4136 psmsmoother(struct psm_softc *sc, finger_t *f, int smoother_id,
4137     mousestatus_t *ms, int *x, int *y)
4138 {
4139         smoother_t *smoother = &sc->smoother[smoother_id];
4140         gesture_t *gest = &(sc->gesture);
4141
4142         /*
4143          * Check pressure to detect a real wanted action on the
4144          * touchpad.
4145          */
4146         if (f->p >= sc->syninfo.min_pressure) {
4147                 int x0, y0;
4148                 int cursor, peer, window;
4149                 int dx, dy, dxp, dyp;
4150                 int max_width, max_pressure;
4151                 int margin_top, margin_right, margin_bottom, margin_left;
4152                 int na_top, na_right, na_bottom, na_left;
4153                 int window_min, window_max;
4154                 int multiplicator;
4155                 int weight_current, weight_previous, weight_len_squared;
4156                 int div_min, div_max, div_len;
4157                 int vscroll_hor_area, vscroll_ver_area;
4158                 int two_finger_scroll;
4159                 int max_x, max_y;
4160                 int len, weight_prev_x, weight_prev_y;
4161                 int div_max_x, div_max_y, div_x, div_y;
4162                 int is_fuzzy;
4163                 int natural_scroll;
4164
4165                 /* Read sysctl. */
4166                 /* XXX Verify values? */
4167                 max_width = sc->syninfo.max_width;
4168                 max_pressure = sc->syninfo.max_pressure;
4169                 margin_top = sc->syninfo.margin_top;
4170                 margin_right = sc->syninfo.margin_right;
4171                 margin_bottom = sc->syninfo.margin_bottom;
4172                 margin_left = sc->syninfo.margin_left;
4173                 na_top = sc->syninfo.na_top;
4174                 na_right = sc->syninfo.na_right;
4175                 na_bottom = sc->syninfo.na_bottom;
4176                 na_left = sc->syninfo.na_left;
4177                 window_min = sc->syninfo.window_min;
4178                 window_max = sc->syninfo.window_max;
4179                 multiplicator = sc->syninfo.multiplicator;
4180                 weight_current = sc->syninfo.weight_current;
4181                 weight_previous = sc->syninfo.weight_previous;
4182                 weight_len_squared = sc->syninfo.weight_len_squared;
4183                 div_min = sc->syninfo.div_min;
4184                 div_max = sc->syninfo.div_max;
4185                 div_len = sc->syninfo.div_len;
4186                 vscroll_hor_area = sc->syninfo.vscroll_hor_area;
4187                 vscroll_ver_area = sc->syninfo.vscroll_ver_area;
4188                 two_finger_scroll = sc->syninfo.two_finger_scroll;
4189                 max_x = sc->syninfo.max_x;
4190                 max_y = sc->syninfo.max_y;
4191                 natural_scroll = sc->syninfo.natural_scroll;
4192
4193                 is_fuzzy = (f->flags & PSM_FINGER_FUZZY) != 0;
4194
4195                 /* Read current absolute position. */
4196                 x0 = f->x;
4197                 y0 = f->y;
4198
4199                 /*
4200                  * Limit the coordinates to the specified margins because
4201                  * this area isn't very reliable.
4202                  */
4203                 if (x0 <= margin_left)
4204                         x0 = margin_left;
4205                 else if (x0 >= max_x - margin_right)
4206                         x0 = max_x - margin_right;
4207                 if (y0 <= margin_bottom)
4208                         y0 = margin_bottom;
4209                 else if (y0 >= max_y - margin_top)
4210                         y0 = max_y - margin_top;
4211
4212                 /* If the action is just beginning, init the structure. */
4213                 if (smoother->active == 0) {
4214                         VLOG(3, (LOG_DEBUG, "smoother%d: ---\n", smoother_id));
4215
4216                         /* Store the first point of this action. */
4217                         smoother->start_x = x0;
4218                         smoother->start_y = y0;
4219                         dx = dy = 0;
4220
4221                         /* Initialize queue. */
4222                         smoother->queue_cursor = SYNAPTICS_PACKETQUEUE;
4223                         smoother->queue_len = 0;
4224
4225                         /* Reset average. */
4226                         smoother->avg_dx = 0;
4227                         smoother->avg_dy = 0;
4228
4229                         /* Reset squelch. */
4230                         smoother->squelch_x = 0;
4231                         smoother->squelch_y = 0;
4232
4233                         /* Activate queue */
4234                         smoother->active = 1;
4235                 } else {
4236                         /* Calculate the current delta. */
4237                         cursor = smoother->queue_cursor;
4238                         dx = x0 - smoother->queue[cursor].x;
4239                         dy = y0 - smoother->queue[cursor].y;
4240                 }
4241
4242                 VLOG(3, (LOG_DEBUG, "smoother%d: ipacket: [%d, %d], %d, %d\n",
4243                     smoother_id, x0, y0, f->p, f->w));
4244
4245                 /* Queue this new packet. */
4246                 cursor = SYNAPTICS_QUEUE_CURSOR(smoother->queue_cursor - 1);
4247                 smoother->queue[cursor].x = x0;
4248                 smoother->queue[cursor].y = y0;
4249                 smoother->queue_cursor = cursor;
4250                 if (smoother->queue_len < SYNAPTICS_PACKETQUEUE)
4251                         smoother->queue_len++;
4252                 VLOG(5, (LOG_DEBUG,
4253                     "smoother%d: cursor[%d]: x=%d, y=%d, dx=%d, dy=%d\n",
4254                     smoother_id, cursor, x0, y0, dx, dy));
4255
4256                 /* Do we have enough packets to consider this a movement? */
4257                 if (smoother->queue_len < gest->window_min)
4258                         return;
4259
4260                 weight_prev_x = weight_prev_y = weight_previous;
4261                 div_max_x = div_max_y = div_max;
4262
4263                 if (gest->in_vscroll) {
4264                         /* Dividers are different with virtual scrolling. */
4265                         div_min = sc->syninfo.vscroll_div_min;
4266                         div_max_x = div_max_y = sc->syninfo.vscroll_div_max;
4267                 } else {
4268                         /*
4269                          * There's a lot of noise in coordinates when
4270                          * the finger is on the touchpad's borders. When
4271                          * using this area, we apply a special weight and
4272                          * div.
4273                          */
4274                         if (x0 <= na_left || x0 >= max_x - na_right) {
4275                                 weight_prev_x = sc->syninfo.weight_previous_na;
4276                                 div_max_x = sc->syninfo.div_max_na;
4277                         }
4278
4279                         if (y0 <= na_bottom || y0 >= max_y - na_top) {
4280                                 weight_prev_y = sc->syninfo.weight_previous_na;
4281                                 div_max_y = sc->syninfo.div_max_na;
4282                         }
4283                 }
4284
4285                 /*
4286                  * Calculate weights for the average operands and
4287                  * the divisor. Both depend on the distance between
4288                  * the current packet and a previous one (based on the
4289                  * window width).
4290                  */
4291                 window = imin(smoother->queue_len, window_max);
4292                 peer = SYNAPTICS_QUEUE_CURSOR(cursor + window - 1);
4293                 dxp = abs(x0 - smoother->queue[peer].x) + 1;
4294                 dyp = abs(y0 - smoother->queue[peer].y) + 1;
4295                 len = (dxp * dxp) + (dyp * dyp);
4296                 weight_prev_x = imin(weight_prev_x,
4297                     weight_len_squared * weight_prev_x / len);
4298                 weight_prev_y = imin(weight_prev_y,
4299                     weight_len_squared * weight_prev_y / len);
4300
4301                 len = (dxp + dyp) / 2;
4302                 div_x = div_len * div_max_x / len;
4303                 div_x = imin(div_max_x, div_x);
4304                 div_x = imax(div_min, div_x);
4305                 div_y = div_len * div_max_y / len;
4306                 div_y = imin(div_max_y, div_y);
4307                 div_y = imax(div_min, div_y);
4308
4309                 VLOG(3, (LOG_DEBUG,
4310                     "smoother%d: peer=%d, len=%d, weight=%d/%d, div=%d/%d\n",
4311                     smoother_id, peer, len, weight_prev_x, weight_prev_y,
4312                     div_x, div_y));
4313
4314                 /* Compute averages. */
4315                 smoother->avg_dx =
4316                     (weight_current * dx * multiplicator +
4317                      weight_prev_x * smoother->avg_dx) /
4318                     (weight_current + weight_prev_x);
4319
4320                 smoother->avg_dy =
4321                     (weight_current * dy * multiplicator +
4322                      weight_prev_y * smoother->avg_dy) /
4323                     (weight_current + weight_prev_y);
4324
4325                 VLOG(5, (LOG_DEBUG,
4326                     "smoother%d: avg_dx~=%d, avg_dy~=%d\n", smoother_id,
4327                     smoother->avg_dx / multiplicator,
4328                     smoother->avg_dy / multiplicator));
4329
4330                 /* Use these averages to calculate x & y. */
4331                 smoother->squelch_x += smoother->avg_dx;
4332                 dxp = smoother->squelch_x / (div_x * multiplicator);
4333                 smoother->squelch_x = smoother->squelch_x %
4334                     (div_x * multiplicator);
4335
4336                 smoother->squelch_y += smoother->avg_dy;
4337                 dyp = smoother->squelch_y / (div_y * multiplicator);
4338                 smoother->squelch_y = smoother->squelch_y %
4339                     (div_y * multiplicator);
4340
4341                 switch(gest->in_vscroll) {
4342                 case 0: /* Pointer movement. */
4343                         /* On real<->fuzzy finger switch the x/y pos jumps */
4344                         if (is_fuzzy == smoother->is_fuzzy) {
4345                                 *x += dxp;
4346                                 *y += dyp;
4347                         }
4348
4349                         VLOG(3, (LOG_DEBUG, "smoother%d: [%d, %d] -> [%d, %d]\n",
4350                             smoother_id, dx, dy, dxp, dyp));
4351                         break;
4352                 case 1: /* Vertical scrolling. */
4353                         if (dyp != 0) {
4354                                 if (two_finger_scroll && natural_scroll)
4355                                         ms->button |= (dyp > 0) ?
4356                                             MOUSE_BUTTON5DOWN : MOUSE_BUTTON4DOWN;
4357                                 else
4358                                         ms->button |= (dyp > 0) ?
4359                                             MOUSE_BUTTON4DOWN : MOUSE_BUTTON5DOWN;
4360                         }
4361                         break;
4362                 case 2: /* Horizontal scrolling. */
4363                         if (dxp != 0) {
4364                                 if (two_finger_scroll && natural_scroll)
4365                                         ms->button |= (dxp > 0) ?
4366                                             MOUSE_BUTTON6DOWN : MOUSE_BUTTON7DOWN;
4367                                 else
4368                                         ms->button |= (dxp > 0) ?
4369                                             MOUSE_BUTTON7DOWN : MOUSE_BUTTON6DOWN;
4370                         }
4371                         break;
4372                 }
4373
4374                 smoother->is_fuzzy = is_fuzzy;
4375
4376         } else {
4377                 /*
4378                  * Deactivate queue. Note: We can not just reset queue here
4379                  * as these values are still used by gesture processor.
4380                  * So postpone reset till next touch.
4381                  */
4382                 smoother->active = 0;
4383         }
4384 }
4385
4386 static int
4387 proc_elantech(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
4388     int *x, int *y, int *z)
4389 {
4390         static int touchpad_button, trackpoint_button;
4391         finger_t fn, f[ELANTECH_MAX_FINGERS];
4392         int pkt, id, scale, i, nfingers, mask, palm;
4393
4394         if (!elantech_support)
4395                 return (0);
4396
4397         /* Determine packet format and do a sanity check for out of sync packets. */
4398         if (ELANTECH_PKT_IS_DEBOUNCE(pb, sc->elanhw.hwversion))
4399                 pkt = ELANTECH_PKT_NOP;
4400         else if (sc->elanhw.hastrackpoint && ELANTECH_PKT_IS_TRACKPOINT(pb))
4401                 pkt = ELANTECH_PKT_TRACKPOINT;
4402         else
4403         switch (sc->elanhw.hwversion) {
4404         case 2:
4405                 if (!ELANTECH_PKT_IS_V2(pb))
4406                         return (-1);
4407
4408                 pkt = (pb->ipacket[0] & 0xc0) == 0x80 ?
4409                     ELANTECH_PKT_V2_2FINGER : ELANTECH_PKT_V2_COMMON;
4410                 break;
4411         case 3:
4412                 if (!ELANTECH_PKT_IS_V3_HEAD(pb, sc->elanhw.hascrc) &&
4413                     !ELANTECH_PKT_IS_V3_TAIL(pb, sc->elanhw.hascrc))
4414                         return (-1);
4415
4416                 pkt = ELANTECH_PKT_V3;
4417                 break;
4418         case 4:
4419                 if (!ELANTECH_PKT_IS_V4(pb, sc->elanhw.hascrc))
4420                         return (-1);
4421
4422                 switch (pb->ipacket[3] & 0x03) {
4423                 case 0x00:
4424                         pkt = ELANTECH_PKT_V4_STATUS;
4425                         break;
4426                 case 0x01:
4427                         pkt = ELANTECH_PKT_V4_HEAD;
4428                         break;
4429                 case 0x02:
4430                         pkt = ELANTECH_PKT_V4_MOTION;
4431                         break;
4432                 default:
4433                         return (-1);
4434                 }
4435                 break;
4436         default:
4437                 return (-1);
4438         }
4439
4440         VLOG(5, (LOG_DEBUG, "elantech: ipacket format: %d\n", pkt));
4441
4442         for (id = 0; id < ELANTECH_MAX_FINGERS; id++)
4443                 PSM_FINGER_RESET(f[id]);
4444
4445         *x = *y = *z = 0;
4446         ms->button = ms->obutton;
4447
4448         if (sc->syninfo.touchpad_off && pkt != ELANTECH_PKT_TRACKPOINT)
4449                 return (0);
4450
4451         /* Common legend
4452          * L: Left mouse button pressed
4453          * R: Right mouse button pressed
4454          * N: number of fingers on touchpad
4455          * X: absolute x value (horizontal)
4456          * Y: absolute y value (vertical)
4457          * W; width of the finger touch
4458          * P: pressure
4459          */
4460         switch (pkt) {
4461         case ELANTECH_PKT_V2_COMMON:    /* HW V2. One/Three finger touch */
4462                 /*               7   6   5   4   3   2   1   0 (LSB)
4463                  * -------------------------------------------
4464                  * ipacket[0]:  N1  N0  W3  W2   .   .   R   L
4465                  * ipacket[1]:  P7  P6  P5  P4 X11 X10  X9  X8
4466                  * ipacket[2]:  X7  X6  X5  X4  X3  X2  X1  X0
4467                  * ipacket[3]:  N4  VF  W1  W0   .   .   .  B2
4468                  * ipacket[4]:  P3  P1  P2  P0 Y11 Y10  Y9  Y8
4469                  * ipacket[5]:  Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
4470                  * -------------------------------------------
4471                  * N4: set if more than 3 fingers (only in 3 fingers mode)
4472                  * VF: a kind of flag? (only on EF123, 0 when finger
4473                  *     is over one of the buttons, 1 otherwise)
4474                  * B2: (on EF113 only, 0 otherwise), one button pressed
4475                  * P & W is not reported on EF113 touchpads
4476                  */
4477                 nfingers = (pb->ipacket[0] & 0xc0) >> 6;
4478                 if (nfingers == 3 && (pb->ipacket[3] & 0x80))
4479                         nfingers = 4;
4480
4481                 if (nfingers == 0) {
4482                         mask = (1 << nfingers) - 1;     /* = 0x00 */
4483                         break;
4484                 }
4485
4486                 /* Map 3-rd and 4-th fingers to first finger */
4487                 mask = (1 << 1) - 1;    /* = 0x01 */
4488                 f[0] = ELANTECH_FINGER_SET_XYP(pb);
4489                 if (sc->elanhw.haspressure) {
4490                         f[0].w = ((pb->ipacket[0] & 0x30) >> 2) |
4491                             ((pb->ipacket[3] & 0x30) >> 4);
4492                 } else {
4493                         f[0].p = PSM_FINGER_DEFAULT_P;
4494                         f[0].w = PSM_FINGER_DEFAULT_W;
4495                 }
4496
4497                 /*
4498                  * HW v2 dont report exact finger positions when 3 or more
4499                  * fingers are on touchpad.
4500                  */
4501                 if (nfingers > 2)
4502                         f[0].flags = PSM_FINGER_FUZZY;
4503
4504                 break;
4505
4506         case ELANTECH_PKT_V2_2FINGER:   /*HW V2. Two finger touch */
4507                 /*               7   6   5   4   3   2   1   0 (LSB)
4508                  * -------------------------------------------
4509                  * ipacket[0]:  N1  N0 AY8 AX8   .   .   R   L
4510                  * ipacket[1]: AX7 AX6 AX5 AX4 AX3 AX2 AX1 AX0
4511                  * ipacket[2]: AY7 AY6 AY5 AY4 AY3 AY2 AY1 AY0
4512                  * ipacket[3]:   .   . BY8 BX8   .   .   .   .
4513                  * ipacket[4]: BX7 BX6 BX5 BX4 BX3 BX2 BX1 BX0
4514                  * ipacket[5]: BY7 BY6 BY5 BY4 BY3 BY2 BY1 BY0
4515                  * -------------------------------------------
4516                  * AX: lower-left finger absolute x value
4517                  * AY: lower-left finger absolute y value
4518                  * BX: upper-right finger absolute x value
4519                  * BY: upper-right finger absolute y value
4520                  */
4521                 nfingers = 2;
4522                 mask = (1 << nfingers) - 1;
4523
4524                 for (id = 0; id < imin(2, ELANTECH_MAX_FINGERS); id ++)
4525                         f[id] = (finger_t) {
4526                                 .x = (((pb->ipacket[id * 3] & 0x10) << 4) |
4527                                     pb->ipacket[id * 3 + 1]) << 2,
4528                                 .y = (((pb->ipacket[id * 3] & 0x20) << 3) |
4529                                     pb->ipacket[id * 3 + 2]) << 2,
4530                                 .p = PSM_FINGER_DEFAULT_P,
4531                                 .w = PSM_FINGER_DEFAULT_W,
4532                                 /* HW ver.2 sends bounding box */
4533                                 .flags = PSM_FINGER_FUZZY
4534                         };
4535                 break;
4536
4537         case ELANTECH_PKT_V3:   /* HW Version 3 */
4538                 /*               7   6   5   4   3   2   1   0 (LSB)
4539                  * -------------------------------------------
4540                  * ipacket[0]:  N1  N0  W3  W2   0   1   R   L
4541                  * ipacket[1]:  P7  P6  P5  P4 X11 X10  X9  X8
4542                  * ipacket[2]:  X7  X6  X5  X4  X3  X2  X1  X0
4543                  * ipacket[3]:   0   0  W1  W0   0   0   1   0
4544                  * ipacket[4]:  P3  P1  P2  P0 Y11 Y10  Y9  Y8
4545                  * ipacket[5]:  Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
4546                  * -------------------------------------------
4547                  */
4548                 nfingers = (pb->ipacket[0] & 0xc0) >> 6;
4549                 /* Map 3-rd finger to first finger */
4550                 id = nfingers > 2 ? 0 : nfingers - 1;
4551                 mask = (1 << (id + 1)) - 1;
4552
4553                 if (nfingers == 0)
4554                         break;
4555
4556                 fn = ELANTECH_FINGER_SET_XYP(pb);
4557                 fn.w = ((pb->ipacket[0] & 0x30) >> 2) |
4558                     ((pb->ipacket[3] & 0x30) >> 4);
4559
4560                 /*
4561                  * HW v3 dont report exact finger positions when 3 or more
4562                  * fingers are on touchpad.
4563                  */
4564                 if (nfingers > 1)
4565                         fn.flags = PSM_FINGER_FUZZY;
4566
4567                 if (nfingers == 2) {
4568                         if (ELANTECH_PKT_IS_V3_HEAD(pb, sc->elanhw.hascrc)) {
4569                                 sc->elanaction.fingers[0] = fn;
4570                                 return (0);
4571                         } else
4572                                 f[0] = sc->elanaction.fingers[0];
4573                 }
4574                 f[id] = fn;
4575                 break;
4576
4577         case ELANTECH_PKT_V4_STATUS:    /* HW Version 4. Status packet */
4578                 /*               7   6   5   4   3   2   1   0 (LSB)
4579                  * -------------------------------------------
4580                  * ipacket[0]:   .   .   .   .   0   1   R   L
4581                  * ipacket[1]:   .   .   .  F4  F3  F2  F1  F0
4582                  * ipacket[2]:   .   .   .   .   .   .   .   .
4583                  * ipacket[3]:   .   .   .   1   0   0   0   0
4584                  * ipacket[4]:  PL   .   .   .   .   .   .   .
4585                  * ipacket[5]:   .   .   .   .   .   .   .   .
4586                  * -------------------------------------------
4587                  * Fn: finger n is on touchpad
4588                  * PL: palm
4589                  * HV ver4 sends a status packet to indicate that the numbers
4590                  * or identities of the fingers has been changed
4591                  */
4592
4593                 mask = pb->ipacket[1] & 0x1f;
4594                 nfingers = bitcount(mask);
4595
4596                 if (sc->elanaction.mask_v4wait != 0)
4597                         VLOG(3, (LOG_DEBUG, "elantech: HW v4 status packet"
4598                             " when not all previous head packets received\n"));
4599
4600                 /* Bitmap of fingers to receive before gesture processing */
4601                 sc->elanaction.mask_v4wait = mask & ~sc->elanaction.mask;
4602
4603                 /* Skip "new finger is on touchpad" packets */
4604                 if (sc->elanaction.mask_v4wait) {
4605                         sc->elanaction.mask = mask;
4606                         return (0);
4607                 }
4608
4609                 break;
4610
4611         case ELANTECH_PKT_V4_HEAD:      /* HW Version 4. Head packet */
4612                 /*               7   6   5   4   3   2   1   0 (LSB)
4613                  * -------------------------------------------
4614                  * ipacket[0]:  W3  W2  W1  W0   0   1   R   L
4615                  * ipacket[1]:  P7  P6  P5  P4 X11 X10  X9  X8
4616                  * ipacket[2]:  X7  X6  X5  X4  X3  X2  X1  X0
4617                  * ipacket[3]: ID2 ID1 ID0   1   0   0   0   1
4618                  * ipacket[4]:  P3  P1  P2  P0 Y11 Y10  Y9  Y8
4619                  * ipacket[5]:  Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
4620                  * -------------------------------------------
4621                  * ID: finger id
4622                  * HW ver 4 sends head packets in two cases:
4623                  * 1. One finger touch and movement.
4624                  * 2. Next after status packet to tell new finger positions.
4625                  */
4626                 mask = sc->elanaction.mask;
4627                 nfingers = bitcount(mask);
4628                 id = ((pb->ipacket[3] & 0xe0) >> 5) - 1;
4629                 fn = ELANTECH_FINGER_SET_XYP(pb);
4630                 fn.w =(pb->ipacket[0] & 0xf0) >> 4;
4631
4632                 if (id < 0)
4633                         return (0);
4634
4635                 /* Packet is finger position update. Report it */
4636                 if (sc->elanaction.mask_v4wait == 0) {
4637                         if (id < ELANTECH_MAX_FINGERS)
4638                                 f[id] = fn;
4639                         break;
4640                 }
4641
4642                 /* Remove finger from waiting bitmap and store into context */
4643                 sc->elanaction.mask_v4wait &= ~(1 << id);
4644                 if (id < ELANTECH_MAX_FINGERS)
4645                         sc->elanaction.fingers[id] = fn;
4646
4647                 /* Wait for other fingers if needed */
4648                 if (sc->elanaction.mask_v4wait != 0)
4649                         return (0);
4650
4651                 /* All new fingers are received. Report them from context */
4652                 for (id = 0; id < ELANTECH_MAX_FINGERS; id++)
4653                         if (sc->elanaction.mask & (1 << id))
4654                                 f[id] =  sc->elanaction.fingers[id];
4655
4656                 break;
4657
4658         case ELANTECH_PKT_V4_MOTION:    /* HW Version 4. Motion packet */
4659                 /*               7   6   5   4   3   2   1   0 (LSB)
4660                  * -------------------------------------------
4661                  * ipacket[0]: ID2 ID1 ID0  OF   0   1   R   L
4662                  * ipacket[1]: DX7 DX6 DX5 DX4 DX3 DX2 DX1 DX0
4663                  * ipacket[2]: DY7 DY6 DY5 DY4 DY3 DY2 DY1 DY0
4664                  * ipacket[3]: ID2 ID1 ID0   1   0   0   1   0
4665                  * ipacket[4]: DX7 DX6 DX5 DX4 DX3 DX2 DX1 DX0
4666                  * ipacket[5]: DY7 DY6 DY5 DY4 DY3 DY2 DY1 DY0
4667                  * -------------------------------------------
4668                  * OF: delta overflows (> 127 or < -128), in this case
4669                  *     firmware sends us (delta x / 5) and (delta y / 5)
4670                  * ID: finger id
4671                  * DX: delta x (two's complement)
4672                  * XY: delta y (two's complement)
4673                  * byte 0 ~ 2 for one finger
4674                  * byte 3 ~ 5 for another finger
4675                  */
4676                 mask = sc->elanaction.mask;
4677                 nfingers = bitcount(mask);
4678
4679                 scale = (pb->ipacket[0] & 0x10) ? 5 : 1;
4680                 for (i = 0; i <= 3; i += 3) {
4681                         id = ((pb->ipacket[i] & 0xe0) >> 5) - 1;
4682                         if (id < 0 || id >= ELANTECH_MAX_FINGERS)
4683                                 continue;
4684
4685                         if (PSM_FINGER_IS_SET(sc->elanaction.fingers[id])) {
4686                                 f[id] = sc->elanaction.fingers[id];
4687                                 f[id].x += imax(-f[id].x,
4688                                     (signed char)pb->ipacket[i+1] * scale);
4689                                 f[id].y += imax(-f[id].y,
4690                                     (signed char)pb->ipacket[i+2] * scale);
4691                         } else {
4692                                 VLOG(3, (LOG_DEBUG, "elantech: "
4693                                     "HW v4 motion packet skipped\n"));
4694                         }
4695                 }
4696
4697                 break;
4698
4699         case ELANTECH_PKT_TRACKPOINT:
4700                 /*               7   6   5   4   3   2   1   0 (LSB)
4701                  * -------------------------------------------
4702                  * ipacket[0]:   0   0  SY  SX   0   M   R   L
4703                  * ipacket[1]: ~SX   0   0   0   0   0   0   0
4704                  * ipacket[2]: ~SY   0   0   0   0   0   0   0
4705                  * ipacket[3]:   0   0 ~SY ~SX   0   1   1   0
4706                  * ipacket[4]:  X7  X6  X5  X4  X3  X2  X1  X0
4707                  * ipacket[5]:  Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
4708                  * -------------------------------------------
4709                  * X and Y are written in two's complement spread
4710                  * over 9 bits with SX/SY the relative top bit and
4711                  * X7..X0 and Y7..Y0 the lower bits.
4712                  */
4713                 if (!(pb->ipacket[0] & 0xC8) && !(pb->ipacket[1] & 0x7F) &&
4714                     !(pb->ipacket[2] & 0x7F) && !(pb->ipacket[3] & 0xC9) &&
4715                     !(pb->ipacket[0] & 0x10) != !(pb->ipacket[1] & 0x80) &&
4716                     !(pb->ipacket[0] & 0x10) != !(pb->ipacket[3] & 0x10) &&
4717                     !(pb->ipacket[0] & 0x20) != !(pb->ipacket[2] & 0x80) &&
4718                     !(pb->ipacket[0] & 0x20) != !(pb->ipacket[3] & 0x20)) {
4719
4720                         *x = (pb->ipacket[0] & MOUSE_PS2_XNEG) ?
4721                             pb->ipacket[4] - 256 : pb->ipacket[4];
4722                         *y = (pb->ipacket[0] & MOUSE_PS2_YNEG) ?
4723                             pb->ipacket[5] - 256 : pb->ipacket[5];
4724
4725                         trackpoint_button =
4726                             ((pb->ipacket[0] & 0x01) ? MOUSE_BUTTON1DOWN : 0) |
4727                             ((pb->ipacket[0] & 0x02) ? MOUSE_BUTTON3DOWN : 0) |
4728                             ((pb->ipacket[0] & 0x04) ? MOUSE_BUTTON2DOWN : 0);
4729 #ifdef EVDEV_SUPPORT
4730                         evdev_push_rel(sc->evdev_r, REL_X, *x);
4731                         evdev_push_rel(sc->evdev_r, REL_Y, -*y);
4732                         evdev_push_mouse_btn(sc->evdev_r, trackpoint_button);
4733                         evdev_sync(sc->evdev_r);
4734 #endif
4735                         ms->button = touchpad_button | trackpoint_button;
4736                 } else
4737                         VLOG(3, (LOG_DEBUG, "elantech: "
4738                             "unexpected trackpoint packet skipped\n"));
4739                 return (0);
4740
4741         case ELANTECH_PKT_NOP:
4742                 return (0);
4743
4744         default:
4745                 return (-1);
4746         }
4747
4748         for (id = 0; id < ELANTECH_MAX_FINGERS; id++)
4749                 if (PSM_FINGER_IS_SET(f[id]))
4750                         VLOG(2, (LOG_DEBUG, "elantech: "
4751                             "finger %d: down [%d, %d], %d, %d, %d\n", id + 1,
4752                             f[id].x, f[id].y, f[id].p, f[id].w, f[id].flags));
4753
4754         /* Touchpad button presses */
4755         if (sc->elanhw.isclickpad) {
4756                 touchpad_button =
4757                     ((pb->ipacket[0] & 0x03) ? MOUSE_BUTTON1DOWN : 0);
4758         } else {
4759                 touchpad_button =
4760                     ((pb->ipacket[0] & 0x01) ? MOUSE_BUTTON1DOWN : 0) |
4761                     ((pb->ipacket[0] & 0x02) ? MOUSE_BUTTON3DOWN : 0);
4762         }
4763
4764 #ifdef EVDEV_SUPPORT
4765         if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
4766                 for (id = 0; id < ELANTECH_MAX_FINGERS; id++) {
4767                         if (PSM_FINGER_IS_SET(f[id])) {
4768                                 psm_push_mt_finger(sc, id, &f[id]);
4769                                 /* Convert touch width to surface units */
4770                                 evdev_push_abs(sc->evdev_a, ABS_MT_TOUCH_MAJOR,
4771                                     f[id].w * sc->elanhw.dptracex);
4772                         }
4773                         if (sc->elanaction.mask & (1 << id) &&
4774                             !(mask & (1 << id)))
4775                                 psm_release_mt_slot(sc->evdev_a, id);
4776                 }
4777                 evdev_push_key(sc->evdev_a, BTN_TOUCH, nfingers > 0);
4778                 evdev_push_nfingers(sc->evdev_a, nfingers);
4779                 if (nfingers > 0) {
4780                         if (PSM_FINGER_IS_SET(f[0]))
4781                                 psm_push_st_finger(sc, &f[0]);
4782                 } else
4783                         evdev_push_abs(sc->evdev_a, ABS_PRESSURE, 0);
4784                 evdev_push_mouse_btn(sc->evdev_a, touchpad_button);
4785                 evdev_sync(sc->evdev_a);
4786         }
4787 #endif
4788
4789         ms->button = touchpad_button | trackpoint_button;
4790
4791         /* Palm detection doesn't terminate the current action. */
4792         palm = psmpalmdetect(sc, &f[0], nfingers);
4793
4794         /* Send finger 1 position to gesture processor */
4795         if ((PSM_FINGER_IS_SET(f[0]) || PSM_FINGER_IS_SET(f[1]) ||
4796             nfingers == 0) && !palm)
4797                 psmgestures(sc, &f[0], imin(nfingers, 3), ms);
4798
4799         /* Send fingers positions to movement smoothers */
4800         for (id = 0; id < PSM_FINGERS; id++)
4801                 if (PSM_FINGER_IS_SET(f[id]) || !(mask & (1 << id)))
4802                         psmsmoother(sc, &f[id], id, ms, x, y);
4803
4804         /* Store current finger positions in action context */
4805         for (id = 0; id < ELANTECH_MAX_FINGERS; id++) {
4806                 if (PSM_FINGER_IS_SET(f[id]))
4807                         sc->elanaction.fingers[id] = f[id];
4808                 if ((sc->elanaction.mask & (1 << id)) && !(mask & (1 << id)))
4809                         PSM_FINGER_RESET(sc->elanaction.fingers[id]);
4810         }
4811         sc->elanaction.mask = mask;
4812
4813         if (palm) {
4814                 *x = *y = *z = 0;
4815                 ms->button = ms->obutton;
4816                 return (0);
4817         }
4818
4819         /* Use the extra buttons as a scrollwheel */
4820         if (ms->button & MOUSE_BUTTON4DOWN)
4821                 *z = -1;
4822         else if (ms->button & MOUSE_BUTTON5DOWN)
4823                 *z = 1;
4824         else if (ms->button & MOUSE_BUTTON6DOWN)
4825                 *z = -2;
4826         else if (ms->button & MOUSE_BUTTON7DOWN)
4827                 *z = 2;
4828         else
4829                 *z = 0;
4830         ms->button &= ~(MOUSE_BUTTON4DOWN | MOUSE_BUTTON5DOWN |
4831             MOUSE_BUTTON6DOWN | MOUSE_BUTTON7DOWN);
4832
4833         return (0);
4834 }
4835
4836 static void
4837 proc_versapad(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
4838     int *x, int *y, int *z)
4839 {
4840         static int butmap_versapad[8] = {
4841                 0,
4842                 MOUSE_BUTTON3DOWN,
4843                 0,
4844                 MOUSE_BUTTON3DOWN,
4845                 MOUSE_BUTTON1DOWN,
4846                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
4847                 MOUSE_BUTTON1DOWN,
4848                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
4849         };
4850         int c, x0, y0;
4851
4852         /* VersaPad PS/2 absolute mode message format
4853          *
4854          * [packet1]     7   6   5   4   3   2   1   0(LSB)
4855          *  ipacket[0]:  1   1   0   A   1   L   T   R
4856          *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
4857          *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
4858          *  ipacket[3]:  1   1   1   A   1   L   T   R
4859          *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
4860          *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
4861          *
4862          * [note]
4863          *  R: right physical mouse button (1=on)
4864          *  T: touch pad virtual button (1=tapping)
4865          *  L: left physical mouse button (1=on)
4866          *  A: position data is valid (1=valid)
4867          *  H: horizontal data (12bit signed integer. H11 is sign bit.)
4868          *  V: vertical data (12bit signed integer. V11 is sign bit.)
4869          *  P: pressure data
4870          *
4871          * Tapping is mapped to MOUSE_BUTTON4.
4872          */
4873         c = pb->ipacket[0];
4874         *x = *y = 0;
4875         ms->button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
4876         ms->button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
4877         if (c & MOUSE_PS2VERSA_IN_USE) {
4878                 x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
4879                 y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
4880                 if (x0 & 0x800)
4881                         x0 -= 0x1000;
4882                 if (y0 & 0x800)
4883                         y0 -= 0x1000;
4884                 if (sc->flags & PSM_FLAGS_FINGERDOWN) {
4885                         *x = sc->xold - x0;
4886                         *y = y0 - sc->yold;
4887                         if (*x < 0)     /* XXX */
4888                                 ++*x;
4889                         else if (*x)
4890                                 --*x;
4891                         if (*y < 0)
4892                                 ++*y;
4893                         else if (*y)
4894                                 --*y;
4895                 } else
4896                         sc->flags |= PSM_FLAGS_FINGERDOWN;
4897                 sc->xold = x0;
4898                 sc->yold = y0;
4899         } else
4900                 sc->flags &= ~PSM_FLAGS_FINGERDOWN;
4901 }
4902
4903 static void
4904 psmsoftintridle(void *arg)
4905 {
4906         struct psm_softc *sc = arg;
4907         packetbuf_t *pb;
4908
4909         /* Invoke soft handler only when pqueue is empty. Otherwise it will be
4910          * invoked from psmintr soon with pqueue filled with real data */
4911         if (sc->pqueue_start == sc->pqueue_end &&
4912             sc->idlepacket.inputbytes > 0) {
4913                 /* Grow circular queue backwards to avoid race with psmintr */
4914                 if (--sc->pqueue_start < 0)
4915                         sc->pqueue_start = PSM_PACKETQUEUE - 1;
4916
4917                 pb = &sc->pqueue[sc->pqueue_start];
4918                 memcpy(pb, &sc->idlepacket, sizeof(packetbuf_t));
4919                 VLOG(4, (LOG_DEBUG,
4920                     "psmsoftintridle: %02x %02x %02x %02x %02x %02x\n",
4921                     pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
4922                     pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
4923
4924                 psmsoftintr(arg);
4925         }
4926 }
4927
4928 static void
4929 psmsoftintr(void *arg)
4930 {
4931         /*
4932          * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
4933          * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
4934          */
4935         static int butmap[8] = {
4936                 0,
4937                 MOUSE_BUTTON1DOWN,
4938                 MOUSE_BUTTON3DOWN,
4939                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
4940                 MOUSE_BUTTON2DOWN,
4941                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
4942                 MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
4943                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
4944         };
4945         struct psm_softc *sc = arg;
4946         mousestatus_t ms;
4947         packetbuf_t *pb;
4948         int x, y, z, c, l, s;
4949
4950         getmicrouptime(&sc->lastsoftintr);
4951
4952         s = spltty();
4953
4954         do {
4955                 pb = &sc->pqueue[sc->pqueue_start];
4956
4957                 if (sc->mode.level == PSM_LEVEL_NATIVE)
4958                         goto next_native;
4959
4960                 c = pb->ipacket[0];
4961                 /*
4962                  * A kludge for Kensington device!
4963                  * The MSB of the horizontal count appears to be stored in
4964                  * a strange place.
4965                  */
4966                 if (sc->hw.model == MOUSE_MODEL_THINK)
4967                         pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
4968
4969                 /* ignore the overflow bits... */
4970                 x = (c & MOUSE_PS2_XNEG) ?
4971                     pb->ipacket[1] - 256 : pb->ipacket[1];
4972                 y = (c & MOUSE_PS2_YNEG) ?
4973                     pb->ipacket[2] - 256 : pb->ipacket[2];
4974                 z = 0;
4975                 ms.obutton = sc->button;          /* previous button state */
4976                 ms.button = butmap[c & MOUSE_PS2_BUTTONS];
4977                 /* `tapping' action */
4978                 if (sc->config & PSM_CONFIG_FORCETAP)
4979                         ms.button |= ((c & MOUSE_PS2_TAP)) ?
4980                             0 : MOUSE_BUTTON4DOWN;
4981                 timevalclear(&sc->idletimeout);
4982                 sc->idlepacket.inputbytes = 0;
4983
4984                 switch (sc->hw.model) {
4985
4986                 case MOUSE_MODEL_EXPLORER:
4987                         /*
4988                          *          b7 b6 b5 b4 b3 b2 b1 b0
4989                          * byte 1:  oy ox sy sx 1  M  R  L
4990                          * byte 2:  x  x  x  x  x  x  x  x
4991                          * byte 3:  y  y  y  y  y  y  y  y
4992                          * byte 4:  *  *  S2 S1 s  d2 d1 d0
4993                          *
4994                          * L, M, R, S1, S2: left, middle, right and side buttons
4995                          * s: wheel data sign bit
4996                          * d2-d0: wheel data
4997                          */
4998                         z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG) ?
4999                             (pb->ipacket[3] & 0x0f) - 16 :
5000                             (pb->ipacket[3] & 0x0f);
5001                         ms.button |=
5002                             (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN) ?
5003                             MOUSE_BUTTON4DOWN : 0;
5004                         ms.button |=
5005                             (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN) ?
5006                             MOUSE_BUTTON5DOWN : 0;
5007                         break;
5008
5009                 case MOUSE_MODEL_INTELLI:
5010                 case MOUSE_MODEL_NET:
5011                         /* wheel data is in the fourth byte */
5012                         z = (char)pb->ipacket[3];
5013                         /*
5014                          * XXX some mice may send 7 when there is no Z movement?                         */
5015                         if ((z >= 7) || (z <= -7))
5016                                 z = 0;
5017                         /* some compatible mice have additional buttons */
5018                         ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN) ?
5019                             MOUSE_BUTTON4DOWN : 0;
5020                         ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN) ?
5021                             MOUSE_BUTTON5DOWN : 0;
5022                         break;
5023
5024                 case MOUSE_MODEL_MOUSEMANPLUS:
5025                         proc_mmanplus(sc, pb, &ms, &x, &y, &z);
5026                         break;
5027
5028                 case MOUSE_MODEL_GLIDEPOINT:
5029                         /* `tapping' action */
5030                         ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 :
5031                             MOUSE_BUTTON4DOWN;
5032                         break;
5033
5034                 case MOUSE_MODEL_NETSCROLL:
5035                         /*
5036                          * three additional bytes encode buttons and
5037                          * wheel events
5038                          */
5039                         ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN) ?
5040                             MOUSE_BUTTON4DOWN : 0;
5041                         ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN) ?
5042                             MOUSE_BUTTON5DOWN : 0;
5043                         z = (pb->ipacket[3] & MOUSE_PS2_XNEG) ?
5044                             pb->ipacket[4] - 256 : pb->ipacket[4];
5045                         break;
5046
5047                 case MOUSE_MODEL_THINK:
5048                         /* the fourth button state in the first byte */
5049                         ms.button |= (c & MOUSE_PS2_TAP) ?
5050                             MOUSE_BUTTON4DOWN : 0;
5051                         break;
5052
5053                 case MOUSE_MODEL_VERSAPAD:
5054                         proc_versapad(sc, pb, &ms, &x, &y, &z);
5055                         c = ((x < 0) ? MOUSE_PS2_XNEG : 0) |
5056                             ((y < 0) ? MOUSE_PS2_YNEG : 0);
5057                         break;
5058
5059                 case MOUSE_MODEL_4D:
5060                         /*
5061                          *          b7 b6 b5 b4 b3 b2 b1 b0
5062                          * byte 1:  s2 d2 s1 d1 1  M  R  L
5063                          * byte 2:  sx x  x  x  x  x  x  x
5064                          * byte 3:  sy y  y  y  y  y  y  y
5065                          *
5066                          * s1: wheel 1 direction
5067                          * d1: wheel 1 data
5068                          * s2: wheel 2 direction
5069                          * d2: wheel 2 data
5070                          */
5071                         x = (pb->ipacket[1] & 0x80) ?
5072                             pb->ipacket[1] - 256 : pb->ipacket[1];
5073                         y = (pb->ipacket[2] & 0x80) ?
5074                             pb->ipacket[2] - 256 : pb->ipacket[2];
5075                         switch (c & MOUSE_4D_WHEELBITS) {
5076                         case 0x10:
5077                                 z = 1;
5078                                 break;
5079                         case 0x30:
5080                                 z = -1;
5081                                 break;
5082                         case 0x40:      /* XXX 2nd wheel turning right */
5083                                 z = 2;
5084                                 break;
5085                         case 0xc0:      /* XXX 2nd wheel turning left */
5086                                 z = -2;
5087                                 break;
5088                         }
5089                         break;
5090
5091                 case MOUSE_MODEL_4DPLUS:
5092                         if ((x < 16 - 256) && (y < 16 - 256)) {
5093                                 /*
5094                                  *          b7 b6 b5 b4 b3 b2 b1 b0
5095                                  * byte 1:  0  0  1  1  1  M  R  L
5096                                  * byte 2:  0  0  0  0  1  0  0  0
5097                                  * byte 3:  0  0  0  0  S  s  d1 d0
5098                                  *
5099                                  * L, M, R, S: left, middle, right,
5100                                  *             and side buttons
5101                                  * s: wheel data sign bit
5102                                  * d1-d0: wheel data
5103                                  */
5104                                 x = y = 0;
5105                                 if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
5106                                         ms.button |= MOUSE_BUTTON4DOWN;
5107                                 z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG) ?
5108                                     ((pb->ipacket[2] & 0x07) - 8) :
5109                                     (pb->ipacket[2] & 0x07) ;
5110                         } else {
5111                                 /* preserve previous button states */
5112                                 ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
5113                         }
5114                         break;
5115
5116                 case MOUSE_MODEL_SYNAPTICS:
5117                         if (pb->inputbytes == MOUSE_PS2_PACKETSIZE)
5118                                 if (proc_synaptics_mux(sc, pb))
5119                                         goto next;
5120
5121                         if (proc_synaptics(sc, pb, &ms, &x, &y, &z) != 0) {
5122                                 VLOG(3, (LOG_DEBUG, "synaptics: "
5123                                     "packet rejected\n"));
5124                                 goto next;
5125                         }
5126                         break;
5127
5128                 case MOUSE_MODEL_ELANTECH:
5129                         if (proc_elantech(sc, pb, &ms, &x, &y, &z) != 0) {
5130                                 VLOG(3, (LOG_DEBUG, "elantech: "
5131                                     "packet rejected\n"));
5132                                 goto next;
5133                         }
5134                         break;
5135
5136                 case MOUSE_MODEL_TRACKPOINT:
5137                 case MOUSE_MODEL_GENERIC:
5138                 default:
5139                         break;
5140                 }
5141
5142 #ifdef EVDEV_SUPPORT
5143         if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE &&
5144             sc->hw.model != MOUSE_MODEL_ELANTECH &&
5145             sc->hw.model != MOUSE_MODEL_SYNAPTICS) {
5146                 evdev_push_rel(sc->evdev_r, REL_X, x);
5147                 evdev_push_rel(sc->evdev_r, REL_Y, -y);
5148
5149                 switch (sc->hw.model) {
5150                 case MOUSE_MODEL_EXPLORER:
5151                 case MOUSE_MODEL_INTELLI:
5152                 case MOUSE_MODEL_NET:
5153                 case MOUSE_MODEL_NETSCROLL:
5154                 case MOUSE_MODEL_4DPLUS:
5155                         evdev_push_rel(sc->evdev_r, REL_WHEEL, -z);
5156                         break;
5157                 case MOUSE_MODEL_MOUSEMANPLUS:
5158                 case MOUSE_MODEL_4D:
5159                         switch (z) {
5160                         case 1:
5161                         case -1:
5162                                 evdev_push_rel(sc->evdev_r, REL_WHEEL, -z);
5163                                 break;
5164                         case 2:
5165                         case -2:
5166                                 evdev_push_rel(sc->evdev_r, REL_HWHEEL, z / 2);
5167                                 break;
5168                         }
5169                         break;
5170                 }
5171
5172                 evdev_push_mouse_btn(sc->evdev_r, ms.button);
5173                 evdev_sync(sc->evdev_r);
5174         }
5175 #endif
5176
5177         /* scale values */
5178         if (sc->mode.accelfactor >= 1) {
5179                 if (x != 0) {
5180                         x = x * x / sc->mode.accelfactor;
5181                         if (x == 0)
5182                                 x = 1;
5183                         if (c & MOUSE_PS2_XNEG)
5184                                 x = -x;
5185                 }
5186                 if (y != 0) {
5187                         y = y * y / sc->mode.accelfactor;
5188                         if (y == 0)
5189                                 y = 1;
5190                         if (c & MOUSE_PS2_YNEG)
5191                                 y = -y;
5192                 }
5193         }
5194
5195         /* Store last packet for reinjection if it has not been set already */
5196         if (timevalisset(&sc->idletimeout) && sc->idlepacket.inputbytes == 0)
5197                 sc->idlepacket = *pb;
5198
5199         ms.dx = x;
5200         ms.dy = y;
5201         ms.dz = z;
5202         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0) |
5203             (ms.obutton ^ ms.button);
5204
5205         pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);
5206
5207         sc->status.flags |= ms.flags;
5208         sc->status.dx += ms.dx;
5209         sc->status.dy += ms.dy;
5210         sc->status.dz += ms.dz;
5211         sc->status.button = ms.button;
5212         sc->button = ms.button;
5213
5214 next_native:
5215         sc->watchdog = FALSE;
5216
5217         /* queue data */
5218         if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
5219                 l = imin(pb->inputbytes,
5220                     sizeof(sc->queue.buf) - sc->queue.tail);
5221                 bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
5222                 if (pb->inputbytes > l)
5223                         bcopy(&pb->ipacket[l], &sc->queue.buf[0],
5224                             pb->inputbytes - l);
5225                 sc->queue.tail = (sc->queue.tail + pb->inputbytes) %
5226                     sizeof(sc->queue.buf);
5227                 sc->queue.count += pb->inputbytes;
5228         }
5229
5230 next:
5231         pb->inputbytes = 0;
5232         if (++sc->pqueue_start >= PSM_PACKETQUEUE)
5233                 sc->pqueue_start = 0;
5234         } while (sc->pqueue_start != sc->pqueue_end);
5235
5236         if (sc->state & PSM_ASLP) {
5237                 sc->state &= ~PSM_ASLP;
5238                 wakeup(sc);
5239         }
5240         selwakeuppri(&sc->rsel, PZERO);
5241         if (sc->async != NULL) {
5242                 pgsigio(&sc->async, SIGIO, 0);
5243         }
5244         sc->state &= ~PSM_SOFTARMED;
5245
5246         /* schedule injection of predefined packet after idletimeout
5247          * if no data packets have been received from psmintr */
5248         if (timevalisset(&sc->idletimeout)) {
5249                 sc->state |= PSM_SOFTARMED;
5250                 callout_reset(&sc->softcallout, tvtohz(&sc->idletimeout),
5251                     psmsoftintridle, sc);
5252                 VLOG(2, (LOG_DEBUG, "softintr: callout set: %d ticks\n",
5253                     tvtohz(&sc->idletimeout)));
5254         }
5255         splx(s);
5256 }
5257
5258 static int
5259 psmpoll(struct cdev *dev, int events, struct thread *td)
5260 {
5261         struct psm_softc *sc = dev->si_drv1;
5262         int s;
5263         int revents = 0;
5264
5265         /* Return true if a mouse event available */
5266         s = spltty();
5267         if (events & (POLLIN | POLLRDNORM)) {
5268                 if (sc->queue.count > 0)
5269                         revents |= events & (POLLIN | POLLRDNORM);
5270                 else
5271                         selrecord(td, &sc->rsel);
5272         }
5273         splx(s);
5274
5275         return (revents);
5276 }
5277
5278 /* vendor/model specific routines */
5279
5280 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
5281 {
5282         if (set_mouse_resolution(kbdc, res) != res)
5283                 return (FALSE);
5284         if (set_mouse_scaling(kbdc, scale) &&
5285             set_mouse_scaling(kbdc, scale) &&
5286             set_mouse_scaling(kbdc, scale) &&
5287             (get_mouse_status(kbdc, status, 0, 3) >= 3))
5288                 return (TRUE);
5289         return (FALSE);
5290 }
5291
5292 static int
5293 mouse_ext_command(KBDC kbdc, int command)
5294 {
5295         int c;
5296
5297         c = (command >> 6) & 0x03;
5298         if (set_mouse_resolution(kbdc, c) != c)
5299                 return (FALSE);
5300         c = (command >> 4) & 0x03;
5301         if (set_mouse_resolution(kbdc, c) != c)
5302                 return (FALSE);
5303         c = (command >> 2) & 0x03;
5304         if (set_mouse_resolution(kbdc, c) != c)
5305                 return (FALSE);
5306         c = (command >> 0) & 0x03;
5307         if (set_mouse_resolution(kbdc, c) != c)
5308                 return (FALSE);
5309         return (TRUE);
5310 }
5311
5312 #ifdef notyet
5313 /* Logitech MouseMan Cordless II */
5314 static int
5315 enable_lcordless(struct psm_softc *sc, enum probearg arg)
5316 {
5317         KBDC kbdc = sc->kbdc;
5318         int status[3];
5319         int ch;
5320
5321         if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 2, status))
5322                 return (FALSE);
5323         if (status[1] == PSMD_RES_HIGH)
5324                 return (FALSE);
5325         ch = (status[0] & 0x07) - 1;    /* channel # */
5326         if ((ch <= 0) || (ch > 4))
5327                 return (FALSE);
5328         /*
5329          * status[1]: always one?
5330          * status[2]: battery status? (0-100)
5331          */
5332         return (TRUE);
5333 }
5334 #endif /* notyet */
5335
5336 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
5337 static int
5338 enable_groller(struct psm_softc *sc, enum probearg arg)
5339 {
5340         KBDC kbdc = sc->kbdc;
5341         int status[3];
5342
5343         /*
5344          * The special sequence to enable the fourth button and the
5345          * roller. Immediately after this sequence check status bytes.
5346          * if the mouse is NetScroll, the second and the third bytes are
5347          * '3' and 'D'.
5348          */
5349
5350         /*
5351          * If the mouse is an ordinary PS/2 mouse, the status bytes should
5352          * look like the following.
5353          *
5354          * byte 1 bit 7 always 0
5355          *        bit 6 stream mode (0)
5356          *        bit 5 disabled (0)
5357          *        bit 4 1:1 scaling (0)
5358          *        bit 3 always 0
5359          *        bit 0-2 button status
5360          * byte 2 resolution (PSMD_RES_HIGH)
5361          * byte 3 report rate (?)
5362          */
5363
5364         if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
5365                 return (FALSE);
5366         if ((status[1] != '3') || (status[2] != 'D'))
5367                 return (FALSE);
5368         /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
5369         if (arg == PROBE)
5370                 sc->hw.buttons = 4;
5371         return (TRUE);
5372 }
5373
5374 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
5375 static int
5376 enable_gmouse(struct psm_softc *sc, enum probearg arg)
5377 {
5378         KBDC kbdc = sc->kbdc;
5379         int status[3];
5380
5381         /*
5382          * The special sequence to enable the middle, "rubber" button.
5383          * Immediately after this sequence check status bytes.
5384          * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
5385          * the second and the third bytes are '3' and 'U'.
5386          * NOTE: NetMouse reports that it has three buttons although it has
5387          * two buttons and a rubber button. NetMouse Pro and MIE Mouse
5388          * say they have three buttons too and they do have a button on the
5389          * side...
5390          */
5391         if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
5392                 return (FALSE);
5393         if ((status[1] != '3') || (status[2] != 'U'))
5394                 return (FALSE);
5395         return (TRUE);
5396 }
5397
5398 /* ALPS GlidePoint */
5399 static int
5400 enable_aglide(struct psm_softc *sc, enum probearg arg)
5401 {
5402         KBDC kbdc = sc->kbdc;
5403         int status[3];
5404
5405         /*
5406          * The special sequence to obtain ALPS GlidePoint specific
5407          * information. Immediately after this sequence, status bytes will
5408          * contain something interesting.
5409          * NOTE: ALPS produces several models of GlidePoint. Some of those
5410          * do not respond to this sequence, thus, cannot be detected this way.
5411          */
5412         if (set_mouse_sampling_rate(kbdc, 100) != 100)
5413                 return (FALSE);
5414         if (!mouse_id_proc1(kbdc, PSMD_RES_LOW, 2, status))
5415                 return (FALSE);
5416         if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
5417                 return (FALSE);
5418         return (TRUE);
5419 }
5420
5421 /* Kensington ThinkingMouse/Trackball */
5422 static int
5423 enable_kmouse(struct psm_softc *sc, enum probearg arg)
5424 {
5425         static u_char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
5426         KBDC kbdc = sc->kbdc;
5427         int status[3];
5428         int id1;
5429         int id2;
5430         int i;
5431
5432         id1 = get_aux_id(kbdc);
5433         if (set_mouse_sampling_rate(kbdc, 10) != 10)
5434                 return (FALSE);
5435         /*
5436          * The device is now in the native mode? It returns a different
5437          * ID value...
5438          */
5439         id2 = get_aux_id(kbdc);
5440         if ((id1 == id2) || (id2 != 2))
5441                 return (FALSE);
5442
5443         if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
5444                 return (FALSE);
5445 #if PSM_DEBUG >= 2
5446         /* at this point, resolution is LOW, sampling rate is 10/sec */
5447         if (get_mouse_status(kbdc, status, 0, 3) < 3)
5448                 return (FALSE);
5449 #endif
5450
5451         /*
5452          * The special sequence to enable the third and fourth buttons.
5453          * Otherwise they behave like the first and second buttons.
5454          */
5455         for (i = 0; i < nitems(rate); ++i)
5456                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
5457                         return (FALSE);
5458
5459         /*
5460          * At this point, the device is using default resolution and
5461          * sampling rate for the native mode.
5462          */
5463         if (get_mouse_status(kbdc, status, 0, 3) < 3)
5464                 return (FALSE);
5465         if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
5466                 return (FALSE);
5467
5468         /* the device appears be enabled by this sequence, diable it for now */
5469         disable_aux_dev(kbdc);
5470         empty_aux_buffer(kbdc, 5);
5471
5472         return (TRUE);
5473 }
5474
5475 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
5476 static int
5477 enable_mmanplus(struct psm_softc *sc, enum probearg arg)
5478 {
5479         KBDC kbdc = sc->kbdc;
5480         int data[3];
5481
5482         /* the special sequence to enable the fourth button and the roller. */
5483         /*
5484          * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
5485          * must be called exactly three times since the last RESET command
5486          * before this sequence. XXX
5487          */
5488         if (!set_mouse_scaling(kbdc, 1))
5489                 return (FALSE);
5490         if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
5491                 return (FALSE);
5492         if (get_mouse_status(kbdc, data, 1, 3) < 3)
5493                 return (FALSE);
5494
5495         /*
5496          * PS2++ protocol, packet type 0
5497          *
5498          *          b7 b6 b5 b4 b3 b2 b1 b0
5499          * byte 1:  *  1  p3 p2 1  *  *  *
5500          * byte 2:  1  1  p1 p0 m1 m0 1  0
5501          * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
5502          *
5503          * p3-p0: packet type: 0
5504          * m7-m0: model ID: MouseMan+:0x50,
5505          *                  FirstMouse+:0x51,
5506          *                  ScrollPoint:0x58...
5507          */
5508         /* check constant bits */
5509         if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
5510                 return (FALSE);
5511         if ((data[1] & 0xc3) != 0xc2)
5512                 return (FALSE);
5513         /* check d3-d0 in byte 2 */
5514         if (!MOUSE_PS2PLUS_CHECKBITS(data))
5515                 return (FALSE);
5516         /* check p3-p0 */
5517         if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
5518                 return (FALSE);
5519
5520         if (arg == PROBE) {
5521                 sc->hw.hwid &= 0x00ff;
5522                 sc->hw.hwid |= data[2] << 8;    /* save model ID */
5523         }
5524
5525         /*
5526          * MouseMan+ (or FirstMouse+) is now in its native mode, in which
5527          * the wheel and the fourth button events are encoded in the
5528          * special data packet. The mouse may be put in the IntelliMouse mode
5529          * if it is initialized by the IntelliMouse's method.
5530          */
5531         return (TRUE);
5532 }
5533
5534 /* MS IntelliMouse Explorer */
5535 static int
5536 enable_msexplorer(struct psm_softc *sc, enum probearg arg)
5537 {
5538         KBDC kbdc = sc->kbdc;
5539         static u_char rate0[] = { 200, 100, 80, };
5540         static u_char rate1[] = { 200, 200, 80, };
5541         int id;
5542         int i;
5543
5544         /*
5545          * This is needed for at least A4Tech X-7xx mice - they do not go
5546          * straight to Explorer mode, but need to be set to Intelli mode
5547          * first.
5548          */
5549         enable_msintelli(sc, arg);
5550
5551         /* the special sequence to enable the extra buttons and the roller. */
5552         for (i = 0; i < nitems(rate1); ++i)
5553                 if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
5554                         return (FALSE);
5555         /* the device will give the genuine ID only after the above sequence */
5556         id = get_aux_id(kbdc);
5557         if (id != PSM_EXPLORER_ID)
5558                 return (FALSE);
5559
5560         if (arg == PROBE) {
5561                 sc->hw.buttons = 5;     /* IntelliMouse Explorer XXX */
5562                 sc->hw.hwid = id;
5563         }
5564
5565         /*
5566          * XXX: this is a kludge to fool some KVM switch products
5567          * which think they are clever enough to know the 4-byte IntelliMouse
5568          * protocol, and assume any other protocols use 3-byte packets.
5569          * They don't convey 4-byte data packets from the IntelliMouse Explorer
5570          * correctly to the host computer because of this!
5571          * The following sequence is actually IntelliMouse's "wake up"
5572          * sequence; it will make the KVM think the mouse is IntelliMouse
5573          * when it is in fact IntelliMouse Explorer.
5574          */
5575         for (i = 0; i < nitems(rate0); ++i)
5576                 if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
5577                         break;
5578         get_aux_id(kbdc);
5579
5580         return (TRUE);
5581 }
5582
5583 /*
5584  * MS IntelliMouse
5585  * Logitech MouseMan+ and FirstMouse+ will also respond to this
5586  * probe routine and act like IntelliMouse.
5587  */
5588 static int
5589 enable_msintelli(struct psm_softc *sc, enum probearg arg)
5590 {
5591         KBDC kbdc = sc->kbdc;
5592         static u_char rate[] = { 200, 100, 80, };
5593         int id;
5594         int i;
5595
5596         /* the special sequence to enable the third button and the roller. */
5597         for (i = 0; i < nitems(rate); ++i)
5598                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
5599                         return (FALSE);
5600         /* the device will give the genuine ID only after the above sequence */
5601         id = get_aux_id(kbdc);
5602         if (id != PSM_INTELLI_ID)
5603                 return (FALSE);
5604
5605         if (arg == PROBE) {
5606                 sc->hw.buttons = 3;
5607                 sc->hw.hwid = id;
5608         }
5609
5610         return (TRUE);
5611 }
5612
5613 /*
5614  * A4 Tech 4D Mouse
5615  * Newer wheel mice from A4 Tech may use the 4D+ protocol.
5616  */
5617 static int
5618 enable_4dmouse(struct psm_softc *sc, enum probearg arg)
5619 {
5620         static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
5621         KBDC kbdc = sc->kbdc;
5622         int id;
5623         int i;
5624
5625         for (i = 0; i < nitems(rate); ++i)
5626                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
5627                         return (FALSE);
5628         id = get_aux_id(kbdc);
5629         /*
5630          * WinEasy 4D, 4 Way Scroll 4D: 6
5631          * Cable-Free 4D: 8 (4DPLUS)
5632          * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
5633          */
5634         if (id != PSM_4DMOUSE_ID)
5635                 return (FALSE);
5636
5637         if (arg == PROBE) {
5638                 sc->hw.buttons = 3;     /* XXX some 4D mice have 4? */
5639                 sc->hw.hwid = id;
5640         }
5641
5642         return (TRUE);
5643 }
5644
5645 /*
5646  * A4 Tech 4D+ Mouse
5647  * Newer wheel mice from A4 Tech seem to use this protocol.
5648  * Older models are recognized as either 4D Mouse or IntelliMouse.
5649  */
5650 static int
5651 enable_4dplus(struct psm_softc *sc, enum probearg arg)
5652 {
5653         KBDC kbdc = sc->kbdc;
5654         int id;
5655
5656         /*
5657          * enable_4dmouse() already issued the following ID sequence...
5658         static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
5659         int i;
5660
5661         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
5662                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
5663                         return (FALSE);
5664         */
5665
5666         id = get_aux_id(kbdc);
5667         switch (id) {
5668         case PSM_4DPLUS_ID:
5669                 break;
5670         case PSM_4DPLUS_RFSW35_ID:
5671                 break;
5672         default:
5673                 return (FALSE);
5674         }
5675
5676         if (arg == PROBE) {
5677                 sc->hw.buttons = (id == PSM_4DPLUS_ID) ? 4 : 3;
5678                 sc->hw.hwid = id;
5679         }
5680
5681         return (TRUE);
5682 }
5683
5684 /* Synaptics Touchpad */
5685 static int
5686 synaptics_sysctl(SYSCTL_HANDLER_ARGS)
5687 {
5688         struct psm_softc *sc;
5689         int error, arg;
5690
5691         if (oidp->oid_arg1 == NULL || oidp->oid_arg2 < 0 ||
5692             oidp->oid_arg2 > SYNAPTICS_SYSCTL_LAST)
5693                 return (EINVAL);
5694
5695         sc = oidp->oid_arg1;
5696
5697         /* Read the current value. */
5698         arg = *(int *)((char *)sc + oidp->oid_arg2);
5699         error = sysctl_handle_int(oidp, &arg, 0, req);
5700
5701         /* Sanity check. */
5702         if (error || !req->newptr)
5703                 return (error);
5704
5705         /*
5706          * Check that the new value is in the concerned node's range
5707          * of values.
5708          */
5709         switch (oidp->oid_arg2) {
5710         case SYNAPTICS_SYSCTL_MIN_PRESSURE:
5711         case SYNAPTICS_SYSCTL_MAX_PRESSURE:
5712                 if (arg < 0 || arg > 255)
5713                         return (EINVAL);
5714                 break;
5715         case SYNAPTICS_SYSCTL_MAX_WIDTH:
5716                 if (arg < 4 || arg > 15)
5717                         return (EINVAL);
5718                 break;
5719         case SYNAPTICS_SYSCTL_MARGIN_TOP:
5720         case SYNAPTICS_SYSCTL_MARGIN_BOTTOM:
5721         case SYNAPTICS_SYSCTL_NA_TOP:
5722         case SYNAPTICS_SYSCTL_NA_BOTTOM:
5723                 if (arg < 0 || arg > sc->synhw.maximumYCoord)
5724                         return (EINVAL);
5725                 break;
5726         case SYNAPTICS_SYSCTL_SOFTBUTTON2_X:
5727         case SYNAPTICS_SYSCTL_SOFTBUTTON3_X:
5728                 /* Softbuttons is clickpad only feature */
5729                 if (!sc->synhw.capClickPad && arg != 0)
5730                         return (EINVAL);
5731                 /* FALLTHROUGH */
5732         case SYNAPTICS_SYSCTL_MARGIN_RIGHT:
5733         case SYNAPTICS_SYSCTL_MARGIN_LEFT:
5734         case SYNAPTICS_SYSCTL_NA_RIGHT:
5735         case SYNAPTICS_SYSCTL_NA_LEFT:
5736                 if (arg < 0 || arg > sc->synhw.maximumXCoord)
5737                         return (EINVAL);
5738                 break;
5739         case SYNAPTICS_SYSCTL_WINDOW_MIN:
5740         case SYNAPTICS_SYSCTL_WINDOW_MAX:
5741         case SYNAPTICS_SYSCTL_TAP_MIN_QUEUE:
5742                 if (arg < 1 || arg > SYNAPTICS_PACKETQUEUE)
5743                         return (EINVAL);
5744                 break;
5745         case SYNAPTICS_SYSCTL_MULTIPLICATOR:
5746         case SYNAPTICS_SYSCTL_WEIGHT_CURRENT:
5747         case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS:
5748         case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA:
5749         case SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED:
5750         case SYNAPTICS_SYSCTL_DIV_MIN:
5751         case SYNAPTICS_SYSCTL_DIV_MAX:
5752         case SYNAPTICS_SYSCTL_DIV_MAX_NA:
5753         case SYNAPTICS_SYSCTL_DIV_LEN:
5754         case SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN:
5755         case SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX:
5756                 if (arg < 1)
5757                         return (EINVAL);
5758                 break;
5759         case SYNAPTICS_SYSCTL_TAP_MAX_DELTA:
5760         case SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT:
5761         case SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA:
5762                 if (arg < 0)
5763                         return (EINVAL);
5764                 break;
5765         case SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA:
5766                 if (arg < -sc->synhw.maximumXCoord ||
5767                     arg > sc->synhw.maximumXCoord)
5768                         return (EINVAL);
5769                 break;
5770         case SYNAPTICS_SYSCTL_SOFTBUTTONS_Y:
5771                 /* Softbuttons is clickpad only feature */
5772                 if (!sc->synhw.capClickPad && arg != 0)
5773                         return (EINVAL);
5774                 /* FALLTHROUGH */
5775         case SYNAPTICS_SYSCTL_VSCROLL_VER_AREA:
5776                 if (arg < -sc->synhw.maximumYCoord ||
5777                     arg > sc->synhw.maximumYCoord)
5778                         return (EINVAL);
5779                 break;
5780         case SYNAPTICS_SYSCTL_TOUCHPAD_OFF:
5781         case SYNAPTICS_SYSCTL_THREE_FINGER_DRAG:
5782         case SYNAPTICS_SYSCTL_NATURAL_SCROLL:
5783                 if (arg < 0 || arg > 1)
5784                         return (EINVAL);
5785                 break;
5786         default:
5787                 return (EINVAL);
5788         }
5789
5790         /* Update. */
5791         *(int *)((char *)sc + oidp->oid_arg2) = arg;
5792
5793         return (error);
5794 }
5795
5796 static void
5797 synaptics_sysctl_create_softbuttons_tree(struct psm_softc *sc)
5798 {
5799         /*
5800          * Set predefined sizes for softbuttons.
5801          * Values are taken to match HP Pavilion dv6 clickpad drawings
5802          * with thin middle softbutton placed on separator
5803          */
5804
5805         /* hw.psm.synaptics.softbuttons_y */
5806         sc->syninfo.softbuttons_y = sc->synhw.topButtonPad ? -1700 : 1700;
5807         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5808             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5809             "softbuttons_y",
5810             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5811             sc, SYNAPTICS_SYSCTL_SOFTBUTTONS_Y,
5812             synaptics_sysctl, "I",
5813             "Vertical size of softbuttons area");
5814
5815         /* hw.psm.synaptics.softbutton2_x */
5816         sc->syninfo.softbutton2_x = 3100;
5817         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5818             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5819             "softbutton2_x",
5820             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5821             sc, SYNAPTICS_SYSCTL_SOFTBUTTON2_X,
5822             synaptics_sysctl, "I",
5823             "Horisontal position of 2-nd softbutton left edge (0-disable)");
5824
5825         /* hw.psm.synaptics.softbutton3_x */
5826         sc->syninfo.softbutton3_x = 3900;
5827         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5828             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5829             "softbutton3_x",
5830             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5831             sc, SYNAPTICS_SYSCTL_SOFTBUTTON3_X,
5832             synaptics_sysctl, "I",
5833             "Horisontal position of 3-rd softbutton left edge (0-disable)");
5834 }
5835
5836 static void
5837 synaptics_sysctl_create_tree(struct psm_softc *sc, const char *name,
5838     const char *descr)
5839 {
5840
5841         if (sc->syninfo.sysctl_tree != NULL)
5842                 return;
5843
5844         /* Attach extra synaptics sysctl nodes under hw.psm.synaptics */
5845         sysctl_ctx_init(&sc->syninfo.sysctl_ctx);
5846         sc->syninfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->syninfo.sysctl_ctx,
5847             SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, name,
5848             CTLFLAG_RD | CTLFLAG_MPSAFE, 0, descr);
5849
5850         /* hw.psm.synaptics.directional_scrolls. */
5851         sc->syninfo.directional_scrolls = 0;
5852         SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
5853             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5854             "directional_scrolls", CTLFLAG_RW|CTLFLAG_ANYBODY,
5855             &sc->syninfo.directional_scrolls, 0,
5856             "Enable hardware scrolling pad (if non-zero) or register it as "
5857             "extended buttons (if 0)");
5858
5859         /* hw.psm.synaptics.max_x. */
5860         sc->syninfo.max_x = 6143;
5861         SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
5862             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5863             "max_x", CTLFLAG_RD|CTLFLAG_ANYBODY,
5864             &sc->syninfo.max_x, 0,
5865             "Horizontal reporting range");
5866
5867         /* hw.psm.synaptics.max_y. */
5868         sc->syninfo.max_y = 6143;
5869         SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
5870             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5871             "max_y", CTLFLAG_RD|CTLFLAG_ANYBODY,
5872             &sc->syninfo.max_y, 0,
5873             "Vertical reporting range");
5874
5875         /*
5876          * Turn off two finger scroll if we have a
5877          * physical area reserved for scrolling or when
5878          * there's no multi finger support.
5879          */
5880         if (sc->synhw.verticalScroll || (sc->synhw.capMultiFinger == 0 &&
5881                                          sc->synhw.capAdvancedGestures == 0))
5882                 sc->syninfo.two_finger_scroll = 0;
5883         else
5884                 sc->syninfo.two_finger_scroll = 1;
5885         /* hw.psm.synaptics.two_finger_scroll. */
5886         SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
5887             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5888             "two_finger_scroll", CTLFLAG_RW|CTLFLAG_ANYBODY,
5889             &sc->syninfo.two_finger_scroll, 0,
5890             "Enable two finger scrolling");
5891
5892         /* hw.psm.synaptics.min_pressure. */
5893         sc->syninfo.min_pressure = 32;
5894         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5895             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5896             "min_pressure",
5897             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5898             sc, SYNAPTICS_SYSCTL_MIN_PRESSURE,
5899             synaptics_sysctl, "I",
5900             "Minimum pressure required to start an action");
5901
5902         /* hw.psm.synaptics.max_pressure. */
5903         sc->syninfo.max_pressure = 220;
5904         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5905             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5906             "max_pressure",
5907             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5908             sc, SYNAPTICS_SYSCTL_MAX_PRESSURE,
5909             synaptics_sysctl, "I",
5910             "Maximum pressure to detect palm");
5911
5912         /* hw.psm.synaptics.max_width. */
5913         sc->syninfo.max_width = 10;
5914         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5915             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5916             "max_width",
5917             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5918             sc, SYNAPTICS_SYSCTL_MAX_WIDTH,
5919             synaptics_sysctl, "I",
5920             "Maximum finger width to detect palm");
5921
5922         /* hw.psm.synaptics.top_margin. */
5923         sc->syninfo.margin_top = 200;
5924         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5925             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5926             "margin_top",
5927             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5928             sc, SYNAPTICS_SYSCTL_MARGIN_TOP,
5929             synaptics_sysctl, "I",
5930             "Top margin");
5931
5932         /* hw.psm.synaptics.right_margin. */
5933         sc->syninfo.margin_right = 200;
5934         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5935             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5936             "margin_right",
5937             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5938             sc, SYNAPTICS_SYSCTL_MARGIN_RIGHT,
5939             synaptics_sysctl, "I",
5940             "Right margin");
5941
5942         /* hw.psm.synaptics.bottom_margin. */
5943         sc->syninfo.margin_bottom = 200;
5944         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5945             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5946             "margin_bottom",
5947             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5948             sc, SYNAPTICS_SYSCTL_MARGIN_BOTTOM,
5949             synaptics_sysctl, "I",
5950             "Bottom margin");
5951
5952         /* hw.psm.synaptics.left_margin. */
5953         sc->syninfo.margin_left = 200;
5954         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5955             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5956             "margin_left",
5957             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5958             sc, SYNAPTICS_SYSCTL_MARGIN_LEFT,
5959             synaptics_sysctl, "I",
5960             "Left margin");
5961
5962         /* hw.psm.synaptics.na_top. */
5963         sc->syninfo.na_top = 1783;
5964         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5965             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5966             "na_top",
5967             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5968             sc, SYNAPTICS_SYSCTL_NA_TOP,
5969             synaptics_sysctl, "I",
5970             "Top noisy area, where weight_previous_na is used instead "
5971             "of weight_previous");
5972
5973         /* hw.psm.synaptics.na_right. */
5974         sc->syninfo.na_right = 563;
5975         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5976             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5977             "na_right",
5978             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5979             sc, SYNAPTICS_SYSCTL_NA_RIGHT,
5980             synaptics_sysctl, "I",
5981             "Right noisy area, where weight_previous_na is used instead "
5982             "of weight_previous");
5983
5984         /* hw.psm.synaptics.na_bottom. */
5985         sc->syninfo.na_bottom = 1408;
5986         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5987             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5988             "na_bottom",
5989             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
5990             sc, SYNAPTICS_SYSCTL_NA_BOTTOM,
5991             synaptics_sysctl, "I",
5992             "Bottom noisy area, where weight_previous_na is used instead "
5993             "of weight_previous");
5994
5995         /* hw.psm.synaptics.na_left. */
5996         sc->syninfo.na_left = 1600;
5997         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
5998             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
5999             "na_left",
6000             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6001             sc, SYNAPTICS_SYSCTL_NA_LEFT,
6002             synaptics_sysctl, "I",
6003             "Left noisy area, where weight_previous_na is used instead "
6004             "of weight_previous");
6005
6006         /* hw.psm.synaptics.window_min. */
6007         sc->syninfo.window_min = 4;
6008         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6009             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6010             "window_min",
6011             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6012             sc, SYNAPTICS_SYSCTL_WINDOW_MIN,
6013             synaptics_sysctl, "I",
6014             "Minimum window size to start an action");
6015
6016         /* hw.psm.synaptics.window_max. */
6017         sc->syninfo.window_max = 10;
6018         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6019             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6020             "window_max",
6021             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6022             sc, SYNAPTICS_SYSCTL_WINDOW_MAX,
6023             synaptics_sysctl, "I",
6024             "Maximum window size");
6025
6026         /* hw.psm.synaptics.multiplicator. */
6027         sc->syninfo.multiplicator = 10000;
6028         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6029             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6030             "multiplicator",
6031             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6032             sc, SYNAPTICS_SYSCTL_MULTIPLICATOR,
6033             synaptics_sysctl, "I",
6034             "Multiplicator to increase precision in averages and divisions");
6035
6036         /* hw.psm.synaptics.weight_current. */
6037         sc->syninfo.weight_current = 3;
6038         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6039             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6040             "weight_current",
6041             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6042             sc, SYNAPTICS_SYSCTL_WEIGHT_CURRENT,
6043             synaptics_sysctl, "I",
6044             "Weight of the current movement in the new average");
6045
6046         /* hw.psm.synaptics.weight_previous. */
6047         sc->syninfo.weight_previous = 6;
6048         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6049             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6050             "weight_previous",
6051             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6052             sc, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS,
6053             synaptics_sysctl, "I",
6054             "Weight of the previous average");
6055
6056         /* hw.psm.synaptics.weight_previous_na. */
6057         sc->syninfo.weight_previous_na = 20;
6058         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6059             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6060             "weight_previous_na",
6061             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6062             sc, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA,
6063             synaptics_sysctl, "I",
6064             "Weight of the previous average (inside the noisy area)");
6065
6066         /* hw.psm.synaptics.weight_len_squared. */
6067         sc->syninfo.weight_len_squared = 2000;
6068         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6069             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6070             "weight_len_squared",
6071             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6072             sc, SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED,
6073             synaptics_sysctl, "I",
6074             "Length (squared) of segments where weight_previous "
6075             "starts to decrease");
6076
6077         /* hw.psm.synaptics.div_min. */
6078         sc->syninfo.div_min = 9;
6079         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6080             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6081             "div_min",
6082             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6083             sc, SYNAPTICS_SYSCTL_DIV_MIN,
6084             synaptics_sysctl, "I",
6085             "Divisor for fast movements");
6086
6087         /* hw.psm.synaptics.div_max. */
6088         sc->syninfo.div_max = 17;
6089         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6090             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6091             "div_max",
6092             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6093             sc, SYNAPTICS_SYSCTL_DIV_MAX,
6094             synaptics_sysctl, "I",
6095             "Divisor for slow movements");
6096
6097         /* hw.psm.synaptics.div_max_na. */
6098         sc->syninfo.div_max_na = 30;
6099         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6100             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6101             "div_max_na",
6102             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6103             sc, SYNAPTICS_SYSCTL_DIV_MAX_NA,
6104             synaptics_sysctl, "I",
6105             "Divisor with slow movements (inside the noisy area)");
6106
6107         /* hw.psm.synaptics.div_len. */
6108         sc->syninfo.div_len = 100;
6109         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6110             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6111             "div_len",
6112             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6113             sc, SYNAPTICS_SYSCTL_DIV_LEN,
6114             synaptics_sysctl, "I",
6115             "Length of segments where div_max starts to decrease");
6116
6117         /* hw.psm.synaptics.tap_max_delta. */
6118         sc->syninfo.tap_max_delta = 80;
6119         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6120             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6121             "tap_max_delta",
6122             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6123             sc, SYNAPTICS_SYSCTL_TAP_MAX_DELTA,
6124             synaptics_sysctl, "I",
6125             "Length of segments above which a tap is ignored");
6126
6127         /* hw.psm.synaptics.tap_min_queue. */
6128         sc->syninfo.tap_min_queue = 2;
6129         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6130             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6131             "tap_min_queue",
6132             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6133             sc, SYNAPTICS_SYSCTL_TAP_MIN_QUEUE,
6134             synaptics_sysctl, "I",
6135             "Number of packets required to consider a tap");
6136
6137         /* hw.psm.synaptics.taphold_timeout. */
6138         sc->gesture.in_taphold = 0;
6139         sc->syninfo.taphold_timeout = tap_timeout;
6140         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6141             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6142             "taphold_timeout",
6143             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6144             sc, SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT,
6145             synaptics_sysctl, "I",
6146             "Maximum elapsed time between two taps to consider a tap-hold "
6147             "action");
6148
6149         /* hw.psm.synaptics.vscroll_hor_area. */
6150         sc->syninfo.vscroll_hor_area = 0; /* 1300 */
6151         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6152             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6153             "vscroll_hor_area",
6154             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6155             sc, SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA,
6156             synaptics_sysctl, "I",
6157             "Area reserved for horizontal virtual scrolling");
6158
6159         /* hw.psm.synaptics.vscroll_ver_area. */
6160         sc->syninfo.vscroll_ver_area = -400 - sc->syninfo.margin_right;
6161         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6162             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6163             "vscroll_ver_area",
6164             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6165             sc, SYNAPTICS_SYSCTL_VSCROLL_VER_AREA,
6166             synaptics_sysctl, "I",
6167             "Area reserved for vertical virtual scrolling");
6168
6169         /* hw.psm.synaptics.vscroll_min_delta. */
6170         sc->syninfo.vscroll_min_delta = 50;
6171         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6172             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6173             "vscroll_min_delta",
6174             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6175             sc, SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA,
6176             synaptics_sysctl, "I",
6177             "Minimum movement to consider virtual scrolling");
6178
6179         /* hw.psm.synaptics.vscroll_div_min. */
6180         sc->syninfo.vscroll_div_min = 100;
6181         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6182             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6183             "vscroll_div_min",
6184             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6185             sc, SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN,
6186             synaptics_sysctl, "I",
6187             "Divisor for fast scrolling");
6188
6189         /* hw.psm.synaptics.vscroll_div_min. */
6190         sc->syninfo.vscroll_div_max = 150;
6191         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6192             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6193             "vscroll_div_max",
6194             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6195             sc, SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX,
6196             synaptics_sysctl, "I",
6197             "Divisor for slow scrolling");
6198
6199         /* hw.psm.synaptics.touchpad_off. */
6200         sc->syninfo.touchpad_off = 0;
6201         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6202             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6203             "touchpad_off",
6204             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6205             sc, SYNAPTICS_SYSCTL_TOUCHPAD_OFF,
6206             synaptics_sysctl, "I",
6207             "Turn off touchpad");
6208
6209         sc->syninfo.three_finger_drag = 0;
6210         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6211             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6212             "three_finger_drag",
6213             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6214             sc, SYNAPTICS_SYSCTL_THREE_FINGER_DRAG,
6215             synaptics_sysctl, "I",
6216             "Enable dragging with three fingers");
6217
6218         /* hw.psm.synaptics.natural_scroll. */
6219         sc->syninfo.natural_scroll = 0;
6220         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
6221             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
6222             "natural_scroll",
6223             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6224             sc, SYNAPTICS_SYSCTL_NATURAL_SCROLL,
6225             synaptics_sysctl, "I",
6226             "Enable natural scrolling");
6227
6228         sc->syninfo.softbuttons_y = 0;
6229         sc->syninfo.softbutton2_x = 0;
6230         sc->syninfo.softbutton3_x = 0;
6231
6232         /* skip softbuttons sysctl on not clickpads */
6233         if (sc->synhw.capClickPad)
6234                 synaptics_sysctl_create_softbuttons_tree(sc);
6235 }
6236
6237 static int
6238 synaptics_preferred_mode(struct psm_softc *sc) {
6239         int mode_byte;
6240
6241         /* Check if we are in relative mode */
6242         if (sc->hw.model != MOUSE_MODEL_SYNAPTICS) {
6243                 if (tap_enabled == 0)
6244                         /*
6245                          * Disable tap & drag gestures. We use a Mode Byte
6246                          * and set the DisGest bit (see Â§2.5 of Synaptics
6247                          * TouchPad Interfacing Guide).
6248                          */
6249                         return (0x04);
6250                 else
6251                         /*
6252                          * Enable tap & drag gestures. We use a Mode Byte
6253                          * and clear the DisGest bit (see Â§2.5 of Synaptics
6254                          * TouchPad Interfacing Guide).
6255                          */
6256                         return (0x00);
6257         }
6258
6259         mode_byte = 0xc4;
6260
6261         /* request wmode where available */
6262         if (sc->synhw.capExtended)
6263                 mode_byte |= 1;
6264
6265         return mode_byte;
6266 }
6267
6268 static void
6269 synaptics_set_mode(struct psm_softc *sc, int mode_byte) {
6270         mouse_ext_command(sc->kbdc, mode_byte);
6271
6272         /* "Commit" the Set Mode Byte command sent above. */
6273         set_mouse_sampling_rate(sc->kbdc, 20);
6274
6275         /*
6276          * Enable advanced gestures mode if supported and we are not entering
6277          * passthrough or relative mode.
6278          */
6279         if ((sc->synhw.capAdvancedGestures || sc->synhw.capReportsV) &&
6280             sc->hw.model == MOUSE_MODEL_SYNAPTICS && !(mode_byte & (1 << 5))) {
6281                 mouse_ext_command(sc->kbdc, SYNAPTICS_READ_MODEL_ID);
6282                 set_mouse_sampling_rate(sc->kbdc, 0xc8);
6283         }
6284 }
6285
6286 /*
6287  * AUX MUX detection code should be placed at very beginning of probe sequence
6288  * at least before 4-byte protocol mouse probes e.g. MS IntelliMouse probe as
6289  * latter can trigger switching the MUX to incompatible state.
6290  */
6291 static int
6292 enable_synaptics_mux(struct psm_softc *sc, enum probearg arg)
6293 {
6294         KBDC kbdc = sc->kbdc;
6295         int port, version;
6296         int probe = FALSE;
6297         int active_ports_count = 0;
6298         int active_ports_mask = 0;
6299
6300         if (mux_disabled != 0)
6301                 return (FALSE);
6302
6303         version = enable_aux_mux(kbdc);
6304         if (version == -1)
6305                 return (FALSE);
6306
6307         for (port = 0; port < KBDC_AUX_MUX_NUM_PORTS; port++) {
6308                 VLOG(3, (LOG_DEBUG, "aux_mux: ping port %d\n", port));
6309                 set_active_aux_mux_port(kbdc, port);
6310                 if (enable_aux_dev(kbdc) && disable_aux_dev(kbdc)) {
6311                         active_ports_count++;
6312                         active_ports_mask |= 1 << port;
6313                 }
6314         }
6315
6316         if (verbose >= 2)
6317                 printf("Active Multiplexing PS/2 controller v%d.%d with %d "
6318                     "active port(s)\n", version >> 4 & 0x0f, version & 0x0f,
6319                     active_ports_count);
6320
6321         /* psm has a special support for GenMouse + SynTouchpad combination */
6322         if (active_ports_count >= 2) {
6323                 for (port = 0; port < KBDC_AUX_MUX_NUM_PORTS; port++) {
6324                         if ((active_ports_mask & 1 << port) == 0)
6325                                 continue;
6326                         VLOG(3, (LOG_DEBUG, "aux_mux: probe port %d\n", port));
6327                         set_active_aux_mux_port(kbdc, port);
6328                         probe = enable_synaptics(sc, arg);
6329                         if (probe) {
6330                                 if (arg == PROBE)
6331                                         sc->muxport = port;
6332                                 break;
6333                         }
6334                 }
6335         }
6336
6337         /* IRQ handler does not support active multiplexing mode */
6338         disable_aux_mux(kbdc);
6339
6340         /* Is MUX still alive after switching back to legacy mode? */
6341         if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
6342                 /*
6343                  * On some laptops e.g. Lenovo X121e dead AUX MUX can be
6344                  * brought back to life with resetting of keyboard.
6345                  */
6346                 reset_kbd(kbdc);
6347                 if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
6348                         printf("psm%d: AUX MUX hang detected!\n", sc->unit);
6349                         printf("Consider adding hw.psm.mux_disabled=1 to "
6350                             "loader tunables\n");
6351                 }
6352         }
6353         empty_both_buffers(kbdc, 10);   /* remove stray data if any */
6354
6355         return (probe);
6356 }
6357
6358 static int
6359 enable_synaptics(struct psm_softc *sc, enum probearg arg)
6360 {
6361         device_t psmcpnp;
6362         struct psmcpnp_softc *psmcpnp_sc;
6363         KBDC kbdc = sc->kbdc;
6364         synapticshw_t synhw;
6365         int status[3];
6366         int buttons;
6367
6368         VLOG(3, (LOG_DEBUG, "synaptics: BEGIN init\n"));
6369
6370         /*
6371          * Just to be on the safe side: this avoids troubles with
6372          * following mouse_ext_command() when the previous command
6373          * was PSMC_SET_RESOLUTION. Set Scaling has no effect on
6374          * Synaptics Touchpad behaviour.
6375          */
6376         set_mouse_scaling(kbdc, 1);
6377
6378         /* Identify the Touchpad version. */
6379         if (mouse_ext_command(kbdc, SYNAPTICS_READ_IDENTITY) == 0)
6380                 return (FALSE);
6381         if (get_mouse_status(kbdc, status, 0, 3) != 3)
6382                 return (FALSE);
6383         if (status[1] != 0x47)
6384                 return (FALSE);
6385
6386         bzero(&synhw, sizeof(synhw));
6387         synhw.infoMinor = status[0];
6388         synhw.infoMajor = status[2] & 0x0f;
6389
6390         if (verbose >= 2)
6391                 printf("Synaptics Touchpad v%d.%d\n", synhw.infoMajor,
6392                     synhw.infoMinor);
6393
6394         if (synhw.infoMajor < 4) {
6395                 printf("  Unsupported (pre-v4) Touchpad detected\n");
6396                 return (FALSE);
6397         }
6398
6399         /* Get the Touchpad model information. */
6400         if (mouse_ext_command(kbdc, SYNAPTICS_READ_MODEL_ID) == 0)
6401                 return (FALSE);
6402         if (get_mouse_status(kbdc, status, 0, 3) != 3)
6403                 return (FALSE);
6404         if ((status[1] & 0x01) != 0) {
6405                 printf("  Failed to read model information\n");
6406                 return (FALSE);
6407         }
6408
6409         synhw.infoRot180   = (status[0] & 0x80) != 0;
6410         synhw.infoPortrait = (status[0] & 0x40) != 0;
6411         synhw.infoSensor   =  status[0] & 0x3f;
6412         synhw.infoHardware = (status[1] & 0xfe) >> 1;
6413         synhw.infoNewAbs   = (status[2] & 0x80) != 0;
6414         synhw.capPen       = (status[2] & 0x40) != 0;
6415         synhw.infoSimplC   = (status[2] & 0x20) != 0;
6416         synhw.infoGeometry =  status[2] & 0x0f;
6417
6418         if (verbose >= 2) {
6419                 printf("  Model information:\n");
6420                 printf("   infoRot180: %d\n", synhw.infoRot180);
6421                 printf("   infoPortrait: %d\n", synhw.infoPortrait);
6422                 printf("   infoSensor: %d\n", synhw.infoSensor);
6423                 printf("   infoHardware: %d\n", synhw.infoHardware);
6424                 printf("   infoNewAbs: %d\n", synhw.infoNewAbs);
6425                 printf("   capPen: %d\n", synhw.capPen);
6426                 printf("   infoSimplC: %d\n", synhw.infoSimplC);
6427                 printf("   infoGeometry: %d\n", synhw.infoGeometry);
6428         }
6429
6430         /* Read the extended capability bits. */
6431         if (mouse_ext_command(kbdc, SYNAPTICS_READ_CAPABILITIES) == 0)
6432                 return (FALSE);
6433         if (get_mouse_status(kbdc, status, 0, 3) != 3)
6434                 return (FALSE);
6435         if (!SYNAPTICS_VERSION_GE(synhw, 7, 5) && status[1] != 0x47) {
6436                 printf("  Failed to read extended capability bits\n");
6437                 return (FALSE);
6438         }
6439
6440         psmcpnp = devclass_get_device(devclass_find(PSMCPNP_DRIVER_NAME),
6441             sc->unit);
6442         psmcpnp_sc = (psmcpnp != NULL) ? device_get_softc(psmcpnp) : NULL;
6443
6444         /* Set the different capabilities when they exist. */
6445         buttons = 0;
6446         synhw.capExtended = (status[0] & 0x80) != 0;
6447         if (synhw.capExtended) {
6448                 synhw.nExtendedQueries = (status[0] & 0x70) >> 4;
6449                 synhw.capMiddle        = (status[0] & 0x04) != 0;
6450                 synhw.capPassthrough   = (status[2] & 0x80) != 0;
6451                 synhw.capLowPower      = (status[2] & 0x40) != 0;
6452                 synhw.capMultiFingerReport =
6453                                          (status[2] & 0x20) != 0;
6454                 synhw.capSleep         = (status[2] & 0x10) != 0;
6455                 synhw.capFourButtons   = (status[2] & 0x08) != 0;
6456                 synhw.capBallistics    = (status[2] & 0x04) != 0;
6457                 synhw.capMultiFinger   = (status[2] & 0x02) != 0;
6458                 synhw.capPalmDetect    = (status[2] & 0x01) != 0;
6459
6460                 if (!set_mouse_scaling(kbdc, 1))
6461                         return (FALSE);
6462                 if (mouse_ext_command(kbdc, SYNAPTICS_READ_RESOLUTIONS) == 0)
6463                         return (FALSE);
6464                 if (get_mouse_status(kbdc, status, 0, 3) != 3)
6465                         return (FALSE);
6466
6467                 if (status[0] != 0 && (status[1] & 0x80) && status[2] != 0) {
6468                         synhw.infoXupmm = status[0];
6469                         synhw.infoYupmm = status[2];
6470                 }
6471
6472                 if (verbose >= 2) {
6473                         printf("  Extended capabilities:\n");
6474                         printf("   capExtended: %d\n", synhw.capExtended);
6475                         printf("   capMiddle: %d\n", synhw.capMiddle);
6476                         printf("   nExtendedQueries: %d\n",
6477                             synhw.nExtendedQueries);
6478                         printf("   capPassthrough: %d\n", synhw.capPassthrough);
6479                         printf("   capLowPower: %d\n", synhw.capLowPower);
6480                         printf("   capMultiFingerReport: %d\n",
6481                             synhw.capMultiFingerReport);
6482                         printf("   capSleep: %d\n", synhw.capSleep);
6483                         printf("   capFourButtons: %d\n", synhw.capFourButtons);
6484                         printf("   capBallistics: %d\n", synhw.capBallistics);
6485                         printf("   capMultiFinger: %d\n", synhw.capMultiFinger);
6486                         printf("   capPalmDetect: %d\n", synhw.capPalmDetect);
6487                         printf("   infoXupmm: %d\n", synhw.infoXupmm);
6488                         printf("   infoYupmm: %d\n", synhw.infoYupmm);
6489                 }
6490
6491                 /*
6492                  * If nExtendedQueries is 1 or greater, then the TouchPad
6493                  * supports this number of extended queries. We can load
6494                  * more information about buttons using query 0x09.
6495                  */
6496                 if (synhw.nExtendedQueries >= 1) {
6497                         if (!set_mouse_scaling(kbdc, 1))
6498                                 return (FALSE);
6499                         if (mouse_ext_command(kbdc,
6500                             SYNAPTICS_READ_EXTENDED) == 0)
6501                                 return (FALSE);
6502                         if (get_mouse_status(kbdc, status, 0, 3) != 3)
6503                                 return (FALSE);
6504                         synhw.verticalScroll   = (status[0] & 0x01) != 0;
6505                         synhw.horizontalScroll = (status[0] & 0x02) != 0;
6506                         synhw.verticalWheel    = (status[0] & 0x08) != 0;
6507                         synhw.nExtendedButtons = (status[1] & 0xf0) >> 4;
6508                         synhw.capEWmode        = (status[0] & 0x04) != 0;
6509                         if (verbose >= 2) {
6510                                 printf("  Extended model ID:\n");
6511                                 printf("   verticalScroll: %d\n",
6512                                     synhw.verticalScroll);
6513                                 printf("   horizontalScroll: %d\n",
6514                                     synhw.horizontalScroll);
6515                                 printf("   verticalWheel: %d\n",
6516                                     synhw.verticalWheel);
6517                                 printf("   nExtendedButtons: %d\n",
6518                                     synhw.nExtendedButtons);
6519                                 printf("   capEWmode: %d\n",
6520                                     synhw.capEWmode);
6521                         }
6522                         /*
6523                          * Add the number of extended buttons to the total
6524                          * button support count, including the middle button
6525                          * if capMiddle support bit is set.
6526                          */
6527                         buttons = synhw.nExtendedButtons + synhw.capMiddle;
6528                 } else
6529                         /*
6530                          * If the capFourButtons support bit is set,
6531                          * add a fourth button to the total button count.
6532                          */
6533                         buttons = synhw.capFourButtons ? 1 : 0;
6534
6535                 /* Read the continued capabilities bits. */
6536                 if (synhw.nExtendedQueries >= 4) {
6537                         if (!set_mouse_scaling(kbdc, 1))
6538                                 return (FALSE);
6539                         if (mouse_ext_command(kbdc,
6540                             SYNAPTICS_READ_CAPABILITIES_CONT) == 0)
6541                                 return (FALSE);
6542                         if (get_mouse_status(kbdc, status, 0, 3) != 3)
6543                                 return (FALSE);
6544
6545                         synhw.capClickPad         = (status[1] & 0x01) << 1;
6546                         synhw.capClickPad        |= (status[0] & 0x10) != 0;
6547                         synhw.capDeluxeLEDs       = (status[1] & 0x02) != 0;
6548                         synhw.noAbsoluteFilter    = (status[1] & 0x04) != 0;
6549                         synhw.capReportsV         = (status[1] & 0x08) != 0;
6550                         synhw.capUniformClickPad  = (status[1] & 0x10) != 0;
6551                         synhw.capReportsMin       = (status[1] & 0x20) != 0;
6552                         synhw.capInterTouch       = (status[1] & 0x40) != 0;
6553                         synhw.capReportsMax       = (status[0] & 0x02) != 0;
6554                         synhw.capClearPad         = (status[0] & 0x04) != 0;
6555                         synhw.capAdvancedGestures = (status[0] & 0x08) != 0;
6556                         synhw.capCoveredPad       = (status[0] & 0x80) != 0;
6557
6558                         if (synhw.capReportsMax) {
6559                                 if (!set_mouse_scaling(kbdc, 1))
6560                                         return (FALSE);
6561                                 if (mouse_ext_command(kbdc,
6562                                     SYNAPTICS_READ_MAX_COORDS) == 0)
6563                                         return (FALSE);
6564                                 if (get_mouse_status(kbdc, status, 0, 3) != 3)
6565                                         return (FALSE);
6566
6567                                 synhw.maximumXCoord = (status[0] << 5) |
6568                                                      ((status[1] & 0x0f) << 1);
6569                                 synhw.maximumYCoord = (status[2] << 5) |
6570                                                      ((status[1] & 0xf0) >> 3);
6571                         } else {
6572                                 /*
6573                                  * Typical bezel limits. Taken from 'Synaptics
6574                                  * PS/2 * TouchPad Interfacing Guide' p.3.2.3.
6575                                  */
6576                                 synhw.maximumXCoord = 5472;
6577                                 synhw.maximumYCoord = 4448;
6578                         }
6579
6580                         if (synhw.capReportsMin) {
6581                                 if (!set_mouse_scaling(kbdc, 1))
6582                                         return (FALSE);
6583                                 if (mouse_ext_command(kbdc,
6584                                     SYNAPTICS_READ_MIN_COORDS) == 0)
6585                                         return (FALSE);
6586                                 if (get_mouse_status(kbdc, status, 0, 3) != 3)
6587                                         return (FALSE);
6588
6589                                 synhw.minimumXCoord = (status[0] << 5) |
6590                                                      ((status[1] & 0x0f) << 1);
6591                                 synhw.minimumYCoord = (status[2] << 5) |
6592                                                      ((status[1] & 0xf0) >> 3);
6593                         } else {
6594                                 /*
6595                                  * Typical bezel limits. Taken from 'Synaptics
6596                                  * PS/2 * TouchPad Interfacing Guide' p.3.2.3.
6597                                  */
6598                                 synhw.minimumXCoord = 1472;
6599                                 synhw.minimumYCoord = 1408;
6600                         }
6601
6602                         /*
6603                          * ClickPad properties are not exported through PS/2
6604                          * protocol. Detection is based on controller's PnP ID.
6605                          */
6606                         if (synhw.capClickPad && psmcpnp_sc != NULL) {
6607                                 switch (psmcpnp_sc->type) {
6608                                 case PSMCPNP_FORCEPAD:
6609                                         synhw.forcePad = 1;
6610                                         break;
6611                                 case PSMCPNP_TOPBUTTONPAD:
6612                                         synhw.topButtonPad = 1;
6613                                         break;
6614                                 default:
6615                                         break;
6616                                 }
6617                         }
6618
6619                         if (verbose >= 2) {
6620                                 printf("  Continued capabilities:\n");
6621                                 printf("   capClickPad: %d\n",
6622                                        synhw.capClickPad);
6623                                 printf("   capDeluxeLEDs: %d\n",
6624                                        synhw.capDeluxeLEDs);
6625                                 printf("   noAbsoluteFilter: %d\n",
6626                                        synhw.noAbsoluteFilter);
6627                                 printf("   capReportsV: %d\n",
6628                                        synhw.capReportsV);
6629                                 printf("   capUniformClickPad: %d\n",
6630                                        synhw.capUniformClickPad);
6631                                 printf("   capReportsMin: %d\n",
6632                                        synhw.capReportsMin);
6633                                 printf("   capInterTouch: %d\n",
6634                                        synhw.capInterTouch);
6635                                 printf("   capReportsMax: %d\n",
6636                                        synhw.capReportsMax);
6637                                 printf("   capClearPad: %d\n",
6638                                        synhw.capClearPad);
6639                                 printf("   capAdvancedGestures: %d\n",
6640                                        synhw.capAdvancedGestures);
6641                                 printf("   capCoveredPad: %d\n",
6642                                        synhw.capCoveredPad);
6643                                 if (synhw.capReportsMax) {
6644                                         printf("   maximumXCoord: %d\n",
6645                                                synhw.maximumXCoord);
6646                                         printf("   maximumYCoord: %d\n",
6647                                                synhw.maximumYCoord);
6648                                 }
6649                                 if (synhw.capReportsMin) {
6650                                         printf("   minimumXCoord: %d\n",
6651                                                synhw.minimumXCoord);
6652                                         printf("   minimumYCoord: %d\n",
6653                                                synhw.minimumYCoord);
6654                                 }
6655                                 if (synhw.capClickPad) {
6656                                         printf("  Clickpad capabilities:\n");
6657                                         printf("   forcePad: %d\n",
6658                                                synhw.forcePad);
6659                                         printf("   topButtonPad: %d\n",
6660                                                synhw.topButtonPad);
6661                                 }
6662                         }
6663                         buttons += synhw.capClickPad;
6664                 }
6665         }
6666
6667         if (verbose >= 2) {
6668                 if (synhw.capExtended)
6669                         printf("  Additional Buttons: %d\n", buttons);
6670                 else
6671                         printf("  No extended capabilities\n");
6672         }
6673
6674         /*
6675          * Add the default number of 3 buttons to the total
6676          * count of supported buttons reported above.
6677          */
6678         buttons += 3;
6679
6680         /*
6681          * Read the mode byte.
6682          *
6683          * XXX: Note the Synaptics documentation also defines the first
6684          * byte of the response to this query to be a constant 0x3b, this
6685          * does not appear to be true for Touchpads with guest devices.
6686          */
6687         if (mouse_ext_command(kbdc, SYNAPTICS_READ_MODES) == 0)
6688                 return (FALSE);
6689         if (get_mouse_status(kbdc, status, 0, 3) != 3)
6690                 return (FALSE);
6691         if (!SYNAPTICS_VERSION_GE(synhw, 7, 5) && status[1] != 0x47) {
6692                 printf("  Failed to read mode byte\n");
6693                 return (FALSE);
6694         }
6695
6696         if (arg == PROBE)
6697                 sc->synhw = synhw;
6698         if (!synaptics_support)
6699                 return (FALSE);
6700
6701         /* Set mouse type just now for synaptics_set_mode() */
6702         sc->hw.model = MOUSE_MODEL_SYNAPTICS;
6703
6704         synaptics_set_mode(sc, synaptics_preferred_mode(sc));
6705
6706         if (trackpoint_support && synhw.capPassthrough) {
6707                 enable_trackpoint(sc, arg);
6708         }
6709
6710         VLOG(3, (LOG_DEBUG, "synaptics: END init (%d buttons)\n", buttons));
6711
6712         if (arg == PROBE) {
6713                 /* Create sysctl tree. */
6714                 synaptics_sysctl_create_tree(sc, "synaptics",
6715                     "Synaptics TouchPad");
6716                 sc->hw.buttons = buttons;
6717         }
6718
6719         return (TRUE);
6720 }
6721
6722 static void
6723 synaptics_passthrough_on(struct psm_softc *sc)
6724 {
6725         VLOG(2, (LOG_NOTICE, "psm: setting pass-through mode.\n"));
6726         synaptics_set_mode(sc, synaptics_preferred_mode(sc) | (1 << 5));
6727 }
6728
6729 static void
6730 synaptics_passthrough_off(struct psm_softc *sc)
6731 {
6732         VLOG(2, (LOG_NOTICE, "psm: turning pass-through mode off.\n"));
6733         set_mouse_scaling(sc->kbdc, 2);
6734         set_mouse_scaling(sc->kbdc, 1);
6735         synaptics_set_mode(sc, synaptics_preferred_mode(sc));
6736 }
6737
6738 /* IBM/Lenovo TrackPoint */
6739 static int
6740 trackpoint_command(struct psm_softc *sc, int cmd, int loc, int val)
6741 {
6742         const int seq[] = { 0xe2, cmd, loc, val };
6743         int i;
6744
6745         if (sc->synhw.capPassthrough)
6746                 synaptics_passthrough_on(sc);
6747
6748         for (i = 0; i < nitems(seq); i++) {
6749                 if (sc->synhw.capPassthrough &&
6750                     (seq[i] == 0xff || seq[i] == 0xe7))
6751                         if (send_aux_command(sc->kbdc, 0xe7) != PSM_ACK) {
6752                                 synaptics_passthrough_off(sc);
6753                                 return (EIO);
6754                         }
6755                 if (send_aux_command(sc->kbdc, seq[i]) != PSM_ACK) {
6756                         if (sc->synhw.capPassthrough)
6757                                 synaptics_passthrough_off(sc);
6758                         return (EIO);
6759                 }
6760         }
6761
6762         if (sc->synhw.capPassthrough)
6763                 synaptics_passthrough_off(sc);
6764
6765         return (0);
6766 }
6767
6768 #define PSM_TPINFO(x)   offsetof(struct psm_softc, tpinfo.x)
6769 #define TPMASK          0
6770 #define TPLOC           1
6771 #define TPINFO          2
6772
6773 static int
6774 trackpoint_sysctl(SYSCTL_HANDLER_ARGS)
6775 {
6776         static const int data[][3] = {
6777                 { 0x00, 0x4a, PSM_TPINFO(sensitivity) },
6778                 { 0x00, 0x4d, PSM_TPINFO(inertia) },
6779                 { 0x00, 0x60, PSM_TPINFO(uplateau) },
6780                 { 0x00, 0x57, PSM_TPINFO(reach) },
6781                 { 0x00, 0x58, PSM_TPINFO(draghys) },
6782                 { 0x00, 0x59, PSM_TPINFO(mindrag) },
6783                 { 0x00, 0x5a, PSM_TPINFO(upthresh) },
6784                 { 0x00, 0x5c, PSM_TPINFO(threshold) },
6785                 { 0x00, 0x5d, PSM_TPINFO(jenks) },
6786                 { 0x00, 0x5e, PSM_TPINFO(ztime) },
6787                 { 0x01, 0x2c, PSM_TPINFO(pts) },
6788                 { 0x08, 0x2d, PSM_TPINFO(skipback) }
6789         };
6790         struct psm_softc *sc;
6791         int error, newval, *oldvalp;
6792         const int *tp;
6793
6794         if (arg1 == NULL || arg2 < 0 || arg2 >= nitems(data))
6795                 return (EINVAL);
6796         sc = arg1;
6797         tp = data[arg2];
6798         oldvalp = (int *)((intptr_t)sc + tp[TPINFO]);
6799         newval = *oldvalp;
6800         error = sysctl_handle_int(oidp, &newval, 0, req);
6801         if (error != 0)
6802                 return (error);
6803         if (newval == *oldvalp)
6804                 return (0);
6805         if (newval < 0 || newval > (tp[TPMASK] == 0 ? 255 : 1))
6806                 return (EINVAL);
6807         error = trackpoint_command(sc, tp[TPMASK] == 0 ? 0x81 : 0x47,
6808             tp[TPLOC], tp[TPMASK] == 0 ? newval : tp[TPMASK]);
6809         if (error != 0)
6810                 return (error);
6811         *oldvalp = newval;
6812
6813         return (0);
6814 }
6815
6816 static void
6817 trackpoint_sysctl_create_tree(struct psm_softc *sc)
6818 {
6819
6820         if (sc->tpinfo.sysctl_tree != NULL)
6821                 return;
6822
6823         /* Attach extra trackpoint sysctl nodes under hw.psm.trackpoint */
6824         sysctl_ctx_init(&sc->tpinfo.sysctl_ctx);
6825         sc->tpinfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->tpinfo.sysctl_ctx,
6826             SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "trackpoint",
6827             CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "IBM/Lenovo TrackPoint");
6828
6829         /* hw.psm.trackpoint.sensitivity */
6830         sc->tpinfo.sensitivity = 0x80;
6831         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6832             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6833             "sensitivity",
6834             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6835             sc, TRACKPOINT_SYSCTL_SENSITIVITY,
6836             trackpoint_sysctl, "I",
6837             "Sensitivity");
6838
6839         /* hw.psm.trackpoint.negative_inertia */
6840         sc->tpinfo.inertia = 0x06;
6841         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6842             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6843             "negative_inertia",
6844             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6845             sc, TRACKPOINT_SYSCTL_NEGATIVE_INERTIA,
6846             trackpoint_sysctl, "I",
6847             "Negative inertia factor");
6848
6849         /* hw.psm.trackpoint.upper_plateau */
6850         sc->tpinfo.uplateau = 0x61;
6851         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6852             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6853             "upper_plateau",
6854             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6855             sc, TRACKPOINT_SYSCTL_UPPER_PLATEAU,
6856             trackpoint_sysctl, "I",
6857             "Transfer function upper plateau speed");
6858
6859         /* hw.psm.trackpoint.backup_range */
6860         sc->tpinfo.reach = 0x0a;
6861         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6862             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6863             "backup_range",
6864             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6865             sc, TRACKPOINT_SYSCTL_BACKUP_RANGE,
6866             trackpoint_sysctl, "I",
6867             "Backup range");
6868
6869         /* hw.psm.trackpoint.drag_hysteresis */
6870         sc->tpinfo.draghys = 0xff;
6871         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6872             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6873             "drag_hysteresis",
6874             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6875             sc, TRACKPOINT_SYSCTL_DRAG_HYSTERESIS,
6876             trackpoint_sysctl, "I",
6877             "Drag hysteresis");
6878
6879         /* hw.psm.trackpoint.minimum_drag */
6880         sc->tpinfo.mindrag = 0x14;
6881         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6882             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6883             "minimum_drag",
6884             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6885             sc, TRACKPOINT_SYSCTL_MINIMUM_DRAG,
6886             trackpoint_sysctl, "I",
6887             "Minimum drag");
6888
6889         /* hw.psm.trackpoint.up_threshold */
6890         sc->tpinfo.upthresh = 0xff;
6891         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6892             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6893             "up_threshold",
6894             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6895             sc, TRACKPOINT_SYSCTL_UP_THRESHOLD,
6896             trackpoint_sysctl, "I",
6897             "Up threshold for release");
6898
6899         /* hw.psm.trackpoint.threshold */
6900         sc->tpinfo.threshold = 0x08;
6901         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6902             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6903             "threshold",
6904             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6905             sc, TRACKPOINT_SYSCTL_THRESHOLD,
6906             trackpoint_sysctl, "I",
6907             "Threshold");
6908
6909         /* hw.psm.trackpoint.jenks_curvature */
6910         sc->tpinfo.jenks = 0x87;
6911         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6912             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6913             "jenks_curvature",
6914             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6915             sc, TRACKPOINT_SYSCTL_JENKS_CURVATURE,
6916             trackpoint_sysctl, "I",
6917             "Jenks curvature");
6918
6919         /* hw.psm.trackpoint.z_time */
6920         sc->tpinfo.ztime = 0x26;
6921         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6922             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6923             "z_time",
6924             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6925             sc, TRACKPOINT_SYSCTL_Z_TIME,
6926             trackpoint_sysctl, "I",
6927             "Z time constant");
6928
6929         /* hw.psm.trackpoint.press_to_select */
6930         sc->tpinfo.pts = 0x00;
6931         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6932             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6933             "press_to_select",
6934             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6935             sc, TRACKPOINT_SYSCTL_PRESS_TO_SELECT,
6936             trackpoint_sysctl, "I",
6937             "Press to Select");
6938
6939         /* hw.psm.trackpoint.skip_backups */
6940         sc->tpinfo.skipback = 0x00;
6941         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
6942             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
6943             "skip_backups",
6944             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NEEDGIANT,
6945             sc, TRACKPOINT_SYSCTL_SKIP_BACKUPS,
6946             trackpoint_sysctl, "I",
6947             "Skip backups from drags");
6948 }
6949
6950 static void
6951 set_trackpoint_parameters(struct psm_softc *sc)
6952 {
6953         trackpoint_command(sc, 0x81, 0x4a, sc->tpinfo.sensitivity);
6954         trackpoint_command(sc, 0x81, 0x60, sc->tpinfo.uplateau);
6955         trackpoint_command(sc, 0x81, 0x4d, sc->tpinfo.inertia);
6956         trackpoint_command(sc, 0x81, 0x57, sc->tpinfo.reach);
6957         trackpoint_command(sc, 0x81, 0x58, sc->tpinfo.draghys);
6958         trackpoint_command(sc, 0x81, 0x59, sc->tpinfo.mindrag);
6959         trackpoint_command(sc, 0x81, 0x5a, sc->tpinfo.upthresh);
6960         trackpoint_command(sc, 0x81, 0x5c, sc->tpinfo.threshold);
6961         trackpoint_command(sc, 0x81, 0x5d, sc->tpinfo.jenks);
6962         trackpoint_command(sc, 0x81, 0x5e, sc->tpinfo.ztime);
6963         if (sc->tpinfo.pts == 0x01)
6964                 trackpoint_command(sc, 0x47, 0x2c, 0x01);
6965         if (sc->tpinfo.skipback == 0x01)
6966                 trackpoint_command(sc, 0x47, 0x2d, 0x08);
6967 }
6968
6969 static int
6970 enable_trackpoint(struct psm_softc *sc, enum probearg arg)
6971 {
6972         KBDC kbdc = sc->kbdc;
6973         int id;
6974
6975         /*
6976          * If called from enable_synaptics(), make sure that passthrough
6977          * mode is enabled so we can reach the trackpoint.
6978          * However, passthrough mode must be disabled before setting the
6979          * trackpoint parameters, as rackpoint_command() enables and disables
6980          * passthrough mode on its own.
6981          */
6982         if (sc->synhw.capPassthrough)
6983                 synaptics_passthrough_on(sc);
6984
6985         if (send_aux_command(kbdc, 0xe1) != PSM_ACK ||
6986             read_aux_data(kbdc) != 0x01)
6987                 goto no_trackpoint;
6988         id = read_aux_data(kbdc);
6989         if (id < 0x01)
6990                 goto no_trackpoint;
6991         if (arg == PROBE)
6992                 sc->tphw = id;
6993         if (!trackpoint_support)
6994                 goto no_trackpoint;
6995
6996         if (sc->synhw.capPassthrough)
6997                 synaptics_passthrough_off(sc);
6998
6999         if (arg == PROBE) {
7000                 trackpoint_sysctl_create_tree(sc);
7001                 /*
7002                  * Don't overwrite hwid and buttons when we are
7003                  * a guest device.
7004                  */
7005                 if (!sc->synhw.capPassthrough) {
7006                         sc->hw.hwid = id;
7007                         sc->hw.buttons = 3;
7008                 }
7009         }
7010
7011         set_trackpoint_parameters(sc);
7012
7013         return (TRUE);
7014
7015 no_trackpoint:
7016         if (sc->synhw.capPassthrough)
7017                 synaptics_passthrough_off(sc);
7018
7019         return (FALSE);
7020 }
7021
7022 /* Interlink electronics VersaPad */
7023 static int
7024 enable_versapad(struct psm_softc *sc, enum probearg arg)
7025 {
7026         KBDC kbdc = sc->kbdc;
7027         int data[3];
7028
7029         set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
7030         set_mouse_sampling_rate(kbdc, 100);             /* set rate 100 */
7031         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
7032         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
7033         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
7034         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
7035         if (get_mouse_status(kbdc, data, 0, 3) < 3)     /* get status */
7036                 return (FALSE);
7037         if (data[2] != 0xa || data[1] != 0 )    /* rate == 0xa && res. == 0 */
7038                 return (FALSE);
7039         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
7040
7041         return (TRUE);                          /* PS/2 absolute mode */
7042 }
7043
7044 /* Elantech Touchpad */
7045 static int
7046 elantech_read_1(KBDC kbdc, int hwversion, int reg, int *val)
7047 {
7048         int res, readcmd, retidx;
7049         int resp[3];
7050
7051         readcmd = hwversion == 2 ? ELANTECH_REG_READ : ELANTECH_REG_RDWR;
7052         retidx = hwversion == 4 ? 1 : 0;
7053
7054         res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
7055         res |= send_aux_command(kbdc, readcmd) != PSM_ACK;
7056         res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
7057         res |= send_aux_command(kbdc, reg) != PSM_ACK;
7058         res |= get_mouse_status(kbdc, resp, 0, 3) != 3;
7059
7060         if (res == 0)
7061                 *val = resp[retidx];
7062
7063         return (res);
7064 }
7065
7066 static int
7067 elantech_write_1(KBDC kbdc, int hwversion, int reg, int val)
7068 {
7069         int res, writecmd;
7070
7071         writecmd = hwversion == 2 ? ELANTECH_REG_WRITE : ELANTECH_REG_RDWR;
7072
7073         res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
7074         res |= send_aux_command(kbdc, writecmd) != PSM_ACK;
7075         res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
7076         res |= send_aux_command(kbdc, reg) != PSM_ACK;
7077         if (hwversion == 4) {
7078                 res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
7079                 res |= send_aux_command(kbdc, writecmd) != PSM_ACK;
7080         }
7081         res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
7082         res |= send_aux_command(kbdc, val) != PSM_ACK;
7083         res |= set_mouse_scaling(kbdc, 1) == 0;
7084
7085         return (res);
7086 }
7087
7088 static int
7089 elantech_cmd(KBDC kbdc, int hwversion, int cmd, int *resp)
7090 {
7091         int res;
7092
7093         if (hwversion == 2) {
7094                 res = set_mouse_scaling(kbdc, 1) == 0;
7095                 res |= mouse_ext_command(kbdc, cmd) == 0;
7096         } else {
7097                 res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK;
7098                 res |= send_aux_command(kbdc, cmd) != PSM_ACK;
7099         }
7100         res |= get_mouse_status(kbdc, resp, 0, 3) != 3;
7101
7102         return (res);
7103 }
7104
7105 static int
7106 elantech_init(KBDC kbdc, elantechhw_t *elanhw)
7107 {
7108         int i, val, res, hwversion, reg10;
7109
7110         /* set absolute mode */
7111         hwversion = elanhw->hwversion;
7112         reg10 = -1;
7113         switch (hwversion) {
7114         case 2:
7115                 reg10 = elanhw->fwversion == 0x020030 ? 0x54 : 0xc4;
7116                 res = elantech_write_1(kbdc, hwversion, 0x10, reg10);
7117                 if (res)
7118                         break;
7119                 res = elantech_write_1(kbdc, hwversion, 0x11, 0x8A);
7120                 break;
7121         case 3:
7122                 reg10 = 0x0b;
7123                 res = elantech_write_1(kbdc, hwversion, 0x10, reg10);
7124                 break;
7125         case 4:
7126                 res = elantech_write_1(kbdc, hwversion, 0x07, 0x01);
7127                 break;
7128         default:
7129                 res = 1;
7130         }
7131
7132         /* Read back reg 0x10 to ensure hardware is ready. */
7133         if (res == 0 && reg10 >= 0) {
7134                 for (i = 0; i < 5; i++) {
7135                         if (elantech_read_1(kbdc, hwversion, 0x10, &val) == 0)
7136                                 break;
7137                         DELAY(2000);
7138                 }
7139                 if (i == 5)
7140                         res = 1;
7141         }
7142
7143         if (res)
7144                 printf("couldn't set absolute mode\n");
7145
7146         return (res);
7147 }
7148
7149 static void
7150 elantech_init_synaptics(struct psm_softc *sc)
7151 {
7152
7153         /* Set capabilites required by movement smother */
7154         sc->synhw.infoMajor = sc->elanhw.hwversion;
7155         sc->synhw.infoMinor = sc->elanhw.fwversion;
7156         sc->synhw.infoXupmm = sc->elanhw.dpmmx;
7157         sc->synhw.infoYupmm = sc->elanhw.dpmmy;
7158         sc->synhw.verticalScroll = 0;
7159         sc->synhw.nExtendedQueries = 4;
7160         sc->synhw.capExtended = 1;
7161         sc->synhw.capPassthrough = sc->elanhw.hastrackpoint;
7162         sc->synhw.capClickPad = sc->elanhw.isclickpad;
7163         sc->synhw.capMultiFinger = 1;
7164         if (sc->elanhw.issemimt)
7165                 sc->synhw.capAdvancedGestures = 1;
7166         else
7167                 sc->synhw.capReportsV = 1;
7168         sc->synhw.capPalmDetect = 1;
7169         sc->synhw.capPen = 0;
7170         sc->synhw.capReportsMax = 1;
7171         sc->synhw.maximumXCoord = sc->elanhw.sizex;
7172         sc->synhw.maximumYCoord = sc->elanhw.sizey;
7173         sc->synhw.capReportsMin = 1;
7174         sc->synhw.minimumXCoord = 0;
7175         sc->synhw.minimumYCoord = 0;
7176
7177         if (sc->syninfo.sysctl_tree == NULL) {
7178                 synaptics_sysctl_create_tree(sc, "elantech",
7179                     "Elantech Touchpad");
7180
7181                 /*
7182                  * Adjust synaptic smoother tunables
7183                  * 1. Disable finger detection pressure threshold. Unlike
7184                  *    synaptics we assume the finger is acting when packet with
7185                  *    its X&Y arrives not when pressure exceedes some threshold
7186                  * 2. Disable unrelated features like margins and noisy areas
7187                  * 3. Disable virtual scroll areas as 2nd finger is preferable
7188                  * 4. For clickpads set bottom quarter as 42% - 16% - 42% sized
7189                  *    softbuttons
7190                  * 5. Scale down divisors and movement lengths by a factor of 3
7191                  *    where 3 is Synaptics to Elantech (~2200/800) dpi ratio
7192                  */
7193
7194                 /* Set reporting range to be equal touchpad size */
7195                 sc->syninfo.max_x = sc->elanhw.sizex;
7196                 sc->syninfo.max_y = sc->elanhw.sizey;
7197
7198                 /* Disable finger detection pressure threshold */
7199                 sc->syninfo.min_pressure = 1;
7200
7201                 /* Adjust palm width to nearly match synaptics w=10 */
7202                 sc->syninfo.max_width = 7;
7203
7204                 /* Elans often report double & triple taps as single event */
7205                 sc->syninfo.tap_min_queue = 1;
7206
7207                 /* Use full area of touchpad */
7208                 sc->syninfo.margin_top = 0;
7209                 sc->syninfo.margin_right = 0;
7210                 sc->syninfo.margin_bottom = 0;
7211                 sc->syninfo.margin_left = 0;
7212
7213                 /* Disable noisy area */
7214                 sc->syninfo.na_top = 0;
7215                 sc->syninfo.na_right = 0;
7216                 sc->syninfo.na_bottom = 0;
7217                 sc->syninfo.na_left = 0;
7218
7219                 /* Tune divisors and movement lengths */
7220                 sc->syninfo.weight_len_squared = 200;
7221                 sc->syninfo.div_min = 3;
7222                 sc->syninfo.div_max = 6;
7223                 sc->syninfo.div_max_na = 10;
7224                 sc->syninfo.div_len = 30;
7225                 sc->syninfo.tap_max_delta = 25;
7226
7227                 /* Disable virtual scrolling areas and tune its divisors */
7228                 sc->syninfo.vscroll_hor_area = 0;
7229                 sc->syninfo.vscroll_ver_area = 0;
7230                 sc->syninfo.vscroll_min_delta = 15;
7231                 sc->syninfo.vscroll_div_min = 30;
7232                 sc->syninfo.vscroll_div_max = 50;
7233
7234                 /* Set bottom quarter as 42% - 16% - 42% sized softbuttons */
7235                 if (sc->elanhw.isclickpad) {
7236                         sc->syninfo.softbuttons_y = sc->elanhw.sizey / 4;
7237                         sc->syninfo.softbutton2_x = sc->elanhw.sizex * 11 / 25;
7238                         sc->syninfo.softbutton3_x = sc->elanhw.sizex * 14 / 25;
7239                 }
7240         }
7241
7242         return;
7243 }
7244
7245 static int
7246 enable_elantech(struct psm_softc *sc, enum probearg arg)
7247 {
7248         static const int ic2hw[] =
7249         /*IC: 0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f */
7250             { 0, 0, 2, 0, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 };
7251         static const int fw_sizes[][3] = {
7252                 /* FW.vers  MaxX  MaxY */
7253                 { 0x020030, 1152,  768 },
7254                 { 0x020800, 1152,  768 },
7255                 { 0x020b00, 1152,  768 },
7256                 { 0x040215,  900,  500 },
7257                 { 0x040216,  819,  405 },
7258                 { 0x040219,  900,  500 },
7259         };
7260         elantechhw_t elanhw;
7261         int icversion, hwversion, xtr, i, id, resp[3], dpix, dpiy;
7262         KBDC kbdc = sc->kbdc;
7263
7264         VLOG(3, (LOG_DEBUG, "elantech: BEGIN init\n"));
7265
7266         set_mouse_scaling(kbdc, 1);
7267         set_mouse_scaling(kbdc, 1);
7268         set_mouse_scaling(kbdc, 1);
7269         if (get_mouse_status(kbdc, resp, 0, 3) != 3)
7270                 return (FALSE);
7271
7272         if (!ELANTECH_MAGIC(resp))
7273                 return (FALSE);
7274
7275         /* Identify the Touchpad version. */
7276         if (elantech_cmd(kbdc, 2, ELANTECH_FW_VERSION, resp))
7277                 return (FALSE);
7278
7279         bzero(&elanhw, sizeof(elanhw));
7280
7281         elanhw.fwversion = (resp[0] << 16) | (resp[1] << 8) | resp[2];
7282         icversion = resp[0] & 0x0f;
7283         hwversion = ic2hw[icversion];
7284
7285         if (verbose >= 2)
7286                 printf("Elantech touchpad hardware v.%d firmware v.0x%06x\n",
7287                     hwversion, elanhw.fwversion);
7288
7289         if (ELANTECH_HW_IS_V1(elanhw.fwversion)) {
7290                 printf ("  Unsupported touchpad hardware (v1)\n");
7291                 return (FALSE);
7292         }
7293         if (hwversion == 0) {
7294                 printf ("  Unknown touchpad hardware (firmware v.0x%06x)\n",
7295                     elanhw.fwversion);
7296                 return (FALSE);
7297         }
7298
7299         /* Get the Touchpad model information. */
7300         elanhw.hwversion = hwversion;
7301         elanhw.issemimt = hwversion == 2;
7302         elanhw.isclickpad = (resp[1] & 0x10) != 0;
7303         elanhw.hascrc = (resp[1] & 0x40) != 0;
7304         elanhw.haspressure = elanhw.fwversion >= 0x020800;
7305
7306         /* Read the capability bits. */
7307         if (elantech_cmd(kbdc, hwversion, ELANTECH_CAPABILITIES, resp) != 0) {
7308                 printf("  Failed to read capability bits\n");
7309                 return (FALSE);
7310         }
7311
7312         elanhw.ntracesx = imax(resp[1], 3);
7313         elanhw.ntracesy = imax(resp[2], 3);
7314         elanhw.hastrackpoint = (resp[0] & 0x80) != 0;
7315
7316         /* Get the touchpad resolution */
7317         switch (hwversion) {
7318         case 4:
7319                 if (elantech_cmd(kbdc, hwversion, ELANTECH_RESOLUTION, resp)
7320                     == 0) {
7321                         dpix = (resp[1] & 0x0f) * 10 + 790;
7322                         dpiy = ((resp[1] & 0xf0) >> 4) * 10 + 790;
7323                         elanhw.dpmmx = (dpix * 10 + 5) / 254;
7324                         elanhw.dpmmy = (dpiy * 10 + 5) / 254;
7325                         break;
7326                 }
7327                 /* FALLTHROUGH */
7328         case 2:
7329         case 3:
7330                 elanhw.dpmmx = elanhw.dpmmy = 32; /* 800 dpi */
7331                 break;
7332         }
7333
7334         if (!elantech_support)
7335                 return (FALSE);
7336
7337         if (elantech_init(kbdc, &elanhw)) {
7338                 printf("couldn't initialize elantech touchpad\n");
7339                 return (FALSE);
7340         }
7341
7342         /*
7343          * Get the touchpad reporting range.
7344          * On HW v.3 touchpads it should be done after switching hardware
7345          * to real resolution mode (by setting bit 3 of reg10)
7346          */
7347         elanhw.dptracex = elanhw.dptracey = 64;
7348         for (i = 0; i < nitems(fw_sizes); i++) {
7349                 if (elanhw.fwversion == fw_sizes[i][0]) {
7350                         elanhw.sizex = fw_sizes[i][1];
7351                         elanhw.sizey = fw_sizes[i][2];
7352                         goto found;
7353                 }
7354         }
7355         if (elantech_cmd(kbdc, hwversion, ELANTECH_FW_ID, resp) != 0) {
7356                 printf("  Failed to read touchpad size\n");
7357                 elanhw.sizex = 10000; /* Arbitrary high values to     */
7358                 elanhw.sizey = 10000; /* prevent clipping in smoother */
7359         } else if (hwversion == 2) {
7360                 if ((elanhw.fwversion >> 16) == 0x14 && (resp[1] & 0x10) &&
7361                     !elantech_cmd(kbdc, hwversion, ELANTECH_SAMPLE, resp)) {
7362                         elanhw.dptracex = resp[1] / 2;
7363                         elanhw.dptracey = resp[2] / 2;
7364                 }
7365                 xtr = ((elanhw.fwversion >> 8) == 0x0208) ? 1 : 2;
7366                 elanhw.sizex = (elanhw.ntracesx - xtr) * elanhw.dptracex;
7367                 elanhw.sizey = (elanhw.ntracesy - xtr) * elanhw.dptracey;
7368         } else {
7369                 elanhw.sizex = (resp[0] & 0x0f) << 8 | resp[1];
7370                 elanhw.sizey = (resp[0] & 0xf0) << 4 | resp[2];
7371                 xtr = (elanhw.sizex % (elanhw.ntracesx - 2) == 0) ? 2 : 1;
7372                 elanhw.dptracex = elanhw.sizex / (elanhw.ntracesx - xtr);
7373                 elanhw.dptracey = elanhw.sizey / (elanhw.ntracesy - xtr);
7374         }
7375 found:
7376         if (verbose >= 2) {
7377                 printf("  Model information:\n");
7378                 printf("   MaxX:       %d\n", elanhw.sizex);
7379                 printf("   MaxY:       %d\n", elanhw.sizey);
7380                 printf("   DpmmX:      %d\n", elanhw.dpmmx);
7381                 printf("   DpmmY:      %d\n", elanhw.dpmmy);
7382                 printf("   TracesX:    %d\n", elanhw.ntracesx);
7383                 printf("   TracesY:    %d\n", elanhw.ntracesy);
7384                 printf("   DptraceX:   %d\n", elanhw.dptracex);
7385                 printf("   DptraceY:   %d\n", elanhw.dptracey);
7386                 printf("   SemiMT:     %d\n", elanhw.issemimt);
7387                 printf("   Clickpad:   %d\n", elanhw.isclickpad);
7388                 printf("   Trackpoint: %d\n", elanhw.hastrackpoint);
7389                 printf("   CRC:        %d\n", elanhw.hascrc);
7390                 printf("   Pressure:   %d\n", elanhw.haspressure);
7391         }
7392
7393         VLOG(3, (LOG_DEBUG, "elantech: END init\n"));
7394
7395         if (arg == PROBE) {
7396                 sc->elanhw = elanhw;
7397                 sc->hw.buttons = 3;
7398
7399                 /* Initialize synaptics movement smoother */
7400                 elantech_init_synaptics(sc);
7401
7402                 for (id = 0; id < ELANTECH_MAX_FINGERS; id++)
7403                         PSM_FINGER_RESET(sc->elanaction.fingers[id]);
7404         }
7405
7406         return (TRUE);
7407 }
7408
7409 /*
7410  * Return true if 'now' is earlier than (start + (secs.usecs)).
7411  * Now may be NULL and the function will fetch the current time from
7412  * getmicrouptime(), or a cached 'now' can be passed in.
7413  * All values should be numbers derived from getmicrouptime().
7414  */
7415 static int
7416 timeelapsed(start, secs, usecs, now)
7417         const struct timeval *start, *now;
7418         int secs, usecs;
7419 {
7420         struct timeval snow, tv;
7421
7422         /* if there is no 'now' passed in, the get it as a convience. */
7423         if (now == NULL) {
7424                 getmicrouptime(&snow);
7425                 now = &snow;
7426         }
7427
7428         tv.tv_sec = secs;
7429         tv.tv_usec = usecs;
7430         timevaladd(&tv, start);
7431         return (timevalcmp(&tv, now, <));
7432 }
7433
7434 static int
7435 psmresume(device_t dev)
7436 {
7437         struct psm_softc *sc = device_get_softc(dev);
7438         int unit = device_get_unit(dev);
7439         int err;
7440
7441         VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit));
7442
7443         if ((sc->config &
7444             (PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND)) == 0)
7445                 return (0);
7446
7447         err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
7448
7449         if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
7450                 /*
7451                  * Release the blocked process; it must be notified that
7452                  * the device cannot be accessed anymore.
7453                  */
7454                 sc->state &= ~PSM_ASLP;
7455                 wakeup(sc);
7456         }
7457
7458         VLOG(2, (LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit));
7459
7460         return (err);
7461 }
7462
7463 DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
7464 #ifdef EVDEV_SUPPORT
7465 MODULE_DEPEND(psm, evdev, 1, 1, 1);
7466 #endif
7467
7468 #ifdef DEV_ISA
7469
7470 /*
7471  * This sucks up assignments from PNPBIOS and ACPI.
7472  */
7473
7474 /*
7475  * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
7476  * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
7477  * can be probed and attached only after the AT keyboard controller is
7478  * attached, we shall quietly reserve the IRQ resource for later use.
7479  * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
7480  * copy the IRQ resource to the PS/2 mouse device instance hanging
7481  * under the keyboard controller, then probe and attach it.
7482  */
7483
7484 static  devclass_t                      psmcpnp_devclass;
7485
7486 static  device_probe_t                  psmcpnp_probe;
7487 static  device_attach_t                 psmcpnp_attach;
7488
7489 static device_method_t psmcpnp_methods[] = {
7490         DEVMETHOD(device_probe,         psmcpnp_probe),
7491         DEVMETHOD(device_attach,        psmcpnp_attach),
7492
7493         { 0, 0 }
7494 };
7495
7496 static driver_t psmcpnp_driver = {
7497         PSMCPNP_DRIVER_NAME,
7498         psmcpnp_methods,
7499         sizeof(struct psmcpnp_softc),
7500 };
7501
7502 static struct isa_pnp_id psmcpnp_ids[] = {
7503         { 0x030fd041, "PS/2 mouse port" },              /* PNP0F03 */
7504         { 0x0e0fd041, "PS/2 mouse port" },              /* PNP0F0E */
7505         { 0x120fd041, "PS/2 mouse port" },              /* PNP0F12 */
7506         { 0x130fd041, "PS/2 mouse port" },              /* PNP0F13 */
7507         { 0x1303d041, "PS/2 port" },                    /* PNP0313, XXX */
7508         { 0x02002e4f, "Dell PS/2 mouse port" },         /* Lat. X200, Dell */
7509         { 0x0002a906, "ALPS Glide Point" },             /* ALPS Glide Point */
7510         { 0x80374d24, "IBM PS/2 mouse port" },          /* IBM3780, ThinkPad */
7511         { 0x81374d24, "IBM PS/2 mouse port" },          /* IBM3781, ThinkPad */
7512         { 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
7513         { 0x0290d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9002, Vaio */
7514         { 0x0390d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9003, Vaio */
7515         { 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
7516         { 0 }
7517 };
7518
7519 /* _HID list for quirk detection. Any device below has _CID from psmcpnp_ids */
7520 static struct isa_pnp_id topbtpad_ids[] = {
7521         { 0x1700ae30, "Lenovo PS/2 clickpad port" },    /* LEN0017, ThinkPad */
7522         { 0x1800ae30, "Lenovo PS/2 clickpad port" },    /* LEN0018, ThinkPad */
7523         { 0x1900ae30, "Lenovo PS/2 clickpad port" },    /* LEN0019, ThinkPad */
7524         { 0x2300ae30, "Lenovo PS/2 clickpad port" },    /* LEN0023, ThinkPad */
7525         { 0x2a00ae30, "Lenovo PS/2 clickpad port" },    /* LEN002a, ThinkPad */
7526         { 0x2b00ae30, "Lenovo PS/2 clickpad port" },    /* LEN002b, ThinkPad */
7527         { 0x2c00ae30, "Lenovo PS/2 clickpad port" },    /* LEN002c, ThinkPad */
7528         { 0x2d00ae30, "Lenovo PS/2 clickpad port" },    /* LEN002d, ThinkPad */
7529         { 0x2e00ae30, "Lenovo PS/2 clickpad port" },    /* LEN002e, ThinkPad */
7530         { 0x3300ae30, "Lenovo PS/2 clickpad port" },    /* LEN0033, ThinkPad */
7531         { 0x3400ae30, "Lenovo PS/2 clickpad port" },    /* LEN0034, ThinkPad */
7532         { 0x3500ae30, "Lenovo PS/2 clickpad port" },    /* LEN0035, ThinkPad */
7533         { 0x3600ae30, "Lenovo PS/2 clickpad port" },    /* LEN0036, ThinkPad */
7534         { 0x3700ae30, "Lenovo PS/2 clickpad port" },    /* LEN0037, ThinkPad */
7535         { 0x3800ae30, "Lenovo PS/2 clickpad port" },    /* LEN0038, ThinkPad */
7536         { 0x3900ae30, "Lenovo PS/2 clickpad port" },    /* LEN0039, ThinkPad */
7537         { 0x4100ae30, "Lenovo PS/2 clickpad port" },    /* LEN0041, ThinkPad */
7538         { 0x4200ae30, "Lenovo PS/2 clickpad port" },    /* LEN0042, ThinkPad */
7539         { 0x4500ae30, "Lenovo PS/2 clickpad port" },    /* LEN0045, ThinkPad */
7540         { 0x4700ae30, "Lenovo PS/2 clickpad port" },    /* LEN0047, ThinkPad */
7541         { 0x4900ae30, "Lenovo PS/2 clickpad port" },    /* LEN0049, ThinkPad */
7542         { 0x0020ae30, "Lenovo PS/2 clickpad port" },    /* LEN2000, ThinkPad */
7543         { 0x0120ae30, "Lenovo PS/2 clickpad port" },    /* LEN2001, ThinkPad */
7544         { 0x0220ae30, "Lenovo PS/2 clickpad port" },    /* LEN2002, ThinkPad */
7545         { 0x0320ae30, "Lenovo PS/2 clickpad port" },    /* LEN2003, ThinkPad */
7546         { 0x0420ae30, "Lenovo PS/2 clickpad port" },    /* LEN2004, ThinkPad */
7547         { 0x0520ae30, "Lenovo PS/2 clickpad port" },    /* LEN2005, ThinkPad */
7548         { 0x0620ae30, "Lenovo PS/2 clickpad port" },    /* LEN2006, ThinkPad */
7549         { 0x0720ae30, "Lenovo PS/2 clickpad port" },    /* LEN2007, ThinkPad */
7550         { 0x0820ae30, "Lenovo PS/2 clickpad port" },    /* LEN2008, ThinkPad */
7551         { 0x0920ae30, "Lenovo PS/2 clickpad port" },    /* LEN2009, ThinkPad */
7552         { 0x0a20ae30, "Lenovo PS/2 clickpad port" },    /* LEN200a, ThinkPad */
7553         { 0x0b20ae30, "Lenovo PS/2 clickpad port" },    /* LEN200b, ThinkPad */
7554         { 0 }
7555 };
7556
7557 /* _HID list for quirk detection. Any device below has _CID from psmcpnp_ids */
7558 static struct isa_pnp_id forcepad_ids[] = {
7559         { 0x0d302e4f, "HP PS/2 forcepad port" },        /* SYN300D, EB 1040 */
7560         { 0x14302e4f, "HP PS/2 forcepad port" },        /* SYN3014, EB 1040 */
7561         { 0 }
7562 };
7563
7564 static int
7565 create_a_copy(device_t atkbdc, device_t me)
7566 {
7567         device_t psm;
7568         u_long irq;
7569
7570         /* find the PS/2 mouse device instance under the keyboard controller */
7571         psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
7572             device_get_unit(atkbdc));
7573         if (psm == NULL)
7574                 return (ENXIO);
7575         if (device_get_state(psm) != DS_NOTPRESENT)
7576                 return (0);
7577
7578         /* move our resource to the found device */
7579         irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
7580         bus_delete_resource(me, SYS_RES_IRQ, 0);
7581         bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
7582
7583         /* ...then probe and attach it */
7584         return (device_probe_and_attach(psm));
7585 }
7586
7587 static int
7588 psmcpnp_probe(device_t dev)
7589 {
7590         struct psmcpnp_softc *sc = device_get_softc(dev);
7591         struct resource *res;
7592         u_long irq;
7593         int rid;
7594
7595         if (ISA_PNP_PROBE(device_get_parent(dev), dev, forcepad_ids) == 0)
7596                 sc->type = PSMCPNP_FORCEPAD;
7597         else if (ISA_PNP_PROBE(device_get_parent(dev), dev, topbtpad_ids) == 0)
7598                 sc->type = PSMCPNP_TOPBUTTONPAD;
7599         else if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids) == 0)
7600                 sc->type = PSMCPNP_GENERIC;
7601         else
7602                 return (ENXIO);
7603
7604         /*
7605          * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
7606          * to the PS/2 mouse device node. But, some buggy PnP BIOS
7607          * declares the PS/2 mouse device node without an IRQ resource!
7608          * If this happens, we shall refer to device hints.
7609          * If we still don't find it there, use a hardcoded value... XXX
7610          */
7611         rid = 0;
7612         irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
7613         if (irq <= 0) {
7614                 if (resource_long_value(PSM_DRIVER_NAME,
7615                     device_get_unit(dev),"irq", &irq) != 0)
7616                         irq = 12;       /* XXX */
7617                 device_printf(dev, "irq resource info is missing; "
7618                     "assuming irq %ld\n", irq);
7619                 bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
7620         }
7621         res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, 0);
7622         bus_release_resource(dev, SYS_RES_IRQ, rid, res);
7623
7624         /* keep quiet */
7625         if (!bootverbose)
7626                 device_quiet(dev);
7627
7628         return ((res == NULL) ? ENXIO : 0);
7629 }
7630
7631 static int
7632 psmcpnp_attach(device_t dev)
7633 {
7634         device_t atkbdc;
7635
7636         /* find the keyboard controller, which may be on acpi* or isa* bus */
7637         atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
7638             device_get_unit(dev));
7639         if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED))
7640                 create_a_copy(atkbdc, dev);
7641
7642         return (0);
7643 }
7644
7645 DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
7646 DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
7647 ISA_PNP_INFO(psmcpnp_ids);
7648 #endif /* DEV_ISA */