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