The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/dev/atkbdc/psm.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: 5992e06810decea38d14ac5107ff1f8b


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.