xref: /openbsd-src/usr.sbin/wsmoused/mouse_protocols.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /* $OpenBSD: mouse_protocols.c,v 1.3 2001/08/13 06:32:18 pvalchev Exp $ */
2 
3 /*
4  * Copyright (c) 2001 Jean-Baptiste Marchand, Julien Montagne and Jerome Verdon
5  *
6  * Copyright (c) 1998 by Kazutaka Yokota
7  *
8  * Copyright (c) 1995 Michael Smith
9  *
10  * Copyright (c) 1993 by David Dawes <dawes@xfree86.org>
11  *
12  * Copyright (c) 1990,91 by Thomas Roell, Dinkelscherben, Germany.
13  *
14  * All rights reserved.
15  *
16  * Most of this code was taken from the FreeBSD moused daemon, written by
17  * Michael Smith. The FreeBSD moused daemon already contained code from the
18  * Xfree Project, written by David Dawes and Thomas Roell and Kazutaka Yokota.
19  *
20  * Adaptation to OpenBSD was done by Jean-Baptiste Marchand, Julien Montagne
21  * and Jerome Verdon.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the above copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *	This product includes software developed by
34  *      David Dawes, Jean-Baptiste Marchand, Julien Montagne, Thomas Roell,
35  *      Michael Smith, Jerome Verdon and Kazutaka Yokota.
36  * 4. The name authors may not be used to endorse or promote products
37  *    derived from this software without specific prior written permission.
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
40  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
41  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
42  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
43  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
45  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
46  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
47  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
48  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49  *
50  *
51  */
52 
53 /* Support for non-wsmouse (i.e. serial mice) mice */
54 
55 /*
56  * Most of this code comes from the Xfree Project and are derived from two files
57  * of Xfree86 3.3.6 with the following CVS tags :
58  $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.21.2.24
59  1999/12/11 19:00:42 hohndel Exp $
60  and
61  $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_PnPMouse.c,v 1.1.2.6
62  1999/07/29 09:22:51 hohndel Exp $
63  */
64 
65 #include <sys/ioctl.h>
66 #include <sys/types.h>
67 #include <sys/time.h>
68 #include <sys/tty.h>
69 
70 #include <ctype.h>
71 #include <err.h>
72 #include <errno.h>
73 #include <fcntl.h>
74 #include <unistd.h>
75 #include <setjmp.h>
76 #include <signal.h>
77 #include <poll.h>
78 #include <stdio.h>
79 #include <string.h>
80 #include <stdlib.h>
81 #include <syslog.h>
82 #include <varargs.h>
83 
84 #include "wsmoused.h"
85 #include "mouse_protocols.h"
86 
87 extern int debug;
88 extern int nodaemon;
89 extern int background;
90 extern mouse_t mouse;
91 
92 /*  Cflags of each mouse protocol, ordered by P_XXX */
93 static unsigned short mousecflags[] =
94 {
95     (CS7	           | CREAD | CLOCAL | HUPCL ),	/* MicroSoft */
96     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL ),	/* MouseSystems */
97     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL ),	/* Logitech */
98     (CS8 | PARENB | PARODD | CREAD | CLOCAL | HUPCL ),	/* MMSeries */
99     (CS7		   | CREAD | CLOCAL | HUPCL ),	/* MouseMan */
100     (CS8		   | CREAD | CLOCAL | HUPCL ),	/* MM HitTablet */
101     (CS7	           | CREAD | CLOCAL | HUPCL ),	/* GlidePoint */
102     (CS7                   | CREAD | CLOCAL | HUPCL ),	/* IntelliMouse */
103     (CS7                   | CREAD | CLOCAL | HUPCL ),	/* Thinking Mouse */
104 };
105 
106 /* array ordered by P_XXX giving protocol properties */
107 static unsigned char proto[][7] = {
108     /*  hd_mask hd_id   dp_mask dp_id   bytes b4_mask b4_id */
109     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* MicroSoft */
110     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* MouseSystems */
111     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* Logitech */
112     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MMSeries */
113     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* MouseMan */
114     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MM HitTablet */
115     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* GlidePoint */
116     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x3f,  0x00 }, /* IntelliMouse */
117     { 	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* ThinkingMouse */
118 };
119 
120 /* array ordered by P_XXX (mouse protocols) giving the protocol corresponding
121    to the name of a mouse */
122 char *mouse_names[] = {
123     "microsoft",
124     "mousesystems",
125     "logitech",
126     "mmseries",
127     "mouseman",
128     "mmhitab",
129     "glidepoint",
130     "intellimouse",
131     "thinkingmouse",
132     NULL
133 };
134 
135 /* protocol currently used */
136 static unsigned char cur_proto[7];
137 
138 /* PnP EISA/product IDs */
139 static symtab_t pnpprod[] = {
140     { "KML0001", P_THINKING},	/* Kensignton ThinkingMouse */
141     { "MSH0001", P_IMSERIAL},	/* MS IntelliMouse */
142     { "MSH0004", P_IMSERIAL},	/* MS IntelliMouse TrackBall */
143     { "KYEEZ00", P_MS}, 	/* Genius EZScroll */
144     { "KYE0001", P_MS}, 	/* Genius PnP Mouse */
145     { "KYE0003", P_IMSERIAL},	/* Genius NetMouse */
146     { "LGI800C", P_IMSERIAL}, 	/* Logitech MouseMan (4 button model) */
147     { "LGI8050", P_IMSERIAL}, 	/* Logitech MouseMan+ */
148     { "LGI8051", P_IMSERIAL}, 	/* Logitech FirstMouse+ */
149     { "LGI8001", P_LOGIMAN},	/* Logitech serial */
150     { "PNP0F01", P_MS},		/* MS serial */
151     /*
152      * XXX EzScroll returns PNP0F04 in the compatible device field; but it
153      * doesn't look compatible...
154      */
155     { "PNP0F04", P_MSC},	/* MouseSystems */
156     { "PNP0F05", P_MSC},	/* MouseSystems */
157     { "PNP0F08", P_LOGIMAN},	/* Logitech serial */
158     { "PNP0F09", P_MS},		/* MS BallPoint serial */
159     { "PNP0F0A", P_MS},		/* MS PnP serial */
160     { "PNP0F0B", P_MS},		/* MS PnP BallPoint serial */
161     { "PNP0F0C", P_MS},		/* MS serial comatible */
162     { "PNP0F0F", P_MS},		/* MS BallPoint comatible */
163     { "PNP0F17", P_LOGIMAN},	/* Logitech serial compat */
164     { NULL, -1 },
165 };
166 
167 static symtab_t *
168 gettoken(symtab_t *tab, char *s, int len)
169 {
170     int i;
171 
172     for (i = 0; tab[i].name != NULL; ++i) {
173 	if (strncmp(tab[i].name, s, len) == 0)
174 		break;
175     }
176     return &tab[i];
177 }
178 
179 char *
180 mouse_name(int type)
181 {
182     return ((type == P_UNKNOWN)
183 	|| (type > sizeof(mouse_names)/sizeof(mouse_names[0]) - 1))
184 	? "unknown" : mouse_names[type];
185 }
186 
187 void SetMouseSpeed(int old, int new, unsigned int cflag)
188 {
189 	struct termios tty;
190 	char *c;
191 
192 	if (!IS_SERIAL_DEV(mouse.portname))
193 		return;
194 
195 	if (tcgetattr(mouse.mfd, &tty) < 0)
196 	{
197 		debug("Warning: %s unable to get status of mouse fd (%s)\n",
198 		       mouse.portname, strerror(errno));
199 		return;
200 	}
201 
202 	/* this will query the initial baudrate only once */
203 	if (mouse.old_baudrate < 0) {
204 	   switch (cfgetispeed(&tty))
205 	      {
206 	      case B9600:
207 		 mouse.old_baudrate = 9600;
208 		 break;
209 	      case B4800:
210 		 mouse.old_baudrate = 4800;
211 		 break;
212 	      case B2400:
213 		 mouse.old_baudrate = 2400;
214 		 break;
215 	      case B1200:
216 	      default:
217 		 mouse.old_baudrate = 1200;
218 		 break;
219 	      }
220 	}
221 
222 	tty.c_iflag = IGNBRK | IGNPAR;
223 	tty.c_oflag = 0;
224 	tty.c_lflag = 0;
225 	tty.c_cflag = (tcflag_t)cflag;
226 	tty.c_cc[VTIME] = 0;
227 	tty.c_cc[VMIN] = 1;
228 
229 	switch (old)
230 	{
231 	case 9600:
232 		cfsetispeed(&tty, B9600);
233 		cfsetospeed(&tty, B9600);
234 		break;
235 	case 4800:
236 		cfsetispeed(&tty, B4800);
237 		cfsetospeed(&tty, B4800);
238 		break;
239 	case 2400:
240 		cfsetispeed(&tty, B2400);
241 		cfsetospeed(&tty, B2400);
242 		break;
243 	case 1200:
244 	default:
245 		cfsetispeed(&tty, B1200);
246 		cfsetospeed(&tty, B1200);
247 	}
248 
249 	if (tcsetattr(mouse.mfd, TCSADRAIN, &tty) < 0) {
250 		printf("Unable to get mouse status. Exiting...\n");
251 		exit(1);
252 	}
253 
254 	switch (new)
255 	{
256 	case 9600:
257 		c = "*q";
258 		cfsetispeed(&tty, B9600);
259 		cfsetospeed(&tty, B9600);
260 		break;
261 	case 4800:
262 		c = "*p";
263 		cfsetispeed(&tty, B4800);
264 		cfsetospeed(&tty, B4800);
265 		break;
266 	case 2400:
267 		c = "*o";
268 		cfsetispeed(&tty, B2400);
269 		cfsetospeed(&tty, B2400);
270 		break;
271 	case 1200:
272 	default:
273 		c = "*n";
274 		cfsetispeed(&tty, B1200);
275 		cfsetospeed(&tty, B1200);
276 	}
277 
278 	if (mouse.proto == P_LOGIMAN || mouse.proto == P_LOGI)
279 	{
280 		if (write(mouse.mfd, c, 2) != 2) {
281 			printf("Unable to write to mouse. Exiting...\n");
282 			exit(1);
283 		}
284 	}
285 	usleep(100000);
286 
287 	if (tcsetattr(mouse.mfd, TCSADRAIN, &tty) < 0) {
288 		printf("Unable to get mouse status. Exiting...\n");
289 		exit(1);
290 	}
291 }
292 
293 int
294 FlushInput(int fd)
295 {
296 	struct pollfd pfd[1];
297 	char c[4];
298 
299 	if (tcflush(fd, TCIFLUSH) == 0)
300 		return 0;
301 
302 	pfd[0].fd = fd;
303 	pfd[0].events = POLLIN;
304 
305 	while (poll(pfd, 1, 0) > 0)
306 		read(fd, &c, sizeof(c));
307 	return 0;
308 }
309 
310 /*
311  * Try to elicit a PnP ID as described in
312  * Microsoft, Hayes: "Plug and Play External COM Device Specification,
313  * rev 1.00", 1995.
314  *
315  * The routine does not fully implement the COM Enumerator as par Section
316  * 2.1 of the document.  In particular, we don't have idle state in which
317  * the driver software monitors the com port for dynamic connection or
318  * removal of a device at the port, because `moused' simply quits if no
319  * device is found.
320  *
321  * In addition, as PnP COM device enumeration procedure slightly has
322  * changed since its first publication, devices which follow earlier
323  * revisions of the above spec. may fail to respond if the rev 1.0
324  * procedure is used. XXX
325  */
326 
327 static int
328 pnpgets(int mouse_fd, char *buf)
329 {
330     struct pollfd pfd[1];
331     int i;
332     char c;
333 
334     pfd[0].fd = mouse_fd;
335     pfd[0].events = POLLIN;
336 
337 #if 0
338     /*
339      * This is the procedure described in rev 1.0 of PnP COM device spec.
340      * Unfortunately, some devices which comform to earlier revisions of
341      * the spec gets confused and do not return the ID string...
342      */
343 
344     /* port initialization (2.1.2) */
345     ioctl(mouse_fd, TIOCMGET, &i);
346     i |= TIOCM_DTR;		/* DTR = 1 */
347     i &= ~TIOCM_RTS;		/* RTS = 0 */
348     ioctl(mouse_fd, TIOCMSET, &i);
349     usleep(200000);
350     if ((ioctl(mouse_fd, TIOCMGET, &i) == -1) || ((i & TIOCM_DSR) == 0))
351 	goto disconnect_idle;
352 
353     /* port setup, 1st phase (2.1.3) */
354     SetMouseSpeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
355     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
356     ioctl(mouse_fd, TIOCMBIC, &i);
357     usleep(200000);
358     i = TIOCM_DTR;		/* DTR = 1, RTS = 0 */
359     ioctl(mouse_fd, TIOCMBIS, &i);
360     usleep(200000);
361 
362     /* wait for response, 1st phase (2.1.4) */
363     FlushInput(mouse_fd);
364     i = TIOCM_RTS;		/* DTR = 1, RTS = 1 */
365     ioctl(mouse_fd, TIOCMBIS, &i);
366 
367     /* try to read something */
368     if (poll(pfd, 1, 200000/1000) <= 0) {
369 
370 	/* port setup, 2nd phase (2.1.5) */
371         i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
372         ioctl(mouse_fd, TIOCMBIC, &i);
373         usleep(200000);
374 
375 	/* wait for respose, 2nd phase (2.1.6) */
376 	FlushInput(mouse_fd);
377         i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
378         ioctl(mouse_fd, TIOCMBIS, &i);
379 
380         /* try to read something */
381         if (poll(pfd, 1, 200000/1000) <= 0)
382 	    goto connect_idle;
383     }
384 #else
385 
386     /*
387      * This is a simplified procedure; it simply toggles RTS.
388      */
389     SetMouseSpeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
390 
391     ioctl(mouse_fd, TIOCMGET, &i);
392     i |= TIOCM_DTR;		/* DTR = 1 */
393     i &= ~TIOCM_RTS;		/* RTS = 0 */
394     ioctl(mouse_fd, TIOCMSET, &i);
395     usleep(200000);
396 
397     /* wait for response */
398     FlushInput(mouse_fd);
399     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
400     ioctl(mouse_fd, TIOCMBIS, &i);
401 
402     /* try to read something */
403     if (poll(pfd, 1, 200000/1000) <= 0)
404         goto connect_idle;
405 #endif
406 
407     /* collect PnP COM device ID (2.1.7) */
408     i = 0;
409     usleep(200000);	/* the mouse must send `Begin ID' within 200msec */
410     while (read(mouse_fd, &c, 1) == 1) {
411 	/* we may see "M", or "M3..." before `Begin ID' */
412         if ((c == 0x08) || (c == 0x28)) {	/* Begin ID */
413 	    buf[i++] = c;
414 	    break;
415         }
416     }
417     if (i <= 0) {
418 	/* we haven't seen `Begin ID' in time... */
419 	goto connect_idle;
420     }
421 
422     ++c;			/* make it `End ID' */
423     for (;;) {
424         if (poll(pfd, 1, 200000/1000) <= 0)
425 	    break;
426 
427 	read(mouse_fd, &buf[i], 1);
428         if (buf[i++] == c)	/* End ID */
429 	    break;
430 	if (i >= 256)
431 	    break;
432     }
433     if (buf[i - 1] != c)
434 	goto connect_idle;
435     return i;
436 
437 #if 0
438     /*
439      * According to PnP spec, we should set DTR = 1 and RTS = 0 while
440      * in idle state.  But, `moused' shall set DTR = RTS = 1 and proceed,
441      * assuming there is something at the port even if it didn't
442      * respond to the PnP enumeration procedure.
443      */
444 disconnect_idle:
445     i = TIOCM_DTR | TIOCM_RTS;		/* DTR = 1, RTS = 1 */
446     ioctl(mouse_fd, TIOCMBIS, &i);
447 #endif
448 
449 connect_idle:
450     return 0;
451 }
452 
453 /* pnpparse : parse a PnP string ID */
454 static int
455 pnpparse(pnpid_t *id, char *buf, int len)
456 {
457     char s[3];
458     int offset;
459     int sum = 0;
460     int i, j;
461 
462     id->revision = 0;
463     id->eisaid = NULL;
464     id->serial = NULL;
465     id->class = NULL;
466     id->compat = NULL;
467     id->description = NULL;
468     id->neisaid = 0;
469     id->nserial = 0;
470     id->nclass = 0;
471     id->ncompat = 0;
472     id->ndescription = 0;
473 
474     offset = 0x28 - buf[0];
475 
476     /* calculate checksum */
477     for (i = 0; i < len - 3; ++i) {
478 	sum += buf[i];
479 	buf[i] += offset;
480     }
481     sum += buf[len - 1];
482     for (; i < len; ++i)
483 	buf[i] += offset;
484     debug("Mouse: PnP ID string: '%*.*s'\n", len, len, buf);
485 
486     /* revision */
487     buf[1] -= offset;
488     buf[2] -= offset;
489     id->revision = ((buf[1] & 0x3f) << 6) | (buf[2] & 0x3f);
490     debug("Mouse: PnP rev %d.%02d\n", id->revision / 100, id->revision % 100);
491 
492     /* EISA vender and product ID */
493     id->eisaid = &buf[3];
494     id->neisaid = 7;
495 
496     /* option strings */
497     i = 10;
498     if (buf[i] == '\\') {
499         /* device serial # */
500         for (j = ++i; i < len; ++i) {
501             if (buf[i] == '\\')
502 		break;
503         }
504 	if (i >= len)
505 	    i -= 3;
506 	if (i - j == 8) {
507             id->serial = &buf[j];
508             id->nserial = 8;
509 	}
510     }
511     if (buf[i] == '\\') {
512         /* PnP class */
513         for (j = ++i; i < len; ++i) {
514             if (buf[i] == '\\')
515 		break;
516         }
517 	if (i >= len)
518 	    i -= 3;
519 	if (i > j + 1) {
520             id->class = &buf[j];
521             id->nclass = i - j;
522         }
523     }
524     if (buf[i] == '\\') {
525 	/* compatible driver */
526         for (j = ++i; i < len; ++i) {
527             if (buf[i] == '\\')
528 		break;
529         }
530 	/*
531 	 * PnP COM spec prior to v0.96 allowed '*' in this field,
532 	 * it's not allowed now; just ignore it.
533 	 */
534 	if (buf[j] == '*')
535 	    ++j;
536 	if (i >= len)
537 	    i -= 3;
538 	if (i > j + 1) {
539             id->compat = &buf[j];
540             id->ncompat = i - j;
541         }
542     }
543     if (buf[i] == '\\') {
544 	/* product description */
545         for (j = ++i; i < len; ++i) {
546             if (buf[i] == ';')
547 		break;
548         }
549 	if (i >= len)
550 	    i -= 3;
551 	if (i > j + 1) {
552             id->description = &buf[j];
553             id->ndescription = i - j;
554         }
555     }
556 
557     /* checksum exists if there are any optional fields */
558     if ((id->nserial > 0) || (id->nclass > 0)
559 	|| (id->ncompat > 0) || (id->ndescription > 0)) {
560 #if 0
561         debug("Mouse: PnP checksum: 0x%02X\n", sum);
562 #endif
563         sprintf(s, "%02X", sum & 0x0ff);
564         if (strncmp(s, &buf[len - 3], 2) != 0) {
565 #if 0
566             /*
567 	     * Checksum error!!
568 	     * I found some mice do not comply with the PnP COM device
569 	     * spec regarding checksum... XXX
570 	     */
571 	    return FALSE;
572 #endif
573         }
574     }
575 
576     return 1;
577 }
578 
579 /* pnpproto : return the prototype used, based on the PnP ID string */
580 static symtab_t *
581 pnpproto(pnpid_t *id)
582 {
583     symtab_t *t;
584     int i, j;
585 
586     if (id->nclass > 0)
587 	if (strncmp(id->class, "MOUSE", id->nclass) != 0)
588 	    /* this is not a mouse! */
589 	    return NULL;
590 
591     if (id->neisaid > 0) {
592         t = gettoken(pnpprod, id->eisaid, id->neisaid);
593 	if (t->val != -1)
594             return t;
595     }
596     /*
597      * The 'Compatible drivers' field may contain more than one
598      * ID separated by ','.
599      */
600     if (id->ncompat <= 0)
601 	return NULL;
602     for (i = 0; i < id->ncompat; ++i) {
603         for (j = i; id->compat[i] != ','; ++i)
604             if (i >= id->ncompat)
605 		break;
606         if (i > j) {
607             t = gettoken(pnpprod, id->compat + j, i - j);
608 	    if (t->val != -1)
609                 return t;
610 	}
611     }
612 
613     return NULL;
614 }
615 
616 /* mouse_init : init the mouse by writing appropriate sequences */
617 void
618 mouse_init(void)
619 {
620     struct pollfd pfd[1];
621     char *s;
622     char c;
623     int i;
624 
625     if (IS_WSMOUSE_DEV(mouse.portname)) {
626 	    wsmouse_init();
627 	    return ;
628     }
629 
630     pfd[0].fd = mouse.mfd;
631     pfd[0].events = POLLIN;
632 
633     /**
634      ** This comment is a little out of context here, but it contains
635      ** some useful information...
636      ********************************************************************
637      **
638      ** The following lines take care of the Logitech MouseMan protocols.
639      **
640      ** NOTE: There are diffrent versions of both MouseMan and TrackMan!
641      **       Hence I add another protocol P_LOGIMAN, which the user can
642      **       specify as MouseMan in his XF86Config file. This entry was
643      **       formerly handled as a special case of P_MS. However, people
644      **       who don't have the middle button problem, can still specify
645      **       Microsoft and use P_MS.
646      **
647      ** By default, these mice should use a 3 byte Microsoft protocol
648      ** plus a 4th byte for the middle button. However, the mouse might
649      ** have switched to a different protocol before we use it, so I send
650      ** the proper sequence just in case.
651      **
652      ** NOTE: - all commands to (at least the European) MouseMan have to
653      **         be sent at 1200 Baud.
654      **       - each command starts with a '*'.
655      **       - whenever the MouseMan receives a '*', it will switch back
656      **	 to 1200 Baud. Hence I have to select the desired protocol
657      **	 first, then select the baud rate.
658      **
659      ** The protocols supported by the (European) MouseMan are:
660      **   -  5 byte packed binary protocol, as with the Mouse Systems
661      **      mouse. Selected by sequence "*U".
662      **   -  2 button 3 byte MicroSoft compatible protocol. Selected
663      **      by sequence "*V".
664      **   -  3 button 3+1 byte MicroSoft compatible protocol (default).
665      **      Selected by sequence "*X".
666      **
667      ** The following baud rates are supported:
668      **   -  1200 Baud (default). Selected by sequence "*n".
669      **   -  9600 Baud. Selected by sequence "*q".
670      **
671      ** Selecting a sample rate is no longer supported with the MouseMan!
672      ** Some additional lines in xf86Config.c take care of ill configured
673      ** baud rates and sample rates. (The user will get an error.)
674      */
675 
676     switch (mouse.proto) {
677 
678     case P_LOGI:
679 	/*
680 	 * The baud rate selection command must be sent at the current
681 	 * baud rate; try all likely settings
682 	 */
683 	SetMouseSpeed(9600, mouse.baudrate, mousecflags[mouse.proto]);
684 	SetMouseSpeed(4800, mouse.baudrate, mousecflags[mouse.proto]);
685 	SetMouseSpeed(2400, mouse.baudrate, mousecflags[mouse.proto]);
686 	// SetMouseSpeed(1200, mouse.baudrate, mousecflags[mouse.proto]);
687 	/* select MM series data format */
688 	write(mouse.mfd, "S", 1);
689 	SetMouseSpeed(mouse.baudrate, mouse.baudrate,
690 		      mousecflags[P_MM]);
691 	/* select report rate/frequency */
692 	if      (mouse.rate <= 0)   write(mouse.mfd, "O", 1);
693 	else if (mouse.rate <= 15)  write(mouse.mfd, "J", 1);
694 	else if (mouse.rate <= 27)  write(mouse.mfd, "K", 1);
695 	else if (mouse.rate <= 42)  write(mouse.mfd, "L", 1);
696 	else if (mouse.rate <= 60)  write(mouse.mfd, "R", 1);
697 	else if (mouse.rate <= 85)  write(mouse.mfd, "M", 1);
698 	else if (mouse.rate <= 125) write(mouse.mfd, "Q", 1);
699 	else			     write(mouse.mfd, "N", 1);
700 	break;
701 
702     case P_LOGIMAN:
703 	/* The command must always be sent at 1200 baud */
704 	SetMouseSpeed(1200, 1200, mousecflags[mouse.proto]);
705 	write(mouse.mfd, "*X", 2);
706 	SetMouseSpeed(1200, mouse.baudrate, mousecflags[mouse.proto]);
707 	break;
708 
709     case P_MMHIT:
710 	SetMouseSpeed(1200, mouse.baudrate, mousecflags[mouse.proto]);
711 
712 	/*
713 	 * Initialize Hitachi PUMA Plus - Model 1212E to desired settings.
714 	 * The tablet must be configured to be in MM mode, NO parity,
715 	 * Binary Format.  xf86Info.sampleRate controls the sensativity
716 	 * of the tablet.  We only use this tablet for it's 4-button puck
717 	 * so we don't run in "Absolute Mode"
718 	 */
719 	write(mouse.mfd, "z8", 2);	/* Set Parity = "NONE" */
720 	usleep(50000);
721 	write(mouse.mfd, "zb", 2);	/* Set Format = "Binary" */
722 	usleep(50000);
723 	write(mouse.mfd, "@", 1);	/* Set Report Mode = "Stream" */
724 	usleep(50000);
725 	write(mouse.mfd, "R", 1);	/* Set Output Rate = "45 rps" */
726 	usleep(50000);
727 	write(mouse.mfd, "I\x20", 2);	/* Set Incrememtal Mode "20" */
728 	usleep(50000);
729 	write(mouse.mfd, "E", 1);	/* Set Data Type = "Relative */
730 	usleep(50000);
731 
732 	/* Resolution is in 'lines per inch' on the Hitachi tablet */
733 	if      (mouse.resolution == MOUSE_RES_LOW) 		c = 'g';
734 	else if (mouse.resolution == MOUSE_RES_MEDIUMLOW)	c = 'e';
735 	else if (mouse.resolution == MOUSE_RES_MEDIUMHIGH)	c = 'h';
736 	else if (mouse.resolution == MOUSE_RES_HIGH)		c = 'd';
737 	else if (mouse.resolution <=   40) 			c = 'g';
738 	else if (mouse.resolution <=  100) 			c = 'd';
739 	else if (mouse.resolution <=  200) 			c = 'e';
740 	else if (mouse.resolution <=  500) 			c = 'h';
741 	else if (mouse.resolution <= 1000) 			c = 'j';
742 	else                                			c = 'd';
743 	write(mouse.mfd, &c, 1);
744 	usleep(50000);
745 
746 	write(mouse.mfd, "\021", 1);	/* Resume DATA output */
747 	break;
748 
749     case P_THINKING:
750 	SetMouseSpeed(1200, mouse.baudrate, mousecflags[mouse.proto]);
751 	/* the PnP ID string may be sent again, discard it */
752 	usleep(200000);
753 	i = FREAD;
754 	ioctl(mouse.mfd, TIOCFLUSH, &i);
755 	/* send the command to initialize the beast */
756 	for (s = "E5E5"; *s; ++s) {
757 	    write(mouse.mfd, s, 1);
758 
759 	    if (poll(pfd, 1, INFTIM) <= 0)
760 		break;
761 	    read(mouse.mfd, &c, 1);
762 	    debug("%c", c);
763 	    if (c != *s)
764 	        break;
765 	}
766 	break;
767 
768     case P_MSC:
769 	SetMouseSpeed(1200, mouse.baudrate, mousecflags[mouse.proto]);
770 #if 0
771 	if (mouse.flags & ClearDTR) {
772 	   i = TIOCM_DTR;
773 	   ioctl(mouse.mfd, TIOCMBIC, &i);
774         }
775         if (mouse.flags & ClearRTS) {
776 	   i = TIOCM_RTS;
777 	   ioctl(mouse.mfd, TIOCMBIC, &i);
778         }
779 #endif
780 	break;
781 
782     default:
783 	SetMouseSpeed(1200, mouse.baudrate, mousecflags[mouse.proto]);
784 	break;
785     }
786 }
787 
788 /* mouse_identify : identify the protocol used by the mouse */
789 int
790 mouse_identify(void)
791 {
792 	char pnpbuf[256];/* PnP identifier string may be up to 256 bytes long */
793 	pnpid_t pnpid;
794     	symtab_t *t;
795 	int len;
796 
797 	/* protocol has been specified with '-t' */
798 	if (mouse.proto != P_UNKNOWN)
799 		bcopy(proto[mouse.proto], cur_proto, sizeof(cur_proto));
800 	else {
801 		/* maybe this is an PnP mouse... */
802 		if (mouse.flags & NoPnP)
803 			return mouse.proto;
804 		if (((len = pnpgets(mouse.mfd, pnpbuf)) <= 0)
805 				|| !pnpparse(&pnpid, pnpbuf, len))
806 			return mouse.proto;
807 
808 		debug("PnP serial mouse: '%*.*s' '%*.*s' '%*.*s'",
809 				pnpid.neisaid, pnpid.neisaid,
810 				pnpid.eisaid, pnpid.ncompat,
811 				pnpid.ncompat, pnpid.compat,
812 				pnpid.ndescription, pnpid.ndescription,
813 				pnpid.description);
814 
815 		/* we have a valid PnP serial device ID */
816 		t = pnpproto(&pnpid);
817 		if (t != NULL) {
818 			mouse.proto = t->val;
819 			bcopy(proto[mouse.proto], cur_proto, sizeof(cur_proto));
820 		}
821 		else
822 			mouse.proto = P_UNKNOWN;
823 
824 	}
825 
826 	debug("proto params: %02x %02x %02x %02x %d %02x %02x",
827 			cur_proto[0], cur_proto[1], cur_proto[2], cur_proto[3],
828 			cur_proto[4], cur_proto[5], cur_proto[6]);
829 
830 	return mouse.proto;
831 }
832 
833 /* mouse_protocol : decode bytes with the current mouse protocol */
834 int
835 mouse_protocol(u_char rBuf, mousestatus_t *act)
836 {
837 	/* MOUSE_MSS_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
838     static int butmapmss[4] = {	/* Microsoft, MouseMan, GlidePoint,
839 				   IntelliMouse, Thinking Mouse */
840 	0,
841 	MOUSE_BUTTON3DOWN,
842 	MOUSE_BUTTON1DOWN,
843 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
844     };
845     static int butmapmss2[4] = { /* Microsoft, MouseMan, GlidePoint,
846 				    Thinking Mouse */
847 	0,
848 	MOUSE_BUTTON4DOWN,
849 	MOUSE_BUTTON2DOWN,
850 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
851     };
852     /* MOUSE_INTELLI_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
853     static int butmapintelli[4] = { /* IntelliMouse, NetMouse, Mie Mouse,
854 				       MouseMan+ */
855 	0,
856 	MOUSE_BUTTON2DOWN,
857 	MOUSE_BUTTON4DOWN,
858 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
859     };
860     /* MOUSE_MSC_BUTTON?UP -> MOUSE_BUTTON?DOWN */
861     static int butmapmsc[8] = {	/* MouseSystems, MMSeries, Logitech,
862 				   Bus, sysmouse */
863 	0,
864 	MOUSE_BUTTON3DOWN,
865 	MOUSE_BUTTON2DOWN,
866 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
867 	MOUSE_BUTTON1DOWN,
868 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
869 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
870 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
871     };
872     /* for Hitachi tablet */
873     static int butmaphit[8] = {	/* MM HitTablet */
874 	0,
875 	MOUSE_BUTTON3DOWN,
876 	MOUSE_BUTTON2DOWN,
877 	MOUSE_BUTTON1DOWN,
878 	MOUSE_BUTTON4DOWN,
879 	MOUSE_BUTTON5DOWN,
880 	MOUSE_BUTTON6DOWN,
881 	MOUSE_BUTTON7DOWN,
882     };
883     /* for PS/2 VersaPad */
884     static int butmapversaps2[8] = { /* VersaPad */
885 	0,
886 	MOUSE_BUTTON3DOWN,
887 	0,
888 	MOUSE_BUTTON3DOWN,
889 	MOUSE_BUTTON1DOWN,
890 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
891 	MOUSE_BUTTON1DOWN,
892 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
893     };
894     static int           pBufP = 0;
895     static unsigned char pBuf[8];
896 
897     debug("received char 0x%x",(int)rBuf);
898 
899     /*
900      * Hack for resyncing: We check here for a package that is:
901      *  a) illegal (detected by wrong data-package header)
902      *  b) invalid (0x80 == -128 and that might be wrong for MouseSystems)
903      *  c) bad header-package
904      *
905      * NOTE: b) is a voilation of the MouseSystems-Protocol, since values of
906      *       -128 are allowed, but since they are very seldom we can easily
907      *       use them as package-header with no button pressed.
908      * NOTE/2: On a PS/2 mouse any byte is valid as a data byte. Furthermore,
909      *         0x80 is not valid as a header byte. For a PS/2 mouse we skip
910      *         checking data bytes.
911      *         For resyncing a PS/2 mouse we require the two most significant
912      *         bits in the header byte to be 0. These are the overflow bits,
913      *         and in case of an overflow we actually lose sync. Overflows
914      *         are very rare, however, and we quickly gain sync again after
915      *         an overflow condition. This is the best we can do. (Actually,
916      *         we could use bit 0x08 in the header byte for resyncing, since
917      *         that bit is supposed to be always on, but nobody told
918      *         Microsoft...)
919      */
920 
921     if (pBufP != 0 && ((rBuf & cur_proto[2]) != cur_proto[3] || rBuf == 0x80))
922     {
923 	pBufP = 0;		/* skip package */
924     }
925 
926     if (pBufP == 0 && (rBuf & cur_proto[0]) != cur_proto[1])
927 	return 0;
928 
929     /* is there an extra data byte? */
930     if (pBufP >= cur_proto[4] && (rBuf & cur_proto[0]) != cur_proto[1])
931     {
932 	/*
933 	 * Hack for Logitech MouseMan Mouse - Middle button
934 	 *
935 	 * Unfortunately this mouse has variable length packets: the standard
936 	 * Microsoft 3 byte packet plus an optional 4th byte whenever the
937 	 * middle button status changes.
938 	 *
939 	 * We have already processed the standard packet with the movement
940 	 * and button info.  Now post an event message with the old status
941 	 * of the left and right buttons and the updated middle button.
942 	 */
943 
944 	/*
945 	 * Even worse, different MouseMen and TrackMen differ in the 4th
946 	 * byte: some will send 0x00/0x20, others 0x01/0x21, or even
947 	 * 0x02/0x22, so I have to strip off the lower bits.
948          *
949          * [JCH-96/01/21]
950          * HACK for ALPS "fourth button". (It's bit 0x10 of the "fourth byte"
951          * and it is activated by tapping the glidepad with the finger! 8^)
952          * We map it to bit bit3, and the reverse map in xf86Events just has
953          * to be extended so that it is identified as Button 4. The lower
954          * half of the reverse-map may remain unchanged.
955 	 */
956 
957         /*
958 	 * [KY-97/08/03]
959 	 * Receive the fourth byte only when preceeding three bytes have
960 	 * been detected (pBufP >= cur_proto[4]).  In the previous
961 	 * versions, the test was pBufP == 0; thus, we may have mistakingly
962 	 * received a byte even if we didn't see anything preceeding
963 	 * the byte.
964 	 */
965 
966 	if ((rBuf & cur_proto[5]) != cur_proto[6]) {
967             pBufP = 0;
968 	    return 0;
969 	}
970 
971 	switch (mouse.proto) {
972 
973 	/*
974 	 * IntelliMouse, NetMouse (including NetMouse Pro) and Mie Mouse
975 	 * always send the fourth byte, whereas the fourth byte is
976 	 * optional for GlidePoint and ThinkingMouse. The fourth byte
977 	 * is also optional for MouseMan+ and FirstMouse+ in their
978 	 * native mode. It is always sent if they are in the IntelliMouse
979 	 * compatible mode.
980 	 */
981 	case P_IMSERIAL:	/* IntelliMouse, NetMouse, Mie Mouse,
982 					   MouseMan+ */
983 	    act->dx = act->dy = 0;
984 	    act->dz = (rBuf & 0x08) ? (rBuf & 0x0f) - 16 : (rBuf & 0x0f);
985 	    act->obutton = act->button;
986 	    act->button = butmapintelli[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
987 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
988 	    break;
989 
990 	default:
991 	    act->dx = act->dy = act->dz = 0;
992 	    act->obutton = act->button;
993 	    act->button = butmapmss2[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
994 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
995 	    break;
996 	}
997 
998 	act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
999 	    | (act->obutton ^ act->button);
1000         pBufP = 0;
1001 	return act->flags;
1002     }
1003 
1004     if (pBufP >= cur_proto[4])
1005 	pBufP = 0;
1006     pBuf[pBufP++] = rBuf;
1007     if (pBufP != cur_proto[4])
1008 	return 0;
1009 
1010     /*
1011      * assembly full package
1012      */
1013 
1014     debug("assembled full packet (len %d) %x,%x,%x,%x,%x,%x,%x,%x",
1015 	cur_proto[4],
1016 	pBuf[0], pBuf[1], pBuf[2], pBuf[3],
1017 	pBuf[4], pBuf[5], pBuf[6], pBuf[7]);
1018 
1019     act->dz = 0;
1020     act->obutton = act->button;
1021     switch (mouse.proto)
1022     {
1023     case P_MS:		/* Microsoft */
1024     case P_LOGIMAN:	/* MouseMan/TrackMan */
1025     case P_GLIDEPOINT:	/* GlidePoint */
1026     case P_THINKING:		/* ThinkingMouse */
1027     case P_IMSERIAL:		/* IntelliMouse, NetMouse, Mie Mouse,
1028 					   MouseMan+ */
1029 	act->button = (act->obutton & (MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN))
1030             | butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
1031 	act->dx = (char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
1032 	act->dy = (char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
1033 	break;
1034 
1035     case P_MSC:		/* MouseSystems Corp */
1036 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_MSC_BUTTONS];
1037 	act->dx =    (char)(pBuf[1]) + (char)(pBuf[3]);
1038 	act->dy = - ((char)(pBuf[2]) + (char)(pBuf[4]));
1039 	break;
1040 
1041     case P_MMHIT:		/* MM HitTablet */
1042 	act->button = butmaphit[pBuf[0] & 0x07];
1043 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
1044 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
1045 	break;
1046 
1047     case P_MM:		/* MM Series */
1048     case P_LOGI:		/* Logitech Mice */
1049 	act->button = butmapmsc[pBuf[0] & MOUSE_MSC_BUTTONS];
1050 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
1051 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
1052 	break;
1053 
1054 	/* XXX
1055 	 * removed the code for BusMouse and PS/2 protocols
1056 	 * which are now handled by wsmouse compatible mouse drivers
1057 	 * XXX
1058 	 */
1059 
1060     default:
1061 	return 0;
1062     }
1063 
1064     /*
1065      * We don't reset pBufP here yet, as there may be an additional data
1066      * byte in some protocols. See above.
1067      */
1068 
1069     /* has something changed? */
1070     act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
1071 	| (act->obutton ^ act->button);
1072 
1073     return act->flags;
1074 }
1075 
1076