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