xref: /dragonfly/sys/dev/smbus/atmel_mxt/atmel_mxt.c (revision 5071e670)
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/vnode.h>
157 #include <sys/sysctl.h>
158 #include <sys/event.h>
159 #include <sys/devfs.h>
160 
161 #include <bus/smbus/smbconf.h>
162 #include <bus/smbus/smbus.h>
163 #include "atmel_mxt.h"
164 
165 #include "smbus_if.h"
166 #include "bus_if.h"
167 #include "device_if.h"
168 
169 struct elopacket {
170 	uint8_t	sync;
171 	uint8_t	cmd;
172 	uint8_t	byte2;
173 	uint8_t	byte3;
174 	uint8_t	byte4;
175 	uint8_t	byte5;
176 	uint8_t	byte6;
177 	uint8_t	byte7;
178 	uint8_t	byte8;
179 	uint8_t	csum;
180 } __packed;
181 
182 typedef struct elopacket elopacket_t;
183 
184 typedef struct atmel_track {
185 	uint16_t x;
186 	uint16_t y;
187 	uint16_t pressure;
188 	int	status;
189 	int	report;		/* what we have to report */
190 } atmel_track_t;
191 
192 #define ATMEL_TRACK_RELEASED		0
193 #define ATMEL_TRACK_PRESSED		1
194 
195 #define ATMEL_REPORT_PRESS	0x0001
196 #define ATMEL_REPORT_MOVE	0x0002
197 #define ATMEL_REPORT_RELEASE	0x0004
198 
199 #define ATMEL_MAXTRACK		10
200 
201 struct atmel_mxt_softc {
202 	device_t dev;
203 	int	count;			/* >0 if device opened */
204 	int	unit;
205 	int	addr;
206 	cdev_t	devnode;
207 	struct kqinfo kqinfo;
208 	struct lock lk;
209 
210 	int	poll_flags;
211 	thread_t poll_td;
212 
213 	/*
214 	 * Hardware state
215 	 */
216 	struct mxt_rollup	core;
217 	struct mxt_object	*msgprocobj;
218 	struct mxt_object	*cmdprocobj;
219 
220 	/*
221 	 * Capabilities
222 	 */
223 	short	cap_resx;
224 	short	cap_resy;
225 
226 	/*
227 	 * Emulation
228 	 */
229 	atmel_track_t track[ATMEL_MAXTRACK];
230 	int	tracking;
231 	int	track_fingers;
232 
233 	elopacket_t pend_rep;		/* pending reply to command */
234 	int	pend_ack;		/* pending reply mode */
235 
236 	int	last_active_tick;
237 	int	last_calibrate_tick;
238 	int	data_signal;		/* something ready to read */
239 	int	blocked;		/* someone is blocking */
240 	int	reporting_mode;
241 	int	sample_rate;		/* samples/sec */
242 	int	poll_ticks;
243 };
244 
245 typedef struct atmel_mxt_softc atmel_mxt_softc_t;
246 
247 #define ATMEL_POLL_SHUTDOWN	0x0001
248 
249 #define PEND_ACK_NONE		0	/* no reply to command pending */
250 #define PEND_ACK_RESPOND	1	/* reply w/response and ack */
251 #define PEND_ACK_ACK		2	/* reply w/ack only */
252 
253 #define REPORT_NONE		0x0000
254 #define REPORT_ALL		0x0001
255 
256 /*
257  * Async debug variable commands are executed by the poller and will
258  * auto-clear.
259  */
260 static int atmel_mxt_idle_freq = 1;
261 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_idle_freq, CTLFLAG_RW,
262 		&atmel_mxt_idle_freq, 0, "");
263 static int atmel_mxt_slow_freq = 20;
264 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_slow_freq, CTLFLAG_RW,
265 		&atmel_mxt_slow_freq, 0, "");
266 static int atmel_mxt_norm_freq = 100;
267 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_norm_freq, CTLFLAG_RW,
268 		&atmel_mxt_norm_freq, 0, "");
269 static int atmel_mxt_minpressure = 16;
270 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_minpressure, CTLFLAG_RW,
271 		&atmel_mxt_minpressure, 0, "");
272 static int atmel_mxt_reset = 0;
273 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_reset, CTLFLAG_RW,
274 		&atmel_mxt_reset, 0, "");
275 
276 /*
277  * Run a calibration command every N seconds only when idle.  0 to disable.
278  * Default every 30 seconds.
279  */
280 static int atmel_mxt_autocalibrate = 30;
281 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_autocalibrate, CTLFLAG_RW,
282 		&atmel_mxt_autocalibrate, 0, "");
283 
284 /*
285  * run a calibration on module startup.
286  */
287 static int atmel_mxt_debug = 0;
288 SYSCTL_INT(_debug, OID_AUTO, atmel_mxt_debug, CTLFLAG_RW,
289 		&atmel_mxt_debug, 0, "");
290 
291 static void atmel_mxt_poll_thread(void *arg);
292 static void atmel_find_active_state(atmel_mxt_softc_t *sc);
293 static int atmel_mxt_raw_input(atmel_mxt_softc_t *sc, mxt_message_t *msg);
294 static struct mxt_object *mxt_findobject(struct mxt_rollup *core, int type);
295 static int mxt_read_reg(atmel_mxt_softc_t *sc, uint16_t reg,
296 			void *rbuf, int bytes);
297 static int mxt_write_reg_buf(atmel_mxt_softc_t *sc, uint16_t reg,
298 			void *xbuf, int bytes);
299 static int mxt_write_reg(atmel_mxt_softc_t *sc, uint16_t reg, uint8_t val);
300 static int mxt_read_object(atmel_mxt_softc_t *sc, struct mxt_object *obj,
301 			void *rbuf, int rbytes);
302 static int mxt_write_object_off(atmel_mxt_softc_t *sc, struct mxt_object *obj,
303 			int offset, uint8_t val);
304 static void atmel_reset_device(atmel_mxt_softc_t *sc);
305 
306 static
307 const char *
308 msgflagsstr(uint8_t flags)
309 {
310 	static char buf[9];
311 
312 	buf[0] = (flags & MXT_MSGF_DETECT) ? 'D' : '.';
313 	buf[1] = (flags & MXT_MSGF_PRESS) ? 'P' : '.';
314 	buf[2] = (flags & MXT_MSGF_RELEASE) ? 'R' : '.';
315 	buf[3] = (flags & MXT_MSGF_MOVE) ? 'M' : '.';
316 	buf[4] = (flags & MXT_MSGF_VECTOR) ? 'V' : '.';
317 	buf[5] = (flags & MXT_MSGF_AMP) ? 'A' : '.';
318 	buf[6] = (flags & MXT_MSGF_SUPPRESS) ? 'S' : '.';
319 	buf[7] = (flags & MXT_MSGF_UNGRIP) ? 'U' : '.';
320 
321 	return buf;
322 }
323 
324 static
325 void
326 atmel_mxt_lock(atmel_mxt_softc_t *sc)
327 {
328 	lockmgr(&sc->lk, LK_EXCLUSIVE);
329 }
330 
331 static
332 void
333 atmel_mxt_unlock(atmel_mxt_softc_t *sc)
334 {
335 	lockmgr(&sc->lk, LK_RELEASE);
336 }
337 
338 /*
339  * Notify if possible receive data ready.  Must be called
340  * without the lock held to avoid deadlocking in kqueue.
341  */
342 static
343 void
344 atmel_mxt_notify(atmel_mxt_softc_t *sc)
345 {
346 	if (sc->data_signal) {
347 		KNOTE(&sc->kqinfo.ki_note, 0);
348 		atmel_mxt_lock(sc);
349 		if (sc->blocked) {
350 			sc->blocked = 0;
351 			wakeup(&sc->blocked);
352 		}
353 		atmel_mxt_unlock(sc);
354 	}
355 }
356 
357 /*
358  * Initialize the device
359  */
360 static
361 int
362 init_device(atmel_mxt_softc_t *sc, int probe)
363 {
364 	int blksize;
365 	int totsize;
366 	uint32_t crc;
367 
368 	if (mxt_read_reg(sc, 0, &sc->core.info, sizeof(sc->core.info))) {
369 		device_printf(sc->dev, "init_device read-reg failed\n");
370 		return ENXIO;
371 	}
372 	sc->core.nobjs = sc->core.info.num_objects;
373 	if (!probe) {
374 		device_printf(sc->dev,
375 			      "%d configuration objects\n",
376 			      sc->core.info.num_objects);
377 	}
378 	if (sc->core.nobjs < 0 || sc->core.nobjs > 1024) {
379 		device_printf(sc->dev,
380 			      "init_device nobjs (%d) out of bounds\n",
381 			      sc->core.nobjs);
382 		return ENXIO;
383 	}
384 	blksize = sizeof(sc->core.info) +
385 		  sc->core.nobjs * sizeof(struct mxt_object);
386 	totsize = blksize + sizeof(struct mxt_raw_crc);
387 
388 	sc->core.buf = kmalloc(totsize, M_DEVBUF, M_WAITOK | M_ZERO);
389 	if (mxt_read_reg(sc, 0, sc->core.buf, totsize)) {
390 		device_printf(sc->dev,
391 			      "init_device cannot read configuration space\n");
392 		goto done;
393 	}
394 	kprintf("COREBUF %p %d\n", sc->core.buf, blksize);
395 	crc = obp_convert_crc((void *)((uint8_t *)sc->core.buf + blksize));
396 	if (obp_crc24(sc->core.buf, blksize) != crc) {
397 		device_printf(sc->dev,
398 			      "init_device: configuration space "
399 			      "crc mismatch %08x/%08x\n",
400 			      crc, obp_crc24(sc->core.buf, blksize));
401 		/*goto done;*/
402 	}
403 	{
404 		int i;
405 
406 		kprintf("info:   ");
407 		for (i = 0; i < sizeof(sc->core.info); ++i)
408 			kprintf(" %02x", sc->core.buf[i]);
409 		kprintf("\nconfig: ");
410 		while (i < blksize) {
411 			kprintf(" %02x", sc->core.buf[i]);
412 			++i;
413 		}
414 		kprintf("\n");
415 	}
416 	sc->core.objs = (void *)((uint8_t *)sc->core.buf +
417 				 sizeof(sc->core.info));
418 	sc->msgprocobj = mxt_findobject(&sc->core, MXT_GEN_MESSAGEPROCESSOR);
419 	sc->cmdprocobj = mxt_findobject(&sc->core, MXT_GEN_COMMANDPROCESSOR);
420 	if (sc->msgprocobj == NULL) {
421 		device_printf(sc->dev,
422 			      "init_device: cannot find msgproc config\n");
423 		goto done;
424 	}
425 
426 done:
427 	if (sc->msgprocobj == NULL) {
428 		if (sc->core.buf) {
429 			kfree(sc->core.buf, M_DEVBUF);
430 			sc->core.buf = NULL;
431 		}
432 		return ENXIO;
433 	} else {
434 		if (probe) {
435 			kfree(sc->core.buf, M_DEVBUF);
436 			sc->core.buf = NULL;
437 		} else {
438 			atmel_reset_device(sc);
439 		}
440 		return 0;
441 	}
442 }
443 
444 /*
445  * Device infrastructure
446  */
447 #define ATMEL_SOFTC(unit) \
448 	((atmel_mxt_softc_t *)devclass_get_softc(atmel_mxt_devclass, (unit)))
449 
450 static void atmel_mxt_identify(driver_t *driver, device_t parent);
451 static int atmel_mxt_probe(device_t);
452 static int atmel_mxt_attach(device_t);
453 static int atmel_mxt_detach(device_t);
454 
455 static devclass_t atmel_mxt_devclass;
456 
457 static device_method_t atmel_mxt_methods[] = {
458 	/* device interface */
459 	DEVMETHOD(device_identify,	atmel_mxt_identify),
460 	DEVMETHOD(device_probe,		atmel_mxt_probe),
461 	DEVMETHOD(device_attach,	atmel_mxt_attach),
462 	DEVMETHOD(device_detach,	atmel_mxt_detach),
463 
464 #if 0
465 	/* smbus interface */
466 	DEVMETHOD(smbus_intr,		smbus_generic_intr),
467 #endif
468 
469 	DEVMETHOD_END
470 };
471 
472 static driver_t atmel_mxt_driver = {
473 	"atmel_mxt",
474 	atmel_mxt_methods,
475 	sizeof(atmel_mxt_softc_t),
476 };
477 
478 static	d_open_t	atmel_mxtopen;
479 static	d_close_t	atmel_mxtclose;
480 static	d_ioctl_t	atmel_mxtioctl;
481 static	d_read_t	atmel_mxtread;
482 static	d_write_t	atmel_mxtwrite;
483 static	d_kqfilter_t	atmel_mxtkqfilter;
484 
485 static struct dev_ops atmel_mxt_ops = {
486 	{ "atmel_mxt", 0, 0 },
487 	.d_open =	atmel_mxtopen,
488 	.d_close =	atmel_mxtclose,
489 	.d_ioctl =	atmel_mxtioctl,
490 	.d_read =	atmel_mxtread,
491 	.d_write =	atmel_mxtwrite,
492 	.d_kqfilter =	atmel_mxtkqfilter,
493 };
494 
495 static void
496 atmel_mxt_identify(driver_t *driver, device_t parent)
497 {
498 	if (device_find_child(parent, "atmel_mxt", -1) == NULL)
499 		BUS_ADD_CHILD(parent, parent, 0, "atmel_mxt", -1);
500 }
501 
502 static int
503 atmel_mxt_probe(device_t dev)
504 {
505 	atmel_mxt_softc_t sc;
506 	int error;
507 
508 	bzero(&sc, sizeof(sc));
509 	sc.dev = dev;
510 	sc.unit = device_get_unit(dev);
511 
512 	/*
513 	 * Only match against specific addresses to avoid blowing up
514 	 * other I2C devices (?).  At least for now.
515 	 *
516 	 * 0x400 (from smbus) - means specific device address probe,
517 	 *			rather than generic.
518 	 *
519 	 * 0x4A - cypress trackpad on the acer c720.
520 	 */
521 	if ((sc.unit & 0x04FF) != (0x0400 | 0x04A))
522 		return ENXIO;
523 	sc.addr = sc.unit & 0x3FF;
524 	error = init_device(&sc, 1);
525 	if (error)
526 		return ENXIO;
527 
528 	device_set_desc(dev, "Atmel MXT TouchScreen");
529 
530 	return (BUS_PROBE_VENDOR);
531 }
532 
533 static int
534 atmel_mxt_attach(device_t dev)
535 {
536 	atmel_mxt_softc_t *sc;
537 
538 	sc = (atmel_mxt_softc_t *)device_get_softc(dev);
539 	if (!sc)
540 		return ENOMEM;
541 
542 	bzero(sc, sizeof(*sc));
543 
544 	lockinit(&sc->lk, "atmel_mxt", 0, 0);
545 	sc->reporting_mode = 1;
546 
547 	sc->dev = dev;
548 	sc->unit = device_get_unit(dev);
549 	if ((sc->unit & 0x04FF) != (0x0400 | 0x04A))
550 		return ENXIO;
551 	sc->addr = sc->unit & 0x3FF;
552 	sc->last_active_tick = ticks;
553 	sc->last_calibrate_tick = ticks - atmel_mxt_autocalibrate * hz;
554 
555 	if (init_device(sc, 0))
556 		return ENXIO;
557 
558 	if (sc->unit & 0x0400) {
559 		sc->devnode = make_dev(&atmel_mxt_ops, sc->unit,
560 				UID_ROOT, GID_WHEEL, 0600,
561 				"atmel%d-%02x",
562 				sc->unit >> 11, sc->unit & 1023);
563 	} else {
564 		sc->devnode = make_dev(&atmel_mxt_ops, sc->unit,
565 				UID_ROOT, GID_WHEEL, 0600, "atmel%d", sc->unit);
566 	}
567 	device_printf(dev, "atmel mxt touchscreen driver attached\n");
568 	/* device_printf(dev, "...."); */
569 
570 	/*
571 	 * Start the polling thread.
572 	 */
573 	lwkt_create(atmel_mxt_poll_thread, sc,
574 		    &sc->poll_td, NULL, 0, -1, "atmel_mxt-poll");
575 
576 	return (0);
577 }
578 
579 static int
580 atmel_mxt_detach(device_t dev)
581 {
582 	atmel_mxt_softc_t *sc;
583 
584 	sc = (atmel_mxt_softc_t *)device_get_softc(dev);
585 
586 	/*
587 	 * Cleanup our poller thread
588 	 */
589 	atomic_set_int(&sc->poll_flags, ATMEL_POLL_SHUTDOWN);
590 	while (sc->poll_td) {
591 		wakeup(&sc->poll_flags);
592 		tsleep(&sc->poll_td, 0, "atmel_mxtdet", hz);
593 	}
594 
595 	if (sc->devnode)
596 		dev_ops_remove_minor(&atmel_mxt_ops, device_get_unit(dev));
597 	if (sc->devnode)
598 		devfs_assume_knotes(sc->devnode, &sc->kqinfo);
599 	if (sc->core.buf) {
600 		kfree(sc->core.buf, M_DEVBUF);
601 		sc->core.buf = NULL;
602 	}
603 	sc->msgprocobj = NULL;
604 	sc->cmdprocobj = NULL;
605 
606 	return (0);
607 }
608 
609 /*
610  * USER DEVICE I/O FUNCTIONS
611  */
612 static int
613 atmel_mxtopen (struct dev_open_args *ap)
614 {
615 	cdev_t dev = ap->a_head.a_dev;
616 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
617 
618 	if (sc == NULL)
619 		return (ENXIO);
620 
621 	if (sc->count != 0)
622 		return (EBUSY);
623 
624 	sc->count++;
625 
626 	return (0);
627 }
628 
629 static int
630 atmel_mxtclose(struct dev_close_args *ap)
631 {
632 	cdev_t dev = ap->a_head.a_dev;
633 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
634 
635 	if (sc == NULL)
636 		return (ENXIO);
637 
638 	if (sc->count == 0) {
639 		/* This is not supposed to happen. */
640 		return (0);
641 	}
642 
643 	if (sc->count-- == 0) {
644 		sc->reporting_mode = 0;
645 	}
646 
647 	return (0);
648 }
649 
650 static int
651 atmel_mxtread(struct dev_read_args *ap)
652 {
653 	cdev_t dev = ap->a_head.a_dev;
654 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
655 	int error;
656 	struct uio *uio = ap->a_uio;
657 	int ioflag = ap->a_ioflag;
658 	size_t n;
659 	elopacket_t pkt;
660 	atmel_track_t *track;
661 
662 	/*
663 	 * Load next ready event, block if necessary.
664 	 */
665 	atmel_mxt_lock(sc);
666 	for (;;) {
667 		error = 0;
668 
669 		switch(sc->pend_ack) {
670 		case PEND_ACK_NONE:
671 			if (sc->tracking && sc->track[sc->tracking].report) {
672 				/*
673 				 * Report ready
674 				 */
675 				track = &sc->track[sc->tracking];
676 				bzero(&pkt, sizeof(pkt));
677 				pkt.cmd = 'T';
678 				if (track->report & ATMEL_REPORT_PRESS) {
679 					pkt.byte2 |= 0x01;
680 					track->report &= ~ATMEL_REPORT_PRESS;
681 				} else if (track->report & ATMEL_REPORT_MOVE) {
682 					pkt.byte2 |= 0x02;
683 					track->report &= ~ATMEL_REPORT_MOVE;
684 				} else if (track->report &
685 					   ATMEL_REPORT_RELEASE) {
686 					pkt.byte2 |= 0x04;
687 					track->report &= ~ATMEL_REPORT_RELEASE;
688 				}
689 				pkt.byte3 = track->x & 0xFF;
690 				pkt.byte4 = track->x >> 8;
691 				pkt.byte5 = track->y & 0xFF;
692 				pkt.byte6 = track->y >> 8;
693 				pkt.byte7 = track->pressure & 0xFF;
694 				pkt.byte8 = track->pressure >> 8;
695 			} else if (ioflag & IO_NDELAY) {
696 				/*
697 				 * Non-blocking, nothing ready
698 				 */
699 				error = EWOULDBLOCK;
700 			} else {
701 				/*
702 				 * Blocking, nothing ready
703 				 */
704 				sc->data_signal = 0;
705 				sc->blocked = 1;
706 				error = lksleep(&sc->blocked, &sc->lk,
707 						PCATCH, "atmelw", 0);
708 				if (error == 0)
709 					continue;
710 			}
711 			break;
712 		case PEND_ACK_RESPOND:
713 			pkt = sc->pend_rep;
714 			sc->pend_ack = PEND_ACK_ACK;
715 			break;
716 		case PEND_ACK_ACK:
717 			bzero(&pkt, sizeof(pkt));
718 			pkt.cmd = 'A';
719 			sc->pend_ack = PEND_ACK_NONE;
720 			break;
721 		}
722 		atmel_find_active_state(sc);
723 		break;
724 	}
725 	atmel_mxt_unlock(sc);
726 
727 	/*
728 	 * If no error we can return the event loaded into pkt.
729 	 */
730 	if (error == 0) {
731 		uint8_t csum = 0xAA;
732 		int i;
733 
734 		pkt.sync = 'U';
735 		for (i = 0; i < sizeof(pkt) - 1; ++i)
736 			csum += ((uint8_t *)&pkt)[i];
737 		pkt.csum = csum;
738 		n = uio->uio_resid;
739 		if (n > sizeof(pkt))
740 			n = sizeof(pkt);
741 		error = uiomove((void *)&pkt, n, uio);
742 	}
743 
744 	return error;
745 }
746 
747 static int
748 atmel_mxtwrite(struct dev_write_args *ap)
749 {
750 	cdev_t dev = ap->a_head.a_dev;
751 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
752 	struct uio *uio = ap->a_uio;
753 	elopacket_t pkt;
754 	int error;
755 	size_t n;
756 
757 	error = 0;
758 
759 	while (uio->uio_resid) {
760 		bzero(&pkt, sizeof(pkt));
761 		n = uio->uio_resid;
762 		if (n > sizeof(pkt))
763 			n = sizeof(pkt);
764 		error = uiomove((void *)&pkt, n, uio);
765 		if (error)
766 			break;
767 		atmel_mxt_lock(sc);
768 		switch(pkt.cmd) {
769 		case 'i':
770 			/*
771 			 * ELO_ID request id
772 			 */
773 			bzero(&sc->pend_rep, sizeof(sc->pend_rep));
774 			sc->pend_rep.cmd = 'I';
775 			sc->pend_ack = PEND_ACK_RESPOND;
776 			break;
777 		case 'o':
778 			/*
779 			 * ELO_OWNER request owner
780 			 */
781 			bzero(&sc->pend_rep, sizeof(sc->pend_rep));
782 			sc->pend_rep.cmd = 'O';
783 			sc->pend_ack = PEND_ACK_RESPOND;
784 			break;
785 		case 'm':
786 			/*
787 			 * ELO_MODE control packet
788 			 */
789 			sc->pend_ack = PEND_ACK_ACK;
790 			break;
791 		case 'r':
792 			/*
793 			 * ELO_REPORT control packet
794 			 */
795 			sc->pend_ack = PEND_ACK_ACK;
796 			break;
797 		}
798 		atmel_mxt_unlock(sc);
799 	}
800 	return error;
801 }
802 
803 static void atmel_mxt_filt_detach(struct knote *);
804 static int atmel_mxt_filt(struct knote *, long);
805 
806 static struct filterops atmel_mxt_filtops =
807         { FILTEROP_ISFD, NULL, atmel_mxt_filt_detach, atmel_mxt_filt };
808 
809 static int
810 atmel_mxtkqfilter(struct dev_kqfilter_args *ap)
811 {
812 	cdev_t dev = ap->a_head.a_dev;
813 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
814 	struct knote *kn = ap->a_kn;
815 	struct klist *klist;
816 
817 	switch(kn->kn_filter) {
818 	case EVFILT_READ:
819 		kn->kn_fop = &atmel_mxt_filtops;
820 		kn->kn_hook = (void *)sc;
821 		ap->a_result = 0;
822 		break;
823 	default:
824 		ap->a_result = EOPNOTSUPP;
825 		return (0);
826 	}
827 	klist = &sc->kqinfo.ki_note;
828 	knote_insert(klist, kn);
829 
830 	return (0);
831 }
832 
833 static void
834 atmel_mxt_filt_detach(struct knote *kn)
835 {
836 	atmel_mxt_softc_t *sc = (atmel_mxt_softc_t *)kn->kn_hook;
837 	struct klist *klist;
838 
839 	klist = &sc->kqinfo.ki_note;
840 	knote_remove(klist, kn);
841 }
842 
843 static int
844 atmel_mxt_filt(struct knote *kn, long hint)
845 {
846 	atmel_mxt_softc_t *sc = (atmel_mxt_softc_t *)kn->kn_hook;
847 	int ready;
848 
849 	atmel_mxt_lock(sc);
850 	if (sc->data_signal)
851 		ready = 1;
852 	else
853 		ready = 0;
854 	atmel_mxt_unlock(sc);
855 
856 	return (ready);
857 }
858 
859 static int
860 atmel_mxtioctl(struct dev_ioctl_args *ap)
861 {
862 	cdev_t dev = ap->a_head.a_dev;
863 	device_t bus;		/* smbbus */
864 	/*struct atmel_mxtcmd *s = (struct atmel_mxtcmd *)ap->a_data;*/
865 	void *s = NULL;
866 	atmel_mxt_softc_t *sc = ATMEL_SOFTC(minor(dev));
867 	int error;
868 
869 	if (sc == NULL)
870 		return (ENXIO);
871 	if (s == NULL)
872 		return (EINVAL);
873 
874 	/*
875 	 * NOTE: smbus_*() functions automatically recurse the parent to
876 	 *	 get to the actual device driver.
877 	 */
878 	bus = device_get_parent(sc->dev);	/* smbus */
879 
880 	/* Allocate the bus. */
881 	if ((error = smbus_request_bus(bus, sc->dev,
882 			(ap->a_fflag & O_NONBLOCK) ?
883 			SMB_DONTWAIT : (SMB_WAIT | SMB_INTR))))
884 		return (error);
885 
886 	switch (ap->a_cmd) {
887 	default:
888 #if 0
889 		error = inputev_ioctl(&sc->iev, ap->a_cmd, ap->a_data);
890 #endif
891 		error = ENOTTY;
892 		break;
893 	}
894 
895 	smbus_release_bus(bus, sc->dev);
896 
897 	return (error);
898 }
899 
900 /*
901  * MAJOR SUPPORT FUNCTIONS
902  */
903 static
904 void
905 atmel_mxt_poll_thread(void *arg)
906 {
907 	atmel_mxt_softc_t *sc = arg;
908 	int error;
909 	int freq = atmel_mxt_norm_freq;
910 	int isidle = 0;
911 
912 	while ((sc->poll_flags & ATMEL_POLL_SHUTDOWN) == 0) {
913 		if (sc->msgprocobj)
914 			error = 0;
915 		else
916 			error = ENXIO;
917 		if (error == 0) {
918 			mxt_message_t msg;
919 
920 			error = mxt_read_object(sc, sc->msgprocobj,
921 					    &msg, sizeof(msg));
922 			if (error == 0)
923 				isidle = atmel_mxt_raw_input(sc, &msg);
924 			else
925 				isidle = 1;
926 		}
927 
928 		/*
929 		 * don't let the last_active_tick or last_calibrate_tick
930 		 * delta calculation overflow.
931 		 */
932 		if ((ticks - sc->last_active_tick) > 1000 * hz)
933 			sc->last_active_tick = ticks - 1000 * hz;
934 		if ((ticks - sc->last_calibrate_tick) > 1000 * hz)
935 			sc->last_calibrate_tick = ticks - 1000 * hz;
936 
937 		/*
938 		 * Reset if requested
939 		 */
940 		if (atmel_mxt_reset) {
941 			atmel_mxt_reset = 0;
942 			atmel_reset_device(sc);
943 		}
944 
945 		/*
946 		 * Automatically calibrate when the touchpad has been
947 		 * idle atmel_mxt_autocalibrate seconds, and recalibrate
948 		 * on the same interval while it remains idle.
949 		 *
950 		 * If we don't do this the touchscreen can get really out
951 		 * of whack over time and basically stop functioning properly.
952 		 * It's unclear why the device does not do this automatically.
953 		 *
954 		 * Response occurs in the message stream (which we just
955 		 * ignore).
956 		 */
957 		if (sc->cmdprocobj && atmel_mxt_autocalibrate &&
958 		    ((ticks - sc->last_calibrate_tick) >
959 		     atmel_mxt_autocalibrate * hz) &&
960 		    ((ticks - sc->last_active_tick) >
961 		     atmel_mxt_autocalibrate * hz)) {
962 			sc->last_calibrate_tick = ticks;
963 			mxt_write_object_off(sc, sc->cmdprocobj,
964 					 MXT_CMDPROC_CALIBRATE_OFF, 1);
965 		}
966 		tsleep(&sc->poll_flags, 0, "atmpol", (hz + freq - 1) / freq);
967 		++sc->poll_ticks;
968 		if (sc->count == 0)
969 			freq = atmel_mxt_idle_freq;
970 		else if (isidle)
971 			freq = atmel_mxt_slow_freq;
972 		else
973 			freq = atmel_mxt_norm_freq;
974 	}
975 	sc->poll_td = NULL;
976 	wakeup(&sc->poll_td);
977 }
978 
979 static
980 void
981 atmel_reset_device(atmel_mxt_softc_t *sc)
982 {
983 	int dummy;
984 	mxt_write_object_off(sc, sc->cmdprocobj, MXT_CMDPROC_RESET_OFF, 1);
985 	tsleep(&dummy, 0, "atmel_reset", hz * 2);
986 }
987 
988 /*
989  * Calculate currently active state, if any
990  */
991 static
992 void
993 atmel_find_active_state(atmel_mxt_softc_t *sc)
994 {
995 	atmel_track_t *track;
996 	int i;
997 
998 	track = &sc->track[sc->tracking];
999 	if (track->report == 0) {
1000 		for (i = 0; i < ATMEL_MAXTRACK; ++i) {
1001 			track = &sc->track[i];
1002 			if (track->report) {
1003 				sc->tracking = i;
1004 				break;
1005 			}
1006 		}
1007 	}
1008 	if (track->report == 0 && sc->pend_ack == PEND_ACK_NONE) {
1009 		sc->data_signal = 0;
1010 	} else {
1011 		sc->data_signal = 1;
1012 	}
1013 }
1014 
1015 /*
1016  * Return non-zero if we are idle
1017  */
1018 static
1019 int
1020 atmel_mxt_raw_input(atmel_mxt_softc_t *sc, mxt_message_t *msg)
1021 {
1022 	atmel_track_t *track;
1023 	int donotify = 0;
1024 
1025 	if (atmel_mxt_debug) {
1026 		kprintf("track=%02x f=%s x=%-4d y=%-4d p=%d amp=%d\n",
1027 			msg->any.reportid,
1028 			msgflagsstr(msg->touch.flags),
1029 			(msg->touch.pos[0] << 4) |
1030 				((msg->touch.pos[2] >> 4) & 0x0F),
1031 			(msg->touch.pos[1] << 4) |
1032 				((msg->touch.pos[2]) & 0x0F),
1033 			msg->touch.area,
1034 			msg->touch.amplitude);
1035 	}
1036 	atmel_mxt_lock(sc);
1037 
1038 	/*
1039 	 * If message buffer is empty and no fingers are currently pressed
1040 	 * return idle, else we are not idle.
1041 	 */
1042 	if (msg->any.reportid == 0xFF)
1043 		goto done;
1044 
1045 	/*
1046 	 * Process message buffer.  For now ignore any messages with
1047 	 * reportids that we do not understand.
1048 	 *
1049 	 * note: reportid==1  typicallk acknowledges calibrations (?)
1050 	 */
1051 	if (msg->any.reportid < 3 || msg->any.reportid >= ATMEL_MAXTRACK)
1052 		goto done;
1053 
1054 	sc->last_active_tick = ticks;
1055 
1056 	track = &sc->track[msg->any.reportid];
1057 	track->x = (msg->touch.pos[0] << 4) |
1058 		   ((msg->touch.pos[2] >> 4) & 0x0F);
1059 	track->y = (msg->touch.pos[1] << 4) |
1060 		   (msg->touch.pos[2] & 0x0F);
1061 	track->pressure = msg->touch.amplitude;
1062 
1063 	track->x = track->x * 3000 / 1361;
1064 	track->y = track->y * 3000 / 3064;
1065 
1066 	if (msg->touch.flags & MXT_MSGF_DETECT) {
1067 		track->status = ATMEL_TRACK_PRESSED;
1068 		if (msg->touch.flags & MXT_MSGF_PRESS) {
1069 			track->report |= ATMEL_REPORT_PRESS;
1070 		}
1071 		if (msg->touch.flags & MXT_MSGF_MOVE) {
1072 			track->report |= ATMEL_REPORT_MOVE;
1073 		}
1074 	} else {
1075 		track->status = ATMEL_TRACK_RELEASED;
1076 		track->report |= ATMEL_REPORT_RELEASE;
1077 	}
1078 	atmel_find_active_state(sc);
1079 	donotify = 1;
1080 done:
1081 	atmel_mxt_unlock(sc);
1082 	if (donotify)
1083 		atmel_mxt_notify(sc);
1084 	if (sc->track_fingers)
1085 		return 0;
1086 	else
1087 		return 1;
1088 }
1089 
1090 /*
1091  * Support functions
1092  */
1093 static
1094 struct mxt_object *
1095 mxt_findobject(struct mxt_rollup *core, int type)
1096 {
1097 	int i;
1098 
1099 	for (i = 0; i < core->nobjs; ++i) {
1100 		if (core->objs[i].type == type)
1101 			return(&core->objs[i]);
1102 	}
1103 	return NULL;
1104 }
1105 
1106 static int
1107 mxt_read_reg(atmel_mxt_softc_t *sc, uint16_t reg, void *rbuf, int bytes)
1108 {
1109 	uint8_t wreg[2];
1110 	device_t bus;
1111 	int error;
1112 	int rbytes;
1113 
1114 	wreg[0] = reg & 255;
1115 	wreg[1] = reg >> 8;
1116 
1117 	bus = device_get_parent(sc->dev);
1118 	if ((error = smbus_request_bus(bus, sc->dev, SMB_WAIT | SMB_INTR)) != 0)
1119 		return error;
1120 	error = smbus_trans(bus, sc->addr, 0,
1121 			    SMB_TRANS_NOCNT |
1122 			    SMB_TRANS_NOCMD |
1123 			    SMB_TRANS_7BIT,
1124 			    wreg, 2,
1125 			    rbuf, bytes, &rbytes);
1126 	smbus_release_bus(bus, sc->dev);
1127 
1128 	if (bytes != rbytes) {
1129 		device_printf(sc->dev,
1130 			      "smbus_trans reg %d short read %d/%d\n",
1131 			      reg, bytes, rbytes);
1132 		error = EINVAL;
1133 	}
1134 
1135 	return error;
1136 }
1137 
1138 static int
1139 mxt_write_reg_buf(atmel_mxt_softc_t *sc, uint16_t reg, void *xbuf, int bytes)
1140 {
1141 	uint8_t wbuf[256];
1142 	device_t bus;
1143 	int error;
1144 
1145 	KKASSERT(bytes < sizeof(wbuf) - 2);
1146 	wbuf[0] = reg & 255;
1147 	wbuf[1] = reg >> 8;
1148 	bcopy(xbuf, wbuf + 2, bytes);
1149 
1150 	bus = device_get_parent(sc->dev);
1151 	if ((error = smbus_request_bus(bus, sc->dev, SMB_WAIT | SMB_INTR)) != 0)
1152 		return error;
1153 	error = smbus_trans(bus, sc->addr, 0,
1154 			    SMB_TRANS_NOCNT |
1155 			    SMB_TRANS_NOCMD |
1156 			    SMB_TRANS_7BIT,
1157 			    wbuf, bytes + 2,
1158 			    NULL, 0, NULL);
1159 	smbus_release_bus(bus, sc->dev);
1160 	return error;
1161 }
1162 
1163 static int
1164 mxt_write_reg(atmel_mxt_softc_t *sc, uint16_t reg, uint8_t val)
1165 {
1166 	return mxt_write_reg_buf(sc, reg, &val, 1);
1167 }
1168 
1169 static int
1170 mxt_read_object(atmel_mxt_softc_t *sc, struct mxt_object *obj,
1171 	        void *rbuf, int rbytes)
1172 {
1173 	uint16_t reg = obj->start_pos_lsb + (obj->start_pos_msb << 8);
1174 	int bytes = obj->size_minus_one + 1;
1175 
1176 	if (bytes > rbytes)
1177 		bytes = rbytes;
1178 	return mxt_read_reg(sc, reg, rbuf, bytes);
1179 }
1180 
1181 static int
1182 mxt_write_object_off(atmel_mxt_softc_t *sc, struct mxt_object *obj,
1183 		 int offset, uint8_t val)
1184 {
1185 	uint16_t reg = obj->start_pos_lsb + (obj->start_pos_msb << 8);
1186 
1187 	reg += offset;
1188 	return mxt_write_reg(sc, reg, val);
1189 }
1190 
1191 DRIVER_MODULE(atmel_mxt, smbus, atmel_mxt_driver, atmel_mxt_devclass,
1192 	      NULL, NULL);
1193 MODULE_DEPEND(atmel_mxt, smbus, SMBUS_MINVER, SMBUS_PREFVER, SMBUS_MAXVER);
1194 MODULE_VERSION(atmel_mxt, 1);
1195