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