xref: /freebsd/sys/dev/cyapa/cyapa.c (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*
2  * Copyright (c) 2014 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com> and was subsequently ported,
6  * modified and enhanced for FreeBSD by Michael Gmelin <freebsd@grem.de>.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 /*
38  * CYAPA - Cypress APA trackpad with I2C Interface driver
39  *
40  * Based on DragonFlyBSD's cyapa driver, which referenced the linux
41  * cyapa.c driver to figure out the bootstrapping and commands.
42  *
43  * Unable to locate any datasheet for the device.
44  *
45  *
46  * Trackpad layout:
47  *
48  *                2/3               1/3
49  *       +--------------------+------------+
50  *       |                    |   Middle   |
51  *       |                    |   Button   |
52  *       |       Left         |            |
53  *       |      Button        +------------+
54  *       |                    |   Right    |
55  *       |                    |   Button   |
56  *       +--------------------+............|
57  *       |     Thumb/Button Area           | 15%
58  *       +---------------------------------+
59  *
60  *
61  *                             FEATURES
62  *
63  * IMPS/2 emulation       - Emulates the IntelliMouse protocol.
64  *
65  * Jitter supression      - Implements 2-pixel hysteresis with memory.
66  *
67  * Jump detecion          - Detect jumps caused by touchpad.
68  *
69  * Two finger scrolling   - Use two fingers for Z axis scrolling.
70  *
71  * Button down/2nd finger - While one finger clicks and holds down the
72  *                          touchpad, the second one can be used to move
73  *                          the mouse cursor. Useful for drawing or
74  *                          selecting text.
75  *
76  * Thumb/Button Area      - The lower 15%* of the trackpad will not affect
77  *                          the mouse cursor position. This allows for high
78  *                          precision clicking, by controlling the cursor
79  *                          with the index finger and pushing/holding the
80  *                          pad down with the thumb.
81  *                          * can be changed using sysctl
82  *
83  * Track-pad button       - Push physical button. Left 2/3rds of the pad
84  *                          will issue a LEFT button event, upper right
85  *                          corner will issue a MIDDLE button event,
86  *                          lower right corner will issue a RIGHT button
87  *                          event. Optional tap support can be enabled
88  *                          and configured using sysctl.
89  *
90  *                              WARNINGS
91  *
92  * These trackpads get confused when three or more fingers are down on the
93  * same horizontal axis and will start to glitch the finger detection.
94  * Removing your hand for a few seconds will allow the trackpad to
95  * recalibrate.  Generally speaking, when using three or more fingers
96  * please try to place at least one finger off-axis (a little above or
97  * below) the other two.
98  */
99 
100 #include "opt_evdev.h"
101 
102 #include <sys/param.h>
103 #include <sys/bus.h>
104 #include <sys/conf.h>
105 #include <sys/event.h>
106 #include <sys/fcntl.h>
107 #include <sys/kernel.h>
108 #include <sys/kthread.h>
109 #include <sys/lock.h>
110 #include <sys/lockmgr.h>
111 #include <sys/malloc.h>
112 #include <sys/mbuf.h>
113 #include <sys/module.h>
114 #include <sys/mouse.h>
115 #include <sys/mutex.h>
116 #include <sys/poll.h>
117 #include <sys/selinfo.h>
118 #include <sys/sysctl.h>
119 #include <sys/sysctl.h>
120 #include <sys/systm.h>
121 #include <sys/systm.h>
122 #include <sys/uio.h>
123 #include <sys/vnode.h>
124 
125 #include <dev/iicbus/iiconf.h>
126 #include <dev/iicbus/iicbus.h>
127 #include <dev/cyapa/cyapa.h>
128 
129 #ifdef EVDEV_SUPPORT
130 #include <dev/evdev/input.h>
131 #include <dev/evdev/evdev.h>
132 #endif
133 
134 #include "iicbus_if.h"
135 #include "bus_if.h"
136 #include "device_if.h"
137 
138 #define CYAPA_BUFSIZE	128			/* power of 2 */
139 #define CYAPA_BUFMASK	(CYAPA_BUFSIZE - 1)
140 
141 #define ZSCALE		15
142 
143 #define TIME_TO_IDLE	(hz * 10)
144 #define TIME_TO_RESET	(hz * 3)
145 
146 static MALLOC_DEFINE(M_CYAPA, "cyapa", "CYAPA device data");
147 
148 struct cyapa_fifo {
149 	int	rindex;
150 	int	windex;
151 	char	buf[CYAPA_BUFSIZE];
152 };
153 
154 struct cyapa_softc {
155 	device_t dev;
156 	int	count;			/* >0 if device opened */
157 	struct cdev *devnode;
158 	struct selinfo selinfo;
159 	struct mtx mutex;
160 	struct intr_config_hook intr_hook;
161 #ifdef EVDEV_SUPPORT
162 	struct evdev_dev *evdev;
163 #endif
164 
165 	int	cap_resx;
166 	int	cap_resy;
167 	int	cap_phyx;
168 	int	cap_phyy;
169 	uint8_t	cap_buttons;
170 
171 	int	detaching;		/* driver is detaching */
172 	int	poll_thread_running;	/* poll thread is running */
173 
174 	/* PS/2 mouse emulation */
175 	int	track_x;		/* current tracking */
176 	int	track_y;
177 	int	track_z;
178 	int	track_z_ticks;
179 	uint16_t track_but;
180 	char	track_id;		/* first finger id */
181 	int	track_nfingers;
182 	int	delta_x;		/* accumulation -> report */
183 	int	delta_y;
184 	int	delta_z;
185 	int	fuzz_x;
186 	int	fuzz_y;
187 	int	fuzz_z;
188 	int	touch_x;		/* touch down coordinates */
189 	int	touch_y;
190 	int	touch_z;
191 	int	finger1_ticks;
192 	int	finger2_ticks;
193 	int	finger3_ticks;
194 	uint16_t reported_but;
195 
196 	struct cyapa_fifo rfifo;	/* device->host */
197 	struct cyapa_fifo wfifo;	/* host->device */
198 	uint8_t	ps2_cmd;		/* active p2_cmd waiting for data */
199 	uint8_t ps2_acked;
200 	int	active_tick;
201 	int	data_signal;
202 	int	blocked;
203 	int	isselect;
204 	int	reporting_mode;		/* 0=disabled 1=enabled */
205 	int	scaling_mode;		/* 0=1:1 1=2:1 */
206 	int	remote_mode;		/* 0 for streaming mode */
207 	int	zenabled;		/* z-axis enabled (mode 1 or 2) */
208 	mousehw_t hw;			/* hardware information */
209 	mousemode_t mode;		/* mode */
210 	int	poll_ticks;
211 };
212 
213 struct cyapa_cdevpriv {
214 	struct cyapa_softc *sc;
215 };
216 
217 #define CYPOLL_SHUTDOWN	0x0001
218 
219 static void cyapa_poll_thread(void *arg);
220 static int cyapa_raw_input(struct cyapa_softc *sc, struct cyapa_regs *regs,
221     int freq);
222 static void cyapa_set_power_mode(struct cyapa_softc *sc, int mode);
223 
224 static int fifo_empty(struct cyapa_softc *sc, struct cyapa_fifo *fifo);
225 static size_t fifo_ready(struct cyapa_softc *sc, struct cyapa_fifo *fifo);
226 static char *fifo_read(struct cyapa_softc *sc, struct cyapa_fifo *fifo,
227     size_t n);
228 static char *fifo_write(struct cyapa_softc *sc, struct cyapa_fifo *fifo,
229     size_t n);
230 static uint8_t fifo_read_char(struct cyapa_softc *sc,
231     struct cyapa_fifo *fifo);
232 static void fifo_write_char(struct cyapa_softc *sc, struct cyapa_fifo *fifo,
233     uint8_t c);
234 static size_t fifo_space(struct cyapa_softc *sc, struct cyapa_fifo *fifo);
235 static void fifo_reset(struct cyapa_softc *sc, struct cyapa_fifo *fifo);
236 
237 static int cyapa_fuzz(int delta, int *fuzz);
238 
239 static int cyapa_idle_freq = 1;
240 SYSCTL_INT(_debug, OID_AUTO, cyapa_idle_freq, CTLFLAG_RW,
241 	    &cyapa_idle_freq, 0, "Scan frequency in idle mode");
242 static int cyapa_slow_freq = 20;
243 SYSCTL_INT(_debug, OID_AUTO, cyapa_slow_freq, CTLFLAG_RW,
244 	    &cyapa_slow_freq, 0, "Scan frequency in slow mode ");
245 static int cyapa_norm_freq = 100;
246 SYSCTL_INT(_debug, OID_AUTO, cyapa_norm_freq, CTLFLAG_RW,
247 	    &cyapa_norm_freq, 0, "Normal scan frequency");
248 static int cyapa_minpressure = 12;
249 SYSCTL_INT(_debug, OID_AUTO, cyapa_minpressure, CTLFLAG_RW,
250 	    &cyapa_minpressure, 0, "Minimum pressure to detect finger");
251 static int cyapa_enable_tapclick = 0;
252 SYSCTL_INT(_debug, OID_AUTO, cyapa_enable_tapclick, CTLFLAG_RW,
253 	    &cyapa_enable_tapclick, 0, "Enable tap to click");
254 static int cyapa_tapclick_min_ticks = 1;
255 SYSCTL_INT(_debug, OID_AUTO, cyapa_tapclick_min_ticks, CTLFLAG_RW,
256 	    &cyapa_tapclick_min_ticks, 0, "Minimum tap duration for click");
257 static int cyapa_tapclick_max_ticks = 8;
258 SYSCTL_INT(_debug, OID_AUTO, cyapa_tapclick_max_ticks, CTLFLAG_RW,
259 	    &cyapa_tapclick_max_ticks, 0, "Maximum tap duration for click");
260 static int cyapa_move_min_ticks = 4;
261 SYSCTL_INT(_debug, OID_AUTO, cyapa_move_min_ticks, CTLFLAG_RW,
262 	    &cyapa_move_min_ticks, 0,
263 	    "Minimum ticks before cursor position is changed");
264 static int cyapa_scroll_wait_ticks = 0;
265 SYSCTL_INT(_debug, OID_AUTO, cyapa_scroll_wait_ticks, CTLFLAG_RW,
266 	    &cyapa_scroll_wait_ticks, 0,
267 	    "Wait N ticks before starting to scroll");
268 static int cyapa_scroll_stick_ticks = 15;
269 SYSCTL_INT(_debug, OID_AUTO, cyapa_scroll_stick_ticks, CTLFLAG_RW,
270 	    &cyapa_scroll_stick_ticks, 0,
271 	    "Prevent cursor move on single finger for N ticks after scroll");
272 static int cyapa_thumbarea_percent = 15;
273 SYSCTL_INT(_debug, OID_AUTO, cyapa_thumbarea_percent, CTLFLAG_RW,
274 	    &cyapa_thumbarea_percent, 0,
275 	    "Size of bottom thumb area in percent");
276 
277 static int cyapa_debug = 0;
278 SYSCTL_INT(_debug, OID_AUTO, cyapa_debug, CTLFLAG_RW,
279 	    &cyapa_debug, 0, "Enable debugging");
280 static int cyapa_reset = 0;
281 SYSCTL_INT(_debug, OID_AUTO, cyapa_reset, CTLFLAG_RW,
282 	    &cyapa_reset, 0, "Reset track pad");
283 
284 static int
285 cyapa_read_bytes(device_t dev, uint8_t reg, uint8_t *val, int cnt)
286 {
287 	uint16_t addr = iicbus_get_addr(dev);
288 	struct iic_msg msgs[] = {
289 	     { addr, IIC_M_WR | IIC_M_NOSTOP, 1, &reg },
290 	     { addr, IIC_M_RD, cnt, val },
291 	};
292 
293 	return (iicbus_transfer(dev, msgs, nitems(msgs)));
294 }
295 
296 static int
297 cyapa_write_bytes(device_t dev, uint8_t reg, const uint8_t *val, int cnt)
298 {
299 	uint16_t addr = iicbus_get_addr(dev);
300 	struct iic_msg msgs[] = {
301 	     { addr, IIC_M_WR | IIC_M_NOSTOP, 1, &reg },
302 	     { addr, IIC_M_WR | IIC_M_NOSTART, cnt, __DECONST(uint8_t *, val) },
303 	};
304 
305 	return (iicbus_transfer(dev, msgs, nitems(msgs)));
306 }
307 
308 static void
309 cyapa_lock(struct cyapa_softc *sc)
310 {
311 
312 	mtx_lock(&sc->mutex);
313 }
314 
315 static void
316 cyapa_unlock(struct cyapa_softc *sc)
317 {
318 
319 	mtx_unlock(&sc->mutex);
320 }
321 
322 #define	CYAPA_LOCK_ASSERT(sc)	mtx_assert(&(sc)->mutex, MA_OWNED);
323 
324 /*
325  * Notify if possible receive data ready.  Must be called
326  * with sc->mutex held (cyapa_lock(sc)).
327  */
328 static void
329 cyapa_notify(struct cyapa_softc *sc)
330 {
331 
332 	CYAPA_LOCK_ASSERT(sc);
333 
334 	if (sc->data_signal || !fifo_empty(sc, &sc->rfifo)) {
335 		KNOTE_LOCKED(&sc->selinfo.si_note, 0);
336 		if (sc->blocked || sc->isselect) {
337 			if (sc->blocked) {
338 			    sc->blocked = 0;
339 			    wakeup(&sc->blocked);
340 			}
341 			if (sc->isselect) {
342 			    sc->isselect = 0;
343 			    selwakeup(&sc->selinfo);
344 			}
345 		}
346 	}
347 }
348 
349 /*
350  * Initialize the device
351  */
352 static int
353 init_device(device_t dev, struct cyapa_cap *cap, int probe)
354 {
355 	static char bl_exit[] = {
356 		0x00, 0xff, 0xa5, 0x00, 0x01,
357 		0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
358 	static char bl_deactivate[] = {
359 		0x00, 0xff, 0x3b, 0x00, 0x01,
360 		0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
361 	struct cyapa_boot_regs boot;
362 	int error;
363 	int retries;
364 
365 	/* Get status */
366 	error = cyapa_read_bytes(dev, CMD_BOOT_STATUS,
367 	    (void *)&boot, sizeof(boot));
368 	if (error)
369 		goto done;
370 
371 	/*
372 	 * Bootstrap the device if necessary.  It can take up to 2 seconds
373 	 * for the device to fully initialize.
374 	 */
375 	retries = 20;
376 	while ((boot.stat & CYAPA_STAT_RUNNING) == 0 && retries > 0) {
377 		if (boot.boot & CYAPA_BOOT_BUSY) {
378 			/* Busy, wait loop. */
379 		} else if (boot.error & CYAPA_ERROR_BOOTLOADER) {
380 			/* Magic */
381 			error = cyapa_write_bytes(dev, CMD_BOOT_STATUS,
382 			    bl_deactivate, sizeof(bl_deactivate));
383 			if (error)
384 				goto done;
385 		} else {
386 			/* Magic */
387 			error = cyapa_write_bytes(dev, CMD_BOOT_STATUS,
388 			    bl_exit, sizeof(bl_exit));
389 			if (error)
390 				goto done;
391 		}
392 		pause("cyapab1", (hz * 2) / 10);
393 		--retries;
394 		error = cyapa_read_bytes(dev, CMD_BOOT_STATUS,
395 		    (void *)&boot, sizeof(boot));
396 		if (error)
397 			goto done;
398 	}
399 
400 	if (retries == 0) {
401 		device_printf(dev, "Unable to bring device out of bootstrap\n");
402 		error = ENXIO;
403 		goto done;
404 	}
405 
406 	/* Check identity */
407 	if (cap) {
408 		error = cyapa_read_bytes(dev, CMD_QUERY_CAPABILITIES,
409 		    (void *)cap, sizeof(*cap));
410 
411 		if (strncmp(cap->prod_ida, "CYTRA", 5) != 0) {
412 			device_printf(dev, "Product ID \"%5.5s\" mismatch\n",
413 			    cap->prod_ida);
414 			error = ENXIO;
415 		}
416 	}
417 	error = cyapa_read_bytes(dev, CMD_BOOT_STATUS,
418 	    (void *)&boot, sizeof(boot));
419 
420 	if (probe == 0)		/* official init */
421 		device_printf(dev, "cyapa init status %02x\n", boot.stat);
422 	else if (probe == 2)
423 		device_printf(dev, "cyapa reset status %02x\n", boot.stat);
424 
425 done:
426 	if (error)
427 		device_printf(dev, "Unable to initialize\n");
428 	return (error);
429 }
430 
431 /*
432  * Start the polling thread
433  */
434 static void
435 cyapa_start(void *xdev)
436 {
437 	struct cyapa_softc *sc;
438 	device_t dev = xdev;
439 
440 	sc = device_get_softc(dev);
441 
442 	config_intrhook_disestablish(&sc->intr_hook);
443 
444 	/* Setup input event tracking */
445 	cyapa_set_power_mode(sc, CMD_POWER_MODE_IDLE);
446 
447 	/* Start the polling thread */
448 	kthread_add(cyapa_poll_thread, sc, NULL, NULL,
449 	    0, 0, "cyapa-poll");
450 }
451 
452 static int cyapa_probe(device_t);
453 static int cyapa_attach(device_t);
454 static int cyapa_detach(device_t);
455 static void cyapa_cdevpriv_dtor(void*);
456 
457 static device_method_t cyapa_methods[] = {
458 	/* device interface */
459 	DEVMETHOD(device_probe,		cyapa_probe),
460 	DEVMETHOD(device_attach,	cyapa_attach),
461 	DEVMETHOD(device_detach,	cyapa_detach),
462 
463 	DEVMETHOD_END
464 };
465 
466 static driver_t cyapa_driver = {
467 	"cyapa",
468 	cyapa_methods,
469 	sizeof(struct cyapa_softc),
470 };
471 
472 static	d_open_t	cyapaopen;
473 static	d_ioctl_t	cyapaioctl;
474 static	d_read_t	cyaparead;
475 static	d_write_t	cyapawrite;
476 static	d_kqfilter_t	cyapakqfilter;
477 static	d_poll_t	cyapapoll;
478 
479 static struct cdevsw cyapa_cdevsw = {
480 	.d_version =	D_VERSION,
481 	.d_open =	cyapaopen,
482 	.d_ioctl =	cyapaioctl,
483 	.d_read =	cyaparead,
484 	.d_write =	cyapawrite,
485 	.d_kqfilter =	cyapakqfilter,
486 	.d_poll =	cyapapoll,
487 };
488 
489 static int
490 cyapa_probe(device_t dev)
491 {
492 	struct cyapa_cap cap;
493 	int addr;
494 	int error;
495 
496 	addr = iicbus_get_addr(dev);
497 
498 	/*
499 	 * 0x67 - cypress trackpad on the acer c720
500 	 * (other devices might use other ids).
501 	 */
502 	if (addr != 0xce)
503 		return (ENXIO);
504 
505 	error = init_device(dev, &cap, 1);
506 	if (error != 0)
507 		return (ENXIO);
508 
509 	device_set_desc(dev, "Cypress APA I2C Trackpad");
510 
511 	return (BUS_PROBE_VENDOR);
512 }
513 
514 static int
515 cyapa_attach(device_t dev)
516 {
517 	struct cyapa_softc *sc;
518 	struct cyapa_cap cap;
519 	int unit;
520 	int addr;
521 
522 	sc = device_get_softc(dev);
523 	sc->reporting_mode = 1;
524 
525 	unit = device_get_unit(dev);
526 	addr = iicbus_get_addr(dev);
527 
528 	if (init_device(dev, &cap, 0))
529 		return (ENXIO);
530 
531 	mtx_init(&sc->mutex, "cyapa", NULL, MTX_DEF);
532 
533 	sc->dev = dev;
534 
535 	knlist_init_mtx(&sc->selinfo.si_note, &sc->mutex);
536 
537 	sc->cap_resx = ((cap.max_abs_xy_high << 4) & 0x0F00) |
538 	    cap.max_abs_x_low;
539 	sc->cap_resy = ((cap.max_abs_xy_high << 8) & 0x0F00) |
540 	    cap.max_abs_y_low;
541 	sc->cap_phyx = ((cap.phy_siz_xy_high << 4) & 0x0F00) |
542 	    cap.phy_siz_x_low;
543 	sc->cap_phyy = ((cap.phy_siz_xy_high << 8) & 0x0F00) |
544 	    cap.phy_siz_y_low;
545 	sc->cap_buttons = cap.buttons >> 3 &
546 	    (CYAPA_FNGR_LEFT | CYAPA_FNGR_RIGHT | CYAPA_FNGR_MIDDLE);
547 
548 	device_printf(dev, "%5.5s-%6.6s-%2.2s buttons=%c%c%c res=%dx%d\n",
549 	    cap.prod_ida, cap.prod_idb, cap.prod_idc,
550 	    ((sc->cap_buttons & CYAPA_FNGR_LEFT) ? 'L' : '-'),
551 	    ((sc->cap_buttons & CYAPA_FNGR_MIDDLE) ? 'M' : '-'),
552 	    ((sc->cap_buttons & CYAPA_FNGR_RIGHT) ? 'R' : '-'),
553 	    sc->cap_resx, sc->cap_resy);
554 
555 	sc->hw.buttons = 5;
556 	sc->hw.iftype = MOUSE_IF_PS2;
557 	sc->hw.type = MOUSE_MOUSE;
558 	sc->hw.model = MOUSE_MODEL_INTELLI;
559 	sc->hw.hwid = addr;
560 
561 	sc->mode.protocol = MOUSE_PROTO_PS2;
562 	sc->mode.rate = 100;
563 	sc->mode.resolution = 4;
564 	sc->mode.accelfactor = 1;
565 	sc->mode.level = 0;
566 	sc->mode.packetsize = MOUSE_PS2_PACKETSIZE;
567 
568 	sc->intr_hook.ich_func = cyapa_start;
569 	sc->intr_hook.ich_arg = sc->dev;
570 
571 #ifdef EVDEV_SUPPORT
572 	sc->evdev = evdev_alloc();
573 	evdev_set_name(sc->evdev, device_get_desc(sc->dev));
574 	evdev_set_phys(sc->evdev, device_get_nameunit(sc->dev));
575 	evdev_set_id(sc->evdev, BUS_I2C, 0, 0, 1);
576 	evdev_set_flag(sc->evdev, EVDEV_FLAG_MT_STCOMPAT);
577 	evdev_set_flag(sc->evdev, EVDEV_FLAG_MT_AUTOREL);
578 
579 	evdev_support_event(sc->evdev, EV_SYN);
580 	evdev_support_event(sc->evdev, EV_ABS);
581 	evdev_support_event(sc->evdev, EV_KEY);
582 	evdev_support_prop(sc->evdev, INPUT_PROP_POINTER);
583 	if (sc->cap_buttons & CYAPA_FNGR_LEFT)
584 		evdev_support_key(sc->evdev, BTN_LEFT);
585 	if (sc->cap_buttons & CYAPA_FNGR_RIGHT)
586 		evdev_support_key(sc->evdev, BTN_RIGHT);
587 	if (sc->cap_buttons & CYAPA_FNGR_MIDDLE)
588 		evdev_support_key(sc->evdev, BTN_MIDDLE);
589 	if (sc->cap_buttons == CYAPA_FNGR_LEFT)
590 		evdev_support_prop(sc->evdev, INPUT_PROP_BUTTONPAD);
591 
592 	evdev_support_abs(sc->evdev, ABS_MT_SLOT,
593 	    0, CYAPA_MAX_MT - 1, 0, 0, 0);
594 	evdev_support_abs(sc->evdev, ABS_MT_TRACKING_ID, -1, 15, 0, 0, 0);
595 	evdev_support_abs(sc->evdev, ABS_MT_POSITION_X, 0, sc->cap_resx, 0, 0,
596 	    sc->cap_phyx != 0 ? sc->cap_resx / sc->cap_phyx : 0);
597 	evdev_support_abs(sc->evdev, ABS_MT_POSITION_Y, 0, sc->cap_resy, 0, 0,
598 	    sc->cap_phyy != 0 ? sc->cap_resy / sc->cap_phyy : 0);
599 	evdev_support_abs(sc->evdev, ABS_MT_PRESSURE, 0, 255, 0, 0, 0);
600 
601 	if (evdev_register(sc->evdev) != 0) {
602 		mtx_destroy(&sc->mutex);
603 		return (ENOMEM);
604 	}
605 #endif
606 
607 	/* Postpone start of the polling thread until sleep is available */
608 	if (config_intrhook_establish(&sc->intr_hook) != 0) {
609 #ifdef EVDEV_SUPPORT
610 		evdev_free(sc->evdev);
611 #endif
612 		mtx_destroy(&sc->mutex);
613 		return (ENOMEM);
614 	}
615 
616 	sc->devnode = make_dev(&cyapa_cdevsw, unit,
617 	    UID_ROOT, GID_WHEEL, 0600, "cyapa%d", unit);
618 
619 	sc->devnode->si_drv1 = sc;
620 
621 	return (0);
622 }
623 
624 static int
625 cyapa_detach(device_t dev)
626 {
627 	struct cyapa_softc *sc;
628 
629 	sc = device_get_softc(dev);
630 
631 	/* Cleanup poller thread */
632 	cyapa_lock(sc);
633 	while (sc->poll_thread_running) {
634 		sc->detaching = 1;
635 		mtx_sleep(&sc->detaching, &sc->mutex, PCATCH, "cyapadet", hz);
636 	}
637 	cyapa_unlock(sc);
638 
639 	destroy_dev(sc->devnode);
640 
641 	knlist_clear(&sc->selinfo.si_note, 0);
642 	seldrain(&sc->selinfo);
643 	knlist_destroy(&sc->selinfo.si_note);
644 #ifdef EVDEV_SUPPORT
645 	evdev_free(sc->evdev);
646 #endif
647 
648 	mtx_destroy(&sc->mutex);
649 
650 	return (0);
651 }
652 
653 /*
654  * USER DEVICE I/O FUNCTIONS
655  */
656 static int
657 cyapaopen(struct cdev *dev, int oflags, int devtype, struct thread *td)
658 {
659 	struct cyapa_cdevpriv *priv;
660 	int error;
661 
662 	priv = malloc(sizeof(*priv), M_CYAPA, M_WAITOK | M_ZERO);
663 	priv->sc = dev->si_drv1;
664 
665 	error = devfs_set_cdevpriv(priv, cyapa_cdevpriv_dtor);
666 	if (error == 0) {
667 		cyapa_lock(priv->sc);
668 		priv->sc->count++;
669 		cyapa_unlock(priv->sc);
670 	}
671 	else
672 		free(priv, M_CYAPA);
673 
674 	return (error);
675 }
676 
677 static void
678 cyapa_cdevpriv_dtor(void *data)
679 {
680 	struct cyapa_cdevpriv *priv;
681 
682 	priv = data;
683 	KASSERT(priv != NULL, ("cyapa cdevpriv should not be NULL!"));
684 
685 	cyapa_lock(priv->sc);
686 	priv->sc->count--;
687 	cyapa_unlock(priv->sc);
688 
689 	free(priv, M_CYAPA);
690 }
691 
692 static int
693 cyaparead(struct cdev *dev, struct uio *uio, int ioflag)
694 {
695 	struct cyapa_softc *sc;
696 	int error;
697 	int didread;
698 	size_t n;
699 	char* ptr;
700 
701 	sc = dev->si_drv1;
702 	/* If buffer is empty, load a new event if it is ready */
703 	cyapa_lock(sc);
704 again:
705 	if (fifo_empty(sc, &sc->rfifo) &&
706 	    (sc->data_signal || sc->delta_x || sc->delta_y ||
707 	     sc->track_but != sc->reported_but)) {
708 		uint8_t c0;
709 		uint16_t but;
710 		int delta_x;
711 		int delta_y;
712 		int delta_z;
713 
714 		/* Accumulate delta_x, delta_y */
715 		sc->data_signal = 0;
716 		delta_x = sc->delta_x;
717 		delta_y = sc->delta_y;
718 		delta_z = sc->delta_z;
719 		if (delta_x > 255) {
720 			delta_x = 255;
721 			sc->data_signal = 1;
722 		}
723 		if (delta_x < -256) {
724 			delta_x = -256;
725 			sc->data_signal = 1;
726 		}
727 		if (delta_y > 255) {
728 			delta_y = 255;
729 			sc->data_signal = 1;
730 		}
731 		if (delta_y < -256) {
732 			delta_y = -256;
733 			sc->data_signal = 1;
734 		}
735 		if (delta_z > 255) {
736 			delta_z = 255;
737 			sc->data_signal = 1;
738 		}
739 		if (delta_z < -256) {
740 			delta_z = -256;
741 			sc->data_signal = 1;
742 		}
743 		but = sc->track_but;
744 
745 		/* Adjust baseline for next calculation */
746 		sc->delta_x -= delta_x;
747 		sc->delta_y -= delta_y;
748 		sc->delta_z -= delta_z;
749 		sc->reported_but = but;
750 
751 		/*
752 		 * Fuzz reduces movement jitter by introducing some
753 		 * hysteresis.  It operates without cumulative error so
754 		 * if you swish around quickly and return your finger to
755 		 * where it started, so to will the mouse.
756 		 */
757 		delta_x = cyapa_fuzz(delta_x, &sc->fuzz_x);
758 		delta_y = cyapa_fuzz(delta_y, &sc->fuzz_y);
759 		delta_z = cyapa_fuzz(delta_z, &sc->fuzz_z);
760 
761 		/*
762 		 * Generate report
763 		 */
764 		c0 = 0;
765 		if (delta_x < 0)
766 			c0 |= 0x10;
767 		if (delta_y < 0)
768 			c0 |= 0x20;
769 		c0 |= 0x08;
770 		if (but & CYAPA_FNGR_LEFT)
771 			c0 |= 0x01;
772 		if (but & CYAPA_FNGR_MIDDLE)
773 			c0 |= 0x04;
774 		if (but & CYAPA_FNGR_RIGHT)
775 			c0 |= 0x02;
776 
777 		fifo_write_char(sc, &sc->rfifo, c0);
778 		fifo_write_char(sc, &sc->rfifo, (uint8_t)delta_x);
779 		fifo_write_char(sc, &sc->rfifo, (uint8_t)delta_y);
780 		switch(sc->zenabled) {
781 		case 1:
782 			/* Z axis all 8 bits */
783 			fifo_write_char(sc, &sc->rfifo, (uint8_t)delta_z);
784 			break;
785 		case 2:
786 			/*
787 			 * Z axis low 4 bits + 4th button and 5th button
788 			 * (high 2 bits must be left 0).  Auto-scale
789 			 * delta_z to fit to avoid a wrong-direction
790 			 * overflow (don't try to retain the remainder).
791 			 */
792 			while (delta_z > 7 || delta_z < -8)
793 				delta_z >>= 1;
794 			c0 = (uint8_t)delta_z & 0x0F;
795 			fifo_write_char(sc, &sc->rfifo, c0);
796 			break;
797 		default:
798 			/* basic PS/2 */
799 			break;
800 		}
801 		cyapa_notify(sc);
802 	}
803 
804 	/* Blocking / Non-blocking */
805 	error = 0;
806 	didread = (uio->uio_resid == 0);
807 
808 	while ((ioflag & IO_NDELAY) == 0 && fifo_empty(sc, &sc->rfifo)) {
809 		if (sc->data_signal)
810 			goto again;
811 		sc->blocked = 1;
812 		error = mtx_sleep(&sc->blocked, &sc->mutex, PCATCH, "cyablk", 0);
813 		if (error)
814 			break;
815 	}
816 
817 	/* Return any buffered data */
818 	while (error == 0 && uio->uio_resid &&
819 	    (n = fifo_ready(sc, &sc->rfifo)) > 0) {
820 		if (n > uio->uio_resid)
821 			n = uio->uio_resid;
822 		ptr = fifo_read(sc, &sc->rfifo, 0);
823 		cyapa_unlock(sc);
824 		error = uiomove(ptr, n, uio);
825 		cyapa_lock(sc);
826 		if (error)
827 			break;
828 		fifo_read(sc, &sc->rfifo, n);
829 		didread = 1;
830 	}
831 	cyapa_unlock(sc);
832 
833 	if (error == 0 && didread == 0) {
834 		error = EWOULDBLOCK;
835 	}
836 	return (didread ? 0 : error);
837 }
838 
839 static int
840 cyapawrite(struct cdev *dev, struct uio *uio, int ioflag)
841 {
842 	struct cyapa_softc *sc;
843 	int error;
844 	int cmd_completed;
845 	size_t n;
846 	uint8_t c0;
847 	char* ptr;
848 
849 	sc = dev->si_drv1;
850 again:
851 	/*
852 	 * Copy data from userland.  This will also cross-over the end
853 	 * of the fifo and keep filling.
854 	 */
855 	cyapa_lock(sc);
856 	while ((n = fifo_space(sc, &sc->wfifo)) > 0 && uio->uio_resid) {
857 		if (n > uio->uio_resid)
858 			n = uio->uio_resid;
859 		ptr = fifo_write(sc, &sc->wfifo, 0);
860 		cyapa_unlock(sc);
861 		error = uiomove(ptr, n, uio);
862 		cyapa_lock(sc);
863 		if (error)
864 			break;
865 		fifo_write(sc, &sc->wfifo, n);
866 	}
867 
868 	/* Handle commands */
869 	cmd_completed = (fifo_ready(sc, &sc->wfifo) != 0);
870 	while (fifo_ready(sc, &sc->wfifo) && cmd_completed && error == 0) {
871 		if (sc->ps2_cmd == 0)
872 			sc->ps2_cmd = fifo_read_char(sc, &sc->wfifo);
873 		switch(sc->ps2_cmd) {
874 		case 0xE6:
875 			/* SET SCALING 1:1 */
876 			sc->scaling_mode = 0;
877 			fifo_write_char(sc, &sc->rfifo, 0xFA);
878 			break;
879 		case 0xE7:
880 			/* SET SCALING 2:1 */
881 			sc->scaling_mode = 1;
882 			fifo_write_char(sc, &sc->rfifo, 0xFA);
883 			break;
884 		case 0xE8:
885 			/* SET RESOLUTION +1 byte */
886 			if (sc->ps2_acked == 0) {
887 				sc->ps2_acked = 1;
888 				fifo_write_char(sc, &sc->rfifo, 0xFA);
889 			}
890 			if (fifo_ready(sc, &sc->wfifo) == 0) {
891 				cmd_completed = 0;
892 				break;
893 			}
894 			sc->mode.resolution = fifo_read_char(sc, &sc->wfifo);
895 			fifo_write_char(sc, &sc->rfifo, 0xFA);
896 			break;
897 		case 0xE9:
898 			/*
899 			 * STATUS REQUEST
900 			 *
901 			 * byte1:
902 			 *	bit 7	0
903 			 *	bit 6	Mode	(1=remote mode, 0=stream mode)
904 			 *	bit 5	Enable	(data reporting enabled)
905 			 *	bit 4	Scaling	(0=1:1 1=2:1)
906 			 *	bit 3	0
907 			 *	bit 2	LEFT BUTTON    (1 if pressed)
908 			 *	bit 1	MIDDLE BUTTON  (1 if pressed)
909 			 *	bit 0	RIGHT BUTTON   (1 if pressed)
910 			 *
911 			 * byte2: resolution counts/mm
912 			 * byte3: sample rate
913 			 */
914 			c0 = 0;
915 			if (sc->remote_mode)
916 				c0 |= 0x40;
917 			if (sc->reporting_mode)
918 				c0 |= 0x20;
919 			if (sc->scaling_mode)
920 				c0 |= 0x10;
921 			if (sc->track_but & CYAPA_FNGR_LEFT)
922 				c0 |= 0x04;
923 			if (sc->track_but & CYAPA_FNGR_MIDDLE)
924 				c0 |= 0x02;
925 			if (sc->track_but & CYAPA_FNGR_RIGHT)
926 				c0 |= 0x01;
927 			fifo_write_char(sc, &sc->rfifo, 0xFA);
928 			fifo_write_char(sc, &sc->rfifo, c0);
929 			fifo_write_char(sc, &sc->rfifo, 0x00);
930 			fifo_write_char(sc, &sc->rfifo, 100);
931 			break;
932 		case 0xEA:
933 			/* Set stream mode and reset movement counters */
934 			sc->remote_mode = 0;
935 			fifo_write_char(sc, &sc->rfifo, 0xFA);
936 			sc->delta_x = 0;
937 			sc->delta_y = 0;
938 			sc->delta_z = 0;
939 			break;
940 		case 0xEB:
941 			/*
942 			 * Read Data (if in remote mode).  If not in remote
943 			 * mode force an event.
944 			 */
945 			fifo_write_char(sc, &sc->rfifo, 0xFA);
946 			sc->data_signal = 1;
947 			break;
948 		case 0xEC:
949 			/* Reset Wrap Mode (ignored) */
950 			fifo_write_char(sc, &sc->rfifo, 0xFA);
951 			break;
952 		case 0xEE:
953 			/* Set Wrap Mode (ignored) */
954 			fifo_write_char(sc, &sc->rfifo, 0xFA);
955 			break;
956 		case 0xF0:
957 			/* Set Remote Mode */
958 			sc->remote_mode = 1;
959 			fifo_write_char(sc, &sc->rfifo, 0xFA);
960 			sc->delta_x = 0;
961 			sc->delta_y = 0;
962 			sc->delta_z = 0;
963 			break;
964 		case 0xF2:
965 			/*
966 			 * Get Device ID
967 			 *
968 			 * If we send 0x00 - normal PS/2 mouse, no Z-axis
969 			 *
970 			 * If we send 0x03 - Intellimouse, data packet has
971 			 * an additional Z movement byte (8 bits signed).
972 			 * (also reset movement counters)
973 			 *
974 			 * If we send 0x04 - Now includes z-axis and the
975 			 * 4th and 5th mouse buttons.
976 			 */
977 			fifo_write_char(sc, &sc->rfifo, 0xFA);
978 			switch(sc->zenabled) {
979 			case 1:
980 				fifo_write_char(sc, &sc->rfifo, 0x03);
981 				break;
982 			case 2:
983 				fifo_write_char(sc, &sc->rfifo, 0x04);
984 				break;
985 			default:
986 				fifo_write_char(sc, &sc->rfifo, 0x00);
987 				break;
988 			}
989 			sc->delta_x = 0;
990 			sc->delta_y = 0;
991 			sc->delta_z = 0;
992 			break;
993 		case 0xF3:
994 			/*
995 			 * Set Sample Rate
996 			 *
997 			 * byte1: the sample rate
998 			 */
999 			if (sc->ps2_acked == 0) {
1000 				sc->ps2_acked = 1;
1001 				fifo_write_char(sc, &sc->rfifo, 0xFA);
1002 			}
1003 			if (fifo_ready(sc, &sc->wfifo) == 0) {
1004 				cmd_completed = 0;
1005 				break;
1006 			}
1007 			sc->mode.rate = fifo_read_char(sc, &sc->wfifo);
1008 			fifo_write_char(sc, &sc->rfifo, 0xFA);
1009 
1010 			/*
1011 			 * zenabling sequence: 200,100,80 (device id 0x03)
1012 			 *		       200,200,80 (device id 0x04)
1013 			 *
1014 			 * We support id 0x03 (no 4th or 5th button).
1015 			 * We support id 0x04 (w/ 4th and 5th button).
1016 			 */
1017 			if (sc->zenabled == 0 && sc->mode.rate == 200)
1018 				sc->zenabled = -1;
1019 			else if (sc->zenabled == -1 && sc->mode.rate == 100)
1020 				sc->zenabled = -2;
1021 			else if (sc->zenabled == -1 && sc->mode.rate == 200)
1022 				sc->zenabled = -3;
1023 			else if (sc->zenabled == -2 && sc->mode.rate == 80)
1024 				sc->zenabled = 1;	/* z-axis mode */
1025 			else if (sc->zenabled == -3 && sc->mode.rate == 80)
1026 				sc->zenabled = 2;	/* z-axis+but4/5 */
1027 			if (sc->mode.level)
1028 				sc->zenabled = 1;
1029 			break;
1030 		case 0xF4:
1031 			/* Enable data reporting.  Only effects stream mode. */
1032 			fifo_write_char(sc, &sc->rfifo, 0xFA);
1033 			sc->reporting_mode = 1;
1034 			break;
1035 		case 0xF5:
1036 			/*
1037 			 * Disable data reporting.  Only effects stream mode
1038 			 * and is ignored right now.
1039 			 */
1040 			fifo_write_char(sc, &sc->rfifo, 0xFA);
1041 			sc->reporting_mode = 1;
1042 			break;
1043 		case 0xF6:
1044 			/*
1045 			 * SET DEFAULTS
1046 			 *
1047 			 * (reset sampling rate, resolution, scaling and
1048 			 *  enter stream mode)
1049 			 */
1050 			fifo_write_char(sc, &sc->rfifo, 0xFA);
1051 			sc->mode.rate = 100;
1052 			sc->mode.resolution = 4;
1053 			sc->scaling_mode = 0;
1054 			sc->reporting_mode = 1;
1055 			sc->remote_mode = 0;
1056 			sc->delta_x = 0;
1057 			sc->delta_y = 0;
1058 			sc->delta_z = 0;
1059 			/* signal */
1060 			break;
1061 		case 0xFE:
1062 			/*
1063 			 * RESEND
1064 			 *
1065 			 * Force a resend by guaranteeing that reported_but
1066 			 * differs from track_but.
1067 			 */
1068 			fifo_write_char(sc, &sc->rfifo, 0xFA);
1069 			sc->data_signal = 1;
1070 			break;
1071 		case 0xFF:
1072 			/*
1073 			 * RESET
1074 			 */
1075 			fifo_reset(sc, &sc->rfifo);	/* should we do this? */
1076 			fifo_reset(sc, &sc->wfifo);	/* should we do this? */
1077 			fifo_write_char(sc, &sc->rfifo, 0xFA);
1078 			sc->delta_x = 0;
1079 			sc->delta_y = 0;
1080 			sc->delta_z = 0;
1081 			sc->zenabled = 0;
1082 			sc->mode.level = 0;
1083 			break;
1084 		default:
1085 			printf("unknown command %02x\n", sc->ps2_cmd);
1086 			break;
1087 		}
1088 		if (cmd_completed) {
1089 			sc->ps2_cmd = 0;
1090 			sc->ps2_acked = 0;
1091 		}
1092 		cyapa_notify(sc);
1093 	}
1094 	cyapa_unlock(sc);
1095 	if (error == 0 && (cmd_completed || uio->uio_resid))
1096 		goto again;
1097 	return (error);
1098 }
1099 
1100 static void cyapafiltdetach(struct knote *);
1101 static int cyapafilt(struct knote *, long);
1102 
1103 static struct filterops cyapa_filtops = {
1104 	    .f_isfd = 1,
1105 	    .f_detach = cyapafiltdetach,
1106 	    .f_event = cyapafilt
1107 };
1108 
1109 static int
1110 cyapakqfilter(struct cdev *dev, struct knote *kn)
1111 {
1112 	struct cyapa_softc *sc;
1113 	struct knlist *knlist;
1114 
1115 	sc = dev->si_drv1;
1116 
1117 	switch(kn->kn_filter) {
1118 	case EVFILT_READ:
1119 		kn->kn_fop = &cyapa_filtops;
1120 		kn->kn_hook = (void *)sc;
1121 		break;
1122 	default:
1123 		return (EOPNOTSUPP);
1124 	}
1125 	knlist = &sc->selinfo.si_note;
1126 	knlist_add(knlist, kn, 0);
1127 
1128 	return (0);
1129 }
1130 
1131 static int
1132 cyapapoll(struct cdev *dev, int events, struct thread *td)
1133 {
1134 	struct cyapa_softc *sc;
1135 	int revents;
1136 
1137 	sc = dev->si_drv1;
1138 	revents = 0;
1139 
1140 	cyapa_lock(sc);
1141 	if (events & (POLLIN | POLLRDNORM)) {
1142 		if (sc->data_signal || !fifo_empty(sc, &sc->rfifo))
1143 			revents = events & (POLLIN | POLLRDNORM);
1144 		else {
1145 			sc->isselect = 1;
1146 			selrecord(td, &sc->selinfo);
1147 		}
1148 	}
1149 	cyapa_unlock(sc);
1150 
1151 	return (revents);
1152 }
1153 
1154 static void
1155 cyapafiltdetach(struct knote *kn)
1156 {
1157 	struct cyapa_softc *sc;
1158 	struct knlist *knlist;
1159 
1160 	sc = (struct cyapa_softc *)kn->kn_hook;
1161 
1162 	knlist = &sc->selinfo.si_note;
1163 	knlist_remove(knlist, kn, 0);
1164 }
1165 
1166 static int
1167 cyapafilt(struct knote *kn, long hint)
1168 {
1169 	struct cyapa_softc *sc;
1170 	int ready;
1171 
1172 	sc = (struct cyapa_softc *)kn->kn_hook;
1173 
1174 	cyapa_lock(sc);
1175 	ready = fifo_ready(sc, &sc->rfifo) || sc->data_signal;
1176 	cyapa_unlock(sc);
1177 
1178 	return (ready);
1179 }
1180 
1181 static int
1182 cyapaioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
1183 {
1184 	struct cyapa_softc *sc;
1185 	int error;
1186 
1187 	sc = dev->si_drv1;
1188 	error = 0;
1189 
1190 	cyapa_lock(sc);
1191 	switch (cmd) {
1192 	case MOUSE_GETHWINFO:
1193 		*(mousehw_t *)data = sc->hw;
1194 		if (sc->mode.level == 0)
1195 			((mousehw_t *)data)->model = MOUSE_MODEL_GENERIC;
1196 		break;
1197 
1198 	case MOUSE_GETMODE:
1199 		*(mousemode_t *)data = sc->mode;
1200 		((mousemode_t *)data)->resolution =
1201 		    MOUSE_RES_LOW - sc->mode.resolution;
1202 		switch (sc->mode.level) {
1203 		case 0:
1204 			((mousemode_t *)data)->protocol = MOUSE_PROTO_PS2;
1205 			((mousemode_t *)data)->packetsize =
1206 			    MOUSE_PS2_PACKETSIZE;
1207 			break;
1208 		case 2:
1209 			((mousemode_t *)data)->protocol = MOUSE_PROTO_PS2;
1210 			((mousemode_t *)data)->packetsize =
1211 			    MOUSE_PS2_PACKETSIZE + 1;
1212 			break;
1213 		}
1214 		break;
1215 
1216 	case MOUSE_GETLEVEL:
1217 		*(int *)data = sc->mode.level;
1218 		break;
1219 
1220 	case MOUSE_SETLEVEL:
1221 		if ((*(int *)data < 0) &&
1222 		    (*(int *)data > 2)) {
1223 			error = EINVAL;
1224 			break;
1225 		}
1226 		sc->mode.level = *(int *)data ? 2 : 0;
1227 		sc->zenabled = sc->mode.level ? 1 : 0;
1228 		break;
1229 
1230 	default:
1231 		error = ENOTTY;
1232 		break;
1233 	}
1234 	cyapa_unlock(sc);
1235 
1236 	return (error);
1237 }
1238 
1239 /*
1240  * MAJOR SUPPORT FUNCTIONS
1241  */
1242 static void
1243 cyapa_poll_thread(void *arg)
1244 {
1245 	struct cyapa_softc *sc;
1246 	struct cyapa_regs regs;
1247 	device_t bus;		/* iicbus */
1248 	int error;
1249 	int freq;
1250 	int isidle;
1251 	int pstate;
1252 	int npstate;
1253 	int last_reset;
1254 
1255 	sc = arg;
1256 	freq = cyapa_norm_freq;
1257 	isidle = 0;
1258 	pstate = CMD_POWER_MODE_IDLE;
1259 	last_reset = ticks;
1260 
1261 	bus = device_get_parent(sc->dev);
1262 
1263 	cyapa_lock(sc);
1264 	sc->poll_thread_running = 1;
1265 
1266 	while (!sc->detaching) {
1267 		cyapa_unlock(sc);
1268 		error = iicbus_request_bus(bus, sc->dev, IIC_WAIT);
1269 		if (error == 0) {
1270 			error = cyapa_read_bytes(sc->dev, CMD_DEV_STATUS,
1271 			    (void *)&regs, sizeof(regs));
1272 			if (error == 0) {
1273 				isidle = cyapa_raw_input(sc, &regs, freq);
1274 			}
1275 
1276 			/*
1277 			 * For some reason the device can crap-out.  If it
1278 			 * drops back into bootstrap mode try to reinitialize
1279 			 * it.
1280 			 */
1281 			if (cyapa_reset ||
1282 			    ((regs.stat & CYAPA_STAT_RUNNING) == 0 &&
1283 			     (unsigned)(ticks - last_reset) > TIME_TO_RESET)) {
1284 				cyapa_reset = 0;
1285 				last_reset = ticks;
1286 				init_device(sc->dev, NULL, 2);
1287 			}
1288 			iicbus_release_bus(bus, sc->dev);
1289 		}
1290 		pause("cyapw", hz / freq);
1291 		++sc->poll_ticks;
1292 
1293 		if (sc->count == 0) {
1294 			freq = cyapa_idle_freq;
1295 			npstate = CMD_POWER_MODE_IDLE;
1296 		} else if (isidle) {
1297 			freq = cyapa_slow_freq;
1298 			npstate = CMD_POWER_MODE_IDLE;
1299 		} else {
1300 			freq = cyapa_norm_freq;
1301 			npstate = CMD_POWER_MODE_FULL;
1302 		}
1303 		if (pstate != npstate) {
1304 			pstate = npstate;
1305 			cyapa_set_power_mode(sc, pstate);
1306 			if (cyapa_debug) {
1307 				switch(pstate) {
1308 				case CMD_POWER_MODE_OFF:
1309 					printf("cyapa: power off\n");
1310 					break;
1311 				case CMD_POWER_MODE_IDLE:
1312 					printf("cyapa: power idle\n");
1313 					break;
1314 				case CMD_POWER_MODE_FULL:
1315 					printf("cyapa: power full\n");
1316 					break;
1317 				}
1318 			}
1319 		}
1320 
1321 		cyapa_lock(sc);
1322 	}
1323 	sc->poll_thread_running = 0;
1324 	cyapa_unlock(sc);
1325 	kthread_exit();
1326 }
1327 
1328 static int
1329 cyapa_raw_input(struct cyapa_softc *sc, struct cyapa_regs *regs, int freq)
1330 {
1331 	int nfingers;
1332 	int afingers;	/* actual fingers after culling */
1333 	int i;
1334 	int j;
1335 	int isidle;
1336 	int thumbarea_begin;
1337 	int seen_thumb;
1338 	int x;
1339 	int y;
1340 	int z;
1341 	int newfinger;
1342 	int lessfingers;
1343 	int click_x;
1344 	int click_y;
1345 	uint16_t but;	/* high bits used for simulated but4/but5 */
1346 
1347 	thumbarea_begin = sc->cap_resy -
1348 	    ((sc->cap_resy *  cyapa_thumbarea_percent) / 100);
1349 	click_x = click_y = 0;
1350 
1351 	/*
1352 	 * If the device is not running the rest of the status
1353 	 * means something else, set fingers to 0.
1354 	 */
1355 	if ((regs->stat & CYAPA_STAT_RUNNING) == 0) {
1356 		regs->fngr = 0;
1357 	}
1358 
1359 	/* Process fingers/movement */
1360 	nfingers = CYAPA_FNGR_NUMFINGERS(regs->fngr);
1361 	afingers = nfingers;
1362 
1363 	if (cyapa_debug) {
1364 		printf("stat %02x buttons %c%c%c nfngrs=%d ",
1365 		    regs->stat,
1366 		    ((regs->fngr & CYAPA_FNGR_LEFT) ? 'L' : '-'),
1367 		    ((regs->fngr & CYAPA_FNGR_MIDDLE) ? 'M' : '-'),
1368 		    ((regs->fngr & CYAPA_FNGR_RIGHT) ? 'R' : '-'),
1369 		    nfingers);
1370 	}
1371 
1372 #ifdef EVDEV_SUPPORT
1373 	if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) {
1374 		for (i = 0; i < nfingers; ++i) {
1375 			int slot = evdev_mt_id_to_slot(
1376 			    sc->evdev, regs->touch[i].id);
1377 			if (slot == -1) {
1378 				if (cyapa_debug)
1379 					printf("Slot overflow for i=%d\n",
1380 					    regs->touch[i].id);
1381 				continue;
1382 			}
1383 			evdev_push_abs(sc->evdev, ABS_MT_SLOT, slot);
1384 			evdev_push_abs(sc->evdev, ABS_MT_TRACKING_ID,
1385 			    regs->touch[i].id);
1386 			evdev_push_abs(sc->evdev, ABS_MT_POSITION_X,
1387 			    CYAPA_TOUCH_X(regs, i));
1388 			evdev_push_abs(sc->evdev, ABS_MT_POSITION_Y,
1389 			    CYAPA_TOUCH_Y(regs, i));
1390 			evdev_push_abs(sc->evdev, ABS_MT_PRESSURE,
1391 			    CYAPA_TOUCH_P(regs, i));
1392 		}
1393 		if (sc->cap_buttons & CYAPA_FNGR_LEFT)
1394 			evdev_push_key(sc->evdev, BTN_LEFT,
1395 			    regs->fngr & CYAPA_FNGR_LEFT);
1396 		if (sc->cap_buttons & CYAPA_FNGR_RIGHT)
1397 			evdev_push_key(sc->evdev, BTN_RIGHT,
1398 			    regs->fngr & CYAPA_FNGR_RIGHT);
1399 		if (sc->cap_buttons & CYAPA_FNGR_MIDDLE)
1400 			evdev_push_key(sc->evdev, BTN_MIDDLE,
1401 			    regs->fngr & CYAPA_FNGR_MIDDLE);
1402 		evdev_sync(sc->evdev);
1403 	}
1404 #endif
1405 
1406 	seen_thumb = 0;
1407 	for (i = 0; i < afingers; ) {
1408 		if (cyapa_debug) {
1409 			printf(" [x=%04d y=%04d p=%d i=%d]",
1410 			    CYAPA_TOUCH_X(regs, i),
1411 			    CYAPA_TOUCH_Y(regs, i),
1412 			    CYAPA_TOUCH_P(regs, i),
1413 			    regs->touch[i].id);
1414 		}
1415 		if ((CYAPA_TOUCH_Y(regs, i) > thumbarea_begin && seen_thumb) ||
1416 		     CYAPA_TOUCH_P(regs, i) < cyapa_minpressure) {
1417 			--afingers;
1418 			if (i < afingers) {
1419 			    regs->touch[i] = regs->touch[i+1];
1420 			    continue;
1421 			}
1422 		} else {
1423 			if (CYAPA_TOUCH_Y(regs, i) > thumbarea_begin)
1424 			    seen_thumb = 1;
1425 		}
1426 		++i;
1427 	}
1428 	nfingers = afingers;
1429 
1430 	/* Tracking for local solutions */
1431 	cyapa_lock(sc);
1432 
1433 	/*
1434 	 * Track timing for finger-downs.  Used to detect false-3-finger
1435 	 * button-down.
1436 	 */
1437 	switch(afingers) {
1438 	case 0:
1439 		break;
1440 	case 1:
1441 		if (sc->track_nfingers == 0)
1442 			sc->finger1_ticks = sc->poll_ticks;
1443 		break;
1444 	case 2:
1445 		if (sc->track_nfingers <= 0)
1446 			sc->finger1_ticks = sc->poll_ticks;
1447 		if (sc->track_nfingers <= 1)
1448 			sc->finger2_ticks = sc->poll_ticks;
1449 		break;
1450 	case 3:
1451 	default:
1452 		if (sc->track_nfingers <= 0)
1453 			sc->finger1_ticks = sc->poll_ticks;
1454 		if (sc->track_nfingers <= 1)
1455 			sc->finger2_ticks = sc->poll_ticks;
1456 		if (sc->track_nfingers <= 2)
1457 			sc->finger3_ticks = sc->poll_ticks;
1458 		break;
1459 	}
1460 	newfinger = sc->track_nfingers < afingers;
1461 	lessfingers = sc->track_nfingers > afingers;
1462 	sc->track_nfingers = afingers;
1463 
1464 	/*
1465 	 * Lookup and track finger indexes in the touch[] array.
1466 	 */
1467 	if (afingers == 0) {
1468 		click_x = sc->track_x;
1469 		click_y = sc->track_y;
1470 		sc->track_x = -1;
1471 		sc->track_y = -1;
1472 		sc->track_z = -1;
1473 		sc->fuzz_x = 0;
1474 		sc->fuzz_y = 0;
1475 		sc->fuzz_z = 0;
1476 		sc->touch_x = -1;
1477 		sc->touch_y = -1;
1478 		sc->touch_z = -1;
1479 		sc->track_id = -1;
1480 		sc->track_but = 0;
1481 		i = 0;
1482 		j = 0;
1483 	} else {
1484 		/*
1485 		 * The id assigned on touch can move around in the array,
1486 		 * find it.  If that finger is lifted up, assign some other
1487 		 * finger for mouse tracking and reset track_x and track_y
1488 		 * to avoid a mouse jump.
1489 		 *
1490 		 * If >= 2 fingers are down be sure not to assign i and
1491 		 * j to the same index.
1492 		 */
1493 		for (i = 0; i < nfingers; ++i) {
1494 			if (sc->track_id == regs->touch[i].id)
1495 				break;
1496 		}
1497 		if (i == nfingers) {
1498 			i = 0;
1499 			sc->track_x = -1;
1500 			sc->track_y = -1;
1501 			sc->track_z = -1;
1502 			while (CYAPA_TOUCH_Y(regs, i) >= thumbarea_begin &&
1503 			    i < nfingers) ++i;
1504 			if (i == nfingers) {
1505 				i = 0;
1506 			}
1507 			sc->track_id = regs->touch[i].id;
1508 		}
1509 		else if ((sc->track_but ||
1510 		     CYAPA_TOUCH_Y(regs, i) >= thumbarea_begin) &&
1511 		    newfinger && afingers == 2) {
1512 			j = regs->touch[0].id == sc->track_id ? 1 : 0;
1513 			if (CYAPA_TOUCH_Y(regs, j) < thumbarea_begin) {
1514 			    i = j;
1515 			    sc->track_x = -1;
1516 			    sc->track_y = -1;
1517 			    sc->track_z = -1;
1518 			    sc->track_id = regs->touch[i].id;
1519 			}
1520 		}
1521 	}
1522 
1523 	/* Two finger scrolling - reset after timeout */
1524 	if (sc->track_z != -1 && afingers != 2 &&
1525 	    (sc->poll_ticks - sc->track_z_ticks) > cyapa_scroll_stick_ticks) {
1526 		sc->track_z = -1;
1527 		sc->track_z_ticks = 0;
1528 	}
1529 
1530 	/* Initiate two finger scrolling */
1531 	if (!(regs->fngr & CYAPA_FNGR_LEFT) &&
1532 	    ((afingers && sc->track_z != -1) ||
1533 	     (afingers == 2 && CYAPA_TOUCH_Y(regs, 0) < thumbarea_begin &&
1534 	     CYAPA_TOUCH_Y(regs, 1) < thumbarea_begin))) {
1535 		if (afingers == 2 && (sc->poll_ticks - sc->finger2_ticks)
1536 		    > cyapa_scroll_wait_ticks) {
1537 			z = (CYAPA_TOUCH_Y(regs, 0) +
1538 			    CYAPA_TOUCH_Y(regs, 1)) >> 1;
1539 			sc->delta_z += z / ZSCALE - sc->track_z;
1540 			if (sc->track_z == -1) {
1541 			    sc->delta_z = 0;
1542 			}
1543 			if (sc->touch_z == -1)
1544 			    sc->touch_z = z;	/* not used atm */
1545 			sc->track_z = z / ZSCALE;
1546 			sc->track_z_ticks = sc->poll_ticks;
1547 		}
1548 	} else if (afingers) {
1549 		/* Normal pad position reporting */
1550 		x = CYAPA_TOUCH_X(regs, i);
1551 		y = CYAPA_TOUCH_Y(regs, i);
1552 		click_x = x;
1553 		click_y = y;
1554 		if (sc->track_x != -1 && sc->track_y < thumbarea_begin &&
1555 		    (afingers > 1 || (sc->poll_ticks - sc->finger1_ticks)
1556 		    >= cyapa_move_min_ticks || freq < cyapa_norm_freq)) {
1557 			sc->delta_x += x - sc->track_x;
1558 			sc->delta_y -= y - sc->track_y;
1559 			if (sc->delta_x > sc->cap_resx)
1560 				sc->delta_x = sc->cap_resx;
1561 			if (sc->delta_x < -sc->cap_resx)
1562 				sc->delta_x = -sc->cap_resx;
1563 			if (sc->delta_y > sc->cap_resy)
1564 				sc->delta_y = sc->cap_resy;
1565 			if (sc->delta_y < -sc->cap_resy)
1566 				sc->delta_y = -sc->cap_resy;
1567 
1568 			if (abs(sc->delta_y) > sc->cap_resy / 2 ||
1569 			    abs(sc->delta_x) > sc->cap_resx / 2) {
1570 				if (cyapa_debug)
1571 					printf("Detected jump by %i %i\n",
1572 					    sc->delta_x, sc->delta_y);
1573 			    sc->delta_x = sc->delta_y = 0;
1574 			}
1575 		}
1576 		if (sc->touch_x == -1) {
1577 			sc->touch_x = x;
1578 			sc->touch_y = y;
1579 		}
1580 		sc->track_x = x;
1581 		sc->track_y = y;
1582 	}
1583 
1584 	/* Select finger (L = 2/3x, M = 1/3u, R = 1/3d) */
1585 	int is_tapclick = (cyapa_enable_tapclick && lessfingers &&
1586 	    afingers == 0 && sc->poll_ticks - sc->finger1_ticks
1587 	    >= cyapa_tapclick_min_ticks &&
1588 	    sc->poll_ticks - sc->finger1_ticks < cyapa_tapclick_max_ticks);
1589 
1590 	if (regs->fngr & CYAPA_FNGR_LEFT || is_tapclick) {
1591 		if (sc->track_but) {
1592 			but = sc->track_but;
1593 		} else if (afingers == 1) {
1594 			if (click_x < sc->cap_resx * 2 / 3)
1595 				but = CYAPA_FNGR_LEFT;
1596 			else if (click_y < sc->cap_resy / 2)
1597 				but = CYAPA_FNGR_MIDDLE;
1598 			else
1599 				but = CYAPA_FNGR_RIGHT;
1600 		} else if (is_tapclick) {
1601 			if (click_x < sc->cap_resx * 2 / 3 ||
1602 			    cyapa_enable_tapclick < 2)
1603 				but = CYAPA_FNGR_LEFT;
1604 			else if (click_y < sc->cap_resy / 2 &&
1605 			    cyapa_enable_tapclick > 2)
1606 				but = CYAPA_FNGR_MIDDLE;
1607 			else
1608 				but = CYAPA_FNGR_RIGHT;
1609 		} else {
1610 			but = CYAPA_FNGR_LEFT;
1611 		}
1612 	} else {
1613 		but = 0;
1614 	}
1615 
1616 	/*
1617 	 * Detect state change from last reported state and
1618 	 * determine if we have gone idle.
1619 	 */
1620 	sc->track_but = but;
1621 	if (sc->delta_x || sc->delta_y || sc->delta_z ||
1622 	    sc->track_but != sc->reported_but) {
1623 		sc->active_tick = ticks;
1624 		if (sc->remote_mode == 0 && sc->reporting_mode)
1625 			sc->data_signal = 1;
1626 		isidle = 0;
1627 	} else if ((unsigned)(ticks - sc->active_tick) >= TIME_TO_IDLE) {
1628 		sc->active_tick = ticks - TIME_TO_IDLE; /* prevent overflow */
1629 		isidle = 1;
1630 	} else {
1631 		isidle = 0;
1632 	}
1633 	cyapa_notify(sc);
1634 	cyapa_unlock(sc);
1635 
1636 	if (cyapa_debug)
1637 		printf("%i >> %i << %i\n", isidle, sc->track_id, sc->delta_y);
1638 	return (isidle);
1639 }
1640 
1641 static void
1642 cyapa_set_power_mode(struct cyapa_softc *sc, int mode)
1643 {
1644 	uint8_t data;
1645 	device_t bus;
1646 	int error;
1647 
1648 	bus = device_get_parent(sc->dev);
1649 	error = iicbus_request_bus(bus, sc->dev, IIC_WAIT);
1650 	if (error == 0) {
1651 		error = cyapa_read_bytes(sc->dev, CMD_POWER_MODE,
1652 		    &data, 1);
1653 		data = (data & ~0xFC) | mode;
1654 		if (error == 0) {
1655 			error = cyapa_write_bytes(sc->dev, CMD_POWER_MODE,
1656 			    &data, 1);
1657 		}
1658 		iicbus_release_bus(bus, sc->dev);
1659 	}
1660 }
1661 
1662 /*
1663  * FIFO FUNCTIONS
1664  */
1665 
1666 /*
1667  * Returns non-zero if the fifo is empty
1668  */
1669 static int
1670 fifo_empty(struct cyapa_softc *sc, struct cyapa_fifo *fifo)
1671 {
1672 
1673 	CYAPA_LOCK_ASSERT(sc);
1674 
1675 	return (fifo->rindex == fifo->windex);
1676 }
1677 
1678 /*
1679  * Returns the number of characters available for reading from
1680  * the fifo without wrapping the fifo buffer.
1681  */
1682 static size_t
1683 fifo_ready(struct cyapa_softc *sc, struct cyapa_fifo *fifo)
1684 {
1685 	size_t n;
1686 
1687 	CYAPA_LOCK_ASSERT(sc);
1688 
1689 	n = CYAPA_BUFSIZE - (fifo->rindex & CYAPA_BUFMASK);
1690 	if (n > (size_t)(fifo->windex - fifo->rindex))
1691 		n = (size_t)(fifo->windex - fifo->rindex);
1692 	return (n);
1693 }
1694 
1695 /*
1696  * Returns a read pointer into the fifo and then bumps
1697  * rindex.  The FIFO must have at least 'n' characters in
1698  * it.  The value (n) can cause the index to wrap but users
1699  * of the buffer should never supply a value for (n) that wraps
1700  * the buffer.
1701  */
1702 static char *
1703 fifo_read(struct cyapa_softc *sc, struct cyapa_fifo *fifo, size_t n)
1704 {
1705 	char *ptr;
1706 
1707 	CYAPA_LOCK_ASSERT(sc);
1708 	if (n > (CYAPA_BUFSIZE - (fifo->rindex & CYAPA_BUFMASK))) {
1709 		printf("fifo_read: overflow\n");
1710 		return (fifo->buf);
1711 	}
1712 	ptr = fifo->buf + (fifo->rindex & CYAPA_BUFMASK);
1713 	fifo->rindex += n;
1714 
1715 	return (ptr);
1716 }
1717 
1718 static uint8_t
1719 fifo_read_char(struct cyapa_softc *sc, struct cyapa_fifo *fifo)
1720 {
1721 	uint8_t c;
1722 
1723 	CYAPA_LOCK_ASSERT(sc);
1724 
1725 	if (fifo->rindex == fifo->windex) {
1726 		printf("fifo_read_char: overflow\n");
1727 		c = 0;
1728 	} else {
1729 		c = fifo->buf[fifo->rindex & CYAPA_BUFMASK];
1730 		++fifo->rindex;
1731 	}
1732 	return (c);
1733 }
1734 
1735 
1736 /*
1737  * Write a character to the FIFO.  The character will be discarded
1738  * if the FIFO is full.
1739  */
1740 static void
1741 fifo_write_char(struct cyapa_softc *sc, struct cyapa_fifo *fifo, uint8_t c)
1742 {
1743 
1744 	CYAPA_LOCK_ASSERT(sc);
1745 
1746 	if (fifo->windex - fifo->rindex < CYAPA_BUFSIZE) {
1747 		fifo->buf[fifo->windex & CYAPA_BUFMASK] = c;
1748 		++fifo->windex;
1749 	}
1750 }
1751 
1752 /*
1753  * Return the amount of space available for writing without wrapping
1754  * the fifo.
1755  */
1756 static size_t
1757 fifo_space(struct cyapa_softc *sc, struct cyapa_fifo *fifo)
1758 {
1759 	size_t n;
1760 
1761 	CYAPA_LOCK_ASSERT(sc);
1762 
1763 	n = CYAPA_BUFSIZE - (fifo->windex & CYAPA_BUFMASK);
1764 	if (n > (size_t)(CYAPA_BUFSIZE - (fifo->windex - fifo->rindex)))
1765 		n = (size_t)(CYAPA_BUFSIZE - (fifo->windex - fifo->rindex));
1766 	return (n);
1767 }
1768 
1769 static char *
1770 fifo_write(struct cyapa_softc *sc, struct cyapa_fifo *fifo, size_t n)
1771 {
1772 	char *ptr;
1773 
1774 	CYAPA_LOCK_ASSERT(sc);
1775 
1776 	ptr = fifo->buf + (fifo->windex & CYAPA_BUFMASK);
1777 	fifo->windex += n;
1778 
1779 	return (ptr);
1780 }
1781 
1782 static void
1783 fifo_reset(struct cyapa_softc *sc, struct cyapa_fifo *fifo)
1784 {
1785 
1786 	CYAPA_LOCK_ASSERT(sc);
1787 
1788 	fifo->rindex = 0;
1789 	fifo->windex = 0;
1790 }
1791 
1792 /*
1793  * Fuzz handling
1794  */
1795 static int
1796 cyapa_fuzz(int delta, int *fuzzp)
1797 {
1798 	int fuzz;
1799 
1800 	fuzz = *fuzzp;
1801 	if (fuzz >= 0 && delta < 0) {
1802 		++delta;
1803 		--fuzz;
1804 	} else if (fuzz <= 0 && delta > 0) {
1805 		--delta;
1806 		++fuzz;
1807 	}
1808 	*fuzzp = fuzz;
1809 
1810 	return (delta);
1811 }
1812 
1813 DRIVER_MODULE(cyapa, iicbus, cyapa_driver, NULL, NULL);
1814 MODULE_DEPEND(cyapa, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER);
1815 #ifdef EVDEV_SUPPORT
1816 MODULE_DEPEND(cyapa, evdev, 1, 1, 1);
1817 #endif
1818 MODULE_VERSION(cyapa, 1);
1819