1/*-
2 * Copyright (c) 2016 Ganbold Tsagaankhuu <ganbold@freebsd.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27/*
28 * Allwinner Consumer IR controller
29 */
30
31#include <sys/param.h>
32#include <sys/systm.h>
33#include <sys/bus.h>
34#include <sys/kernel.h>
35#include <sys/module.h>
36#include <sys/rman.h>
37#include <sys/sysctl.h>
38#include <machine/bus.h>
39
40#include <dev/ofw/openfirm.h>
41#include <dev/ofw/ofw_bus.h>
42#include <dev/ofw/ofw_bus_subr.h>
43#include <dev/clk/clk.h>
44#include <dev/hwreset/hwreset.h>
45
46#include <dev/evdev/input.h>
47#include <dev/evdev/evdev.h>
48
49#define	READ(_sc, _r)		bus_read_4((_sc)->res[0], (_r))
50#define	WRITE(_sc, _r, _v)	bus_write_4((_sc)->res[0], (_r), (_v))
51
52/* IR Control */
53#define	AW_IR_CTL			0x00
54/* Global Enable */
55#define	 AW_IR_CTL_GEN			(1 << 0)
56/* RX enable */
57#define	 AW_IR_CTL_RXEN			(1 << 1)
58/* CIR mode enable */
59#define	 AW_IR_CTL_MD			(1 << 4) | (1 << 5)
60
61/* RX Config Reg */
62#define	AW_IR_RXCTL			0x10
63/* Pulse Polarity Invert flag */
64#define	 AW_IR_RXCTL_RPPI		(1 << 2)
65
66/* RX Data */
67#define	AW_IR_RXFIFO			0x20
68
69/* RX Interrupt Control */
70#define	AW_IR_RXINT			0x2C
71/* RX FIFO Overflow */
72#define	 AW_IR_RXINT_ROI_EN		(1 << 0)
73/* RX Packet End */
74#define	 AW_IR_RXINT_RPEI_EN		(1 << 1)
75/* RX FIFO Data Available */
76#define	 AW_IR_RXINT_RAI_EN		(1 << 4)
77/* RX FIFO available byte level */
78#define	 AW_IR_RXINT_RAL(val)		((val) << 8)
79
80/* RX Interrupt Status Reg */
81#define	AW_IR_RXSTA			0x30
82/* RX FIFO Get Available Counter */
83#define	 AW_IR_RXSTA_COUNTER(val)	(((val) >> 8) & (sc->fifo_size * 2 - 1))
84/* Clear all interrupt status */
85#define	 AW_IR_RXSTA_CLEARALL		0xff
86
87/* IR Sample Configure Reg */
88#define	AW_IR_CIR			0x34
89
90/*
91 * Frequency sample: 23437.5Hz (Cycle: 42.7us)
92 * Pulse of NEC Remote > 560us
93 */
94/* Filter Threshold = 8 * 42.7 = ~341us < 500us */
95#define	 AW_IR_RXFILT_VAL		(((8) & 0x3f) << 2)
96/* Idle Threshold = (2 + 1) * 128 * 42.7 = ~16.4ms > 9ms */
97#define	 AW_IR_RXIDLE_VAL		(((2) & 0xff) << 8)
98
99/* Bit 15 - value (pulse/space) */
100#define	VAL_MASK			0x80
101/* Bits 0:14 - sample duration  */
102#define	PERIOD_MASK			0x7f
103
104/* Clock rate for IR0 or IR1 clock in CIR mode */
105#define	AW_IR_BASE_CLK			3000000
106/* Frequency sample 3MHz/64 = 46875Hz (21.3us) */
107#define	AW_IR_SAMPLE_64			(0 << 0)
108/* Frequency sample 3MHz/128 = 23437.5Hz (42.7us) */
109#define	AW_IR_SAMPLE_128		(1 << 0)
110
111#define	AW_IR_ERROR_CODE		0xffffffff
112#define	AW_IR_REPEAT_CODE		0x0
113
114/* 80 * 42.7 = ~3.4ms, Lead1(4.5ms) > AW_IR_L1_MIN */
115#define	AW_IR_L1_MIN			80
116/* 40 * 42.7 = ~1.7ms, Lead0(4.5ms) Lead0R(2.25ms) > AW_IR_L0_MIN */
117#define	AW_IR_L0_MIN			40
118/* 26 * 42.7 = ~1109us ~= 561 * 2, Pulse < AW_IR_PMAX */
119#define	AW_IR_PMAX			26
120/* 26 * 42.7 = ~1109us ~= 561 * 2, D1 > AW_IR_DMID, D0 <= AW_IR_DMID */
121#define	AW_IR_DMID			26
122/* 53 * 42.7 = ~2263us ~= 561 * 4, D < AW_IR_DMAX */
123#define	AW_IR_DMAX			53
124
125/* Active Thresholds */
126#define	AW_IR_ACTIVE_T_VAL		AW_IR_L1_MIN
127#define	AW_IR_ACTIVE_T			(((AW_IR_ACTIVE_T_VAL - 1) & 0xff) << 16)
128#define	AW_IR_ACTIVE_T_C_VAL		0
129#define	AW_IR_ACTIVE_T_C		((AW_IR_ACTIVE_T_C_VAL & 0xff) << 23)
130
131/* Code masks */
132#define	CODE_MASK			0x00ff00ff
133#define	INV_CODE_MASK			0xff00ff00
134#define	VALID_CODE_MASK			0x00ff0000
135
136enum {
137	A10_IR = 1,
138	A13_IR,
139	A31_IR,
140};
141
142#define	AW_IR_RAW_BUF_SIZE		128
143
144SYSCTL_NODE(_hw, OID_AUTO, aw_cir, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
145    "aw_cir driver");
146
147static int aw_cir_debug = 0;
148SYSCTL_INT(_hw_aw_cir, OID_AUTO, debug, CTLFLAG_RWTUN, &aw_cir_debug, 0,
149    "Debug 1=on 0=off");
150
151struct aw_ir_softc {
152	device_t		dev;
153	struct resource		*res[2];
154	void *			intrhand;
155	int			fifo_size;
156	int			dcnt;	/* Packet Count */
157	unsigned char		buf[AW_IR_RAW_BUF_SIZE];
158	struct evdev_dev	*sc_evdev;
159};
160
161static struct resource_spec aw_ir_spec[] = {
162	{ SYS_RES_MEMORY,	0,	RF_ACTIVE },
163	{ SYS_RES_IRQ,		0,	RF_ACTIVE | RF_SHAREABLE },
164	{ -1, 0 }
165};
166
167static struct ofw_compat_data compat_data[] = {
168	{ "allwinner,sun4i-a10-ir",	A10_IR },
169	{ "allwinner,sun5i-a13-ir",	A13_IR },
170	{ "allwinner,sun6i-a31-ir",	A31_IR },
171	{ NULL,				0 }
172};
173
174static void
175aw_ir_buf_reset(struct aw_ir_softc *sc)
176{
177
178	sc->dcnt = 0;
179}
180
181static void
182aw_ir_buf_write(struct aw_ir_softc *sc, unsigned char data)
183{
184
185	if (sc->dcnt < AW_IR_RAW_BUF_SIZE)
186		sc->buf[sc->dcnt++] = data;
187	else
188		if (bootverbose)
189			device_printf(sc->dev, "IR RX Buffer Full!\n");
190}
191
192static int
193aw_ir_buf_full(struct aw_ir_softc *sc)
194{
195
196	return (sc->dcnt >= AW_IR_RAW_BUF_SIZE);
197}
198
199static unsigned char
200aw_ir_read_data(struct aw_ir_softc *sc)
201{
202
203	return (unsigned char)(READ(sc, AW_IR_RXFIFO) & 0xff);
204}
205
206static unsigned long
207aw_ir_decode_packets(struct aw_ir_softc *sc)
208{
209	unsigned int len, code;
210	unsigned int active_delay;
211	unsigned char val, last;
212	int i, bitcount;
213
214	if (bootverbose && __predict_false(aw_cir_debug) != 0)
215		device_printf(sc->dev, "sc->dcnt = %d\n", sc->dcnt);
216
217	/* Find Lead 1 (bit separator) */
218	active_delay = AW_IR_ACTIVE_T_VAL *
219	    (AW_IR_ACTIVE_T_C_VAL != 0 ? 128 : 1);
220	len = active_delay;
221	if (bootverbose && __predict_false(aw_cir_debug) != 0)
222		device_printf(sc->dev, "Initial len: %d\n", len);
223	for (i = 0;  i < sc->dcnt; i++) {
224		val = sc->buf[i];
225		if (val & VAL_MASK)
226			len += (val & PERIOD_MASK) + 1;
227		else {
228			if (len > AW_IR_L1_MIN)
229				break;
230			len = 0;
231		}
232	}
233	if (bootverbose && __predict_false(aw_cir_debug) != 0)
234		device_printf(sc->dev, "len = %d\n", len);
235	if ((val & VAL_MASK) || (len <= AW_IR_L1_MIN)) {
236		if (bootverbose && __predict_false(aw_cir_debug) != 0)
237			device_printf(sc->dev, "Bit separator error\n");
238		goto error_code;
239	}
240
241	/* Find Lead 0 (bit length) */
242	len = 0;
243	for (; i < sc->dcnt; i++) {
244		val = sc->buf[i];
245		if (val & VAL_MASK) {
246			if(len > AW_IR_L0_MIN)
247				break;
248			len = 0;
249		} else
250			len += (val & PERIOD_MASK) + 1;
251	}
252	if ((!(val & VAL_MASK)) || (len <= AW_IR_L0_MIN)) {
253		if (bootverbose && __predict_false(aw_cir_debug) != 0)
254			device_printf(sc->dev, "Bit length error\n");
255		goto error_code;
256	}
257
258	/* Start decoding */
259	code = 0;
260	bitcount = 0;
261	last = 1;
262	len = 0;
263	for (; i < sc->dcnt; i++) {
264		val = sc->buf[i];
265		if (last) {
266			if (val & VAL_MASK)
267				len += (val & PERIOD_MASK) + 1;
268			else {
269				if (len > AW_IR_PMAX) {
270					if (bootverbose)
271						device_printf(sc->dev,
272						    "Pulse error, len=%d\n",
273						    len);
274					goto error_code;
275				}
276				last = 0;
277				len = (val & PERIOD_MASK) + 1;
278			}
279		} else {
280			if (val & VAL_MASK) {
281				if (len > AW_IR_DMAX) {
282					if (bootverbose)
283						device_printf(sc->dev,
284						    "Distance error, len=%d\n",
285						    len);
286					goto error_code;
287				} else {
288					if (len > AW_IR_DMID) {
289						/* Decode */
290						code |= 1 << bitcount;
291					}
292					bitcount++;
293					if (bitcount == 32)
294						break;  /* Finish decoding */
295				}
296				last = 1;
297				len = (val & PERIOD_MASK) + 1;
298			} else
299				len += (val & PERIOD_MASK) + 1;
300		}
301	}
302	return (code);
303
304error_code:
305
306	return (AW_IR_ERROR_CODE);
307}
308
309static int
310aw_ir_validate_code(unsigned long code)
311{
312	unsigned long v1, v2;
313
314	/* Don't check address */
315	v1 = code & CODE_MASK;
316	v2 = (code & INV_CODE_MASK) >> 8;
317
318	if (((v1 ^ v2) & VALID_CODE_MASK) == VALID_CODE_MASK)
319		return (0);	/* valid */
320	else
321		return (1);	/* invalid */
322}
323
324static void
325aw_ir_intr(void *arg)
326{
327	struct aw_ir_softc *sc;
328	uint32_t val;
329	int i, dcnt;
330	unsigned long ir_code;
331	int stat;
332
333	sc = (struct aw_ir_softc *)arg;
334
335	/* Read RX interrupt status */
336	val = READ(sc, AW_IR_RXSTA);
337	if (bootverbose && __predict_false(aw_cir_debug) != 0)
338		device_printf(sc->dev, "RX interrupt status: %x\n", val);
339
340	/* Clean all pending interrupt statuses */
341	WRITE(sc, AW_IR_RXSTA, val | AW_IR_RXSTA_CLEARALL);
342
343	/* When Rx FIFO Data available or Packet end */
344	if (val & (AW_IR_RXINT_RAI_EN | AW_IR_RXINT_RPEI_EN)) {
345		if (bootverbose && __predict_false(aw_cir_debug) != 0)
346			device_printf(sc->dev,
347			    "RX FIFO Data available or Packet end\n");
348		/* Get available message count in RX FIFO */
349		dcnt  = AW_IR_RXSTA_COUNTER(val);
350		/* Read FIFO */
351		for (i = 0; i < dcnt; i++) {
352			if (aw_ir_buf_full(sc)) {
353				if (bootverbose)
354					device_printf(sc->dev,
355					    "raw buffer full\n");
356				break;
357			} else
358				aw_ir_buf_write(sc, aw_ir_read_data(sc));
359		}
360	}
361
362	if (val & AW_IR_RXINT_RPEI_EN) {
363		/* RX Packet end */
364		if (bootverbose && __predict_false(aw_cir_debug) != 0)
365			device_printf(sc->dev, "RX Packet end\n");
366		ir_code = aw_ir_decode_packets(sc);
367		stat = aw_ir_validate_code(ir_code);
368		if (stat == 0) {
369			evdev_push_event(sc->sc_evdev,
370			    EV_MSC, MSC_SCAN, ir_code);
371			evdev_sync(sc->sc_evdev);
372		}
373		if (bootverbose && __predict_false(aw_cir_debug) != 0) {
374			device_printf(sc->dev, "Final IR code: %lx\n",
375			    ir_code);
376			device_printf(sc->dev, "IR code status: %d\n",
377			    stat);
378		}
379		aw_ir_buf_reset(sc);
380	}
381	if (val & AW_IR_RXINT_ROI_EN) {
382		/* RX FIFO overflow */
383		if (bootverbose)
384			device_printf(sc->dev, "RX FIFO overflow\n");
385		/* Flush raw buffer */
386		aw_ir_buf_reset(sc);
387	}
388}
389
390static int
391aw_ir_probe(device_t dev)
392{
393
394	if (!ofw_bus_status_okay(dev))
395		return (ENXIO);
396
397	if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0)
398		return (ENXIO);
399
400	device_set_desc(dev, "Allwinner CIR controller");
401	return (BUS_PROBE_DEFAULT);
402}
403
404static int
405aw_ir_attach(device_t dev)
406{
407	struct aw_ir_softc *sc;
408	hwreset_t rst_apb;
409	clk_t clk_ir, clk_gate;
410	int err;
411	uint32_t val = 0;
412
413	clk_ir = clk_gate = NULL;
414	rst_apb = NULL;
415
416	sc = device_get_softc(dev);
417	sc->dev = dev;
418
419	if (bus_alloc_resources(dev, aw_ir_spec, sc->res) != 0) {
420		device_printf(dev, "could not allocate memory resource\n");
421		return (ENXIO);
422	}
423
424	switch (ofw_bus_search_compatible(dev, compat_data)->ocd_data) {
425	case A10_IR:
426		sc->fifo_size = 16;
427		break;
428	case A13_IR:
429	case A31_IR:
430		sc->fifo_size = 64;
431		break;
432	}
433
434	/* De-assert reset */
435	if (hwreset_get_by_ofw_idx(dev, 0, 0, &rst_apb) == 0) {
436		err = hwreset_deassert(rst_apb);
437		if (err != 0) {
438			device_printf(dev, "cannot de-assert reset\n");
439			goto error;
440		}
441	}
442
443	/* Reset buffer */
444	aw_ir_buf_reset(sc);
445
446	/* Get clocks and enable them */
447	err = clk_get_by_ofw_name(dev, 0, "apb", &clk_gate);
448	if (err != 0) {
449		device_printf(dev, "Cannot get gate clock\n");
450		goto error;
451	}
452	err = clk_get_by_ofw_name(dev, 0, "ir", &clk_ir);
453	if (err != 0) {
454		device_printf(dev, "Cannot get IR clock\n");
455		goto error;
456	}
457	/* Set clock rate */
458	err = clk_set_freq(clk_ir, AW_IR_BASE_CLK, 0);
459	if (err != 0) {
460		device_printf(dev, "cannot set IR clock rate\n");
461		goto error;
462	}
463	/* Enable clocks */
464	err = clk_enable(clk_gate);
465	if (err != 0) {
466		device_printf(dev, "Cannot enable clk gate\n");
467		goto error;
468	}
469	err = clk_enable(clk_ir);
470	if (err != 0) {
471		device_printf(dev, "Cannot enable IR clock\n");
472		goto error;
473	}
474
475	if (bus_setup_intr(dev, sc->res[1],
476	    INTR_TYPE_MISC | INTR_MPSAFE, NULL, aw_ir_intr, sc,
477	    &sc->intrhand)) {
478		bus_release_resources(dev, aw_ir_spec, sc->res);
479		device_printf(dev, "cannot setup interrupt handler\n");
480		err = ENXIO;
481		goto error;
482	}
483
484	/* Enable CIR Mode */
485	WRITE(sc, AW_IR_CTL, AW_IR_CTL_MD);
486
487	/*
488	 * Set clock sample, filter, idle thresholds.
489	 * Frequency sample = 3MHz/128 = 23437.5Hz (42.7us)
490	 */
491	val = AW_IR_SAMPLE_128;
492	val |= (AW_IR_RXFILT_VAL | AW_IR_RXIDLE_VAL);
493	val |= (AW_IR_ACTIVE_T | AW_IR_ACTIVE_T_C);
494	WRITE(sc, AW_IR_CIR, val);
495
496	/* Invert Input Signal */
497	WRITE(sc, AW_IR_RXCTL, AW_IR_RXCTL_RPPI);
498
499	/* Clear All RX Interrupt Status */
500	WRITE(sc, AW_IR_RXSTA, AW_IR_RXSTA_CLEARALL);
501
502	/*
503	 * Enable RX interrupt in case of overflow, packet end
504	 * and FIFO available.
505	 * RX FIFO Threshold = FIFO size / 2
506	 */
507	WRITE(sc, AW_IR_RXINT, AW_IR_RXINT_ROI_EN | AW_IR_RXINT_RPEI_EN |
508	    AW_IR_RXINT_RAI_EN | AW_IR_RXINT_RAL((sc->fifo_size >> 1) - 1));
509
510	/* Enable IR Module */
511	val = READ(sc, AW_IR_CTL);
512	WRITE(sc, AW_IR_CTL, val | AW_IR_CTL_GEN | AW_IR_CTL_RXEN);
513
514	sc->sc_evdev = evdev_alloc();
515	evdev_set_name(sc->sc_evdev, device_get_desc(sc->dev));
516	evdev_set_phys(sc->sc_evdev, device_get_nameunit(sc->dev));
517	evdev_set_id(sc->sc_evdev, BUS_HOST, 0, 0, 0);
518	evdev_support_event(sc->sc_evdev, EV_SYN);
519	evdev_support_event(sc->sc_evdev, EV_MSC);
520	evdev_support_msc(sc->sc_evdev, MSC_SCAN);
521
522	err = evdev_register(sc->sc_evdev);
523	if (err) {
524		device_printf(dev,
525		    "failed to register evdev: error=%d\n", err);
526		goto error;
527	}
528
529	return (0);
530error:
531	if (clk_gate != NULL)
532		clk_release(clk_gate);
533	if (clk_ir != NULL)
534		clk_release(clk_ir);
535	if (rst_apb != NULL)
536		hwreset_release(rst_apb);
537	evdev_free(sc->sc_evdev);
538	sc->sc_evdev = NULL;	/* Avoid double free */
539
540	bus_release_resources(dev, aw_ir_spec, sc->res);
541	return (ENXIO);
542}
543
544static device_method_t aw_ir_methods[] = {
545	DEVMETHOD(device_probe, aw_ir_probe),
546	DEVMETHOD(device_attach, aw_ir_attach),
547
548	DEVMETHOD_END
549};
550
551static driver_t aw_ir_driver = {
552	"aw_ir",
553	aw_ir_methods,
554	sizeof(struct aw_ir_softc),
555};
556
557DRIVER_MODULE(aw_ir, simplebus, aw_ir_driver, 0, 0);
558MODULE_DEPEND(aw_ir, evdev, 1, 1, 1);
559