]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - sys/dev/atkbdc/psm.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.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
85 #include <sys/limits.h>
86 #include <sys/mouse.h>
87 #include <machine/resource.h>
88
89 #ifdef DEV_ISA
90 #include <isa/isavar.h>
91 #endif
92
93 #include <dev/atkbdc/atkbdcreg.h>
94 #include <dev/atkbdc/psm.h>
95
96 /*
97  * Driver specific options: the following options may be set by
98  * `options' statements in the kernel configuration file.
99  */
100
101 /* debugging */
102 #ifndef PSM_DEBUG
103 #define PSM_DEBUG       0       /*
104                                  * logging: 0: none, 1: brief, 2: verbose
105                                  *          3: sync errors, 4: all packets
106                                  */
107 #endif
108 #define VLOG(level, args)       do {    \
109         if (verbose >= level)           \
110                 log args;               \
111 } while (0)
112
113 #ifndef PSM_INPUT_TIMEOUT
114 #define PSM_INPUT_TIMEOUT       2000000 /* 2 sec */
115 #endif
116
117 #ifndef PSM_TAP_TIMEOUT
118 #define PSM_TAP_TIMEOUT         125000
119 #endif
120
121 #ifndef PSM_TAP_THRESHOLD
122 #define PSM_TAP_THRESHOLD       25
123 #endif
124
125 /* end of driver specific options */
126
127 #define PSMCPNP_DRIVER_NAME     "psmcpnp"
128
129 /* input queue */
130 #define PSM_BUFSIZE             960
131 #define PSM_SMALLBUFSIZE        240
132
133 /* operation levels */
134 #define PSM_LEVEL_BASE          0
135 #define PSM_LEVEL_STANDARD      1
136 #define PSM_LEVEL_NATIVE        2
137 #define PSM_LEVEL_MIN           PSM_LEVEL_BASE
138 #define PSM_LEVEL_MAX           PSM_LEVEL_NATIVE
139
140 /* Logitech PS2++ protocol */
141 #define MOUSE_PS2PLUS_CHECKBITS(b)      \
142     ((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
143 #define MOUSE_PS2PLUS_PACKET_TYPE(b)    \
144     (((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
145
146 /* ring buffer */
147 typedef struct ringbuf {
148         int             count;  /* # of valid elements in the buffer */
149         int             head;   /* head pointer */
150         int             tail;   /* tail poiner */
151         u_char buf[PSM_BUFSIZE];
152 } ringbuf_t;
153
154 /* data buffer */
155 typedef struct packetbuf {
156         u_char  ipacket[16];    /* interim input buffer */
157         int     inputbytes;     /* # of bytes in the input buffer */
158 } packetbuf_t;
159
160 #ifndef PSM_PACKETQUEUE
161 #define PSM_PACKETQUEUE 128
162 #endif
163
164 enum {
165         SYNAPTICS_SYSCTL_MIN_PRESSURE,
166         SYNAPTICS_SYSCTL_MAX_PRESSURE,
167         SYNAPTICS_SYSCTL_MAX_WIDTH,
168         SYNAPTICS_SYSCTL_MARGIN_TOP,
169         SYNAPTICS_SYSCTL_MARGIN_RIGHT,
170         SYNAPTICS_SYSCTL_MARGIN_BOTTOM,
171         SYNAPTICS_SYSCTL_MARGIN_LEFT,
172         SYNAPTICS_SYSCTL_NA_TOP,
173         SYNAPTICS_SYSCTL_NA_RIGHT,
174         SYNAPTICS_SYSCTL_NA_BOTTOM,
175         SYNAPTICS_SYSCTL_NA_LEFT,
176         SYNAPTICS_SYSCTL_WINDOW_MIN,
177         SYNAPTICS_SYSCTL_WINDOW_MAX,
178         SYNAPTICS_SYSCTL_MULTIPLICATOR,
179         SYNAPTICS_SYSCTL_WEIGHT_CURRENT,
180         SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS,
181         SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA,
182         SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED,
183         SYNAPTICS_SYSCTL_DIV_MIN,
184         SYNAPTICS_SYSCTL_DIV_MAX,
185         SYNAPTICS_SYSCTL_DIV_MAX_NA,
186         SYNAPTICS_SYSCTL_DIV_LEN,
187         SYNAPTICS_SYSCTL_TAP_MAX_DELTA,
188         SYNAPTICS_SYSCTL_TAP_MIN_QUEUE,
189         SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT,
190         SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA,
191         SYNAPTICS_SYSCTL_VSCROLL_VER_AREA,
192         SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA,
193         SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN,
194         SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX
195 };
196
197 typedef struct synapticsinfo {
198         struct sysctl_ctx_list   sysctl_ctx;
199         struct sysctl_oid       *sysctl_tree;
200         int                      directional_scrolls;
201         int                      min_pressure;
202         int                      max_pressure;
203         int                      max_width;
204         int                      margin_top;
205         int                      margin_right;
206         int                      margin_bottom;
207         int                      margin_left;
208         int                      na_top;
209         int                      na_right;
210         int                      na_bottom;
211         int                      na_left;
212         int                      window_min;
213         int                      window_max;
214         int                      multiplicator;
215         int                      weight_current;
216         int                      weight_previous;
217         int                      weight_previous_na;
218         int                      weight_len_squared;
219         int                      div_min;
220         int                      div_max;
221         int                      div_max_na;
222         int                      div_len;
223         int                      tap_max_delta;
224         int                      tap_min_queue;
225         int                      taphold_timeout;
226         int                      vscroll_ver_area;
227         int                      vscroll_hor_area;
228         int                      vscroll_min_delta;
229         int                      vscroll_div_min;
230         int                      vscroll_div_max;
231 } synapticsinfo_t;
232
233 typedef struct synapticspacket {
234         int                     x;
235         int                     y;
236 } synapticspacket_t;
237
238 #define SYNAPTICS_PACKETQUEUE 10
239 #define SYNAPTICS_QUEUE_CURSOR(x)                                       \
240         (x + SYNAPTICS_PACKETQUEUE) % SYNAPTICS_PACKETQUEUE
241
242 #define SYNAPTICS_VERSION_GE(synhw, major, minor)                       \
243     ((synhw).infoMajor > (major) ||                                     \
244      ((synhw).infoMajor == (major) && (synhw).infoMinor >= (minor)))
245
246 typedef struct synapticsaction {
247         synapticspacket_t       queue[SYNAPTICS_PACKETQUEUE];
248         int                     queue_len;
249         int                     queue_cursor;
250         int                     window_min;
251         int                     start_x;
252         int                     start_y;
253         int                     avg_dx;
254         int                     avg_dy;
255         int                     squelch_x;
256         int                     squelch_y;
257         int                     fingers_nb;
258         int                     tap_button;
259         int                     in_taphold;
260         int                     in_vscroll;
261 } synapticsaction_t;
262
263 enum {
264         TRACKPOINT_SYSCTL_SENSITIVITY,
265         TRACKPOINT_SYSCTL_NEGATIVE_INERTIA,
266         TRACKPOINT_SYSCTL_UPPER_PLATEAU,
267         TRACKPOINT_SYSCTL_BACKUP_RANGE,
268         TRACKPOINT_SYSCTL_DRAG_HYSTERESIS,
269         TRACKPOINT_SYSCTL_MINIMUM_DRAG,
270         TRACKPOINT_SYSCTL_UP_THRESHOLD,
271         TRACKPOINT_SYSCTL_THRESHOLD,
272         TRACKPOINT_SYSCTL_JENKS_CURVATURE,
273         TRACKPOINT_SYSCTL_Z_TIME,
274         TRACKPOINT_SYSCTL_PRESS_TO_SELECT,
275         TRACKPOINT_SYSCTL_SKIP_BACKUPS
276 };
277
278 typedef struct trackpointinfo {
279         struct sysctl_ctx_list sysctl_ctx;
280         struct sysctl_oid *sysctl_tree;
281         int     sensitivity;
282         int     inertia;
283         int     uplateau;
284         int     reach;
285         int     draghys;
286         int     mindrag;
287         int     upthresh;
288         int     threshold;
289         int     jenks;
290         int     ztime;
291         int     pts;
292         int     skipback;
293 } trackpointinfo_t;
294
295 /* driver control block */
296 struct psm_softc {              /* Driver status information */
297         int             unit;
298         struct selinfo  rsel;           /* Process selecting for Input */
299         u_char          state;          /* Mouse driver state */
300         int             config;         /* driver configuration flags */
301         int             flags;          /* other flags */
302         KBDC            kbdc;           /* handle to access kbd controller */
303         struct resource *intr;          /* IRQ resource */
304         void            *ih;            /* interrupt handle */
305         mousehw_t       hw;             /* hardware information */
306         synapticshw_t   synhw;          /* Synaptics hardware information */
307         synapticsinfo_t syninfo;        /* Synaptics configuration */
308         synapticsaction_t synaction;    /* Synaptics action context */
309         int             tphw;           /* TrackPoint hardware information */
310         trackpointinfo_t tpinfo;        /* TrackPoint configuration */
311         mousemode_t     mode;           /* operation mode */
312         mousemode_t     dflt_mode;      /* default operation mode */
313         mousestatus_t   status;         /* accumulated mouse movement */
314         ringbuf_t       queue;          /* mouse status queue */
315         packetbuf_t     pqueue[PSM_PACKETQUEUE]; /* mouse data queue */
316         int             pqueue_start;   /* start of data in queue */
317         int             pqueue_end;     /* end of data in queue */
318         int             button;         /* the latest button state */
319         int             xold;           /* previous absolute X position */
320         int             yold;           /* previous absolute Y position */
321         int             xaverage;       /* average X position */
322         int             yaverage;       /* average Y position */
323         int             squelch; /* level to filter movement at low speed */
324         int             zmax;   /* maximum pressure value for touchpads */
325         int             syncerrors; /* # of bytes discarded to synchronize */
326         int             pkterrors;  /* # of packets failed during quaranteen. */
327         struct timeval  inputtimeout;
328         struct timeval  lastsoftintr;   /* time of last soft interrupt */
329         struct timeval  lastinputerr;   /* time last sync error happened */
330         struct timeval  taptimeout;     /* tap timeout for touchpads */
331         int             watchdog;       /* watchdog timer flag */
332         struct callout_handle callout;  /* watchdog timer call out */
333         struct callout_handle softcallout; /* buffer timer call out */
334         struct cdev     *dev;
335         struct cdev     *bdev;
336         int             lasterr;
337         int             cmdcount;
338         struct sigio    *async;         /* Processes waiting for SIGIO */
339 };
340 static devclass_t psm_devclass;
341
342 /* driver state flags (state) */
343 #define PSM_VALID               0x80
344 #define PSM_OPEN                1       /* Device is open */
345 #define PSM_ASLP                2       /* Waiting for mouse data */
346 #define PSM_SOFTARMED           4       /* Software interrupt armed */
347 #define PSM_NEED_SYNCBITS       8       /* Set syncbits using next data pkt */
348
349 /* driver configuration flags (config) */
350 #define PSM_CONFIG_RESOLUTION   0x000f  /* resolution */
351 #define PSM_CONFIG_ACCEL        0x00f0  /* acceleration factor */
352 #define PSM_CONFIG_NOCHECKSYNC  0x0100  /* disable sync. test */
353 #define PSM_CONFIG_NOIDPROBE    0x0200  /* disable mouse model probe */
354 #define PSM_CONFIG_NORESET      0x0400  /* don't reset the mouse */
355 #define PSM_CONFIG_FORCETAP     0x0800  /* assume `tap' action exists */
356 #define PSM_CONFIG_IGNPORTERROR 0x1000  /* ignore error in aux port test */
357 #define PSM_CONFIG_HOOKRESUME   0x2000  /* hook the system resume event */
358 #define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
359
360 #define PSM_CONFIG_FLAGS        \
361     (PSM_CONFIG_RESOLUTION |    \
362     PSM_CONFIG_ACCEL |          \
363     PSM_CONFIG_NOCHECKSYNC |    \
364     PSM_CONFIG_NOIDPROBE |      \
365     PSM_CONFIG_NORESET |        \
366     PSM_CONFIG_FORCETAP |       \
367     PSM_CONFIG_IGNPORTERROR |   \
368     PSM_CONFIG_HOOKRESUME |     \
369     PSM_CONFIG_INITAFTERSUSPEND)
370
371 /* other flags (flags) */
372 #define PSM_FLAGS_FINGERDOWN    0x0001  /* VersaPad finger down */
373
374 /* Tunables */
375 static int tap_enabled = -1;
376 TUNABLE_INT("hw.psm.tap_enabled", &tap_enabled);
377
378 static int synaptics_support = 0;
379 TUNABLE_INT("hw.psm.synaptics_support", &synaptics_support);
380
381 static int trackpoint_support = 0;
382 TUNABLE_INT("hw.psm.trackpoint_support", &trackpoint_support);
383
384 static int verbose = PSM_DEBUG;
385 TUNABLE_INT("debug.psm.loglevel", &verbose);
386
387 /* for backward compatibility */
388 #define OLD_MOUSE_GETHWINFO     _IOR('M', 1, old_mousehw_t)
389 #define OLD_MOUSE_GETMODE       _IOR('M', 2, old_mousemode_t)
390 #define OLD_MOUSE_SETMODE       _IOW('M', 3, old_mousemode_t)
391
392 typedef struct old_mousehw {
393         int     buttons;
394         int     iftype;
395         int     type;
396         int     hwid;
397 } old_mousehw_t;
398
399 typedef struct old_mousemode {
400         int     protocol;
401         int     rate;
402         int     resolution;
403         int     accelfactor;
404 } old_mousemode_t;
405
406 /* packet formatting function */
407 typedef int     packetfunc_t(struct psm_softc *, u_char *, int *, int,
408     mousestatus_t *);
409
410 /* function prototypes */
411 static void     psmidentify(driver_t *, device_t);
412 static int      psmprobe(device_t);
413 static int      psmattach(device_t);
414 static int      psmdetach(device_t);
415 static int      psmresume(device_t);
416
417 static d_open_t         psmopen;
418 static d_close_t        psmclose;
419 static d_read_t         psmread;
420 static d_write_t        psmwrite;
421 static d_ioctl_t        psmioctl;
422 static d_poll_t         psmpoll;
423
424 static int      enable_aux_dev(KBDC);
425 static int      disable_aux_dev(KBDC);
426 static int      get_mouse_status(KBDC, int *, int, int);
427 static int      get_aux_id(KBDC);
428 static int      set_mouse_sampling_rate(KBDC, int);
429 static int      set_mouse_scaling(KBDC, int);
430 static int      set_mouse_resolution(KBDC, int);
431 static int      set_mouse_mode(KBDC);
432 static int      get_mouse_buttons(KBDC);
433 static int      is_a_mouse(int);
434 static void     recover_from_error(KBDC);
435 static int      restore_controller(KBDC, int);
436 static int      doinitialize(struct psm_softc *, mousemode_t *);
437 static int      doopen(struct psm_softc *, int);
438 static int      reinitialize(struct psm_softc *, int);
439 static char     *model_name(int);
440 static void     psmsoftintr(void *);
441 static void     psmintr(void *);
442 static void     psmtimeout(void *);
443 static int      timeelapsed(const struct timeval *, int, int,
444                     const struct timeval *);
445 static void     dropqueue(struct psm_softc *);
446 static void     flushpackets(struct psm_softc *);
447 static void     proc_mmanplus(struct psm_softc *, packetbuf_t *,
448                     mousestatus_t *, int *, int *, int *);
449 static int      proc_synaptics(struct psm_softc *, packetbuf_t *,
450                     mousestatus_t *, int *, int *, int *);
451 static void     proc_versapad(struct psm_softc *, packetbuf_t *,
452                     mousestatus_t *, int *, int *, int *);
453 static int      tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *,
454                     u_char *);
455
456 /* vendor specific features */
457 typedef int     probefunc_t(KBDC, struct psm_softc *);
458
459 static int      mouse_id_proc1(KBDC, int, int, int *);
460 static int      mouse_ext_command(KBDC, int);
461
462 static probefunc_t      enable_groller;
463 static probefunc_t      enable_gmouse;
464 static probefunc_t      enable_aglide;
465 static probefunc_t      enable_kmouse;
466 static probefunc_t      enable_msexplorer;
467 static probefunc_t      enable_msintelli;
468 static probefunc_t      enable_4dmouse;
469 static probefunc_t      enable_4dplus;
470 static probefunc_t      enable_mmanplus;
471 static probefunc_t      enable_synaptics;
472 static probefunc_t      enable_trackpoint;
473 static probefunc_t      enable_versapad;
474
475 static struct {
476         int             model;
477         u_char          syncmask;
478         int             packetsize;
479         probefunc_t     *probefunc;
480 } vendortype[] = {
481         /*
482          * WARNING: the order of probe is very important.  Don't mess it
483          * unless you know what you are doing.
484          */
485         { MOUSE_MODEL_NET,              /* Genius NetMouse */
486           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse },
487         { MOUSE_MODEL_NETSCROLL,        /* Genius NetScroll */
488           0xc8, 6, enable_groller },
489         { MOUSE_MODEL_MOUSEMANPLUS,     /* Logitech MouseMan+ */
490           0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus },
491         { MOUSE_MODEL_EXPLORER,         /* Microsoft IntelliMouse Explorer */
492           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer },
493         { MOUSE_MODEL_4D,               /* A4 Tech 4D Mouse */
494           0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse },
495         { MOUSE_MODEL_4DPLUS,           /* A4 Tech 4D+ Mouse */
496           0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus },
497         { MOUSE_MODEL_SYNAPTICS,        /* Synaptics Touchpad */
498           0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics },
499         { MOUSE_MODEL_INTELLI,          /* Microsoft IntelliMouse */
500           0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli },
501         { MOUSE_MODEL_GLIDEPOINT,       /* ALPS GlidePoint */
502           0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide },
503         { MOUSE_MODEL_THINK,            /* Kensington ThinkingMouse */
504           0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse },
505         { MOUSE_MODEL_VERSAPAD,         /* Interlink electronics VersaPad */
506           0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad },
507         { MOUSE_MODEL_TRACKPOINT,       /* IBM/Lenovo TrackPoint */
508           0xc0, MOUSE_PS2_PACKETSIZE, enable_trackpoint },
509         { MOUSE_MODEL_GENERIC,
510           0xc0, MOUSE_PS2_PACKETSIZE, NULL },
511 };
512 #define GENERIC_MOUSE_ENTRY     \
513     ((sizeof(vendortype) / sizeof(*vendortype)) - 1)
514
515 /* device driver declarateion */
516 static device_method_t psm_methods[] = {
517         /* Device interface */
518         DEVMETHOD(device_identify,      psmidentify),
519         DEVMETHOD(device_probe,         psmprobe),
520         DEVMETHOD(device_attach,        psmattach),
521         DEVMETHOD(device_detach,        psmdetach),
522         DEVMETHOD(device_resume,        psmresume),
523
524         { 0, 0 }
525 };
526
527 static driver_t psm_driver = {
528         PSM_DRIVER_NAME,
529         psm_methods,
530         sizeof(struct psm_softc),
531 };
532
533 static struct cdevsw psm_cdevsw = {
534         .d_version =    D_VERSION,
535         .d_flags =      D_NEEDGIANT,
536         .d_open =       psmopen,
537         .d_close =      psmclose,
538         .d_read =       psmread,
539         .d_write =      psmwrite,
540         .d_ioctl =      psmioctl,
541         .d_poll =       psmpoll,
542         .d_name =       PSM_DRIVER_NAME,
543 };
544
545 /* device I/O routines */
546 static int
547 enable_aux_dev(KBDC kbdc)
548 {
549         int res;
550
551         res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
552         VLOG(2, (LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res));
553
554         return (res == PSM_ACK);
555 }
556
557 static int
558 disable_aux_dev(KBDC kbdc)
559 {
560         int res;
561
562         res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
563         VLOG(2, (LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res));
564
565         return (res == PSM_ACK);
566 }
567
568 static int
569 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
570 {
571         int cmd;
572         int res;
573         int i;
574
575         switch (flag) {
576         case 0:
577         default:
578                 cmd = PSMC_SEND_DEV_STATUS;
579                 break;
580         case 1:
581                 cmd = PSMC_SEND_DEV_DATA;
582                 break;
583         }
584         empty_aux_buffer(kbdc, 5);
585         res = send_aux_command(kbdc, cmd);
586         VLOG(2, (LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
587             (flag == 1) ? "DATA" : "STATUS", res));
588         if (res != PSM_ACK)
589                 return (0);
590
591         for (i = 0; i < len; ++i) {
592                 status[i] = read_aux_data(kbdc);
593                 if (status[i] < 0)
594                         break;
595         }
596
597         VLOG(1, (LOG_DEBUG, "psm: %s %02x %02x %02x\n",
598             (flag == 1) ? "data" : "status", status[0], status[1], status[2]));
599
600         return (i);
601 }
602
603 static int
604 get_aux_id(KBDC kbdc)
605 {
606         int res;
607         int id;
608
609         empty_aux_buffer(kbdc, 5);
610         res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
611         VLOG(2, (LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res));
612         if (res != PSM_ACK)
613                 return (-1);
614
615         /* 10ms delay */
616         DELAY(10000);
617
618         id = read_aux_data(kbdc);
619         VLOG(2, (LOG_DEBUG, "psm: device ID: %04x\n", id));
620
621         return (id);
622 }
623
624 static int
625 set_mouse_sampling_rate(KBDC kbdc, int rate)
626 {
627         int res;
628
629         res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
630         VLOG(2, (LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res));
631
632         return ((res == PSM_ACK) ? rate : -1);
633 }
634
635 static int
636 set_mouse_scaling(KBDC kbdc, int scale)
637 {
638         int res;
639
640         switch (scale) {
641         case 1:
642         default:
643                 scale = PSMC_SET_SCALING11;
644                 break;
645         case 2:
646                 scale = PSMC_SET_SCALING21;
647                 break;
648         }
649         res = send_aux_command(kbdc, scale);
650         VLOG(2, (LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
651             (scale == PSMC_SET_SCALING21) ? "21" : "11", res));
652
653         return (res == PSM_ACK);
654 }
655
656 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
657 static int
658 set_mouse_resolution(KBDC kbdc, int val)
659 {
660         int res;
661
662         res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
663         VLOG(2, (LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res));
664
665         return ((res == PSM_ACK) ? val : -1);
666 }
667
668 /*
669  * NOTE: once `set_mouse_mode()' is called, the mouse device must be
670  * re-enabled by calling `enable_aux_dev()'
671  */
672 static int
673 set_mouse_mode(KBDC kbdc)
674 {
675         int res;
676
677         res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
678         VLOG(2, (LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res));
679
680         return (res == PSM_ACK);
681 }
682
683 static int
684 get_mouse_buttons(KBDC kbdc)
685 {
686         int c = 2;              /* assume two buttons by default */
687         int status[3];
688
689         /*
690          * NOTE: a special sequence to obtain Logitech Mouse specific
691          * information: set resolution to 25 ppi, set scaling to 1:1, set
692          * scaling to 1:1, set scaling to 1:1. Then the second byte of the
693          * mouse status bytes is the number of available buttons.
694          * Some manufactures also support this sequence.
695          */
696         if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
697                 return (c);
698         if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1) &&
699             set_mouse_scaling(kbdc, 1) &&
700             get_mouse_status(kbdc, status, 0, 3) >= 3 && status[1] != 0)
701                 return (status[1]);
702         return (c);
703 }
704
705 /* misc subroutines */
706 /*
707  * Someday, I will get the complete list of valid pointing devices and
708  * their IDs... XXX
709  */
710 static int
711 is_a_mouse(int id)
712 {
713 #if 0
714         static int valid_ids[] = {
715                 PSM_MOUSE_ID,           /* mouse */
716                 PSM_BALLPOINT_ID,       /* ballpoint device */
717                 PSM_INTELLI_ID,         /* Intellimouse */
718                 PSM_EXPLORER_ID,        /* Intellimouse Explorer */
719                 -1                      /* end of table */
720         };
721         int i;
722
723         for (i = 0; valid_ids[i] >= 0; ++i)
724         if (valid_ids[i] == id)
725                 return (TRUE);
726         return (FALSE);
727 #else
728         return (TRUE);
729 #endif
730 }
731
732 static char *
733 model_name(int model)
734 {
735         static struct {
736                 int     model_code;
737                 char    *model_name;
738         } models[] = {
739                 { MOUSE_MODEL_NETSCROLL,        "NetScroll" },
740                 { MOUSE_MODEL_NET,              "NetMouse/NetScroll Optical" },
741                 { MOUSE_MODEL_GLIDEPOINT,       "GlidePoint" },
742                 { MOUSE_MODEL_THINK,            "ThinkingMouse" },
743                 { MOUSE_MODEL_INTELLI,          "IntelliMouse" },
744                 { MOUSE_MODEL_MOUSEMANPLUS,     "MouseMan+" },
745                 { MOUSE_MODEL_VERSAPAD,         "VersaPad" },
746                 { MOUSE_MODEL_EXPLORER,         "IntelliMouse Explorer" },
747                 { MOUSE_MODEL_4D,               "4D Mouse" },
748                 { MOUSE_MODEL_4DPLUS,           "4D+ Mouse" },
749                 { MOUSE_MODEL_SYNAPTICS,        "Synaptics Touchpad" },
750                 { MOUSE_MODEL_TRACKPOINT,       "IBM/Lenovo TrackPoint" },
751                 { MOUSE_MODEL_GENERIC,          "Generic PS/2 mouse" },
752                 { MOUSE_MODEL_UNKNOWN,          "Unknown" },
753         };
754         int i;
755
756         for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i)
757                 if (models[i].model_code == model)
758                         break;
759         return (models[i].model_name);
760 }
761
762 static void
763 recover_from_error(KBDC kbdc)
764 {
765         /* discard anything left in the output buffer */
766         empty_both_buffers(kbdc, 10);
767
768 #if 0
769         /*
770          * NOTE: KBDC_RESET_KBD may not restore the communication between the
771          * keyboard and the controller.
772          */
773         reset_kbd(kbdc);
774 #else
775         /*
776          * NOTE: somehow diagnostic and keyboard port test commands bring the
777          * keyboard back.
778          */
779         if (!test_controller(kbdc))
780                 log(LOG_ERR, "psm: keyboard controller failed.\n");
781         /* if there isn't a keyboard in the system, the following error is OK */
782         if (test_kbd_port(kbdc) != 0)
783                 VLOG(1, (LOG_ERR, "psm: keyboard port failed.\n"));
784 #endif
785 }
786
787 static int
788 restore_controller(KBDC kbdc, int command_byte)
789 {
790         empty_both_buffers(kbdc, 10);
791
792         if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
793                 log(LOG_ERR, "psm: failed to restore the keyboard controller "
794                     "command byte.\n");
795                 empty_both_buffers(kbdc, 10);
796                 return (FALSE);
797         } else {
798                 empty_both_buffers(kbdc, 10);
799                 return (TRUE);
800         }
801 }
802
803 /*
804  * Re-initialize the aux port and device. The aux port must be enabled
805  * and its interrupt must be disabled before calling this routine.
806  * The aux device will be disabled before returning.
807  * The keyboard controller must be locked via `kbdc_lock()' before
808  * calling this routine.
809  */
810 static int
811 doinitialize(struct psm_softc *sc, mousemode_t *mode)
812 {
813         KBDC kbdc = sc->kbdc;
814         int stat[3];
815         int i;
816
817         switch((i = test_aux_port(kbdc))) {
818         case 1: /* ignore these errors */
819         case 2:
820         case 3:
821         case PSM_ACK:
822                 if (verbose)
823                         log(LOG_DEBUG,
824                             "psm%d: strange result for test aux port (%d).\n",
825                             sc->unit, i);
826                 /* FALLTHROUGH */
827         case 0:         /* no error */
828                 break;
829         case -1:        /* time out */
830         default:        /* error */
831                 recover_from_error(kbdc);
832                 if (sc->config & PSM_CONFIG_IGNPORTERROR)
833                         break;
834                 log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
835                     sc->unit, i);
836                 return (FALSE);
837         }
838
839         if (sc->config & PSM_CONFIG_NORESET) {
840                 /*
841                  * Don't try to reset the pointing device.  It may possibly
842                  * be left in the unknown state, though...
843                  */
844         } else {
845                 /*
846                  * NOTE: some controllers appears to hang the `keyboard' when
847                  * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
848                  */
849                 if (!reset_aux_dev(kbdc)) {
850                         recover_from_error(kbdc);
851                         log(LOG_ERR, "psm%d: failed to reset the aux device.\n",
852                             sc->unit);
853                         return (FALSE);
854                 }
855         }
856
857         /*
858          * both the aux port and the aux device is functioning, see
859          * if the device can be enabled.
860          */
861         if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
862                 log(LOG_ERR, "psm%d: failed to enable the aux device.\n",
863                     sc->unit);
864                 return (FALSE);
865         }
866         empty_both_buffers(kbdc, 10);   /* remove stray data if any */
867
868         /* Re-enable the mouse. */
869         for (i = 0; vendortype[i].probefunc != NULL; ++i)
870                 if (vendortype[i].model == sc->hw.model)
871                         (*vendortype[i].probefunc)(sc->kbdc, NULL);
872
873         /* set mouse parameters */
874         if (mode != (mousemode_t *)NULL) {
875                 if (mode->rate > 0)
876                         mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
877                 if (mode->resolution >= 0)
878                         mode->resolution =
879                             set_mouse_resolution(kbdc, mode->resolution);
880                 set_mouse_scaling(kbdc, 1);
881                 set_mouse_mode(kbdc);
882         }
883
884         /* Record sync on the next data packet we see. */
885         sc->flags |= PSM_NEED_SYNCBITS;
886
887         /* just check the status of the mouse */
888         if (get_mouse_status(kbdc, stat, 0, 3) < 3)
889                 log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
890                     sc->unit);
891
892         return (TRUE);
893 }
894
895 static int
896 doopen(struct psm_softc *sc, int command_byte)
897 {
898         int stat[3];
899
900         /*
901          * FIXME: Synaptics TouchPad seems to go back to Relative Mode with
902          * no obvious reason. Thus we check the current mode and restore the
903          * Absolute Mode if it was cleared.
904          *
905          * The previous hack at the end of psmprobe() wasn't efficient when
906          * moused(8) was restarted.
907          *
908          * A Reset (FF) or Set Defaults (F6) command would clear the
909          * Absolute Mode bit. But a verbose boot or debug.psm.loglevel=5
910          * doesn't show any evidence of such a command.
911          */
912         if (sc->hw.model == MOUSE_MODEL_SYNAPTICS) {
913                 mouse_ext_command(sc->kbdc, 1);
914                 get_mouse_status(sc->kbdc, stat, 0, 3);
915                 if ((SYNAPTICS_VERSION_GE(sc->synhw, 7, 5) ||
916                      stat[1] == 0x47) &&
917                     stat[2] == 0x40) {
918                         /* Set the mode byte -- request wmode where
919                          * available */
920                         if (sc->synhw.capExtended)
921                                 mouse_ext_command(sc->kbdc, 0xc1);
922                         else
923                                 mouse_ext_command(sc->kbdc, 0xc0);
924                         set_mouse_sampling_rate(sc->kbdc, 20);
925                         VLOG(5, (LOG_DEBUG, "psm%d: Synaptis Absolute Mode "
926                             "hopefully restored\n",
927                             sc->unit));
928                 }
929         }
930
931         /*
932          * A user may want to disable tap and drag gestures on a Synaptics
933          * TouchPad when it operates in Relative Mode.
934          */
935         if (sc->hw.model == MOUSE_MODEL_GENERIC) {
936                 if (tap_enabled > 0) {
937                         /*
938                          * Enable tap & drag gestures. We use a Mode Byte
939                          * and clear the DisGest bit (see Â§2.5 of Synaptics
940                          * TouchPad Interfacing Guide).
941                          */
942                         VLOG(2, (LOG_DEBUG,
943                             "psm%d: enable tap and drag gestures\n",
944                             sc->unit));
945                         mouse_ext_command(sc->kbdc, 0x00);
946                         set_mouse_sampling_rate(sc->kbdc, 20);
947                 } else if (tap_enabled == 0) {
948                         /*
949                          * Disable tap & drag gestures. We use a Mode Byte
950                          * and set the DisGest bit (see Â§2.5 of Synaptics
951                          * TouchPad Interfacing Guide).
952                          */
953                         VLOG(2, (LOG_DEBUG,
954                             "psm%d: disable tap and drag gestures\n",
955                             sc->unit));
956                         mouse_ext_command(sc->kbdc, 0x04);
957                         set_mouse_sampling_rate(sc->kbdc, 20);
958                 }
959         }
960
961         /* enable the mouse device */
962         if (!enable_aux_dev(sc->kbdc)) {
963                 /* MOUSE ERROR: failed to enable the mouse because:
964                  * 1) the mouse is faulty,
965                  * 2) the mouse has been removed(!?)
966                  * In the latter case, the keyboard may have hung, and need
967                  * recovery procedure...
968                  */
969                 recover_from_error(sc->kbdc);
970 #if 0
971                 /* FIXME: we could reset the mouse here and try to enable
972                  * it again. But it will take long time and it's not a good
973                  * idea to disable the keyboard that long...
974                  */
975                 if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
976                         recover_from_error(sc->kbdc);
977 #else
978                 {
979 #endif
980                         restore_controller(sc->kbdc, command_byte);
981                         /* mark this device is no longer available */
982                         sc->state &= ~PSM_VALID;
983                         log(LOG_ERR,
984                             "psm%d: failed to enable the device (doopen).\n",
985                         sc->unit);
986                         return (EIO);
987                 }
988         }
989
990         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
991                 log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n",
992                     sc->unit);
993
994         /* enable the aux port and interrupt */
995         if (!set_controller_command_byte(sc->kbdc,
996             kbdc_get_device_mask(sc->kbdc),
997             (command_byte & KBD_KBD_CONTROL_BITS) |
998             KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
999                 /* CONTROLLER ERROR */
1000                 disable_aux_dev(sc->kbdc);
1001                 restore_controller(sc->kbdc, command_byte);
1002                 log(LOG_ERR,
1003                     "psm%d: failed to enable the aux interrupt (doopen).\n",
1004                     sc->unit);
1005                 return (EIO);
1006         }
1007
1008         /* start the watchdog timer */
1009         sc->watchdog = FALSE;
1010         sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz*2);
1011
1012         return (0);
1013 }
1014
1015 static int
1016 reinitialize(struct psm_softc *sc, int doinit)
1017 {
1018         int err;
1019         int c;
1020         int s;
1021
1022         /* don't let anybody mess with the aux device */
1023         if (!kbdc_lock(sc->kbdc, TRUE))
1024                 return (EIO);
1025         s = spltty();
1026
1027         /* block our watchdog timer */
1028         sc->watchdog = FALSE;
1029         untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
1030         callout_handle_init(&sc->callout);
1031
1032         /* save the current controller command byte */
1033         empty_both_buffers(sc->kbdc, 10);
1034         c = get_controller_command_byte(sc->kbdc);
1035         VLOG(2, (LOG_DEBUG,
1036             "psm%d: current command byte: %04x (reinitialize).\n",
1037             sc->unit, c));
1038
1039         /* enable the aux port but disable the aux interrupt and the keyboard */
1040         if ((c == -1) || !set_controller_command_byte(sc->kbdc,
1041             kbdc_get_device_mask(sc->kbdc),
1042             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1043             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1044                 /* CONTROLLER ERROR */
1045                 splx(s);
1046                 kbdc_lock(sc->kbdc, FALSE);
1047                 log(LOG_ERR,
1048                     "psm%d: unable to set the command byte (reinitialize).\n",
1049                     sc->unit);
1050                 return (EIO);
1051         }
1052
1053         /* flush any data */
1054         if (sc->state & PSM_VALID) {
1055                 /* this may fail; but never mind... */
1056                 disable_aux_dev(sc->kbdc);
1057                 empty_aux_buffer(sc->kbdc, 10);
1058         }
1059         flushpackets(sc);
1060         sc->syncerrors = 0;
1061         sc->pkterrors = 0;
1062         memset(&sc->lastinputerr, 0, sizeof(sc->lastinputerr));
1063
1064         /* try to detect the aux device; are you still there? */
1065         err = 0;
1066         if (doinit) {
1067                 if (doinitialize(sc, &sc->mode)) {
1068                         /* yes */
1069                         sc->state |= PSM_VALID;
1070                 } else {
1071                         /* the device has gone! */
1072                         restore_controller(sc->kbdc, c);
1073                         sc->state &= ~PSM_VALID;
1074                         log(LOG_ERR,
1075                             "psm%d: the aux device has gone! (reinitialize).\n",
1076                             sc->unit);
1077                         err = ENXIO;
1078                 }
1079         }
1080         splx(s);
1081
1082         /* restore the driver state */
1083         if ((sc->state & PSM_OPEN) && (err == 0)) {
1084                 /* enable the aux device and the port again */
1085                 err = doopen(sc, c);
1086                 if (err != 0)
1087                         log(LOG_ERR, "psm%d: failed to enable the device "
1088                             "(reinitialize).\n", sc->unit);
1089         } else {
1090                 /* restore the keyboard port and disable the aux port */
1091                 if (!set_controller_command_byte(sc->kbdc,
1092                     kbdc_get_device_mask(sc->kbdc),
1093                     (c & KBD_KBD_CONTROL_BITS) |
1094                     KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1095                         /* CONTROLLER ERROR */
1096                         log(LOG_ERR, "psm%d: failed to disable the aux port "
1097                             "(reinitialize).\n", sc->unit);
1098                         err = EIO;
1099                 }
1100         }
1101
1102         kbdc_lock(sc->kbdc, FALSE);
1103         return (err);
1104 }
1105
1106 /* psm driver entry points */
1107
1108 static void
1109 psmidentify(driver_t *driver, device_t parent)
1110 {
1111         device_t psmc;
1112         device_t psm;
1113         u_long irq;
1114         int unit;
1115
1116         unit = device_get_unit(parent);
1117
1118         /* always add at least one child */
1119         psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
1120         if (psm == NULL)
1121                 return;
1122
1123         irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
1124         if (irq > 0)
1125                 return;
1126
1127         /*
1128          * If the PS/2 mouse device has already been reported by ACPI or
1129          * PnP BIOS, obtain the IRQ resource from it.
1130          * (See psmcpnp_attach() below.)
1131          */
1132         psmc = device_find_child(device_get_parent(parent),
1133             PSMCPNP_DRIVER_NAME, unit);
1134         if (psmc == NULL)
1135                 return;
1136         irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
1137         if (irq <= 0)
1138                 return;
1139         bus_delete_resource(psmc, SYS_RES_IRQ, 0);
1140         bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
1141 }
1142
1143 #define endprobe(v)     do {                    \
1144         if (bootverbose)                        \
1145                 --verbose;                      \
1146         kbdc_set_device_mask(sc->kbdc, mask);   \
1147         kbdc_lock(sc->kbdc, FALSE);             \
1148         return (v);                             \
1149 } while (0)
1150
1151 static int
1152 psmprobe(device_t dev)
1153 {
1154         int unit = device_get_unit(dev);
1155         struct psm_softc *sc = device_get_softc(dev);
1156         int stat[3];
1157         int command_byte;
1158         int mask;
1159         int rid;
1160         int i;
1161
1162 #if 0
1163         kbdc_debug(TRUE);
1164 #endif
1165
1166         /* see if IRQ is available */
1167         rid = KBDC_RID_AUX;
1168         sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1169         if (sc->intr == NULL) {
1170                 if (bootverbose)
1171                         device_printf(dev, "unable to allocate IRQ\n");
1172                 return (ENXIO);
1173         }
1174         bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1175
1176         sc->unit = unit;
1177         sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
1178         sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
1179         /* XXX: for backward compatibility */
1180 #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
1181         sc->config |=
1182 #ifdef PSM_RESETAFTERSUSPEND
1183         PSM_CONFIG_INITAFTERSUSPEND;
1184 #else
1185         PSM_CONFIG_HOOKRESUME;
1186 #endif
1187 #endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
1188         sc->flags = 0;
1189         if (bootverbose)
1190                 ++verbose;
1191
1192         device_set_desc(dev, "PS/2 Mouse");
1193
1194         if (!kbdc_lock(sc->kbdc, TRUE)) {
1195                 printf("psm%d: unable to lock the controller.\n", unit);
1196                 if (bootverbose)
1197                         --verbose;
1198                 return (ENXIO);
1199         }
1200
1201         /*
1202          * NOTE: two bits in the command byte controls the operation of the
1203          * aux port (mouse port): the aux port disable bit (bit 5) and the aux
1204          * port interrupt (IRQ 12) enable bit (bit 2).
1205          */
1206
1207         /* discard anything left after the keyboard initialization */
1208         empty_both_buffers(sc->kbdc, 10);
1209
1210         /* save the current command byte; it will be used later */
1211         mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
1212         command_byte = get_controller_command_byte(sc->kbdc);
1213         if (verbose)
1214                 printf("psm%d: current command byte:%04x\n", unit,
1215                     command_byte);
1216         if (command_byte == -1) {
1217                 /* CONTROLLER ERROR */
1218                 printf("psm%d: unable to get the current command byte value.\n",
1219                         unit);
1220                 endprobe(ENXIO);
1221         }
1222
1223         /*
1224          * disable the keyboard port while probing the aux port, which must be
1225          * enabled during this routine
1226          */
1227         if (!set_controller_command_byte(sc->kbdc,
1228             KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1229             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1230             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1231                 /*
1232                  * this is CONTROLLER ERROR; I don't know how to recover
1233                  * from this error...
1234                  */
1235                 restore_controller(sc->kbdc, command_byte);
1236                 printf("psm%d: unable to set the command byte.\n", unit);
1237                 endprobe(ENXIO);
1238         }
1239         write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
1240
1241         /*
1242          * NOTE: `test_aux_port()' is designed to return with zero if the aux
1243          * port exists and is functioning. However, some controllers appears
1244          * to respond with zero even when the aux port doesn't exist. (It may
1245          * be that this is only the case when the controller DOES have the aux
1246          * port but the port is not wired on the motherboard.) The keyboard
1247          * controllers without the port, such as the original AT, are
1248          * supposed to return with an error code or simply time out. In any
1249          * case, we have to continue probing the port even when the controller
1250          * passes this test.
1251          *
1252          * XXX: some controllers erroneously return the error code 1, 2 or 3
1253          * when it has a perfectly functional aux port. We have to ignore
1254          * this error code. Even if the controller HAS error with the aux
1255          * port, it will be detected later...
1256          * XXX: another incompatible controller returns PSM_ACK (0xfa)...
1257          */
1258         switch ((i = test_aux_port(sc->kbdc))) {
1259         case 1:         /* ignore these errors */
1260         case 2:
1261         case 3:
1262         case PSM_ACK:
1263                 if (verbose)
1264                         printf("psm%d: strange result for test aux port "
1265                             "(%d).\n", unit, i);
1266                 /* FALLTHROUGH */
1267         case 0:         /* no error */
1268                 break;
1269         case -1:        /* time out */
1270         default:        /* error */
1271                 recover_from_error(sc->kbdc);
1272                 if (sc->config & PSM_CONFIG_IGNPORTERROR)
1273                         break;
1274                 restore_controller(sc->kbdc, command_byte);
1275                 if (verbose)
1276                         printf("psm%d: the aux port is not functioning (%d).\n",
1277                             unit, i);
1278                 endprobe(ENXIO);
1279         }
1280
1281         if (sc->config & PSM_CONFIG_NORESET) {
1282                 /*
1283                  * Don't try to reset the pointing device.  It may possibly be
1284                  * left in an unknown state, though...
1285                  */
1286         } else {
1287                 /*
1288                  * NOTE: some controllers appears to hang the `keyboard' when
1289                  * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
1290                  *
1291                  * Attempt to reset the controller twice -- this helps
1292                  * pierce through some KVM switches. The second reset
1293                  * is non-fatal.
1294                  */
1295                 if (!reset_aux_dev(sc->kbdc)) {
1296                         recover_from_error(sc->kbdc);
1297                         restore_controller(sc->kbdc, command_byte);
1298                         if (verbose)
1299                                 printf("psm%d: failed to reset the aux "
1300                                     "device.\n", unit);
1301                         endprobe(ENXIO);
1302                 } else if (!reset_aux_dev(sc->kbdc)) {
1303                         recover_from_error(sc->kbdc);
1304                         if (verbose >= 2)
1305                                 printf("psm%d: failed to reset the aux device "
1306                                     "(2).\n", unit);
1307                 }
1308         }
1309
1310         /*
1311          * both the aux port and the aux device are functioning, see if the
1312          * device can be enabled. NOTE: when enabled, the device will start
1313          * sending data; we shall immediately disable the device once we know
1314          * the device can be enabled.
1315          */
1316         if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1317                 /* MOUSE ERROR */
1318                 recover_from_error(sc->kbdc);
1319                 restore_controller(sc->kbdc, command_byte);
1320                 if (verbose)
1321                         printf("psm%d: failed to enable the aux device.\n",
1322                             unit);
1323                 endprobe(ENXIO);
1324         }
1325
1326         /* save the default values after reset */
1327         if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1328                 sc->dflt_mode.rate = sc->mode.rate = stat[2];
1329                 sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1330         } else {
1331                 sc->dflt_mode.rate = sc->mode.rate = -1;
1332                 sc->dflt_mode.resolution = sc->mode.resolution = -1;
1333         }
1334
1335         /* hardware information */
1336         sc->hw.iftype = MOUSE_IF_PS2;
1337
1338         /* verify the device is a mouse */
1339         sc->hw.hwid = get_aux_id(sc->kbdc);
1340         if (!is_a_mouse(sc->hw.hwid)) {
1341                 restore_controller(sc->kbdc, command_byte);
1342                 if (verbose)
1343                         printf("psm%d: unknown device type (%d).\n", unit,
1344                             sc->hw.hwid);
1345                 endprobe(ENXIO);
1346         }
1347         switch (sc->hw.hwid) {
1348         case PSM_BALLPOINT_ID:
1349                 sc->hw.type = MOUSE_TRACKBALL;
1350                 break;
1351         case PSM_MOUSE_ID:
1352         case PSM_INTELLI_ID:
1353         case PSM_EXPLORER_ID:
1354         case PSM_4DMOUSE_ID:
1355         case PSM_4DPLUS_ID:
1356                 sc->hw.type = MOUSE_MOUSE;
1357                 break;
1358         default:
1359                 sc->hw.type = MOUSE_UNKNOWN;
1360                 break;
1361         }
1362
1363         if (sc->config & PSM_CONFIG_NOIDPROBE) {
1364                 sc->hw.buttons = 2;
1365                 i = GENERIC_MOUSE_ENTRY;
1366         } else {
1367                 /* # of buttons */
1368                 sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1369
1370                 /* other parameters */
1371                 for (i = 0; vendortype[i].probefunc != NULL; ++i)
1372                         if ((*vendortype[i].probefunc)(sc->kbdc, sc)) {
1373                                 if (verbose >= 2)
1374                                         printf("psm%d: found %s\n", unit,
1375                                             model_name(vendortype[i].model));
1376                                 break;
1377                         }
1378         }
1379
1380         sc->hw.model = vendortype[i].model;
1381
1382         sc->dflt_mode.level = PSM_LEVEL_BASE;
1383         sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1384         sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1385         if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1386                 sc->dflt_mode.syncmask[0] = 0;
1387         else
1388                 sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1389         if (sc->config & PSM_CONFIG_FORCETAP)
1390                 sc->dflt_mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1391         sc->dflt_mode.syncmask[1] = 0;  /* syncbits */
1392         sc->mode = sc->dflt_mode;
1393         sc->mode.packetsize = vendortype[i].packetsize;
1394
1395         /* set mouse parameters */
1396 #if 0
1397         /*
1398          * A version of Logitech FirstMouse+ won't report wheel movement,
1399          * if SET_DEFAULTS is sent...  Don't use this command.
1400          * This fix was found by Takashi Nishida.
1401          */
1402         i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1403         if (verbose >= 2)
1404                 printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1405 #endif
1406         if (sc->config & PSM_CONFIG_RESOLUTION)
1407                 sc->mode.resolution =
1408                     set_mouse_resolution(sc->kbdc,
1409                     (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1410         else if (sc->mode.resolution >= 0)
1411                 sc->mode.resolution =
1412                     set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1413         if (sc->mode.rate > 0)
1414                 sc->mode.rate =
1415                     set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1416         set_mouse_scaling(sc->kbdc, 1);
1417
1418         /* Record sync on the next data packet we see. */
1419         sc->flags |= PSM_NEED_SYNCBITS;
1420
1421         /* just check the status of the mouse */
1422         /*
1423          * NOTE: XXX there are some arcane controller/mouse combinations out
1424          * there, which hung the controller unless there is data transmission
1425          * after ACK from the mouse.
1426          */
1427         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1428                 printf("psm%d: failed to get status.\n", unit);
1429         else {
1430                 /*
1431                  * When in its native mode, some mice operate with different
1432                  * default parameters than in the PS/2 compatible mode.
1433                  */
1434                 sc->dflt_mode.rate = sc->mode.rate = stat[2];
1435                 sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1436         }
1437
1438         /* disable the aux port for now... */
1439         if (!set_controller_command_byte(sc->kbdc,
1440             KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1441             (command_byte & KBD_KBD_CONTROL_BITS) |
1442             KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1443                 /*
1444                  * this is CONTROLLER ERROR; I don't know the proper way to
1445                  * recover from this error...
1446                  */
1447                 restore_controller(sc->kbdc, command_byte);
1448                 printf("psm%d: unable to set the command byte.\n", unit);
1449                 endprobe(ENXIO);
1450         }
1451
1452         /* done */
1453         kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1454         kbdc_lock(sc->kbdc, FALSE);
1455         return (0);
1456 }
1457
1458 static int
1459 psmattach(device_t dev)
1460 {
1461         int unit = device_get_unit(dev);
1462         struct psm_softc *sc = device_get_softc(dev);
1463         int error;
1464         int rid;
1465
1466         /* Setup initial state */
1467         sc->state = PSM_VALID;
1468         callout_handle_init(&sc->callout);
1469
1470         /* Setup our interrupt handler */
1471         rid = KBDC_RID_AUX;
1472         sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
1473         if (sc->intr == NULL)
1474                 return (ENXIO);
1475         error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, NULL, psmintr, sc,
1476             &sc->ih);
1477         if (error) {
1478                 bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1479                 return (error);
1480         }
1481
1482         /* Done */
1483         sc->dev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "psm%d", unit);
1484         sc->dev->si_drv1 = sc;
1485         sc->bdev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "bpsm%d", unit);
1486         sc->bdev->si_drv1 = sc;
1487
1488         /* Some touchpad devices need full reinitialization after suspend. */
1489         switch (sc->hw.model) {
1490         case MOUSE_MODEL_SYNAPTICS:
1491         case MOUSE_MODEL_GLIDEPOINT:
1492         case MOUSE_MODEL_VERSAPAD:
1493                 sc->config |= PSM_CONFIG_INITAFTERSUSPEND;
1494                 break;
1495         default:
1496                 if (sc->synhw.infoMajor >= 4 || sc->tphw > 0)
1497                         sc->config |= PSM_CONFIG_INITAFTERSUSPEND;
1498                 break;
1499         }
1500
1501         if (!verbose)
1502                 printf("psm%d: model %s, device ID %d\n",
1503                     unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1504         else {
1505                 printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1506                     unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff,
1507                     sc->hw.hwid >> 8, sc->hw.buttons);
1508                 printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1509                     unit, sc->config, sc->flags, sc->mode.packetsize);
1510                 printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1511                     unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1512         }
1513
1514         if (bootverbose)
1515                 --verbose;
1516
1517         return (0);
1518 }
1519
1520 static int
1521 psmdetach(device_t dev)
1522 {
1523         struct psm_softc *sc;
1524         int rid;
1525
1526         sc = device_get_softc(dev);
1527         if (sc->state & PSM_OPEN)
1528                 return (EBUSY);
1529
1530         rid = KBDC_RID_AUX;
1531         bus_teardown_intr(dev, sc->intr, sc->ih);
1532         bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1533
1534         destroy_dev(sc->dev);
1535         destroy_dev(sc->bdev);
1536
1537         return (0);
1538 }
1539
1540 static int
1541 psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
1542 {
1543         struct psm_softc *sc;
1544         int command_byte;
1545         int err;
1546         int s;
1547
1548         /* Get device data */
1549         sc = dev->si_drv1;
1550         if ((sc == NULL) || (sc->state & PSM_VALID) == 0) {
1551                 /* the device is no longer valid/functioning */
1552                 return (ENXIO);
1553         }
1554
1555         /* Disallow multiple opens */
1556         if (sc->state & PSM_OPEN)
1557                 return (EBUSY);
1558
1559         device_busy(devclass_get_device(psm_devclass, sc->unit));
1560
1561         /* Initialize state */
1562         sc->mode.level = sc->dflt_mode.level;
1563         sc->mode.protocol = sc->dflt_mode.protocol;
1564         sc->watchdog = FALSE;
1565         sc->async = NULL;
1566
1567         /* flush the event queue */
1568         sc->queue.count = 0;
1569         sc->queue.head = 0;
1570         sc->queue.tail = 0;
1571         sc->status.flags = 0;
1572         sc->status.button = 0;
1573         sc->status.obutton = 0;
1574         sc->status.dx = 0;
1575         sc->status.dy = 0;
1576         sc->status.dz = 0;
1577         sc->button = 0;
1578         sc->pqueue_start = 0;
1579         sc->pqueue_end = 0;
1580
1581         /* empty input buffer */
1582         flushpackets(sc);
1583         sc->syncerrors = 0;
1584         sc->pkterrors = 0;
1585
1586         /* don't let timeout routines in the keyboard driver to poll the kbdc */
1587         if (!kbdc_lock(sc->kbdc, TRUE))
1588                 return (EIO);
1589
1590         /* save the current controller command byte */
1591         s = spltty();
1592         command_byte = get_controller_command_byte(sc->kbdc);
1593
1594         /* enable the aux port and temporalily disable the keyboard */
1595         if (command_byte == -1 || !set_controller_command_byte(sc->kbdc,
1596             kbdc_get_device_mask(sc->kbdc),
1597             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1598             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1599                 /* CONTROLLER ERROR; do you know how to get out of this? */
1600                 kbdc_lock(sc->kbdc, FALSE);
1601                 splx(s);
1602                 log(LOG_ERR,
1603                     "psm%d: unable to set the command byte (psmopen).\n",
1604                     sc->unit);
1605                 return (EIO);
1606         }
1607         /*
1608          * Now that the keyboard controller is told not to generate
1609          * the keyboard and mouse interrupts, call `splx()' to allow
1610          * the other tty interrupts. The clock interrupt may also occur,
1611          * but timeout routines will be blocked by the poll flag set
1612          * via `kbdc_lock()'
1613          */
1614         splx(s);
1615
1616         /* enable the mouse device */
1617         err = doopen(sc, command_byte);
1618
1619         /* done */
1620         if (err == 0)
1621                 sc->state |= PSM_OPEN;
1622         kbdc_lock(sc->kbdc, FALSE);
1623         return (err);
1624 }
1625
1626 static int
1627 psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
1628 {
1629         struct psm_softc *sc = dev->si_drv1;
1630         int stat[3];
1631         int command_byte;
1632         int s;
1633
1634         /* don't let timeout routines in the keyboard driver to poll the kbdc */
1635         if (!kbdc_lock(sc->kbdc, TRUE))
1636                 return (EIO);
1637
1638         /* save the current controller command byte */
1639         s = spltty();
1640         command_byte = get_controller_command_byte(sc->kbdc);
1641         if (command_byte == -1) {
1642                 kbdc_lock(sc->kbdc, FALSE);
1643                 splx(s);
1644                 return (EIO);
1645         }
1646
1647         /* disable the aux interrupt and temporalily disable the keyboard */
1648         if (!set_controller_command_byte(sc->kbdc,
1649             kbdc_get_device_mask(sc->kbdc),
1650             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1651             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1652                 log(LOG_ERR,
1653                     "psm%d: failed to disable the aux int (psmclose).\n",
1654                     sc->unit);
1655                 /* CONTROLLER ERROR;
1656                  * NOTE: we shall force our way through. Because the only
1657                  * ill effect we shall see is that we may not be able
1658                  * to read ACK from the mouse, and it doesn't matter much
1659                  * so long as the mouse will accept the DISABLE command.
1660                  */
1661         }
1662         splx(s);
1663
1664         /* stop the watchdog timer */
1665         untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
1666         callout_handle_init(&sc->callout);
1667
1668         /* remove anything left in the output buffer */
1669         empty_aux_buffer(sc->kbdc, 10);
1670
1671         /* disable the aux device, port and interrupt */
1672         if (sc->state & PSM_VALID) {
1673                 if (!disable_aux_dev(sc->kbdc)) {
1674                         /* MOUSE ERROR;
1675                          * NOTE: we don't return (error) and continue,
1676                          * pretending we have successfully disabled the device.
1677                          * It's OK because the interrupt routine will discard
1678                          * any data from the mouse hereafter.
1679                          */
1680                         log(LOG_ERR,
1681                             "psm%d: failed to disable the device (psmclose).\n",
1682                             sc->unit);
1683                 }
1684
1685                 if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1686                         log(LOG_DEBUG,
1687                             "psm%d: failed to get status (psmclose).\n",
1688                             sc->unit);
1689         }
1690
1691         if (!set_controller_command_byte(sc->kbdc,
1692             kbdc_get_device_mask(sc->kbdc),
1693             (command_byte & KBD_KBD_CONTROL_BITS) |
1694             KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1695                 /*
1696                  * CONTROLLER ERROR;
1697                  * we shall ignore this error; see the above comment.
1698                  */
1699                 log(LOG_ERR,
1700                     "psm%d: failed to disable the aux port (psmclose).\n",
1701                     sc->unit);
1702         }
1703
1704         /* remove anything left in the output buffer */
1705         empty_aux_buffer(sc->kbdc, 10);
1706
1707         /* clean up and sigio requests */
1708         if (sc->async != NULL) {
1709                 funsetown(&sc->async);
1710                 sc->async = NULL;
1711         }
1712
1713         /* close is almost always successful */
1714         sc->state &= ~PSM_OPEN;
1715         kbdc_lock(sc->kbdc, FALSE);
1716         device_unbusy(devclass_get_device(psm_devclass, sc->unit));
1717         return (0);
1718 }
1719
1720 static int
1721 tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status,
1722     u_char *buf)
1723 {
1724         static u_char butmapps2[8] = {
1725                 0,
1726                 MOUSE_PS2_BUTTON1DOWN,
1727                 MOUSE_PS2_BUTTON2DOWN,
1728                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1729                 MOUSE_PS2_BUTTON3DOWN,
1730                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1731                 MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1732                 MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN |
1733                     MOUSE_PS2_BUTTON3DOWN,
1734         };
1735         static u_char butmapmsc[8] = {
1736                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP |
1737                     MOUSE_MSC_BUTTON3UP,
1738                 MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1739                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1740                 MOUSE_MSC_BUTTON3UP,
1741                 MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1742                 MOUSE_MSC_BUTTON2UP,
1743                 MOUSE_MSC_BUTTON1UP,
1744                 0,
1745         };
1746         int mapped;
1747         int i;
1748
1749         if (sc->mode.level == PSM_LEVEL_BASE) {
1750                 mapped = status->button & ~MOUSE_BUTTON4DOWN;
1751                 if (status->button & MOUSE_BUTTON4DOWN)
1752                         mapped |= MOUSE_BUTTON1DOWN;
1753                 status->button = mapped;
1754                 buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1755                 i = imax(imin(status->dx, 255), -256);
1756                 if (i < 0)
1757                         buf[0] |= MOUSE_PS2_XNEG;
1758                 buf[1] = i;
1759                 i = imax(imin(status->dy, 255), -256);
1760                 if (i < 0)
1761                         buf[0] |= MOUSE_PS2_YNEG;
1762                 buf[2] = i;
1763                 return (MOUSE_PS2_PACKETSIZE);
1764         } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1765                 buf[0] = MOUSE_MSC_SYNC |
1766                     butmapmsc[status->button & MOUSE_STDBUTTONS];
1767                 i = imax(imin(status->dx, 255), -256);
1768                 buf[1] = i >> 1;
1769                 buf[3] = i - buf[1];
1770                 i = imax(imin(status->dy, 255), -256);
1771                 buf[2] = i >> 1;
1772                 buf[4] = i - buf[2];
1773                 i = imax(imin(status->dz, 127), -128);
1774                 buf[5] = (i >> 1) & 0x7f;
1775                 buf[6] = (i - (i >> 1)) & 0x7f;
1776                 buf[7] = (~status->button >> 3) & 0x7f;
1777                 return (MOUSE_SYS_PACKETSIZE);
1778         }
1779         return (pb->inputbytes);
1780 }
1781
1782 static int
1783 psmread(struct cdev *dev, struct uio *uio, int flag)
1784 {
1785         struct psm_softc *sc = dev->si_drv1;
1786         u_char buf[PSM_SMALLBUFSIZE];
1787         int error = 0;
1788         int s;
1789         int l;
1790
1791         if ((sc->state & PSM_VALID) == 0)
1792                 return (EIO);
1793
1794         /* block until mouse activity occured */
1795         s = spltty();
1796         while (sc->queue.count <= 0) {
1797                 if (dev != sc->bdev) {
1798                         splx(s);
1799                         return (EWOULDBLOCK);
1800                 }
1801                 sc->state |= PSM_ASLP;
1802                 error = tsleep(sc, PZERO | PCATCH, "psmrea", 0);
1803                 sc->state &= ~PSM_ASLP;
1804                 if (error) {
1805                         splx(s);
1806                         return (error);
1807                 } else if ((sc->state & PSM_VALID) == 0) {
1808                         /* the device disappeared! */
1809                         splx(s);
1810                         return (EIO);
1811                 }
1812         }
1813         splx(s);
1814
1815         /* copy data to the user land */
1816         while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1817                 s = spltty();
1818                 l = imin(sc->queue.count, uio->uio_resid);
1819                 if (l > sizeof(buf))
1820                         l = sizeof(buf);
1821                 if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1822                         bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1823                             sizeof(sc->queue.buf) - sc->queue.head);
1824                         bcopy(&sc->queue.buf[0],
1825                             &buf[sizeof(sc->queue.buf) - sc->queue.head],
1826                             l - (sizeof(sc->queue.buf) - sc->queue.head));
1827                 } else
1828                         bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1829                 sc->queue.count -= l;
1830                 sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1831                 splx(s);
1832                 error = uiomove(buf, l, uio);
1833                 if (error)
1834                         break;
1835         }
1836
1837         return (error);
1838 }
1839
1840 static int
1841 block_mouse_data(struct psm_softc *sc, int *c)
1842 {
1843         int s;
1844
1845         if (!kbdc_lock(sc->kbdc, TRUE))
1846                 return (EIO);
1847
1848         s = spltty();
1849         *c = get_controller_command_byte(sc->kbdc);
1850         if ((*c == -1) || !set_controller_command_byte(sc->kbdc,
1851             kbdc_get_device_mask(sc->kbdc),
1852             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
1853             KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1854                 /* this is CONTROLLER ERROR */
1855                 splx(s);
1856                 kbdc_lock(sc->kbdc, FALSE);
1857                 return (EIO);
1858         }
1859
1860         /*
1861          * The device may be in the middle of status data transmission.
1862          * The transmission will be interrupted, thus, incomplete status
1863          * data must be discarded. Although the aux interrupt is disabled
1864          * at the keyboard controller level, at most one aux interrupt
1865          * may have already been pending and a data byte is in the
1866          * output buffer; throw it away. Note that the second argument
1867          * to `empty_aux_buffer()' is zero, so that the call will just
1868          * flush the internal queue.
1869          * `psmintr()' will be invoked after `splx()' if an interrupt is
1870          * pending; it will see no data and returns immediately.
1871          */
1872         empty_aux_buffer(sc->kbdc, 0);          /* flush the queue */
1873         read_aux_data_no_wait(sc->kbdc);        /* throw away data if any */
1874         flushpackets(sc);
1875         splx(s);
1876
1877         return (0);
1878 }
1879
1880 static void
1881 dropqueue(struct psm_softc *sc)
1882 {
1883
1884         sc->queue.count = 0;
1885         sc->queue.head = 0;
1886         sc->queue.tail = 0;
1887         if ((sc->state & PSM_SOFTARMED) != 0) {
1888                 sc->state &= ~PSM_SOFTARMED;
1889                 untimeout(psmsoftintr, (void *)(uintptr_t)sc, sc->softcallout);
1890         }
1891         sc->pqueue_start = sc->pqueue_end;
1892 }
1893
1894 static void
1895 flushpackets(struct psm_softc *sc)
1896 {
1897
1898         dropqueue(sc);
1899         bzero(&sc->pqueue, sizeof(sc->pqueue));
1900 }
1901
1902 static int
1903 unblock_mouse_data(struct psm_softc *sc, int c)
1904 {
1905         int error = 0;
1906
1907         /*
1908          * We may have seen a part of status data during `set_mouse_XXX()'.
1909          * they have been queued; flush it.
1910          */
1911         empty_aux_buffer(sc->kbdc, 0);
1912
1913         /* restore ports and interrupt */
1914         if (!set_controller_command_byte(sc->kbdc,
1915             kbdc_get_device_mask(sc->kbdc),
1916             c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1917                 /*
1918                  * CONTROLLER ERROR; this is serious, we may have
1919                  * been left with the inaccessible keyboard and
1920                  * the disabled mouse interrupt.
1921                  */
1922                 error = EIO;
1923         }
1924
1925         kbdc_lock(sc->kbdc, FALSE);
1926         return (error);
1927 }
1928
1929 static int
1930 psmwrite(struct cdev *dev, struct uio *uio, int flag)
1931 {
1932         struct psm_softc *sc = dev->si_drv1;
1933         u_char buf[PSM_SMALLBUFSIZE];
1934         int error = 0, i, l;
1935
1936         if ((sc->state & PSM_VALID) == 0)
1937                 return (EIO);
1938
1939         if (sc->mode.level < PSM_LEVEL_NATIVE)
1940                 return (ENODEV);
1941
1942         /* copy data from the user land */
1943         while (uio->uio_resid > 0) {
1944                 l = imin(PSM_SMALLBUFSIZE, uio->uio_resid);
1945                 error = uiomove(buf, l, uio);
1946                 if (error)
1947                         break;
1948                 for (i = 0; i < l; i++) {
1949                         VLOG(4, (LOG_DEBUG, "psm: cmd 0x%x\n", buf[i]));
1950                         if (!write_aux_command(sc->kbdc, buf[i])) {
1951                                 VLOG(2, (LOG_DEBUG,
1952                                     "psm: cmd 0x%x failed.\n", buf[i]));
1953                                 return (reinitialize(sc, FALSE));
1954                         }
1955                 }
1956         }
1957
1958         return (error);
1959 }
1960
1961 static int
1962 psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
1963     struct thread *td)
1964 {
1965         struct psm_softc *sc = dev->si_drv1;
1966         mousemode_t mode;
1967         mousestatus_t status;
1968 #if (defined(MOUSE_GETVARS))
1969         mousevar_t *var;
1970 #endif
1971         mousedata_t *data;
1972         int stat[3];
1973         int command_byte;
1974         int error = 0;
1975         int s;
1976
1977         /* Perform IOCTL command */
1978         switch (cmd) {
1979
1980         case OLD_MOUSE_GETHWINFO:
1981                 s = spltty();
1982                 ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1983                 ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1984                 ((old_mousehw_t *)addr)->type = sc->hw.type;
1985                 ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
1986                 splx(s);
1987                 break;
1988
1989         case MOUSE_GETHWINFO:
1990                 s = spltty();
1991                 *(mousehw_t *)addr = sc->hw;
1992                 if (sc->mode.level == PSM_LEVEL_BASE)
1993                         ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1994                 splx(s);
1995                 break;
1996
1997         case MOUSE_SYN_GETHWINFO:
1998                 s = spltty();
1999                 if (sc->synhw.infoMajor >= 4)
2000                         *(synapticshw_t *)addr = sc->synhw;
2001                 else
2002                         error = EINVAL;
2003                 splx(s);
2004                 break;
2005
2006         case OLD_MOUSE_GETMODE:
2007                 s = spltty();
2008                 switch (sc->mode.level) {
2009                 case PSM_LEVEL_BASE:
2010                         ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2011                         break;
2012                 case PSM_LEVEL_STANDARD:
2013                         ((old_mousemode_t *)addr)->protocol =
2014                             MOUSE_PROTO_SYSMOUSE;
2015                         break;
2016                 case PSM_LEVEL_NATIVE:
2017                         ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2018                         break;
2019                 }
2020                 ((old_mousemode_t *)addr)->rate = sc->mode.rate;
2021                 ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
2022                 ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
2023                 splx(s);
2024                 break;
2025
2026         case MOUSE_GETMODE:
2027                 s = spltty();
2028                 *(mousemode_t *)addr = sc->mode;
2029                 if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2030                         ((mousemode_t *)addr)->syncmask[0] = 0;
2031                         ((mousemode_t *)addr)->syncmask[1] = 0;
2032                 }
2033                 ((mousemode_t *)addr)->resolution =
2034                         MOUSE_RES_LOW - sc->mode.resolution;
2035                 switch (sc->mode.level) {
2036                 case PSM_LEVEL_BASE:
2037                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2038                         ((mousemode_t *)addr)->packetsize =
2039                             MOUSE_PS2_PACKETSIZE;
2040                         break;
2041                 case PSM_LEVEL_STANDARD:
2042                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
2043                         ((mousemode_t *)addr)->packetsize =
2044                             MOUSE_SYS_PACKETSIZE;
2045                         ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
2046                         ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
2047                         break;
2048                 case PSM_LEVEL_NATIVE:
2049                         /* FIXME: this isn't quite correct... XXX */
2050                         ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
2051                         break;
2052                 }
2053                 splx(s);
2054                 break;
2055
2056         case OLD_MOUSE_SETMODE:
2057         case MOUSE_SETMODE:
2058                 if (cmd == OLD_MOUSE_SETMODE) {
2059                         mode.rate = ((old_mousemode_t *)addr)->rate;
2060                         /*
2061                          * resolution  old I/F   new I/F
2062                          * default        0         0
2063                          * low            1        -2
2064                          * medium low     2        -3
2065                          * medium high    3        -4
2066                          * high           4        -5
2067                          */
2068                         if (((old_mousemode_t *)addr)->resolution > 0)
2069                                 mode.resolution =
2070                                     -((old_mousemode_t *)addr)->resolution - 1;
2071                         else
2072                                 mode.resolution = 0;
2073                         mode.accelfactor =
2074                             ((old_mousemode_t *)addr)->accelfactor;
2075                         mode.level = -1;
2076                 } else
2077                         mode = *(mousemode_t *)addr;
2078
2079                 /* adjust and validate parameters. */
2080                 if (mode.rate > UCHAR_MAX)
2081                         return (EINVAL);
2082                 if (mode.rate == 0)
2083                         mode.rate = sc->dflt_mode.rate;
2084                 else if (mode.rate == -1)
2085                         /* don't change the current setting */
2086                         ;
2087                 else if (mode.rate < 0)
2088                         return (EINVAL);
2089                 if (mode.resolution >= UCHAR_MAX)
2090                         return (EINVAL);
2091                 if (mode.resolution >= 200)
2092                         mode.resolution = MOUSE_RES_HIGH;
2093                 else if (mode.resolution >= 100)
2094                         mode.resolution = MOUSE_RES_MEDIUMHIGH;
2095                 else if (mode.resolution >= 50)
2096                         mode.resolution = MOUSE_RES_MEDIUMLOW;
2097                 else if (mode.resolution > 0)
2098                         mode.resolution = MOUSE_RES_LOW;
2099                 if (mode.resolution == MOUSE_RES_DEFAULT)
2100                         mode.resolution = sc->dflt_mode.resolution;
2101                 else if (mode.resolution == -1)
2102                         /* don't change the current setting */
2103                         ;
2104                 else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2105                         mode.resolution = MOUSE_RES_LOW - mode.resolution;
2106                 if (mode.level == -1)
2107                         /* don't change the current setting */
2108                         mode.level = sc->mode.level;
2109                 else if ((mode.level < PSM_LEVEL_MIN) ||
2110                     (mode.level > PSM_LEVEL_MAX))
2111                         return (EINVAL);
2112                 if (mode.accelfactor == -1)
2113                         /* don't change the current setting */
2114                         mode.accelfactor = sc->mode.accelfactor;
2115                 else if (mode.accelfactor < 0)
2116                         return (EINVAL);
2117
2118                 /* don't allow anybody to poll the keyboard controller */
2119                 error = block_mouse_data(sc, &command_byte);
2120                 if (error)
2121                         return (error);
2122
2123                 /* set mouse parameters */
2124                 if (mode.rate > 0)
2125                         mode.rate = set_mouse_sampling_rate(sc->kbdc,
2126                             mode.rate);
2127                 if (mode.resolution >= 0)
2128                         mode.resolution =
2129                             set_mouse_resolution(sc->kbdc, mode.resolution);
2130                 set_mouse_scaling(sc->kbdc, 1);
2131                 get_mouse_status(sc->kbdc, stat, 0, 3);
2132
2133                 s = spltty();
2134                 sc->mode.rate = mode.rate;
2135                 sc->mode.resolution = mode.resolution;
2136                 sc->mode.accelfactor = mode.accelfactor;
2137                 sc->mode.level = mode.level;
2138                 splx(s);
2139
2140                 unblock_mouse_data(sc, command_byte);
2141                 break;
2142
2143         case MOUSE_GETLEVEL:
2144                 *(int *)addr = sc->mode.level;
2145                 break;
2146
2147         case MOUSE_SETLEVEL:
2148                 if ((*(int *)addr < PSM_LEVEL_MIN) ||
2149                     (*(int *)addr > PSM_LEVEL_MAX))
2150                         return (EINVAL);
2151                 sc->mode.level = *(int *)addr;
2152                 break;
2153
2154         case MOUSE_GETSTATUS:
2155                 s = spltty();
2156                 status = sc->status;
2157                 sc->status.flags = 0;
2158                 sc->status.obutton = sc->status.button;
2159                 sc->status.button = 0;
2160                 sc->status.dx = 0;
2161                 sc->status.dy = 0;
2162                 sc->status.dz = 0;
2163                 splx(s);
2164                 *(mousestatus_t *)addr = status;
2165                 break;
2166
2167 #if (defined(MOUSE_GETVARS))
2168         case MOUSE_GETVARS:
2169                 var = (mousevar_t *)addr;
2170                 bzero(var, sizeof(*var));
2171                 s = spltty();
2172                 var->var[0] = MOUSE_VARS_PS2_SIG;
2173                 var->var[1] = sc->config;
2174                 var->var[2] = sc->flags;
2175                 splx(s);
2176                 break;
2177
2178         case MOUSE_SETVARS:
2179                 return (ENODEV);
2180 #endif /* MOUSE_GETVARS */
2181
2182         case MOUSE_READSTATE:
2183         case MOUSE_READDATA:
2184                 data = (mousedata_t *)addr;
2185                 if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
2186                         return (EINVAL);
2187
2188                 error = block_mouse_data(sc, &command_byte);
2189                 if (error)
2190                         return (error);
2191                 if ((data->len = get_mouse_status(sc->kbdc, data->buf,
2192                     (cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
2193                         error = EIO;
2194                 unblock_mouse_data(sc, command_byte);
2195                 break;
2196
2197 #if (defined(MOUSE_SETRESOLUTION))
2198         case MOUSE_SETRESOLUTION:
2199                 mode.resolution = *(int *)addr;
2200                 if (mode.resolution >= UCHAR_MAX)
2201                         return (EINVAL);
2202                 else if (mode.resolution >= 200)
2203                         mode.resolution = MOUSE_RES_HIGH;
2204                 else if (mode.resolution >= 100)
2205                         mode.resolution = MOUSE_RES_MEDIUMHIGH;
2206                 else if (mode.resolution >= 50)
2207                         mode.resolution = MOUSE_RES_MEDIUMLOW;
2208                 else if (mode.resolution > 0)
2209                         mode.resolution = MOUSE_RES_LOW;
2210                 if (mode.resolution == MOUSE_RES_DEFAULT)
2211                         mode.resolution = sc->dflt_mode.resolution;
2212                 else if (mode.resolution == -1)
2213                         mode.resolution = sc->mode.resolution;
2214                 else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
2215                         mode.resolution = MOUSE_RES_LOW - mode.resolution;
2216
2217                 error = block_mouse_data(sc, &command_byte);
2218                 if (error)
2219                         return (error);
2220                 sc->mode.resolution =
2221                     set_mouse_resolution(sc->kbdc, mode.resolution);
2222                 if (sc->mode.resolution != mode.resolution)
2223                         error = EIO;
2224                 unblock_mouse_data(sc, command_byte);
2225                 break;
2226 #endif /* MOUSE_SETRESOLUTION */
2227
2228 #if (defined(MOUSE_SETRATE))
2229         case MOUSE_SETRATE:
2230                 mode.rate = *(int *)addr;
2231                 if (mode.rate > UCHAR_MAX)
2232                         return (EINVAL);
2233                 if (mode.rate == 0)
2234                         mode.rate = sc->dflt_mode.rate;
2235                 else if (mode.rate < 0)
2236                         mode.rate = sc->mode.rate;
2237
2238                 error = block_mouse_data(sc, &command_byte);
2239                 if (error)
2240                         return (error);
2241                 sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
2242                 if (sc->mode.rate != mode.rate)
2243                         error = EIO;
2244                 unblock_mouse_data(sc, command_byte);
2245                 break;
2246 #endif /* MOUSE_SETRATE */
2247
2248 #if (defined(MOUSE_SETSCALING))
2249         case MOUSE_SETSCALING:
2250                 if ((*(int *)addr <= 0) || (*(int *)addr > 2))
2251                         return (EINVAL);
2252
2253                 error = block_mouse_data(sc, &command_byte);
2254                 if (error)
2255                         return (error);
2256                 if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
2257                         error = EIO;
2258                 unblock_mouse_data(sc, command_byte);
2259                 break;
2260 #endif /* MOUSE_SETSCALING */
2261
2262 #if (defined(MOUSE_GETHWID))
2263         case MOUSE_GETHWID:
2264                 error = block_mouse_data(sc, &command_byte);
2265                 if (error)
2266                         return (error);
2267                 sc->hw.hwid &= ~0x00ff;
2268                 sc->hw.hwid |= get_aux_id(sc->kbdc);
2269                 *(int *)addr = sc->hw.hwid & 0x00ff;
2270                 unblock_mouse_data(sc, command_byte);
2271                 break;
2272 #endif /* MOUSE_GETHWID */
2273
2274         case FIONBIO:
2275         case FIOASYNC:
2276                 break;
2277         case FIOSETOWN:
2278                 error = fsetown(*(int *)addr, &sc->async);
2279                 break;
2280         case FIOGETOWN:
2281                 *(int *) addr = fgetown(&sc->async);
2282                 break;
2283         default:
2284                 return (ENOTTY);
2285         }
2286
2287         return (error);
2288 }
2289
2290 static void
2291 psmtimeout(void *arg)
2292 {
2293         struct psm_softc *sc;
2294         int s;
2295
2296         sc = (struct psm_softc *)arg;
2297         s = spltty();
2298         if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
2299                 VLOG(4, (LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit));
2300                 psmintr(sc);
2301                 kbdc_lock(sc->kbdc, FALSE);
2302         }
2303         sc->watchdog = TRUE;
2304         splx(s);
2305         sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz);
2306 }
2307
2308 /* Add all sysctls under the debug.psm and hw.psm nodes */
2309 static SYSCTL_NODE(_debug, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2310 static SYSCTL_NODE(_hw, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2311
2312 SYSCTL_INT(_debug_psm, OID_AUTO, loglevel, CTLFLAG_RW, &verbose, 0,
2313     "Verbosity level");
2314
2315 static int psmhz = 20;
2316 SYSCTL_INT(_debug_psm, OID_AUTO, hz, CTLFLAG_RW, &psmhz, 0,
2317     "Frequency of the softcallout (in hz)");
2318 static int psmerrsecs = 2;
2319 SYSCTL_INT(_debug_psm, OID_AUTO, errsecs, CTLFLAG_RW, &psmerrsecs, 0,
2320     "Number of seconds during which packets will dropped after a sync error");
2321 static int psmerrusecs = 0;
2322 SYSCTL_INT(_debug_psm, OID_AUTO, errusecs, CTLFLAG_RW, &psmerrusecs, 0,
2323     "Microseconds to add to psmerrsecs");
2324 static int psmsecs = 0;
2325 SYSCTL_INT(_debug_psm, OID_AUTO, secs, CTLFLAG_RW, &psmsecs, 0,
2326     "Max number of seconds between soft interrupts");
2327 static int psmusecs = 500000;
2328 SYSCTL_INT(_debug_psm, OID_AUTO, usecs, CTLFLAG_RW, &psmusecs, 0,
2329     "Microseconds to add to psmsecs");
2330 static int pkterrthresh = 2;
2331 SYSCTL_INT(_debug_psm, OID_AUTO, pkterrthresh, CTLFLAG_RW, &pkterrthresh, 0,
2332     "Number of error packets allowed before reinitializing the mouse");
2333
2334 SYSCTL_INT(_hw_psm, OID_AUTO, tap_enabled, CTLFLAG_RW, &tap_enabled, 0,
2335     "Enable tap and drag gestures");
2336 static int tap_threshold = PSM_TAP_THRESHOLD;
2337 SYSCTL_INT(_hw_psm, OID_AUTO, tap_threshold, CTLFLAG_RW, &tap_threshold, 0,
2338     "Button tap threshold");
2339 static int tap_timeout = PSM_TAP_TIMEOUT;
2340 SYSCTL_INT(_hw_psm, OID_AUTO, tap_timeout, CTLFLAG_RW, &tap_timeout, 0,
2341     "Tap timeout for touchpads");
2342
2343 static void
2344 psmintr(void *arg)
2345 {
2346         struct psm_softc *sc = arg;
2347         struct timeval now;
2348         int c;
2349         packetbuf_t *pb;
2350
2351
2352         /* read until there is nothing to read */
2353         while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
2354                 pb = &sc->pqueue[sc->pqueue_end];
2355
2356                 /* discard the byte if the device is not open */
2357                 if ((sc->state & PSM_OPEN) == 0)
2358                         continue;
2359
2360                 getmicrouptime(&now);
2361                 if ((pb->inputbytes > 0) &&
2362                     timevalcmp(&now, &sc->inputtimeout, >)) {
2363                         VLOG(3, (LOG_DEBUG, "psmintr: delay too long; "
2364                             "resetting byte count\n"));
2365                         pb->inputbytes = 0;
2366                         sc->syncerrors = 0;
2367                         sc->pkterrors = 0;
2368                 }
2369                 sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT / 1000000;
2370                 sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT % 1000000;
2371                 timevaladd(&sc->inputtimeout, &now);
2372
2373                 pb->ipacket[pb->inputbytes++] = c;
2374
2375                 if (sc->mode.level == PSM_LEVEL_NATIVE) {
2376                         VLOG(4, (LOG_DEBUG, "psmintr: %02x\n", pb->ipacket[0]));
2377                         sc->syncerrors = 0;
2378                         sc->pkterrors = 0;
2379                         goto next;
2380                 } else {
2381                         if (pb->inputbytes < sc->mode.packetsize)
2382                                 continue;
2383
2384                         VLOG(4, (LOG_DEBUG,
2385                             "psmintr: %02x %02x %02x %02x %02x %02x\n",
2386                             pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
2387                             pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
2388                 }
2389
2390                 c = pb->ipacket[0];
2391
2392                 if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2393                         sc->mode.syncmask[1] = (c & sc->mode.syncmask[0]);
2394                         sc->flags &= ~PSM_NEED_SYNCBITS;
2395                         VLOG(2, (LOG_DEBUG,
2396                             "psmintr: Sync bytes now %04x,%04x\n",
2397                             sc->mode.syncmask[0], sc->mode.syncmask[0]));
2398                 } else if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
2399                         VLOG(3, (LOG_DEBUG, "psmintr: out of sync "
2400                             "(%04x != %04x) %d cmds since last error.\n",
2401                             c & sc->mode.syncmask[0], sc->mode.syncmask[1],
2402                             sc->cmdcount - sc->lasterr));
2403                         sc->lasterr = sc->cmdcount;
2404                         /*
2405                          * The sync byte test is a weak measure of packet
2406                          * validity.  Conservatively discard any input yet
2407                          * to be seen by userland when we detect a sync
2408                          * error since there is a good chance some of
2409                          * the queued packets have undetected errors.
2410                          */
2411                         dropqueue(sc);
2412                         if (sc->syncerrors == 0)
2413                                 sc->pkterrors++;
2414                         ++sc->syncerrors;
2415                         sc->lastinputerr = now;
2416                         if (sc->syncerrors >= sc->mode.packetsize * 2 ||
2417                             sc->pkterrors >= pkterrthresh) {
2418                                 /*
2419                                  * If we've failed to find a single sync byte
2420                                  * in 2 packets worth of data, or we've seen
2421                                  * persistent packet errors during the
2422                                  * validation period, reinitialize the mouse
2423                                  * in hopes of returning it to the expected
2424                                  * mode.
2425                                  */
2426                                 VLOG(3, (LOG_DEBUG,
2427                                     "psmintr: reset the mouse.\n"));
2428                                 reinitialize(sc, TRUE);
2429                         } else if (sc->syncerrors == sc->mode.packetsize) {
2430                                 /*
2431                                  * Try a soft reset after searching for a sync
2432                                  * byte through a packet length of bytes.
2433                                  */
2434                                 VLOG(3, (LOG_DEBUG,
2435                                     "psmintr: re-enable the mouse.\n"));
2436                                 pb->inputbytes = 0;
2437                                 disable_aux_dev(sc->kbdc);
2438                                 enable_aux_dev(sc->kbdc);
2439                         } else {
2440                                 VLOG(3, (LOG_DEBUG,
2441                                     "psmintr: discard a byte (%d)\n",
2442                                     sc->syncerrors));
2443                                 pb->inputbytes--;
2444                                 bcopy(&pb->ipacket[1], &pb->ipacket[0],
2445                                     pb->inputbytes);
2446                         }
2447                         continue;
2448                 }
2449
2450                 /*
2451                  * We have what appears to be a valid packet.
2452                  * Reset the error counters.
2453                  */
2454                 sc->syncerrors = 0;
2455
2456                 /*
2457                  * Drop even good packets if they occur within a timeout
2458                  * period of a sync error.  This allows the detection of
2459                  * a change in the mouse's packet mode without exposing
2460                  * erratic mouse behavior to the user.  Some KVMs forget
2461                  * enhanced mouse modes during switch events.
2462                  */
2463                 if (!timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs,
2464                     &now)) {
2465                         pb->inputbytes = 0;
2466                         continue;
2467                 }
2468
2469                 /*
2470                  * Now that we're out of the validation period, reset
2471                  * the packet error count.
2472                  */
2473                 sc->pkterrors = 0;
2474
2475                 sc->cmdcount++;
2476 next:
2477                 if (++sc->pqueue_end >= PSM_PACKETQUEUE)
2478                         sc->pqueue_end = 0;
2479                 /*
2480                  * If we've filled the queue then call the softintr ourselves,
2481                  * otherwise schedule the interrupt for later.
2482                  */
2483                 if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
2484                     (sc->pqueue_end == sc->pqueue_start)) {
2485                         if ((sc->state & PSM_SOFTARMED) != 0) {
2486                                 sc->state &= ~PSM_SOFTARMED;
2487                                 untimeout(psmsoftintr, arg, sc->softcallout);
2488                         }
2489                         psmsoftintr(arg);
2490                 } else if ((sc->state & PSM_SOFTARMED) == 0) {
2491                         sc->state |= PSM_SOFTARMED;
2492                         sc->softcallout = timeout(psmsoftintr, arg,
2493                             psmhz < 1 ? 1 : (hz/psmhz));
2494                 }
2495         }
2496 }
2497
2498 static void
2499 proc_mmanplus(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
2500     int *x, int *y, int *z)
2501 {
2502
2503         /*
2504          * PS2++ protocol packet
2505          *
2506          *          b7 b6 b5 b4 b3 b2 b1 b0
2507          * byte 1:  *  1  p3 p2 1  *  *  *
2508          * byte 2:  c1 c2 p1 p0 d1 d0 1  0
2509          *
2510          * p3-p0: packet type
2511          * c1, c2: c1 & c2 == 1, if p2 == 0
2512          *         c1 & c2 == 0, if p2 == 1
2513          *
2514          * packet type: 0 (device type)
2515          * See comments in enable_mmanplus() below.
2516          *
2517          * packet type: 1 (wheel data)
2518          *
2519          *          b7 b6 b5 b4 b3 b2 b1 b0
2520          * byte 3:  h  *  B5 B4 s  d2 d1 d0
2521          *
2522          * h: 1, if horizontal roller data
2523          *    0, if vertical roller data
2524          * B4, B5: button 4 and 5
2525          * s: sign bit
2526          * d2-d0: roller data
2527          *
2528          * packet type: 2 (reserved)
2529          */
2530         if (((pb->ipacket[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC) &&
2531             (abs(*x) > 191) && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
2532                 /*
2533                  * the extended data packet encodes button
2534                  * and wheel events
2535                  */
2536                 switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
2537                 case 1:
2538                         /* wheel data packet */
2539                         *x = *y = 0;
2540                         if (pb->ipacket[2] & 0x80) {
2541                                 /* XXX horizontal roller count - ignore it */
2542                                 ;
2543                         } else {
2544                                 /* vertical roller count */
2545                                 *z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG) ?
2546                                     (pb->ipacket[2] & 0x0f) - 16 :
2547                                     (pb->ipacket[2] & 0x0f);
2548                         }
2549                         ms->button |= (pb->ipacket[2] &
2550                             MOUSE_PS2PLUS_BUTTON4DOWN) ?
2551                             MOUSE_BUTTON4DOWN : 0;
2552                         ms->button |= (pb->ipacket[2] &
2553                             MOUSE_PS2PLUS_BUTTON5DOWN) ?
2554                             MOUSE_BUTTON5DOWN : 0;
2555                         break;
2556                 case 2:
2557                         /*
2558                          * this packet type is reserved by
2559                          * Logitech...
2560                          */
2561                         /*
2562                          * IBM ScrollPoint Mouse uses this
2563                          * packet type to encode both vertical
2564                          * and horizontal scroll movement.
2565                          */
2566                         *x = *y = 0;
2567                         /* horizontal count */
2568                         if (pb->ipacket[2] & 0x0f)
2569                                 *z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ?
2570                                     -2 : 2;
2571                         /* vertical count */
2572                         if (pb->ipacket[2] & 0xf0)
2573                                 *z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ?
2574                                     -1 : 1;
2575                         break;
2576                 case 0:
2577                         /* device type packet - shouldn't happen */
2578                         /* FALLTHROUGH */
2579                 default:
2580                         *x = *y = 0;
2581                         ms->button = ms->obutton;
2582                         VLOG(1, (LOG_DEBUG, "psmintr: unknown PS2++ packet "
2583                             "type %d: 0x%02x 0x%02x 0x%02x\n",
2584                             MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
2585                             pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]));
2586                         break;
2587                 }
2588         } else {
2589                 /* preserve button states */
2590                 ms->button |= ms->obutton & MOUSE_EXTBUTTONS;
2591         }
2592 }
2593
2594 static int
2595 proc_synaptics(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
2596     int *x, int *y, int *z)
2597 {
2598         static int touchpad_buttons;
2599         static int guest_buttons;
2600         int w, x0, y0;
2601
2602         /* TouchPad PS/2 absolute mode message format
2603          *
2604          *  Bits:        7   6   5   4   3   2   1   0 (LSB)
2605          *  ------------------------------------------------
2606          *  ipacket[0]:  1   0  W3  W2   0  W1   R   L
2607          *  ipacket[1]: Yb  Ya  Y9  Y8  Xb  Xa  X9  X8
2608          *  ipacket[2]: Z7  Z6  Z5  Z4  Z3  Z2  Z1  Z0
2609          *  ipacket[3]:  1   1  Yc  Xc   0  W0   D   U
2610          *  ipacket[4]: X7  X6  X5  X4  X3  X2  X1  X0
2611          *  ipacket[5]: Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
2612          *
2613          * Legend:
2614          *  L: left physical mouse button
2615          *  R: right physical mouse button
2616          *  D: down button
2617          *  U: up button
2618          *  W: "wrist" value
2619          *  X: x position
2620          *  Y: y position
2621          *  Z: pressure
2622          *
2623          * Absolute reportable limits:    0 - 6143.
2624          * Typical bezel limits:       1472 - 5472.
2625          * Typical edge marings:       1632 - 5312.
2626          *
2627          * w = 3 Passthrough Packet
2628          *
2629          * Byte 2,5,6 == Byte 1,2,3 of "Guest"
2630          */
2631
2632         if (!synaptics_support)
2633                 return (0);
2634
2635         /* Sanity check for out of sync packets. */
2636         if ((pb->ipacket[0] & 0xc8) != 0x80 ||
2637             (pb->ipacket[3] & 0xc8) != 0xc0)
2638                 return (-1);
2639
2640         *x = *y = 0;
2641
2642         /*
2643          * Pressure value.
2644          * Interpretation:
2645          *   z = 0      No finger contact
2646          *   z = 10     Finger hovering near the pad
2647          *   z = 30     Very light finger contact
2648          *   z = 80     Normal finger contact
2649          *   z = 110    Very heavy finger contact
2650          *   z = 200    Finger lying flat on pad surface
2651          *   z = 255    Maximum reportable Z
2652          */
2653         *z = pb->ipacket[2];
2654
2655         /*
2656          * Finger width value
2657          * Interpretation:
2658          *   w = 0      Two finger on the pad (capMultiFinger needed)
2659          *   w = 1      Three or more fingers (capMultiFinger needed)
2660          *   w = 2      Pen (instead of finger) (capPen needed)
2661          *   w = 3      Reserved (passthrough?)
2662          *   w = 4-7    Finger of normal width (capPalmDetect needed)
2663          *   w = 8-14   Very wide finger or palm (capPalmDetect needed)
2664          *   w = 15     Maximum reportable width (capPalmDetect needed)
2665          */
2666         /* XXX Is checking capExtended enough? */
2667         if (sc->synhw.capExtended)
2668                 w = ((pb->ipacket[0] & 0x30) >> 2) |
2669                     ((pb->ipacket[0] & 0x04) >> 1) |
2670                     ((pb->ipacket[3] & 0x04) >> 2);
2671         else {
2672                 /* Assume a finger of regular width. */
2673                 w = 4;
2674         }
2675
2676         /* Handle packets from the guest device */
2677         /* XXX Documentation? */
2678         if (w == 3 && sc->synhw.capPassthrough) {
2679                 *x = ((pb->ipacket[1] & 0x10) ?
2680                     pb->ipacket[4] - 256 : pb->ipacket[4]);
2681                 *y = ((pb->ipacket[1] & 0x20) ?
2682                     pb->ipacket[5] - 256 : pb->ipacket[5]);
2683                 *z = 0;
2684
2685                 guest_buttons = 0;
2686                 if (pb->ipacket[1] & 0x01)
2687                         guest_buttons |= MOUSE_BUTTON1DOWN;
2688                 if (pb->ipacket[1] & 0x04)
2689                         guest_buttons |= MOUSE_BUTTON2DOWN;
2690                 if (pb->ipacket[1] & 0x02)
2691                         guest_buttons |= MOUSE_BUTTON3DOWN;
2692
2693                 ms->button = touchpad_buttons | guest_buttons;
2694                 goto SYNAPTICS_END;
2695         }
2696
2697         /* Button presses */
2698         touchpad_buttons = 0;
2699         if (pb->ipacket[0] & 0x01)
2700                 touchpad_buttons |= MOUSE_BUTTON1DOWN;
2701         if (pb->ipacket[0] & 0x02)
2702                 touchpad_buttons |= MOUSE_BUTTON3DOWN;
2703
2704         if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
2705                 if ((pb->ipacket[3] & 0x01) && (pb->ipacket[0] & 0x01) == 0)
2706                         touchpad_buttons |= MOUSE_BUTTON4DOWN;
2707                 if ((pb->ipacket[3] & 0x02) && (pb->ipacket[0] & 0x02) == 0)
2708                         touchpad_buttons |= MOUSE_BUTTON5DOWN;
2709         }
2710
2711         /*
2712          * In newer pads - bit 0x02 in the third byte of
2713          * the packet indicates that we have an extended
2714          * button press.
2715          */
2716         /* XXX Documentation? */
2717         if (pb->ipacket[3] & 0x02) {
2718                 /*
2719                  * if directional_scrolls is not 1, we treat any of
2720                  * the scrolling directions as middle-click.
2721                  */
2722                 if (sc->syninfo.directional_scrolls) {
2723                         if (pb->ipacket[4] & 0x01)
2724                                 touchpad_buttons |= MOUSE_BUTTON4DOWN;
2725                         if (pb->ipacket[5] & 0x01)
2726                                 touchpad_buttons |= MOUSE_BUTTON5DOWN;
2727                         if (pb->ipacket[4] & 0x02)
2728                                 touchpad_buttons |= MOUSE_BUTTON6DOWN;
2729                         if (pb->ipacket[5] & 0x02)
2730                                 touchpad_buttons |= MOUSE_BUTTON7DOWN;
2731                 } else {
2732                         if ((pb->ipacket[4] & 0x0F) ||
2733                             (pb->ipacket[5] & 0x0F))
2734                                 touchpad_buttons |= MOUSE_BUTTON2DOWN;
2735                 }
2736         }
2737
2738         ms->button = touchpad_buttons | guest_buttons;
2739
2740         /* Check pressure to detect a real wanted action on the
2741          * touchpad. */
2742         if (*z >= sc->syninfo.min_pressure) {
2743                 synapticsaction_t *synaction;
2744                 int cursor, peer, window;
2745                 int dx, dy, dxp, dyp;
2746                 int max_width, max_pressure;
2747                 int margin_top, margin_right, margin_bottom, margin_left;
2748                 int na_top, na_right, na_bottom, na_left;
2749                 int window_min, window_max;
2750                 int multiplicator;
2751                 int weight_current, weight_previous, weight_len_squared;
2752                 int div_min, div_max, div_len;
2753                 int vscroll_hor_area, vscroll_ver_area;
2754
2755                 int len, weight_prev_x, weight_prev_y;
2756                 int div_max_x, div_max_y, div_x, div_y;
2757
2758                 /* Read sysctl. */
2759                 /* XXX Verify values? */
2760                 max_width = sc->syninfo.max_width;
2761                 max_pressure = sc->syninfo.max_pressure;
2762                 margin_top = sc->syninfo.margin_top;
2763                 margin_right = sc->syninfo.margin_right;
2764                 margin_bottom = sc->syninfo.margin_bottom;
2765                 margin_left = sc->syninfo.margin_left;
2766                 na_top = sc->syninfo.na_top;
2767                 na_right = sc->syninfo.na_right;
2768                 na_bottom = sc->syninfo.na_bottom;
2769                 na_left = sc->syninfo.na_left;
2770                 window_min = sc->syninfo.window_min;
2771                 window_max = sc->syninfo.window_max;
2772                 multiplicator = sc->syninfo.multiplicator;
2773                 weight_current = sc->syninfo.weight_current;
2774                 weight_previous = sc->syninfo.weight_previous;
2775                 weight_len_squared = sc->syninfo.weight_len_squared;
2776                 div_min = sc->syninfo.div_min;
2777                 div_max = sc->syninfo.div_max;
2778                 div_len = sc->syninfo.div_len;
2779                 vscroll_hor_area = sc->syninfo.vscroll_hor_area;
2780                 vscroll_ver_area = sc->syninfo.vscroll_ver_area;
2781
2782                 /* Palm detection. */
2783                 if (!(
2784                     (sc->synhw.capMultiFinger && (w == 0 || w == 1)) ||
2785                     (sc->synhw.capPalmDetect && w >= 4 && w <= max_width) ||
2786                     (!sc->synhw.capPalmDetect && *z <= max_pressure) ||
2787                     (sc->synhw.capPen && w == 2))) {
2788                         /*
2789                          * We consider the packet irrelevant for the current
2790                          * action when:
2791                          *  - the width isn't comprised in:
2792                          *    [4; max_width]
2793                          *  - the pressure isn't comprised in:
2794                          *    [min_pressure; max_pressure]
2795                          *  - pen aren't supported but w is 2
2796                          *
2797                          *  Note that this doesn't terminate the current action.
2798                          */
2799                         VLOG(2, (LOG_DEBUG,
2800                             "synaptics: palm detected! (%d)\n", w));
2801                         goto SYNAPTICS_END;
2802                 }
2803
2804                 /* Read current absolute position. */
2805                 x0 = ((pb->ipacket[3] & 0x10) << 8) |
2806                     ((pb->ipacket[1] & 0x0f) << 8) |
2807                     pb->ipacket[4];
2808                 y0 = ((pb->ipacket[3] & 0x20) << 7) |
2809                     ((pb->ipacket[1] & 0xf0) << 4) |
2810                     pb->ipacket[5];
2811
2812                 synaction = &(sc->synaction);
2813
2814                 /*
2815                  * If the action is just beginning, init the structure and
2816                  * compute tap timeout.
2817                  */
2818                 if (!(sc->flags & PSM_FLAGS_FINGERDOWN)) {
2819                         VLOG(3, (LOG_DEBUG, "synaptics: ----\n"));
2820
2821                         /* Store the first point of this action. */
2822                         synaction->start_x = x0;
2823                         synaction->start_y = y0;
2824                         dx = dy = 0;
2825
2826                         /* Initialize queue. */
2827                         synaction->queue_cursor = SYNAPTICS_PACKETQUEUE;
2828                         synaction->queue_len = 0;
2829                         synaction->window_min = window_min;
2830
2831                         /* Reset average. */
2832                         synaction->avg_dx = 0;
2833                         synaction->avg_dy = 0;
2834
2835                         /* Reset squelch. */
2836                         synaction->squelch_x = 0;
2837                         synaction->squelch_y = 0;
2838
2839                         /* Reset pressure peak. */
2840                         sc->zmax = 0;
2841
2842                         /* Reset fingers count. */
2843                         synaction->fingers_nb = 0;
2844
2845                         /* Reset virtual scrolling state. */
2846                         synaction->in_vscroll = 0;
2847
2848                         /* Compute tap timeout. */
2849                         sc->taptimeout.tv_sec  = tap_timeout / 1000000;
2850                         sc->taptimeout.tv_usec = tap_timeout % 1000000;
2851                         timevaladd(&sc->taptimeout, &sc->lastsoftintr);
2852
2853                         sc->flags |= PSM_FLAGS_FINGERDOWN;
2854                 } else {
2855                         /* Calculate the current delta. */
2856                         cursor = synaction->queue_cursor;
2857                         dx = x0 - synaction->queue[cursor].x;
2858                         dy = y0 - synaction->queue[cursor].y;
2859                 }
2860
2861                 /* If in tap-hold, add the recorded button. */
2862                 if (synaction->in_taphold)
2863                         ms->button |= synaction->tap_button;
2864
2865                 /*
2866                  * From now on, we can use the SYNAPTICS_END label to skip
2867                  * the current packet.
2868                  */
2869
2870                 /*
2871                  * Limit the coordinates to the specified margins because
2872                  * this area isn't very reliable.
2873                  */
2874                 if (x0 <= margin_left)
2875                         x0 = margin_left;
2876                 else if (x0 >= 6143 - margin_right)
2877                         x0 = 6143 - margin_right;
2878                 if (y0 <= margin_bottom)
2879                         y0 = margin_bottom;
2880                 else if (y0 >= 6143 - margin_top)
2881                         y0 = 6143 - margin_top;
2882
2883                 VLOG(3, (LOG_DEBUG, "synaptics: ipacket: [%d, %d], %d, %d\n",
2884                     x0, y0, *z, w));
2885
2886                 /* Queue this new packet. */
2887                 cursor = SYNAPTICS_QUEUE_CURSOR(synaction->queue_cursor - 1);
2888                 synaction->queue[cursor].x = x0;
2889                 synaction->queue[cursor].y = y0;
2890                 synaction->queue_cursor = cursor;
2891                 if (synaction->queue_len < SYNAPTICS_PACKETQUEUE)
2892                         synaction->queue_len++;
2893                 VLOG(5, (LOG_DEBUG,
2894                     "synaptics: cursor[%d]: x=%d, y=%d, dx=%d, dy=%d\n",
2895                     cursor, x0, y0, dx, dy));
2896
2897                 /*
2898                  * For tap, we keep the maximum number of fingers and the
2899                  * pressure peak. Also with multiple fingers, we increase
2900                  * the minimum window.
2901                  */
2902                 switch (w) {
2903                 case 1: /* Three or more fingers. */
2904                         synaction->fingers_nb = imax(3, synaction->fingers_nb);
2905                         synaction->window_min = window_max;
2906                         break;
2907                 case 0: /* Two fingers. */
2908                         synaction->fingers_nb = imax(2, synaction->fingers_nb);
2909                         synaction->window_min = window_max;
2910                         break;
2911                 default: /* One finger or undetectable. */
2912                         synaction->fingers_nb = imax(1, synaction->fingers_nb);
2913                 }
2914                 sc->zmax = imax(*z, sc->zmax);
2915
2916                 /* Do we have enough packets to consider this a movement? */
2917                 if (synaction->queue_len < synaction->window_min)
2918                         goto SYNAPTICS_END;
2919
2920                 /* Is a scrolling action occuring? */
2921                 if (!synaction->in_taphold && !synaction->in_vscroll) {
2922                         /*
2923                          * A scrolling action must not conflict with a tap
2924                          * action. Here are the conditions to consider a
2925                          * scrolling action:
2926                          *  - the action in a configurable area
2927                          *  - one of the following:
2928                          *     . the distance between the last packet and the
2929                          *       first should be above a configurable minimum
2930                          *     . tap timed out
2931                          */
2932                         dxp = abs(synaction->queue[synaction->queue_cursor].x -
2933                             synaction->start_x);
2934                         dyp = abs(synaction->queue[synaction->queue_cursor].y -
2935                             synaction->start_y);
2936
2937                         if (timevalcmp(&sc->lastsoftintr, &sc->taptimeout, >) ||
2938                             dxp >= sc->syninfo.vscroll_min_delta ||
2939                             dyp >= sc->syninfo.vscroll_min_delta) {
2940                                 /* Check for horizontal scrolling. */
2941                                 if ((vscroll_hor_area > 0 &&
2942                                     synaction->start_y <= vscroll_hor_area) ||
2943                                     (vscroll_hor_area < 0 &&
2944                                      synaction->start_y >=
2945                                      6143 + vscroll_hor_area))
2946                                         synaction->in_vscroll += 2;
2947
2948                                 /* Check for vertical scrolling. */
2949                                 if ((vscroll_ver_area > 0 &&
2950                                     synaction->start_x <= vscroll_ver_area) ||
2951                                     (vscroll_ver_area < 0 &&
2952                                      synaction->start_x >=
2953                                      6143 + vscroll_ver_area))
2954                                         synaction->in_vscroll += 1;
2955
2956                                 /* Avoid conflicts if area overlaps. */
2957                                 if (synaction->in_vscroll == 3)
2958                                         synaction->in_vscroll =
2959                                             (dxp > dyp) ? 2 : 1;
2960                         }
2961                         VLOG(5, (LOG_DEBUG,
2962                             "synaptics: virtual scrolling: %s "
2963                             "(direction=%d, dxp=%d, dyp=%d)\n",
2964                             synaction->in_vscroll ? "YES" : "NO",
2965                             synaction->in_vscroll, dxp, dyp));
2966                 }
2967
2968                 weight_prev_x = weight_prev_y = weight_previous;
2969                 div_max_x = div_max_y = div_max;
2970
2971                 if (synaction->in_vscroll) {
2972                         /* Dividers are different with virtual scrolling. */
2973                         div_min = sc->syninfo.vscroll_div_min;
2974                         div_max_x = div_max_y = sc->syninfo.vscroll_div_max;
2975                 } else {
2976                         /*
2977                          * There's a lot of noise in coordinates when
2978                          * the finger is on the touchpad's borders. When
2979                          * using this area, we apply a special weight and
2980                          * div.
2981                          */
2982                         if (x0 <= na_left || x0 >= 6143 - na_right) {
2983                                 weight_prev_x = sc->syninfo.weight_previous_na;
2984                                 div_max_x = sc->syninfo.div_max_na;
2985                         }
2986
2987                         if (y0 <= na_bottom || y0 >= 6143 - na_top) {
2988                                 weight_prev_y = sc->syninfo.weight_previous_na;
2989                                 div_max_y = sc->syninfo.div_max_na;
2990                         }
2991                 }
2992
2993                 /*
2994                  * Calculate weights for the average operands and
2995                  * the divisor. Both depend on the distance between
2996                  * the current packet and a previous one (based on the
2997                  * window width).
2998                  */
2999                 window = imin(synaction->queue_len, window_max);
3000                 peer = SYNAPTICS_QUEUE_CURSOR(cursor + window - 1);
3001                 dxp = abs(x0 - synaction->queue[peer].x) + 1;
3002                 dyp = abs(y0 - synaction->queue[peer].y) + 1;
3003                 len = (dxp * dxp) + (dyp * dyp);
3004                 weight_prev_x = imin(weight_prev_x,
3005                     weight_len_squared * weight_prev_x / len);
3006                 weight_prev_y = imin(weight_prev_y,
3007                     weight_len_squared * weight_prev_y / len);
3008
3009                 len = (dxp + dyp) / 2;
3010                 div_x = div_len * div_max_x / len;
3011                 div_x = imin(div_max_x, div_x);
3012                 div_x = imax(div_min, div_x);
3013                 div_y = div_len * div_max_y / len;
3014                 div_y = imin(div_max_y, div_y);
3015                 div_y = imax(div_min, div_y);
3016
3017                 VLOG(3, (LOG_DEBUG,
3018                     "synaptics: peer=%d, len=%d, weight=%d/%d, div=%d/%d\n",
3019                     peer, len, weight_prev_x, weight_prev_y, div_x, div_y));
3020
3021                 /* Compute averages. */
3022                 synaction->avg_dx =
3023                     (weight_current * dx * multiplicator +
3024                      weight_prev_x * synaction->avg_dx) /
3025                     (weight_current + weight_prev_x);
3026
3027                 synaction->avg_dy =
3028                     (weight_current * dy * multiplicator +
3029                      weight_prev_y * synaction->avg_dy) /
3030                     (weight_current + weight_prev_y);
3031
3032                 VLOG(5, (LOG_DEBUG,
3033                     "synaptics: avg_dx~=%d, avg_dy~=%d\n",
3034                     synaction->avg_dx / multiplicator,
3035                     synaction->avg_dy / multiplicator));
3036
3037                 /* Use these averages to calculate x & y. */
3038                 synaction->squelch_x += synaction->avg_dx;
3039                 *x = synaction->squelch_x / (div_x * multiplicator);
3040                 synaction->squelch_x = synaction->squelch_x %
3041                     (div_x * multiplicator);
3042
3043                 synaction->squelch_y += synaction->avg_dy;
3044                 *y = synaction->squelch_y / (div_y * multiplicator);
3045                 synaction->squelch_y = synaction->squelch_y %
3046                     (div_y * multiplicator);
3047
3048                 if (synaction->in_vscroll) {
3049                         switch(synaction->in_vscroll) {
3050                         case 1: /* Vertical scrolling. */
3051                                 if (*y != 0)
3052                                         ms->button |= (*y > 0) ?
3053                                             MOUSE_BUTTON4DOWN :
3054                                             MOUSE_BUTTON5DOWN;
3055                                 break;
3056                         case 2: /* Horizontal scrolling. */
3057                                 if (*x != 0)
3058                                         ms->button |= (*x > 0) ?
3059                                             MOUSE_BUTTON7DOWN :
3060                                             MOUSE_BUTTON6DOWN;
3061                                 break;
3062                         }
3063
3064                         /* The pointer is not moved. */
3065                         *x = *y = 0;
3066                 } else {
3067                         VLOG(3, (LOG_DEBUG, "synaptics: [%d, %d] -> [%d, %d]\n",
3068                             dx, dy, *x, *y));
3069                 }
3070         } else if (sc->flags & PSM_FLAGS_FINGERDOWN) {
3071                 /*
3072                  * An action is currently taking place but the pressure
3073                  * dropped under the minimum, putting an end to it.
3074                  */
3075                 synapticsaction_t *synaction;
3076                 int taphold_timeout, dx, dy, tap_max_delta;
3077
3078                 synaction = &(sc->synaction);
3079                 dx = abs(synaction->queue[synaction->queue_cursor].x -
3080                     synaction->start_x);
3081                 dy = abs(synaction->queue[synaction->queue_cursor].y -
3082                     synaction->start_y);
3083
3084                 /* Max delta is disabled for multi-fingers tap. */
3085                 if (synaction->fingers_nb > 1)
3086                         tap_max_delta = imax(dx, dy);
3087                 else
3088                         tap_max_delta = sc->syninfo.tap_max_delta;
3089
3090                 sc->flags &= ~PSM_FLAGS_FINGERDOWN;
3091
3092                 /* Check for tap. */
3093                 VLOG(3, (LOG_DEBUG,
3094                     "synaptics: zmax=%d, dx=%d, dy=%d, "
3095                     "delta=%d, fingers=%d, queue=%d\n",
3096                     sc->zmax, dx, dy, tap_max_delta, synaction->fingers_nb,
3097                     synaction->queue_len));
3098                 if (!synaction->in_vscroll && sc->zmax >= tap_threshold &&
3099                     timevalcmp(&sc->lastsoftintr, &sc->taptimeout, <=) &&
3100                     dx <= tap_max_delta && dy <= tap_max_delta &&
3101                     synaction->queue_len >= sc->syninfo.tap_min_queue) {
3102                         /*
3103                          * We have a tap if:
3104                          *   - the maximum pressure went over tap_threshold
3105                          *   - the action ended before tap_timeout
3106                          *
3107                          * To handle tap-hold, we must delay any button push to
3108                          * the next action.
3109                          */
3110                         if (synaction->in_taphold) {
3111                                 /*
3112                                  * This is the second and last tap of a
3113                                  * double tap action, not a tap-hold.
3114                                  */
3115                                 synaction->in_taphold = 0;
3116
3117                                 /*
3118                                  * For double-tap to work:
3119                                  *   - no button press is emitted (to
3120                                  *     simulate a button release)
3121                                  *   - PSM_FLAGS_FINGERDOWN is set to
3122                                  *     force the next packet to emit a
3123                                  *     button press)
3124                                  */
3125                                 VLOG(2, (LOG_DEBUG,
3126                                     "synaptics: button RELEASE: %d\n",
3127                                     synaction->tap_button));
3128                                 sc->flags |= PSM_FLAGS_FINGERDOWN;
3129                         } else {
3130                                 /*
3131                                  * This is the first tap: we set the
3132                                  * tap-hold state and notify the button
3133                                  * down event.
3134                                  */
3135                                 synaction->in_taphold = 1;
3136                                 taphold_timeout = sc->syninfo.taphold_timeout;
3137                                 sc->taptimeout.tv_sec  = taphold_timeout /
3138                                     1000000;
3139                                 sc->taptimeout.tv_usec = taphold_timeout %
3140                                     1000000;
3141                                 timevaladd(&sc->taptimeout, &sc->lastsoftintr);
3142
3143                                 switch (synaction->fingers_nb) {
3144                                 case 3:
3145                                         synaction->tap_button =
3146                                             MOUSE_BUTTON2DOWN;
3147                                         break;
3148                                 case 2:
3149                                         synaction->tap_button =
3150                                             MOUSE_BUTTON3DOWN;
3151                                         break;
3152                                 default:
3153                                         synaction->tap_button =
3154                                             MOUSE_BUTTON1DOWN;
3155                                 }
3156                                 VLOG(2, (LOG_DEBUG,
3157                                     "synaptics: button PRESS: %d\n",
3158                                     synaction->tap_button));
3159                                 ms->button |= synaction->tap_button;
3160                         }
3161                 } else {
3162                         /*
3163                          * Not enough pressure or timeout: reset
3164                          * tap-hold state.
3165                          */
3166                         if (synaction->in_taphold) {
3167                                 VLOG(2, (LOG_DEBUG,
3168                                     "synaptics: button RELEASE: %d\n",
3169                                     synaction->tap_button));
3170                                 synaction->in_taphold = 0;
3171                         } else {
3172                                 VLOG(2, (LOG_DEBUG,
3173                                     "synaptics: not a tap-hold\n"));
3174                         }
3175                 }
3176         } else if (!(sc->flags & PSM_FLAGS_FINGERDOWN) &&
3177             sc->synaction.in_taphold) {
3178                 /*
3179                  * For a tap-hold to work, the button must remain down at
3180                  * least until timeout (where the in_taphold flags will be
3181                  * cleared) or during the next action.
3182                  */
3183                 if (timevalcmp(&sc->lastsoftintr, &sc->taptimeout, <=)) {
3184                         ms->button |= sc->synaction.tap_button;
3185                 } else {
3186                         VLOG(2, (LOG_DEBUG,
3187                             "synaptics: button RELEASE: %d\n",
3188                             sc->synaction.tap_button));
3189                         sc->synaction.in_taphold = 0;
3190                 }
3191         }
3192
3193 SYNAPTICS_END:
3194         /*
3195          * Use the extra buttons as a scrollwheel
3196          *
3197          * XXX X.Org uses the Z axis for vertical wheel only,
3198          * whereas moused(8) understands special values to differ
3199          * vertical and horizontal wheels.
3200          *
3201          * xf86-input-mouse needs therefore a small patch to
3202          * understand these special values. Without it, the
3203          * horizontal wheel acts as a vertical wheel in X.Org.
3204          *
3205          * That's why the horizontal wheel is disabled by
3206          * default for now.
3207          */
3208         if (ms->button & MOUSE_BUTTON4DOWN) {
3209                 *z = -1;
3210                 ms->button &= ~MOUSE_BUTTON4DOWN;
3211         } else if (ms->button & MOUSE_BUTTON5DOWN) {
3212                 *z = 1;
3213                 ms->button &= ~MOUSE_BUTTON5DOWN;
3214         } else if (ms->button & MOUSE_BUTTON6DOWN) {
3215                 *z = -2;
3216                 ms->button &= ~MOUSE_BUTTON6DOWN;
3217         } else if (ms->button & MOUSE_BUTTON7DOWN) {
3218                 *z = 2;
3219                 ms->button &= ~MOUSE_BUTTON7DOWN;
3220         } else
3221                 *z = 0;
3222
3223         return (0);
3224 }
3225
3226 static void
3227 proc_versapad(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms,
3228     int *x, int *y, int *z)
3229 {
3230         static int butmap_versapad[8] = {
3231                 0,
3232                 MOUSE_BUTTON3DOWN,
3233                 0,
3234                 MOUSE_BUTTON3DOWN,
3235                 MOUSE_BUTTON1DOWN,
3236                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
3237                 MOUSE_BUTTON1DOWN,
3238                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
3239         };
3240         int c, x0, y0;
3241
3242         /* VersaPad PS/2 absolute mode message format
3243          *
3244          * [packet1]     7   6   5   4   3   2   1   0(LSB)
3245          *  ipacket[0]:  1   1   0   A   1   L   T   R
3246          *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
3247          *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
3248          *  ipacket[3]:  1   1   1   A   1   L   T   R
3249          *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
3250          *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
3251          *
3252          * [note]
3253          *  R: right physical mouse button (1=on)
3254          *  T: touch pad virtual button (1=tapping)
3255          *  L: left physical mouse button (1=on)
3256          *  A: position data is valid (1=valid)
3257          *  H: horizontal data (12bit signed integer. H11 is sign bit.)
3258          *  V: vertical data (12bit signed integer. V11 is sign bit.)
3259          *  P: pressure data
3260          *
3261          * Tapping is mapped to MOUSE_BUTTON4.
3262          */
3263         c = pb->ipacket[0];
3264         *x = *y = 0;
3265         ms->button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
3266         ms->button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
3267         if (c & MOUSE_PS2VERSA_IN_USE) {
3268                 x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
3269                 y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
3270                 if (x0 & 0x800)
3271                         x0 -= 0x1000;
3272                 if (y0 & 0x800)
3273                         y0 -= 0x1000;
3274                 if (sc->flags & PSM_FLAGS_FINGERDOWN) {
3275                         *x = sc->xold - x0;
3276                         *y = y0 - sc->yold;
3277                         if (*x < 0)     /* XXX */
3278                                 ++*x;
3279                         else if (*x)
3280                                 --*x;
3281                         if (*y < 0)
3282                                 ++*y;
3283                         else if (*y)
3284                                 --*y;
3285                 } else
3286                         sc->flags |= PSM_FLAGS_FINGERDOWN;
3287                 sc->xold = x0;
3288                 sc->yold = y0;
3289         } else
3290                 sc->flags &= ~PSM_FLAGS_FINGERDOWN;
3291 }
3292
3293 static void
3294 psmsoftintr(void *arg)
3295 {
3296         /*
3297          * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
3298          * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
3299          */
3300         static int butmap[8] = {
3301                 0,
3302                 MOUSE_BUTTON1DOWN,
3303                 MOUSE_BUTTON3DOWN,
3304                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
3305                 MOUSE_BUTTON2DOWN,
3306                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
3307                 MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
3308                 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
3309         };
3310         struct psm_softc *sc = arg;
3311         mousestatus_t ms;
3312         packetbuf_t *pb;
3313         int x, y, z, c, l, s;
3314
3315         getmicrouptime(&sc->lastsoftintr);
3316
3317         s = spltty();
3318
3319         do {
3320                 pb = &sc->pqueue[sc->pqueue_start];
3321
3322                 if (sc->mode.level == PSM_LEVEL_NATIVE)
3323                         goto next_native;
3324
3325                 c = pb->ipacket[0];
3326                 /*
3327                  * A kludge for Kensington device!
3328                  * The MSB of the horizontal count appears to be stored in
3329                  * a strange place.
3330                  */
3331                 if (sc->hw.model == MOUSE_MODEL_THINK)
3332                         pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
3333
3334                 /* ignore the overflow bits... */
3335                 x = (c & MOUSE_PS2_XNEG) ?
3336                     pb->ipacket[1] - 256 : pb->ipacket[1];
3337                 y = (c & MOUSE_PS2_YNEG) ?
3338                     pb->ipacket[2] - 256 : pb->ipacket[2];
3339                 z = 0;
3340                 ms.obutton = sc->button;          /* previous button state */
3341                 ms.button = butmap[c & MOUSE_PS2_BUTTONS];
3342                 /* `tapping' action */
3343                 if (sc->config & PSM_CONFIG_FORCETAP)
3344                         ms.button |= ((c & MOUSE_PS2_TAP)) ?
3345                             0 : MOUSE_BUTTON4DOWN;
3346
3347                 switch (sc->hw.model) {
3348
3349                 case MOUSE_MODEL_EXPLORER:
3350                         /*
3351                          *          b7 b6 b5 b4 b3 b2 b1 b0
3352                          * byte 1:  oy ox sy sx 1  M  R  L
3353                          * byte 2:  x  x  x  x  x  x  x  x
3354                          * byte 3:  y  y  y  y  y  y  y  y
3355                          * byte 4:  *  *  S2 S1 s  d2 d1 d0
3356                          *
3357                          * L, M, R, S1, S2: left, middle, right and side buttons
3358                          * s: wheel data sign bit
3359                          * d2-d0: wheel data
3360                          */
3361                         z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG) ?
3362                             (pb->ipacket[3] & 0x0f) - 16 :
3363                             (pb->ipacket[3] & 0x0f);
3364                         ms.button |=
3365                             (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN) ?
3366                             MOUSE_BUTTON4DOWN : 0;
3367                         ms.button |=
3368                             (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN) ?
3369                             MOUSE_BUTTON5DOWN : 0;
3370                         break;
3371
3372                 case MOUSE_MODEL_INTELLI:
3373                 case MOUSE_MODEL_NET:
3374                         /* wheel data is in the fourth byte */
3375                         z = (char)pb->ipacket[3];
3376                         /*
3377                          * XXX some mice may send 7 when there is no Z movement?                         */
3378                         if ((z >= 7) || (z <= -7))
3379                                 z = 0;
3380                         /* some compatible mice have additional buttons */
3381                         ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN) ?
3382                             MOUSE_BUTTON4DOWN : 0;
3383                         ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN) ?
3384                             MOUSE_BUTTON5DOWN : 0;
3385                         break;
3386
3387                 case MOUSE_MODEL_MOUSEMANPLUS:
3388                         proc_mmanplus(sc, pb, &ms, &x, &y, &z);
3389                         break;
3390
3391                 case MOUSE_MODEL_GLIDEPOINT:
3392                         /* `tapping' action */
3393                         ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 :
3394                             MOUSE_BUTTON4DOWN;
3395                         break;
3396
3397                 case MOUSE_MODEL_NETSCROLL:
3398                         /*
3399                          * three addtional bytes encode buttons and
3400                          * wheel events
3401                          */
3402                         ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN) ?
3403                             MOUSE_BUTTON4DOWN : 0;
3404                         ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN) ?
3405                             MOUSE_BUTTON5DOWN : 0;
3406                         z = (pb->ipacket[3] & MOUSE_PS2_XNEG) ?
3407                             pb->ipacket[4] - 256 : pb->ipacket[4];
3408                         break;
3409
3410                 case MOUSE_MODEL_THINK:
3411                         /* the fourth button state in the first byte */
3412                         ms.button |= (c & MOUSE_PS2_TAP) ?
3413                             MOUSE_BUTTON4DOWN : 0;
3414                         break;
3415
3416                 case MOUSE_MODEL_VERSAPAD:
3417                         proc_versapad(sc, pb, &ms, &x, &y, &z);
3418                         c = ((x < 0) ? MOUSE_PS2_XNEG : 0) |
3419                             ((y < 0) ? MOUSE_PS2_YNEG : 0);
3420                         break;
3421         
3422                 case MOUSE_MODEL_4D:
3423                         /*
3424                          *          b7 b6 b5 b4 b3 b2 b1 b0
3425                          * byte 1:  s2 d2 s1 d1 1  M  R  L
3426                          * byte 2:  sx x  x  x  x  x  x  x
3427                          * byte 3:  sy y  y  y  y  y  y  y
3428                          *
3429                          * s1: wheel 1 direction
3430                          * d1: wheel 1 data
3431                          * s2: wheel 2 direction
3432                          * d2: wheel 2 data
3433                          */
3434                         x = (pb->ipacket[1] & 0x80) ?
3435                             pb->ipacket[1] - 256 : pb->ipacket[1];
3436                         y = (pb->ipacket[2] & 0x80) ?
3437                             pb->ipacket[2] - 256 : pb->ipacket[2];
3438                         switch (c & MOUSE_4D_WHEELBITS) {
3439                         case 0x10:
3440                                 z = 1;
3441                                 break;
3442                         case 0x30:
3443                                 z = -1;
3444                                 break;
3445                         case 0x40:      /* XXX 2nd wheel turning right */
3446                                 z = 2;
3447                                 break;
3448                         case 0xc0:      /* XXX 2nd wheel turning left */
3449                                 z = -2;
3450                                 break;
3451                         }
3452                         break;
3453
3454                 case MOUSE_MODEL_4DPLUS:
3455                         if ((x < 16 - 256) && (y < 16 - 256)) {
3456                                 /*
3457                                  *          b7 b6 b5 b4 b3 b2 b1 b0
3458                                  * byte 1:  0  0  1  1  1  M  R  L
3459                                  * byte 2:  0  0  0  0  1  0  0  0
3460                                  * byte 3:  0  0  0  0  S  s  d1 d0
3461                                  *
3462                                  * L, M, R, S: left, middle, right,
3463                                  *             and side buttons
3464                                  * s: wheel data sign bit
3465                                  * d1-d0: wheel data
3466                                  */
3467                                 x = y = 0;
3468                                 if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
3469                                         ms.button |= MOUSE_BUTTON4DOWN;
3470                                 z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG) ?
3471                                     ((pb->ipacket[2] & 0x07) - 8) :
3472                                     (pb->ipacket[2] & 0x07) ;
3473                         } else {
3474                                 /* preserve previous button states */
3475                                 ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
3476                         }
3477                         break;
3478
3479                 case MOUSE_MODEL_SYNAPTICS:
3480                         if (proc_synaptics(sc, pb, &ms, &x, &y, &z) != 0)
3481                                 goto next;
3482                         break;
3483
3484                 case MOUSE_MODEL_TRACKPOINT:
3485                 case MOUSE_MODEL_GENERIC:
3486                 default:
3487                         break;
3488                 }
3489
3490         /* scale values */
3491         if (sc->mode.accelfactor >= 1) {
3492                 if (x != 0) {
3493                         x = x * x / sc->mode.accelfactor;
3494                         if (x == 0)
3495                                 x = 1;
3496                         if (c & MOUSE_PS2_XNEG)
3497                                 x = -x;
3498                 }
3499                 if (y != 0) {
3500                         y = y * y / sc->mode.accelfactor;
3501                         if (y == 0)
3502                                 y = 1;
3503                         if (c & MOUSE_PS2_YNEG)
3504                                 y = -y;
3505                 }
3506         }
3507
3508         ms.dx = x;
3509         ms.dy = y;
3510         ms.dz = z;
3511         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0) |
3512             (ms.obutton ^ ms.button);
3513
3514         pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);
3515
3516         sc->status.flags |= ms.flags;
3517         sc->status.dx += ms.dx;
3518         sc->status.dy += ms.dy;
3519         sc->status.dz += ms.dz;
3520         sc->status.button = ms.button;
3521         sc->button = ms.button;
3522
3523 next_native:
3524         sc->watchdog = FALSE;
3525
3526         /* queue data */
3527         if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
3528                 l = imin(pb->inputbytes,
3529                     sizeof(sc->queue.buf) - sc->queue.tail);
3530                 bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
3531                 if (pb->inputbytes > l)
3532                         bcopy(&pb->ipacket[l], &sc->queue.buf[0],
3533                             pb->inputbytes - l);
3534                 sc->queue.tail = (sc->queue.tail + pb->inputbytes) %
3535                     sizeof(sc->queue.buf);
3536                 sc->queue.count += pb->inputbytes;
3537         }
3538         pb->inputbytes = 0;
3539
3540 next:
3541         if (++sc->pqueue_start >= PSM_PACKETQUEUE)
3542                 sc->pqueue_start = 0;
3543         } while (sc->pqueue_start != sc->pqueue_end);
3544
3545         if (sc->state & PSM_ASLP) {
3546                 sc->state &= ~PSM_ASLP;
3547                 wakeup(sc);
3548         }
3549         selwakeuppri(&sc->rsel, PZERO);
3550         if (sc->async != NULL) {
3551                 pgsigio(&sc->async, SIGIO, 0);
3552         }
3553         sc->state &= ~PSM_SOFTARMED;
3554         splx(s);
3555 }
3556
3557 static int
3558 psmpoll(struct cdev *dev, int events, struct thread *td)
3559 {
3560         struct psm_softc *sc = dev->si_drv1;
3561         int s;
3562         int revents = 0;
3563
3564         /* Return true if a mouse event available */
3565         s = spltty();
3566         if (events & (POLLIN | POLLRDNORM)) {
3567                 if (sc->queue.count > 0)
3568                         revents |= events & (POLLIN | POLLRDNORM);
3569                 else
3570                         selrecord(td, &sc->rsel);
3571         }
3572         splx(s);
3573
3574         return (revents);
3575 }
3576
3577 /* vendor/model specific routines */
3578
3579 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
3580 {
3581         if (set_mouse_resolution(kbdc, res) != res)
3582                 return (FALSE);
3583         if (set_mouse_scaling(kbdc, scale) &&
3584             set_mouse_scaling(kbdc, scale) &&
3585             set_mouse_scaling(kbdc, scale) &&
3586             (get_mouse_status(kbdc, status, 0, 3) >= 3))
3587                 return (TRUE);
3588         return (FALSE);
3589 }
3590
3591 static int
3592 mouse_ext_command(KBDC kbdc, int command)
3593 {
3594         int c;
3595
3596         c = (command >> 6) & 0x03;
3597         if (set_mouse_resolution(kbdc, c) != c)
3598                 return (FALSE);
3599         c = (command >> 4) & 0x03;
3600         if (set_mouse_resolution(kbdc, c) != c)
3601                 return (FALSE);
3602         c = (command >> 2) & 0x03;
3603         if (set_mouse_resolution(kbdc, c) != c)
3604                 return (FALSE);
3605         c = (command >> 0) & 0x03;
3606         if (set_mouse_resolution(kbdc, c) != c)
3607                 return (FALSE);
3608         return (TRUE);
3609 }
3610
3611 #ifdef notyet
3612 /* Logitech MouseMan Cordless II */
3613 static int
3614 enable_lcordless(KDBC kbdc, struct psm_softc *sc)
3615 {
3616         int status[3];
3617         int ch;
3618
3619         if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 2, status))
3620                 return (FALSE);
3621         if (status[1] == PSMD_RES_HIGH)
3622                 return (FALSE);
3623         ch = (status[0] & 0x07) - 1;    /* channel # */
3624         if ((ch <= 0) || (ch > 4))
3625                 return (FALSE);
3626         /*
3627          * status[1]: always one?
3628          * status[2]: battery status? (0-100)
3629          */
3630         return (TRUE);
3631 }
3632 #endif /* notyet */
3633
3634 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
3635 static int
3636 enable_groller(KBDC kbdc, struct psm_softc *sc)
3637 {
3638         int status[3];
3639
3640         /*
3641          * The special sequence to enable the fourth button and the
3642          * roller. Immediately after this sequence check status bytes.
3643          * if the mouse is NetScroll, the second and the third bytes are
3644          * '3' and 'D'.
3645          */
3646
3647         /*
3648          * If the mouse is an ordinary PS/2 mouse, the status bytes should
3649          * look like the following.
3650          *
3651          * byte 1 bit 7 always 0
3652          *        bit 6 stream mode (0)
3653          *        bit 5 disabled (0)
3654          *        bit 4 1:1 scaling (0)
3655          *        bit 3 always 0
3656          *        bit 0-2 button status
3657          * byte 2 resolution (PSMD_RES_HIGH)
3658          * byte 3 report rate (?)
3659          */
3660
3661         if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
3662                 return (FALSE);
3663         if ((status[1] != '3') || (status[2] != 'D'))
3664                 return (FALSE);
3665         /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
3666         if (sc != NULL)
3667                 sc->hw.buttons = 4;
3668         return (TRUE);
3669 }
3670
3671 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
3672 static int
3673 enable_gmouse(KBDC kbdc, struct psm_softc *sc)
3674 {
3675         int status[3];
3676
3677         /*
3678          * The special sequence to enable the middle, "rubber" button.
3679          * Immediately after this sequence check status bytes.
3680          * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
3681          * the second and the third bytes are '3' and 'U'.
3682          * NOTE: NetMouse reports that it has three buttons although it has
3683          * two buttons and a rubber button. NetMouse Pro and MIE Mouse
3684          * say they have three buttons too and they do have a button on the
3685          * side...
3686          */
3687         if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
3688                 return (FALSE);
3689         if ((status[1] != '3') || (status[2] != 'U'))
3690                 return (FALSE);
3691         return (TRUE);
3692 }
3693
3694 /* ALPS GlidePoint */
3695 static int
3696 enable_aglide(KBDC kbdc, struct psm_softc *sc)
3697 {
3698         int status[3];
3699
3700         /*
3701          * The special sequence to obtain ALPS GlidePoint specific
3702          * information. Immediately after this sequence, status bytes will
3703          * contain something interesting.
3704          * NOTE: ALPS produces several models of GlidePoint. Some of those
3705          * do not respond to this sequence, thus, cannot be detected this way.
3706          */
3707         if (set_mouse_sampling_rate(kbdc, 100) != 100)
3708                 return (FALSE);
3709         if (!mouse_id_proc1(kbdc, PSMD_RES_LOW, 2, status))
3710                 return (FALSE);
3711         if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
3712                 return (FALSE);
3713         return (TRUE);
3714 }
3715
3716 /* Kensington ThinkingMouse/Trackball */
3717 static int
3718 enable_kmouse(KBDC kbdc, struct psm_softc *sc)
3719 {
3720         static u_char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
3721         int status[3];
3722         int id1;
3723         int id2;
3724         int i;
3725
3726         id1 = get_aux_id(kbdc);
3727         if (set_mouse_sampling_rate(kbdc, 10) != 10)
3728                 return (FALSE);
3729         /*
3730          * The device is now in the native mode? It returns a different
3731          * ID value...
3732          */
3733         id2 = get_aux_id(kbdc);
3734         if ((id1 == id2) || (id2 != 2))
3735                 return (FALSE);
3736
3737         if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
3738                 return (FALSE);
3739 #if PSM_DEBUG >= 2
3740         /* at this point, resolution is LOW, sampling rate is 10/sec */
3741         if (get_mouse_status(kbdc, status, 0, 3) < 3)
3742                 return (FALSE);
3743 #endif
3744
3745         /*
3746          * The special sequence to enable the third and fourth buttons.
3747          * Otherwise they behave like the first and second buttons.
3748          */
3749         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3750                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3751                         return (FALSE);
3752
3753         /*
3754          * At this point, the device is using default resolution and
3755          * sampling rate for the native mode.
3756          */
3757         if (get_mouse_status(kbdc, status, 0, 3) < 3)
3758                 return (FALSE);
3759         if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
3760                 return (FALSE);
3761
3762         /* the device appears be enabled by this sequence, diable it for now */
3763         disable_aux_dev(kbdc);
3764         empty_aux_buffer(kbdc, 5);
3765
3766         return (TRUE);
3767 }
3768
3769 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
3770 static int
3771 enable_mmanplus(KBDC kbdc, struct psm_softc *sc)
3772 {
3773         int data[3];
3774
3775         /* the special sequence to enable the fourth button and the roller. */
3776         /*
3777          * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
3778          * must be called exactly three times since the last RESET command
3779          * before this sequence. XXX
3780          */
3781         if (!set_mouse_scaling(kbdc, 1))
3782                 return (FALSE);
3783         if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
3784                 return (FALSE);
3785         if (get_mouse_status(kbdc, data, 1, 3) < 3)
3786                 return (FALSE);
3787
3788         /*
3789          * PS2++ protocol, packet type 0
3790          *
3791          *          b7 b6 b5 b4 b3 b2 b1 b0
3792          * byte 1:  *  1  p3 p2 1  *  *  *
3793          * byte 2:  1  1  p1 p0 m1 m0 1  0
3794          * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
3795          *
3796          * p3-p0: packet type: 0
3797          * m7-m0: model ID: MouseMan+:0x50,
3798          *                  FirstMouse+:0x51,
3799          *                  ScrollPoint:0x58...
3800          */
3801         /* check constant bits */
3802         if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
3803                 return (FALSE);
3804         if ((data[1] & 0xc3) != 0xc2)
3805                 return (FALSE);
3806         /* check d3-d0 in byte 2 */
3807         if (!MOUSE_PS2PLUS_CHECKBITS(data))
3808                 return (FALSE);
3809         /* check p3-p0 */
3810         if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
3811                 return (FALSE);
3812
3813         if (sc != NULL) {
3814                 sc->hw.hwid &= 0x00ff;
3815                 sc->hw.hwid |= data[2] << 8;    /* save model ID */
3816         }
3817
3818         /*
3819          * MouseMan+ (or FirstMouse+) is now in its native mode, in which
3820          * the wheel and the fourth button events are encoded in the
3821          * special data packet. The mouse may be put in the IntelliMouse mode
3822          * if it is initialized by the IntelliMouse's method.
3823          */
3824         return (TRUE);
3825 }
3826
3827 /* MS IntelliMouse Explorer */
3828 static int
3829 enable_msexplorer(KBDC kbdc, struct psm_softc *sc)
3830 {
3831         static u_char rate0[] = { 200, 100, 80, };
3832         static u_char rate1[] = { 200, 200, 80, };
3833         int id;
3834         int i;
3835
3836         /*
3837          * This is needed for at least A4Tech X-7xx mice - they do not go
3838          * straight to Explorer mode, but need to be set to Intelli mode
3839          * first.
3840          */
3841         enable_msintelli(kbdc, sc);
3842
3843         /* the special sequence to enable the extra buttons and the roller. */
3844         for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i)
3845                 if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
3846                         return (FALSE);
3847         /* the device will give the genuine ID only after the above sequence */
3848         id = get_aux_id(kbdc);
3849         if (id != PSM_EXPLORER_ID)
3850                 return (FALSE);
3851
3852         if (sc != NULL) {
3853                 sc->hw.buttons = 5;     /* IntelliMouse Explorer XXX */
3854                 sc->hw.hwid = id;
3855         }
3856
3857         /*
3858          * XXX: this is a kludge to fool some KVM switch products
3859          * which think they are clever enough to know the 4-byte IntelliMouse
3860          * protocol, and assume any other protocols use 3-byte packets.
3861          * They don't convey 4-byte data packets from the IntelliMouse Explorer
3862          * correctly to the host computer because of this!
3863          * The following sequence is actually IntelliMouse's "wake up"
3864          * sequence; it will make the KVM think the mouse is IntelliMouse
3865          * when it is in fact IntelliMouse Explorer.
3866          */
3867         for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i)
3868                 if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
3869                         break;
3870         get_aux_id(kbdc);
3871
3872         return (TRUE);
3873 }
3874
3875 /* MS IntelliMouse */
3876 static int
3877 enable_msintelli(KBDC kbdc, struct psm_softc *sc)
3878 {
3879         /*
3880          * Logitech MouseMan+ and FirstMouse+ will also respond to this
3881          * probe routine and act like IntelliMouse.
3882          */
3883
3884         static u_char rate[] = { 200, 100, 80, };
3885         int id;
3886         int i;
3887
3888         /* the special sequence to enable the third button and the roller. */
3889         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3890                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3891                         return (FALSE);
3892         /* the device will give the genuine ID only after the above sequence */
3893         id = get_aux_id(kbdc);
3894         if (id != PSM_INTELLI_ID)
3895                 return (FALSE);
3896
3897         if (sc != NULL) {
3898                 sc->hw.buttons = 3;
3899                 sc->hw.hwid = id;
3900         }
3901
3902         return (TRUE);
3903 }
3904
3905 /* A4 Tech 4D Mouse */
3906 static int
3907 enable_4dmouse(KBDC kbdc, struct psm_softc *sc)
3908 {
3909         /*
3910          * Newer wheel mice from A4 Tech may use the 4D+ protocol.
3911          */
3912
3913         static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
3914         int id;
3915         int i;
3916
3917         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3918                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3919                         return (FALSE);
3920         id = get_aux_id(kbdc);
3921         /*
3922          * WinEasy 4D, 4 Way Scroll 4D: 6
3923          * Cable-Free 4D: 8 (4DPLUS)
3924          * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
3925          */
3926         if (id != PSM_4DMOUSE_ID)
3927                 return (FALSE);
3928
3929         if (sc != NULL) {
3930                 sc->hw.buttons = 3;     /* XXX some 4D mice have 4? */
3931                 sc->hw.hwid = id;
3932         }
3933
3934         return (TRUE);
3935 }
3936
3937 /* A4 Tech 4D+ Mouse */
3938 static int
3939 enable_4dplus(KBDC kbdc, struct psm_softc *sc)
3940 {
3941         /*
3942          * Newer wheel mice from A4 Tech seem to use this protocol.
3943          * Older models are recognized as either 4D Mouse or IntelliMouse.
3944          */
3945         int id;
3946
3947         /*
3948          * enable_4dmouse() already issued the following ID sequence...
3949         static u_char rate[] = { 200, 100, 80, 60, 40, 20 };
3950         int i;
3951
3952         for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i)
3953                 if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3954                         return (FALSE);
3955         */
3956
3957         id = get_aux_id(kbdc);
3958         switch (id) {
3959         case PSM_4DPLUS_ID:
3960                 break;
3961         case PSM_4DPLUS_RFSW35_ID:
3962                 break;
3963         default:
3964                 return (FALSE);
3965         }
3966
3967         if (sc != NULL) {
3968                 sc->hw.buttons = (id == PSM_4DPLUS_ID) ? 4 : 3;
3969                 sc->hw.hwid = id;
3970         }
3971
3972         return (TRUE);
3973 }
3974
3975 /* Synaptics Touchpad */
3976 static int
3977 synaptics_sysctl(SYSCTL_HANDLER_ARGS)
3978 {
3979         int error, arg;
3980
3981         /* Read the current value. */
3982         arg = *(int *)oidp->oid_arg1;
3983         error = sysctl_handle_int(oidp, &arg, 0, req);
3984
3985         /* Sanity check. */
3986         if (error || !req->newptr)
3987                 return (error);
3988
3989         /*
3990          * Check that the new value is in the concerned node's range
3991          * of values.
3992          */
3993         switch (oidp->oid_arg2) {
3994         case SYNAPTICS_SYSCTL_MIN_PRESSURE:
3995         case SYNAPTICS_SYSCTL_MAX_PRESSURE:
3996                 if (arg < 0 || arg > 255)
3997                         return (EINVAL);
3998                 break;
3999         case SYNAPTICS_SYSCTL_MAX_WIDTH:
4000                 if (arg < 4 || arg > 15)
4001                         return (EINVAL);
4002                 break;
4003         case SYNAPTICS_SYSCTL_MARGIN_TOP:
4004         case SYNAPTICS_SYSCTL_MARGIN_RIGHT:
4005         case SYNAPTICS_SYSCTL_MARGIN_BOTTOM:
4006         case SYNAPTICS_SYSCTL_MARGIN_LEFT:
4007         case SYNAPTICS_SYSCTL_NA_TOP:
4008         case SYNAPTICS_SYSCTL_NA_RIGHT:
4009         case SYNAPTICS_SYSCTL_NA_BOTTOM:
4010         case SYNAPTICS_SYSCTL_NA_LEFT:
4011                 if (arg < 0 || arg > 6143)
4012                         return (EINVAL);
4013                 break;
4014         case SYNAPTICS_SYSCTL_WINDOW_MIN:
4015         case SYNAPTICS_SYSCTL_WINDOW_MAX:
4016         case SYNAPTICS_SYSCTL_TAP_MIN_QUEUE:
4017                 if (arg < 1 || arg > SYNAPTICS_PACKETQUEUE)
4018                         return (EINVAL);
4019                 break;
4020         case SYNAPTICS_SYSCTL_MULTIPLICATOR:
4021         case SYNAPTICS_SYSCTL_WEIGHT_CURRENT:
4022         case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS:
4023         case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA:
4024         case SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED:
4025         case SYNAPTICS_SYSCTL_DIV_MIN:
4026         case SYNAPTICS_SYSCTL_DIV_MAX:
4027         case SYNAPTICS_SYSCTL_DIV_MAX_NA:
4028         case SYNAPTICS_SYSCTL_DIV_LEN:
4029         case SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN:
4030         case SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX:
4031                 if (arg < 1)
4032                         return (EINVAL);
4033                 break;
4034         case SYNAPTICS_SYSCTL_TAP_MAX_DELTA:
4035         case SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT:
4036         case SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA:
4037                 if (arg < 0)
4038                         return (EINVAL);
4039                 break;
4040         case SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA:
4041         case SYNAPTICS_SYSCTL_VSCROLL_VER_AREA:
4042                 if (arg < -6143 || arg > 6143)
4043                         return (EINVAL);
4044                 break;
4045         default:
4046                 return (EINVAL);
4047         }
4048
4049         /* Update. */
4050         *(int *)oidp->oid_arg1 = arg;
4051
4052         return (error);
4053 }
4054
4055 static void
4056 synaptics_sysctl_create_tree(struct psm_softc *sc)
4057 {
4058
4059         if (sc->syninfo.sysctl_tree != NULL)
4060                 return;
4061
4062         /* Attach extra synaptics sysctl nodes under hw.psm.synaptics */
4063         sysctl_ctx_init(&sc->syninfo.sysctl_ctx);
4064         sc->syninfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->syninfo.sysctl_ctx,
4065             SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "synaptics", CTLFLAG_RD,
4066             0, "Synaptics TouchPad");
4067
4068         /* hw.psm.synaptics.directional_scrolls. */
4069         sc->syninfo.directional_scrolls = 1;
4070         SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
4071             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4072             "directional_scrolls", CTLFLAG_RW|CTLFLAG_ANYBODY,
4073             &sc->syninfo.directional_scrolls, 0,
4074             "Enable hardware scrolling pad (if non-zero) or register it as "
4075             "a middle-click (if 0)");
4076
4077         /* hw.psm.synaptics.min_pressure. */
4078         sc->syninfo.min_pressure = 16;
4079         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4080             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4081             "min_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4082             &sc->syninfo.min_pressure, SYNAPTICS_SYSCTL_MIN_PRESSURE,
4083             synaptics_sysctl, "I",
4084             "Minimum pressure required to start an action");
4085
4086         /* hw.psm.synaptics.max_pressure. */
4087         sc->syninfo.max_pressure = 220;
4088         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4089             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4090             "max_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4091             &sc->syninfo.max_pressure, SYNAPTICS_SYSCTL_MAX_PRESSURE,
4092             synaptics_sysctl, "I",
4093             "Maximum pressure to detect palm");
4094
4095         /* hw.psm.synaptics.max_width. */
4096         sc->syninfo.max_width = 10;
4097         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4098             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4099             "max_width", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4100             &sc->syninfo.max_width, SYNAPTICS_SYSCTL_MAX_WIDTH,
4101             synaptics_sysctl, "I",
4102             "Maximum finger width to detect palm");
4103
4104         /* hw.psm.synaptics.top_margin. */
4105         sc->syninfo.margin_top = 200;
4106         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4107             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4108             "margin_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4109             &sc->syninfo.margin_top, SYNAPTICS_SYSCTL_MARGIN_TOP,
4110             synaptics_sysctl, "I",
4111             "Top margin");
4112
4113         /* hw.psm.synaptics.right_margin. */
4114         sc->syninfo.margin_right = 200;
4115         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4116             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4117             "margin_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4118             &sc->syninfo.margin_right, SYNAPTICS_SYSCTL_MARGIN_RIGHT,
4119             synaptics_sysctl, "I",
4120             "Right margin");
4121
4122         /* hw.psm.synaptics.bottom_margin. */
4123         sc->syninfo.margin_bottom = 200;
4124         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4125             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4126             "margin_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4127             &sc->syninfo.margin_bottom, SYNAPTICS_SYSCTL_MARGIN_BOTTOM,
4128             synaptics_sysctl, "I",
4129             "Bottom margin");
4130
4131         /* hw.psm.synaptics.left_margin. */
4132         sc->syninfo.margin_left = 200;
4133         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4134             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4135             "margin_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4136             &sc->syninfo.margin_left, SYNAPTICS_SYSCTL_MARGIN_LEFT,
4137             synaptics_sysctl, "I",
4138             "Left margin");
4139
4140         /* hw.psm.synaptics.na_top. */
4141         sc->syninfo.na_top = 1783;
4142         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4143             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4144             "na_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4145             &sc->syninfo.na_top, SYNAPTICS_SYSCTL_NA_TOP,
4146             synaptics_sysctl, "I",
4147             "Top noisy area, where weight_previous_na is used instead "
4148             "of weight_previous");
4149
4150         /* hw.psm.synaptics.na_right. */
4151         sc->syninfo.na_right = 563;
4152         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4153             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4154             "na_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4155             &sc->syninfo.na_right, SYNAPTICS_SYSCTL_NA_RIGHT,
4156             synaptics_sysctl, "I",
4157             "Right noisy area, where weight_previous_na is used instead "
4158             "of weight_previous");
4159
4160         /* hw.psm.synaptics.na_bottom. */
4161         sc->syninfo.na_bottom = 1408;
4162         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4163             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4164             "na_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4165             &sc->syninfo.na_bottom, SYNAPTICS_SYSCTL_NA_BOTTOM,
4166             synaptics_sysctl, "I",
4167             "Bottom noisy area, where weight_previous_na is used instead "
4168             "of weight_previous");
4169
4170         /* hw.psm.synaptics.na_left. */
4171         sc->syninfo.na_left = 1600;
4172         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4173             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4174             "na_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4175             &sc->syninfo.na_left, SYNAPTICS_SYSCTL_NA_LEFT,
4176             synaptics_sysctl, "I",
4177             "Left noisy area, where weight_previous_na is used instead "
4178             "of weight_previous");
4179
4180         /* hw.psm.synaptics.window_min. */
4181         sc->syninfo.window_min = 4;
4182         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4183             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4184             "window_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4185             &sc->syninfo.window_min, SYNAPTICS_SYSCTL_WINDOW_MIN,
4186             synaptics_sysctl, "I",
4187             "Minimum window size to start an action");
4188
4189         /* hw.psm.synaptics.window_max. */
4190         sc->syninfo.window_max = 10;
4191         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4192             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4193             "window_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4194             &sc->syninfo.window_max, SYNAPTICS_SYSCTL_WINDOW_MAX,
4195             synaptics_sysctl, "I",
4196             "Maximum window size");
4197
4198         /* hw.psm.synaptics.multiplicator. */
4199         sc->syninfo.multiplicator = 10000;
4200         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4201             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4202             "multiplicator", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4203             &sc->syninfo.multiplicator, SYNAPTICS_SYSCTL_MULTIPLICATOR,
4204             synaptics_sysctl, "I",
4205             "Multiplicator to increase precision in averages and divisions");
4206
4207         /* hw.psm.synaptics.weight_current. */
4208         sc->syninfo.weight_current = 3;
4209         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4210             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4211             "weight_current", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4212             &sc->syninfo.weight_current, SYNAPTICS_SYSCTL_WEIGHT_CURRENT,
4213             synaptics_sysctl, "I",
4214             "Weight of the current movement in the new average");
4215
4216         /* hw.psm.synaptics.weight_previous. */
4217         sc->syninfo.weight_previous = 6;
4218         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4219             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4220             "weight_previous", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4221             &sc->syninfo.weight_previous, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS,
4222             synaptics_sysctl, "I",
4223             "Weight of the previous average");
4224
4225         /* hw.psm.synaptics.weight_previous_na. */
4226         sc->syninfo.weight_previous_na = 20;
4227         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4228             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4229             "weight_previous_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4230             &sc->syninfo.weight_previous_na,
4231             SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA,
4232             synaptics_sysctl, "I",
4233             "Weight of the previous average (inside the noisy area)");
4234
4235         /* hw.psm.synaptics.weight_len_squared. */
4236         sc->syninfo.weight_len_squared = 2000;
4237         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4238             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4239             "weight_len_squared", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4240             &sc->syninfo.weight_len_squared,
4241             SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED,
4242             synaptics_sysctl, "I",
4243             "Length (squared) of segments where weight_previous "
4244             "starts to decrease");
4245
4246         /* hw.psm.synaptics.div_min. */
4247         sc->syninfo.div_min = 9;
4248         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4249             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4250             "div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4251             &sc->syninfo.div_min, SYNAPTICS_SYSCTL_DIV_MIN,
4252             synaptics_sysctl, "I",
4253             "Divisor for fast movements");
4254
4255         /* hw.psm.synaptics.div_max. */
4256         sc->syninfo.div_max = 17;
4257         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4258             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4259             "div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4260             &sc->syninfo.div_max, SYNAPTICS_SYSCTL_DIV_MAX,
4261             synaptics_sysctl, "I",
4262             "Divisor for slow movements");
4263
4264         /* hw.psm.synaptics.div_max_na. */
4265         sc->syninfo.div_max_na = 30;
4266         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4267             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4268             "div_max_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4269             &sc->syninfo.div_max_na, SYNAPTICS_SYSCTL_DIV_MAX_NA,
4270             synaptics_sysctl, "I",
4271             "Divisor with slow movements (inside the noisy area)");
4272
4273         /* hw.psm.synaptics.div_len. */
4274         sc->syninfo.div_len = 100;
4275         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4276             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4277             "div_len", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4278             &sc->syninfo.div_len, SYNAPTICS_SYSCTL_DIV_LEN,
4279             synaptics_sysctl, "I",
4280             "Length of segments where div_max starts to decrease");
4281
4282         /* hw.psm.synaptics.tap_max_delta. */
4283         sc->syninfo.tap_max_delta = 80;
4284         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4285             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4286             "tap_max_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4287             &sc->syninfo.tap_max_delta, SYNAPTICS_SYSCTL_TAP_MAX_DELTA,
4288             synaptics_sysctl, "I",
4289             "Length of segments above which a tap is ignored");
4290
4291         /* hw.psm.synaptics.tap_min_queue. */
4292         sc->syninfo.tap_min_queue = 2;
4293         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4294             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4295             "tap_min_queue", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4296             &sc->syninfo.tap_min_queue, SYNAPTICS_SYSCTL_TAP_MIN_QUEUE,
4297             synaptics_sysctl, "I",
4298             "Number of packets required to consider a tap");
4299
4300         /* hw.psm.synaptics.taphold_timeout. */
4301         sc->synaction.in_taphold = 0;
4302         sc->syninfo.taphold_timeout = tap_timeout;
4303         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4304             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4305             "taphold_timeout", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4306             &sc->syninfo.taphold_timeout, SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT,
4307             synaptics_sysctl, "I",
4308             "Maximum elapsed time between two taps to consider a tap-hold "
4309             "action");
4310
4311         /* hw.psm.synaptics.vscroll_hor_area. */
4312         sc->syninfo.vscroll_hor_area = 0; /* 1300 */
4313         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4314             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4315             "vscroll_hor_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4316             &sc->syninfo.vscroll_hor_area, SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA,
4317             synaptics_sysctl, "I",
4318             "Area reserved for horizontal virtual scrolling");
4319
4320         /* hw.psm.synaptics.vscroll_ver_area. */
4321         sc->syninfo.vscroll_ver_area = -600;
4322         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4323             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4324             "vscroll_ver_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4325             &sc->syninfo.vscroll_ver_area, SYNAPTICS_SYSCTL_VSCROLL_VER_AREA,
4326             synaptics_sysctl, "I",
4327             "Area reserved for vertical virtual scrolling");
4328
4329         /* hw.psm.synaptics.vscroll_min_delta. */
4330         sc->syninfo.vscroll_min_delta = 50;
4331         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4332             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4333             "vscroll_min_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4334             &sc->syninfo.vscroll_min_delta,
4335             SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA,
4336             synaptics_sysctl, "I",
4337             "Minimum movement to consider virtual scrolling");
4338
4339         /* hw.psm.synaptics.vscroll_div_min. */
4340         sc->syninfo.vscroll_div_min = 100;
4341         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4342             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4343             "vscroll_div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4344             &sc->syninfo.vscroll_div_min, SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN,
4345             synaptics_sysctl, "I",
4346             "Divisor for fast scrolling");
4347
4348         /* hw.psm.synaptics.vscroll_div_min. */
4349         sc->syninfo.vscroll_div_max = 150;
4350         SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx,
4351             SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO,
4352             "vscroll_div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4353             &sc->syninfo.vscroll_div_max, SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX,
4354             synaptics_sysctl, "I",
4355             "Divisor for slow scrolling");
4356 }
4357
4358 static int
4359 enable_synaptics(KBDC kbdc, struct psm_softc *sc)
4360 {
4361         synapticshw_t synhw;
4362         int status[3];
4363         int buttons;
4364
4365         VLOG(3, (LOG_DEBUG, "synaptics: BEGIN init\n"));
4366
4367         /*
4368          * Just to be on the safe side: this avoids troubles with
4369          * following mouse_ext_command() when the previous command
4370          * was PSMC_SET_RESOLUTION. Set Scaling has no effect on
4371          * Synaptics Touchpad behaviour.
4372          */
4373         set_mouse_scaling(kbdc, 1);
4374
4375         /* Identify the Touchpad version. */
4376         if (mouse_ext_command(kbdc, 0) == 0)
4377                 return (FALSE);
4378         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4379                 return (FALSE);
4380         if (status[1] != 0x47)
4381                 return (FALSE);
4382
4383         bzero(&synhw, sizeof(synhw));
4384         synhw.infoMinor = status[0];
4385         synhw.infoMajor = status[2] & 0x0f;
4386
4387         if (verbose >= 2)
4388                 printf("Synaptics Touchpad v%d.%d\n", synhw.infoMajor,
4389                     synhw.infoMinor);
4390
4391         if (synhw.infoMajor < 4) {
4392                 printf("  Unsupported (pre-v4) Touchpad detected\n");
4393                 return (FALSE);
4394         }
4395
4396         /* Get the Touchpad model information. */
4397         if (mouse_ext_command(kbdc, 3) == 0)
4398                 return (FALSE);
4399         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4400                 return (FALSE);
4401         if ((status[1] & 0x01) != 0) {
4402                 printf("  Failed to read model information\n");
4403                 return (FALSE);
4404         }
4405
4406         synhw.infoRot180   = (status[0] & 0x80) != 0;
4407         synhw.infoPortrait = (status[0] & 0x40) != 0;
4408         synhw.infoSensor   =  status[0] & 0x3f;
4409         synhw.infoHardware = (status[1] & 0xfe) >> 1;
4410         synhw.infoNewAbs   = (status[2] & 0x80) != 0;
4411         synhw.capPen       = (status[2] & 0x40) != 0;
4412         synhw.infoSimplC   = (status[2] & 0x20) != 0;
4413         synhw.infoGeometry =  status[2] & 0x0f;
4414
4415         if (verbose >= 2) {
4416                 printf("  Model information:\n");
4417                 printf("   infoRot180: %d\n", synhw.infoRot180);
4418                 printf("   infoPortrait: %d\n", synhw.infoPortrait);
4419                 printf("   infoSensor: %d\n", synhw.infoSensor);
4420                 printf("   infoHardware: %d\n", synhw.infoHardware);
4421                 printf("   infoNewAbs: %d\n", synhw.infoNewAbs);
4422                 printf("   capPen: %d\n", synhw.capPen);
4423                 printf("   infoSimplC: %d\n", synhw.infoSimplC);
4424                 printf("   infoGeometry: %d\n", synhw.infoGeometry);
4425         }
4426
4427         /* Read the extended capability bits. */
4428         if (mouse_ext_command(kbdc, 2) == 0)
4429                 return (FALSE);
4430         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4431                 return (FALSE);
4432         if (!SYNAPTICS_VERSION_GE(synhw, 7, 5) && status[1] != 0x47) {
4433                 printf("  Failed to read extended capability bits\n");
4434                 return (FALSE);
4435         }
4436
4437         /* Set the different capabilities when they exist. */
4438         buttons = 0;
4439         synhw.capExtended = (status[0] & 0x80) != 0;
4440         if (synhw.capExtended) {
4441                 synhw.capPassthrough = (status[2] & 0x80) != 0;
4442                 synhw.capSleep       = (status[2] & 0x10) != 0;
4443                 synhw.capFourButtons = (status[2] & 0x08) != 0;
4444                 synhw.capMultiFinger = (status[2] & 0x02) != 0;
4445                 synhw.capPalmDetect  = (status[2] & 0x01) != 0;
4446
4447                 if (verbose >= 2) {
4448                         printf("  Extended capabilities:\n");
4449                         printf("   capExtended: %d\n", synhw.capExtended);
4450                         printf("   capPassthrough: %d\n", synhw.capPassthrough);
4451                         printf("   capSleep: %d\n", synhw.capSleep);
4452                         printf("   capFourButtons: %d\n", synhw.capFourButtons);
4453                         printf("   capMultiFinger: %d\n", synhw.capMultiFinger);
4454                         printf("   capPalmDetect: %d\n", synhw.capPalmDetect);
4455                 }
4456
4457                 /*
4458                  * If we have bits set in status[0] & 0x70, then we can load
4459                  * more information about buttons using query 0x09.
4460                  */
4461                 if ((status[0] & 0x70) != 0) {
4462                         if (mouse_ext_command(kbdc, 0x09) == 0)
4463                                 return (FALSE);
4464                         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4465                                 return (FALSE);
4466                         buttons = (status[1] & 0xf0) >> 4;
4467                 } else
4468                         buttons = synhw.capFourButtons ? 1 : 0;
4469         }
4470         if (verbose >= 2) {
4471                 if (synhw.capExtended)
4472                         printf("  Additional Buttons: %d\n", buttons);
4473                 else
4474                         printf("  No extended capabilities\n");
4475         }
4476
4477         /*
4478          * Read the mode byte.
4479          *
4480          * XXX: Note the Synaptics documentation also defines the first
4481          * byte of the response to this query to be a constant 0x3b, this
4482          * does not appear to be true for Touchpads with guest devices.
4483          */
4484         if (mouse_ext_command(kbdc, 1) == 0)
4485                 return (FALSE);
4486         if (get_mouse_status(kbdc, status, 0, 3) != 3)
4487                 return (FALSE);
4488         if (!SYNAPTICS_VERSION_GE(synhw, 7, 5) && status[1] != 0x47) {
4489                 printf("  Failed to read mode byte\n");
4490                 return (FALSE);
4491         }
4492
4493         if (sc != NULL)
4494                 sc->synhw = synhw;
4495         if (!synaptics_support)
4496                 return (FALSE);
4497
4498         /* Set the mode byte; request wmode where available. */
4499         mouse_ext_command(kbdc, synhw.capExtended ? 0xc1 : 0xc0);
4500
4501         /* "Commit" the Set Mode Byte command sent above. */
4502         set_mouse_sampling_rate(kbdc, 20);
4503
4504         buttons += 3;
4505         VLOG(3, (LOG_DEBUG, "synaptics: END init (%d buttons)\n", buttons));
4506
4507         if (sc != NULL) {
4508                 /* Create sysctl tree. */
4509                 synaptics_sysctl_create_tree(sc);
4510
4511                 sc->hw.buttons = buttons;
4512         }
4513
4514         return (TRUE);
4515 }
4516
4517 /* IBM/Lenovo TrackPoint */
4518 static int
4519 trackpoint_command(KBDC kbdc, int cmd, int loc, int val)
4520 {
4521         const int seq[] = { 0xe2, cmd, loc, val };
4522         int i;
4523
4524         for (i = 0; i < nitems(seq); i++)
4525                 if (send_aux_command(kbdc, seq[i]) != PSM_ACK)
4526                         return (EIO);
4527         return (0);
4528 }
4529
4530 #define PSM_TPINFO(x)   offsetof(struct psm_softc, tpinfo.x)
4531 #define TPMASK          0
4532 #define TPLOC           1
4533 #define TPINFO          2
4534
4535 static int
4536 trackpoint_sysctl(SYSCTL_HANDLER_ARGS)
4537 {
4538         static const int data[][3] = {
4539                 { 0x00, 0x4a, PSM_TPINFO(sensitivity) },
4540                 { 0x00, 0x4d, PSM_TPINFO(inertia) },
4541                 { 0x00, 0x60, PSM_TPINFO(uplateau) },
4542                 { 0x00, 0x57, PSM_TPINFO(reach) },
4543                 { 0x00, 0x58, PSM_TPINFO(draghys) },
4544                 { 0x00, 0x59, PSM_TPINFO(mindrag) },
4545                 { 0x00, 0x5a, PSM_TPINFO(upthresh) },
4546                 { 0x00, 0x5c, PSM_TPINFO(threshold) },
4547                 { 0x00, 0x5d, PSM_TPINFO(jenks) },
4548                 { 0x00, 0x5e, PSM_TPINFO(ztime) },
4549                 { 0x01, 0x2c, PSM_TPINFO(pts) },
4550                 { 0x08, 0x2d, PSM_TPINFO(skipback) }
4551         };
4552         struct psm_softc *sc;
4553         int error, newval, *oldvalp;
4554         const int *tp;
4555
4556         if (arg1 == NULL || arg2 < 0 || arg2 >= nitems(data))
4557                 return (EINVAL);
4558         sc = arg1;
4559         tp = data[arg2];
4560         oldvalp = (int *)((intptr_t)sc + tp[TPINFO]);
4561         newval = *oldvalp;
4562         error = sysctl_handle_int(oidp, &newval, 0, req);
4563         if (error != 0)
4564                 return (error);
4565         if (newval == *oldvalp)
4566                 return (0);
4567         if (newval < 0 || newval > (tp[TPMASK] == 0 ? 255 : 1))
4568                 return (EINVAL);
4569         error = trackpoint_command(sc->kbdc, tp[TPMASK] == 0 ? 0x81 : 0x47,
4570             tp[TPLOC], tp[TPMASK] == 0 ? newval : tp[TPMASK]);
4571         if (error != 0)
4572                 return (error);
4573         *oldvalp = newval;
4574
4575         return (0);
4576 }
4577
4578 static void
4579 trackpoint_sysctl_create_tree(struct psm_softc *sc)
4580 {
4581
4582         if (sc->tpinfo.sysctl_tree != NULL)
4583                 return;
4584
4585         /* Attach extra trackpoint sysctl nodes under hw.psm.trackpoint */
4586         sysctl_ctx_init(&sc->tpinfo.sysctl_ctx);
4587         sc->tpinfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->tpinfo.sysctl_ctx,
4588             SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "trackpoint", CTLFLAG_RD,
4589             0, "IBM/Lenovo TrackPoint");
4590
4591         /* hw.psm.trackpoint.sensitivity */
4592         sc->tpinfo.sensitivity = 0x64;
4593         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4594             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4595             "sensitivity", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4596             sc, TRACKPOINT_SYSCTL_SENSITIVITY,
4597             trackpoint_sysctl, "I",
4598             "Sensitivity");
4599
4600         /* hw.psm.trackpoint.negative_inertia */
4601         sc->tpinfo.inertia = 0x06;
4602         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4603             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4604             "negative_inertia", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4605             sc, TRACKPOINT_SYSCTL_NEGATIVE_INERTIA,
4606             trackpoint_sysctl, "I",
4607             "Negative inertia factor");
4608
4609         /* hw.psm.trackpoint.upper_plateau */
4610         sc->tpinfo.uplateau = 0x61;
4611         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4612             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4613             "upper_plateau", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4614             sc, TRACKPOINT_SYSCTL_UPPER_PLATEAU,
4615             trackpoint_sysctl, "I",
4616             "Transfer function upper plateau speed");
4617
4618         /* hw.psm.trackpoint.backup_range */
4619         sc->tpinfo.reach = 0x0a;
4620         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4621             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4622             "backup_range", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4623             sc, TRACKPOINT_SYSCTL_BACKUP_RANGE,
4624             trackpoint_sysctl, "I",
4625             "Backup range");
4626
4627         /* hw.psm.trackpoint.drag_hysteresis */
4628         sc->tpinfo.draghys = 0xff;
4629         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4630             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4631             "drag_hysteresis", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4632             sc, TRACKPOINT_SYSCTL_DRAG_HYSTERESIS,
4633             trackpoint_sysctl, "I",
4634             "Drag hysteresis");
4635
4636         /* hw.psm.trackpoint.minimum_drag */
4637         sc->tpinfo.mindrag = 0x14;
4638         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4639             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4640             "minimum_drag", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4641             sc, TRACKPOINT_SYSCTL_MINIMUM_DRAG,
4642             trackpoint_sysctl, "I",
4643             "Minimum drag");
4644
4645         /* hw.psm.trackpoint.up_threshold */
4646         sc->tpinfo.upthresh = 0xff;
4647         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4648             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4649             "up_threshold", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4650             sc, TRACKPOINT_SYSCTL_UP_THRESHOLD,
4651             trackpoint_sysctl, "I",
4652             "Up threshold for release");
4653
4654         /* hw.psm.trackpoint.threshold */
4655         sc->tpinfo.threshold = 0x08;
4656         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4657             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4658             "threshold", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4659             sc, TRACKPOINT_SYSCTL_THRESHOLD,
4660             trackpoint_sysctl, "I",
4661             "Threshold");
4662
4663         /* hw.psm.trackpoint.jenks_curvature */
4664         sc->tpinfo.jenks = 0x87;
4665         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4666             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4667             "jenks_curvature", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4668             sc, TRACKPOINT_SYSCTL_JENKS_CURVATURE,
4669             trackpoint_sysctl, "I",
4670             "Jenks curvature");
4671
4672         /* hw.psm.trackpoint.z_time */
4673         sc->tpinfo.ztime = 0x26;
4674         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4675             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4676             "z_time", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4677             sc, TRACKPOINT_SYSCTL_Z_TIME,
4678             trackpoint_sysctl, "I",
4679             "Z time constant");
4680
4681         /* hw.psm.trackpoint.press_to_select */
4682         sc->tpinfo.pts = 0x00;
4683         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4684             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4685             "press_to_select", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4686             sc, TRACKPOINT_SYSCTL_PRESS_TO_SELECT,
4687             trackpoint_sysctl, "I",
4688             "Press to Select");
4689
4690         /* hw.psm.trackpoint.skip_backups */
4691         sc->tpinfo.skipback = 0x00;
4692         SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx,
4693             SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO,
4694             "skip_backups", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY,
4695             sc, TRACKPOINT_SYSCTL_SKIP_BACKUPS,
4696             trackpoint_sysctl, "I",
4697             "Skip backups from drags");
4698 }
4699
4700 static int
4701 enable_trackpoint(KBDC kbdc, struct psm_softc *sc)
4702 {
4703         int id;
4704
4705         kbdc = sc->kbdc;
4706
4707         if (send_aux_command(kbdc, 0xe1) != PSM_ACK ||
4708             read_aux_data(kbdc) != 0x01)
4709                 return (FALSE);
4710         id = read_aux_data(kbdc);
4711         if (id < 0x01)
4712                 return (FALSE);
4713         if (sc != NULL)
4714                 sc->tphw = id;
4715         if (!trackpoint_support)
4716                 return (FALSE);
4717
4718         if (sc != NULL) {
4719                 /* Create sysctl tree. */
4720                 trackpoint_sysctl_create_tree(sc);
4721
4722                 trackpoint_command(kbdc, 0x81, 0x4a, sc->tpinfo.sensitivity);
4723                 trackpoint_command(kbdc, 0x81, 0x4d, sc->tpinfo.inertia);
4724                 trackpoint_command(kbdc, 0x81, 0x60, sc->tpinfo.uplateau);
4725                 trackpoint_command(kbdc, 0x81, 0x57, sc->tpinfo.reach);
4726                 trackpoint_command(kbdc, 0x81, 0x58, sc->tpinfo.draghys);
4727                 trackpoint_command(kbdc, 0x81, 0x59, sc->tpinfo.mindrag);
4728                 trackpoint_command(kbdc, 0x81, 0x5a, sc->tpinfo.upthresh);
4729                 trackpoint_command(kbdc, 0x81, 0x5c, sc->tpinfo.threshold);
4730                 trackpoint_command(kbdc, 0x81, 0x5d, sc->tpinfo.jenks);
4731                 trackpoint_command(kbdc, 0x81, 0x5e, sc->tpinfo.ztime);
4732                 if (sc->tpinfo.pts == 0x01)
4733                         trackpoint_command(kbdc, 0x47, 0x2c, 0x01);
4734                 if (sc->tpinfo.skipback == 0x01)
4735                         trackpoint_command(kbdc, 0x47, 0x2d, 0x08);
4736
4737                 sc->hw.hwid = id;
4738                 sc->hw.buttons = 3;
4739         }
4740
4741         return (TRUE);
4742 }
4743
4744 /* Interlink electronics VersaPad */
4745 static int
4746 enable_versapad(KBDC kbdc, struct psm_softc *sc)
4747 {
4748         int data[3];
4749
4750         set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
4751         set_mouse_sampling_rate(kbdc, 100);             /* set rate 100 */
4752         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4753         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4754         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4755         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4756         if (get_mouse_status(kbdc, data, 0, 3) < 3)     /* get status */
4757                 return (FALSE);
4758         if (data[2] != 0xa || data[1] != 0 )    /* rate == 0xa && res. == 0 */
4759                 return (FALSE);
4760         set_mouse_scaling(kbdc, 1);                     /* set scale 1:1 */
4761
4762         return (TRUE);                          /* PS/2 absolute mode */
4763 }
4764
4765 /*
4766  * Return true if 'now' is earlier than (start + (secs.usecs)).
4767  * Now may be NULL and the function will fetch the current time from
4768  * getmicrouptime(), or a cached 'now' can be passed in.
4769  * All values should be numbers derived from getmicrouptime().
4770  */
4771 static int
4772 timeelapsed(start, secs, usecs, now)
4773         const struct timeval *start, *now;
4774         int secs, usecs;
4775 {
4776         struct timeval snow, tv;
4777
4778         /* if there is no 'now' passed in, the get it as a convience. */
4779         if (now == NULL) {
4780                 getmicrouptime(&snow);
4781                 now = &snow;
4782         }
4783
4784         tv.tv_sec = secs;
4785         tv.tv_usec = usecs;
4786         timevaladd(&tv, start);
4787         return (timevalcmp(&tv, now, <));
4788 }
4789
4790 static int
4791 psmresume(device_t dev)
4792 {
4793         struct psm_softc *sc = device_get_softc(dev);
4794         int unit = device_get_unit(dev);
4795         int err;
4796
4797         VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit));
4798
4799         if ((sc->config &
4800             (PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND)) == 0)
4801                 return (0);
4802
4803         err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
4804
4805         if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
4806                 /*
4807                  * Release the blocked process; it must be notified that
4808                  * the device cannot be accessed anymore.
4809                  */
4810                 sc->state &= ~PSM_ASLP;
4811                 wakeup(sc);
4812         }
4813
4814         VLOG(2, (LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit));
4815
4816         return (err);
4817 }
4818
4819 DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
4820
4821 #ifdef DEV_ISA
4822
4823 /*
4824  * This sucks up assignments from PNPBIOS and ACPI.
4825  */
4826
4827 /*
4828  * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
4829  * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
4830  * can be probed and attached only after the AT keyboard controller is
4831  * attached, we shall quietly reserve the IRQ resource for later use.
4832  * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
4833  * copy the IRQ resource to the PS/2 mouse device instance hanging
4834  * under the keyboard controller, then probe and attach it.
4835  */
4836
4837 static  devclass_t                      psmcpnp_devclass;
4838
4839 static  device_probe_t                  psmcpnp_probe;
4840 static  device_attach_t                 psmcpnp_attach;
4841
4842 static device_method_t psmcpnp_methods[] = {
4843         DEVMETHOD(device_probe,         psmcpnp_probe),
4844         DEVMETHOD(device_attach,        psmcpnp_attach),
4845
4846         { 0, 0 }
4847 };
4848
4849 static driver_t psmcpnp_driver = {
4850         PSMCPNP_DRIVER_NAME,
4851         psmcpnp_methods,
4852         1,                      /* no softc */
4853 };
4854
4855 static struct isa_pnp_id psmcpnp_ids[] = {
4856         { 0x030fd041, "PS/2 mouse port" },              /* PNP0F03 */
4857         { 0x0e0fd041, "PS/2 mouse port" },              /* PNP0F0E */
4858         { 0x120fd041, "PS/2 mouse port" },              /* PNP0F12 */
4859         { 0x130fd041, "PS/2 mouse port" },              /* PNP0F13 */
4860         { 0x1303d041, "PS/2 port" },                    /* PNP0313, XXX */
4861         { 0x02002e4f, "Dell PS/2 mouse port" },         /* Lat. X200, Dell */
4862         { 0x0002a906, "ALPS Glide Point" },             /* ALPS Glide Point */
4863         { 0x80374d24, "IBM PS/2 mouse port" },          /* IBM3780, ThinkPad */
4864         { 0x81374d24, "IBM PS/2 mouse port" },          /* IBM3781, ThinkPad */
4865         { 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
4866         { 0x0290d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9002, Vaio */
4867         { 0x0390d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9003, Vaio */
4868         { 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
4869         { 0 }
4870 };
4871
4872 static int
4873 create_a_copy(device_t atkbdc, device_t me)
4874 {
4875         device_t psm;
4876         u_long irq;
4877
4878         /* find the PS/2 mouse device instance under the keyboard controller */
4879         psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
4880             device_get_unit(atkbdc));
4881         if (psm == NULL)
4882                 return (ENXIO);
4883         if (device_get_state(psm) != DS_NOTPRESENT)
4884                 return (0);
4885
4886         /* move our resource to the found device */
4887         irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
4888         bus_delete_resource(me, SYS_RES_IRQ, 0);
4889         bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
4890
4891         /* ...then probe and attach it */
4892         return (device_probe_and_attach(psm));
4893 }
4894
4895 static int
4896 psmcpnp_probe(device_t dev)
4897 {
4898         struct resource *res;
4899         u_long irq;
4900         int rid;
4901
4902         if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids))
4903                 return (ENXIO);
4904
4905         /*
4906          * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
4907          * to the PS/2 mouse device node. But, some buggy PnP BIOS
4908          * declares the PS/2 mouse device node without an IRQ resource!
4909          * If this happens, we shall refer to device hints.
4910          * If we still don't find it there, use a hardcoded value... XXX
4911          */
4912         rid = 0;
4913         irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
4914         if (irq <= 0) {
4915                 if (resource_long_value(PSM_DRIVER_NAME,
4916                     device_get_unit(dev),"irq", &irq) != 0)
4917                         irq = 12;       /* XXX */
4918                 device_printf(dev, "irq resource info is missing; "
4919                     "assuming irq %ld\n", irq);
4920                 bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
4921         }
4922         res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, 0);
4923         bus_release_resource(dev, SYS_RES_IRQ, rid, res);
4924
4925         /* keep quiet */
4926         if (!bootverbose)
4927                 device_quiet(dev);
4928
4929         return ((res == NULL) ? ENXIO : 0);
4930 }
4931
4932 static int
4933 psmcpnp_attach(device_t dev)
4934 {
4935         device_t atkbdc;
4936
4937         /* find the keyboard controller, which may be on acpi* or isa* bus */
4938         atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
4939             device_get_unit(dev));
4940         if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED))
4941                 create_a_copy(atkbdc, dev);
4942
4943         return (0);
4944 }
4945
4946 DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
4947 DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
4948
4949 #endif /* DEV_ISA */