xref: /dragonfly/sys/dev/smbus/atmel_mxt/atmel_mxt.c (revision f2c43266)
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>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 /*
35  * ATMEL_MXT - Atmel MXT touchscreen driver
36  *
37  *	PRELIMINARY DRIVER PRELIMINARY DRIVER PRELIMINARY DRIVERE
38  *
39  * (everything is pretty much hardwired and we assume the device is already
40  *  operational, which it appears to be.  ONLY TESTED ON ACER C720).
41  *
42  * This driver attaches to Acer TouchScreen MXT chipsets and currently
43  * emulates the ELO touchscreen serial protocol "elographics" for X:
44  *
45  *	Section "InputDevice"
46  *		Identifier  "TouchScreen0"
47  *		Driver      "elographics"
48  *		Option      "Device" "/dev/atmel1-4a"
49  *	EndSection
50  *
51  * The MXT chipsets typically attach on haswell chromebooks on one of the I2C
52  * busses at address 0x4A.  On my Acer C720 it attaches to the ig4 driver's
53  * I2C bus #1 at 0x4A.  kldload ig4; kldload atmel_mxt.
54  *
55  * The kernel driver and test code is written from scratch, but some code has
56  * been snarfed (in separate files) from linux development as referenced
57  * here:
58  *
59  * www.atmel.com/products/touchsolutions/touchscreens/unlimited_touch.aspx
60  * git://github.com/atmel-maxtouch/obp-utils.git
61  *
62  * The linux driver was also consulted, but not used.  Note that the linux
63  * driver appears to be GPL'd but uses code from obp-utils.git on github
64  * which is (c)Copyright by Atmel and uses more of a BSD-like license.  The
65  * obp-* source files contain the snarfed code and include this license.
66  *
67  * The ELO touchscreen serial protocol uses 10-byte fixed-length packets:
68  *
69  *	Byte 0:	    ELO_SYNC_BYTE ('U')
70  *	Byte 1-8:   Packet data
71  *	Byte 9:	    checksum of bytes 0 to 8
72  *
73  * Our interface reads and writes only whole packets and does not do any
74  * buffer stitching.  It is compatible with Xorg.
75  *
76  * Control Commands sent from Userland (only an Ack packet is returned)
77  *
78  *	Byte 0:	    ELO_SYNC_BYTE ('U')
79  *	Byte 1:	    ELO_MODE ('m')
80  *	Byte 2:	    Flags
81  *	    0x80 -
82  *	    0x40 Tracking mode
83  *	    0x20 -
84  *	    0x10 -
85  *	    0x08 Scaling mode
86  *	    0x04 Untouch mode
87  *	    0x02 Streaming mode
88  *	    0x01 Touch mode
89  *
90  *	Byte 0:	    ELO_SYNC_BYTE ('U')
91  *	Byte 1:	    ELO_REPORT ('r')
92  *
93  * Query Command sent from Userland: (expect response packet and Ack packet)
94  *
95  *	Byte 0:	    ELO_SYNC_BYTE ('U')		Request ID
96  *	Byte 1:	    ELO_ID ('i')
97  *
98  *	Byte 0:	    ELO_SYNC_BYTE ('U')`	Request Owner
99  *	Byte 1:	    ELO_OWNER ('o')
100  *
101  * Streaming packets sent from the driver to userland
102  *
103  *	Byte 0:	    ELO_SYNC_BYTE ('U')
104  *	Byte 1:	    ELO_TOUCH ('T')
105  *	Byte 2:	    Packet type
106  *	  Bit 2 : Pen Up	(Release)	0x04
107  *	  Bit 1 : Position	(Stream)	0x02
108  *	  Bit 0 : Pen Down	(Press)		0x01
109  *	Byte 3:	    X coordinate lsb
110  *	Byte 4:	    X coordinate msb
111  *	Byte 5:	    Y coordinate lsb
112  *	Byte 6:	    Y coordinate msb
113  *	Byte 7:	    Z coordinate lsb
114  *	Byte 8:	    Z coordinate msb
115  *
116  * Responses to commands: (one or two packets returned)
117  *
118  *	Byte 0:	    ELO_SYNC_BYTE ('U')		(if in response to query)
119  *	Byte 1:	    toupper(command_byte)	(control commands have no
120  *	Byte 2-8:   ... depends ....		 response)
121  *
122  *	Byte 0:	    ELO_SYNC_BYTE ('U')		(unconditional ack)
123  *	Byte 1:	    'A'ck
124  *	Byte 2-8:   ... depends ....
125  *
126  * NOTE!  For the most part we ignore commands other than doing the handwaving
127  *	  to send a dummied-up response and ack as assumed by the X driver.
128  *	  Also, the read() and write() support only reads and writes whole
129  *	  packets.  There is NO byte-partial buffering.  The X driver appears
130  *	  to be compatible with these restrictions.
131  *
132  * figure out the bootstrapping and commands.
133  *
134  * Unable to locate any datasheet for the device.
135  *
136  *				    FEATURES
137  *
138  * Currently no features.  Only one finger is supported by this attachment
139  * for now and I haven't written any de-jitter and finger-transfer code.
140  * This is good enough for moving and resizing windows (given big enough
141  * widgets), and hitting browser buttons and hotlinks.
142  *
143  * Currently no scrolling control or other features.  We would need to
144  * basically implement either the linux general input even infrastructure
145  * which is a LOT of code, or a mouse emulator to handle scrolling emulation.
146  */
147 #include <sys/kernel.h>
148 #include <sys/param.h>
149 #include <sys/systm.h>
150 #include <sys/device.h>
151 #include <sys/module.h>
152 #include <sys/bus.h>
153 #include <sys/conf.h>
154 #include <sys/uio.h>
155 #include <sys/fcntl.h>
156 /*#include <sys/input.h>*/
157 #include <sys/vnode.h>
158 #include <sys/sysctl.h>
159 #include <sys/event.h>
160 #include <sys/devfs.h>
161 
162 #include <bus/smbus/smbconf.h>
163 #include <bus/smbus/smbus.h>
164 #include "atmel_mxt.h"
165 
166 #include "smbus_if.h"
167 #include "bus_if.h"
168 #include "device_if.h"
169 
170 struct elopacket {
171 	uint8_t	sync;
172 	uint8_t	cmd;
173 	uint8_t	byte2;
174 	uint8_t	byte3;
175 	uint8_t	byte4;
176 	uint8_t	byte5;
177 	uint8_t	byte6;
178 	uint8_t	byte7;
179 	uint8_t	byte8;
180 	uint8_t	csum;
181 } __packed;
182 
183 typedef struct elopacket elopacket_t;
184 
185 typedef struct atmel_track {
186 	uint16_t x;
187 	uint16_t y;
188 	uint16_t pressure;
189 	int	status;
190 	int	report;		/* what we have to report */
191 } atmel_track_t;
192 
193 #define ATMEL_TRACK_RELEASED		0
194 #define ATMEL_TRACK_PRESSED		1
195 
196 #define ATMEL_REPORT_PRESS	0x0001
197 #define ATMEL_REPORT_MOVE	0x0002
198 #define ATMEL_REPORT_RELEASE	0x0004
199 
200 #define ATMEL_MAXTRACK		10
201 
202 struct atmel_mxt_softc {
203 	device_t dev;
204 	int	count;			/* >0 if device opened */
205 	int	unit;
206 	int	addr;
207 	cdev_t	devnode;
208 	struct kqinfo kqinfo;
209 	struct lock lk;
210 
211 	int	poll_flags;
212 	thread_t poll_td;
213 
214 	/*
215 	 * Hardware state
216 	 */
217 	struct mxt_rollup	core;
218 	struct mxt_object	*msgprocobj;
219 	struct mxt_object	*cmdprocobj;
220 
221 	/*
222 	 * Capabilities
223 	 */
224 	short	cap_resx;
225 	short	cap_resy;
226 
227 	/*
228 	 * Emulation
229 	 */
230 	atmel_track_t track[ATMEL_MAXTRACK];
231 	int	tracking;
232 	int	track_fingers;
233 
234 	elopacket_t pend_rep;		/* pending reply to command */
235 	int	pend_ack;		/* pending reply mode */
236 
237 	int	last_active_tick;
238 	int	last_calibrate_tick;
239 	int	data_signal;		/* something ready to read */
240 	int	blocked;		/* someone is blocking */
241 	int	reporting_mode;
242 	int	sample_rate;		/* samples/sec */
243 	int	poll_ticks;
244 };
245 
246 typedef struct atmel_mxt_softc atmel_mxt_softc_t;
247 
248 #define ATMEL_POLL_SHUTDOWN	0x0001
249 
250 #define PEND_ACK_NONE		0	/* no reply to command pending */
251 #define PEND_ACK_RESPOND	1	/* reply w/response and ack */
252 #define PEND_ACK_ACK		2	/* reply w/ack only */
253 
254 #define REPORT_NONE		0x0000
255 #define REPORT_ALL		0x0001
256 
257 /*
258  * Async debug variable commands are executed by the poller and will
259  * auto-clear.
260  */
261 static int atmel_mxt_idle_freq = 1;
262 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_idle_freq, CTLFLAG_RW,
263 		&atmel_mxt_idle_freq, 0, "");
264 static int atmel_mxt_slow_freq = 20;
265 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_slow_freq, CTLFLAG_RW,
266 		&atmel_mxt_slow_freq, 0, "");
267 static int atmel_mxt_norm_freq = 100;
268 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_norm_freq, CTLFLAG_RW,
269 		&atmel_mxt_norm_freq, 0, "");
270 static int atmel_mxt_minpressure = 16;
271 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_minpressure, CTLFLAG_RW,
272 		&atmel_mxt_minpressure, 0, "");
273 static int atmel_mxt_reset = 0;
274 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_reset, CTLFLAG_RW,
275 		&atmel_mxt_reset, 0, "");
276 
277 /*
278  * Run a calibration command every N seconds only when idle.  0 to disable.
279  * Default every 30 seconds.
280  */
281 static int atmel_mxt_autocalibrate = 30;
282 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_autocalibrate, CTLFLAG_RW,
283 		&atmel_mxt_autocalibrate, 0, "");
284 
285 /*
286  * run a calibration on module startup.
287  */
288 static int atmel_mxt_debug = 0;
289 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_debug, CTLFLAG_RW,
290 		&atmel_mxt_debug, 0, "");
291 
292 static void atmel_mxt_poll_thread(void *arg);
293 static void atmel_find_active_state(atmel_mxt_softc_t *sc);
294 static int atmel_mxt_raw_input(atmel_mxt_softc_t *sc, mxt_message_t *msg);
295 static struct mxt_object *mxt_findobject(struct mxt_rollup *core, int type);
296 static int mxt_read_reg(atmel_mxt_softc_t *sc, uint16_t reg,
297 			void *rbuf, int bytes);
298 static int mxt_write_reg_buf(atmel_mxt_softc_t *sc, uint16_t reg,
299 			void *xbuf, int bytes);
300 static int mxt_write_reg(atmel_mxt_softc_t *sc, uint16_t reg, uint8_t val);
301 static int mxt_read_object(atmel_mxt_softc_t *sc, struct mxt_object *obj,
302 			void *rbuf, int rbytes);
303 static int mxt_write_object_off(atmel_mxt_softc_t *sc, struct mxt_object *obj,
304 			int offset, uint8_t val);
305 static void atmel_reset_device(atmel_mxt_softc_t *sc);
306 
307 static
308 const char *
309 msgflagsstr(uint8_t flags)
310 {
311 	static char buf[9];
312 
313 	buf[0] = (flags & MXT_MSGF_DETECT) ? 'D' : '.';
314 	buf[1] = (flags & MXT_MSGF_PRESS) ? 'P' : '.';
315 	buf[2] = (flags & MXT_MSGF_RELEASE) ? 'R' : '.';
316 	buf[3] = (flags & MXT_MSGF_MOVE) ? 'M' : '.';
317 	buf[4] = (flags & MXT_MSGF_VECTOR) ? 'V' : '.';
318 	buf[5] = (flags & MXT_MSGF_AMP) ? 'A' : '.';
319 	buf[6] = (flags & MXT_MSGF_SUPPRESS) ? 'S' : '.';
320 	buf[7] = (flags & MXT_MSGF_UNGRIP) ? 'U' : '.';
321 
322 	return buf;
323 }
324 
325 static
326 void
327 atmel_mxt_lock(atmel_mxt_softc_t *sc)
328 {
329 	lockmgr(&sc->lk, LK_EXCLUSIVE);
330 }
331 
332 static
333 void
334 atmel_mxt_unlock(atmel_mxt_softc_t *sc)
335 {
336 	lockmgr(&sc->lk, LK_RELEASE);
337 }
338 
339 /*
340  * Notify if possible receive data ready.  Must be called
341  * without the lock held to avoid deadlocking in kqueue.
342  */
343 static
344 void
345 atmel_mxt_notify(atmel_mxt_softc_t *sc)
346 {
347 	if (sc->data_signal) {
348 		KNOTE(&sc->kqinfo.ki_note, 0);
349 		atmel_mxt_lock(sc);
350 		if (sc->blocked) {
351 			sc->blocked = 0;
352 			wakeup(&sc->blocked);
353 		}
354 		atmel_mxt_unlock(sc);
355 	}
356 }
357 
358 /*
359  * Initialize the device
360  */
361 static
362 int
363 init_device(atmel_mxt_softc_t *sc, int probe)
364 {
365 	int blksize;
366 	int totsize;
367 	uint32_t crc;
368 
369 	if (mxt_read_reg(sc, 0, &sc->core.info, sizeof(sc->core.info))) {
370 		device_printf(sc->dev, "init_device read-reg failed\n");
371 		return ENXIO;
372 	}
373 	sc->core.nobjs = sc->core.info.num_objects;
374 	if (!probe) {
375 		device_printf(sc->dev,
376 			      "%d configuration objects\n",
377 			      sc->core.info.num_objects);
378 	}
379 	if (sc->core.nobjs < 0 || sc->core.nobjs > 1024) {
380 		device_printf(sc->dev,
381 			      "init_device nobjs (%d) out of bounds\n",
382 			      sc->core.nobjs);
383 		return ENXIO;
384 	}
385 	blksize = sizeof(sc->core.info) +
386 		  sc->core.nobjs * sizeof(struct mxt_object);
387 	totsize = blksize + sizeof(struct mxt_raw_crc);
388 
389 	sc->core.buf = kmalloc(totsize, M_DEVBUF, M_WAITOK | M_ZERO);
390 	if (mxt_read_reg(sc, 0, sc->core.buf, totsize)) {
391 		device_printf(sc->dev,
392 			      "init_device cannot read configuration space\n");
393 		goto done;
394 	}
395 	kprintf("COREBUF %p %d\n", sc->core.buf, blksize);
396 	crc = obp_convert_crc((void *)((uint8_t *)sc->core.buf + blksize));
397 	if (obp_crc24(sc->core.buf, blksize) != crc) {
398 		device_printf(sc->dev,
399 			      "init_device: configuration space "
400 			      "crc mismatch %08x/%08x\n",
401 			      crc, obp_crc24(sc->core.buf, blksize));
402 		/*goto done;*/
403 	}
404 	{
405 		int i;
406 
407 		kprintf("info:   ");
408 		for (i = 0; i < sizeof(sc->core.info); ++i)
409 			kprintf(" %02x", sc->core.buf[i]);
410 		kprintf("\nconfig: ");
411 		while (i < blksize) {
412 			kprintf(" %02x", sc->core.buf[i]);
413 			++i;
414 		}
415 		kprintf("\n");
416 	}
417 	sc->core.objs = (void *)((uint8_t *)sc->core.buf +
418 				 sizeof(sc->core.info));
419 	sc->msgprocobj = mxt_findobject(&sc->core, MXT_GEN_MESSAGEPROCESSOR);
420 	sc->cmdprocobj = mxt_findobject(&sc->core, MXT_GEN_COMMANDPROCESSOR);
421 	if (sc->msgprocobj == NULL) {
422 		device_printf(sc->dev,
423 			      "init_device: cannot find msgproc config\n");
424 		goto done;
425 	}
426 
427 done:
428 	if (sc->msgprocobj == NULL) {
429 		if (sc->core.buf) {
430 			kfree(sc->core.buf, M_DEVBUF);
431 			sc->core.buf = NULL;
432 		}
433 		return ENXIO;
434 	} else {
435 		if (probe) {
436 			kfree(sc->core.buf, M_DEVBUF);
437 			sc->core.buf = NULL;
438 		} else {
439 			atmel_reset_device(sc);
440 		}
441 		return 0;
442 	}
443 }
444 
445 /*
446  * Device infrastructure
447  */
448 #define ATMEL_SOFTC(unit) \
449 	((atmel_mxt_softc_t *)devclass_get_softc(atmel_mxt_devclass, (unit)))
450 
451 static void atmel_mxt_identify(driver_t *driver, device_t parent);
452 static int atmel_mxt_probe(device_t);
453 static int atmel_mxt_attach(device_t);
454 static int atmel_mxt_detach(device_t);
455 
456 static devclass_t atmel_mxt_devclass;
457 
458 static device_method_t atmel_mxt_methods[] = {
459 	/* device interface */
460 	DEVMETHOD(device_identify,	atmel_mxt_identify),
461 	DEVMETHOD(device_probe,		atmel_mxt_probe),
462 	DEVMETHOD(device_attach,	atmel_mxt_attach),
463 	DEVMETHOD(device_detach,	atmel_mxt_detach),
464 
465 #if 0
466 	/* smbus interface */
467 	DEVMETHOD(smbus_intr,		smbus_generic_intr),
468 #endif
469 
470 	DEVMETHOD_END
471 };
472 
473 static driver_t atmel_mxt_driver = {
474 	"atmel_mxt",
475 	atmel_mxt_methods,
476 	sizeof(atmel_mxt_softc_t),
477 };
478 
479 static	d_open_t	atmel_mxtopen;
480 static	d_close_t	atmel_mxtclose;
481 static	d_ioctl_t	atmel_mxtioctl;
482 static	d_read_t	atmel_mxtread;
483 static	d_write_t	atmel_mxtwrite;
484 static	d_kqfilter_t	atmel_mxtkqfilter;
485 
486 static struct dev_ops atmel_mxt_ops = {
487 	{ "atmel_mxt", 0, 0 },
488 	.d_open =	atmel_mxtopen,
489 	.d_close =	atmel_mxtclose,
490 	.d_ioctl =	atmel_mxtioctl,
491 	.d_read =	atmel_mxtread,
492 	.d_write =	atmel_mxtwrite,
493 	.d_kqfilter =	atmel_mxtkqfilter,
494 };
495 
496 static void
497 atmel_mxt_identify(driver_t *driver, device_t parent)
498 {
499 	if (device_find_child(parent, "atmel_mxt", -1) == NULL)
500 		BUS_ADD_CHILD(parent, parent, 0, "atmel_mxt", -1);
501 }
502 
503 static int
504 atmel_mxt_probe(device_t dev)
505 {
506 	atmel_mxt_softc_t sc;
507 	int error;
508 
509 	bzero(&sc, sizeof(sc));
510 	sc.dev = dev;
511 	sc.unit = device_get_unit(dev);
512 
513 	/*
514 	 * Only match against specific addresses to avoid blowing up
515 	 * other I2C devices (?).  At least for now.
516 	 *
517 	 * 0x400 (from smbus) - means specific device address probe,
518 	 *			rather than generic.
519 	 *
520 	 * 0x4A - cypress trackpad on the acer c720.
521 	 */
522 	if ((sc.unit & 0x04FF) != (0x0400 | 0x04A))
523 		return ENXIO;
524 	sc.addr = sc.unit & 0x3FF;
525 	error = init_device(&sc, 1);
526 	if (error)
527 		return ENXIO;
528 
529 	device_set_desc(dev, "Atmel MXT TouchScreen");
530 
531 	return (BUS_PROBE_VENDOR);
532 }
533 
534 static int
535 atmel_mxt_attach(device_t dev)
536 {
537 	atmel_mxt_softc_t *sc;
538 
539 	sc = (atmel_mxt_softc_t *)device_get_softc(dev);
540 	if (!sc)
541 		return ENOMEM;
542 
543 	bzero(sc, sizeof(*sc));
544 
545 	lockinit(&sc->lk, "atmel_mxt", 0, 0);
546 	sc->reporting_mode = 1;
547 
548 	sc->dev = dev;
549 	sc->unit = device_get_unit(dev);
550 	if ((sc->unit & 0x04FF) != (0x0400 | 0x04A))
551 		return ENXIO;
552 	sc->addr = sc->unit & 0x3FF;
553 	sc->last_active_tick = ticks;
554 	sc->last_calibrate_tick = ticks - atmel_mxt_autocalibrate * hz;
555 
556 	if (init_device(sc, 0))
557 		return ENXIO;
558 
559 	if (sc->unit & 0x0400) {
560 		sc->devnode = make_dev(&atmel_mxt_ops, sc->unit,
561 				UID_ROOT, GID_WHEEL, 0600,
562 				"atmel%d-%02x",
563 				sc->unit >> 11, sc->unit & 1023);
564 	} else {
565 		sc->devnode = make_dev(&atmel_mxt_ops, sc->unit,
566 				UID_ROOT, GID_WHEEL, 0600, "atmel%d", sc->unit);
567 	}
568 	device_printf(dev, "atmel mxt touchscreen driver attached\n");
569 	/* device_printf(dev, "...."); */
570 
571 	/*
572 	 * Start the polling thread.
573 	 */
574 	lwkt_create(atmel_mxt_poll_thread, sc,
575 		    &sc->poll_td, NULL, 0, -1, "atmel_mxt-poll");
576 
577 	return (0);
578 }
579 
580 static int
581 atmel_mxt_detach(device_t dev)
582 {
583 	atmel_mxt_softc_t *sc;
584 
585 	sc = (atmel_mxt_softc_t *)device_get_softc(dev);
586 
587 	/*
588 	 * Cleanup our poller thread
589 	 */
590 	atomic_set_int(&sc->poll_flags, ATMEL_POLL_SHUTDOWN);
591 	while (sc->poll_td) {
592 		wakeup(&sc->poll_flags);
593 		tsleep(&sc->poll_td, 0, "atmel_mxtdet", hz);
594 	}
595 
596 	if (sc->devnode)
597 		dev_ops_remove_minor(&atmel_mxt_ops, device_get_unit(dev));
598 	if (sc->devnode)
599 		devfs_assume_knotes(sc->devnode, &sc->kqinfo);
600 	if (sc->core.buf) {
601 		kfree(sc->core.buf, M_DEVBUF);
602 		sc->core.buf = NULL;
603 	}
604 	sc->msgprocobj = NULL;
605 	sc->cmdprocobj = NULL;
606 
607 	return (0);
608 }
609 
610 /*
611  * USER DEVICE I/O FUNCTIONS
612  */
613 static int
614 atmel_mxtopen (struct dev_open_args *ap)
615 {
616 	cdev_t dev = ap->a_head.a_dev;
617 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
618 
619 	if (sc == NULL)
620 		return (ENXIO);
621 
622 	if (sc->count != 0)
623 		return (EBUSY);
624 
625 	sc->count++;
626 
627 	return (0);
628 }
629 
630 static int
631 atmel_mxtclose(struct dev_close_args *ap)
632 {
633 	cdev_t dev = ap->a_head.a_dev;
634 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
635 
636 	if (sc == NULL)
637 		return (ENXIO);
638 
639 	if (sc->count == 0) {
640 		/* This is not supposed to happen. */
641 		return (0);
642 	}
643 
644 	if (sc->count-- == 0) {
645 		sc->reporting_mode = 0;
646 	}
647 
648 	return (0);
649 }
650 
651 static int
652 atmel_mxtread(struct dev_read_args *ap)
653 {
654 	cdev_t dev = ap->a_head.a_dev;
655 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
656 	int error;
657 	struct uio *uio = ap->a_uio;
658 	int ioflag = ap->a_ioflag;
659 	size_t n;
660 	elopacket_t pkt;
661 	atmel_track_t *track;
662 
663 	/*
664 	 * Load next ready event, block if necessary.
665 	 */
666 	atmel_mxt_lock(sc);
667 	for (;;) {
668 		error = 0;
669 
670 		switch(sc->pend_ack) {
671 		case PEND_ACK_NONE:
672 			if (sc->tracking && sc->track[sc->tracking].report) {
673 				/*
674 				 * Report ready
675 				 */
676 				track = &sc->track[sc->tracking];
677 				bzero(&pkt, sizeof(pkt));
678 				pkt.cmd = 'T';
679 				if (track->report & ATMEL_REPORT_PRESS) {
680 					pkt.byte2 |= 0x01;
681 					track->report &= ~ATMEL_REPORT_PRESS;
682 				} else if (track->report & ATMEL_REPORT_MOVE) {
683 					pkt.byte2 |= 0x02;
684 					track->report &= ~ATMEL_REPORT_MOVE;
685 				} else if (track->report &
686 					   ATMEL_REPORT_RELEASE) {
687 					pkt.byte2 |= 0x04;
688 					track->report &= ~ATMEL_REPORT_RELEASE;
689 				}
690 				pkt.byte3 = track->x & 0xFF;
691 				pkt.byte4 = track->x >> 8;
692 				pkt.byte5 = track->y & 0xFF;
693 				pkt.byte6 = track->y >> 8;
694 				pkt.byte7 = track->pressure & 0xFF;
695 				pkt.byte8 = track->pressure >> 8;
696 			} else if (ioflag & IO_NDELAY) {
697 				/*
698 				 * Non-blocking, nothing ready
699 				 */
700 				error = EWOULDBLOCK;
701 			} else {
702 				/*
703 				 * Blocking, nothing ready
704 				 */
705 				sc->data_signal = 0;
706 				sc->blocked = 1;
707 				error = lksleep(&sc->blocked, &sc->lk,
708 						PCATCH, "atmelw", 0);
709 				if (error == 0)
710 					continue;
711 			}
712 			break;
713 		case PEND_ACK_RESPOND:
714 			pkt = sc->pend_rep;
715 			sc->pend_ack = PEND_ACK_ACK;
716 			break;
717 		case PEND_ACK_ACK:
718 			bzero(&pkt, sizeof(pkt));
719 			pkt.cmd = 'A';
720 			sc->pend_ack = PEND_ACK_NONE;
721 			break;
722 		}
723 		atmel_find_active_state(sc);
724 		break;
725 	}
726 	atmel_mxt_unlock(sc);
727 
728 	/*
729 	 * If no error we can return the event loaded into pkt.
730 	 */
731 	if (error == 0) {
732 		uint8_t csum = 0xAA;
733 		int i;
734 
735 		pkt.sync = 'U';
736 		for (i = 0; i < sizeof(pkt) - 1; ++i)
737 			csum += ((uint8_t *)&pkt)[i];
738 		pkt.csum = csum;
739 		n = uio->uio_resid;
740 		if (n > sizeof(pkt))
741 			n = sizeof(pkt);
742 		error = uiomove((void *)&pkt, n, uio);
743 	}
744 
745 	return error;
746 }
747 
748 static int
749 atmel_mxtwrite(struct dev_write_args *ap)
750 {
751 	cdev_t dev = ap->a_head.a_dev;
752 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
753 	struct uio *uio = ap->a_uio;
754 	elopacket_t pkt;
755 	int error;
756 	size_t n;
757 
758 	error = 0;
759 
760 	while (uio->uio_resid) {
761 		bzero(&pkt, sizeof(pkt));
762 		n = uio->uio_resid;
763 		if (n > sizeof(pkt))
764 			n = sizeof(pkt);
765 		error = uiomove((void *)&pkt, n, uio);
766 		if (error)
767 			break;
768 		atmel_mxt_lock(sc);
769 		switch(pkt.cmd) {
770 		case 'i':
771 			/*
772 			 * ELO_ID request id
773 			 */
774 			bzero(&sc->pend_rep, sizeof(sc->pend_rep));
775 			sc->pend_rep.cmd = 'I';
776 			sc->pend_ack = PEND_ACK_RESPOND;
777 			break;
778 		case 'o':
779 			/*
780 			 * ELO_OWNER request owner
781 			 */
782 			bzero(&sc->pend_rep, sizeof(sc->pend_rep));
783 			sc->pend_rep.cmd = 'O';
784 			sc->pend_ack = PEND_ACK_RESPOND;
785 			break;
786 		case 'm':
787 			/*
788 			 * ELO_MODE control packet
789 			 */
790 			sc->pend_ack = PEND_ACK_ACK;
791 			break;
792 		case 'r':
793 			/*
794 			 * ELO_REPORT control packet
795 			 */
796 			sc->pend_ack = PEND_ACK_ACK;
797 			break;
798 		}
799 		atmel_mxt_unlock(sc);
800 	}
801 	return error;
802 }
803 
804 static void atmel_mxt_filt_detach(struct knote *);
805 static int atmel_mxt_filt(struct knote *, long);
806 
807 static struct filterops atmel_mxt_filtops =
808         { FILTEROP_ISFD, NULL, atmel_mxt_filt_detach, atmel_mxt_filt };
809 
810 static int
811 atmel_mxtkqfilter(struct dev_kqfilter_args *ap)
812 {
813 	cdev_t dev = ap->a_head.a_dev;
814 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
815 	struct knote *kn = ap->a_kn;
816 	struct klist *klist;
817 
818 	switch(kn->kn_filter) {
819 	case EVFILT_READ:
820 		kn->kn_fop = &atmel_mxt_filtops;
821 		kn->kn_hook = (void *)sc;
822 		ap->a_result = 0;
823 		break;
824 	default:
825 		ap->a_result = EOPNOTSUPP;
826 		return (0);
827 	}
828 	klist = &sc->kqinfo.ki_note;
829 	knote_insert(klist, kn);
830 
831 	return (0);
832 }
833 
834 static void
835 atmel_mxt_filt_detach(struct knote *kn)
836 {
837 	atmel_mxt_softc_t *sc = (atmel_mxt_softc_t *)kn->kn_hook;
838 	struct klist *klist;
839 
840 	klist = &sc->kqinfo.ki_note;
841 	knote_remove(klist, kn);
842 }
843 
844 static int
845 atmel_mxt_filt(struct knote *kn, long hint)
846 {
847 	atmel_mxt_softc_t *sc = (atmel_mxt_softc_t *)kn->kn_hook;
848 	int ready;
849 
850 	atmel_mxt_lock(sc);
851 	if (sc->data_signal)
852 		ready = 1;
853 	else
854 		ready = 0;
855 	atmel_mxt_unlock(sc);
856 
857 	return (ready);
858 }
859 
860 static int
861 atmel_mxtioctl(struct dev_ioctl_args *ap)
862 {
863 	cdev_t dev = ap->a_head.a_dev;
864 	device_t bus;		/* smbbus */
865 	/*struct atmel_mxtcmd *s = (struct atmel_mxtcmd *)ap->a_data;*/
866 	void *s = NULL;
867 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
868 	int error;
869 
870 	if (sc == NULL)
871 		return (ENXIO);
872 	if (s == NULL)
873 		return (EINVAL);
874 
875 	/*
876 	 * NOTE: smbus_*() functions automatically recurse the parent to
877 	 *	 get to the actual device driver.
878 	 */
879 	bus = device_get_parent(sc->dev);	/* smbus */
880 
881 	/* Allocate the bus. */
882 	if ((error = smbus_request_bus(bus, sc->dev,
883 			(ap->a_fflag & O_NONBLOCK) ?
884 			SMB_DONTWAIT : (SMB_WAIT | SMB_INTR))))
885 		return (error);
886 
887 	switch (ap->a_cmd) {
888 	default:
889 #if 0
890 		error = inputev_ioctl(&sc->iev, ap->a_cmd, ap->a_data);
891 #endif
892 		error = ENOTTY;
893 		break;
894 	}
895 
896 	smbus_release_bus(bus, sc->dev);
897 
898 	return (error);
899 }
900 
901 /*
902  * MAJOR SUPPORT FUNCTIONS
903  */
904 static
905 void
906 atmel_mxt_poll_thread(void *arg)
907 {
908 	atmel_mxt_softc_t *sc = arg;
909 	int error;
910 	int freq = atmel_mxt_norm_freq;
911 	int isidle = 0;
912 
913 	while ((sc->poll_flags & ATMEL_POLL_SHUTDOWN) == 0) {
914 		if (sc->msgprocobj)
915 			error = 0;
916 		else
917 			error = ENXIO;
918 		if (error == 0) {
919 			mxt_message_t msg;
920 
921 			error = mxt_read_object(sc, sc->msgprocobj,
922 					    &msg, sizeof(msg));
923 			if (error == 0)
924 				isidle = atmel_mxt_raw_input(sc, &msg);
925 			else
926 				isidle = 1;
927 		}
928 
929 		/*
930 		 * don't let the last_active_tick or last_calibrate_tick
931 		 * delta calculation overflow.
932 		 */
933 		if ((ticks - sc->last_active_tick) > 1000 * hz)
934 			sc->last_active_tick = ticks - 1000 * hz;
935 		if ((ticks - sc->last_calibrate_tick) > 1000 * hz)
936 			sc->last_calibrate_tick = ticks - 1000 * hz;
937 
938 		/*
939 		 * Reset if requested
940 		 */
941 		if (atmel_mxt_reset) {
942 			atmel_mxt_reset = 0;
943 			atmel_reset_device(sc);
944 		}
945 
946 		/*
947 		 * Automatically calibrate when the touchpad has been
948 		 * idle atmel_mxt_autocalibrate seconds, and recalibrate
949 		 * on the same interval while it remains idle.
950 		 *
951 		 * If we don't do this the touchscreen can get really out
952 		 * of whack over time and basically stop functioning properly.
953 		 * It's unclear why the device does not do this automatically.
954 		 *
955 		 * Response occurs in the message stream (which we just
956 		 * ignore).
957 		 */
958 		if (sc->cmdprocobj && atmel_mxt_autocalibrate &&
959 		    ((ticks - sc->last_calibrate_tick) >
960 		     atmel_mxt_autocalibrate * hz) &&
961 		    ((ticks - sc->last_active_tick) >
962 		     atmel_mxt_autocalibrate * hz)) {
963 			sc->last_calibrate_tick = ticks;
964 			mxt_write_object_off(sc, sc->cmdprocobj,
965 					 MXT_CMDPROC_CALIBRATE_OFF, 1);
966 		}
967 		tsleep(&sc->poll_flags, 0, "atmpol", (hz + freq - 1) / freq);
968 		++sc->poll_ticks;
969 		if (sc->count == 0)
970 			freq = atmel_mxt_idle_freq;
971 		else if (isidle)
972 			freq = atmel_mxt_slow_freq;
973 		else
974 			freq = atmel_mxt_norm_freq;
975 	}
976 	sc->poll_td = NULL;
977 	wakeup(&sc->poll_td);
978 }
979 
980 static
981 void
982 atmel_reset_device(atmel_mxt_softc_t *sc)
983 {
984 	int dummy;
985 	mxt_write_object_off(sc, sc->cmdprocobj, MXT_CMDPROC_RESET_OFF, 1);
986 	tsleep(&dummy, 0, "atmel_reset", hz * 2);
987 }
988 
989 /*
990  * Calculate currently active state, if any
991  */
992 static
993 void
994 atmel_find_active_state(atmel_mxt_softc_t *sc)
995 {
996 	atmel_track_t *track;
997 	int i;
998 
999 	track = &sc->track[sc->tracking];
1000 	if (track->report == 0) {
1001 		for (i = 0; i < ATMEL_MAXTRACK; ++i) {
1002 			track = &sc->track[i];
1003 			if (track->report) {
1004 				sc->tracking = i;
1005 				break;
1006 			}
1007 		}
1008 	}
1009 	if (track->report == 0 && sc->pend_ack == PEND_ACK_NONE) {
1010 		sc->data_signal = 0;
1011 	} else {
1012 		sc->data_signal = 1;
1013 	}
1014 }
1015 
1016 /*
1017  * Return non-zero if we are idle
1018  */
1019 static
1020 int
1021 atmel_mxt_raw_input(atmel_mxt_softc_t *sc, mxt_message_t *msg)
1022 {
1023 	atmel_track_t *track;
1024 	int donotify = 0;
1025 
1026 	if (atmel_mxt_debug) {
1027 		kprintf("track=%02x f=%s x=%-4d y=%-4d p=%d amp=%d\n",
1028 			msg->any.reportid,
1029 			msgflagsstr(msg->touch.flags),
1030 			(msg->touch.pos[0] << 4) |
1031 				((msg->touch.pos[2] >> 4) & 0x0F),
1032 			(msg->touch.pos[1] << 4) |
1033 				((msg->touch.pos[2]) & 0x0F),
1034 			msg->touch.area,
1035 			msg->touch.amplitude);
1036 	}
1037 	atmel_mxt_lock(sc);
1038 
1039 	/*
1040 	 * If message buffer is empty and no fingers are currently pressed
1041 	 * return idle, else we are not idle.
1042 	 */
1043 	if (msg->any.reportid == 0xFF)
1044 		goto done;
1045 
1046 	/*
1047 	 * Process message buffer.  For now ignore any messages with
1048 	 * reportids that we do not understand.
1049 	 *
1050 	 * note: reportid==1  typicallk acknowledges calibrations (?)
1051 	 */
1052 	if (msg->any.reportid < 3 || msg->any.reportid >= ATMEL_MAXTRACK)
1053 		goto done;
1054 
1055 	sc->last_active_tick = ticks;
1056 
1057 	track = &sc->track[msg->any.reportid];
1058 	track->x = (msg->touch.pos[0] << 4) |
1059 		   ((msg->touch.pos[2] >> 4) & 0x0F);
1060 	track->y = (msg->touch.pos[1] << 4) |
1061 		   (msg->touch.pos[2] & 0x0F);
1062 	track->pressure = msg->touch.amplitude;
1063 
1064 	track->x = track->x * 3000 / 1361;
1065 	track->y = track->y * 3000 / 3064;
1066 
1067 	if (msg->touch.flags & MXT_MSGF_DETECT) {
1068 		track->status = ATMEL_TRACK_PRESSED;
1069 		if (msg->touch.flags & MXT_MSGF_PRESS) {
1070 			track->report |= ATMEL_REPORT_PRESS;
1071 		}
1072 		if (msg->touch.flags & MXT_MSGF_MOVE) {
1073 			track->report |= ATMEL_REPORT_MOVE;
1074 		}
1075 	} else {
1076 		track->status = ATMEL_TRACK_RELEASED;
1077 		track->report |= ATMEL_REPORT_RELEASE;
1078 	}
1079 	atmel_find_active_state(sc);
1080 	donotify = 1;
1081 done:
1082 	atmel_mxt_unlock(sc);
1083 	if (donotify)
1084 		atmel_mxt_notify(sc);
1085 	if (sc->track_fingers)
1086 		return 0;
1087 	else
1088 		return 1;
1089 }
1090 
1091 /*
1092  * Support functions
1093  */
1094 static
1095 struct mxt_object *
1096 mxt_findobject(struct mxt_rollup *core, int type)
1097 {
1098 	int i;
1099 
1100 	for (i = 0; i < core->nobjs; ++i) {
1101 		if (core->objs[i].type == type)
1102 			return(&core->objs[i]);
1103 	}
1104 	return NULL;
1105 }
1106 
1107 static int
1108 mxt_read_reg(atmel_mxt_softc_t *sc, uint16_t reg, void *rbuf, int bytes)
1109 {
1110 	uint8_t wreg[2];
1111 	device_t bus;
1112 	int error;
1113 	int rbytes;
1114 
1115 	wreg[0] = reg & 255;
1116 	wreg[1] = reg >> 8;
1117 
1118 	bus = device_get_parent(sc->dev);
1119 	if ((error = smbus_request_bus(bus, sc->dev, SMB_WAIT | SMB_INTR)) != 0)
1120 		return error;
1121 	error = smbus_trans(bus, sc->addr, 0,
1122 			    SMB_TRANS_NOCNT |
1123 			    SMB_TRANS_NOCMD |
1124 			    SMB_TRANS_7BIT,
1125 			    wreg, 2,
1126 			    rbuf, bytes, &rbytes);
1127 	smbus_release_bus(bus, sc->dev);
1128 
1129 	if (bytes != rbytes) {
1130 		device_printf(sc->dev,
1131 			      "smbus_trans reg %d short read %d/%d\n",
1132 			      reg, bytes, rbytes);
1133 		error = EINVAL;
1134 	}
1135 
1136 	return error;
1137 }
1138 
1139 static int
1140 mxt_write_reg_buf(atmel_mxt_softc_t *sc, uint16_t reg, void *xbuf, int bytes)
1141 {
1142 	uint8_t wbuf[256];
1143 	device_t bus;
1144 	int error;
1145 
1146 	KKASSERT(bytes < sizeof(wbuf) - 2);
1147 	wbuf[0] = reg & 255;
1148 	wbuf[1] = reg >> 8;
1149 	bcopy(xbuf, wbuf + 2, bytes);
1150 
1151 	bus = device_get_parent(sc->dev);
1152 	if ((error = smbus_request_bus(bus, sc->dev, SMB_WAIT | SMB_INTR)) != 0)
1153 		return error;
1154 	error = smbus_trans(bus, sc->addr, 0,
1155 			    SMB_TRANS_NOCNT |
1156 			    SMB_TRANS_NOCMD |
1157 			    SMB_TRANS_7BIT,
1158 			    wbuf, bytes + 2,
1159 			    NULL, 0, NULL);
1160 	smbus_release_bus(bus, sc->dev);
1161 	return error;
1162 }
1163 
1164 static int
1165 mxt_write_reg(atmel_mxt_softc_t *sc, uint16_t reg, uint8_t val)
1166 {
1167 	return mxt_write_reg_buf(sc, reg, &val, 1);
1168 }
1169 
1170 static int
1171 mxt_read_object(atmel_mxt_softc_t *sc, struct mxt_object *obj,
1172 	        void *rbuf, int rbytes)
1173 {
1174 	uint16_t reg = obj->start_pos_lsb + (obj->start_pos_msb << 8);
1175 	int bytes = obj->size_minus_one + 1;
1176 
1177 	if (bytes > rbytes)
1178 		bytes = rbytes;
1179 	return mxt_read_reg(sc, reg, rbuf, bytes);
1180 }
1181 
1182 static int
1183 mxt_write_object_off(atmel_mxt_softc_t *sc, struct mxt_object *obj,
1184 		 int offset, uint8_t val)
1185 {
1186 	uint16_t reg = obj->start_pos_lsb + (obj->start_pos_msb << 8);
1187 
1188 	reg += offset;
1189 	return mxt_write_reg(sc, reg, val);
1190 }
1191 
1192 DRIVER_MODULE(atmel_mxt, smbus, atmel_mxt_driver, atmel_mxt_devclass,
1193 	      NULL, NULL);
1194 MODULE_DEPEND(atmel_mxt, smbus, SMBUS_MINVER, SMBUS_PREFVER, SMBUS_MAXVER);
1195 MODULE_VERSION(atmel_mxt, 1);
1196