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