xref: /openbmc/linux/drivers/iio/adc/ti-tsc2046.c (revision dff03381)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Texas Instruments TSC2046 SPI ADC driver
4  *
5  * Copyright (c) 2021 Oleksij Rempel <kernel@pengutronix.de>, Pengutronix
6  */
7 
8 #include <linux/bitfield.h>
9 #include <linux/delay.h>
10 #include <linux/module.h>
11 #include <linux/spi/spi.h>
12 
13 #include <asm/unaligned.h>
14 
15 #include <linux/iio/buffer.h>
16 #include <linux/iio/trigger_consumer.h>
17 #include <linux/iio/triggered_buffer.h>
18 #include <linux/iio/trigger.h>
19 
20 /*
21  * The PENIRQ of TSC2046 controller is implemented as level shifter attached to
22  * the X+ line. If voltage of the X+ line reaches a specific level the IRQ will
23  * be activated or deactivated.
24  * To make this kind of IRQ reusable as trigger following additions were
25  * implemented:
26  * - rate limiting:
27  *   For typical touchscreen use case, we need to trigger about each 10ms.
28  * - hrtimer:
29  *   Continue triggering at least once after the IRQ was deactivated. Then
30  *   deactivate this trigger to stop sampling in order to reduce power
31  *   consumption.
32  */
33 
34 #define TI_TSC2046_NAME				"tsc2046"
35 
36 /* This driver doesn't aim at the peak continuous sample rate */
37 #define	TI_TSC2046_MAX_SAMPLE_RATE		125000
38 #define	TI_TSC2046_SAMPLE_BITS \
39 	BITS_PER_TYPE(struct tsc2046_adc_atom)
40 #define	TI_TSC2046_MAX_CLK_FREQ \
41 	(TI_TSC2046_MAX_SAMPLE_RATE * TI_TSC2046_SAMPLE_BITS)
42 
43 #define TI_TSC2046_SAMPLE_INTERVAL_US		10000
44 
45 #define TI_TSC2046_START			BIT(7)
46 #define TI_TSC2046_ADDR				GENMASK(6, 4)
47 #define TI_TSC2046_ADDR_TEMP1			7
48 #define TI_TSC2046_ADDR_AUX			6
49 #define TI_TSC2046_ADDR_X			5
50 #define TI_TSC2046_ADDR_Z2			4
51 #define TI_TSC2046_ADDR_Z1			3
52 #define TI_TSC2046_ADDR_VBAT			2
53 #define TI_TSC2046_ADDR_Y			1
54 #define TI_TSC2046_ADDR_TEMP0			0
55 
56 /*
57  * The mode bit sets the resolution of the ADC. With this bit low, the next
58  * conversion has 12-bit resolution, whereas with this bit high, the next
59  * conversion has 8-bit resolution. This driver is optimized for 12-bit mode.
60  * So, for this driver, this bit should stay zero.
61  */
62 #define TI_TSC2046_8BIT_MODE			BIT(3)
63 
64 /*
65  * SER/DFR - The SER/DFR bit controls the reference mode, either single-ended
66  * (high) or differential (low).
67  */
68 #define TI_TSC2046_SER				BIT(2)
69 
70 /*
71  * If VREF_ON and ADC_ON are both zero, then the chip operates in
72  * auto-wake/suspend mode. In most case this bits should stay zero.
73  */
74 #define TI_TSC2046_PD1_VREF_ON			BIT(1)
75 #define TI_TSC2046_PD0_ADC_ON			BIT(0)
76 
77 /*
78  * All supported devices can do 8 or 12bit resolution. This driver
79  * supports only 12bit mode, here we have a 16bit data transfer, where
80  * the MSB and the 3 LSB are 0.
81  */
82 #define TI_TSC2046_DATA_12BIT			GENMASK(14, 3)
83 
84 #define TI_TSC2046_MAX_CHAN			8
85 #define TI_TSC2046_MIN_POLL_CNT			3
86 #define TI_TSC2046_EXT_POLL_CNT			3
87 #define TI_TSC2046_POLL_CNT \
88 	(TI_TSC2046_MIN_POLL_CNT + TI_TSC2046_EXT_POLL_CNT)
89 #define TI_TSC2046_INT_VREF			2500
90 
91 /* Represents a HW sample */
92 struct tsc2046_adc_atom {
93 	/*
94 	 * Command transmitted to the controller. This field is empty on the RX
95 	 * buffer.
96 	 */
97 	u8 cmd;
98 	/*
99 	 * Data received from the controller. This field is empty for the TX
100 	 * buffer
101 	 */
102 	__be16 data;
103 } __packed;
104 
105 /* Layout of atomic buffers within big buffer */
106 struct tsc2046_adc_group_layout {
107 	/* Group offset within the SPI RX buffer */
108 	unsigned int offset;
109 	/*
110 	 * Amount of tsc2046_adc_atom structs within the same command gathered
111 	 * within same group.
112 	 */
113 	unsigned int count;
114 	/*
115 	 * Settling samples (tsc2046_adc_atom structs) which should be skipped
116 	 * before good samples will start.
117 	 */
118 	unsigned int skip;
119 };
120 
121 struct tsc2046_adc_dcfg {
122 	const struct iio_chan_spec *channels;
123 	unsigned int num_channels;
124 };
125 
126 struct tsc2046_adc_ch_cfg {
127 	unsigned int settling_time_us;
128 	unsigned int oversampling_ratio;
129 };
130 
131 enum tsc2046_state {
132 	TSC2046_STATE_SHUTDOWN,
133 	TSC2046_STATE_STANDBY,
134 	TSC2046_STATE_POLL,
135 	TSC2046_STATE_POLL_IRQ_DISABLE,
136 	TSC2046_STATE_ENABLE_IRQ,
137 };
138 
139 struct tsc2046_adc_priv {
140 	struct spi_device *spi;
141 	const struct tsc2046_adc_dcfg *dcfg;
142 
143 	struct iio_trigger *trig;
144 	struct hrtimer trig_timer;
145 	enum tsc2046_state state;
146 	int poll_cnt;
147 	spinlock_t state_lock;
148 
149 	struct spi_transfer xfer;
150 	struct spi_message msg;
151 
152 	struct {
153 		/* Scan data for each channel */
154 		u16 data[TI_TSC2046_MAX_CHAN];
155 		/* Timestamp */
156 		s64 ts __aligned(8);
157 	} scan_buf;
158 
159 	/*
160 	 * Lock to protect the layout and the SPI transfer buffer.
161 	 * tsc2046_adc_group_layout can be changed within update_scan_mode(),
162 	 * in this case the l[] and tx/rx buffer will be out of sync to each
163 	 * other.
164 	 */
165 	struct mutex slock;
166 	struct tsc2046_adc_group_layout l[TI_TSC2046_MAX_CHAN];
167 	struct tsc2046_adc_atom *rx;
168 	struct tsc2046_adc_atom *tx;
169 
170 	unsigned int count;
171 	unsigned int groups;
172 	u32 effective_speed_hz;
173 	u32 scan_interval_us;
174 	u32 time_per_scan_us;
175 	u32 time_per_bit_ns;
176 
177 	struct tsc2046_adc_ch_cfg ch_cfg[TI_TSC2046_MAX_CHAN];
178 };
179 
180 #define TI_TSC2046_V_CHAN(index, bits, name)			\
181 {								\
182 	.type = IIO_VOLTAGE,					\
183 	.indexed = 1,						\
184 	.channel = index,					\
185 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
186 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),	\
187 	.datasheet_name = "#name",				\
188 	.scan_index = index,					\
189 	.scan_type = {						\
190 		.sign = 'u',					\
191 		.realbits = bits,				\
192 		.storagebits = 16,				\
193 		.endianness = IIO_CPU,				\
194 	},							\
195 }
196 
197 #define DECLARE_TI_TSC2046_8_CHANNELS(name, bits) \
198 const struct iio_chan_spec name ## _channels[] = { \
199 	TI_TSC2046_V_CHAN(0, bits, TEMP0), \
200 	TI_TSC2046_V_CHAN(1, bits, Y), \
201 	TI_TSC2046_V_CHAN(2, bits, VBAT), \
202 	TI_TSC2046_V_CHAN(3, bits, Z1), \
203 	TI_TSC2046_V_CHAN(4, bits, Z2), \
204 	TI_TSC2046_V_CHAN(5, bits, X), \
205 	TI_TSC2046_V_CHAN(6, bits, AUX), \
206 	TI_TSC2046_V_CHAN(7, bits, TEMP1), \
207 	IIO_CHAN_SOFT_TIMESTAMP(8), \
208 }
209 
210 static DECLARE_TI_TSC2046_8_CHANNELS(tsc2046_adc, 12);
211 
212 static const struct tsc2046_adc_dcfg tsc2046_adc_dcfg_tsc2046e = {
213 	.channels = tsc2046_adc_channels,
214 	.num_channels = ARRAY_SIZE(tsc2046_adc_channels),
215 };
216 
217 /*
218  * Convert time to a number of samples which can be transferred within this
219  * time.
220  */
221 static unsigned int tsc2046_adc_time_to_count(struct tsc2046_adc_priv *priv,
222 					      unsigned long time)
223 {
224 	unsigned int bit_count, sample_count;
225 
226 	bit_count = DIV_ROUND_UP(time * NSEC_PER_USEC, priv->time_per_bit_ns);
227 	sample_count = DIV_ROUND_UP(bit_count, TI_TSC2046_SAMPLE_BITS);
228 
229 	dev_dbg(&priv->spi->dev, "Effective speed %u, time per bit: %u, count bits: %u, count samples: %u\n",
230 		priv->effective_speed_hz, priv->time_per_bit_ns,
231 		bit_count, sample_count);
232 
233 	return sample_count;
234 }
235 
236 static u8 tsc2046_adc_get_cmd(struct tsc2046_adc_priv *priv, int ch_idx,
237 			      bool keep_power)
238 {
239 	u32 pd;
240 
241 	/*
242 	 * if PD bits are 0, controller will automatically disable ADC, VREF and
243 	 * enable IRQ.
244 	 */
245 	if (keep_power)
246 		pd = TI_TSC2046_PD0_ADC_ON;
247 	else
248 		pd = 0;
249 
250 	switch (ch_idx) {
251 	case TI_TSC2046_ADDR_TEMP1:
252 	case TI_TSC2046_ADDR_AUX:
253 	case TI_TSC2046_ADDR_VBAT:
254 	case TI_TSC2046_ADDR_TEMP0:
255 		pd |= TI_TSC2046_SER | TI_TSC2046_PD1_VREF_ON;
256 	}
257 
258 	return TI_TSC2046_START | FIELD_PREP(TI_TSC2046_ADDR, ch_idx) | pd;
259 }
260 
261 static u16 tsc2046_adc_get_value(struct tsc2046_adc_atom *buf)
262 {
263 	return FIELD_GET(TI_TSC2046_DATA_12BIT, get_unaligned_be16(&buf->data));
264 }
265 
266 static int tsc2046_adc_read_one(struct tsc2046_adc_priv *priv, int ch_idx,
267 				u32 *effective_speed_hz)
268 {
269 	struct tsc2046_adc_ch_cfg *ch = &priv->ch_cfg[ch_idx];
270 	struct tsc2046_adc_atom *rx_buf, *tx_buf;
271 	unsigned int val, val_normalized = 0;
272 	int ret, i, count_skip = 0, max_count;
273 	struct spi_transfer xfer;
274 	struct spi_message msg;
275 	u8 cmd;
276 
277 	if (!effective_speed_hz) {
278 		count_skip = tsc2046_adc_time_to_count(priv, ch->settling_time_us);
279 		max_count = count_skip + ch->oversampling_ratio;
280 	} else {
281 		max_count = 1;
282 	}
283 
284 	if (sizeof(*tx_buf) * max_count > PAGE_SIZE)
285 		return -ENOSPC;
286 
287 	tx_buf = kcalloc(max_count, sizeof(*tx_buf), GFP_KERNEL);
288 	if (!tx_buf)
289 		return -ENOMEM;
290 
291 	rx_buf = kcalloc(max_count, sizeof(*rx_buf), GFP_KERNEL);
292 	if (!rx_buf) {
293 		ret = -ENOMEM;
294 		goto free_tx;
295 	}
296 
297 	/*
298 	 * Do not enable automatic power down on working samples. Otherwise the
299 	 * plates will never be completely charged.
300 	 */
301 	cmd = tsc2046_adc_get_cmd(priv, ch_idx, true);
302 
303 	for (i = 0; i < max_count - 1; i++)
304 		tx_buf[i].cmd = cmd;
305 
306 	/* automatically power down on last sample */
307 	tx_buf[i].cmd = tsc2046_adc_get_cmd(priv, ch_idx, false);
308 
309 	memset(&xfer, 0, sizeof(xfer));
310 	xfer.tx_buf = tx_buf;
311 	xfer.rx_buf = rx_buf;
312 	xfer.len = sizeof(*tx_buf) * max_count;
313 	spi_message_init_with_transfers(&msg, &xfer, 1);
314 
315 	/*
316 	 * We aren't using spi_write_then_read() because we need to be able
317 	 * to get hold of the effective_speed_hz from the xfer
318 	 */
319 	ret = spi_sync(priv->spi, &msg);
320 	if (ret) {
321 		dev_err_ratelimited(&priv->spi->dev, "SPI transfer failed %pe\n",
322 				    ERR_PTR(ret));
323 		goto free_bufs;
324 	}
325 
326 	if (effective_speed_hz)
327 		*effective_speed_hz = xfer.effective_speed_hz;
328 
329 	for (i = 0; i < max_count - count_skip; i++) {
330 		val = tsc2046_adc_get_value(&rx_buf[count_skip + i]);
331 		val_normalized += val;
332 	}
333 
334 	ret = DIV_ROUND_UP(val_normalized, max_count - count_skip);
335 
336 free_bufs:
337 	kfree(rx_buf);
338 free_tx:
339 	kfree(tx_buf);
340 
341 	return ret;
342 }
343 
344 static size_t tsc2046_adc_group_set_layout(struct tsc2046_adc_priv *priv,
345 					   unsigned int group,
346 					   unsigned int ch_idx)
347 {
348 	struct tsc2046_adc_ch_cfg *ch = &priv->ch_cfg[ch_idx];
349 	struct tsc2046_adc_group_layout *cur;
350 	unsigned int max_count, count_skip;
351 	unsigned int offset = 0;
352 
353 	if (group)
354 		offset = priv->l[group - 1].offset + priv->l[group - 1].count;
355 
356 	count_skip = tsc2046_adc_time_to_count(priv, ch->settling_time_us);
357 	max_count = count_skip + ch->oversampling_ratio;
358 
359 	cur = &priv->l[group];
360 	cur->offset = offset;
361 	cur->count = max_count;
362 	cur->skip = count_skip;
363 
364 	return sizeof(*priv->tx) * max_count;
365 }
366 
367 static void tsc2046_adc_group_set_cmd(struct tsc2046_adc_priv *priv,
368 				      unsigned int group, int ch_idx)
369 {
370 	struct tsc2046_adc_group_layout *l = &priv->l[group];
371 	unsigned int i;
372 	u8 cmd;
373 
374 	/*
375 	 * Do not enable automatic power down on working samples. Otherwise the
376 	 * plates will never be completely charged.
377 	 */
378 	cmd = tsc2046_adc_get_cmd(priv, ch_idx, true);
379 
380 	for (i = 0; i < l->count - 1; i++)
381 		priv->tx[l->offset + i].cmd = cmd;
382 
383 	/* automatically power down on last sample */
384 	priv->tx[l->offset + i].cmd = tsc2046_adc_get_cmd(priv, ch_idx, false);
385 }
386 
387 static u16 tsc2046_adc_get_val(struct tsc2046_adc_priv *priv, int group)
388 {
389 	struct tsc2046_adc_group_layout *l;
390 	unsigned int val, val_normalized = 0;
391 	int valid_count, i;
392 
393 	l = &priv->l[group];
394 	valid_count = l->count - l->skip;
395 
396 	for (i = 0; i < valid_count; i++) {
397 		val = tsc2046_adc_get_value(&priv->rx[l->offset + l->skip + i]);
398 		val_normalized += val;
399 	}
400 
401 	return DIV_ROUND_UP(val_normalized, valid_count);
402 }
403 
404 static int tsc2046_adc_scan(struct iio_dev *indio_dev)
405 {
406 	struct tsc2046_adc_priv *priv = iio_priv(indio_dev);
407 	struct device *dev = &priv->spi->dev;
408 	int group;
409 	int ret;
410 
411 	ret = spi_sync(priv->spi, &priv->msg);
412 	if (ret < 0) {
413 		dev_err_ratelimited(dev, "SPI transfer failed: %pe\n", ERR_PTR(ret));
414 		return ret;
415 	}
416 
417 	for (group = 0; group < priv->groups; group++)
418 		priv->scan_buf.data[group] = tsc2046_adc_get_val(priv, group);
419 
420 	ret = iio_push_to_buffers_with_timestamp(indio_dev, &priv->scan_buf,
421 						 iio_get_time_ns(indio_dev));
422 	/* If the consumer is kfifo, we may get a EBUSY here - ignore it. */
423 	if (ret < 0 && ret != -EBUSY) {
424 		dev_err_ratelimited(dev, "Failed to push scan buffer %pe\n",
425 				    ERR_PTR(ret));
426 
427 		return ret;
428 	}
429 
430 	return 0;
431 }
432 
433 static irqreturn_t tsc2046_adc_trigger_handler(int irq, void *p)
434 {
435 	struct iio_poll_func *pf = p;
436 	struct iio_dev *indio_dev = pf->indio_dev;
437 	struct tsc2046_adc_priv *priv = iio_priv(indio_dev);
438 
439 	mutex_lock(&priv->slock);
440 	tsc2046_adc_scan(indio_dev);
441 	mutex_unlock(&priv->slock);
442 
443 	iio_trigger_notify_done(indio_dev->trig);
444 
445 	return IRQ_HANDLED;
446 }
447 
448 static int tsc2046_adc_read_raw(struct iio_dev *indio_dev,
449 				struct iio_chan_spec const *chan,
450 				int *val, int *val2, long m)
451 {
452 	struct tsc2046_adc_priv *priv = iio_priv(indio_dev);
453 	int ret;
454 
455 	switch (m) {
456 	case IIO_CHAN_INFO_RAW:
457 		ret = tsc2046_adc_read_one(priv, chan->channel, NULL);
458 		if (ret < 0)
459 			return ret;
460 
461 		*val = ret;
462 
463 		return IIO_VAL_INT;
464 	case IIO_CHAN_INFO_SCALE:
465 		/*
466 		 * Note: the TSC2046 has internal voltage divider on the VBAT
467 		 * line. This divider can be influenced by external divider.
468 		 * So, it is better to use external voltage-divider driver
469 		 * instead, which is calculating complete chain.
470 		 */
471 		*val = TI_TSC2046_INT_VREF;
472 		*val2 = chan->scan_type.realbits;
473 		return IIO_VAL_FRACTIONAL_LOG2;
474 	}
475 
476 	return -EINVAL;
477 }
478 
479 static int tsc2046_adc_update_scan_mode(struct iio_dev *indio_dev,
480 					const unsigned long *active_scan_mask)
481 {
482 	struct tsc2046_adc_priv *priv = iio_priv(indio_dev);
483 	unsigned int ch_idx, group = 0;
484 	size_t size;
485 
486 	mutex_lock(&priv->slock);
487 
488 	size = 0;
489 	for_each_set_bit(ch_idx, active_scan_mask, ARRAY_SIZE(priv->l)) {
490 		size += tsc2046_adc_group_set_layout(priv, group, ch_idx);
491 		tsc2046_adc_group_set_cmd(priv, group, ch_idx);
492 		group++;
493 	}
494 
495 	priv->groups = group;
496 	priv->xfer.len = size;
497 	priv->time_per_scan_us = size * 8 * priv->time_per_bit_ns / NSEC_PER_USEC;
498 
499 	if (priv->scan_interval_us < priv->time_per_scan_us)
500 		dev_warn(&priv->spi->dev, "The scan interval (%d) is less then calculated scan time (%d)\n",
501 			 priv->scan_interval_us, priv->time_per_scan_us);
502 
503 	mutex_unlock(&priv->slock);
504 
505 	return 0;
506 }
507 
508 static const struct iio_info tsc2046_adc_info = {
509 	.read_raw	  = tsc2046_adc_read_raw,
510 	.update_scan_mode = tsc2046_adc_update_scan_mode,
511 };
512 
513 static enum hrtimer_restart tsc2046_adc_timer(struct hrtimer *hrtimer)
514 {
515 	struct tsc2046_adc_priv *priv = container_of(hrtimer,
516 						     struct tsc2046_adc_priv,
517 						     trig_timer);
518 	unsigned long flags;
519 
520 	/*
521 	 * This state machine should address following challenges :
522 	 * - the interrupt source is based on level shifter attached to the X
523 	 *   channel of ADC. It will change the state every time we switch
524 	 *   between channels. So, we need to disable IRQ if we do
525 	 *   iio_trigger_poll().
526 	 * - we should do iio_trigger_poll() at some reduced sample rate
527 	 * - we should still trigger for some amount of time after last
528 	 *   interrupt with enabled IRQ was processed.
529 	 */
530 
531 	spin_lock_irqsave(&priv->state_lock, flags);
532 	switch (priv->state) {
533 	case TSC2046_STATE_ENABLE_IRQ:
534 		if (priv->poll_cnt < TI_TSC2046_POLL_CNT) {
535 			priv->poll_cnt++;
536 			hrtimer_start(&priv->trig_timer,
537 				      ns_to_ktime(priv->scan_interval_us *
538 						  NSEC_PER_USEC),
539 				      HRTIMER_MODE_REL_SOFT);
540 
541 			if (priv->poll_cnt >= TI_TSC2046_MIN_POLL_CNT) {
542 				priv->state = TSC2046_STATE_POLL_IRQ_DISABLE;
543 				enable_irq(priv->spi->irq);
544 			} else {
545 				priv->state = TSC2046_STATE_POLL;
546 			}
547 		} else {
548 			priv->state = TSC2046_STATE_STANDBY;
549 			enable_irq(priv->spi->irq);
550 		}
551 		break;
552 	case TSC2046_STATE_POLL_IRQ_DISABLE:
553 		disable_irq_nosync(priv->spi->irq);
554 		fallthrough;
555 	case TSC2046_STATE_POLL:
556 		priv->state = TSC2046_STATE_ENABLE_IRQ;
557 		/* iio_trigger_poll() starts hrtimer */
558 		iio_trigger_poll(priv->trig);
559 		break;
560 	case TSC2046_STATE_SHUTDOWN:
561 		break;
562 	case TSC2046_STATE_STANDBY:
563 		fallthrough;
564 	default:
565 		dev_warn(&priv->spi->dev, "Got unexpected state: %i\n",
566 			 priv->state);
567 		break;
568 	}
569 	spin_unlock_irqrestore(&priv->state_lock, flags);
570 
571 	return HRTIMER_NORESTART;
572 }
573 
574 static irqreturn_t tsc2046_adc_irq(int irq, void *dev_id)
575 {
576 	struct iio_dev *indio_dev = dev_id;
577 	struct tsc2046_adc_priv *priv = iio_priv(indio_dev);
578 	unsigned long flags;
579 
580 	hrtimer_try_to_cancel(&priv->trig_timer);
581 
582 	spin_lock_irqsave(&priv->state_lock, flags);
583 	if (priv->state != TSC2046_STATE_SHUTDOWN) {
584 		priv->state = TSC2046_STATE_ENABLE_IRQ;
585 		priv->poll_cnt = 0;
586 
587 		/* iio_trigger_poll() starts hrtimer */
588 		disable_irq_nosync(priv->spi->irq);
589 		iio_trigger_poll(priv->trig);
590 	}
591 	spin_unlock_irqrestore(&priv->state_lock, flags);
592 
593 	return IRQ_HANDLED;
594 }
595 
596 static void tsc2046_adc_reenable_trigger(struct iio_trigger *trig)
597 {
598 	struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig);
599 	struct tsc2046_adc_priv *priv = iio_priv(indio_dev);
600 	ktime_t tim;
601 
602 	/*
603 	 * We can sample it as fast as we can, but usually we do not need so
604 	 * many samples. Reduce the sample rate for default (touchscreen) use
605 	 * case.
606 	 */
607 	tim = ns_to_ktime((priv->scan_interval_us - priv->time_per_scan_us) *
608 			  NSEC_PER_USEC);
609 	hrtimer_start(&priv->trig_timer, tim, HRTIMER_MODE_REL_SOFT);
610 }
611 
612 static int tsc2046_adc_set_trigger_state(struct iio_trigger *trig, bool enable)
613 {
614 	struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig);
615 	struct tsc2046_adc_priv *priv = iio_priv(indio_dev);
616 	unsigned long flags;
617 
618 	if (enable) {
619 		spin_lock_irqsave(&priv->state_lock, flags);
620 		if (priv->state == TSC2046_STATE_SHUTDOWN) {
621 			priv->state = TSC2046_STATE_STANDBY;
622 			enable_irq(priv->spi->irq);
623 		}
624 		spin_unlock_irqrestore(&priv->state_lock, flags);
625 	} else {
626 		spin_lock_irqsave(&priv->state_lock, flags);
627 
628 		if (priv->state == TSC2046_STATE_STANDBY ||
629 		    priv->state == TSC2046_STATE_POLL_IRQ_DISABLE)
630 			disable_irq_nosync(priv->spi->irq);
631 
632 		priv->state = TSC2046_STATE_SHUTDOWN;
633 		spin_unlock_irqrestore(&priv->state_lock, flags);
634 
635 		hrtimer_cancel(&priv->trig_timer);
636 	}
637 
638 	return 0;
639 }
640 
641 static const struct iio_trigger_ops tsc2046_adc_trigger_ops = {
642 	.set_trigger_state = tsc2046_adc_set_trigger_state,
643 	.reenable = tsc2046_adc_reenable_trigger,
644 };
645 
646 static int tsc2046_adc_setup_spi_msg(struct tsc2046_adc_priv *priv)
647 {
648 	unsigned int ch_idx;
649 	size_t size;
650 	int ret;
651 
652 	/*
653 	 * Make dummy read to set initial power state and get real SPI clock
654 	 * freq. It seems to be not important which channel is used for this
655 	 * case.
656 	 */
657 	ret = tsc2046_adc_read_one(priv, TI_TSC2046_ADDR_TEMP0,
658 				   &priv->effective_speed_hz);
659 	if (ret < 0)
660 		return ret;
661 
662 	/*
663 	 * In case SPI controller do not report effective_speed_hz, use
664 	 * configure value and hope it will match.
665 	 */
666 	if (!priv->effective_speed_hz)
667 		priv->effective_speed_hz = priv->spi->max_speed_hz;
668 
669 
670 	priv->scan_interval_us = TI_TSC2046_SAMPLE_INTERVAL_US;
671 	priv->time_per_bit_ns = DIV_ROUND_UP(NSEC_PER_SEC,
672 					     priv->effective_speed_hz);
673 
674 	/*
675 	 * Calculate and allocate maximal size buffer if all channels are
676 	 * enabled.
677 	 */
678 	size = 0;
679 	for (ch_idx = 0; ch_idx < ARRAY_SIZE(priv->l); ch_idx++)
680 		size += tsc2046_adc_group_set_layout(priv, ch_idx, ch_idx);
681 
682 	if (size > PAGE_SIZE) {
683 		dev_err(&priv->spi->dev,
684 			"Calculated scan buffer is too big. Try to reduce spi-max-frequency, settling-time-us or oversampling-ratio\n");
685 		return -ENOSPC;
686 	}
687 
688 	priv->tx = devm_kzalloc(&priv->spi->dev, size, GFP_KERNEL);
689 	if (!priv->tx)
690 		return -ENOMEM;
691 
692 	priv->rx = devm_kzalloc(&priv->spi->dev, size, GFP_KERNEL);
693 	if (!priv->rx)
694 		return -ENOMEM;
695 
696 	priv->xfer.tx_buf = priv->tx;
697 	priv->xfer.rx_buf = priv->rx;
698 	priv->xfer.len = size;
699 	spi_message_init_with_transfers(&priv->msg, &priv->xfer, 1);
700 
701 	return 0;
702 }
703 
704 static void tsc2046_adc_parse_fwnode(struct tsc2046_adc_priv *priv)
705 {
706 	struct fwnode_handle *child;
707 	struct device *dev = &priv->spi->dev;
708 	unsigned int i;
709 
710 	for (i = 0; i < ARRAY_SIZE(priv->ch_cfg); i++) {
711 		priv->ch_cfg[i].settling_time_us = 1;
712 		priv->ch_cfg[i].oversampling_ratio = 1;
713 	}
714 
715 	device_for_each_child_node(dev, child) {
716 		u32 stl, overs, reg;
717 		int ret;
718 
719 		ret = fwnode_property_read_u32(child, "reg", &reg);
720 		if (ret) {
721 			dev_err(dev, "invalid reg on %pfw, err: %pe\n", child,
722 				ERR_PTR(ret));
723 			continue;
724 		}
725 
726 		if (reg >= ARRAY_SIZE(priv->ch_cfg)) {
727 			dev_err(dev, "%pfw: Unsupported reg value: %i, max supported is: %zu.\n",
728 				child, reg, ARRAY_SIZE(priv->ch_cfg));
729 			continue;
730 		}
731 
732 		ret = fwnode_property_read_u32(child, "settling-time-us", &stl);
733 		if (!ret)
734 			priv->ch_cfg[reg].settling_time_us = stl;
735 
736 		ret = fwnode_property_read_u32(child, "oversampling-ratio",
737 					       &overs);
738 		if (!ret)
739 			priv->ch_cfg[reg].oversampling_ratio = overs;
740 	}
741 }
742 
743 static int tsc2046_adc_probe(struct spi_device *spi)
744 {
745 	const struct tsc2046_adc_dcfg *dcfg;
746 	struct device *dev = &spi->dev;
747 	struct tsc2046_adc_priv *priv;
748 	struct iio_dev *indio_dev;
749 	struct iio_trigger *trig;
750 	int ret;
751 
752 	if (spi->max_speed_hz > TI_TSC2046_MAX_CLK_FREQ) {
753 		dev_err(dev, "SPI max_speed_hz is too high: %d Hz. Max supported freq is %zu Hz\n",
754 			spi->max_speed_hz, TI_TSC2046_MAX_CLK_FREQ);
755 		return -EINVAL;
756 	}
757 
758 	dcfg = device_get_match_data(dev);
759 	if (!dcfg)
760 		return -EINVAL;
761 
762 	spi->bits_per_word = 8;
763 	spi->mode &= ~SPI_MODE_X_MASK;
764 	spi->mode |= SPI_MODE_0;
765 	ret = spi_setup(spi);
766 	if (ret < 0)
767 		return dev_err_probe(dev, ret, "Error in SPI setup\n");
768 
769 	indio_dev = devm_iio_device_alloc(dev, sizeof(*priv));
770 	if (!indio_dev)
771 		return -ENOMEM;
772 
773 	priv = iio_priv(indio_dev);
774 	priv->dcfg = dcfg;
775 
776 	priv->spi = spi;
777 
778 	indio_dev->name = TI_TSC2046_NAME;
779 	indio_dev->modes = INDIO_DIRECT_MODE;
780 	indio_dev->channels = dcfg->channels;
781 	indio_dev->num_channels = dcfg->num_channels;
782 	indio_dev->info = &tsc2046_adc_info;
783 
784 	tsc2046_adc_parse_fwnode(priv);
785 
786 	ret = tsc2046_adc_setup_spi_msg(priv);
787 	if (ret)
788 		return ret;
789 
790 	mutex_init(&priv->slock);
791 
792 	ret = devm_request_irq(dev, spi->irq, &tsc2046_adc_irq,
793 			       IRQF_NO_AUTOEN, indio_dev->name, indio_dev);
794 	if (ret)
795 		return ret;
796 
797 	trig = devm_iio_trigger_alloc(dev, "touchscreen-%s", indio_dev->name);
798 	if (!trig)
799 		return -ENOMEM;
800 
801 	priv->trig = trig;
802 	iio_trigger_set_drvdata(trig, indio_dev);
803 	trig->ops = &tsc2046_adc_trigger_ops;
804 
805 	spin_lock_init(&priv->state_lock);
806 	priv->state = TSC2046_STATE_SHUTDOWN;
807 	hrtimer_init(&priv->trig_timer, CLOCK_MONOTONIC,
808 		     HRTIMER_MODE_REL_SOFT);
809 	priv->trig_timer.function = tsc2046_adc_timer;
810 
811 	ret = devm_iio_trigger_register(dev, trig);
812 	if (ret) {
813 		dev_err(dev, "failed to register trigger\n");
814 		return ret;
815 	}
816 
817 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev, NULL,
818 					      &tsc2046_adc_trigger_handler, NULL);
819 	if (ret) {
820 		dev_err(dev, "Failed to setup triggered buffer\n");
821 		return ret;
822 	}
823 
824 	/* set default trigger */
825 	indio_dev->trig = iio_trigger_get(priv->trig);
826 
827 	return devm_iio_device_register(dev, indio_dev);
828 }
829 
830 static const struct of_device_id ads7950_of_table[] = {
831 	{ .compatible = "ti,tsc2046e-adc", .data = &tsc2046_adc_dcfg_tsc2046e },
832 	{ }
833 };
834 MODULE_DEVICE_TABLE(of, ads7950_of_table);
835 
836 static struct spi_driver tsc2046_adc_driver = {
837 	.driver = {
838 		.name = "tsc2046",
839 		.of_match_table = ads7950_of_table,
840 	},
841 	.probe = tsc2046_adc_probe,
842 };
843 module_spi_driver(tsc2046_adc_driver);
844 
845 MODULE_AUTHOR("Oleksij Rempel <kernel@pengutronix.de>");
846 MODULE_DESCRIPTION("TI TSC2046 ADC");
847 MODULE_LICENSE("GPL v2");
848