1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * STMicroelectronics gyroscopes driver
4  *
5  * Copyright 2012-2013 STMicroelectronics Inc.
6  *
7  * Denis Ciocca <denis.ciocca@st.com>
8  */
9 
10 #include <linux/module.h>
11 #include <linux/kernel.h>
12 #include <linux/slab.h>
13 #include <linux/stat.h>
14 #include <linux/interrupt.h>
15 #include <linux/i2c.h>
16 #include <linux/delay.h>
17 #include <linux/iio/iio.h>
18 #include <linux/iio/buffer.h>
19 #include <linux/iio/trigger_consumer.h>
20 #include <linux/iio/triggered_buffer.h>
21 
22 #include <linux/iio/common/st_sensors.h>
23 #include "st_gyro.h"
24 
25 int st_gyro_trig_set_state(struct iio_trigger *trig, bool state)
26 {
27 	struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig);
28 
29 	return st_sensors_set_dataready_irq(indio_dev, state);
30 }
31 
32 static int st_gyro_buffer_postenable(struct iio_dev *indio_dev)
33 {
34 	int err;
35 
36 	err = iio_triggered_buffer_postenable(indio_dev);
37 	if (err < 0)
38 		return err;
39 
40 	err = st_sensors_set_axis_enable(indio_dev, indio_dev->active_scan_mask[0]);
41 	if (err < 0)
42 		goto st_gyro_buffer_predisable;
43 
44 	err = st_sensors_set_enable(indio_dev, true);
45 	if (err < 0)
46 		goto st_gyro_buffer_enable_all_axis;
47 
48 	return 0;
49 
50 st_gyro_buffer_enable_all_axis:
51 	st_sensors_set_axis_enable(indio_dev, ST_SENSORS_ENABLE_ALL_AXIS);
52 st_gyro_buffer_predisable:
53 	iio_triggered_buffer_predisable(indio_dev);
54 	return err;
55 }
56 
57 static int st_gyro_buffer_predisable(struct iio_dev *indio_dev)
58 {
59 	int err, err2;
60 
61 	err = st_sensors_set_enable(indio_dev, false);
62 	if (err < 0)
63 		goto st_gyro_buffer_predisable;
64 
65 	err = st_sensors_set_axis_enable(indio_dev, ST_SENSORS_ENABLE_ALL_AXIS);
66 
67 st_gyro_buffer_predisable:
68 	err2 = iio_triggered_buffer_predisable(indio_dev);
69 	if (!err)
70 		err = err2;
71 
72 	return err;
73 }
74 
75 static const struct iio_buffer_setup_ops st_gyro_buffer_setup_ops = {
76 	.postenable = &st_gyro_buffer_postenable,
77 	.predisable = &st_gyro_buffer_predisable,
78 };
79 
80 int st_gyro_allocate_ring(struct iio_dev *indio_dev)
81 {
82 	return iio_triggered_buffer_setup(indio_dev, NULL,
83 		&st_sensors_trigger_handler, &st_gyro_buffer_setup_ops);
84 }
85 
86 void st_gyro_deallocate_ring(struct iio_dev *indio_dev)
87 {
88 	iio_triggered_buffer_cleanup(indio_dev);
89 }
90 
91 MODULE_AUTHOR("Denis Ciocca <denis.ciocca@st.com>");
92 MODULE_DESCRIPTION("STMicroelectronics gyroscopes buffer");
93 MODULE_LICENSE("GPL v2");
94