psm.c revision 178017
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: head/sys/dev/atkbdc/psm.c 178017 2008-04-08 17:55:26Z jkim $");
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/poll.h>
74#include <sys/syslog.h>
75#include <machine/bus.h>
76#include <sys/rman.h>
77#include <sys/selinfo.h>
78#include <sys/sysctl.h>
79#include <sys/time.h>
80#include <sys/uio.h>
81
82#include <sys/limits.h>
83#include <sys/mouse.h>
84#include <machine/resource.h>
85
86#ifdef DEV_ISA
87#include <isa/isavar.h>
88#endif
89
90#include <dev/atkbdc/atkbdcreg.h>
91#include <dev/atkbdc/psm.h>
92
93/*
94 * Driver specific options: the following options may be set by
95 * `options' statements in the kernel configuration file.
96 */
97
98/* debugging */
99#ifndef PSM_DEBUG
100#define PSM_DEBUG	0	/*
101				 * logging: 0: none, 1: brief, 2: verbose
102				 *          3: sync errors, 4: all packets
103				 */
104#endif
105#define VLOG(level, args) 	\
106do {				\
107	if (verbose >= level)	\
108		log args;	\
109} while (0)
110
111#ifndef PSM_INPUT_TIMEOUT
112#define PSM_INPUT_TIMEOUT	2000000	/* 2 sec */
113#endif
114
115#ifndef PSM_TAP_TIMEOUT
116#define PSM_TAP_TIMEOUT		125000
117#endif
118
119#ifndef PSM_TAP_THRESHOLD
120#define PSM_TAP_THRESHOLD	25
121#endif
122
123/* end of driver specific options */
124
125#define PSMCPNP_DRIVER_NAME	"psmcpnp"
126
127/* input queue */
128#define PSM_BUFSIZE		960
129#define PSM_SMALLBUFSIZE	240
130
131/* operation levels */
132#define PSM_LEVEL_BASE		0
133#define PSM_LEVEL_STANDARD	1
134#define PSM_LEVEL_NATIVE	2
135#define PSM_LEVEL_MIN		PSM_LEVEL_BASE
136#define PSM_LEVEL_MAX		PSM_LEVEL_NATIVE
137
138/* Logitech PS2++ protocol */
139#define MOUSE_PS2PLUS_CHECKBITS(b)	\
140				((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
141#define MOUSE_PS2PLUS_PACKET_TYPE(b)	\
142				(((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
143
144/* some macros */
145#define PSM_UNIT(dev)		(minor(dev) >> 1)
146#define PSM_NBLOCKIO(dev)	(minor(dev) & 1)
147#define PSM_MKMINOR(unit,block)	(((unit) << 1) | ((block) ? 0:1))
148
149/* ring buffer */
150typedef struct ringbuf {
151    int           count;	/* # of valid elements in the buffer */
152    int           head;		/* head pointer */
153    int           tail;		/* tail poiner */
154    unsigned char buf[PSM_BUFSIZE];
155} ringbuf_t;
156
157/* data buffer */
158typedef struct packetbuf {
159    unsigned char ipacket[16];	/* interim input buffer */
160    int           inputbytes;	/* # of bytes in the input buffer */
161} packetbuf_t;
162
163#ifndef PSM_PACKETQUEUE
164#define PSM_PACKETQUEUE	128
165#endif
166
167typedef struct synapticsinfo {
168    struct sysctl_ctx_list	sysctl_ctx;
169    struct sysctl_oid		*sysctl_tree;
170    int				directional_scrolls;
171    int				low_speed_threshold;
172    int				min_movement;
173    int				squelch_level;
174} synapticsinfo_t;
175
176/* driver control block */
177struct psm_softc {		/* Driver status information */
178    int		  unit;
179    struct selinfo rsel;	/* Process selecting for Input */
180    unsigned char state;	/* Mouse driver state */
181    int           config;	/* driver configuration flags */
182    int           flags;	/* other flags */
183    KBDC          kbdc;		/* handle to access the keyboard controller */
184    struct resource *intr;	/* IRQ resource */
185    void	  *ih;		/* interrupt handle */
186    mousehw_t     hw;		/* hardware information */
187    synapticshw_t synhw;	/* Synaptics-specific hardware information */
188    synapticsinfo_t syninfo;	/* Synaptics-specific configuration */
189    mousemode_t   mode;		/* operation mode */
190    mousemode_t   dflt_mode;	/* default operation mode */
191    mousestatus_t status;	/* accumulated mouse movement */
192    ringbuf_t     queue;	/* mouse status queue */
193    packetbuf_t   pqueue[PSM_PACKETQUEUE];	/* mouse data queue */
194    int           pqueue_start; /* start of data in queue */
195    int           pqueue_end;   /* end of data in queue */
196    int           button;	/* the latest button state */
197    int		  xold;		/* previous absolute X position */
198    int		  yold;		/* previous absolute Y position */
199    int		  xaverage;	/* average X position */
200    int		  yaverage;	/* average Y position */
201    int		  squelch;	/* level to filter movement data at low speed */
202    int		  zmax;		/* maximum pressure value for touchpads */
203    int		  syncerrors;	/* # of bytes discarded searching for sync */
204    int		  pkterrors;	/* # of packets failed during quaranteen. */
205    struct timeval inputtimeout;
206    struct timeval lastsoftintr;	/* time of last soft interrupt */
207    struct timeval lastinputerr;	/* time last sync error happened */
208    struct timeval taptimeout;		/* tap timeout for touchpads */
209    int		  watchdog;		/* watchdog timer flag */
210    struct callout_handle callout;	/* watchdog timer call out */
211    struct callout_handle softcallout;	/* buffer timer call out */
212    struct cdev *dev;
213    struct cdev *bdev;
214    int           lasterr;
215    int           cmdcount;
216};
217static devclass_t psm_devclass;
218#define PSM_SOFTC(unit)	((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
219
220/* driver state flags (state) */
221#define PSM_VALID		0x80
222#define PSM_OPEN		1	/* Device is open */
223#define PSM_ASLP		2	/* Waiting for mouse data */
224#define PSM_SOFTARMED		4	/* Software interrupt armed */
225#define PSM_NEED_SYNCBITS	8	/* Set syncbits using next data pkt */
226
227/* driver configuration flags (config) */
228#define PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
229#define PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
230#define PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
231#define PSM_CONFIG_NOIDPROBE	0x0200  /* disable mouse model probe */
232#define PSM_CONFIG_NORESET	0x0400  /* don't reset the mouse */
233#define PSM_CONFIG_FORCETAP	0x0800  /* assume `tap' action exists */
234#define PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
235#define PSM_CONFIG_HOOKRESUME	0x2000	/* hook the system resume event */
236#define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
237#define PSM_CONFIG_SYNCHACK	0x8000 /* enable `out-of-sync' hack */
238
239#define PSM_CONFIG_FLAGS	(PSM_CONFIG_RESOLUTION 		\
240				    | PSM_CONFIG_ACCEL		\
241				    | PSM_CONFIG_NOCHECKSYNC	\
242				    | PSM_CONFIG_SYNCHACK	\
243				    | PSM_CONFIG_NOIDPROBE	\
244				    | PSM_CONFIG_NORESET	\
245				    | PSM_CONFIG_FORCETAP	\
246				    | PSM_CONFIG_IGNPORTERROR	\
247				    | PSM_CONFIG_HOOKRESUME	\
248				    | PSM_CONFIG_INITAFTERSUSPEND)
249
250/* other flags (flags) */
251#define PSM_FLAGS_FINGERDOWN	0x0001 /* VersaPad finger down */
252
253/* Tunables */
254static int synaptics_support = 0;
255TUNABLE_INT("hw.psm.synaptics_support", &synaptics_support);
256
257static int verbose = PSM_DEBUG;
258TUNABLE_INT("debug.psm.loglevel", &verbose);
259
260/* for backward compatibility */
261#define OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
262#define OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
263#define OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)
264
265typedef struct old_mousehw {
266    int buttons;
267    int iftype;
268    int type;
269    int hwid;
270} old_mousehw_t;
271
272typedef struct old_mousemode {
273    int protocol;
274    int rate;
275    int resolution;
276    int accelfactor;
277} old_mousemode_t;
278
279/* packet formatting function */
280typedef int packetfunc_t(struct psm_softc *, unsigned char *,
281			      int *, int, mousestatus_t *);
282
283/* function prototypes */
284static void psmidentify(driver_t *, device_t);
285static int psmprobe(device_t);
286static int psmattach(device_t);
287static int psmdetach(device_t);
288static int psmresume(device_t);
289
290static d_open_t psmopen;
291static d_close_t psmclose;
292static d_read_t psmread;
293static d_write_t psmwrite;
294static d_ioctl_t psmioctl;
295static d_poll_t psmpoll;
296
297static int enable_aux_dev(KBDC);
298static int disable_aux_dev(KBDC);
299static int get_mouse_status(KBDC, int *, int, int);
300static int get_aux_id(KBDC);
301static int set_mouse_sampling_rate(KBDC, int);
302static int set_mouse_scaling(KBDC, int);
303static int set_mouse_resolution(KBDC, int);
304static int set_mouse_mode(KBDC);
305static int get_mouse_buttons(KBDC);
306static int is_a_mouse(int);
307static void recover_from_error(KBDC);
308static int restore_controller(KBDC, int);
309static int doinitialize(struct psm_softc *, mousemode_t *);
310static int doopen(struct psm_softc *, int);
311static int reinitialize(struct psm_softc *, int);
312static char *model_name(int);
313static void psmsoftintr(void *);
314static void psmintr(void *);
315static void psmtimeout(void *);
316static int timeelapsed(const struct timeval *,
317    int, int, const struct timeval *);
318static void dropqueue(struct psm_softc *);
319static void flushpackets(struct psm_softc *);
320
321/* vendor specific features */
322typedef int probefunc_t(struct psm_softc *);
323
324static int mouse_id_proc1(KBDC, int, int, int *);
325static int mouse_ext_command(KBDC, int);
326static probefunc_t enable_groller;
327static probefunc_t enable_gmouse;
328static probefunc_t enable_aglide;
329static probefunc_t enable_kmouse;
330static probefunc_t enable_msexplorer;
331static probefunc_t enable_msintelli;
332static probefunc_t enable_4dmouse;
333static probefunc_t enable_4dplus;
334static probefunc_t enable_mmanplus;
335static probefunc_t enable_synaptics;
336static probefunc_t enable_versapad;
337static int tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *, unsigned char *);
338
339static struct {
340    int                 model;
341    unsigned char	syncmask;
342    int 		packetsize;
343    probefunc_t 	*probefunc;
344} vendortype[] = {
345    /*
346     * WARNING: the order of probe is very important.  Don't mess it
347     * unless you know what you are doing.
348     */
349    { MOUSE_MODEL_NET,			/* Genius NetMouse */
350      0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse, },
351    { MOUSE_MODEL_NETSCROLL,		/* Genius NetScroll */
352      0xc8, 6, enable_groller, },
353    { MOUSE_MODEL_MOUSEMANPLUS,		/* Logitech MouseMan+ */
354      0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus, },
355    { MOUSE_MODEL_EXPLORER,		/* Microsoft IntelliMouse Explorer */
356      0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer, },
357    { MOUSE_MODEL_4D,			/* A4 Tech 4D Mouse */
358      0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse, },
359    { MOUSE_MODEL_4DPLUS,		/* A4 Tech 4D+ Mouse */
360      0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus, },
361    { MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
362      0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli, },
363    { MOUSE_MODEL_GLIDEPOINT,		/* ALPS GlidePoint */
364      0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide, },
365    { MOUSE_MODEL_THINK,		/* Kensington ThinkingMouse */
366      0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse, },
367    { MOUSE_MODEL_VERSAPAD,		/* Interlink electronics VersaPad */
368      0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad, },
369    { MOUSE_MODEL_SYNAPTICS,		/* Synaptics Touchpad */
370      0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics, },
371    { MOUSE_MODEL_GENERIC,
372      0xc0, MOUSE_PS2_PACKETSIZE, NULL, },
373};
374#define GENERIC_MOUSE_ENTRY	((sizeof(vendortype) / sizeof(*vendortype)) - 1)
375
376/* device driver declarateion */
377static device_method_t psm_methods[] = {
378	/* Device interface */
379	DEVMETHOD(device_identify,	psmidentify),
380	DEVMETHOD(device_probe,		psmprobe),
381	DEVMETHOD(device_attach,	psmattach),
382	DEVMETHOD(device_detach,	psmdetach),
383	DEVMETHOD(device_resume,	psmresume),
384
385	{ 0, 0 }
386};
387
388static driver_t psm_driver = {
389    PSM_DRIVER_NAME,
390    psm_methods,
391    sizeof(struct psm_softc),
392};
393
394
395static struct cdevsw psm_cdevsw = {
396	.d_version =	D_VERSION,
397	.d_flags =	D_NEEDGIANT,
398	.d_open =	psmopen,
399	.d_close =	psmclose,
400	.d_read =	psmread,
401	.d_write =	psmwrite,
402	.d_ioctl =	psmioctl,
403	.d_poll =	psmpoll,
404	.d_name =	PSM_DRIVER_NAME,
405};
406
407/* device I/O routines */
408static int
409enable_aux_dev(KBDC kbdc)
410{
411    int res;
412
413    res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
414    VLOG(2, (LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res));
415
416    return (res == PSM_ACK);
417}
418
419static int
420disable_aux_dev(KBDC kbdc)
421{
422    int res;
423
424    res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
425    VLOG(2, (LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res));
426
427    return (res == PSM_ACK);
428}
429
430static int
431get_mouse_status(KBDC kbdc, int *status, int flag, int len)
432{
433    int cmd;
434    int res;
435    int i;
436
437    switch (flag) {
438    case 0:
439    default:
440	cmd = PSMC_SEND_DEV_STATUS;
441	break;
442    case 1:
443	cmd = PSMC_SEND_DEV_DATA;
444	break;
445    }
446    empty_aux_buffer(kbdc, 5);
447    res = send_aux_command(kbdc, cmd);
448    VLOG(2, (LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
449	 (flag == 1) ? "DATA" : "STATUS", res));
450    if (res != PSM_ACK)
451        return 0;
452
453    for (i = 0; i < len; ++i) {
454        status[i] = read_aux_data(kbdc);
455	if (status[i] < 0)
456	    break;
457    }
458
459    VLOG(1, (LOG_DEBUG, "psm: %s %02x %02x %02x\n",
460         (flag == 1) ? "data" : "status", status[0], status[1], status[2]));
461
462    return i;
463}
464
465static int
466get_aux_id(KBDC kbdc)
467{
468    int res;
469    int id;
470
471    empty_aux_buffer(kbdc, 5);
472    res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
473    VLOG(2, (LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res));
474    if (res != PSM_ACK)
475	return (-1);
476
477    /* 10ms delay */
478    DELAY(10000);
479
480    id = read_aux_data(kbdc);
481    VLOG(2, (LOG_DEBUG, "psm: device ID: %04x\n", id));
482
483    return id;
484}
485
486static int
487set_mouse_sampling_rate(KBDC kbdc, int rate)
488{
489    int res;
490
491    res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
492    VLOG(2, (LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res));
493
494    return ((res == PSM_ACK) ? rate : -1);
495}
496
497static int
498set_mouse_scaling(KBDC kbdc, int scale)
499{
500    int res;
501
502    switch (scale) {
503    case 1:
504    default:
505	scale = PSMC_SET_SCALING11;
506	break;
507    case 2:
508	scale = PSMC_SET_SCALING21;
509	break;
510    }
511    res = send_aux_command(kbdc, scale);
512    VLOG(2, (LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
513	 (scale == PSMC_SET_SCALING21) ? "21" : "11", res));
514
515    return (res == PSM_ACK);
516}
517
518/* `val' must be 0 through PSMD_MAX_RESOLUTION */
519static int
520set_mouse_resolution(KBDC kbdc, int val)
521{
522    int res;
523
524    res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
525    VLOG(2, (LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res));
526
527    return ((res == PSM_ACK) ? val : -1);
528}
529
530/*
531 * NOTE: once `set_mouse_mode()' is called, the mouse device must be
532 * re-enabled by calling `enable_aux_dev()'
533 */
534static int
535set_mouse_mode(KBDC kbdc)
536{
537    int res;
538
539    res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
540    VLOG(2, (LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res));
541
542    return (res == PSM_ACK);
543}
544
545static int
546get_mouse_buttons(KBDC kbdc)
547{
548    int c = 2;		/* assume two buttons by default */
549    int status[3];
550
551    /*
552     * NOTE: a special sequence to obtain Logitech Mouse specific
553     * information: set resolution to 25 ppi, set scaling to 1:1, set
554     * scaling to 1:1, set scaling to 1:1. Then the second byte of the
555     * mouse status bytes is the number of available buttons.
556     * Some manufactures also support this sequence.
557     */
558    if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
559        return c;
560    if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1)
561        && set_mouse_scaling(kbdc, 1)
562	&& (get_mouse_status(kbdc, status, 0, 3) >= 3)) {
563        if (status[1] != 0)
564            return status[1];
565    }
566    return c;
567}
568
569/* misc subroutines */
570/*
571 * Someday, I will get the complete list of valid pointing devices and
572 * their IDs... XXX
573 */
574static int
575is_a_mouse(int id)
576{
577#if 0
578    static int valid_ids[] = {
579        PSM_MOUSE_ID,		/* mouse */
580        PSM_BALLPOINT_ID,	/* ballpoint device */
581        PSM_INTELLI_ID,		/* Intellimouse */
582        PSM_EXPLORER_ID,	/* Intellimouse Explorer */
583        -1			/* end of table */
584    };
585    int i;
586
587    for (i = 0; valid_ids[i] >= 0; ++i)
588        if (valid_ids[i] == id)
589            return TRUE;
590    return FALSE;
591#else
592    return TRUE;
593#endif
594}
595
596static char *
597model_name(int model)
598{
599    static struct {
600	int model_code;
601	char *model_name;
602    } models[] = {
603        { MOUSE_MODEL_NETSCROLL,	"NetScroll" },
604        { MOUSE_MODEL_NET,		"NetMouse/NetScroll Optical" },
605        { MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
606        { MOUSE_MODEL_THINK,		"ThinkingMouse" },
607        { MOUSE_MODEL_INTELLI,		"IntelliMouse" },
608        { MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
609        { MOUSE_MODEL_VERSAPAD,		"VersaPad" },
610        { MOUSE_MODEL_EXPLORER,		"IntelliMouse Explorer" },
611        { MOUSE_MODEL_4D,		"4D Mouse" },
612        { MOUSE_MODEL_4DPLUS,		"4D+ Mouse" },
613        { MOUSE_MODEL_SYNAPTICS,	"Synaptics Touchpad" },
614        { MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
615        { MOUSE_MODEL_UNKNOWN,		NULL },
616    };
617    int i;
618
619    for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i) {
620	if (models[i].model_code == model)
621	    return models[i].model_name;
622    }
623    return "Unknown";
624}
625
626static void
627recover_from_error(KBDC kbdc)
628{
629    /* discard anything left in the output buffer */
630    empty_both_buffers(kbdc, 10);
631
632#if 0
633    /*
634     * NOTE: KBDC_RESET_KBD may not restore the communication between the
635     * keyboard and the controller.
636     */
637    reset_kbd(kbdc);
638#else
639    /*
640     * NOTE: somehow diagnostic and keyboard port test commands bring the
641     * keyboard back.
642     */
643    if (!test_controller(kbdc))
644        log(LOG_ERR, "psm: keyboard controller failed.\n");
645    /* if there isn't a keyboard in the system, the following error is OK */
646    if (test_kbd_port(kbdc) != 0)
647	VLOG(1, (LOG_ERR, "psm: keyboard port failed.\n"));
648#endif
649}
650
651static int
652restore_controller(KBDC kbdc, int command_byte)
653{
654    empty_both_buffers(kbdc, 10);
655
656    if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
657	log(LOG_ERR, "psm: failed to restore the keyboard controller "
658		     "command byte.\n");
659	empty_both_buffers(kbdc, 10);
660	return FALSE;
661    } else {
662	empty_both_buffers(kbdc, 10);
663	return TRUE;
664    }
665}
666
667/*
668 * Re-initialize the aux port and device. The aux port must be enabled
669 * and its interrupt must be disabled before calling this routine.
670 * The aux device will be disabled before returning.
671 * The keyboard controller must be locked via `kbdc_lock()' before
672 * calling this routine.
673 */
674static int
675doinitialize(struct psm_softc *sc, mousemode_t *mode)
676{
677    KBDC kbdc = sc->kbdc;
678    int stat[3];
679    int i;
680
681    switch((i = test_aux_port(kbdc))) {
682    case 1:	/* ignore these errors */
683    case 2:
684    case 3:
685    case PSM_ACK:
686	if (verbose)
687	    log(LOG_DEBUG, "psm%d: strange result for test aux port (%d).\n",
688	        sc->unit, i);
689	/* FALLTHROUGH */
690    case 0:	/* no error */
691    	break;
692    case -1: 	/* time out */
693    default: 	/* error */
694    	recover_from_error(kbdc);
695	if (sc->config & PSM_CONFIG_IGNPORTERROR)
696	    break;
697    	log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
698    	    sc->unit, i);
699    	return FALSE;
700    }
701
702    if (sc->config & PSM_CONFIG_NORESET) {
703	/*
704	 * Don't try to reset the pointing device.  It may possibly be
705	 * left in the unknown state, though...
706	 */
707    } else {
708	/*
709	 * NOTE: some controllers appears to hang the `keyboard' when
710	 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
711	 */
712	if (!reset_aux_dev(kbdc)) {
713            recover_from_error(kbdc);
714            log(LOG_ERR, "psm%d: failed to reset the aux device.\n", sc->unit);
715            return FALSE;
716	}
717    }
718
719    /*
720     * both the aux port and the aux device is functioning, see
721     * if the device can be enabled.
722     */
723    if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
724        log(LOG_ERR, "psm%d: failed to enable the aux device.\n", sc->unit);
725        return FALSE;
726    }
727    empty_both_buffers(kbdc, 10);	/* remove stray data if any */
728
729    if (sc->config & PSM_CONFIG_NOIDPROBE) {
730	i = GENERIC_MOUSE_ENTRY;
731    } else {
732	/* FIXME: hardware ID, mouse buttons? */
733
734	/* other parameters */
735	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
736	    if ((*vendortype[i].probefunc)(sc)) {
737		if (verbose >= 2)
738		    log(LOG_ERR, "psm%d: found %s\n",
739			sc->unit, model_name(vendortype[i].model));
740		break;
741	    }
742	}
743    }
744
745    sc->hw.model = vendortype[i].model;
746    sc->mode.packetsize = vendortype[i].packetsize;
747
748    /* set mouse parameters */
749    if (mode != (mousemode_t *)NULL) {
750	if (mode->rate > 0)
751            mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
752	if (mode->resolution >= 0)
753            mode->resolution = set_mouse_resolution(kbdc, mode->resolution);
754        set_mouse_scaling(kbdc, 1);
755        set_mouse_mode(kbdc);
756    }
757
758    /* Record sync on the next data packet we see. */
759    sc->flags |= PSM_NEED_SYNCBITS;
760
761    /* just check the status of the mouse */
762    if (get_mouse_status(kbdc, stat, 0, 3) < 3)
763        log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
764	    sc->unit);
765
766    return TRUE;
767}
768
769static int
770doopen(struct psm_softc *sc, int command_byte)
771{
772    int stat[3];
773
774    /* enable the mouse device */
775    if (!enable_aux_dev(sc->kbdc)) {
776	/* MOUSE ERROR: failed to enable the mouse because:
777	 * 1) the mouse is faulty,
778	 * 2) the mouse has been removed(!?)
779	 * In the latter case, the keyboard may have hung, and need
780	 * recovery procedure...
781	 */
782	recover_from_error(sc->kbdc);
783#if 0
784	/* FIXME: we could reset the mouse here and try to enable
785	 * it again. But it will take long time and it's not a good
786	 * idea to disable the keyboard that long...
787	 */
788	if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
789	    recover_from_error(sc->kbdc);
790#else
791        {
792#endif
793            restore_controller(sc->kbdc, command_byte);
794	    /* mark this device is no longer available */
795	    sc->state &= ~PSM_VALID;
796	    log(LOG_ERR, "psm%d: failed to enable the device (doopen).\n",
797		sc->unit);
798	    return (EIO);
799	}
800    }
801
802    if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
803        log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n", sc->unit);
804
805    /* enable the aux port and interrupt */
806    if (!set_controller_command_byte(sc->kbdc,
807	    kbdc_get_device_mask(sc->kbdc),
808	    (command_byte & KBD_KBD_CONTROL_BITS)
809		| KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
810	/* CONTROLLER ERROR */
811	disable_aux_dev(sc->kbdc);
812        restore_controller(sc->kbdc, command_byte);
813	log(LOG_ERR, "psm%d: failed to enable the aux interrupt (doopen).\n",
814	    sc->unit);
815	return (EIO);
816    }
817
818    /* start the watchdog timer */
819    sc->watchdog = FALSE;
820    sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz*2);
821
822    return (0);
823}
824
825static int
826reinitialize(struct psm_softc *sc, int doinit)
827{
828    int err;
829    int c;
830    int s;
831
832    /* don't let anybody mess with the aux device */
833    if (!kbdc_lock(sc->kbdc, TRUE))
834	return (EIO);
835    s = spltty();
836
837    /* block our watchdog timer */
838    sc->watchdog = FALSE;
839    untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
840    callout_handle_init(&sc->callout);
841
842    /* save the current controller command byte */
843    empty_both_buffers(sc->kbdc, 10);
844    c = get_controller_command_byte(sc->kbdc);
845    VLOG(2, (LOG_DEBUG, "psm%d: current command byte: %04x (reinitialize).\n",
846	 sc->unit, c));
847
848    /* enable the aux port but disable the aux interrupt and the keyboard */
849    if ((c == -1) || !set_controller_command_byte(sc->kbdc,
850	    kbdc_get_device_mask(sc->kbdc),
851  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
852	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
853        /* CONTROLLER ERROR */
854	splx(s);
855        kbdc_lock(sc->kbdc, FALSE);
856	log(LOG_ERR, "psm%d: unable to set the command byte (reinitialize).\n",
857	    sc->unit);
858	return (EIO);
859    }
860
861    /* flush any data */
862    if (sc->state & PSM_VALID) {
863	disable_aux_dev(sc->kbdc);	/* this may fail; but never mind... */
864	empty_aux_buffer(sc->kbdc, 10);
865    }
866    flushpackets(sc);
867    sc->syncerrors = 0;
868    sc->pkterrors = 0;
869    memset(&sc->lastinputerr, 0, sizeof(sc->lastinputerr));
870
871    /* try to detect the aux device; are you still there? */
872    err = 0;
873    if (doinit) {
874	if (doinitialize(sc, &sc->mode)) {
875	    /* yes */
876	    sc->state |= PSM_VALID;
877	} else {
878	    /* the device has gone! */
879	    restore_controller(sc->kbdc, c);
880	    sc->state &= ~PSM_VALID;
881	    log(LOG_ERR, "psm%d: the aux device has gone! (reinitialize).\n",
882		sc->unit);
883	    err = ENXIO;
884	}
885    }
886    splx(s);
887
888    /* restore the driver state */
889    if ((sc->state & PSM_OPEN) && (err == 0)) {
890        /* enable the aux device and the port again */
891	err = doopen(sc, c);
892	if (err != 0)
893	    log(LOG_ERR, "psm%d: failed to enable the device (reinitialize).\n",
894		sc->unit);
895    } else {
896        /* restore the keyboard port and disable the aux port */
897        if (!set_controller_command_byte(sc->kbdc,
898                kbdc_get_device_mask(sc->kbdc),
899                (c & KBD_KBD_CONTROL_BITS)
900                    | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
901            /* CONTROLLER ERROR */
902            log(LOG_ERR,
903                "psm%d: failed to disable the aux port (reinitialize).\n",
904                sc->unit);
905            err = EIO;
906	}
907    }
908
909    kbdc_lock(sc->kbdc, FALSE);
910    return (err);
911}
912
913/* psm driver entry points */
914
915static void
916psmidentify(driver_t *driver, device_t parent)
917{
918    device_t psmc;
919    device_t psm;
920    u_long irq;
921    int unit;
922
923    unit = device_get_unit(parent);
924
925    /* always add at least one child */
926    psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
927    if (psm == NULL)
928	return;
929
930    irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
931    if (irq > 0)
932	return;
933
934    /*
935     * If the PS/2 mouse device has already been reported by ACPI or
936     * PnP BIOS, obtain the IRQ resource from it.
937     * (See psmcpnp_attach() below.)
938     */
939    psmc = device_find_child(device_get_parent(parent),
940			     PSMCPNP_DRIVER_NAME, unit);
941    if (psmc == NULL)
942	return;
943    irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
944    if (irq <= 0)
945	return;
946    bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
947}
948
949#define endprobe(v)	do {   if (bootverbose)				\
950				--verbose;   				\
951                            kbdc_set_device_mask(sc->kbdc, mask);	\
952			    kbdc_lock(sc->kbdc, FALSE);			\
953			    return (v);	     				\
954			} while (0)
955
956static int
957psmprobe(device_t dev)
958{
959    int unit = device_get_unit(dev);
960    struct psm_softc *sc = device_get_softc(dev);
961    int stat[3];
962    int command_byte;
963    int mask;
964    int rid;
965    int i;
966
967#if 0
968    kbdc_debug(TRUE);
969#endif
970
971    /* see if IRQ is available */
972    rid = KBDC_RID_AUX;
973    sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
974				      RF_SHAREABLE | RF_ACTIVE);
975    if (sc->intr == NULL) {
976	if (bootverbose)
977            device_printf(dev, "unable to allocate IRQ\n");
978        return (ENXIO);
979    }
980    bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
981
982    sc->unit = unit;
983    sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
984    sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
985    /* XXX: for backward compatibility */
986#if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
987    sc->config |=
988#ifdef PSM_RESETAFTERSUSPEND
989	PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
990#else
991	PSM_CONFIG_HOOKRESUME;
992#endif
993#endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
994    sc->flags = 0;
995    if (bootverbose)
996        ++verbose;
997
998    device_set_desc(dev, "PS/2 Mouse");
999
1000    if (!kbdc_lock(sc->kbdc, TRUE)) {
1001        printf("psm%d: unable to lock the controller.\n", unit);
1002        if (bootverbose)
1003            --verbose;
1004	return (ENXIO);
1005    }
1006
1007    /*
1008     * NOTE: two bits in the command byte controls the operation of the
1009     * aux port (mouse port): the aux port disable bit (bit 5) and the aux
1010     * port interrupt (IRQ 12) enable bit (bit 2).
1011     */
1012
1013    /* discard anything left after the keyboard initialization */
1014    empty_both_buffers(sc->kbdc, 10);
1015
1016    /* save the current command byte; it will be used later */
1017    mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
1018    command_byte = get_controller_command_byte(sc->kbdc);
1019    if (verbose)
1020        printf("psm%d: current command byte:%04x\n", unit, command_byte);
1021    if (command_byte == -1) {
1022        /* CONTROLLER ERROR */
1023        printf("psm%d: unable to get the current command byte value.\n",
1024            unit);
1025        endprobe(ENXIO);
1026    }
1027
1028    /*
1029     * disable the keyboard port while probing the aux port, which must be
1030     * enabled during this routine
1031     */
1032    if (!set_controller_command_byte(sc->kbdc,
1033	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1034  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1035                | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1036        /*
1037	 * this is CONTROLLER ERROR; I don't know how to recover
1038         * from this error...
1039	 */
1040        restore_controller(sc->kbdc, command_byte);
1041        printf("psm%d: unable to set the command byte.\n", unit);
1042        endprobe(ENXIO);
1043    }
1044    write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
1045
1046    /*
1047     * NOTE: `test_aux_port()' is designed to return with zero if the aux
1048     * port exists and is functioning. However, some controllers appears
1049     * to respond with zero even when the aux port doesn't exist. (It may
1050     * be that this is only the case when the controller DOES have the aux
1051     * port but the port is not wired on the motherboard.) The keyboard
1052     * controllers without the port, such as the original AT, are
1053     * supporsed to return with an error code or simply time out. In any
1054     * case, we have to continue probing the port even when the controller
1055     * passes this test.
1056     *
1057     * XXX: some controllers erroneously return the error code 1, 2 or 3
1058     * when it has the perfectly functional aux port. We have to ignore
1059     * this error code. Even if the controller HAS error with the aux
1060     * port, it will be detected later...
1061     * XXX: another incompatible controller returns PSM_ACK (0xfa)...
1062     */
1063    switch ((i = test_aux_port(sc->kbdc))) {
1064    case 1:	   /* ignore these errors */
1065    case 2:
1066    case 3:
1067    case PSM_ACK:
1068        if (verbose)
1069	    printf("psm%d: strange result for test aux port (%d).\n",
1070	        unit, i);
1071	/* FALLTHROUGH */
1072    case 0:        /* no error */
1073        break;
1074    case -1:        /* time out */
1075    default:        /* error */
1076        recover_from_error(sc->kbdc);
1077	if (sc->config & PSM_CONFIG_IGNPORTERROR)
1078	    break;
1079        restore_controller(sc->kbdc, command_byte);
1080        if (verbose)
1081            printf("psm%d: the aux port is not functioning (%d).\n",
1082                unit, i);
1083        endprobe(ENXIO);
1084    }
1085
1086    if (sc->config & PSM_CONFIG_NORESET) {
1087	/*
1088	 * Don't try to reset the pointing device.  It may possibly be
1089	 * left in the unknown state, though...
1090	 */
1091    } else {
1092	/*
1093	 * NOTE: some controllers appears to hang the `keyboard' when the aux
1094	 * port doesn't exist and `PSMC_RESET_DEV' is issued.
1095	 *
1096	 * Attempt to reset the controller twice -- this helps
1097	 * pierce through some KVM switches. The second reset
1098	 * is non-fatal.
1099	 */
1100	if (!reset_aux_dev(sc->kbdc)) {
1101            recover_from_error(sc->kbdc);
1102            restore_controller(sc->kbdc, command_byte);
1103            if (verbose)
1104        	printf("psm%d: failed to reset the aux device.\n", unit);
1105            endprobe(ENXIO);
1106	} else if (!reset_aux_dev(sc->kbdc)) {
1107	    recover_from_error(sc->kbdc);
1108	    if (verbose >= 2)
1109        	printf("psm%d: failed to reset the aux device (2).\n",
1110        	    unit);
1111	}
1112    }
1113
1114    /*
1115     * both the aux port and the aux device is functioning, see if the
1116     * device can be enabled. NOTE: when enabled, the device will start
1117     * sending data; we shall immediately disable the device once we know
1118     * the device can be enabled.
1119     */
1120    if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1121        /* MOUSE ERROR */
1122	recover_from_error(sc->kbdc);
1123	restore_controller(sc->kbdc, command_byte);
1124	if (verbose)
1125	    printf("psm%d: failed to enable the aux device.\n", unit);
1126        endprobe(ENXIO);
1127    }
1128
1129    /* save the default values after reset */
1130    if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1131	sc->dflt_mode.rate = sc->mode.rate = stat[2];
1132	sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1133    } else {
1134	sc->dflt_mode.rate = sc->mode.rate = -1;
1135	sc->dflt_mode.resolution = sc->mode.resolution = -1;
1136    }
1137
1138    /* hardware information */
1139    sc->hw.iftype = MOUSE_IF_PS2;
1140
1141    /* verify the device is a mouse */
1142    sc->hw.hwid = get_aux_id(sc->kbdc);
1143    if (!is_a_mouse(sc->hw.hwid)) {
1144        restore_controller(sc->kbdc, command_byte);
1145        if (verbose)
1146            printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid);
1147        endprobe(ENXIO);
1148    }
1149    switch (sc->hw.hwid) {
1150    case PSM_BALLPOINT_ID:
1151        sc->hw.type = MOUSE_TRACKBALL;
1152        break;
1153    case PSM_MOUSE_ID:
1154    case PSM_INTELLI_ID:
1155    case PSM_EXPLORER_ID:
1156    case PSM_4DMOUSE_ID:
1157    case PSM_4DPLUS_ID:
1158        sc->hw.type = MOUSE_MOUSE;
1159        break;
1160    default:
1161        sc->hw.type = MOUSE_UNKNOWN;
1162        break;
1163    }
1164
1165    if (sc->config & PSM_CONFIG_NOIDPROBE) {
1166	sc->hw.buttons = 2;
1167	i = GENERIC_MOUSE_ENTRY;
1168    } else {
1169	/* # of buttons */
1170	sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1171
1172	/* other parameters */
1173	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
1174	    if ((*vendortype[i].probefunc)(sc)) {
1175		if (verbose >= 2)
1176		    printf("psm%d: found %s\n",
1177			   unit, model_name(vendortype[i].model));
1178		break;
1179	    }
1180	}
1181    }
1182
1183    sc->hw.model = vendortype[i].model;
1184
1185    sc->dflt_mode.level = PSM_LEVEL_BASE;
1186    sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1187    sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1188    if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1189        sc->dflt_mode.syncmask[0] = 0;
1190    else
1191        sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1192    if (sc->config & PSM_CONFIG_FORCETAP)
1193        sc->dflt_mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1194    sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
1195    sc->mode = sc->dflt_mode;
1196    sc->mode.packetsize = vendortype[i].packetsize;
1197
1198    /* set mouse parameters */
1199#if 0
1200    /*
1201     * A version of Logitech FirstMouse+ won't report wheel movement,
1202     * if SET_DEFAULTS is sent...  Don't use this command.
1203     * This fix was found by Takashi Nishida.
1204     */
1205    i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1206    if (verbose >= 2)
1207	printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1208#endif
1209    if (sc->config & PSM_CONFIG_RESOLUTION) {
1210        sc->mode.resolution
1211	    = set_mouse_resolution(sc->kbdc,
1212				   (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1213    } else if (sc->mode.resolution >= 0) {
1214	sc->mode.resolution
1215	    = set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1216    }
1217    if (sc->mode.rate > 0) {
1218	sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1219    }
1220    set_mouse_scaling(sc->kbdc, 1);
1221
1222    /* Record sync on the next data packet we see. */
1223    sc->flags |= PSM_NEED_SYNCBITS;
1224
1225    /* just check the status of the mouse */
1226    /*
1227     * NOTE: XXX there are some arcane controller/mouse combinations out
1228     * there, which hung the controller unless there is data transmission
1229     * after ACK from the mouse.
1230     */
1231    if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) {
1232        printf("psm%d: failed to get status.\n", unit);
1233    } else {
1234	/*
1235	 * When in its native mode, some mice operate with different
1236	 * default parameters than in the PS/2 compatible mode.
1237	 */
1238        sc->dflt_mode.rate = sc->mode.rate = stat[2];
1239        sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1240     }
1241
1242    /* disable the aux port for now... */
1243    if (!set_controller_command_byte(sc->kbdc,
1244	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1245            (command_byte & KBD_KBD_CONTROL_BITS)
1246                | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1247        /*
1248	 * this is CONTROLLER ERROR; I don't know the proper way to
1249         * recover from this error...
1250	 */
1251        restore_controller(sc->kbdc, command_byte);
1252        printf("psm%d: unable to set the command byte.\n", unit);
1253        endprobe(ENXIO);
1254    }
1255
1256    /*
1257     * Synaptics TouchPad seems to go back to Relative Mode after
1258     * the previous set_controller_command_byte() call; by issueing
1259     * a Read Mode Byte command, the touchpad is in Absolute Mode
1260     * again.
1261     */
1262    if (sc->hw.model == MOUSE_MODEL_SYNAPTICS) {
1263        mouse_ext_command(sc->kbdc, 1);
1264    }
1265
1266    /* done */
1267    kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1268    kbdc_lock(sc->kbdc, FALSE);
1269    return (0);
1270}
1271
1272static int
1273psmattach(device_t dev)
1274{
1275    int unit = device_get_unit(dev);
1276    struct psm_softc *sc = device_get_softc(dev);
1277    int error;
1278    int rid;
1279
1280    /* Setup initial state */
1281    sc->state = PSM_VALID;
1282    callout_handle_init(&sc->callout);
1283
1284    /* Setup our interrupt handler */
1285    rid = KBDC_RID_AUX;
1286    sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1287				      RF_SHAREABLE | RF_ACTIVE);
1288    if (sc->intr == NULL)
1289	return (ENXIO);
1290    error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, NULL, psmintr, sc, &sc->ih);
1291    if (error) {
1292	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1293	return (error);
1294    }
1295
1296    /* Done */
1297    sc->dev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, FALSE), 0, 0, 0666,
1298		       "psm%d", unit);
1299    sc->bdev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, TRUE), 0, 0, 0666,
1300			"bpsm%d", unit);
1301
1302    if (!verbose) {
1303        printf("psm%d: model %s, device ID %d\n",
1304	    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1305    } else {
1306        printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1307	    unit, model_name(sc->hw.model),
1308	    sc->hw.hwid & 0x00ff, sc->hw.hwid >> 8, sc->hw.buttons);
1309	printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1310	    unit, sc->config, sc->flags, sc->mode.packetsize);
1311	printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1312	    unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1313    }
1314
1315    if (bootverbose)
1316        --verbose;
1317
1318    return (0);
1319}
1320
1321static int
1322psmdetach(device_t dev)
1323{
1324    struct psm_softc *sc;
1325    int rid;
1326
1327    sc = device_get_softc(dev);
1328    if (sc->state & PSM_OPEN)
1329	return EBUSY;
1330
1331    rid = KBDC_RID_AUX;
1332    bus_teardown_intr(dev, sc->intr, sc->ih);
1333    bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1334
1335    destroy_dev(sc->dev);
1336    destroy_dev(sc->bdev);
1337
1338    return 0;
1339}
1340
1341static int
1342psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
1343{
1344    int unit = PSM_UNIT(dev);
1345    struct psm_softc *sc;
1346    int command_byte;
1347    int err;
1348    int s;
1349
1350    /* Get device data */
1351    sc = PSM_SOFTC(unit);
1352    if ((sc == NULL) || (sc->state & PSM_VALID) == 0)
1353	/* the device is no longer valid/functioning */
1354        return (ENXIO);
1355
1356    /* Disallow multiple opens */
1357    if (sc->state & PSM_OPEN)
1358        return (EBUSY);
1359
1360    device_busy(devclass_get_device(psm_devclass, unit));
1361
1362    /* Initialize state */
1363    sc->mode.level = sc->dflt_mode.level;
1364    sc->mode.protocol = sc->dflt_mode.protocol;
1365    sc->watchdog = FALSE;
1366
1367    /* flush the event queue */
1368    sc->queue.count = 0;
1369    sc->queue.head = 0;
1370    sc->queue.tail = 0;
1371    sc->status.flags = 0;
1372    sc->status.button = 0;
1373    sc->status.obutton = 0;
1374    sc->status.dx = 0;
1375    sc->status.dy = 0;
1376    sc->status.dz = 0;
1377    sc->button = 0;
1378    sc->pqueue_start = 0;
1379    sc->pqueue_end = 0;
1380
1381    /* empty input buffer */
1382    flushpackets(sc);
1383    sc->syncerrors = 0;
1384    sc->pkterrors = 0;
1385
1386    /* don't let timeout routines in the keyboard driver to poll the kbdc */
1387    if (!kbdc_lock(sc->kbdc, TRUE))
1388	return (EIO);
1389
1390    /* save the current controller command byte */
1391    s = spltty();
1392    command_byte = get_controller_command_byte(sc->kbdc);
1393
1394    /* enable the aux port and temporalily disable the keyboard */
1395    if ((command_byte == -1)
1396        || !set_controller_command_byte(sc->kbdc,
1397	    kbdc_get_device_mask(sc->kbdc),
1398  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1399	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1400        /* CONTROLLER ERROR; do you know how to get out of this? */
1401        kbdc_lock(sc->kbdc, FALSE);
1402	splx(s);
1403	log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n",
1404	    unit);
1405	return (EIO);
1406    }
1407    /*
1408     * Now that the keyboard controller is told not to generate
1409     * the keyboard and mouse interrupts, call `splx()' to allow
1410     * the other tty interrupts. The clock interrupt may also occur,
1411     * but timeout routines will be blocked by the poll flag set
1412     * via `kbdc_lock()'
1413     */
1414    splx(s);
1415
1416    /* enable the mouse device */
1417    err = doopen(sc, command_byte);
1418
1419    /* done */
1420    if (err == 0)
1421        sc->state |= PSM_OPEN;
1422    kbdc_lock(sc->kbdc, FALSE);
1423    return (err);
1424}
1425
1426static int
1427psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
1428{
1429    int unit = PSM_UNIT(dev);
1430    struct psm_softc *sc = PSM_SOFTC(unit);
1431    int stat[3];
1432    int command_byte;
1433    int s;
1434
1435    /* don't let timeout routines in the keyboard driver to poll the kbdc */
1436    if (!kbdc_lock(sc->kbdc, TRUE))
1437	return (EIO);
1438
1439    /* save the current controller command byte */
1440    s = spltty();
1441    command_byte = get_controller_command_byte(sc->kbdc);
1442    if (command_byte == -1) {
1443        kbdc_lock(sc->kbdc, FALSE);
1444	splx(s);
1445	return (EIO);
1446    }
1447
1448    /* disable the aux interrupt and temporalily disable the keyboard */
1449    if (!set_controller_command_byte(sc->kbdc,
1450	    kbdc_get_device_mask(sc->kbdc),
1451  	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1452	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1453	log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n",
1454	    unit);
1455	/* CONTROLLER ERROR;
1456	 * NOTE: we shall force our way through. Because the only
1457	 * ill effect we shall see is that we may not be able
1458	 * to read ACK from the mouse, and it doesn't matter much
1459	 * so long as the mouse will accept the DISABLE command.
1460	 */
1461    }
1462    splx(s);
1463
1464    /* stop the watchdog timer */
1465    untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
1466    callout_handle_init(&sc->callout);
1467
1468    /* remove anything left in the output buffer */
1469    empty_aux_buffer(sc->kbdc, 10);
1470
1471    /* disable the aux device, port and interrupt */
1472    if (sc->state & PSM_VALID) {
1473        if (!disable_aux_dev(sc->kbdc)) {
1474	    /* MOUSE ERROR;
1475	     * NOTE: we don't return error and continue, pretending
1476	     * we have successfully disabled the device. It's OK because
1477	     * the interrupt routine will discard any data from the mouse
1478	     * hereafter.
1479	     */
1480	    log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n",
1481		unit);
1482        }
1483
1484        if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1485            log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n", unit);
1486    }
1487
1488    if (!set_controller_command_byte(sc->kbdc,
1489	    kbdc_get_device_mask(sc->kbdc),
1490	    (command_byte & KBD_KBD_CONTROL_BITS)
1491	        | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1492	/* CONTROLLER ERROR;
1493	 * we shall ignore this error; see the above comment.
1494	 */
1495	log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n",
1496	    unit);
1497    }
1498
1499    /* remove anything left in the output buffer */
1500    empty_aux_buffer(sc->kbdc, 10);
1501
1502    /* close is almost always successful */
1503    sc->state &= ~PSM_OPEN;
1504    kbdc_lock(sc->kbdc, FALSE);
1505    device_unbusy(devclass_get_device(psm_devclass, unit));
1506    return (0);
1507}
1508
1509static int
1510tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status, unsigned char *buf)
1511{
1512    static unsigned char butmapps2[8] = {
1513        0,
1514        MOUSE_PS2_BUTTON1DOWN,
1515        MOUSE_PS2_BUTTON2DOWN,
1516        MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1517        MOUSE_PS2_BUTTON3DOWN,
1518        MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1519        MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1520        MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1521    };
1522    static unsigned char butmapmsc[8] = {
1523        MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1524        MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1525        MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1526        MOUSE_MSC_BUTTON3UP,
1527        MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1528        MOUSE_MSC_BUTTON2UP,
1529        MOUSE_MSC_BUTTON1UP,
1530        0,
1531    };
1532    int mapped;
1533    int i;
1534
1535    if (sc->mode.level == PSM_LEVEL_BASE) {
1536        mapped = status->button & ~MOUSE_BUTTON4DOWN;
1537        if (status->button & MOUSE_BUTTON4DOWN)
1538	    mapped |= MOUSE_BUTTON1DOWN;
1539        status->button = mapped;
1540        buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1541        i = imax(imin(status->dx, 255), -256);
1542	if (i < 0)
1543	    buf[0] |= MOUSE_PS2_XNEG;
1544        buf[1] = i;
1545        i = imax(imin(status->dy, 255), -256);
1546	if (i < 0)
1547	    buf[0] |= MOUSE_PS2_YNEG;
1548        buf[2] = i;
1549	return MOUSE_PS2_PACKETSIZE;
1550    } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1551        buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS];
1552        i = imax(imin(status->dx, 255), -256);
1553        buf[1] = i >> 1;
1554        buf[3] = i - buf[1];
1555        i = imax(imin(status->dy, 255), -256);
1556        buf[2] = i >> 1;
1557        buf[4] = i - buf[2];
1558        i = imax(imin(status->dz, 127), -128);
1559        buf[5] = (i >> 1) & 0x7f;
1560        buf[6] = (i - (i >> 1)) & 0x7f;
1561        buf[7] = (~status->button >> 3) & 0x7f;
1562	return MOUSE_SYS_PACKETSIZE;
1563    }
1564    return pb->inputbytes;
1565}
1566
1567static int
1568psmread(struct cdev *dev, struct uio *uio, int flag)
1569{
1570    register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1571    unsigned char buf[PSM_SMALLBUFSIZE];
1572    int error = 0;
1573    int s;
1574    int l;
1575
1576    if ((sc->state & PSM_VALID) == 0)
1577	return EIO;
1578
1579    /* block until mouse activity occured */
1580    s = spltty();
1581    while (sc->queue.count <= 0) {
1582        if (PSM_NBLOCKIO(dev)) {
1583            splx(s);
1584            return EWOULDBLOCK;
1585        }
1586        sc->state |= PSM_ASLP;
1587        error = tsleep( sc, PZERO | PCATCH, "psmrea", 0);
1588        sc->state &= ~PSM_ASLP;
1589        if (error) {
1590            splx(s);
1591            return error;
1592        } else if ((sc->state & PSM_VALID) == 0) {
1593            /* the device disappeared! */
1594            splx(s);
1595            return EIO;
1596	}
1597    }
1598    splx(s);
1599
1600    /* copy data to the user land */
1601    while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1602        s = spltty();
1603	l = imin(sc->queue.count, uio->uio_resid);
1604	if (l > sizeof(buf))
1605	    l = sizeof(buf);
1606	if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1607	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1608		sizeof(sc->queue.buf) - sc->queue.head);
1609	    bcopy(&sc->queue.buf[0],
1610		&buf[sizeof(sc->queue.buf) - sc->queue.head],
1611		l - (sizeof(sc->queue.buf) - sc->queue.head));
1612	} else {
1613	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1614	}
1615	sc->queue.count -= l;
1616	sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1617        splx(s);
1618        error = uiomove(buf, l, uio);
1619        if (error)
1620	    break;
1621    }
1622
1623    return error;
1624}
1625
1626static int
1627block_mouse_data(struct psm_softc *sc, int *c)
1628{
1629    int s;
1630
1631    if (!kbdc_lock(sc->kbdc, TRUE))
1632	return EIO;
1633
1634    s = spltty();
1635    *c = get_controller_command_byte(sc->kbdc);
1636    if ((*c == -1)
1637	|| !set_controller_command_byte(sc->kbdc,
1638	    kbdc_get_device_mask(sc->kbdc),
1639            KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1640                | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1641        /* this is CONTROLLER ERROR */
1642	splx(s);
1643        kbdc_lock(sc->kbdc, FALSE);
1644	return EIO;
1645    }
1646
1647    /*
1648     * The device may be in the middle of status data transmission.
1649     * The transmission will be interrupted, thus, incomplete status
1650     * data must be discarded. Although the aux interrupt is disabled
1651     * at the keyboard controller level, at most one aux interrupt
1652     * may have already been pending and a data byte is in the
1653     * output buffer; throw it away. Note that the second argument
1654     * to `empty_aux_buffer()' is zero, so that the call will just
1655     * flush the internal queue.
1656     * `psmintr()' will be invoked after `splx()' if an interrupt is
1657     * pending; it will see no data and returns immediately.
1658     */
1659    empty_aux_buffer(sc->kbdc, 0);	/* flush the queue */
1660    read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
1661    flushpackets(sc);
1662    splx(s);
1663
1664    return 0;
1665}
1666
1667static void
1668dropqueue(struct psm_softc *sc)
1669{
1670
1671    	sc->queue.count = 0;
1672   	sc->queue.head = 0;
1673    	sc->queue.tail = 0;
1674	if ((sc->state & PSM_SOFTARMED) != 0) {
1675		sc->state &= ~PSM_SOFTARMED;
1676		untimeout(psmsoftintr, (void *)(uintptr_t)sc, sc->softcallout);
1677	}
1678	sc->pqueue_start = sc->pqueue_end;
1679}
1680
1681static void
1682flushpackets(struct psm_softc *sc)
1683{
1684
1685	dropqueue(sc);
1686	bzero(&sc->pqueue, sizeof(sc->pqueue));
1687}
1688
1689static int
1690unblock_mouse_data(struct psm_softc *sc, int c)
1691{
1692    int error = 0;
1693
1694    /*
1695     * We may have seen a part of status data during `set_mouse_XXX()'.
1696     * they have been queued; flush it.
1697     */
1698    empty_aux_buffer(sc->kbdc, 0);
1699
1700    /* restore ports and interrupt */
1701    if (!set_controller_command_byte(sc->kbdc,
1702            kbdc_get_device_mask(sc->kbdc),
1703	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1704        /* CONTROLLER ERROR; this is serious, we may have
1705         * been left with the inaccessible keyboard and
1706         * the disabled mouse interrupt.
1707         */
1708        error = EIO;
1709    }
1710
1711    kbdc_lock(sc->kbdc, FALSE);
1712    return error;
1713}
1714
1715static int
1716psmwrite(struct cdev *dev, struct uio *uio, int flag)
1717{
1718    register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1719    u_char buf[PSM_SMALLBUFSIZE];
1720    int error = 0, i, l;
1721
1722    if ((sc->state & PSM_VALID) == 0)
1723	return (EIO);
1724
1725    if (sc->mode.level < PSM_LEVEL_NATIVE)
1726	return (ENODEV);
1727
1728    /* copy data from the user land */
1729    while (uio->uio_resid > 0) {
1730	l = imin(PSM_SMALLBUFSIZE, uio->uio_resid);
1731	error = uiomove(buf, l, uio);
1732	if (error)
1733	    break;
1734	for (i = 0; i < l; i++) {
1735	    VLOG(4, (LOG_DEBUG, "psm: cmd 0x%x\n", buf[i]));
1736	    if (!write_aux_command(sc->kbdc, buf[i])) {
1737		VLOG(2, (LOG_DEBUG, "psm: cmd 0x%x failed.\n", buf[i]));
1738		return (reinitialize(sc, FALSE));
1739	    }
1740	}
1741    }
1742
1743    return (error);
1744}
1745
1746static int
1747psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1748{
1749    struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1750    mousemode_t mode;
1751    mousestatus_t status;
1752#if (defined(MOUSE_GETVARS))
1753    mousevar_t *var;
1754#endif
1755    mousedata_t *data;
1756    int stat[3];
1757    int command_byte;
1758    int error = 0;
1759    int s;
1760
1761    /* Perform IOCTL command */
1762    switch (cmd) {
1763
1764    case OLD_MOUSE_GETHWINFO:
1765	s = spltty();
1766        ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1767        ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1768        ((old_mousehw_t *)addr)->type = sc->hw.type;
1769        ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
1770	splx(s);
1771        break;
1772
1773    case MOUSE_GETHWINFO:
1774	s = spltty();
1775        *(mousehw_t *)addr = sc->hw;
1776	if (sc->mode.level == PSM_LEVEL_BASE)
1777	    ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1778	splx(s);
1779        break;
1780
1781    case MOUSE_SYN_GETHWINFO:
1782	s = spltty();
1783	if (synaptics_support && sc->hw.model == MOUSE_MODEL_SYNAPTICS)
1784	    *(synapticshw_t *)addr = sc->synhw;
1785	else
1786	    error = EINVAL;
1787	splx(s);
1788	break;
1789
1790    case OLD_MOUSE_GETMODE:
1791	s = spltty();
1792	switch (sc->mode.level) {
1793	case PSM_LEVEL_BASE:
1794	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1795	    break;
1796	case PSM_LEVEL_STANDARD:
1797	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1798	    break;
1799	case PSM_LEVEL_NATIVE:
1800	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1801	    break;
1802	}
1803        ((old_mousemode_t *)addr)->rate = sc->mode.rate;
1804        ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1805        ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1806	splx(s);
1807        break;
1808
1809    case MOUSE_GETMODE:
1810	s = spltty();
1811        *(mousemode_t *)addr = sc->mode;
1812	if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
1813	    ((mousemode_t *)addr)->syncmask[0] = 0;
1814	    ((mousemode_t *)addr)->syncmask[1] = 0;
1815	}
1816        ((mousemode_t *)addr)->resolution =
1817	    MOUSE_RES_LOW - sc->mode.resolution;
1818	switch (sc->mode.level) {
1819	case PSM_LEVEL_BASE:
1820	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1821	    ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE;
1822	    break;
1823	case PSM_LEVEL_STANDARD:
1824	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1825	    ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE;
1826	    ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1827	    ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
1828	    break;
1829	case PSM_LEVEL_NATIVE:
1830	    /* FIXME: this isn't quite correct... XXX */
1831	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1832	    break;
1833	}
1834	splx(s);
1835        break;
1836
1837    case OLD_MOUSE_SETMODE:
1838    case MOUSE_SETMODE:
1839	if (cmd == OLD_MOUSE_SETMODE) {
1840	    mode.rate = ((old_mousemode_t *)addr)->rate;
1841	    /*
1842	     * resolution  old I/F   new I/F
1843	     * default        0         0
1844	     * low            1        -2
1845	     * medium low     2        -3
1846	     * medium high    3        -4
1847	     * high           4        -5
1848	     */
1849	    if (((old_mousemode_t *)addr)->resolution > 0)
1850	        mode.resolution = -((old_mousemode_t *)addr)->resolution - 1;
1851	    else
1852	        mode.resolution = 0;
1853	    mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor;
1854	    mode.level = -1;
1855	} else {
1856	    mode = *(mousemode_t *)addr;
1857	}
1858
1859	/* adjust and validate parameters. */
1860	if (mode.rate > UCHAR_MAX)
1861	    return EINVAL;
1862        if (mode.rate == 0)
1863            mode.rate = sc->dflt_mode.rate;
1864	else if (mode.rate == -1)
1865	    /* don't change the current setting */
1866	    ;
1867	else if (mode.rate < 0)
1868	    return EINVAL;
1869	if (mode.resolution >= UCHAR_MAX)
1870	    return EINVAL;
1871	if (mode.resolution >= 200)
1872	    mode.resolution = MOUSE_RES_HIGH;
1873	else if (mode.resolution >= 100)
1874	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1875	else if (mode.resolution >= 50)
1876	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1877	else if (mode.resolution > 0)
1878	    mode.resolution = MOUSE_RES_LOW;
1879        if (mode.resolution == MOUSE_RES_DEFAULT)
1880            mode.resolution = sc->dflt_mode.resolution;
1881        else if (mode.resolution == -1)
1882	    /* don't change the current setting */
1883	    ;
1884        else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1885            mode.resolution = MOUSE_RES_LOW - mode.resolution;
1886	if (mode.level == -1)
1887	    /* don't change the current setting */
1888	    mode.level = sc->mode.level;
1889	else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX))
1890	    return EINVAL;
1891        if (mode.accelfactor == -1)
1892	    /* don't change the current setting */
1893	    mode.accelfactor = sc->mode.accelfactor;
1894        else if (mode.accelfactor < 0)
1895	    return EINVAL;
1896
1897	/* don't allow anybody to poll the keyboard controller */
1898	error = block_mouse_data(sc, &command_byte);
1899	if (error)
1900            return error;
1901
1902        /* set mouse parameters */
1903	if (mode.rate > 0)
1904	    mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1905	if (mode.resolution >= 0)
1906	    mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1907	set_mouse_scaling(sc->kbdc, 1);
1908	get_mouse_status(sc->kbdc, stat, 0, 3);
1909
1910        s = spltty();
1911    	sc->mode.rate = mode.rate;
1912    	sc->mode.resolution = mode.resolution;
1913    	sc->mode.accelfactor = mode.accelfactor;
1914    	sc->mode.level = mode.level;
1915        splx(s);
1916
1917	unblock_mouse_data(sc, command_byte);
1918        break;
1919
1920    case MOUSE_GETLEVEL:
1921	*(int *)addr = sc->mode.level;
1922        break;
1923
1924    case MOUSE_SETLEVEL:
1925	if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX))
1926	    return EINVAL;
1927	sc->mode.level = *(int *)addr;
1928        break;
1929
1930    case MOUSE_GETSTATUS:
1931        s = spltty();
1932	status = sc->status;
1933	sc->status.flags = 0;
1934	sc->status.obutton = sc->status.button;
1935	sc->status.button = 0;
1936	sc->status.dx = 0;
1937	sc->status.dy = 0;
1938	sc->status.dz = 0;
1939        splx(s);
1940        *(mousestatus_t *)addr = status;
1941        break;
1942
1943#if (defined(MOUSE_GETVARS))
1944    case MOUSE_GETVARS:
1945	var = (mousevar_t *)addr;
1946	bzero(var, sizeof(*var));
1947	s = spltty();
1948        var->var[0] = MOUSE_VARS_PS2_SIG;
1949        var->var[1] = sc->config;
1950        var->var[2] = sc->flags;
1951	splx(s);
1952        break;
1953
1954    case MOUSE_SETVARS:
1955	return ENODEV;
1956#endif /* MOUSE_GETVARS */
1957
1958    case MOUSE_READSTATE:
1959    case MOUSE_READDATA:
1960	data = (mousedata_t *)addr;
1961	if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
1962	    return EINVAL;
1963
1964	error = block_mouse_data(sc, &command_byte);
1965	if (error)
1966            return error;
1967        if ((data->len = get_mouse_status(sc->kbdc, data->buf,
1968		(cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
1969            error = EIO;
1970	unblock_mouse_data(sc, command_byte);
1971	break;
1972
1973#if (defined(MOUSE_SETRESOLUTION))
1974    case MOUSE_SETRESOLUTION:
1975	mode.resolution = *(int *)addr;
1976	if (mode.resolution >= UCHAR_MAX)
1977	    return EINVAL;
1978	else if (mode.resolution >= 200)
1979	    mode.resolution = MOUSE_RES_HIGH;
1980	else if (mode.resolution >= 100)
1981	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1982	else if (mode.resolution >= 50)
1983	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1984	else if (mode.resolution > 0)
1985	    mode.resolution = MOUSE_RES_LOW;
1986        if (mode.resolution == MOUSE_RES_DEFAULT)
1987            mode.resolution = sc->dflt_mode.resolution;
1988        else if (mode.resolution == -1)
1989	    mode.resolution = sc->mode.resolution;
1990        else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1991            mode.resolution = MOUSE_RES_LOW - mode.resolution;
1992
1993	error = block_mouse_data(sc, &command_byte);
1994	if (error)
1995            return error;
1996        sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1997	if (sc->mode.resolution != mode.resolution)
1998	    error = EIO;
1999	unblock_mouse_data(sc, command_byte);
2000        break;
2001#endif /* MOUSE_SETRESOLUTION */
2002
2003#if (defined(MOUSE_SETRATE))
2004    case MOUSE_SETRATE:
2005	mode.rate = *(int *)addr;
2006	if (mode.rate > UCHAR_MAX)
2007	    return EINVAL;
2008        if (mode.rate == 0)
2009            mode.rate = sc->dflt_mode.rate;
2010	else if (mode.rate < 0)
2011	    mode.rate = sc->mode.rate;
2012
2013	error = block_mouse_data(sc, &command_byte);
2014	if (error)
2015            return error;
2016        sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
2017	if (sc->mode.rate != mode.rate)
2018	    error = EIO;
2019	unblock_mouse_data(sc, command_byte);
2020        break;
2021#endif /* MOUSE_SETRATE */
2022
2023#if (defined(MOUSE_SETSCALING))
2024    case MOUSE_SETSCALING:
2025	if ((*(int *)addr <= 0) || (*(int *)addr > 2))
2026	    return EINVAL;
2027
2028	error = block_mouse_data(sc, &command_byte);
2029	if (error)
2030            return error;
2031        if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
2032	    error = EIO;
2033	unblock_mouse_data(sc, command_byte);
2034        break;
2035#endif /* MOUSE_SETSCALING */
2036
2037#if (defined(MOUSE_GETHWID))
2038    case MOUSE_GETHWID:
2039	error = block_mouse_data(sc, &command_byte);
2040	if (error)
2041            return error;
2042        sc->hw.hwid &= ~0x00ff;
2043        sc->hw.hwid |= get_aux_id(sc->kbdc);
2044	*(int *)addr = sc->hw.hwid & 0x00ff;
2045	unblock_mouse_data(sc, command_byte);
2046        break;
2047#endif /* MOUSE_GETHWID */
2048
2049    default:
2050	return ENOTTY;
2051    }
2052
2053    return error;
2054}
2055
2056static void
2057psmtimeout(void *arg)
2058{
2059    struct psm_softc *sc;
2060    int s;
2061
2062    sc = (struct psm_softc *)arg;
2063    s = spltty();
2064    if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
2065	VLOG(4, (LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit));
2066	psmintr(sc);
2067	kbdc_lock(sc->kbdc, FALSE);
2068    }
2069    sc->watchdog = TRUE;
2070    splx(s);
2071    sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz);
2072}
2073
2074/* Add all sysctls under the debug.psm and hw.psm nodes */
2075SYSCTL_NODE(_debug, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2076SYSCTL_NODE(_hw, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse");
2077
2078SYSCTL_INT(_debug_psm, OID_AUTO, loglevel, CTLFLAG_RW, &verbose, 0, "");
2079
2080static int psmhz = 20;
2081SYSCTL_INT(_debug_psm, OID_AUTO, hz, CTLFLAG_RW, &psmhz, 0, "");
2082static int psmerrsecs = 2;
2083SYSCTL_INT(_debug_psm, OID_AUTO, errsecs, CTLFLAG_RW, &psmerrsecs, 0, "");
2084static int psmerrusecs = 0;
2085SYSCTL_INT(_debug_psm, OID_AUTO, errusecs, CTLFLAG_RW, &psmerrusecs, 0, "");
2086static int psmsecs = 0;
2087SYSCTL_INT(_debug_psm, OID_AUTO, secs, CTLFLAG_RW, &psmsecs, 0, "");
2088static int psmusecs = 500000;
2089SYSCTL_INT(_debug_psm, OID_AUTO, usecs, CTLFLAG_RW, &psmusecs, 0, "");
2090static int pkterrthresh = 2;
2091SYSCTL_INT(_debug_psm, OID_AUTO, pkterrthresh, CTLFLAG_RW, &pkterrthresh, 0, "");
2092
2093static int tap_threshold = PSM_TAP_THRESHOLD;
2094SYSCTL_INT(_hw_psm, OID_AUTO, tap_threshold, CTLFLAG_RW, &tap_threshold, 0, "");
2095static int tap_timeout = PSM_TAP_TIMEOUT;
2096SYSCTL_INT(_hw_psm, OID_AUTO, tap_timeout, CTLFLAG_RW, &tap_timeout, 0, "");
2097
2098static void
2099psmintr(void *arg)
2100{
2101    struct psm_softc *sc = arg;
2102    struct timeval now;
2103    int c;
2104    packetbuf_t *pb;
2105
2106
2107    /* read until there is nothing to read */
2108    while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
2109
2110        pb = &sc->pqueue[sc->pqueue_end];
2111        /* discard the byte if the device is not open */
2112        if ((sc->state & PSM_OPEN) == 0)
2113            continue;
2114
2115	getmicrouptime(&now);
2116	if ((pb->inputbytes > 0) && timevalcmp(&now, &sc->inputtimeout, >)) {
2117	    VLOG(3, (LOG_DEBUG, "psmintr: delay too long; "
2118		 "resetting byte count\n"));
2119	    pb->inputbytes = 0;
2120	    sc->syncerrors = 0;
2121	    sc->pkterrors = 0;
2122	}
2123	sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT/1000000;
2124	sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT%1000000;
2125	timevaladd(&sc->inputtimeout, &now);
2126
2127        pb->ipacket[pb->inputbytes++] = c;
2128
2129	if (sc->mode.level == PSM_LEVEL_NATIVE) {
2130	    VLOG(4, (LOG_DEBUG, "psmintr: %02x\n", pb->ipacket[0]));
2131	    sc->syncerrors = 0;
2132	    sc->pkterrors = 0;
2133	    goto NEXT;
2134	} else {
2135	    if (pb->inputbytes < sc->mode.packetsize)
2136		continue;
2137
2138	    VLOG(4, (LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
2139		pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
2140		pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]));
2141	}
2142
2143	c = pb->ipacket[0];
2144
2145	if ((sc->flags & PSM_NEED_SYNCBITS) != 0) {
2146	    sc->mode.syncmask[1] = (c & sc->mode.syncmask[0]);
2147	    sc->flags &= ~PSM_NEED_SYNCBITS;
2148	    VLOG(2, (LOG_DEBUG, "psmintr: Sync bytes now %04x,%04x\n",
2149	    	 sc->mode.syncmask[0], sc->mode.syncmask[0]));
2150	} else if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
2151	    VLOG(3, (LOG_DEBUG, "psmintr: out of sync (%04x != %04x) %d"
2152		 " cmds since last error.\n",
2153		 c & sc->mode.syncmask[0], sc->mode.syncmask[1],
2154		 sc->cmdcount - sc->lasterr));
2155	    sc->lasterr = sc->cmdcount;
2156	    /*
2157	     * The sync byte test is a weak measure of packet
2158	     * validity.  Conservatively discard any input yet
2159	     * to be seen by userland when we detect a sync
2160	     * error since there is a good chance some of
2161	     * the queued packets have undetected errors.
2162	     */
2163	    dropqueue(sc);
2164	    if (sc->syncerrors == 0)
2165		sc->pkterrors++;
2166	    ++sc->syncerrors;
2167	    sc->lastinputerr = now;
2168	    if (sc->syncerrors >= sc->mode.packetsize * 2 ||
2169	        sc->pkterrors >= pkterrthresh) {
2170
2171		/*
2172		 * If we've failed to find a single sync byte in 2
2173		 * packets worth of data, or we've seen persistent
2174		 * packet errors during the validation period,
2175		 * reinitialize the mouse in hopes of returning it
2176		 * to the expected mode.
2177		 */
2178		VLOG(3, (LOG_DEBUG, "psmintr: reset the mouse.\n"));
2179		reinitialize(sc, TRUE);
2180	    } else if (sc->syncerrors == sc->mode.packetsize) {
2181
2182		/*
2183		 * Try a soft reset after searching for a sync
2184		 * byte through a packet length of bytes.
2185		 */
2186		VLOG(3, (LOG_DEBUG, "psmintr: re-enable the mouse.\n"));
2187		pb->inputbytes = 0;
2188		disable_aux_dev(sc->kbdc);
2189		enable_aux_dev(sc->kbdc);
2190	    } else {
2191		VLOG(3, (LOG_DEBUG, "psmintr: discard a byte (%d)\n",
2192		     sc->syncerrors));
2193		pb->inputbytes--;
2194		bcopy(&pb->ipacket[1], &pb->ipacket[0], pb->inputbytes);
2195	    }
2196	    continue;
2197	}
2198
2199	/*
2200	 * We have what appears to be a valid packet.
2201	 * Reset the error counters.
2202	 */
2203	sc->syncerrors = 0;
2204
2205	/*
2206	 * Drop even good packets if they occur within a timeout
2207	 * period of a sync error.  This allows the detection of
2208	 * a change in the mouse's packet mode without exposing
2209	 * erratic mouse behavior to the user.  Some KVMs forget
2210	 * enhanced mouse modes during switch events.
2211	 */
2212	if (!timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs, &now)) {
2213		pb->inputbytes = 0;
2214		continue;
2215	}
2216
2217	/*
2218	 * Now that we're out of the validation period, reset
2219	 * the packet error count.
2220	 */
2221	sc->pkterrors = 0;
2222
2223	sc->cmdcount++;
2224NEXT:
2225	if (++sc->pqueue_end >= PSM_PACKETQUEUE)
2226		sc->pqueue_end = 0;
2227	/*
2228	 * If we've filled the queue then call the softintr ourselves,
2229	 * otherwise schedule the interrupt for later.
2230	 */
2231	if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
2232	    (sc->pqueue_end == sc->pqueue_start)) {
2233    		if ((sc->state & PSM_SOFTARMED) != 0) {
2234			sc->state &= ~PSM_SOFTARMED;
2235			untimeout(psmsoftintr, arg, sc->softcallout);
2236		}
2237		psmsoftintr(arg);
2238	} else if ((sc->state & PSM_SOFTARMED) == 0) {
2239		sc->state |= PSM_SOFTARMED;
2240		sc->softcallout = timeout(psmsoftintr, arg,
2241		    psmhz < 1 ? 1 : (hz/psmhz));
2242	}
2243    }
2244}
2245
2246static void
2247psmsoftintr(void *arg)
2248{
2249    /*
2250     * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
2251     * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
2252     */
2253    static int butmap[8] = {
2254        0,
2255	MOUSE_BUTTON1DOWN,
2256	MOUSE_BUTTON3DOWN,
2257	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
2258	MOUSE_BUTTON2DOWN,
2259	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
2260	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
2261        MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
2262    };
2263    static int butmap_versapad[8] = {
2264	0,
2265	MOUSE_BUTTON3DOWN,
2266	0,
2267	MOUSE_BUTTON3DOWN,
2268	MOUSE_BUTTON1DOWN,
2269	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
2270	MOUSE_BUTTON1DOWN,
2271	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
2272    };
2273    static int touchpad_buttons;
2274    static int guest_buttons;
2275    register struct psm_softc *sc = arg;
2276    mousestatus_t ms;
2277    int w, x, y, z;
2278    int c;
2279    int l;
2280    int x0, y0, xavg, yavg, xsensitivity, ysensitivity, sensitivity = 0;
2281    int s;
2282    packetbuf_t *pb;
2283
2284    getmicrouptime(&sc->lastsoftintr);
2285
2286    s = spltty();
2287
2288    do {
2289
2290	pb = &sc->pqueue[sc->pqueue_start];
2291
2292	if (sc->mode.level == PSM_LEVEL_NATIVE)
2293	    goto NEXT_NATIVE;
2294
2295	c = pb->ipacket[0];
2296	/*
2297	 * A kludge for Kensington device!
2298	 * The MSB of the horizontal count appears to be stored in
2299	 * a strange place.
2300	 */
2301	if (sc->hw.model == MOUSE_MODEL_THINK)
2302	    pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
2303
2304        /* ignore the overflow bits... */
2305        x = (c & MOUSE_PS2_XNEG) ?  pb->ipacket[1] - 256 : pb->ipacket[1];
2306        y = (c & MOUSE_PS2_YNEG) ?  pb->ipacket[2] - 256 : pb->ipacket[2];
2307	z = 0;
2308        ms.obutton = sc->button;		  /* previous button state */
2309        ms.button = butmap[c & MOUSE_PS2_BUTTONS];
2310	/* `tapping' action */
2311	if (sc->config & PSM_CONFIG_FORCETAP)
2312	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2313
2314	switch (sc->hw.model) {
2315
2316	case MOUSE_MODEL_EXPLORER:
2317	    /*
2318	     *          b7 b6 b5 b4 b3 b2 b1 b0
2319	     * byte 1:  oy ox sy sx 1  M  R  L
2320	     * byte 2:  x  x  x  x  x  x  x  x
2321	     * byte 3:  y  y  y  y  y  y  y  y
2322	     * byte 4:  *  *  S2 S1 s  d2 d1 d0
2323	     *
2324	     * L, M, R, S1, S2: left, middle, right and side buttons
2325	     * s: wheel data sign bit
2326	     * d2-d0: wheel data
2327	     */
2328	    z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG)
2329		? (pb->ipacket[3] & 0x0f) - 16 : (pb->ipacket[3] & 0x0f);
2330	    ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN)
2331		? MOUSE_BUTTON4DOWN : 0;
2332	    ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN)
2333		? MOUSE_BUTTON5DOWN : 0;
2334	    break;
2335
2336	case MOUSE_MODEL_INTELLI:
2337	case MOUSE_MODEL_NET:
2338	    /* wheel data is in the fourth byte */
2339	    z = (char)pb->ipacket[3];
2340	    /* some mice may send 7 when there is no Z movement?! XXX */
2341	    if ((z >= 7) || (z <= -7))
2342		z = 0;
2343	    /* some compatible mice have additional buttons */
2344	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN)
2345		? MOUSE_BUTTON4DOWN : 0;
2346	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN)
2347		? MOUSE_BUTTON5DOWN : 0;
2348	    break;
2349
2350	case MOUSE_MODEL_MOUSEMANPLUS:
2351	    /*
2352	     * PS2++ protocl packet
2353	     *
2354	     *          b7 b6 b5 b4 b3 b2 b1 b0
2355	     * byte 1:  *  1  p3 p2 1  *  *  *
2356	     * byte 2:  c1 c2 p1 p0 d1 d0 1  0
2357	     *
2358	     * p3-p0: packet type
2359	     * c1, c2: c1 & c2 == 1, if p2 == 0
2360	     *         c1 & c2 == 0, if p2 == 1
2361	     *
2362	     * packet type: 0 (device type)
2363	     * See comments in enable_mmanplus() below.
2364	     *
2365	     * packet type: 1 (wheel data)
2366	     *
2367	     *          b7 b6 b5 b4 b3 b2 b1 b0
2368	     * byte 3:  h  *  B5 B4 s  d2 d1 d0
2369	     *
2370	     * h: 1, if horizontal roller data
2371	     *    0, if vertical roller data
2372	     * B4, B5: button 4 and 5
2373	     * s: sign bit
2374	     * d2-d0: roller data
2375	     *
2376	     * packet type: 2 (reserved)
2377	     */
2378	    if (((c & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
2379		    && (abs(x) > 191)
2380		    && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
2381		/* the extended data packet encodes button and wheel events */
2382		switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
2383		case 1:
2384		    /* wheel data packet */
2385		    x = y = 0;
2386		    if (pb->ipacket[2] & 0x80) {
2387			/* horizontal roller count - ignore it XXX*/
2388		    } else {
2389			/* vertical roller count */
2390			z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG)
2391			    ? (pb->ipacket[2] & 0x0f) - 16
2392			    : (pb->ipacket[2] & 0x0f);
2393		    }
2394		    ms.button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
2395			? MOUSE_BUTTON4DOWN : 0;
2396		    ms.button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
2397			? MOUSE_BUTTON5DOWN : 0;
2398		    break;
2399		case 2:
2400		    /* this packet type is reserved by Logitech... */
2401		    /*
2402		     * IBM ScrollPoint Mouse uses this packet type to
2403		     * encode both vertical and horizontal scroll movement.
2404		     */
2405		    x = y = 0;
2406		    /* horizontal count */
2407		    if (pb->ipacket[2] & 0x0f)
2408			z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
2409		    /* vertical count */
2410		    if (pb->ipacket[2] & 0xf0)
2411			z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
2412#if 0
2413		    /* vertical count */
2414		    z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG)
2415			? ((pb->ipacket[2] >> 4) & 0x0f) - 16
2416			: ((pb->ipacket[2] >> 4) & 0x0f);
2417		    /* horizontal count */
2418		    w = (pb->ipacket[2] & MOUSE_SPOINT_WNEG)
2419			? (pb->ipacket[2] & 0x0f) - 16
2420			: (pb->ipacket[2] & 0x0f);
2421#endif
2422		    break;
2423		case 0:
2424		    /* device type packet - shouldn't happen */
2425		    /* FALLTHROUGH */
2426		default:
2427		    x = y = 0;
2428		    ms.button = ms.obutton;
2429		    VLOG(1, (LOG_DEBUG, "psmintr: unknown PS2++ packet type %d:"
2430		         " 0x%02x 0x%02x 0x%02x\n",
2431			 MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
2432			 pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]));
2433		    break;
2434		}
2435	    } else {
2436		/* preserve button states */
2437		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2438	    }
2439	    break;
2440
2441	case MOUSE_MODEL_GLIDEPOINT:
2442	    /* `tapping' action */
2443	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2444	    break;
2445
2446	case MOUSE_MODEL_NETSCROLL:
2447	    /* three addtional bytes encode buttons and wheel events */
2448	    ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
2449		? MOUSE_BUTTON4DOWN : 0;
2450	    ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN)
2451		? MOUSE_BUTTON5DOWN : 0;
2452	    z = (pb->ipacket[3] & MOUSE_PS2_XNEG)
2453		? pb->ipacket[4] - 256 : pb->ipacket[4];
2454	    break;
2455
2456	case MOUSE_MODEL_THINK:
2457	    /* the fourth button state in the first byte */
2458	    ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
2459	    break;
2460
2461	case MOUSE_MODEL_VERSAPAD:
2462	    /* VersaPad PS/2 absolute mode message format
2463	     *
2464	     * [packet1]     7   6   5   4   3   2   1   0(LSB)
2465	     *  ipacket[0]:  1   1   0   A   1   L   T   R
2466	     *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
2467	     *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
2468	     *  ipacket[3]:  1   1   1   A   1   L   T   R
2469	     *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
2470	     *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
2471	     *
2472	     * [note]
2473	     *  R: right physical mouse button (1=on)
2474	     *  T: touch pad virtual button (1=tapping)
2475	     *  L: left physical mouse button (1=on)
2476	     *  A: position data is valid (1=valid)
2477	     *  H: horizontal data (12bit signed integer. H11 is sign bit.)
2478	     *  V: vertical data (12bit signed integer. V11 is sign bit.)
2479	     *  P: pressure data
2480	     *
2481	     * Tapping is mapped to MOUSE_BUTTON4.
2482	     */
2483	    ms.button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
2484	    ms.button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2485	    x = y = 0;
2486	    if (c & MOUSE_PS2VERSA_IN_USE) {
2487		x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
2488		y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
2489		if (x0 & 0x800)
2490		    x0 -= 0x1000;
2491		if (y0 & 0x800)
2492		    y0 -= 0x1000;
2493		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2494		    x = sc->xold - x0;
2495		    y = y0 - sc->yold;
2496		    if (x < 0)	/* XXX */
2497			x++;
2498		    else if (x)
2499			x--;
2500		    if (y < 0)
2501			y++;
2502		    else if (y)
2503			y--;
2504		} else {
2505		    sc->flags |= PSM_FLAGS_FINGERDOWN;
2506		}
2507		sc->xold = x0;
2508		sc->yold = y0;
2509	    } else {
2510		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2511	    }
2512	    c = ((x < 0) ? MOUSE_PS2_XNEG : 0)
2513		| ((y < 0) ? MOUSE_PS2_YNEG : 0);
2514	    break;
2515
2516	case MOUSE_MODEL_4D:
2517	    /*
2518	     *          b7 b6 b5 b4 b3 b2 b1 b0
2519	     * byte 1:  s2 d2 s1 d1 1  M  R  L
2520	     * byte 2:  sx x  x  x  x  x  x  x
2521	     * byte 3:  sy y  y  y  y  y  y  y
2522	     *
2523	     * s1: wheel 1 direction
2524	     * d1: wheel 1 data
2525	     * s2: wheel 2 direction
2526	     * d2: wheel 2 data
2527	     */
2528	    x = (pb->ipacket[1] & 0x80) ? pb->ipacket[1] - 256 : pb->ipacket[1];
2529	    y = (pb->ipacket[2] & 0x80) ? pb->ipacket[2] - 256 : pb->ipacket[2];
2530	    switch (c & MOUSE_4D_WHEELBITS) {
2531	    case 0x10:
2532		z = 1;
2533		break;
2534	    case 0x30:
2535		z = -1;
2536		break;
2537	    case 0x40:	/* 2nd wheel turning right XXX */
2538		z = 2;
2539		break;
2540	    case 0xc0:	/* 2nd wheel turning left XXX */
2541		z = -2;
2542		break;
2543	    }
2544	    break;
2545
2546	case MOUSE_MODEL_4DPLUS:
2547	    if ((x < 16 - 256) && (y < 16 - 256)) {
2548		/*
2549		 *          b7 b6 b5 b4 b3 b2 b1 b0
2550		 * byte 1:  0  0  1  1  1  M  R  L
2551		 * byte 2:  0  0  0  0  1  0  0  0
2552		 * byte 3:  0  0  0  0  S  s  d1 d0
2553		 *
2554		 * L, M, R, S: left, middle, right and side buttons
2555		 * s: wheel data sign bit
2556		 * d1-d0: wheel data
2557		 */
2558		x = y = 0;
2559		if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2560		    ms.button |= MOUSE_BUTTON4DOWN;
2561		z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG)
2562			? ((pb->ipacket[2] & 0x07) - 8)
2563			: (pb->ipacket[2] & 0x07) ;
2564	    } else {
2565		/* preserve previous button states */
2566		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2567	    }
2568	    break;
2569
2570	case MOUSE_MODEL_SYNAPTICS:
2571	    /* TouchPad PS/2 absolute mode message format
2572	     *
2573	     *  Bits:        7   6   5   4   3   2   1   0 (LSB)
2574	     *  ------------------------------------------------
2575	     *  ipacket[0]:  1   0  W3  W2   0  W1   R   L
2576	     *  ipacket[1]: Yb  Ya  Y9  Y8  Xb  Xa  X9  X8
2577	     *  ipacket[2]: Z7  Z6  Z5  Z4  Z3  Z2  Z1  Z0
2578	     *  ipacket[3]:  1   1  Yc  Xc   0  W0   D   U
2579	     *  ipacket[4]: X7  X6  X5  X4  X3  X2  X1  X0
2580	     *  ipacket[5]: Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
2581	     *
2582	     * Legend:
2583	     *  L: left physical mouse button
2584	     *  R: right physical mouse button
2585	     *  D: down button
2586	     *  U: up button
2587	     *  W: "wrist" value
2588	     *  X: x position
2589	     *  Y: x position
2590	     *  Z: pressure
2591	     *
2592	     * Absolute reportable limits:    0 - 6143.
2593	     * Typical bezel limits:       1472 - 5472.
2594	     * Typical edge marings:       1632 - 5312.
2595	     *
2596	     * w = 3 Passthrough Packet
2597	     *
2598	     * Byte 2,5,6 == Byte 1,2,3 of "Guest"
2599	     */
2600
2601	    if (!synaptics_support)
2602		break;
2603
2604	    /* Sanity check for out of sync packets. */
2605	    if ((pb->ipacket[0] & 0xc8) != 0x80 ||
2606		(pb->ipacket[3] & 0xc8) != 0xc0)
2607		goto NEXT;
2608
2609	    x = y = x0 = y0 = 0;
2610
2611	    /* Pressure value. */
2612	    z = pb->ipacket[2];
2613
2614	    /* Finger width value */
2615	    if (sc->synhw.capExtended) {
2616		w = ((pb->ipacket[0] & 0x30) >> 2) |
2617		    ((pb->ipacket[0] & 0x04) >> 1) |
2618		    ((pb->ipacket[3] & 0x04) >> 2);
2619	    } else {
2620		/* Assume a finger of regular width */
2621		w = 4;
2622	    }
2623
2624	    /* Handle packets from the guest device */
2625	    if (w == 3 && sc->synhw.capPassthrough) {
2626		x = ((pb->ipacket[1] & 0x10) ?
2627		    pb->ipacket[4] - 256 : pb->ipacket[4]);
2628		y = ((pb->ipacket[1] & 0x20) ?
2629		    pb->ipacket[5] - 256 : pb->ipacket[5]);
2630		z = 0;
2631
2632		guest_buttons = 0;
2633		if (pb->ipacket[1] & 0x01)
2634		    guest_buttons |= MOUSE_BUTTON1DOWN;
2635		if (pb->ipacket[1] & 0x04)
2636		    guest_buttons |= MOUSE_BUTTON2DOWN;
2637		if (pb->ipacket[1] & 0x02)
2638		    guest_buttons |= MOUSE_BUTTON3DOWN;
2639
2640		ms.button = touchpad_buttons | guest_buttons;
2641		break;
2642	    }
2643
2644	    /* Button presses */
2645	    touchpad_buttons = 0;
2646	    if (pb->ipacket[0] & 0x01)
2647		  touchpad_buttons |= MOUSE_BUTTON1DOWN;
2648	    if (pb->ipacket[0] & 0x02)
2649		  touchpad_buttons |= MOUSE_BUTTON3DOWN;
2650
2651	    if (sc->synhw.capExtended && sc->synhw.capFourButtons) {
2652		if ((pb->ipacket[3] & 0x01) && (pb->ipacket[0] & 0x01) == 0)
2653		    touchpad_buttons |= MOUSE_BUTTON4DOWN;
2654		if ((pb->ipacket[3] & 0x02) && (pb->ipacket[0] & 0x02) == 0)
2655		    touchpad_buttons |= MOUSE_BUTTON5DOWN;
2656	    }
2657
2658	    /*
2659	     * In newer pads - bit 0x02 in the third byte of
2660	     * the packet indicates that we have an extended
2661	     * button press.
2662	     */
2663	    if (pb->ipacket[3] & 0x02) {
2664	        /*
2665		 * if directional_scrolls is not 1, we treat
2666	     	 * any of the scrolling directions as middle-click.
2667	     	 */
2668		if (sc->syninfo.directional_scrolls) {
2669		    if (pb->ipacket[4] & 0x01)
2670			touchpad_buttons |= MOUSE_BUTTON4DOWN;
2671		    if (pb->ipacket[5] & 0x01)
2672			touchpad_buttons |= MOUSE_BUTTON5DOWN;
2673		    if (pb->ipacket[4] & 0x02)
2674			touchpad_buttons |= MOUSE_BUTTON6DOWN;
2675   		    if (pb->ipacket[5] & 0x02)
2676			touchpad_buttons |= MOUSE_BUTTON7DOWN;
2677		} else {
2678		    if ((pb->ipacket[4] & 0x0F) || (pb->ipacket[5] & 0x0F))
2679			touchpad_buttons |= MOUSE_BUTTON2DOWN;
2680		}
2681
2682	    }
2683
2684	    ms.button = touchpad_buttons | guest_buttons;
2685
2686	    /* There is a finger on the pad. */
2687	    if ((w >= 4 && w <= 7) && (z >= 16 && z < 200)) {
2688		x0 = ((pb->ipacket[3] & 0x10) << 8) |
2689		    ((pb->ipacket[1] & 0x0f) << 8) |
2690		    pb->ipacket[4];
2691		y0 = ((pb->ipacket[3] & 0x20) << 7) |
2692		    ((pb->ipacket[1] & 0xf0) << 4) |
2693		    pb->ipacket[5];
2694
2695		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2696		    x = x0 - sc->xold;
2697		    y = y0 - sc->yold;
2698
2699		    /* we compute averages of x and y movement */
2700		    if (sc->xaverage == 0)
2701			sc->xaverage=x;
2702
2703		    if (sc->yaverage == 0)
2704			sc->yaverage=y;
2705
2706                    xavg = sc->xaverage;
2707                    yavg = sc->yaverage;
2708
2709		    sc->xaverage = (xavg + x) >> 1;
2710		    sc->yaverage = (yavg + y) >> 1;
2711
2712		    /*
2713		     * then use the averages to compute a sensitivity level
2714		     * in each dimension
2715		     */
2716		    xsensitivity = (sc->xaverage - xavg);
2717		    if (xsensitivity < 0)
2718			xsensitivity = -xsensitivity;
2719
2720		    ysensitivity = (sc->yaverage - yavg);
2721		    if (ysensitivity < 0)
2722			ysensitivity = -ysensitivity;
2723
2724		    /*
2725		     * The sensitivity level is higher the faster the finger
2726		     * is moving. It also tends to be higher in the middle
2727		     * of a touchpad motion than on either end
2728		     *
2729		     * Note - sensitivity gets to 0 when moving slowly - so
2730		     * we add 1 to it to give it a meaningful value in that case.
2731		     */
2732		    sensitivity = (xsensitivity & ysensitivity)+1;
2733
2734		    /*
2735		     * If either our x or y change is greater than our
2736		     * hi/low speed threshold - we do the high-speed
2737		     * absolute to relative calculation otherwise we
2738		     * do the low-speed calculation.
2739		     */
2740		    if ((x>sc->syninfo.low_speed_threshold ||
2741			 x<-sc->syninfo.low_speed_threshold) ||
2742			(y>sc->syninfo.low_speed_threshold ||
2743			 y<-sc->syninfo.low_speed_threshold)) {
2744		    x0 = (x0 + sc->xold * 3) / 4;
2745		    y0 = (y0 + sc->yold * 3) / 4;
2746		    x = (x0 - sc->xold) * 10 / 85;
2747		    y = (y0 - sc->yold) * 10 / 85;
2748		} else {
2749			/*
2750			 * This is the low speed calculation.
2751			 * We simply check to see if our movement
2752			 * is more than our minimum movement threshold
2753			 * and if it is - set the movement to 1 in the
2754			 * correct direction.
2755			 * NOTE - Normally this would result in pointer
2756			 * movement that was WAY too fast.  This works
2757			 * due to the movement squelch we do later.
2758			 */
2759			if (x < -sc->syninfo.min_movement)
2760		   	    x = -1;
2761			else if (x > sc->syninfo.min_movement)
2762			    x = 1;
2763			else
2764			   x = 0;
2765			if (y < -sc->syninfo.min_movement)
2766			   y = -1;
2767			else if (y > sc->syninfo.min_movement)
2768			   y = 1;
2769			else
2770			   y = 0;
2771
2772		    }
2773		} else {
2774		    sc->flags |= PSM_FLAGS_FINGERDOWN;
2775		}
2776
2777		/*
2778		 * ok - the squelch process.  Take our sensitivity value
2779		 * and add it to the current squelch value - if squelch
2780		 * is less than our squelch threshold we kill the movement,
2781		 * otherwise we reset squelch and pass the movement through.
2782		 * Since squelch is cumulative - when mouse movement is slow
2783		 * (around sensitivity 1) the net result is that only
2784		 * 1 out of every squelch_level packets is
2785		 * delivered, effectively slowing down the movement.
2786		 */
2787		sc->squelch += sensitivity;
2788		if (sc->squelch < sc->syninfo.squelch_level) {
2789		    x = 0;
2790		    y = 0;
2791		} else
2792		    sc->squelch = 0;
2793
2794		sc->xold = x0;
2795		sc->yold = y0;
2796		sc->zmax = imax(z, sc->zmax);
2797	    } else {
2798		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2799
2800		if (sc->zmax > tap_threshold &&
2801		    timevalcmp(&sc->lastsoftintr, &sc->taptimeout, <=)) {
2802			if (w == 0)
2803			    ms.button |= MOUSE_BUTTON3DOWN;
2804			else if (w == 1)
2805			    ms.button |= MOUSE_BUTTON2DOWN;
2806			else
2807			    ms.button |= MOUSE_BUTTON1DOWN;
2808		}
2809
2810		sc->zmax = 0;
2811		sc->taptimeout.tv_sec = tap_timeout / 1000000;
2812		sc->taptimeout.tv_usec = tap_timeout % 1000000;
2813		timevaladd(&sc->taptimeout, &sc->lastsoftintr);
2814	    }
2815
2816	    /* Use the extra buttons as a scrollwheel */
2817	    if (ms.button & MOUSE_BUTTON4DOWN)
2818		z = -1;
2819	    else if (ms.button & MOUSE_BUTTON5DOWN)
2820		z = 1;
2821	    else
2822		z = 0;
2823
2824	    break;
2825
2826	case MOUSE_MODEL_GENERIC:
2827	default:
2828	    break;
2829	}
2830
2831        /* scale values */
2832        if (sc->mode.accelfactor >= 1) {
2833            if (x != 0) {
2834                x = x * x / sc->mode.accelfactor;
2835                if (x == 0)
2836                    x = 1;
2837                if (c & MOUSE_PS2_XNEG)
2838                    x = -x;
2839            }
2840            if (y != 0) {
2841                y = y * y / sc->mode.accelfactor;
2842                if (y == 0)
2843                    y = 1;
2844                if (c & MOUSE_PS2_YNEG)
2845                    y = -y;
2846            }
2847        }
2848
2849        ms.dx = x;
2850        ms.dy = y;
2851        ms.dz = z;
2852        ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0)
2853	    | (ms.obutton ^ ms.button);
2854
2855	pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);
2856
2857        sc->status.flags |= ms.flags;
2858        sc->status.dx += ms.dx;
2859        sc->status.dy += ms.dy;
2860        sc->status.dz += ms.dz;
2861        sc->status.button = ms.button;
2862        sc->button = ms.button;
2863
2864NEXT_NATIVE:
2865	sc->watchdog = FALSE;
2866
2867        /* queue data */
2868        if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
2869	    l = imin(pb->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
2870	    bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
2871	    if (pb->inputbytes > l)
2872	        bcopy(&pb->ipacket[l], &sc->queue.buf[0], pb->inputbytes - l);
2873            sc->queue.tail =
2874		(sc->queue.tail + pb->inputbytes) % sizeof(sc->queue.buf);
2875            sc->queue.count += pb->inputbytes;
2876	}
2877        pb->inputbytes = 0;
2878
2879NEXT:
2880	if (++sc->pqueue_start >= PSM_PACKETQUEUE)
2881		sc->pqueue_start = 0;
2882    } while (sc->pqueue_start != sc->pqueue_end);
2883    if (sc->state & PSM_ASLP) {
2884        sc->state &= ~PSM_ASLP;
2885        wakeup( sc);
2886    }
2887    selwakeuppri(&sc->rsel, PZERO);
2888    sc->state &= ~PSM_SOFTARMED;
2889    splx(s);
2890}
2891
2892static int
2893psmpoll(struct cdev *dev, int events, struct thread *td)
2894{
2895    struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
2896    int s;
2897    int revents = 0;
2898
2899    /* Return true if a mouse event available */
2900    s = spltty();
2901    if (events & (POLLIN | POLLRDNORM)) {
2902	if (sc->queue.count > 0)
2903	    revents |= events & (POLLIN | POLLRDNORM);
2904	else
2905	    selrecord(td, &sc->rsel);
2906    }
2907    splx(s);
2908
2909    return (revents);
2910}
2911
2912/* vendor/model specific routines */
2913
2914static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
2915{
2916    if (set_mouse_resolution(kbdc, res) != res)
2917        return FALSE;
2918    if (set_mouse_scaling(kbdc, scale)
2919	&& set_mouse_scaling(kbdc, scale)
2920	&& set_mouse_scaling(kbdc, scale)
2921	&& (get_mouse_status(kbdc, status, 0, 3) >= 3))
2922	return TRUE;
2923    return FALSE;
2924}
2925
2926static int
2927mouse_ext_command(KBDC kbdc, int command)
2928{
2929    int c;
2930
2931    c = (command >> 6) & 0x03;
2932    if (set_mouse_resolution(kbdc, c) != c)
2933	return FALSE;
2934    c = (command >> 4) & 0x03;
2935    if (set_mouse_resolution(kbdc, c) != c)
2936	return FALSE;
2937    c = (command >> 2) & 0x03;
2938    if (set_mouse_resolution(kbdc, c) != c)
2939	return FALSE;
2940    c = (command >> 0) & 0x03;
2941    if (set_mouse_resolution(kbdc, c) != c)
2942	return FALSE;
2943    return TRUE;
2944}
2945
2946#ifdef notyet
2947/* Logitech MouseMan Cordless II */
2948static int
2949enable_lcordless(struct psm_softc *sc)
2950{
2951    int status[3];
2952    int ch;
2953
2954    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
2955        return FALSE;
2956    if (status[1] == PSMD_RES_HIGH)
2957	return FALSE;
2958    ch = (status[0] & 0x07) - 1;	/* channel # */
2959    if ((ch <= 0) || (ch > 4))
2960	return FALSE;
2961    /*
2962     * status[1]: always one?
2963     * status[2]: battery status? (0-100)
2964     */
2965    return TRUE;
2966}
2967#endif /* notyet */
2968
2969/* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
2970static int
2971enable_groller(struct psm_softc *sc)
2972{
2973    int status[3];
2974
2975    /*
2976     * The special sequence to enable the fourth button and the
2977     * roller. Immediately after this sequence check status bytes.
2978     * if the mouse is NetScroll, the second and the third bytes are
2979     * '3' and 'D'.
2980     */
2981
2982    /*
2983     * If the mouse is an ordinary PS/2 mouse, the status bytes should
2984     * look like the following.
2985     *
2986     * byte 1 bit 7 always 0
2987     *        bit 6 stream mode (0)
2988     *        bit 5 disabled (0)
2989     *        bit 4 1:1 scaling (0)
2990     *        bit 3 always 0
2991     *        bit 0-2 button status
2992     * byte 2 resolution (PSMD_RES_HIGH)
2993     * byte 3 report rate (?)
2994     */
2995
2996    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2997        return FALSE;
2998    if ((status[1] != '3') || (status[2] != 'D'))
2999        return FALSE;
3000    /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
3001    sc->hw.buttons = 4;
3002    return TRUE;
3003}
3004
3005/* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
3006static int
3007enable_gmouse(struct psm_softc *sc)
3008{
3009    int status[3];
3010
3011    /*
3012     * The special sequence to enable the middle, "rubber" button.
3013     * Immediately after this sequence check status bytes.
3014     * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
3015     * the second and the third bytes are '3' and 'U'.
3016     * NOTE: NetMouse reports that it has three buttons although it has
3017     * two buttons and a rubber button. NetMouse Pro and MIE Mouse
3018     * say they have three buttons too and they do have a button on the
3019     * side...
3020     */
3021    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
3022        return FALSE;
3023    if ((status[1] != '3') || (status[2] != 'U'))
3024        return FALSE;
3025    return TRUE;
3026}
3027
3028/* ALPS GlidePoint */
3029static int
3030enable_aglide(struct psm_softc *sc)
3031{
3032    int status[3];
3033
3034    /*
3035     * The special sequence to obtain ALPS GlidePoint specific
3036     * information. Immediately after this sequence, status bytes will
3037     * contain something interesting.
3038     * NOTE: ALPS produces several models of GlidePoint. Some of those
3039     * do not respond to this sequence, thus, cannot be detected this way.
3040     */
3041    if (set_mouse_sampling_rate(sc->kbdc, 100) != 100)
3042	return FALSE;
3043    if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
3044        return FALSE;
3045    if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
3046        return FALSE;
3047    return TRUE;
3048}
3049
3050/* Kensington ThinkingMouse/Trackball */
3051static int
3052enable_kmouse(struct psm_softc *sc)
3053{
3054    static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
3055    KBDC kbdc = sc->kbdc;
3056    int status[3];
3057    int id1;
3058    int id2;
3059    int i;
3060
3061    id1 = get_aux_id(kbdc);
3062    if (set_mouse_sampling_rate(kbdc, 10) != 10)
3063	return FALSE;
3064    /*
3065     * The device is now in the native mode? It returns a different
3066     * ID value...
3067     */
3068    id2 = get_aux_id(kbdc);
3069    if ((id1 == id2) || (id2 != 2))
3070	return FALSE;
3071
3072    if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
3073        return FALSE;
3074#if PSM_DEBUG >= 2
3075    /* at this point, resolution is LOW, sampling rate is 10/sec */
3076    if (get_mouse_status(kbdc, status, 0, 3) < 3)
3077        return FALSE;
3078#endif
3079
3080    /*
3081     * The special sequence to enable the third and fourth buttons.
3082     * Otherwise they behave like the first and second buttons.
3083     */
3084    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
3085        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3086	    return FALSE;
3087    }
3088
3089    /*
3090     * At this point, the device is using default resolution and
3091     * sampling rate for the native mode.
3092     */
3093    if (get_mouse_status(kbdc, status, 0, 3) < 3)
3094        return FALSE;
3095    if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
3096        return FALSE;
3097
3098    /* the device appears be enabled by this sequence, diable it for now */
3099    disable_aux_dev(kbdc);
3100    empty_aux_buffer(kbdc, 5);
3101
3102    return TRUE;
3103}
3104
3105/* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
3106static int
3107enable_mmanplus(struct psm_softc *sc)
3108{
3109    KBDC kbdc = sc->kbdc;
3110    int data[3];
3111
3112    /* the special sequence to enable the fourth button and the roller. */
3113    /*
3114     * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
3115     * must be called exactly three times since the last RESET command
3116     * before this sequence. XXX
3117     */
3118    if (!set_mouse_scaling(kbdc, 1))
3119	return FALSE;
3120    if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
3121	return FALSE;
3122    if (get_mouse_status(kbdc, data, 1, 3) < 3)
3123        return FALSE;
3124
3125    /*
3126     * PS2++ protocl, packet type 0
3127     *
3128     *          b7 b6 b5 b4 b3 b2 b1 b0
3129     * byte 1:  *  1  p3 p2 1  *  *  *
3130     * byte 2:  1  1  p1 p0 m1 m0 1  0
3131     * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
3132     *
3133     * p3-p0: packet type: 0
3134     * m7-m0: model ID: MouseMan+:0x50, FirstMouse+:0x51, ScrollPoint:0x58...
3135     */
3136    /* check constant bits */
3137    if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
3138        return FALSE;
3139    if ((data[1] & 0xc3) != 0xc2)
3140        return FALSE;
3141    /* check d3-d0 in byte 2 */
3142    if (!MOUSE_PS2PLUS_CHECKBITS(data))
3143        return FALSE;
3144    /* check p3-p0 */
3145    if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
3146        return FALSE;
3147
3148    sc->hw.hwid &= 0x00ff;
3149    sc->hw.hwid |= data[2] << 8;	/* save model ID */
3150
3151    /*
3152     * MouseMan+ (or FirstMouse+) is now in its native mode, in which
3153     * the wheel and the fourth button events are encoded in the
3154     * special data packet. The mouse may be put in the IntelliMouse mode
3155     * if it is initialized by the IntelliMouse's method.
3156     */
3157    return TRUE;
3158}
3159
3160/* MS IntelliMouse Explorer */
3161static int
3162enable_msexplorer(struct psm_softc *sc)
3163{
3164    static unsigned char rate0[] = { 200, 100, 80, };
3165    static unsigned char rate1[] = { 200, 200, 80, };
3166    KBDC kbdc = sc->kbdc;
3167    int id;
3168    int i;
3169
3170    /*
3171     * This is needed for at least A4Tech X-7xx mice - they do not go
3172     * straight to Explorer mode, but need to be set to Intelli mode
3173     * first.
3174     */
3175    enable_msintelli(sc);
3176
3177    /* the special sequence to enable the extra buttons and the roller. */
3178    for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i) {
3179        if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
3180	    return FALSE;
3181    }
3182    /* the device will give the genuine ID only after the above sequence */
3183    id = get_aux_id(kbdc);
3184    if (id != PSM_EXPLORER_ID)
3185	return FALSE;
3186
3187    sc->hw.hwid = id;
3188    sc->hw.buttons = 5;		/* IntelliMouse Explorer XXX */
3189
3190    /*
3191     * XXX: this is a kludge to fool some KVM switch products
3192     * which think they are clever enough to know the 4-byte IntelliMouse
3193     * protocol, and assume any other protocols use 3-byte packets.
3194     * They don't convey 4-byte data packets from the IntelliMouse Explorer
3195     * correctly to the host computer because of this!
3196     * The following sequence is actually IntelliMouse's "wake up"
3197     * sequence; it will make the KVM think the mouse is IntelliMouse
3198     * when it is in fact IntelliMouse Explorer.
3199     */
3200    for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i) {
3201        if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
3202	    break;
3203    }
3204    id = get_aux_id(kbdc);
3205
3206    return TRUE;
3207}
3208
3209/* MS IntelliMouse */
3210static int
3211enable_msintelli(struct psm_softc *sc)
3212{
3213    /*
3214     * Logitech MouseMan+ and FirstMouse+ will also respond to this
3215     * probe routine and act like IntelliMouse.
3216     */
3217
3218    static unsigned char rate[] = { 200, 100, 80, };
3219    KBDC kbdc = sc->kbdc;
3220    int id;
3221    int i;
3222
3223    /* the special sequence to enable the third button and the roller. */
3224    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
3225        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3226	    return FALSE;
3227    }
3228    /* the device will give the genuine ID only after the above sequence */
3229    id = get_aux_id(kbdc);
3230    if (id != PSM_INTELLI_ID)
3231	return FALSE;
3232
3233    sc->hw.hwid = id;
3234    sc->hw.buttons = 3;
3235
3236    return TRUE;
3237}
3238
3239/* A4 Tech 4D Mouse */
3240static int
3241enable_4dmouse(struct psm_softc *sc)
3242{
3243    /*
3244     * Newer wheel mice from A4 Tech may use the 4D+ protocol.
3245     */
3246
3247    static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
3248    KBDC kbdc = sc->kbdc;
3249    int id;
3250    int i;
3251
3252    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
3253        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3254	    return FALSE;
3255    }
3256    id = get_aux_id(kbdc);
3257    /*
3258     * WinEasy 4D, 4 Way Scroll 4D: 6
3259     * Cable-Free 4D: 8 (4DPLUS)
3260     * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
3261     */
3262    if (id != PSM_4DMOUSE_ID)
3263	return FALSE;
3264
3265    sc->hw.hwid = id;
3266    sc->hw.buttons = 3;		/* XXX some 4D mice have 4? */
3267
3268    return TRUE;
3269}
3270
3271/* A4 Tech 4D+ Mouse */
3272static int
3273enable_4dplus(struct psm_softc *sc)
3274{
3275    /*
3276     * Newer wheel mice from A4 Tech seem to use this protocol.
3277     * Older models are recognized as either 4D Mouse or IntelliMouse.
3278     */
3279    KBDC kbdc = sc->kbdc;
3280    int id;
3281
3282    /*
3283     * enable_4dmouse() already issued the following ID sequence...
3284    static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
3285    int i;
3286
3287    for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
3288        if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
3289	    return FALSE;
3290    }
3291    */
3292
3293    id = get_aux_id(kbdc);
3294    switch (id) {
3295    case PSM_4DPLUS_ID:
3296	    sc->hw.buttons = 4;
3297	    break;
3298    case PSM_4DPLUS_RFSW35_ID:
3299	    sc->hw.buttons = 3;
3300	    break;
3301    default:
3302	    return FALSE;
3303    }
3304
3305    sc->hw.hwid = id;
3306
3307    return TRUE;
3308}
3309
3310/* Synaptics Touchpad */
3311static int
3312enable_synaptics(struct psm_softc *sc)
3313{
3314    int status[3];
3315    KBDC kbdc;
3316
3317    if (!synaptics_support)
3318	return (FALSE);
3319
3320    /* Attach extra synaptics sysctl nodes under hw.psm.synaptics */
3321    sysctl_ctx_init(&sc->syninfo.sysctl_ctx);
3322    sc->syninfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->syninfo.sysctl_ctx,
3323	SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "synaptics",
3324	CTLFLAG_RD, 0, "Synaptics TouchPad");
3325
3326    /*
3327     * synaptics_directional_scrolls - if non-zero, the directional
3328     * pad scrolls, otherwise it registers as a middle-click.
3329     */
3330    sc->syninfo.directional_scrolls = 1;
3331    SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3332	SYSCTL_CHILDREN(sc->syninfo.sysctl_tree),
3333	OID_AUTO, "directional_scrolls", CTLFLAG_RW,
3334	&sc->syninfo.directional_scrolls, 0,
3335	"directional pad scrolls (1=yes  0=3rd button)");
3336
3337    /*
3338     * Synaptics_low_speed_threshold - the number of touchpad units
3339     * below-which we go into low-speed tracking mode.
3340     */
3341    sc->syninfo.low_speed_threshold = 20;
3342    SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3343	SYSCTL_CHILDREN(sc->syninfo.sysctl_tree),
3344	OID_AUTO, "low_speed_threshold", CTLFLAG_RW,
3345	&sc->syninfo.low_speed_threshold, 0,
3346	"threshold between low and hi speed positioning");
3347
3348    /*
3349     * Synaptics_min_movement - the number of touchpad units below
3350     * which we ignore altogether.
3351     */
3352    sc->syninfo.min_movement = 2;
3353    SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3354	SYSCTL_CHILDREN(sc->syninfo.sysctl_tree),
3355	OID_AUTO, "min_movement", CTLFLAG_RW,
3356	&sc->syninfo.min_movement, 0,
3357	"ignore touchpad movements less than this");
3358
3359    /*
3360     * Synaptics_squelch_level - level at which we squelch movement
3361     * packets.
3362     *
3363     * This effectively sends 1 out of every synaptics_squelch_level
3364     * packets when * running in low-speed mode.
3365     */
3366    sc->syninfo.squelch_level=3;
3367    SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx,
3368	SYSCTL_CHILDREN(sc->syninfo.sysctl_tree),
3369	OID_AUTO, "squelch_level", CTLFLAG_RW,
3370	&sc->syninfo.squelch_level, 0,
3371	"squelch level for synaptics touchpads");
3372
3373    kbdc = sc->kbdc;
3374    disable_aux_dev(kbdc);
3375    sc->hw.buttons = 3;
3376    sc->squelch = 0;
3377
3378    /* Just to be on the safe side */
3379    set_mouse_scaling(kbdc, 1);
3380
3381    /* Identify the Touchpad version */
3382    if (mouse_ext_command(kbdc, 0) == 0)
3383	return (FALSE);
3384    if (get_mouse_status(kbdc, status, 0, 3) != 3)
3385	return (FALSE);
3386    if (status[1] != 0x47)
3387	return (FALSE);
3388
3389    sc->synhw.infoMinor = status[0];
3390    sc->synhw.infoMajor = status[2] & 0x0f;
3391
3392    if (verbose >= 2)
3393	printf("Synaptics Touchpad v%d.%d\n",
3394	    sc->synhw.infoMajor, sc->synhw.infoMinor);
3395
3396    if (sc->synhw.infoMajor < 4) {
3397	printf("  Unsupported (pre-v4) Touchpad detected\n");
3398	return (FALSE);
3399    }
3400
3401    /* Get the Touchpad model information */
3402    if (mouse_ext_command(kbdc, 3) == 0)
3403	return (FALSE);
3404    if (get_mouse_status(kbdc, status, 0, 3) != 3)
3405	return (FALSE);
3406    if ((status[1] & 0x01) != 0) {
3407	printf("  Failed to read model information\n");
3408	return (FALSE);
3409    }
3410
3411    sc->synhw.infoRot180   = (status[0] & 0x80) >> 7;
3412    sc->synhw.infoPortrait = (status[0] & 0x40) >> 6;
3413    sc->synhw.infoSensor   =  status[0] & 0x3f;
3414    sc->synhw.infoHardware = (status[1] & 0xfe) >> 1;
3415    sc->synhw.infoNewAbs   = (status[2] & 0x80) >> 7;
3416    sc->synhw.capPen       = (status[2] & 0x40) >> 6;
3417    sc->synhw.infoSimplC   = (status[2] & 0x20) >> 5;
3418    sc->synhw.infoGeometry =  status[2] & 0x0f;
3419
3420    if (verbose >= 2) {
3421	printf("  Model information:\n");
3422	printf("   infoRot180: %d\n", sc->synhw.infoRot180);
3423	printf("   infoPortrait: %d\n", sc->synhw.infoPortrait);
3424	printf("   infoSensor: %d\n", sc->synhw.infoSensor);
3425	printf("   infoHardware: %d\n", sc->synhw.infoHardware);
3426	printf("   infoNewAbs: %d\n", sc->synhw.infoNewAbs);
3427	printf("   capPen: %d\n", sc->synhw.capPen);
3428	printf("   infoSimplC: %d\n", sc->synhw.infoSimplC);
3429	printf("   infoGeometry: %d\n", sc->synhw.infoGeometry);
3430    }
3431
3432    /* Read the extended capability bits */
3433    if (mouse_ext_command(kbdc, 2) == 0)
3434	return (FALSE);
3435    if (get_mouse_status(kbdc, status, 0, 3) != 3)
3436	return (FALSE);
3437    if (status[1] != 0x47) {
3438	printf("  Failed to read extended capability bits\n");
3439	return (FALSE);
3440    }
3441
3442    /* Set the different capabilities when they exist */
3443    if ((status[0] & 0x80) >> 7) {
3444	sc->synhw.capExtended    = (status[0] & 0x80) >> 7;
3445    	sc->synhw.capPassthrough = (status[2] & 0x80) >> 7;
3446    	sc->synhw.capSleep       = (status[2] & 0x10) >> 4;
3447    	sc->synhw.capFourButtons = (status[2] & 0x08) >> 3;
3448    	sc->synhw.capMultiFinger = (status[2] & 0x02) >> 1;
3449    	sc->synhw.capPalmDetect  = (status[2] & 0x01);
3450
3451	if (verbose >= 2) {
3452	    printf("  Extended capabilities:\n");
3453	    printf("   capExtended: %d\n", sc->synhw.capExtended);
3454	    printf("   capPassthrough: %d\n", sc->synhw.capPassthrough);
3455	    printf("   capSleep: %d\n", sc->synhw.capSleep);
3456	    printf("   capFourButtons: %d\n", sc->synhw.capFourButtons);
3457	    printf("   capMultiFinger: %d\n", sc->synhw.capMultiFinger);
3458	    printf("   capPalmDetect: %d\n", sc->synhw.capPalmDetect);
3459	}
3460
3461	/*
3462	 * if we have bits set in status[0] & 0x70 - then we can load
3463	 * more information about buttons using query 0x09
3464	 */
3465        if (status[0] & 0x70) {
3466    	    if (mouse_ext_command(kbdc, 0x09) == 0)
3467		return (FALSE);
3468	    if (get_mouse_status(kbdc, status, 0, 3) != 3)
3469		return (FALSE);
3470	    sc->hw.buttons = ((status[1] & 0xf0) >> 4) + 3;
3471	    if (verbose >= 2)
3472	       printf("  Additional Buttons: %d\n", sc->hw.buttons -3);
3473	}
3474
3475    } else {
3476	sc->synhw.capExtended = 0;
3477
3478	if (verbose >= 2)
3479	    printf("  No extended capabilities\n");
3480    }
3481
3482    /*
3483     * Read the mode byte
3484     *
3485     * XXX: Note the Synaptics documentation also defines the first
3486     * byte of the response to this query to be a constant 0x3b, this
3487     * does not appear to be true for Touchpads with guest devices.
3488     */
3489    if (mouse_ext_command(kbdc, 1) == 0)
3490	return (FALSE);
3491    if (get_mouse_status(kbdc, status, 0, 3) != 3)
3492	return (FALSE);
3493    if (status[1] != 0x47) {
3494	printf("  Failed to read mode byte\n");
3495	return (FALSE);
3496    }
3497
3498    /* Set the mode byte -- request wmode where available */
3499    if (sc->synhw.capExtended)
3500	mouse_ext_command(kbdc, 0xc1);
3501    else
3502	mouse_ext_command(kbdc, 0xc0);
3503
3504    /* Reset the sampling rate */
3505    set_mouse_sampling_rate(kbdc, 20);
3506
3507    /*
3508     * Report the correct number of buttons
3509     *
3510     * XXX: I'm not sure this is used anywhere.
3511     */
3512    if (sc->synhw.capExtended && sc->synhw.capFourButtons)
3513	sc->hw.buttons = 4;
3514
3515    return (TRUE);
3516}
3517
3518/* Interlink electronics VersaPad */
3519static int
3520enable_versapad(struct psm_softc *sc)
3521{
3522    KBDC kbdc = sc->kbdc;
3523    int data[3];
3524
3525    set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
3526    set_mouse_sampling_rate(kbdc, 100);		/* set rate 100 */
3527    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3528    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3529    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3530    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3531    if (get_mouse_status(kbdc, data, 0, 3) < 3)	/* get status */
3532	return FALSE;
3533    if (data[2] != 0xa || data[1] != 0 )	/* rate == 0xa && res. == 0 */
3534	return FALSE;
3535    set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3536
3537    sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
3538
3539    return TRUE;				/* PS/2 absolute mode */
3540}
3541
3542/*
3543 * Return true if 'now' is earlier than (start + (secs.usecs)).
3544 * Now may be NULL and the function will fetch the current time from
3545 * getmicrouptime(), or a cached 'now' can be passed in.
3546 * All values should be numbers derived from getmicrouptime().
3547 */
3548static int
3549timeelapsed(start, secs, usecs, now)
3550	const struct timeval *start, *now;
3551	int secs, usecs;
3552{
3553	struct timeval snow, tv;
3554
3555	/* if there is no 'now' passed in, the get it as a convience. */
3556	if (now == NULL) {
3557		getmicrouptime(&snow);
3558		now = &snow;
3559	}
3560
3561	tv.tv_sec = secs;
3562	tv.tv_usec = usecs;
3563	timevaladd(&tv, start);
3564	return (timevalcmp(&tv, now, <));
3565}
3566
3567static int
3568psmresume(device_t dev)
3569{
3570    struct psm_softc *sc = device_get_softc(dev);
3571    int unit = device_get_unit(dev);
3572    int err;
3573
3574    VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit));
3575
3576    if (!(sc->config & PSM_CONFIG_HOOKRESUME))
3577	return (0);
3578
3579    err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
3580
3581    if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
3582	/*
3583	 * Release the blocked process; it must be notified that the device
3584	 * cannot be accessed anymore.
3585	 */
3586        sc->state &= ~PSM_ASLP;
3587        wakeup(sc);
3588    }
3589
3590    VLOG(2, (LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit));
3591
3592    return (err);
3593}
3594
3595DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
3596
3597#ifdef DEV_ISA
3598
3599/*
3600 * This sucks up assignments from PNPBIOS and ACPI.
3601 */
3602
3603/*
3604 * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
3605 * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
3606 * can be probed and attached only after the AT keyboard controller is
3607 * attached, we shall quietly reserve the IRQ resource for later use.
3608 * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
3609 * copy the IRQ resource to the PS/2 mouse device instance hanging
3610 * under the keyboard controller, then probe and attach it.
3611 */
3612
3613static	devclass_t			psmcpnp_devclass;
3614
3615static	device_probe_t			psmcpnp_probe;
3616static	device_attach_t			psmcpnp_attach;
3617
3618static device_method_t psmcpnp_methods[] = {
3619	DEVMETHOD(device_probe,		psmcpnp_probe),
3620	DEVMETHOD(device_attach,	psmcpnp_attach),
3621
3622	{ 0, 0 }
3623};
3624
3625static driver_t psmcpnp_driver = {
3626	PSMCPNP_DRIVER_NAME,
3627	psmcpnp_methods,
3628	1,			/* no softc */
3629};
3630
3631static struct isa_pnp_id psmcpnp_ids[] = {
3632	{ 0x030fd041, "PS/2 mouse port" },		/* PNP0F03 */
3633	{ 0x0e0fd041, "PS/2 mouse port" },		/* PNP0F0E */
3634	{ 0x120fd041, "PS/2 mouse port" },		/* PNP0F12 */
3635	{ 0x130fd041, "PS/2 mouse port" },		/* PNP0F13 */
3636	{ 0x1303d041, "PS/2 port" },			/* PNP0313, XXX */
3637	{ 0x02002e4f, "Dell PS/2 mouse port" },		/* Lat. X200, Dell */
3638	{ 0x0002a906, "ALPS Glide Point" },		/* ALPS Glide Point */
3639	{ 0x80374d24, "IBM PS/2 mouse port" },		/* IBM3780, ThinkPad */
3640	{ 0x81374d24, "IBM PS/2 mouse port" },		/* IBM3781, ThinkPad */
3641	{ 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
3642	{ 0x0290d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9002, Vaio */
3643	{ 0x0390d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9003, Vaio */
3644	{ 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
3645	{ 0 }
3646};
3647
3648static int
3649create_a_copy(device_t atkbdc, device_t me)
3650{
3651	device_t psm;
3652	u_long irq;
3653
3654	/* find the PS/2 mouse device instance under the keyboard controller */
3655	psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
3656				device_get_unit(atkbdc));
3657	if (psm == NULL)
3658		return ENXIO;
3659	if (device_get_state(psm) != DS_NOTPRESENT)
3660		return 0;
3661
3662	/* move our resource to the found device */
3663	irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
3664	bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
3665
3666	/* ...then probe and attach it */
3667	return device_probe_and_attach(psm);
3668}
3669
3670static int
3671psmcpnp_probe(device_t dev)
3672{
3673	struct resource *res;
3674	u_long irq;
3675	int rid;
3676
3677	if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids))
3678		return ENXIO;
3679
3680	/*
3681	 * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
3682	 * to the PS/2 mouse device node. But, some buggy PnP BIOS
3683	 * declares the PS/2 mouse device node without an IRQ resource!
3684	 * If this happens, we shall refer to device hints.
3685	 * If we still don't find it there, use a hardcoded value... XXX
3686	 */
3687	rid = 0;
3688	irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
3689	if (irq <= 0) {
3690		if (resource_long_value(PSM_DRIVER_NAME,
3691					device_get_unit(dev), "irq", &irq) != 0)
3692			irq = 12;	/* XXX */
3693		device_printf(dev, "irq resource info is missing; "
3694			      "assuming irq %ld\n", irq);
3695		bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
3696	}
3697	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
3698				     RF_SHAREABLE);
3699	bus_release_resource(dev, SYS_RES_IRQ, rid, res);
3700
3701	/* keep quiet */
3702	if (!bootverbose)
3703		device_quiet(dev);
3704
3705	return ((res == NULL) ? ENXIO : 0);
3706}
3707
3708static int
3709psmcpnp_attach(device_t dev)
3710{
3711	device_t atkbdc;
3712	int rid;
3713
3714	/* find the keyboard controller, which may be on acpi* or isa* bus */
3715	atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
3716				     device_get_unit(dev));
3717	if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED)) {
3718		create_a_copy(atkbdc, dev);
3719	} else {
3720		/*
3721		 * If we don't have the AT keyboard controller yet,
3722		 * just reserve the IRQ for later use...
3723		 * (See psmidentify() above.)
3724		 */
3725		rid = 0;
3726		bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_SHAREABLE);
3727	}
3728
3729	return 0;
3730}
3731
3732DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
3733DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
3734
3735#endif /* DEV_ISA */
3736