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