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