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