1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * STMicroelectronics magnetometers 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_magn.h"
24 
25 int st_magn_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_magn_buffer_postenable(struct iio_dev *indio_dev)
33 {
34 	int err;
35 	struct st_sensor_data *mdata = iio_priv(indio_dev);
36 
37 	mdata->buffer_data = kmalloc(indio_dev->scan_bytes, GFP_KERNEL);
38 	if (mdata->buffer_data == NULL) {
39 		err = -ENOMEM;
40 		goto allocate_memory_error;
41 	}
42 
43 	err = iio_triggered_buffer_postenable(indio_dev);
44 	if (err < 0)
45 		goto st_magn_buffer_postenable_error;
46 
47 	return st_sensors_set_enable(indio_dev, true);
48 
49 st_magn_buffer_postenable_error:
50 	kfree(mdata->buffer_data);
51 allocate_memory_error:
52 	return err;
53 }
54 
55 static int st_magn_buffer_predisable(struct iio_dev *indio_dev)
56 {
57 	int err;
58 	struct st_sensor_data *mdata = iio_priv(indio_dev);
59 
60 	err = st_sensors_set_enable(indio_dev, false);
61 	if (err < 0)
62 		goto st_magn_buffer_predisable_error;
63 
64 	err = iio_triggered_buffer_predisable(indio_dev);
65 
66 st_magn_buffer_predisable_error:
67 	kfree(mdata->buffer_data);
68 	return err;
69 }
70 
71 static const struct iio_buffer_setup_ops st_magn_buffer_setup_ops = {
72 	.postenable = &st_magn_buffer_postenable,
73 	.predisable = &st_magn_buffer_predisable,
74 };
75 
76 int st_magn_allocate_ring(struct iio_dev *indio_dev)
77 {
78 	return iio_triggered_buffer_setup(indio_dev, NULL,
79 		&st_sensors_trigger_handler, &st_magn_buffer_setup_ops);
80 }
81 
82 void st_magn_deallocate_ring(struct iio_dev *indio_dev)
83 {
84 	iio_triggered_buffer_cleanup(indio_dev);
85 }
86 
87 MODULE_AUTHOR("Denis Ciocca <denis.ciocca@st.com>");
88 MODULE_DESCRIPTION("STMicroelectronics magnetometers buffer");
89 MODULE_LICENSE("GPL v2");
90