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