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