1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * STMicroelectronics sensors buffer library driver
4 *
5 * Copyright 2012-2013 STMicroelectronics Inc.
6 *
7 * Denis Ciocca <denis.ciocca@st.com>
8 */
9
10#include <linux/kernel.h>
11#include <linux/iio/iio.h>
12#include <linux/iio/trigger.h>
13#include <linux/interrupt.h>
14#include <linux/iio/buffer.h>
15#include <linux/iio/trigger_consumer.h>
16#include <linux/irqreturn.h>
17#include <linux/regmap.h>
18
19#include <linux/iio/common/st_sensors.h>
20
21
22static int st_sensors_get_buffer_element(struct iio_dev *indio_dev, u8 *buf)
23{
24	struct st_sensor_data *sdata = iio_priv(indio_dev);
25	unsigned int num_data_channels = sdata->num_data_channels;
26	int i;
27
28	for_each_set_bit(i, indio_dev->active_scan_mask, num_data_channels) {
29		const struct iio_chan_spec *channel = &indio_dev->channels[i];
30		unsigned int bytes_to_read =
31			DIV_ROUND_UP(channel->scan_type.realbits +
32				     channel->scan_type.shift, 8);
33		unsigned int storage_bytes =
34			channel->scan_type.storagebits >> 3;
35
36		buf = PTR_ALIGN(buf, storage_bytes);
37		if (regmap_bulk_read(sdata->regmap, channel->address,
38				     buf, bytes_to_read) < 0)
39			return -EIO;
40
41		/* Advance the buffer pointer */
42		buf += storage_bytes;
43	}
44
45	return 0;
46}
47
48irqreturn_t st_sensors_trigger_handler(int irq, void *p)
49{
50	int len;
51	struct iio_poll_func *pf = p;
52	struct iio_dev *indio_dev = pf->indio_dev;
53	struct st_sensor_data *sdata = iio_priv(indio_dev);
54	s64 timestamp;
55
56	/*
57	 * If we do timestamping here, do it before reading the values, because
58	 * once we've read the values, new interrupts can occur (when using
59	 * the hardware trigger) and the hw_timestamp may get updated.
60	 * By storing it in a local variable first, we are safe.
61	 */
62	if (iio_trigger_using_own(indio_dev))
63		timestamp = sdata->hw_timestamp;
64	else
65		timestamp = iio_get_time_ns(indio_dev);
66
67	len = st_sensors_get_buffer_element(indio_dev, sdata->buffer_data);
68	if (len < 0)
69		goto st_sensors_get_buffer_element_error;
70
71	iio_push_to_buffers_with_timestamp(indio_dev, sdata->buffer_data,
72					   timestamp);
73
74st_sensors_get_buffer_element_error:
75	iio_trigger_notify_done(indio_dev->trig);
76
77	return IRQ_HANDLED;
78}
79EXPORT_SYMBOL_NS(st_sensors_trigger_handler, IIO_ST_SENSORS);
80