xref: /freebsd/usr.sbin/moused/moused.c (revision c37420b0d5b3b6ef875fbf0b84a13f6f09be56d6)
1 /**
2  ** Copyright (c) 1995 Michael Smith, All rights reserved.
3  **
4  ** Redistribution and use in source and binary forms, with or without
5  ** modification, are permitted provided that the following conditions
6  ** are met:
7  ** 1. Redistributions of source code must retain the above copyright
8  **    notice, this list of conditions and the following disclaimer as
9  **    the first lines of this file unmodified.
10  ** 2. Redistributions in binary form must reproduce the above copyright
11  **    notice, this list of conditions and the following disclaimer in the
12  **    documentation and/or other materials provided with the distribution.
13  ** 3. All advertising materials mentioning features or use of this software
14  **    must display the following acknowledgment:
15  **      This product includes software developed by Michael Smith.
16  ** 4. The name of the author may not be used to endorse or promote products
17  **    derived from this software without specific prior written permission.
18  **
19  **
20  ** THIS SOFTWARE IS PROVIDED BY Michael Smith ``AS IS'' AND ANY
21  ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  ** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Michael Smith BE LIABLE FOR
24  ** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  ** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  ** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27  ** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28  ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
29  ** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30  ** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  **
32  **/
33 
34 /**
35  ** MOUSED.C
36  **
37  ** Mouse daemon : listens to a serial port, the bus mouse interface, or
38  ** the PS/2 mouse port for mouse data stream, interprets data and passes
39  ** ioctls off to the console driver.
40  **
41  ** The mouse interface functions are derived closely from the mouse
42  ** handler in the XFree86 X server.  Many thanks to the XFree86 people
43  ** for their great work!
44  **
45  **/
46 
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/consio.h>
52 #include <sys/linker.h>
53 #include <sys/module.h>
54 #include <sys/mouse.h>
55 #include <sys/socket.h>
56 #include <sys/stat.h>
57 #include <sys/time.h>
58 #include <sys/un.h>
59 
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <limits.h>
65 #include <setjmp.h>
66 #include <signal.h>
67 #include <stdarg.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <syslog.h>
72 #include <termios.h>
73 #include <unistd.h>
74 
75 #define MAX_CLICKTHRESHOLD	2000	/* 2 seconds */
76 #define MAX_BUTTON2TIMEOUT	2000	/* 2 seconds */
77 #define DFLT_CLICKTHRESHOLD	 500	/* 0.5 second */
78 #define DFLT_BUTTON2TIMEOUT	 100	/* 0.1 second */
79 
80 /* Abort 3-button emulation delay after this many movement events. */
81 #define BUTTON2_MAXMOVE	3
82 
83 #define TRUE		1
84 #define FALSE		0
85 
86 #define MOUSE_XAXIS	(-1)
87 #define MOUSE_YAXIS	(-2)
88 
89 /* Logitech PS2++ protocol */
90 #define MOUSE_PS2PLUS_CHECKBITS(b)	\
91 			((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
92 #define MOUSE_PS2PLUS_PACKET_TYPE(b)	\
93 			(((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
94 
95 #define	ChordMiddle	0x0001
96 #define Emulate3Button	0x0002
97 #define ClearDTR	0x0004
98 #define ClearRTS	0x0008
99 #define NoPnP		0x0010
100 
101 #define ID_NONE		0
102 #define ID_PORT		1
103 #define ID_IF		2
104 #define ID_TYPE	4
105 #define ID_MODEL	8
106 #define ID_ALL		(ID_PORT | ID_IF | ID_TYPE | ID_MODEL)
107 
108 #define debug(fmt, args...) do {				\
109 	if (debug && nodaemon)					\
110 		warnx(fmt, ##args);				\
111 } while (0)
112 
113 #define logerr(e, fmt, args...) do {				\
114 	log_or_warn(LOG_DAEMON | LOG_ERR, errno, fmt, ##args);	\
115 	exit(e);						\
116 } while (0)
117 
118 #define logerrx(e, fmt, args...) do {				\
119 	log_or_warn(LOG_DAEMON | LOG_ERR, 0, fmt, ##args);	\
120 	exit(e);						\
121 } while (0)
122 
123 #define logwarn(fmt, args...)					\
124 	log_or_warn(LOG_DAEMON | LOG_WARNING, errno, fmt, ##args)
125 
126 #define logwarnx(fmt, args...)					\
127 	log_or_warn(LOG_DAEMON | LOG_WARNING, 0, fmt, ##args)
128 
129 /* structures */
130 
131 /* symbol table entry */
132 typedef struct {
133     char *name;
134     int val;
135     int val2;
136 } symtab_t;
137 
138 /* serial PnP ID string */
139 typedef struct {
140     int revision;	/* PnP revision, 100 for 1.00 */
141     char *eisaid;	/* EISA ID including mfr ID and product ID */
142     char *serial;	/* serial No, optional */
143     char *class;	/* device class, optional */
144     char *compat;	/* list of compatible drivers, optional */
145     char *description;	/* product description, optional */
146     int neisaid;	/* length of the above fields... */
147     int nserial;
148     int nclass;
149     int ncompat;
150     int ndescription;
151 } pnpid_t;
152 
153 /* global variables */
154 
155 int	debug = 0;
156 int	nodaemon = FALSE;
157 int	background = FALSE;
158 int	identify = ID_NONE;
159 int	extioctl = FALSE;
160 char	*pidfile = "/var/run/moused.pid";
161 
162 /* local variables */
163 
164 /* interface (the table must be ordered by MOUSE_IF_XXX in mouse.h) */
165 static symtab_t rifs[] = {
166     { "serial",		MOUSE_IF_SERIAL },
167     { "bus",		MOUSE_IF_BUS },
168     { "inport",		MOUSE_IF_INPORT },
169     { "ps/2",		MOUSE_IF_PS2 },
170     { "sysmouse",	MOUSE_IF_SYSMOUSE },
171     { "usb",		MOUSE_IF_USB },
172     { NULL,		MOUSE_IF_UNKNOWN },
173 };
174 
175 /* types (the table must be ordered by MOUSE_PROTO_XXX in mouse.h) */
176 static char *rnames[] = {
177     "microsoft",
178     "mousesystems",
179     "logitech",
180     "mmseries",
181     "mouseman",
182     "busmouse",
183     "inportmouse",
184     "ps/2",
185     "mmhitab",
186     "glidepoint",
187     "intellimouse",
188     "thinkingmouse",
189     "sysmouse",
190     "x10mouseremote",
191     "kidspad",
192     "versapad",
193     "jogdial",
194 #if notyet
195     "mariqua",
196 #endif
197     NULL
198 };
199 
200 /* models */
201 static symtab_t	rmodels[] = {
202     { "NetScroll",		MOUSE_MODEL_NETSCROLL },
203     { "NetMouse/NetScroll Optical", MOUSE_MODEL_NET },
204     { "GlidePoint",		MOUSE_MODEL_GLIDEPOINT },
205     { "ThinkingMouse",		MOUSE_MODEL_THINK },
206     { "IntelliMouse",		MOUSE_MODEL_INTELLI },
207     { "EasyScroll/SmartScroll",	MOUSE_MODEL_EASYSCROLL },
208     { "MouseMan+",		MOUSE_MODEL_MOUSEMANPLUS },
209     { "Kidspad",		MOUSE_MODEL_KIDSPAD },
210     { "VersaPad",		MOUSE_MODEL_VERSAPAD },
211     { "IntelliMouse Explorer",	MOUSE_MODEL_EXPLORER },
212     { "4D Mouse",		MOUSE_MODEL_4D },
213     { "4D+ Mouse",		MOUSE_MODEL_4DPLUS },
214     { "Synaptics Touchpad",	MOUSE_MODEL_SYNAPTICS },
215     { "generic",		MOUSE_MODEL_GENERIC },
216     { NULL,			MOUSE_MODEL_UNKNOWN },
217 };
218 
219 /* PnP EISA/product IDs */
220 static symtab_t pnpprod[] = {
221     /* Kensignton ThinkingMouse */
222     { "KML0001",	MOUSE_PROTO_THINK,	MOUSE_MODEL_THINK },
223     /* MS IntelliMouse */
224     { "MSH0001",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
225     /* MS IntelliMouse TrackBall */
226     { "MSH0004",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
227     /* Tremon Wheel Mouse MUSD */
228     { "HTK0001",        MOUSE_PROTO_INTELLI,    MOUSE_MODEL_INTELLI },
229     /* Genius PnP Mouse */
230     { "KYE0001",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
231     /* MouseSystems SmartScroll Mouse (OEM from Genius?) */
232     { "KYE0002",	MOUSE_PROTO_MS,		MOUSE_MODEL_EASYSCROLL },
233     /* Genius NetMouse */
234     { "KYE0003",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_NET },
235     /* Genius Kidspad, Easypad and other tablets */
236     { "KYE0005",	MOUSE_PROTO_KIDSPAD,	MOUSE_MODEL_KIDSPAD },
237     /* Genius EZScroll */
238     { "KYEEZ00",	MOUSE_PROTO_MS,		MOUSE_MODEL_EASYSCROLL },
239     /* Logitech Cordless MouseMan Wheel */
240     { "LGI8033",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
241     /* Logitech MouseMan (new 4 button model) */
242     { "LGI800C",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
243     /* Logitech MouseMan+ */
244     { "LGI8050",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
245     /* Logitech FirstMouse+ */
246     { "LGI8051",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
247     /* Logitech serial */
248     { "LGI8001",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
249     /* A4 Tech 4D/4D+ Mouse */
250     { "A4W0005",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_4D },
251     /* 8D Scroll Mouse */
252     { "PEC9802",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
253     /* Mitsumi Wireless Scroll Mouse */
254     { "MTM6401",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
255 
256     /* MS bus */
257     { "PNP0F00",	MOUSE_PROTO_BUS,	MOUSE_MODEL_GENERIC },
258     /* MS serial */
259     { "PNP0F01",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
260     /* MS InPort */
261     { "PNP0F02",	MOUSE_PROTO_INPORT,	MOUSE_MODEL_GENERIC },
262     /* MS PS/2 */
263     { "PNP0F03",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
264     /*
265      * EzScroll returns PNP0F04 in the compatible device field; but it
266      * doesn't look compatible... XXX
267      */
268     /* MouseSystems */
269     { "PNP0F04",	MOUSE_PROTO_MSC,	MOUSE_MODEL_GENERIC },
270     /* MouseSystems */
271     { "PNP0F05",	MOUSE_PROTO_MSC,	MOUSE_MODEL_GENERIC },
272 #if notyet
273     /* Genius Mouse */
274     { "PNP0F06",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
275     /* Genius Mouse */
276     { "PNP0F07",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
277 #endif
278     /* Logitech serial */
279     { "PNP0F08",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
280     /* MS BallPoint serial */
281     { "PNP0F09",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
282     /* MS PnP serial */
283     { "PNP0F0A",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
284     /* MS PnP BallPoint serial */
285     { "PNP0F0B",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
286     /* MS serial comatible */
287     { "PNP0F0C",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
288     /* MS InPort comatible */
289     { "PNP0F0D",	MOUSE_PROTO_INPORT,	MOUSE_MODEL_GENERIC },
290     /* MS PS/2 comatible */
291     { "PNP0F0E",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
292     /* MS BallPoint comatible */
293     { "PNP0F0F",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
294 #if notyet
295     /* TI QuickPort */
296     { "PNP0F10",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
297 #endif
298     /* MS bus comatible */
299     { "PNP0F11",	MOUSE_PROTO_BUS,	MOUSE_MODEL_GENERIC },
300     /* Logitech PS/2 */
301     { "PNP0F12",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
302     /* PS/2 */
303     { "PNP0F13",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
304 #if notyet
305     /* MS Kids Mouse */
306     { "PNP0F14",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
307 #endif
308     /* Logitech bus */
309     { "PNP0F15",	MOUSE_PROTO_BUS,	MOUSE_MODEL_GENERIC },
310 #if notyet
311     /* Logitech SWIFT */
312     { "PNP0F16",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
313 #endif
314     /* Logitech serial compat */
315     { "PNP0F17",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
316     /* Logitech bus compatible */
317     { "PNP0F18",	MOUSE_PROTO_BUS,	MOUSE_MODEL_GENERIC },
318     /* Logitech PS/2 compatible */
319     { "PNP0F19",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
320 #if notyet
321     /* Logitech SWIFT compatible */
322     { "PNP0F1A",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
323     /* HP Omnibook */
324     { "PNP0F1B",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
325     /* Compaq LTE TrackBall PS/2 */
326     { "PNP0F1C",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
327     /* Compaq LTE TrackBall serial */
328     { "PNP0F1D",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
329     /* MS Kidts Trackball */
330     { "PNP0F1E",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
331 #endif
332     /* Interlink VersaPad */
333     { "LNK0001",	MOUSE_PROTO_VERSAPAD,	MOUSE_MODEL_VERSAPAD },
334 
335     { NULL,		MOUSE_PROTO_UNKNOWN,	MOUSE_MODEL_GENERIC },
336 };
337 
338 /* the table must be ordered by MOUSE_PROTO_XXX in mouse.h */
339 static unsigned short rodentcflags[] =
340 {
341     (CS7	           | CREAD | CLOCAL | HUPCL),	/* MicroSoft */
342     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* MouseSystems */
343     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* Logitech */
344     (CS8 | PARENB | PARODD | CREAD | CLOCAL | HUPCL),	/* MMSeries */
345     (CS7		   | CREAD | CLOCAL | HUPCL),	/* MouseMan */
346     0,							/* Bus */
347     0,							/* InPort */
348     0,							/* PS/2 */
349     (CS8		   | CREAD | CLOCAL | HUPCL),	/* MM HitTablet */
350     (CS7	           | CREAD | CLOCAL | HUPCL),	/* GlidePoint */
351     (CS7                   | CREAD | CLOCAL | HUPCL),	/* IntelliMouse */
352     (CS7                   | CREAD | CLOCAL | HUPCL),	/* Thinking Mouse */
353     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* sysmouse */
354     (CS7	           | CREAD | CLOCAL | HUPCL),	/* X10 MouseRemote */
355     (CS8 | PARENB | PARODD | CREAD | CLOCAL | HUPCL),	/* kidspad etc. */
356     (CS8		   | CREAD | CLOCAL | HUPCL),	/* VersaPad */
357     0,							/* JogDial */
358 #if notyet
359     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* Mariqua */
360 #endif
361 };
362 
363 static struct rodentparam {
364     int flags;
365     char *portname;		/* /dev/XXX */
366     int rtype;			/* MOUSE_PROTO_XXX */
367     int level;			/* operation level: 0 or greater */
368     int baudrate;
369     int rate;			/* report rate */
370     int resolution;		/* MOUSE_RES_XXX or a positive number */
371     int zmap[4];		/* MOUSE_{X|Y}AXIS or a button number */
372     int wmode;			/* wheel mode button number */
373     int mfd;			/* mouse file descriptor */
374     int cfd;			/* /dev/consolectl file descriptor */
375     int mremsfd;		/* mouse remote server file descriptor */
376     int mremcfd;		/* mouse remote client file descriptor */
377     long clickthreshold;	/* double click speed in msec */
378     long button2timeout;	/* 3 button emulation timeout */
379     mousehw_t hw;		/* mouse device hardware information */
380     mousemode_t mode;		/* protocol information */
381     float accelx;		/* Acceleration in the X axis */
382     float accely;		/* Acceleration in the Y axis */
383 } rodent = {
384     .flags = 0,
385     .portname = NULL,
386     .rtype = MOUSE_PROTO_UNKNOWN,
387     .level = -1,
388     .baudrate = 1200,
389     .rate = 0,
390     .resolution = MOUSE_RES_UNKNOWN,
391     .zmap = { 0, 0, 0, 0 },
392     .wmode = 0,
393     .mfd = -1,
394     .cfd = -1,
395     .mremsfd = -1,
396     .mremcfd = -1,
397     .clickthreshold = DFLT_CLICKTHRESHOLD,
398     .button2timeout = DFLT_BUTTON2TIMEOUT,
399     .accelx = 1.0,
400     .accely = 1.0,
401 };
402 
403 /* button status */
404 struct button_state {
405     int count;		/* 0: up, 1: single click, 2: double click,... */
406     struct timeval tv;	/* timestamp on the last button event */
407 };
408 static struct button_state	bstate[MOUSE_MAXBUTTON]; /* button state */
409 static struct button_state	*mstate[MOUSE_MAXBUTTON];/* mapped button st.*/
410 static struct button_state	zstate[4];		 /* Z/W axis state */
411 
412 /* state machine for 3 button emulation */
413 
414 #define S0	0	/* start */
415 #define S1	1	/* button 1 delayed down */
416 #define S2	2	/* button 3 delayed down */
417 #define S3	3	/* both buttons down -> button 2 down */
418 #define S4	4	/* button 1 delayed up */
419 #define S5	5	/* button 1 down */
420 #define S6	6	/* button 3 down */
421 #define S7	7	/* both buttons down */
422 #define S8	8	/* button 3 delayed up */
423 #define S9	9	/* button 1 or 3 up after S3 */
424 
425 #define A(b1, b3)	(((b1) ? 2 : 0) | ((b3) ? 1 : 0))
426 #define A_TIMEOUT	4
427 #define S_DELAYED(st)	(states[st].s[A_TIMEOUT] != (st))
428 
429 static struct {
430     int s[A_TIMEOUT + 1];
431     int buttons;
432     int mask;
433     int timeout;
434 } states[10] = {
435     /* S0 */
436     { { S0, S2, S1, S3, S0 }, 0, ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN), FALSE },
437     /* S1 */
438     { { S4, S2, S1, S3, S5 }, 0, ~MOUSE_BUTTON1DOWN, FALSE },
439     /* S2 */
440     { { S8, S2, S1, S3, S6 }, 0, ~MOUSE_BUTTON3DOWN, FALSE },
441     /* S3 */
442     { { S0, S9, S9, S3, S3 }, MOUSE_BUTTON2DOWN, ~0, FALSE },
443     /* S4 */
444     { { S0, S2, S1, S3, S0 }, MOUSE_BUTTON1DOWN, ~0, TRUE },
445     /* S5 */
446     { { S0, S2, S5, S7, S5 }, MOUSE_BUTTON1DOWN, ~0, FALSE },
447     /* S6 */
448     { { S0, S6, S1, S7, S6 }, MOUSE_BUTTON3DOWN, ~0, FALSE },
449     /* S7 */
450     { { S0, S6, S5, S7, S7 }, MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, ~0, FALSE },
451     /* S8 */
452     { { S0, S2, S1, S3, S0 }, MOUSE_BUTTON3DOWN, ~0, TRUE },
453     /* S9 */
454     { { S0, S9, S9, S3, S9 }, 0, ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN), FALSE },
455 };
456 static int		mouse_button_state;
457 static struct timeval	mouse_button_state_tv;
458 static int		mouse_move_delayed;
459 
460 static jmp_buf env;
461 
462 /* function prototypes */
463 
464 static void	moused(void);
465 static void	hup(int sig);
466 static void	cleanup(int sig);
467 static void	usage(void);
468 static void	log_or_warn(int log_pri, int errnum, const char *fmt, ...)
469 		    __printflike(3, 4);
470 
471 static int	r_identify(void);
472 static char	*r_if(int type);
473 static char	*r_name(int type);
474 static char	*r_model(int model);
475 static void	r_init(void);
476 static int	r_protocol(u_char b, mousestatus_t *act);
477 static int	r_statetrans(mousestatus_t *a1, mousestatus_t *a2, int trans);
478 static int	r_installmap(char *arg);
479 static void	r_map(mousestatus_t *act1, mousestatus_t *act2);
480 static void	r_timestamp(mousestatus_t *act);
481 static int	r_timeout(void);
482 static void	r_click(mousestatus_t *act);
483 static void	setmousespeed(int old, int new, unsigned cflag);
484 
485 static int	pnpwakeup1(void);
486 static int	pnpwakeup2(void);
487 static int	pnpgets(char *buf);
488 static int	pnpparse(pnpid_t *id, char *buf, int len);
489 static symtab_t	*pnpproto(pnpid_t *id);
490 
491 static symtab_t	*gettoken(symtab_t *tab, char *s, int len);
492 static char	*gettokenname(symtab_t *tab, int val);
493 
494 static void	mremote_serversetup();
495 static void	mremote_clientchg(int add);
496 
497 static int	kidspad(u_char rxc, mousestatus_t *act);
498 
499 static int	usbmodule(void);
500 
501 int
502 main(int argc, char *argv[])
503 {
504     int c;
505     int	i;
506     int	j;
507     int retry;
508 
509     for (i = 0; i < MOUSE_MAXBUTTON; ++i)
510 	mstate[i] = &bstate[i];
511 
512     while ((c = getopt(argc, argv, "3C:DE:F:I:PRS:a:cdfhi:l:m:p:r:st:w:z:")) != -1)
513 	switch(c) {
514 
515 	case '3':
516 	    rodent.flags |= Emulate3Button;
517 	    break;
518 
519 	case 'E':
520 	    rodent.button2timeout = atoi(optarg);
521 	    if ((rodent.button2timeout < 0) ||
522 		(rodent.button2timeout > MAX_BUTTON2TIMEOUT)) {
523 		warnx("invalid argument `%s'", optarg);
524 		usage();
525 	    }
526 	    break;
527 
528 	case 'a':
529 	    i = sscanf(optarg, "%f,%f", &rodent.accelx, &rodent.accely);
530 	    if (i == 0) {
531 		warnx("invalid acceleration argument '%s'", optarg);
532 		usage();
533 	    }
534 
535 	    if (i == 1)
536 		rodent.accely = rodent.accelx;
537 
538 	    break;
539 
540 	case 'c':
541 	    rodent.flags |= ChordMiddle;
542 	    break;
543 
544 	case 'd':
545 	    ++debug;
546 	    break;
547 
548 	case 'f':
549 	    nodaemon = TRUE;
550 	    break;
551 
552 	case 'i':
553 	    if (strcmp(optarg, "all") == 0)
554 		identify = ID_ALL;
555 	    else if (strcmp(optarg, "port") == 0)
556 		identify = ID_PORT;
557 	    else if (strcmp(optarg, "if") == 0)
558 		identify = ID_IF;
559 	    else if (strcmp(optarg, "type") == 0)
560 		identify = ID_TYPE;
561 	    else if (strcmp(optarg, "model") == 0)
562 		identify = ID_MODEL;
563 	    else {
564 		warnx("invalid argument `%s'", optarg);
565 		usage();
566 	    }
567 	    nodaemon = TRUE;
568 	    break;
569 
570 	case 'l':
571 	    rodent.level = atoi(optarg);
572 	    if ((rodent.level < 0) || (rodent.level > 4)) {
573 		warnx("invalid argument `%s'", optarg);
574 		usage();
575 	    }
576 	    break;
577 
578 	case 'm':
579 	    if (!r_installmap(optarg)) {
580 		warnx("invalid argument `%s'", optarg);
581 		usage();
582 	    }
583 	    break;
584 
585 	case 'p':
586 	    rodent.portname = optarg;
587 	    break;
588 
589 	case 'r':
590 	    if (strcmp(optarg, "high") == 0)
591 		rodent.resolution = MOUSE_RES_HIGH;
592 	    else if (strcmp(optarg, "medium-high") == 0)
593 		rodent.resolution = MOUSE_RES_HIGH;
594 	    else if (strcmp(optarg, "medium-low") == 0)
595 		rodent.resolution = MOUSE_RES_MEDIUMLOW;
596 	    else if (strcmp(optarg, "low") == 0)
597 		rodent.resolution = MOUSE_RES_LOW;
598 	    else if (strcmp(optarg, "default") == 0)
599 		rodent.resolution = MOUSE_RES_DEFAULT;
600 	    else {
601 		rodent.resolution = atoi(optarg);
602 		if (rodent.resolution <= 0) {
603 		    warnx("invalid argument `%s'", optarg);
604 		    usage();
605 		}
606 	    }
607 	    break;
608 
609 	case 's':
610 	    rodent.baudrate = 9600;
611 	    break;
612 
613 	case 'w':
614 	    i = atoi(optarg);
615 	    if ((i <= 0) || (i > MOUSE_MAXBUTTON)) {
616 		warnx("invalid argument `%s'", optarg);
617 		usage();
618 	    }
619 	    rodent.wmode = 1 << (i - 1);
620 	    break;
621 
622 	case 'z':
623 	    if (strcmp(optarg, "x") == 0)
624 		rodent.zmap[0] = MOUSE_XAXIS;
625 	    else if (strcmp(optarg, "y") == 0)
626 		rodent.zmap[0] = MOUSE_YAXIS;
627 	    else {
628 		i = atoi(optarg);
629 		/*
630 		 * Use button i for negative Z axis movement and
631 		 * button (i + 1) for positive Z axis movement.
632 		 */
633 		if ((i <= 0) || (i > MOUSE_MAXBUTTON - 1)) {
634 		    warnx("invalid argument `%s'", optarg);
635 		    usage();
636 		}
637 		rodent.zmap[0] = i;
638 		rodent.zmap[1] = i + 1;
639 		debug("optind: %d, optarg: '%s'", optind, optarg);
640 		for (j = 1; j < 4; ++j) {
641 		    if ((optind >= argc) || !isdigit(*argv[optind]))
642 			break;
643 		    i = atoi(argv[optind]);
644 		    if ((i <= 0) || (i > MOUSE_MAXBUTTON - 1)) {
645 			warnx("invalid argument `%s'", argv[optind]);
646 			usage();
647 		    }
648 		    rodent.zmap[j] = i;
649 		    ++optind;
650 		}
651 		if ((rodent.zmap[2] != 0) && (rodent.zmap[3] == 0))
652 		    rodent.zmap[3] = rodent.zmap[2] + 1;
653 	    }
654 	    break;
655 
656 	case 'C':
657 	    rodent.clickthreshold = atoi(optarg);
658 	    if ((rodent.clickthreshold < 0) ||
659 		(rodent.clickthreshold > MAX_CLICKTHRESHOLD)) {
660 		warnx("invalid argument `%s'", optarg);
661 		usage();
662 	    }
663 	    break;
664 
665 	case 'D':
666 	    rodent.flags |= ClearDTR;
667 	    break;
668 
669 	case 'F':
670 	    rodent.rate = atoi(optarg);
671 	    if (rodent.rate <= 0) {
672 		warnx("invalid argument `%s'", optarg);
673 		usage();
674 	    }
675 	    break;
676 
677 	case 'I':
678 	    pidfile = optarg;
679 	    break;
680 
681 	case 'P':
682 	    rodent.flags |= NoPnP;
683 	    break;
684 
685 	case 'R':
686 	    rodent.flags |= ClearRTS;
687 	    break;
688 
689 	case 'S':
690 	    rodent.baudrate = atoi(optarg);
691 	    if (rodent.baudrate <= 0) {
692 		warnx("invalid argument `%s'", optarg);
693 		usage();
694 	    }
695 	    debug("rodent baudrate %d", rodent.baudrate);
696 	    break;
697 
698 	case 't':
699 	    if (strcmp(optarg, "auto") == 0) {
700 		rodent.rtype = MOUSE_PROTO_UNKNOWN;
701 		rodent.flags &= ~NoPnP;
702 		rodent.level = -1;
703 		break;
704 	    }
705 	    for (i = 0; rnames[i]; i++)
706 		if (strcmp(optarg, rnames[i]) == 0) {
707 		    rodent.rtype = i;
708 		    rodent.flags |= NoPnP;
709 		    rodent.level = (i == MOUSE_PROTO_SYSMOUSE) ? 1 : 0;
710 		    break;
711 		}
712 	    if (rnames[i])
713 		break;
714 	    warnx("no such mouse type `%s'", optarg);
715 	    usage();
716 
717 	case 'h':
718 	case '?':
719 	default:
720 	    usage();
721 	}
722 
723     /* fix Z axis mapping */
724     for (i = 0; i < 4; ++i) {
725 	if (rodent.zmap[i] > 0) {
726 	    for (j = 0; j < MOUSE_MAXBUTTON; ++j) {
727 		if (mstate[j] == &bstate[rodent.zmap[i] - 1])
728 		    mstate[j] = &zstate[i];
729 	    }
730 	    rodent.zmap[i] = 1 << (rodent.zmap[i] - 1);
731 	}
732     }
733 
734     /* the default port name */
735     switch(rodent.rtype) {
736 
737     case MOUSE_PROTO_INPORT:
738 	/* INPORT and BUS are the same... */
739 	rodent.rtype = MOUSE_PROTO_BUS;
740 	/* FALLTHROUGH */
741     case MOUSE_PROTO_BUS:
742 	if (!rodent.portname)
743 	    rodent.portname = "/dev/mse0";
744 	break;
745 
746     case MOUSE_PROTO_PS2:
747 	if (!rodent.portname)
748 	    rodent.portname = "/dev/psm0";
749 	break;
750 
751     default:
752 	if (rodent.portname)
753 	    break;
754 	warnx("no port name specified");
755 	usage();
756     }
757 
758     retry = 1;
759     if (strncmp(rodent.portname, "/dev/ums", 8) == 0) {
760 	if (usbmodule() != 0)
761 	    retry = 5;
762     }
763 
764     for (;;) {
765 	if (setjmp(env) == 0) {
766 	    signal(SIGHUP, hup);
767 	    signal(SIGINT , cleanup);
768 	    signal(SIGQUIT, cleanup);
769 	    signal(SIGTERM, cleanup);
770 	    for (i = 0; i < retry; ++i) {
771 		if (i > 0)
772 		    sleep(2);
773 		rodent.mfd = open(rodent.portname, O_RDWR | O_NONBLOCK);
774 		if (rodent.mfd != -1 || errno != ENOENT)
775 		    break;
776 	    }
777 	    if (rodent.mfd == -1)
778 		logerr(1, "unable to open %s", rodent.portname);
779 	    if (r_identify() == MOUSE_PROTO_UNKNOWN) {
780 		logwarnx("cannot determine mouse type on %s", rodent.portname);
781 		close(rodent.mfd);
782 		rodent.mfd = -1;
783 	    }
784 
785 	    /* print some information */
786 	    if (identify != ID_NONE) {
787 		if (identify == ID_ALL)
788 		    printf("%s %s %s %s\n",
789 			rodent.portname, r_if(rodent.hw.iftype),
790 			r_name(rodent.rtype), r_model(rodent.hw.model));
791 		else if (identify & ID_PORT)
792 		    printf("%s\n", rodent.portname);
793 		else if (identify & ID_IF)
794 		    printf("%s\n", r_if(rodent.hw.iftype));
795 		else if (identify & ID_TYPE)
796 		    printf("%s\n", r_name(rodent.rtype));
797 		else if (identify & ID_MODEL)
798 		    printf("%s\n", r_model(rodent.hw.model));
799 		exit(0);
800 	    } else {
801 		debug("port: %s  interface: %s  type: %s  model: %s",
802 		    rodent.portname, r_if(rodent.hw.iftype),
803 		    r_name(rodent.rtype), r_model(rodent.hw.model));
804 	    }
805 
806 	    if (rodent.mfd == -1) {
807 		/*
808 		 * We cannot continue because of error.  Exit if the
809 		 * program has not become a daemon.  Otherwise, block
810 		 * until the the user corrects the problem and issues SIGHUP.
811 		 */
812 		if (!background)
813 		    exit(1);
814 		sigpause(0);
815 	    }
816 
817 	    r_init();			/* call init function */
818 	    moused();
819 	}
820 
821 	if (rodent.mfd != -1)
822 	    close(rodent.mfd);
823 	if (rodent.cfd != -1)
824 	    close(rodent.cfd);
825 	rodent.mfd = rodent.cfd = -1;
826     }
827     /* NOT REACHED */
828 
829     exit(0);
830 }
831 
832 static int
833 usbmodule(void)
834 {
835     struct kld_file_stat fstat;
836     struct module_stat mstat;
837     int fileid, modid;
838     int loaded;
839 
840     for (loaded = 0, fileid = kldnext(0); !loaded && fileid > 0;
841 	 fileid = kldnext(fileid)) {
842 	fstat.version = sizeof(fstat);
843 	if (kldstat(fileid, &fstat) < 0)
844 	    continue;
845 	if (strncmp(fstat.name, "uhub/ums", 8) == 0) {
846 	    loaded = 1;
847 	    break;
848 	}
849 	for (modid = kldfirstmod(fileid); modid > 0;
850 	     modid = modfnext(modid)) {
851 	    mstat.version = sizeof(mstat);
852 	    if (modstat(modid, &mstat) < 0)
853 		continue;
854 	    if (strncmp(mstat.name, "uhub/ums", 8) == 0) {
855 		loaded = 1;
856 		break;
857 	    }
858 	}
859     }
860     if (!loaded) {
861 	if (kldload("ums") != -1)
862 	    return 1;
863 	if (errno != EEXIST)
864 	    logerr(1, "unable to load USB mouse driver");
865     }
866     return 0;
867 }
868 
869 static void
870 moused(void)
871 {
872     struct mouse_info mouse;
873     mousestatus_t action0;		/* original mouse action */
874     mousestatus_t action;		/* interrim buffer */
875     mousestatus_t action2;		/* mapped action */
876     struct timeval timeout;
877     fd_set fds;
878     u_char b;
879     FILE *fp;
880     int flags;
881     int c;
882     int i;
883 
884     if ((rodent.cfd = open("/dev/consolectl", O_RDWR, 0)) == -1)
885 	logerr(1, "cannot open /dev/consolectl");
886 
887     if (!nodaemon && !background) {
888 	if (daemon(0, 0)) {
889 	    logerr(1, "failed to become a daemon");
890 	} else {
891 	    background = TRUE;
892 	    fp = fopen(pidfile, "w");
893 	    if (fp != NULL) {
894 		fprintf(fp, "%d\n", getpid());
895 		fclose(fp);
896 	    }
897 	}
898     }
899 
900     /* clear mouse data */
901     bzero(&action0, sizeof(action0));
902     bzero(&action, sizeof(action));
903     bzero(&action2, sizeof(action2));
904     bzero(&mouse, sizeof(mouse));
905     mouse_button_state = S0;
906     gettimeofday(&mouse_button_state_tv, NULL);
907     mouse_move_delayed = 0;
908     for (i = 0; i < MOUSE_MAXBUTTON; ++i) {
909 	bstate[i].count = 0;
910 	bstate[i].tv = mouse_button_state_tv;
911     }
912     for (i = 0; i < sizeof(zstate)/sizeof(zstate[0]); ++i) {
913 	zstate[i].count = 0;
914 	zstate[i].tv = mouse_button_state_tv;
915     }
916 
917     /* choose which ioctl command to use */
918     mouse.operation = MOUSE_MOTION_EVENT;
919     extioctl = (ioctl(rodent.cfd, CONS_MOUSECTL, &mouse) == 0);
920 
921     /* process mouse data */
922     timeout.tv_sec = 0;
923     timeout.tv_usec = 20000;		/* 20 msec */
924     for (;;) {
925 
926 	FD_ZERO(&fds);
927 	FD_SET(rodent.mfd, &fds);
928 	if (rodent.mremsfd >= 0)
929 	    FD_SET(rodent.mremsfd, &fds);
930 	if (rodent.mremcfd >= 0)
931 	    FD_SET(rodent.mremcfd, &fds);
932 
933 	c = select(FD_SETSIZE, &fds, NULL, NULL,
934 		   (rodent.flags & Emulate3Button) ? &timeout : NULL);
935 	if (c < 0) {                    /* error */
936 	    logwarn("failed to read from mouse");
937 	    continue;
938 	} else if (c == 0) {            /* timeout */
939 	    /* assert(rodent.flags & Emulate3Button) */
940 	    action0.button = action0.obutton;
941 	    action0.dx = action0.dy = action0.dz = 0;
942 	    action0.flags = flags = 0;
943 	    if (r_timeout() && r_statetrans(&action0, &action, A_TIMEOUT)) {
944 		if (debug > 2)
945 		    debug("flags:%08x buttons:%08x obuttons:%08x",
946 			  action.flags, action.button, action.obutton);
947 	    } else {
948 		action0.obutton = action0.button;
949 		continue;
950 	    }
951 	} else {
952 	    /*  MouseRemote client connect/disconnect  */
953 	    if ((rodent.mremsfd >= 0) && FD_ISSET(rodent.mremsfd, &fds)) {
954 		mremote_clientchg(TRUE);
955 		continue;
956 	    }
957 	    if ((rodent.mremcfd >= 0) && FD_ISSET(rodent.mremcfd, &fds)) {
958 		mremote_clientchg(FALSE);
959 		continue;
960 	    }
961 	    /* mouse movement */
962 	    if (read(rodent.mfd, &b, 1) == -1) {
963 		if (errno == EWOULDBLOCK)
964 		    continue;
965 		else
966 		    return;
967 	    }
968 	    if ((flags = r_protocol(b, &action0)) == 0)
969 		continue;
970 	    r_timestamp(&action0);
971 	    r_statetrans(&action0, &action,
972 			 A(action0.button & MOUSE_BUTTON1DOWN,
973 			   action0.button & MOUSE_BUTTON3DOWN));
974 	    debug("flags:%08x buttons:%08x obuttons:%08x", action.flags,
975 		  action.button, action.obutton);
976 	}
977 	action0.obutton = action0.button;
978 	flags &= MOUSE_POSCHANGED;
979 	flags |= action.obutton ^ action.button;
980 	action.flags = flags;
981 
982 	if (flags) {			/* handler detected action */
983 	    r_map(&action, &action2);
984 	    debug("activity : buttons 0x%08x  dx %d  dy %d  dz %d",
985 		action2.button, action2.dx, action2.dy, action2.dz);
986 
987 	    if (extioctl) {
988 		r_click(&action2);
989 		if (action2.flags & MOUSE_POSCHANGED) {
990 		    mouse.operation = MOUSE_MOTION_EVENT;
991 		    mouse.u.data.buttons = action2.button;
992 		    mouse.u.data.x = action2.dx * rodent.accelx;
993 		    mouse.u.data.y = action2.dy * rodent.accely;
994 		    mouse.u.data.z = action2.dz;
995 		    if (debug < 2)
996 			ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
997 		}
998 	    } else {
999 		mouse.operation = MOUSE_ACTION;
1000 		mouse.u.data.buttons = action2.button;
1001 		mouse.u.data.x = action2.dx * rodent.accelx;
1002 		mouse.u.data.y = action2.dy * rodent.accely;
1003 		mouse.u.data.z = action2.dz;
1004 		if (debug < 2)
1005 		    ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1006 	    }
1007 
1008 	    /*
1009 	     * If the Z axis movement is mapped to an imaginary physical
1010 	     * button, we need to cook up a corresponding button `up' event
1011 	     * after sending a button `down' event.
1012 	     */
1013 	    if ((rodent.zmap[0] > 0) && (action.dz != 0)) {
1014 		action.obutton = action.button;
1015 		action.dx = action.dy = action.dz = 0;
1016 		r_map(&action, &action2);
1017 		debug("activity : buttons 0x%08x  dx %d  dy %d  dz %d",
1018 		    action2.button, action2.dx, action2.dy, action2.dz);
1019 
1020 		if (extioctl) {
1021 		    r_click(&action2);
1022 		} else {
1023 		    mouse.operation = MOUSE_ACTION;
1024 		    mouse.u.data.buttons = action2.button;
1025 		    mouse.u.data.x = mouse.u.data.y = mouse.u.data.z = 0;
1026 		    if (debug < 2)
1027 			ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1028 		}
1029 	    }
1030 	}
1031     }
1032     /* NOT REACHED */
1033 }
1034 
1035 static void
1036 hup(int sig)
1037 {
1038     longjmp(env, 1);
1039 }
1040 
1041 static void
1042 cleanup(int sig)
1043 {
1044     if (rodent.rtype == MOUSE_PROTO_X10MOUSEREM)
1045 	unlink(_PATH_MOUSEREMOTE);
1046     exit(0);
1047 }
1048 
1049 /**
1050  ** usage
1051  **
1052  ** Complain, and free the CPU for more worthy tasks
1053  **/
1054 static void
1055 usage(void)
1056 {
1057     fprintf(stderr, "%s\n%s\n%s\n%s\n",
1058 	"usage: moused [-DRcdfs] [-I file] [-F rate] [-r resolution] [-S baudrate]",
1059 	"              [-a X [,Y]] [-C threshold] [-m N=M] [-w N] [-z N]",
1060 	"              [-t <mousetype>] [-l level] [-3 [-E timeout]] -p <port>",
1061 	"       moused [-d] -i <port|if|type|model|all> -p <port>");
1062     exit(1);
1063 }
1064 
1065 /*
1066  * Output an error message to syslog or stderr as appropriate. If
1067  * `errnum' is non-zero, append its string form to the message.
1068  */
1069 static void
1070 log_or_warn(int log_pri, int errnum, const char *fmt, ...)
1071 {
1072 	va_list ap;
1073 	char buf[256];
1074 
1075 	va_start(ap, fmt);
1076 	vsnprintf(buf, sizeof(buf), fmt, ap);
1077 	va_end(ap);
1078 	if (errnum) {
1079 		strlcat(buf, ": ", sizeof(buf));
1080 		strlcat(buf, strerror(errnum), sizeof(buf));
1081 	}
1082 
1083 	if (background)
1084 		syslog(log_pri, "%s", buf);
1085 	else
1086 		warnx("%s", buf);
1087 }
1088 
1089 /**
1090  ** Mouse interface code, courtesy of XFree86 3.1.2.
1091  **
1092  ** Note: Various bits have been trimmed, and in my shortsighted enthusiasm
1093  ** to clean, reformat and rationalise naming, it's quite possible that
1094  ** some things in here have been broken.
1095  **
1096  ** I hope not 8)
1097  **
1098  ** The following code is derived from a module marked :
1099  **/
1100 
1101 /* $XConsortium: xf86_Mouse.c,v 1.2 94/10/12 20:33:21 kaleb Exp $ */
1102 /* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.2 1995/01/28
1103  17:03:40 dawes Exp $ */
1104 /*
1105  *
1106  * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
1107  * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
1108  *
1109  * Permission to use, copy, modify, distribute, and sell this software and its
1110  * documentation for any purpose is hereby granted without fee, provided that
1111  * the above copyright notice appear in all copies and that both that
1112  * copyright notice and this permission notice appear in supporting
1113  * documentation, and that the names of Thomas Roell and David Dawes not be
1114  * used in advertising or publicity pertaining to distribution of the
1115  * software without specific, written prior permission.  Thomas Roell
1116  * and David Dawes makes no representations about the suitability of this
1117  * software for any purpose.  It is provided "as is" without express or
1118  * implied warranty.
1119  *
1120  * THOMAS ROELL AND DAVID DAWES DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
1121  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
1122  * FITNESS, IN NO EVENT SHALL THOMAS ROELL OR DAVID DAWES BE LIABLE FOR ANY
1123  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
1124  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
1125  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1126  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1127  *
1128  */
1129 
1130 /**
1131  ** GlidePoint support from XFree86 3.2.
1132  ** Derived from the module:
1133  **/
1134 
1135 /* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.19 1996/10/16 14:40:51 dawes Exp $ */
1136 /* $XConsortium: xf86_Mouse.c /main/10 1996/01/30 15:16:12 kaleb $ */
1137 
1138 /* the following table must be ordered by MOUSE_PROTO_XXX in mouse.h */
1139 static unsigned char proto[][7] = {
1140     /*  hd_mask hd_id   dp_mask dp_id   bytes b4_mask b4_id */
1141     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* MicroSoft */
1142     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* MouseSystems */
1143     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* Logitech */
1144     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MMSeries */
1145     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* MouseMan */
1146     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* Bus */
1147     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* InPort */
1148     {	0xc0,	0x00,	0x00,	0x00,	3,    0x00,  0xff }, /* PS/2 mouse */
1149     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MM HitTablet */
1150     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* GlidePoint */
1151     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x3f,  0x00 }, /* IntelliMouse */
1152     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* ThinkingMouse */
1153     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* sysmouse */
1154     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* X10 MouseRem */
1155     {	0x80,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* KIDSPAD */
1156     {	0xc3,	0xc0,	0x00,	0x00,	6,    0x00,  0xff }, /* VersaPad */
1157     {	0x00,	0x00,	0x00,	0x00,	1,    0x00,  0xff }, /* JogDial */
1158 #if notyet
1159     {	0xf8,	0x80,	0x00,	0x00,	5,   ~0x2f,  0x10 }, /* Mariqua */
1160 #endif
1161 };
1162 static unsigned char cur_proto[7];
1163 
1164 static int
1165 r_identify(void)
1166 {
1167     char pnpbuf[256];	/* PnP identifier string may be up to 256 bytes long */
1168     pnpid_t pnpid;
1169     symtab_t *t;
1170     int level;
1171     int len;
1172 
1173     /* set the driver operation level, if applicable */
1174     if (rodent.level < 0)
1175 	rodent.level = 1;
1176     ioctl(rodent.mfd, MOUSE_SETLEVEL, &rodent.level);
1177     rodent.level = (ioctl(rodent.mfd, MOUSE_GETLEVEL, &level) == 0) ? level : 0;
1178 
1179     /*
1180      * Interrogate the driver and get some intelligence on the device...
1181      * The following ioctl functions are not always supported by device
1182      * drivers.  When the driver doesn't support them, we just trust the
1183      * user to supply valid information.
1184      */
1185     rodent.hw.iftype = MOUSE_IF_UNKNOWN;
1186     rodent.hw.model = MOUSE_MODEL_GENERIC;
1187     ioctl(rodent.mfd, MOUSE_GETHWINFO, &rodent.hw);
1188 
1189     if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1190 	bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1191     rodent.mode.protocol = MOUSE_PROTO_UNKNOWN;
1192     rodent.mode.rate = -1;
1193     rodent.mode.resolution = MOUSE_RES_UNKNOWN;
1194     rodent.mode.accelfactor = 0;
1195     rodent.mode.level = 0;
1196     if (ioctl(rodent.mfd, MOUSE_GETMODE, &rodent.mode) == 0) {
1197 	if ((rodent.mode.protocol == MOUSE_PROTO_UNKNOWN)
1198 	    || (rodent.mode.protocol >= sizeof(proto)/sizeof(proto[0]))) {
1199 	    logwarnx("unknown mouse protocol (%d)", rodent.mode.protocol);
1200 	    return MOUSE_PROTO_UNKNOWN;
1201 	} else {
1202 	    /* INPORT and BUS are the same... */
1203 	    if (rodent.mode.protocol == MOUSE_PROTO_INPORT)
1204 		rodent.mode.protocol = MOUSE_PROTO_BUS;
1205 	    if (rodent.mode.protocol != rodent.rtype) {
1206 		/* Hmm, the driver doesn't agree with the user... */
1207 		if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1208 		    logwarnx("mouse type mismatch (%s != %s), %s is assumed",
1209 			r_name(rodent.mode.protocol), r_name(rodent.rtype),
1210 			r_name(rodent.mode.protocol));
1211 		rodent.rtype = rodent.mode.protocol;
1212 		bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1213 	    }
1214 	}
1215 	cur_proto[4] = rodent.mode.packetsize;
1216 	cur_proto[0] = rodent.mode.syncmask[0];	/* header byte bit mask */
1217 	cur_proto[1] = rodent.mode.syncmask[1];	/* header bit pattern */
1218     }
1219 
1220     /* maybe this is a PnP mouse... */
1221     if (rodent.mode.protocol == MOUSE_PROTO_UNKNOWN) {
1222 
1223 	if (rodent.flags & NoPnP)
1224 	    return rodent.rtype;
1225 	if (((len = pnpgets(pnpbuf)) <= 0) || !pnpparse(&pnpid, pnpbuf, len))
1226 	    return rodent.rtype;
1227 
1228 	debug("PnP serial mouse: '%*.*s' '%*.*s' '%*.*s'",
1229 	    pnpid.neisaid, pnpid.neisaid, pnpid.eisaid,
1230 	    pnpid.ncompat, pnpid.ncompat, pnpid.compat,
1231 	    pnpid.ndescription, pnpid.ndescription, pnpid.description);
1232 
1233 	/* we have a valid PnP serial device ID */
1234 	rodent.hw.iftype = MOUSE_IF_SERIAL;
1235 	t = pnpproto(&pnpid);
1236 	if (t != NULL) {
1237 	    rodent.mode.protocol = t->val;
1238 	    rodent.hw.model = t->val2;
1239 	} else {
1240 	    rodent.mode.protocol = MOUSE_PROTO_UNKNOWN;
1241 	}
1242 	if (rodent.mode.protocol == MOUSE_PROTO_INPORT)
1243 	    rodent.mode.protocol = MOUSE_PROTO_BUS;
1244 
1245 	/* make final adjustment */
1246 	if (rodent.mode.protocol != MOUSE_PROTO_UNKNOWN) {
1247 	    if (rodent.mode.protocol != rodent.rtype) {
1248 		/* Hmm, the device doesn't agree with the user... */
1249 		if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1250 		    logwarnx("mouse type mismatch (%s != %s), %s is assumed",
1251 			r_name(rodent.mode.protocol), r_name(rodent.rtype),
1252 			r_name(rodent.mode.protocol));
1253 		rodent.rtype = rodent.mode.protocol;
1254 		bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1255 	    }
1256 	}
1257     }
1258 
1259     debug("proto params: %02x %02x %02x %02x %d %02x %02x",
1260 	cur_proto[0], cur_proto[1], cur_proto[2], cur_proto[3],
1261 	cur_proto[4], cur_proto[5], cur_proto[6]);
1262 
1263     return rodent.rtype;
1264 }
1265 
1266 static char *
1267 r_if(int iftype)
1268 {
1269     char *s;
1270 
1271     s = gettokenname(rifs, iftype);
1272     return (s == NULL) ? "unknown" : s;
1273 }
1274 
1275 static char *
1276 r_name(int type)
1277 {
1278     return ((type == MOUSE_PROTO_UNKNOWN)
1279 	|| (type > sizeof(rnames)/sizeof(rnames[0]) - 1))
1280 	? "unknown" : rnames[type];
1281 }
1282 
1283 static char *
1284 r_model(int model)
1285 {
1286     char *s;
1287 
1288     s = gettokenname(rmodels, model);
1289     return (s == NULL) ? "unknown" : s;
1290 }
1291 
1292 static void
1293 r_init(void)
1294 {
1295     unsigned char buf[16];	/* scrach buffer */
1296     fd_set fds;
1297     char *s;
1298     char c;
1299     int i;
1300 
1301     /**
1302      ** This comment is a little out of context here, but it contains
1303      ** some useful information...
1304      ********************************************************************
1305      **
1306      ** The following lines take care of the Logitech MouseMan protocols.
1307      **
1308      ** NOTE: There are different versions of both MouseMan and TrackMan!
1309      **       Hence I add another protocol P_LOGIMAN, which the user can
1310      **       specify as MouseMan in his XF86Config file. This entry was
1311      **       formerly handled as a special case of P_MS. However, people
1312      **       who don't have the middle button problem, can still specify
1313      **       Microsoft and use P_MS.
1314      **
1315      ** By default, these mice should use a 3 byte Microsoft protocol
1316      ** plus a 4th byte for the middle button. However, the mouse might
1317      ** have switched to a different protocol before we use it, so I send
1318      ** the proper sequence just in case.
1319      **
1320      ** NOTE: - all commands to (at least the European) MouseMan have to
1321      **         be sent at 1200 Baud.
1322      **       - each command starts with a '*'.
1323      **       - whenever the MouseMan receives a '*', it will switch back
1324      **	 to 1200 Baud. Hence I have to select the desired protocol
1325      **	 first, then select the baud rate.
1326      **
1327      ** The protocols supported by the (European) MouseMan are:
1328      **   -  5 byte packed binary protocol, as with the Mouse Systems
1329      **      mouse. Selected by sequence "*U".
1330      **   -  2 button 3 byte MicroSoft compatible protocol. Selected
1331      **      by sequence "*V".
1332      **   -  3 button 3+1 byte MicroSoft compatible protocol (default).
1333      **      Selected by sequence "*X".
1334      **
1335      ** The following baud rates are supported:
1336      **   -  1200 Baud (default). Selected by sequence "*n".
1337      **   -  9600 Baud. Selected by sequence "*q".
1338      **
1339      ** Selecting a sample rate is no longer supported with the MouseMan!
1340      ** Some additional lines in xf86Config.c take care of ill configured
1341      ** baud rates and sample rates. (The user will get an error.)
1342      */
1343 
1344     switch (rodent.rtype) {
1345 
1346     case MOUSE_PROTO_LOGI:
1347 	/*
1348 	 * The baud rate selection command must be sent at the current
1349 	 * baud rate; try all likely settings
1350 	 */
1351 	setmousespeed(9600, rodent.baudrate, rodentcflags[rodent.rtype]);
1352 	setmousespeed(4800, rodent.baudrate, rodentcflags[rodent.rtype]);
1353 	setmousespeed(2400, rodent.baudrate, rodentcflags[rodent.rtype]);
1354 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1355 	/* select MM series data format */
1356 	write(rodent.mfd, "S", 1);
1357 	setmousespeed(rodent.baudrate, rodent.baudrate,
1358 		      rodentcflags[MOUSE_PROTO_MM]);
1359 	/* select report rate/frequency */
1360 	if      (rodent.rate <= 0)   write(rodent.mfd, "O", 1);
1361 	else if (rodent.rate <= 15)  write(rodent.mfd, "J", 1);
1362 	else if (rodent.rate <= 27)  write(rodent.mfd, "K", 1);
1363 	else if (rodent.rate <= 42)  write(rodent.mfd, "L", 1);
1364 	else if (rodent.rate <= 60)  write(rodent.mfd, "R", 1);
1365 	else if (rodent.rate <= 85)  write(rodent.mfd, "M", 1);
1366 	else if (rodent.rate <= 125) write(rodent.mfd, "Q", 1);
1367 	else			     write(rodent.mfd, "N", 1);
1368 	break;
1369 
1370     case MOUSE_PROTO_LOGIMOUSEMAN:
1371 	/* The command must always be sent at 1200 baud */
1372 	setmousespeed(1200, 1200, rodentcflags[rodent.rtype]);
1373 	write(rodent.mfd, "*X", 2);
1374 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1375 	break;
1376 
1377     case MOUSE_PROTO_HITTAB:
1378 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1379 
1380 	/*
1381 	 * Initialize Hitachi PUMA Plus - Model 1212E to desired settings.
1382 	 * The tablet must be configured to be in MM mode, NO parity,
1383 	 * Binary Format.  xf86Info.sampleRate controls the sensativity
1384 	 * of the tablet.  We only use this tablet for it's 4-button puck
1385 	 * so we don't run in "Absolute Mode"
1386 	 */
1387 	write(rodent.mfd, "z8", 2);	/* Set Parity = "NONE" */
1388 	usleep(50000);
1389 	write(rodent.mfd, "zb", 2);	/* Set Format = "Binary" */
1390 	usleep(50000);
1391 	write(rodent.mfd, "@", 1);	/* Set Report Mode = "Stream" */
1392 	usleep(50000);
1393 	write(rodent.mfd, "R", 1);	/* Set Output Rate = "45 rps" */
1394 	usleep(50000);
1395 	write(rodent.mfd, "I\x20", 2);	/* Set Incrememtal Mode "20" */
1396 	usleep(50000);
1397 	write(rodent.mfd, "E", 1);	/* Set Data Type = "Relative */
1398 	usleep(50000);
1399 
1400 	/* Resolution is in 'lines per inch' on the Hitachi tablet */
1401 	if      (rodent.resolution == MOUSE_RES_LOW)		c = 'g';
1402 	else if (rodent.resolution == MOUSE_RES_MEDIUMLOW)	c = 'e';
1403 	else if (rodent.resolution == MOUSE_RES_MEDIUMHIGH)	c = 'h';
1404 	else if (rodent.resolution == MOUSE_RES_HIGH)		c = 'd';
1405 	else if (rodent.resolution <=   40)			c = 'g';
1406 	else if (rodent.resolution <=  100)			c = 'd';
1407 	else if (rodent.resolution <=  200)			c = 'e';
1408 	else if (rodent.resolution <=  500)			c = 'h';
1409 	else if (rodent.resolution <= 1000)			c = 'j';
1410 	else			c = 'd';
1411 	write(rodent.mfd, &c, 1);
1412 	usleep(50000);
1413 
1414 	write(rodent.mfd, "\021", 1);	/* Resume DATA output */
1415 	break;
1416 
1417     case MOUSE_PROTO_THINK:
1418 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1419 	/* the PnP ID string may be sent again, discard it */
1420 	usleep(200000);
1421 	i = FREAD;
1422 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1423 	/* send the command to initialize the beast */
1424 	for (s = "E5E5"; *s; ++s) {
1425 	    write(rodent.mfd, s, 1);
1426 	    FD_ZERO(&fds);
1427 	    FD_SET(rodent.mfd, &fds);
1428 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1429 		break;
1430 	    read(rodent.mfd, &c, 1);
1431 	    debug("%c", c);
1432 	    if (c != *s)
1433 		break;
1434 	}
1435 	break;
1436 
1437     case MOUSE_PROTO_JOGDIAL:
1438 	break;
1439     case MOUSE_PROTO_MSC:
1440 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1441 	if (rodent.flags & ClearDTR) {
1442 	   i = TIOCM_DTR;
1443 	   ioctl(rodent.mfd, TIOCMBIC, &i);
1444 	}
1445 	if (rodent.flags & ClearRTS) {
1446 	   i = TIOCM_RTS;
1447 	   ioctl(rodent.mfd, TIOCMBIC, &i);
1448 	}
1449 	break;
1450 
1451     case MOUSE_PROTO_SYSMOUSE:
1452 	if (rodent.hw.iftype == MOUSE_IF_SYSMOUSE)
1453 	    setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1454 	/* FALLTHROUGH */
1455 
1456     case MOUSE_PROTO_BUS:
1457     case MOUSE_PROTO_INPORT:
1458     case MOUSE_PROTO_PS2:
1459 	if (rodent.rate >= 0)
1460 	    rodent.mode.rate = rodent.rate;
1461 	if (rodent.resolution != MOUSE_RES_UNKNOWN)
1462 	    rodent.mode.resolution = rodent.resolution;
1463 	ioctl(rodent.mfd, MOUSE_SETMODE, &rodent.mode);
1464 	break;
1465 
1466     case MOUSE_PROTO_X10MOUSEREM:
1467 	mremote_serversetup();
1468 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1469 	break;
1470 
1471 
1472     case MOUSE_PROTO_VERSAPAD:
1473 	tcsendbreak(rodent.mfd, 0);	/* send break for 400 msec */
1474 	i = FREAD;
1475 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1476 	for (i = 0; i < 7; ++i) {
1477 	    FD_ZERO(&fds);
1478 	    FD_SET(rodent.mfd, &fds);
1479 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1480 		break;
1481 	    read(rodent.mfd, &c, 1);
1482 	    buf[i] = c;
1483 	}
1484 	debug("%s\n", buf);
1485 	if ((buf[0] != 'V') || (buf[1] != 'P')|| (buf[7] != '\r'))
1486 	    break;
1487 	setmousespeed(9600, rodent.baudrate, rodentcflags[rodent.rtype]);
1488 	tcsendbreak(rodent.mfd, 0);	/* send break for 400 msec again */
1489 	for (i = 0; i < 7; ++i) {
1490 	    FD_ZERO(&fds);
1491 	    FD_SET(rodent.mfd, &fds);
1492 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1493 		break;
1494 	    read(rodent.mfd, &c, 1);
1495 	    debug("%c", c);
1496 	    if (c != buf[i])
1497 		break;
1498 	}
1499 	i = FREAD;
1500 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1501 	break;
1502 
1503     default:
1504 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1505 	break;
1506     }
1507 }
1508 
1509 static int
1510 r_protocol(u_char rBuf, mousestatus_t *act)
1511 {
1512     /* MOUSE_MSS_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1513     static int butmapmss[4] = {	/* Microsoft, MouseMan, GlidePoint,
1514 				   IntelliMouse, Thinking Mouse */
1515 	0,
1516 	MOUSE_BUTTON3DOWN,
1517 	MOUSE_BUTTON1DOWN,
1518 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1519     };
1520     static int butmapmss2[4] = { /* Microsoft, MouseMan, GlidePoint,
1521 				    Thinking Mouse */
1522 	0,
1523 	MOUSE_BUTTON4DOWN,
1524 	MOUSE_BUTTON2DOWN,
1525 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
1526     };
1527     /* MOUSE_INTELLI_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1528     static int butmapintelli[4] = { /* IntelliMouse, NetMouse, Mie Mouse,
1529 				       MouseMan+ */
1530 	0,
1531 	MOUSE_BUTTON2DOWN,
1532 	MOUSE_BUTTON4DOWN,
1533 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
1534     };
1535     /* MOUSE_MSC_BUTTON?UP -> MOUSE_BUTTON?DOWN */
1536     static int butmapmsc[8] = {	/* MouseSystems, MMSeries, Logitech,
1537 				   Bus, sysmouse */
1538 	0,
1539 	MOUSE_BUTTON3DOWN,
1540 	MOUSE_BUTTON2DOWN,
1541 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1542 	MOUSE_BUTTON1DOWN,
1543 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1544 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1545 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1546     };
1547     /* MOUSE_PS2_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1548     static int butmapps2[8] = {	/* PS/2 */
1549 	0,
1550 	MOUSE_BUTTON1DOWN,
1551 	MOUSE_BUTTON3DOWN,
1552 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1553 	MOUSE_BUTTON2DOWN,
1554 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1555 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1556 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1557     };
1558     /* for Hitachi tablet */
1559     static int butmaphit[8] = {	/* MM HitTablet */
1560 	0,
1561 	MOUSE_BUTTON3DOWN,
1562 	MOUSE_BUTTON2DOWN,
1563 	MOUSE_BUTTON1DOWN,
1564 	MOUSE_BUTTON4DOWN,
1565 	MOUSE_BUTTON5DOWN,
1566 	MOUSE_BUTTON6DOWN,
1567 	MOUSE_BUTTON7DOWN,
1568     };
1569     /* for serial VersaPad */
1570     static int butmapversa[8] = { /* VersaPad */
1571 	0,
1572 	0,
1573 	MOUSE_BUTTON3DOWN,
1574 	MOUSE_BUTTON3DOWN,
1575 	MOUSE_BUTTON1DOWN,
1576 	MOUSE_BUTTON1DOWN,
1577 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1578 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1579     };
1580     /* for PS/2 VersaPad */
1581     static int butmapversaps2[8] = { /* VersaPad */
1582 	0,
1583 	MOUSE_BUTTON3DOWN,
1584 	0,
1585 	MOUSE_BUTTON3DOWN,
1586 	MOUSE_BUTTON1DOWN,
1587 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1588 	MOUSE_BUTTON1DOWN,
1589 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1590     };
1591     static int           pBufP = 0;
1592     static unsigned char pBuf[8];
1593     static int		 prev_x, prev_y;
1594     static int		 on = FALSE;
1595     int			 x, y;
1596 
1597     debug("received char 0x%x",(int)rBuf);
1598     if (rodent.rtype == MOUSE_PROTO_KIDSPAD)
1599 	return kidspad(rBuf, act) ;
1600 
1601     /*
1602      * Hack for resyncing: We check here for a package that is:
1603      *  a) illegal (detected by wrong data-package header)
1604      *  b) invalid (0x80 == -128 and that might be wrong for MouseSystems)
1605      *  c) bad header-package
1606      *
1607      * NOTE: b) is a voilation of the MouseSystems-Protocol, since values of
1608      *       -128 are allowed, but since they are very seldom we can easily
1609      *       use them as package-header with no button pressed.
1610      * NOTE/2: On a PS/2 mouse any byte is valid as a data byte. Furthermore,
1611      *         0x80 is not valid as a header byte. For a PS/2 mouse we skip
1612      *         checking data bytes.
1613      *         For resyncing a PS/2 mouse we require the two most significant
1614      *         bits in the header byte to be 0. These are the overflow bits,
1615      *         and in case of an overflow we actually lose sync. Overflows
1616      *         are very rare, however, and we quickly gain sync again after
1617      *         an overflow condition. This is the best we can do. (Actually,
1618      *         we could use bit 0x08 in the header byte for resyncing, since
1619      *         that bit is supposed to be always on, but nobody told
1620      *         Microsoft...)
1621      */
1622 
1623     if (pBufP != 0 && rodent.rtype != MOUSE_PROTO_PS2 &&
1624 	((rBuf & cur_proto[2]) != cur_proto[3] || rBuf == 0x80))
1625     {
1626 	pBufP = 0;		/* skip package */
1627     }
1628 
1629     if (pBufP == 0 && (rBuf & cur_proto[0]) != cur_proto[1])
1630 	return 0;
1631 
1632     /* is there an extra data byte? */
1633     if (pBufP >= cur_proto[4] && (rBuf & cur_proto[0]) != cur_proto[1])
1634     {
1635 	/*
1636 	 * Hack for Logitech MouseMan Mouse - Middle button
1637 	 *
1638 	 * Unfortunately this mouse has variable length packets: the standard
1639 	 * Microsoft 3 byte packet plus an optional 4th byte whenever the
1640 	 * middle button status changes.
1641 	 *
1642 	 * We have already processed the standard packet with the movement
1643 	 * and button info.  Now post an event message with the old status
1644 	 * of the left and right buttons and the updated middle button.
1645 	 */
1646 
1647 	/*
1648 	 * Even worse, different MouseMen and TrackMen differ in the 4th
1649 	 * byte: some will send 0x00/0x20, others 0x01/0x21, or even
1650 	 * 0x02/0x22, so I have to strip off the lower bits.
1651 	 *
1652 	 * [JCH-96/01/21]
1653 	 * HACK for ALPS "fourth button". (It's bit 0x10 of the "fourth byte"
1654 	 * and it is activated by tapping the glidepad with the finger! 8^)
1655 	 * We map it to bit bit3, and the reverse map in xf86Events just has
1656 	 * to be extended so that it is identified as Button 4. The lower
1657 	 * half of the reverse-map may remain unchanged.
1658 	 */
1659 
1660 	/*
1661 	 * [KY-97/08/03]
1662 	 * Receive the fourth byte only when preceding three bytes have
1663 	 * been detected (pBufP >= cur_proto[4]).  In the previous
1664 	 * versions, the test was pBufP == 0; thus, we may have mistakingly
1665 	 * received a byte even if we didn't see anything preceding
1666 	 * the byte.
1667 	 */
1668 
1669 	if ((rBuf & cur_proto[5]) != cur_proto[6]) {
1670 	    pBufP = 0;
1671 	    return 0;
1672 	}
1673 
1674 	switch (rodent.rtype) {
1675 #if notyet
1676 	case MOUSE_PROTO_MARIQUA:
1677 	    /*
1678 	     * This mouse has 16! buttons in addition to the standard
1679 	     * three of them.  They return 0x10 though 0x1f in the
1680 	     * so-called `ten key' mode and 0x30 though 0x3f in the
1681 	     * `function key' mode.  As there are only 31 bits for
1682 	     * button state (including the standard three), we ignore
1683 	     * the bit 0x20 and don't distinguish the two modes.
1684 	     */
1685 	    act->dx = act->dy = act->dz = 0;
1686 	    act->obutton = act->button;
1687 	    rBuf &= 0x1f;
1688 	    act->button = (1 << (rBuf - 13))
1689 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
1690 	    /*
1691 	     * FIXME: this is a button "down" event. There needs to be
1692 	     * a corresponding button "up" event... XXX
1693 	     */
1694 	    break;
1695 #endif /* notyet */
1696 	case MOUSE_PROTO_JOGDIAL:
1697 	    break;
1698 
1699 	/*
1700 	 * IntelliMouse, NetMouse (including NetMouse Pro) and Mie Mouse
1701 	 * always send the fourth byte, whereas the fourth byte is
1702 	 * optional for GlidePoint and ThinkingMouse. The fourth byte
1703 	 * is also optional for MouseMan+ and FirstMouse+ in their
1704 	 * native mode. It is always sent if they are in the IntelliMouse
1705 	 * compatible mode.
1706 	 */
1707 	case MOUSE_PROTO_INTELLI:	/* IntelliMouse, NetMouse, Mie Mouse,
1708 					   MouseMan+ */
1709 	    act->dx = act->dy = 0;
1710 	    act->dz = (rBuf & 0x08) ? (rBuf & 0x0f) - 16 : (rBuf & 0x0f);
1711 	    if ((act->dz >= 7) || (act->dz <= -7))
1712 		act->dz = 0;
1713 	    act->obutton = act->button;
1714 	    act->button = butmapintelli[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
1715 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
1716 	    break;
1717 
1718 	default:
1719 	    act->dx = act->dy = act->dz = 0;
1720 	    act->obutton = act->button;
1721 	    act->button = butmapmss2[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
1722 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
1723 	    break;
1724 	}
1725 
1726 	act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
1727 	    | (act->obutton ^ act->button);
1728 	pBufP = 0;
1729 	return act->flags;
1730     }
1731 
1732     if (pBufP >= cur_proto[4])
1733 	pBufP = 0;
1734     pBuf[pBufP++] = rBuf;
1735     if (pBufP != cur_proto[4])
1736 	return 0;
1737 
1738     /*
1739      * assembly full package
1740      */
1741 
1742     debug("assembled full packet (len %d) %x,%x,%x,%x,%x,%x,%x,%x",
1743 	cur_proto[4],
1744 	pBuf[0], pBuf[1], pBuf[2], pBuf[3],
1745 	pBuf[4], pBuf[5], pBuf[6], pBuf[7]);
1746 
1747     act->dz = 0;
1748     act->obutton = act->button;
1749     switch (rodent.rtype)
1750     {
1751     case MOUSE_PROTO_MS:		/* Microsoft */
1752     case MOUSE_PROTO_LOGIMOUSEMAN:	/* MouseMan/TrackMan */
1753     case MOUSE_PROTO_X10MOUSEREM:	/* X10 MouseRemote */
1754 	act->button = act->obutton & MOUSE_BUTTON4DOWN;
1755 	if (rodent.flags & ChordMiddle)
1756 	    act->button |= ((pBuf[0] & MOUSE_MSS_BUTTONS) == MOUSE_MSS_BUTTONS)
1757 		? MOUSE_BUTTON2DOWN
1758 		: butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
1759 	else
1760 	    act->button |= (act->obutton & MOUSE_BUTTON2DOWN)
1761 		| butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
1762 
1763 	/* Send X10 btn events to remote client (ensure -128-+127 range) */
1764 	if ((rodent.rtype == MOUSE_PROTO_X10MOUSEREM) &&
1765 	    ((pBuf[0] & 0xFC) == 0x44) && (pBuf[2] == 0x3F)) {
1766 	    if (rodent.mremcfd >= 0) {
1767 		unsigned char key = (signed char)(((pBuf[0] & 0x03) << 6) |
1768 						  (pBuf[1] & 0x3F));
1769 		write(rodent.mremcfd, &key, 1);
1770 	    }
1771 	    return 0;
1772 	}
1773 
1774 	act->dx = (signed char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
1775 	act->dy = (signed char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
1776 	break;
1777 
1778     case MOUSE_PROTO_GLIDEPOINT:	/* GlidePoint */
1779     case MOUSE_PROTO_THINK:		/* ThinkingMouse */
1780     case MOUSE_PROTO_INTELLI:		/* IntelliMouse, NetMouse, Mie Mouse,
1781 					   MouseMan+ */
1782 	act->button = (act->obutton & (MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN))
1783 	    | butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
1784 	act->dx = (signed char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
1785 	act->dy = (signed char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
1786 	break;
1787 
1788     case MOUSE_PROTO_MSC:		/* MouseSystems Corp */
1789 #if notyet
1790     case MOUSE_PROTO_MARIQUA:		/* Mariqua */
1791 #endif
1792 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_MSC_BUTTONS];
1793 	act->dx =    (signed char)(pBuf[1]) + (signed char)(pBuf[3]);
1794 	act->dy = - ((signed char)(pBuf[2]) + (signed char)(pBuf[4]));
1795 	break;
1796 
1797     case MOUSE_PROTO_JOGDIAL:		/* JogDial */
1798 	    if (rBuf == 0x6c)
1799 	      act->dz = -1;
1800 	    if (rBuf == 0x72)
1801 	      act->dz = 1;
1802 	    if (rBuf == 0x64)
1803 	      act->button = MOUSE_BUTTON1DOWN;
1804 	    if (rBuf == 0x75)
1805 	      act->button = 0;
1806 	break;
1807 
1808     case MOUSE_PROTO_HITTAB:		/* MM HitTablet */
1809 	act->button = butmaphit[pBuf[0] & 0x07];
1810 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
1811 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
1812 	break;
1813 
1814     case MOUSE_PROTO_MM:		/* MM Series */
1815     case MOUSE_PROTO_LOGI:		/* Logitech Mice */
1816 	act->button = butmapmsc[pBuf[0] & MOUSE_MSC_BUTTONS];
1817 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
1818 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
1819 	break;
1820 
1821     case MOUSE_PROTO_VERSAPAD:		/* VersaPad */
1822 	act->button = butmapversa[(pBuf[0] & MOUSE_VERSA_BUTTONS) >> 3];
1823 	act->button |= (pBuf[0] & MOUSE_VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
1824 	act->dx = act->dy = 0;
1825 	if (!(pBuf[0] & MOUSE_VERSA_IN_USE)) {
1826 	    on = FALSE;
1827 	    break;
1828 	}
1829 	x = (pBuf[2] << 6) | pBuf[1];
1830 	if (x & 0x800)
1831 	    x -= 0x1000;
1832 	y = (pBuf[4] << 6) | pBuf[3];
1833 	if (y & 0x800)
1834 	    y -= 0x1000;
1835 	if (on) {
1836 	    act->dx = prev_x - x;
1837 	    act->dy = prev_y - y;
1838 	} else {
1839 	    on = TRUE;
1840 	}
1841 	prev_x = x;
1842 	prev_y = y;
1843 	break;
1844 
1845     case MOUSE_PROTO_BUS:		/* Bus */
1846     case MOUSE_PROTO_INPORT:		/* InPort */
1847 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_MSC_BUTTONS];
1848 	act->dx =   (signed char)pBuf[1];
1849 	act->dy = - (signed char)pBuf[2];
1850 	break;
1851 
1852     case MOUSE_PROTO_PS2:		/* PS/2 */
1853 	act->button = butmapps2[pBuf[0] & MOUSE_PS2_BUTTONS];
1854 	act->dx = (pBuf[0] & MOUSE_PS2_XNEG) ?    pBuf[1] - 256  :  pBuf[1];
1855 	act->dy = (pBuf[0] & MOUSE_PS2_YNEG) ?  -(pBuf[2] - 256) : -pBuf[2];
1856 	/*
1857 	 * Moused usually operates the psm driver at the operation level 1
1858 	 * which sends mouse data in MOUSE_PROTO_SYSMOUSE protocol.
1859 	 * The following code takes effect only when the user explicitly
1860 	 * requets the level 2 at which wheel movement and additional button
1861 	 * actions are encoded in model-dependent formats. At the level 0
1862 	 * the following code is no-op because the psm driver says the model
1863 	 * is MOUSE_MODEL_GENERIC.
1864 	 */
1865 	switch (rodent.hw.model) {
1866 	case MOUSE_MODEL_EXPLORER:
1867 	    /* wheel and additional button data is in the fourth byte */
1868 	    act->dz = (pBuf[3] & MOUSE_EXPLORER_ZNEG)
1869 		? (pBuf[3] & 0x0f) - 16 : (pBuf[3] & 0x0f);
1870 	    act->button |= (pBuf[3] & MOUSE_EXPLORER_BUTTON4DOWN)
1871 		? MOUSE_BUTTON4DOWN : 0;
1872 	    act->button |= (pBuf[3] & MOUSE_EXPLORER_BUTTON5DOWN)
1873 		? MOUSE_BUTTON5DOWN : 0;
1874 	    break;
1875 	case MOUSE_MODEL_INTELLI:
1876 	case MOUSE_MODEL_NET:
1877 	    /* wheel data is in the fourth byte */
1878 	    act->dz = (signed char)pBuf[3];
1879 	    if ((act->dz >= 7) || (act->dz <= -7))
1880 		act->dz = 0;
1881 	    /* some compatible mice may have additional buttons */
1882 	    act->button |= (pBuf[0] & MOUSE_PS2INTELLI_BUTTON4DOWN)
1883 		? MOUSE_BUTTON4DOWN : 0;
1884 	    act->button |= (pBuf[0] & MOUSE_PS2INTELLI_BUTTON5DOWN)
1885 		? MOUSE_BUTTON5DOWN : 0;
1886 	    break;
1887 	case MOUSE_MODEL_MOUSEMANPLUS:
1888 	    if (((pBuf[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
1889 		    && (abs(act->dx) > 191)
1890 		    && MOUSE_PS2PLUS_CHECKBITS(pBuf)) {
1891 		/* the extended data packet encodes button and wheel events */
1892 		switch (MOUSE_PS2PLUS_PACKET_TYPE(pBuf)) {
1893 		case 1:
1894 		    /* wheel data packet */
1895 		    act->dx = act->dy = 0;
1896 		    if (pBuf[2] & 0x80) {
1897 			/* horizontal roller count - ignore it XXX*/
1898 		    } else {
1899 			/* vertical roller count */
1900 			act->dz = (pBuf[2] & MOUSE_PS2PLUS_ZNEG)
1901 			    ? (pBuf[2] & 0x0f) - 16 : (pBuf[2] & 0x0f);
1902 		    }
1903 		    act->button |= (pBuf[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
1904 			? MOUSE_BUTTON4DOWN : 0;
1905 		    act->button |= (pBuf[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
1906 			? MOUSE_BUTTON5DOWN : 0;
1907 		    break;
1908 		case 2:
1909 		    /* this packet type is reserved by Logitech */
1910 		    /*
1911 		     * IBM ScrollPoint Mouse uses this packet type to
1912 		     * encode both vertical and horizontal scroll movement.
1913 		     */
1914 		    act->dx = act->dy = 0;
1915 		    /* horizontal roller count */
1916 		    if (pBuf[2] & 0x0f)
1917 			act->dz = (pBuf[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
1918 		    /* vertical roller count */
1919 		    if (pBuf[2] & 0xf0)
1920 			act->dz = (pBuf[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
1921 #if 0
1922 		    /* vertical roller count */
1923 		    act->dz = (pBuf[2] & MOUSE_SPOINT_ZNEG)
1924 			? ((pBuf[2] >> 4) & 0x0f) - 16
1925 			: ((pBuf[2] >> 4) & 0x0f);
1926 		    /* horizontal roller count */
1927 		    act->dw = (pBuf[2] & MOUSE_SPOINT_WNEG)
1928 			? (pBuf[2] & 0x0f) - 16 : (pBuf[2] & 0x0f);
1929 #endif
1930 		    break;
1931 		case 0:
1932 		    /* device type packet - shouldn't happen */
1933 		    /* FALLTHROUGH */
1934 		default:
1935 		    act->dx = act->dy = 0;
1936 		    act->button = act->obutton;
1937 		    debug("unknown PS2++ packet type %d: 0x%02x 0x%02x 0x%02x\n",
1938 			  MOUSE_PS2PLUS_PACKET_TYPE(pBuf),
1939 			  pBuf[0], pBuf[1], pBuf[2]);
1940 		    break;
1941 		}
1942 	    } else {
1943 		/* preserve button states */
1944 		act->button |= act->obutton & MOUSE_EXTBUTTONS;
1945 	    }
1946 	    break;
1947 	case MOUSE_MODEL_GLIDEPOINT:
1948 	    /* `tapping' action */
1949 	    act->button |= ((pBuf[0] & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
1950 	    break;
1951 	case MOUSE_MODEL_NETSCROLL:
1952 	    /* three addtional bytes encode buttons and wheel events */
1953 	    act->button |= (pBuf[3] & MOUSE_PS2_BUTTON3DOWN)
1954 		? MOUSE_BUTTON4DOWN : 0;
1955 	    act->button |= (pBuf[3] & MOUSE_PS2_BUTTON1DOWN)
1956 		? MOUSE_BUTTON5DOWN : 0;
1957 	    act->dz = (pBuf[3] & MOUSE_PS2_XNEG) ? pBuf[4] - 256 : pBuf[4];
1958 	    break;
1959 	case MOUSE_MODEL_THINK:
1960 	    /* the fourth button state in the first byte */
1961 	    act->button |= (pBuf[0] & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
1962 	    break;
1963 	case MOUSE_MODEL_VERSAPAD:
1964 	    act->button = butmapversaps2[pBuf[0] & MOUSE_PS2VERSA_BUTTONS];
1965 	    act->button |=
1966 		(pBuf[0] & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
1967 	    act->dx = act->dy = 0;
1968 	    if (!(pBuf[0] & MOUSE_PS2VERSA_IN_USE)) {
1969 		on = FALSE;
1970 		break;
1971 	    }
1972 	    x = ((pBuf[4] << 8) & 0xf00) | pBuf[1];
1973 	    if (x & 0x800)
1974 		x -= 0x1000;
1975 	    y = ((pBuf[4] << 4) & 0xf00) | pBuf[2];
1976 	    if (y & 0x800)
1977 		y -= 0x1000;
1978 	    if (on) {
1979 		act->dx = prev_x - x;
1980 		act->dy = prev_y - y;
1981 	    } else {
1982 		on = TRUE;
1983 	    }
1984 	    prev_x = x;
1985 	    prev_y = y;
1986 	    break;
1987 	case MOUSE_MODEL_4D:
1988 	    act->dx = (pBuf[1] & 0x80) ?    pBuf[1] - 256  :  pBuf[1];
1989 	    act->dy = (pBuf[2] & 0x80) ?  -(pBuf[2] - 256) : -pBuf[2];
1990 	    switch (pBuf[0] & MOUSE_4D_WHEELBITS) {
1991 	    case 0x10:
1992 		act->dz = 1;
1993 		break;
1994 	    case 0x30:
1995 		act->dz = -1;
1996 		break;
1997 	    case 0x40:	/* 2nd wheel rolling right XXX */
1998 		act->dz = 2;
1999 		break;
2000 	    case 0xc0:	/* 2nd wheel rolling left XXX */
2001 		act->dz = -2;
2002 		break;
2003 	    }
2004 	    break;
2005 	case MOUSE_MODEL_4DPLUS:
2006 	    if ((act->dx < 16 - 256) && (act->dy > 256 - 16)) {
2007 		act->dx = act->dy = 0;
2008 		if (pBuf[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2009 		    act->button |= MOUSE_BUTTON4DOWN;
2010 		act->dz = (pBuf[2] & MOUSE_4DPLUS_ZNEG)
2011 			      ? ((pBuf[2] & 0x07) - 8) : (pBuf[2] & 0x07);
2012 	    } else {
2013 		/* preserve previous button states */
2014 		act->button |= act->obutton & MOUSE_EXTBUTTONS;
2015 	    }
2016 	    break;
2017 	case MOUSE_MODEL_GENERIC:
2018 	default:
2019 	    break;
2020 	}
2021 	break;
2022 
2023     case MOUSE_PROTO_SYSMOUSE:		/* sysmouse */
2024 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_SYS_STDBUTTONS];
2025 	act->dx =    (signed char)(pBuf[1]) + (signed char)(pBuf[3]);
2026 	act->dy = - ((signed char)(pBuf[2]) + (signed char)(pBuf[4]));
2027 	if (rodent.level == 1) {
2028 	    act->dz = ((signed char)(pBuf[5] << 1) + (signed char)(pBuf[6] << 1)) >> 1;
2029 	    act->button |= ((~pBuf[7] & MOUSE_SYS_EXTBUTTONS) << 3);
2030 	}
2031 	break;
2032 
2033     default:
2034 	return 0;
2035     }
2036     /*
2037      * We don't reset pBufP here yet, as there may be an additional data
2038      * byte in some protocols. See above.
2039      */
2040 
2041     /* has something changed? */
2042     act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
2043 	| (act->obutton ^ act->button);
2044 
2045     return act->flags;
2046 }
2047 
2048 static int
2049 r_statetrans(mousestatus_t *a1, mousestatus_t *a2, int trans)
2050 {
2051     int changed;
2052     int flags;
2053 
2054     a2->dx = a1->dx;
2055     a2->dy = a1->dy;
2056     a2->dz = a1->dz;
2057     a2->obutton = a2->button;
2058     a2->button = a1->button;
2059     a2->flags = a1->flags;
2060     changed = FALSE;
2061 
2062     if (rodent.flags & Emulate3Button) {
2063 	if (debug > 2)
2064 	    debug("state:%d, trans:%d -> state:%d",
2065 		  mouse_button_state, trans,
2066 		  states[mouse_button_state].s[trans]);
2067 	/*
2068 	 * Avoid re-ordering button and movement events. While a button
2069 	 * event is deferred, throw away up to BUTTON2_MAXMOVE movement
2070 	 * events to allow for mouse jitter. If more movement events
2071 	 * occur, then complete the deferred button events immediately.
2072 	 */
2073 	if ((a2->dx != 0 || a2->dy != 0) &&
2074 	    S_DELAYED(states[mouse_button_state].s[trans])) {
2075 		if (++mouse_move_delayed > BUTTON2_MAXMOVE) {
2076 			mouse_move_delayed = 0;
2077 			mouse_button_state =
2078 			    states[mouse_button_state].s[A_TIMEOUT];
2079 			changed = TRUE;
2080 		} else
2081 			a2->dx = a2->dy = 0;
2082 	} else
2083 		mouse_move_delayed = 0;
2084 	if (mouse_button_state != states[mouse_button_state].s[trans])
2085 		changed = TRUE;
2086 	if (changed)
2087 		gettimeofday(&mouse_button_state_tv, NULL);
2088 	mouse_button_state = states[mouse_button_state].s[trans];
2089 	a2->button &=
2090 	    ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN);
2091 	a2->button &= states[mouse_button_state].mask;
2092 	a2->button |= states[mouse_button_state].buttons;
2093 	flags = a2->flags & MOUSE_POSCHANGED;
2094 	flags |= a2->obutton ^ a2->button;
2095 	if (flags & MOUSE_BUTTON2DOWN) {
2096 	    a2->flags = flags & MOUSE_BUTTON2DOWN;
2097 	    r_timestamp(a2);
2098 	}
2099 	a2->flags = flags;
2100     }
2101     return changed;
2102 }
2103 
2104 /* phisical to logical button mapping */
2105 static int p2l[MOUSE_MAXBUTTON] = {
2106     MOUSE_BUTTON1DOWN, MOUSE_BUTTON2DOWN, MOUSE_BUTTON3DOWN, MOUSE_BUTTON4DOWN,
2107     MOUSE_BUTTON5DOWN, MOUSE_BUTTON6DOWN, MOUSE_BUTTON7DOWN, MOUSE_BUTTON8DOWN,
2108     0x00000100,        0x00000200,        0x00000400,        0x00000800,
2109     0x00001000,        0x00002000,        0x00004000,        0x00008000,
2110     0x00010000,        0x00020000,        0x00040000,        0x00080000,
2111     0x00100000,        0x00200000,        0x00400000,        0x00800000,
2112     0x01000000,        0x02000000,        0x04000000,        0x08000000,
2113     0x10000000,        0x20000000,        0x40000000,
2114 };
2115 
2116 static char *
2117 skipspace(char *s)
2118 {
2119     while(isspace(*s))
2120 	++s;
2121     return s;
2122 }
2123 
2124 static int
2125 r_installmap(char *arg)
2126 {
2127     int pbutton;
2128     int lbutton;
2129     char *s;
2130 
2131     while (*arg) {
2132 	arg = skipspace(arg);
2133 	s = arg;
2134 	while (isdigit(*arg))
2135 	    ++arg;
2136 	arg = skipspace(arg);
2137 	if ((arg <= s) || (*arg != '='))
2138 	    return FALSE;
2139 	lbutton = atoi(s);
2140 
2141 	arg = skipspace(++arg);
2142 	s = arg;
2143 	while (isdigit(*arg))
2144 	    ++arg;
2145 	if ((arg <= s) || (!isspace(*arg) && (*arg != '\0')))
2146 	    return FALSE;
2147 	pbutton = atoi(s);
2148 
2149 	if ((lbutton <= 0) || (lbutton > MOUSE_MAXBUTTON))
2150 	    return FALSE;
2151 	if ((pbutton <= 0) || (pbutton > MOUSE_MAXBUTTON))
2152 	    return FALSE;
2153 	p2l[pbutton - 1] = 1 << (lbutton - 1);
2154 	mstate[lbutton - 1] = &bstate[pbutton - 1];
2155     }
2156 
2157     return TRUE;
2158 }
2159 
2160 static void
2161 r_map(mousestatus_t *act1, mousestatus_t *act2)
2162 {
2163     register int pb;
2164     register int pbuttons;
2165     int lbuttons;
2166 
2167     pbuttons = act1->button;
2168     lbuttons = 0;
2169 
2170     act2->obutton = act2->button;
2171     if (pbuttons & rodent.wmode) {
2172 	pbuttons &= ~rodent.wmode;
2173 	act1->dz = act1->dy;
2174 	act1->dx = 0;
2175 	act1->dy = 0;
2176     }
2177     act2->dx = act1->dx;
2178     act2->dy = act1->dy;
2179     act2->dz = act1->dz;
2180 
2181     switch (rodent.zmap[0]) {
2182     case 0:	/* do nothing */
2183 	break;
2184     case MOUSE_XAXIS:
2185 	if (act1->dz != 0) {
2186 	    act2->dx = act1->dz;
2187 	    act2->dz = 0;
2188 	}
2189 	break;
2190     case MOUSE_YAXIS:
2191 	if (act1->dz != 0) {
2192 	    act2->dy = act1->dz;
2193 	    act2->dz = 0;
2194 	}
2195 	break;
2196     default:	/* buttons */
2197 	pbuttons &= ~(rodent.zmap[0] | rodent.zmap[1]
2198 		    | rodent.zmap[2] | rodent.zmap[3]);
2199 	if ((act1->dz < -1) && rodent.zmap[2]) {
2200 	    pbuttons |= rodent.zmap[2];
2201 	    zstate[2].count = 1;
2202 	} else if (act1->dz < 0) {
2203 	    pbuttons |= rodent.zmap[0];
2204 	    zstate[0].count = 1;
2205 	} else if ((act1->dz > 1) && rodent.zmap[3]) {
2206 	    pbuttons |= rodent.zmap[3];
2207 	    zstate[3].count = 1;
2208 	} else if (act1->dz > 0) {
2209 	    pbuttons |= rodent.zmap[1];
2210 	    zstate[1].count = 1;
2211 	}
2212 	act2->dz = 0;
2213 	break;
2214     }
2215 
2216     for (pb = 0; (pb < MOUSE_MAXBUTTON) && (pbuttons != 0); ++pb) {
2217 	lbuttons |= (pbuttons & 1) ? p2l[pb] : 0;
2218 	pbuttons >>= 1;
2219     }
2220     act2->button = lbuttons;
2221 
2222     act2->flags = ((act2->dx || act2->dy || act2->dz) ? MOUSE_POSCHANGED : 0)
2223 	| (act2->obutton ^ act2->button);
2224 }
2225 
2226 static void
2227 r_timestamp(mousestatus_t *act)
2228 {
2229     struct timeval tv;
2230     struct timeval tv1;
2231     struct timeval tv2;
2232     struct timeval tv3;
2233     int button;
2234     int mask;
2235     int i;
2236 
2237     mask = act->flags & MOUSE_BUTTONS;
2238 #if 0
2239     if (mask == 0)
2240 	return;
2241 #endif
2242 
2243     gettimeofday(&tv1, NULL);
2244 
2245     /* double click threshold */
2246     tv2.tv_sec = rodent.clickthreshold/1000;
2247     tv2.tv_usec = (rodent.clickthreshold%1000)*1000;
2248     timersub(&tv1, &tv2, &tv);
2249     debug("tv:  %ld %ld", tv.tv_sec, tv.tv_usec);
2250 
2251     /* 3 button emulation timeout */
2252     tv2.tv_sec = rodent.button2timeout/1000;
2253     tv2.tv_usec = (rodent.button2timeout%1000)*1000;
2254     timersub(&tv1, &tv2, &tv3);
2255 
2256     button = MOUSE_BUTTON1DOWN;
2257     for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2258 	if (mask & 1) {
2259 	    if (act->button & button) {
2260 		/* the button is down */
2261 		debug("  :  %ld %ld",
2262 		    bstate[i].tv.tv_sec, bstate[i].tv.tv_usec);
2263 		if (timercmp(&tv, &bstate[i].tv, >)) {
2264 		    bstate[i].count = 1;
2265 		} else {
2266 		    ++bstate[i].count;
2267 		}
2268 		bstate[i].tv = tv1;
2269 	    } else {
2270 		/* the button is up */
2271 		bstate[i].tv = tv1;
2272 	    }
2273 	} else {
2274 	    if (act->button & button) {
2275 		/* the button has been down */
2276 		if (timercmp(&tv3, &bstate[i].tv, >)) {
2277 		    bstate[i].count = 1;
2278 		    bstate[i].tv = tv1;
2279 		    act->flags |= button;
2280 		    debug("button %d timeout", i + 1);
2281 		}
2282 	    } else {
2283 		/* the button has been up */
2284 	    }
2285 	}
2286 	button <<= 1;
2287 	mask >>= 1;
2288     }
2289 }
2290 
2291 static int
2292 r_timeout(void)
2293 {
2294     struct timeval tv;
2295     struct timeval tv1;
2296     struct timeval tv2;
2297 
2298     if (states[mouse_button_state].timeout)
2299 	return TRUE;
2300     gettimeofday(&tv1, NULL);
2301     tv2.tv_sec = rodent.button2timeout/1000;
2302     tv2.tv_usec = (rodent.button2timeout%1000)*1000;
2303     timersub(&tv1, &tv2, &tv);
2304     return timercmp(&tv, &mouse_button_state_tv, >);
2305 }
2306 
2307 static void
2308 r_click(mousestatus_t *act)
2309 {
2310     struct mouse_info mouse;
2311     int button;
2312     int mask;
2313     int i;
2314 
2315     mask = act->flags & MOUSE_BUTTONS;
2316     if (mask == 0)
2317 	return;
2318 
2319     button = MOUSE_BUTTON1DOWN;
2320     for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2321 	if (mask & 1) {
2322 	    debug("mstate[%d]->count:%d", i, mstate[i]->count);
2323 	    if (act->button & button) {
2324 		/* the button is down */
2325 		mouse.u.event.value = mstate[i]->count;
2326 	    } else {
2327 		/* the button is up */
2328 		mouse.u.event.value = 0;
2329 	    }
2330 	    mouse.operation = MOUSE_BUTTON_EVENT;
2331 	    mouse.u.event.id = button;
2332 	    if (debug < 2)
2333 		ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
2334 	    debug("button %d  count %d", i + 1, mouse.u.event.value);
2335 	}
2336 	button <<= 1;
2337 	mask >>= 1;
2338     }
2339 }
2340 
2341 /* $XConsortium: posix_tty.c,v 1.3 95/01/05 20:42:55 kaleb Exp $ */
2342 /* $XFree86: xc/programs/Xserver/hw/xfree86/os-support/shared/posix_tty.c,v 3.4 1995/01/28 17:05:03 dawes Exp $ */
2343 /*
2344  * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
2345  *
2346  * Permission to use, copy, modify, distribute, and sell this software and its
2347  * documentation for any purpose is hereby granted without fee, provided that
2348  * the above copyright notice appear in all copies and that both that
2349  * copyright notice and this permission notice appear in supporting
2350  * documentation, and that the name of David Dawes
2351  * not be used in advertising or publicity pertaining to distribution of
2352  * the software without specific, written prior permission.
2353  * David Dawes makes no representations about the suitability of this
2354  * software for any purpose.  It is provided "as is" without express or
2355  * implied warranty.
2356  *
2357  * DAVID DAWES DISCLAIMS ALL WARRANTIES WITH REGARD TO
2358  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
2359  * FITNESS, IN NO EVENT SHALL DAVID DAWES BE LIABLE FOR
2360  * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
2361  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
2362  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
2363  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2364  *
2365  */
2366 
2367 
2368 static void
2369 setmousespeed(int old, int new, unsigned cflag)
2370 {
2371 	struct termios tty;
2372 	char *c;
2373 
2374 	if (tcgetattr(rodent.mfd, &tty) < 0)
2375 	{
2376 		logwarn("unable to get status of mouse fd");
2377 		return;
2378 	}
2379 
2380 	tty.c_iflag = IGNBRK | IGNPAR;
2381 	tty.c_oflag = 0;
2382 	tty.c_lflag = 0;
2383 	tty.c_cflag = (tcflag_t)cflag;
2384 	tty.c_cc[VTIME] = 0;
2385 	tty.c_cc[VMIN] = 1;
2386 
2387 	switch (old)
2388 	{
2389 	case 9600:
2390 		cfsetispeed(&tty, B9600);
2391 		cfsetospeed(&tty, B9600);
2392 		break;
2393 	case 4800:
2394 		cfsetispeed(&tty, B4800);
2395 		cfsetospeed(&tty, B4800);
2396 		break;
2397 	case 2400:
2398 		cfsetispeed(&tty, B2400);
2399 		cfsetospeed(&tty, B2400);
2400 		break;
2401 	case 1200:
2402 	default:
2403 		cfsetispeed(&tty, B1200);
2404 		cfsetospeed(&tty, B1200);
2405 	}
2406 
2407 	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
2408 	{
2409 		logwarn("unable to set status of mouse fd");
2410 		return;
2411 	}
2412 
2413 	switch (new)
2414 	{
2415 	case 9600:
2416 		c = "*q";
2417 		cfsetispeed(&tty, B9600);
2418 		cfsetospeed(&tty, B9600);
2419 		break;
2420 	case 4800:
2421 		c = "*p";
2422 		cfsetispeed(&tty, B4800);
2423 		cfsetospeed(&tty, B4800);
2424 		break;
2425 	case 2400:
2426 		c = "*o";
2427 		cfsetispeed(&tty, B2400);
2428 		cfsetospeed(&tty, B2400);
2429 		break;
2430 	case 1200:
2431 	default:
2432 		c = "*n";
2433 		cfsetispeed(&tty, B1200);
2434 		cfsetospeed(&tty, B1200);
2435 	}
2436 
2437 	if (rodent.rtype == MOUSE_PROTO_LOGIMOUSEMAN
2438 	    || rodent.rtype == MOUSE_PROTO_LOGI)
2439 	{
2440 		if (write(rodent.mfd, c, 2) != 2)
2441 		{
2442 			logwarn("unable to write to mouse fd");
2443 			return;
2444 		}
2445 	}
2446 	usleep(100000);
2447 
2448 	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
2449 		logwarn("unable to set status of mouse fd");
2450 }
2451 
2452 /*
2453  * PnP COM device support
2454  *
2455  * It's a simplistic implementation, but it works :-)
2456  * KY, 31/7/97.
2457  */
2458 
2459 /*
2460  * Try to elicit a PnP ID as described in
2461  * Microsoft, Hayes: "Plug and Play External COM Device Specification,
2462  * rev 1.00", 1995.
2463  *
2464  * The routine does not fully implement the COM Enumerator as par Section
2465  * 2.1 of the document.  In particular, we don't have idle state in which
2466  * the driver software monitors the com port for dynamic connection or
2467  * removal of a device at the port, because `moused' simply quits if no
2468  * device is found.
2469  *
2470  * In addition, as PnP COM device enumeration procedure slightly has
2471  * changed since its first publication, devices which follow earlier
2472  * revisions of the above spec. may fail to respond if the rev 1.0
2473  * procedure is used. XXX
2474  */
2475 static int
2476 pnpwakeup1(void)
2477 {
2478     struct timeval timeout;
2479     fd_set fds;
2480     int i;
2481 
2482     /*
2483      * This is the procedure described in rev 1.0 of PnP COM device spec.
2484      * Unfortunately, some devices which comform to earlier revisions of
2485      * the spec gets confused and do not return the ID string...
2486      */
2487     debug("PnP COM device rev 1.0 probe...");
2488 
2489     /* port initialization (2.1.2) */
2490     ioctl(rodent.mfd, TIOCMGET, &i);
2491     i |= TIOCM_DTR;		/* DTR = 1 */
2492     i &= ~TIOCM_RTS;		/* RTS = 0 */
2493     ioctl(rodent.mfd, TIOCMSET, &i);
2494     usleep(240000);
2495 
2496     /*
2497      * The PnP COM device spec. dictates that the mouse must set DSR
2498      * in response to DTR (by hardware or by software) and that if DSR is
2499      * not asserted, the host computer should think that there is no device
2500      * at this serial port.  But some mice just don't do that...
2501      */
2502     ioctl(rodent.mfd, TIOCMGET, &i);
2503     debug("modem status 0%o", i);
2504     if ((i & TIOCM_DSR) == 0)
2505 	return FALSE;
2506 
2507     /* port setup, 1st phase (2.1.3) */
2508     setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
2509     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
2510     ioctl(rodent.mfd, TIOCMBIC, &i);
2511     usleep(240000);
2512     i = TIOCM_DTR;		/* DTR = 1, RTS = 0 */
2513     ioctl(rodent.mfd, TIOCMBIS, &i);
2514     usleep(240000);
2515 
2516     /* wait for response, 1st phase (2.1.4) */
2517     i = FREAD;
2518     ioctl(rodent.mfd, TIOCFLUSH, &i);
2519     i = TIOCM_RTS;		/* DTR = 1, RTS = 1 */
2520     ioctl(rodent.mfd, TIOCMBIS, &i);
2521 
2522     /* try to read something */
2523     FD_ZERO(&fds);
2524     FD_SET(rodent.mfd, &fds);
2525     timeout.tv_sec = 0;
2526     timeout.tv_usec = 240000;
2527     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2528 	debug("pnpwakeup1(): valid response in first phase.");
2529 	return TRUE;
2530     }
2531 
2532     /* port setup, 2nd phase (2.1.5) */
2533     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
2534     ioctl(rodent.mfd, TIOCMBIC, &i);
2535     usleep(240000);
2536 
2537     /* wait for respose, 2nd phase (2.1.6) */
2538     i = FREAD;
2539     ioctl(rodent.mfd, TIOCFLUSH, &i);
2540     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
2541     ioctl(rodent.mfd, TIOCMBIS, &i);
2542 
2543     /* try to read something */
2544     FD_ZERO(&fds);
2545     FD_SET(rodent.mfd, &fds);
2546     timeout.tv_sec = 0;
2547     timeout.tv_usec = 240000;
2548     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2549 	debug("pnpwakeup1(): valid response in second phase.");
2550 	return TRUE;
2551     }
2552 
2553     return FALSE;
2554 }
2555 
2556 static int
2557 pnpwakeup2(void)
2558 {
2559     struct timeval timeout;
2560     fd_set fds;
2561     int i;
2562 
2563     /*
2564      * This is a simplified procedure; it simply toggles RTS.
2565      */
2566     debug("alternate probe...");
2567 
2568     ioctl(rodent.mfd, TIOCMGET, &i);
2569     i |= TIOCM_DTR;		/* DTR = 1 */
2570     i &= ~TIOCM_RTS;		/* RTS = 0 */
2571     ioctl(rodent.mfd, TIOCMSET, &i);
2572     usleep(240000);
2573 
2574     setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
2575 
2576     /* wait for respose */
2577     i = FREAD;
2578     ioctl(rodent.mfd, TIOCFLUSH, &i);
2579     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
2580     ioctl(rodent.mfd, TIOCMBIS, &i);
2581 
2582     /* try to read something */
2583     FD_ZERO(&fds);
2584     FD_SET(rodent.mfd, &fds);
2585     timeout.tv_sec = 0;
2586     timeout.tv_usec = 240000;
2587     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2588 	debug("pnpwakeup2(): valid response.");
2589 	return TRUE;
2590     }
2591 
2592     return FALSE;
2593 }
2594 
2595 static int
2596 pnpgets(char *buf)
2597 {
2598     struct timeval timeout;
2599     fd_set fds;
2600     int begin;
2601     int i;
2602     char c;
2603 
2604     if (!pnpwakeup1() && !pnpwakeup2()) {
2605 	/*
2606 	 * According to PnP spec, we should set DTR = 1 and RTS = 0 while
2607 	 * in idle state.  But, `moused' shall set DTR = RTS = 1 and proceed,
2608 	 * assuming there is something at the port even if it didn't
2609 	 * respond to the PnP enumeration procedure.
2610 	 */
2611 	i = TIOCM_DTR | TIOCM_RTS;		/* DTR = 1, RTS = 1 */
2612 	ioctl(rodent.mfd, TIOCMBIS, &i);
2613 	return 0;
2614     }
2615 
2616     /* collect PnP COM device ID (2.1.7) */
2617     begin = -1;
2618     i = 0;
2619     usleep(240000);	/* the mouse must send `Begin ID' within 200msec */
2620     while (read(rodent.mfd, &c, 1) == 1) {
2621 	/* we may see "M", or "M3..." before `Begin ID' */
2622 	buf[i++] = c;
2623 	if ((c == 0x08) || (c == 0x28)) {	/* Begin ID */
2624 	    debug("begin-id %02x", c);
2625 	    begin = i - 1;
2626 	    break;
2627 	}
2628 	debug("%c %02x", c, c);
2629 	if (i >= 256)
2630 	    break;
2631     }
2632     if (begin < 0) {
2633 	/* we haven't seen `Begin ID' in time... */
2634 	goto connect_idle;
2635     }
2636 
2637     ++c;			/* make it `End ID' */
2638     for (;;) {
2639 	FD_ZERO(&fds);
2640 	FD_SET(rodent.mfd, &fds);
2641 	timeout.tv_sec = 0;
2642 	timeout.tv_usec = 240000;
2643 	if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) <= 0)
2644 	    break;
2645 
2646 	read(rodent.mfd, &buf[i], 1);
2647 	if (buf[i++] == c)	/* End ID */
2648 	    break;
2649 	if (i >= 256)
2650 	    break;
2651     }
2652     if (begin > 0) {
2653 	i -= begin;
2654 	bcopy(&buf[begin], &buf[0], i);
2655     }
2656     /* string may not be human readable... */
2657     debug("len:%d, '%-*.*s'", i, i, i, buf);
2658 
2659     if (buf[i - 1] == c)
2660 	return i;		/* a valid PnP string */
2661 
2662     /*
2663      * According to PnP spec, we should set DTR = 1 and RTS = 0 while
2664      * in idle state.  But, `moused' shall leave the modem control lines
2665      * as they are. See above.
2666      */
2667 connect_idle:
2668 
2669     /* we may still have something in the buffer */
2670     return ((i > 0) ? i : 0);
2671 }
2672 
2673 static int
2674 pnpparse(pnpid_t *id, char *buf, int len)
2675 {
2676     char s[3];
2677     int offset;
2678     int sum = 0;
2679     int i, j;
2680 
2681     id->revision = 0;
2682     id->eisaid = NULL;
2683     id->serial = NULL;
2684     id->class = NULL;
2685     id->compat = NULL;
2686     id->description = NULL;
2687     id->neisaid = 0;
2688     id->nserial = 0;
2689     id->nclass = 0;
2690     id->ncompat = 0;
2691     id->ndescription = 0;
2692 
2693     if ((buf[0] != 0x28) && (buf[0] != 0x08)) {
2694 	/* non-PnP mice */
2695 	switch(buf[0]) {
2696 	default:
2697 	    return FALSE;
2698 	case 'M': /* Microsoft */
2699 	    id->eisaid = "PNP0F01";
2700 	    break;
2701 	case 'H': /* MouseSystems */
2702 	    id->eisaid = "PNP0F04";
2703 	    break;
2704 	}
2705 	id->neisaid = strlen(id->eisaid);
2706 	id->class = "MOUSE";
2707 	id->nclass = strlen(id->class);
2708 	debug("non-PnP mouse '%c'", buf[0]);
2709 	return TRUE;
2710     }
2711 
2712     /* PnP mice */
2713     offset = 0x28 - buf[0];
2714 
2715     /* calculate checksum */
2716     for (i = 0; i < len - 3; ++i) {
2717 	sum += buf[i];
2718 	buf[i] += offset;
2719     }
2720     sum += buf[len - 1];
2721     for (; i < len; ++i)
2722 	buf[i] += offset;
2723     debug("PnP ID string: '%*.*s'", len, len, buf);
2724 
2725     /* revision */
2726     buf[1] -= offset;
2727     buf[2] -= offset;
2728     id->revision = ((buf[1] & 0x3f) << 6) | (buf[2] & 0x3f);
2729     debug("PnP rev %d.%02d", id->revision / 100, id->revision % 100);
2730 
2731     /* EISA vender and product ID */
2732     id->eisaid = &buf[3];
2733     id->neisaid = 7;
2734 
2735     /* option strings */
2736     i = 10;
2737     if (buf[i] == '\\') {
2738 	/* device serial # */
2739 	for (j = ++i; i < len; ++i) {
2740 	    if (buf[i] == '\\')
2741 		break;
2742 	}
2743 	if (i >= len)
2744 	    i -= 3;
2745 	if (i - j == 8) {
2746 	    id->serial = &buf[j];
2747 	    id->nserial = 8;
2748 	}
2749     }
2750     if (buf[i] == '\\') {
2751 	/* PnP class */
2752 	for (j = ++i; i < len; ++i) {
2753 	    if (buf[i] == '\\')
2754 		break;
2755 	}
2756 	if (i >= len)
2757 	    i -= 3;
2758 	if (i > j + 1) {
2759 	    id->class = &buf[j];
2760 	    id->nclass = i - j;
2761 	}
2762     }
2763     if (buf[i] == '\\') {
2764 	/* compatible driver */
2765 	for (j = ++i; i < len; ++i) {
2766 	    if (buf[i] == '\\')
2767 		break;
2768 	}
2769 	/*
2770 	 * PnP COM spec prior to v0.96 allowed '*' in this field,
2771 	 * it's not allowed now; just igore it.
2772 	 */
2773 	if (buf[j] == '*')
2774 	    ++j;
2775 	if (i >= len)
2776 	    i -= 3;
2777 	if (i > j + 1) {
2778 	    id->compat = &buf[j];
2779 	    id->ncompat = i - j;
2780 	}
2781     }
2782     if (buf[i] == '\\') {
2783 	/* product description */
2784 	for (j = ++i; i < len; ++i) {
2785 	    if (buf[i] == ';')
2786 		break;
2787 	}
2788 	if (i >= len)
2789 	    i -= 3;
2790 	if (i > j + 1) {
2791 	    id->description = &buf[j];
2792 	    id->ndescription = i - j;
2793 	}
2794     }
2795 
2796     /* checksum exists if there are any optional fields */
2797     if ((id->nserial > 0) || (id->nclass > 0)
2798 	|| (id->ncompat > 0) || (id->ndescription > 0)) {
2799 	debug("PnP checksum: 0x%X", sum);
2800 	sprintf(s, "%02X", sum & 0x0ff);
2801 	if (strncmp(s, &buf[len - 3], 2) != 0) {
2802 #if 0
2803 	    /*
2804 	     * I found some mice do not comply with the PnP COM device
2805 	     * spec regarding checksum... XXX
2806 	     */
2807 	    logwarnx("PnP checksum error", 0);
2808 	    return FALSE;
2809 #endif
2810 	}
2811     }
2812 
2813     return TRUE;
2814 }
2815 
2816 static symtab_t *
2817 pnpproto(pnpid_t *id)
2818 {
2819     symtab_t *t;
2820     int i, j;
2821 
2822     if (id->nclass > 0)
2823 	if (strncmp(id->class, "MOUSE", id->nclass) != 0 &&
2824 	    strncmp(id->class, "TABLET", id->nclass) != 0)
2825 	    /* this is not a mouse! */
2826 	    return NULL;
2827 
2828     if (id->neisaid > 0) {
2829 	t = gettoken(pnpprod, id->eisaid, id->neisaid);
2830 	if (t->val != MOUSE_PROTO_UNKNOWN)
2831 	    return t;
2832     }
2833 
2834     /*
2835      * The 'Compatible drivers' field may contain more than one
2836      * ID separated by ','.
2837      */
2838     if (id->ncompat <= 0)
2839 	return NULL;
2840     for (i = 0; i < id->ncompat; ++i) {
2841 	for (j = i; id->compat[i] != ','; ++i)
2842 	    if (i >= id->ncompat)
2843 		break;
2844 	if (i > j) {
2845 	    t = gettoken(pnpprod, id->compat + j, i - j);
2846 	    if (t->val != MOUSE_PROTO_UNKNOWN)
2847 		return t;
2848 	}
2849     }
2850 
2851     return NULL;
2852 }
2853 
2854 /* name/val mapping */
2855 
2856 static symtab_t *
2857 gettoken(symtab_t *tab, char *s, int len)
2858 {
2859     int i;
2860 
2861     for (i = 0; tab[i].name != NULL; ++i) {
2862 	if (strncmp(tab[i].name, s, len) == 0)
2863 	    break;
2864     }
2865     return &tab[i];
2866 }
2867 
2868 static char *
2869 gettokenname(symtab_t *tab, int val)
2870 {
2871     int i;
2872 
2873     for (i = 0; tab[i].name != NULL; ++i) {
2874 	if (tab[i].val == val)
2875 	    return tab[i].name;
2876     }
2877     return NULL;
2878 }
2879 
2880 
2881 /*
2882  * code to read from the Genius Kidspad tablet.
2883 
2884 The tablet responds to the COM PnP protocol 1.0 with EISA-ID KYE0005,
2885 and to pre-pnp probes (RTS toggle) with 'T' (tablet ?)
2886 9600, 8 bit, parity odd.
2887 
2888 The tablet puts out 5 bytes. b0 (mask 0xb8, value 0xb8) contains
2889 the proximity, tip and button info:
2890    (byte0 & 0x1)	true = tip pressed
2891    (byte0 & 0x2)	true = button pressed
2892    (byte0 & 0x40)	false = pen in proximity of tablet.
2893 
2894 The next 4 bytes are used for coordinates xl, xh, yl, yh (7 bits valid).
2895 
2896 Only absolute coordinates are returned, so we use the following approach:
2897 we store the last coordinates sent when the pen went out of the tablet,
2898 
2899 
2900  *
2901  */
2902 
2903 typedef enum {
2904     S_IDLE, S_PROXY, S_FIRST, S_DOWN, S_UP
2905 } k_status ;
2906 
2907 static int
2908 kidspad(u_char rxc, mousestatus_t *act)
2909 {
2910     static int buf[5];
2911     static int buflen = 0, b_prev = 0 , x_prev = -1, y_prev = -1 ;
2912     static k_status status = S_IDLE ;
2913     static struct timeval old, now ;
2914 
2915     int x, y ;
2916 
2917     if (buflen > 0 && (rxc & 0x80)) {
2918 	fprintf(stderr, "invalid code %d 0x%x\n", buflen, rxc);
2919 	buflen = 0 ;
2920     }
2921     if (buflen == 0 && (rxc & 0xb8) != 0xb8) {
2922 	fprintf(stderr, "invalid code 0 0x%x\n", rxc);
2923 	return 0 ; /* invalid code, no action */
2924     }
2925     buf[buflen++] = rxc ;
2926     if (buflen < 5)
2927 	return 0 ;
2928 
2929     buflen = 0 ; /* for next time... */
2930 
2931     x = buf[1]+128*(buf[2] - 7) ;
2932     if (x < 0) x = 0 ;
2933     y = 28*128 - (buf[3] + 128* (buf[4] - 7)) ;
2934     if (y < 0) y = 0 ;
2935 
2936     x /= 8 ;
2937     y /= 8 ;
2938 
2939     act->flags = 0 ;
2940     act->obutton = act->button ;
2941     act->dx = act->dy = act->dz = 0 ;
2942     gettimeofday(&now, NULL);
2943     if (buf[0] & 0x40) /* pen went out of reach */
2944 	status = S_IDLE ;
2945     else if (status == S_IDLE) { /* pen is newly near the tablet */
2946 	act->flags |= MOUSE_POSCHANGED ; /* force update */
2947 	status = S_PROXY ;
2948 	x_prev = x ;
2949 	y_prev = y ;
2950     }
2951     old = now ;
2952     act->dx = x - x_prev ;
2953     act->dy = y - y_prev ;
2954     if (act->dx || act->dy)
2955 	act->flags |= MOUSE_POSCHANGED ;
2956     x_prev = x ;
2957     y_prev = y ;
2958     if (b_prev != 0 && b_prev != buf[0]) { /* possibly record button change */
2959 	act->button = 0 ;
2960 	if (buf[0] & 0x01) /* tip pressed */
2961 	    act->button |= MOUSE_BUTTON1DOWN ;
2962 	if (buf[0] & 0x02) /* button pressed */
2963 	    act->button |= MOUSE_BUTTON2DOWN ;
2964 	act->flags |= MOUSE_BUTTONSCHANGED ;
2965     }
2966     b_prev = buf[0] ;
2967     return act->flags ;
2968 }
2969 
2970 static void
2971 mremote_serversetup()
2972 {
2973     struct sockaddr_un ad;
2974 
2975     /* Open a UNIX domain stream socket to listen for mouse remote clients */
2976     unlink(_PATH_MOUSEREMOTE);
2977 
2978     if ((rodent.mremsfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
2979 	logerrx(1, "unable to create unix domain socket %s",_PATH_MOUSEREMOTE);
2980 
2981     umask(0111);
2982 
2983     bzero(&ad, sizeof(ad));
2984     ad.sun_family = AF_UNIX;
2985     strcpy(ad.sun_path, _PATH_MOUSEREMOTE);
2986 #ifndef SUN_LEN
2987 #define SUN_LEN(unp) (((char *)(unp)->sun_path - (char *)(unp)) + \
2988 		       strlen((unp)->path))
2989 #endif
2990     if (bind(rodent.mremsfd, (struct sockaddr *) &ad, SUN_LEN(&ad)) < 0)
2991 	logerrx(1, "unable to bind unix domain socket %s", _PATH_MOUSEREMOTE);
2992 
2993     listen(rodent.mremsfd, 1);
2994 }
2995 
2996 static void
2997 mremote_clientchg(int add)
2998 {
2999     struct sockaddr_un ad;
3000     int ad_len, fd;
3001 
3002     if (rodent.rtype != MOUSE_PROTO_X10MOUSEREM)
3003 	return;
3004 
3005     if (add) {
3006 	/*  Accept client connection, if we don't already have one  */
3007 	ad_len = sizeof(ad);
3008 	fd = accept(rodent.mremsfd, (struct sockaddr *) &ad, &ad_len);
3009 	if (fd < 0)
3010 	    logwarnx("failed accept on mouse remote socket");
3011 
3012 	if (rodent.mremcfd < 0) {
3013 	    rodent.mremcfd = fd;
3014 	    debug("remote client connect...accepted");
3015 	}
3016 	else {
3017 	    close(fd);
3018 	    debug("another remote client connect...disconnected");
3019 	}
3020     }
3021     else {
3022 	/* Client disconnected */
3023 	debug("remote client disconnected");
3024 	close(rodent.mremcfd);
3025 	rodent.mremcfd = -1;
3026     }
3027 }
3028