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