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