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