1 /*
2  * STMicroelectronics st_lsm6dsx FIFO buffer library driver
3  *
4  * LSM6DS3/LSM6DS3H/LSM6DSL/LSM6DSM: The FIFO buffer can be configured
5  * to store data from gyroscope and accelerometer. Samples are queued
6  * without any tag according to a specific pattern based on 'FIFO data sets'
7  * (6 bytes each):
8  *  - 1st data set is reserved for gyroscope data
9  *  - 2nd data set is reserved for accelerometer data
10  * The FIFO pattern changes depending on the ODRs and decimation factors
11  * assigned to the FIFO data sets. The first sequence of data stored in FIFO
12  * buffer contains the data of all the enabled FIFO data sets
13  * (e.g. Gx, Gy, Gz, Ax, Ay, Az), then data are repeated depending on the
14  * value of the decimation factor and ODR set for each FIFO data set.
15  * FIFO supported modes:
16  *  - BYPASS: FIFO disabled
17  *  - CONTINUOUS: FIFO enabled. When the buffer is full, the FIFO index
18  *    restarts from the beginning and the oldest sample is overwritten
19  *
20  * Copyright 2016 STMicroelectronics Inc.
21  *
22  * Lorenzo Bianconi <lorenzo.bianconi@st.com>
23  * Denis Ciocca <denis.ciocca@st.com>
24  *
25  * Licensed under the GPL-2.
26  */
27 #include <linux/module.h>
28 #include <linux/interrupt.h>
29 #include <linux/irq.h>
30 #include <linux/iio/kfifo_buf.h>
31 #include <linux/iio/iio.h>
32 #include <linux/iio/buffer.h>
33 
34 #include <linux/platform_data/st_sensors_pdata.h>
35 
36 #include "st_lsm6dsx.h"
37 
38 #define ST_LSM6DSX_REG_HLACTIVE_ADDR		0x12
39 #define ST_LSM6DSX_REG_HLACTIVE_MASK		BIT(5)
40 #define ST_LSM6DSX_REG_PP_OD_ADDR		0x12
41 #define ST_LSM6DSX_REG_PP_OD_MASK		BIT(4)
42 #define ST_LSM6DSX_REG_FIFO_MODE_ADDR		0x0a
43 #define ST_LSM6DSX_FIFO_MODE_MASK		GENMASK(2, 0)
44 #define ST_LSM6DSX_FIFO_ODR_MASK		GENMASK(6, 3)
45 #define ST_LSM6DSX_FIFO_EMPTY_MASK		BIT(12)
46 #define ST_LSM6DSX_REG_FIFO_OUTL_ADDR		0x3e
47 
48 #define ST_LSM6DSX_MAX_FIFO_ODR_VAL		0x08
49 
50 struct st_lsm6dsx_decimator_entry {
51 	u8 decimator;
52 	u8 val;
53 };
54 
55 static const
56 struct st_lsm6dsx_decimator_entry st_lsm6dsx_decimator_table[] = {
57 	{  0, 0x0 },
58 	{  1, 0x1 },
59 	{  2, 0x2 },
60 	{  3, 0x3 },
61 	{  4, 0x4 },
62 	{  8, 0x5 },
63 	{ 16, 0x6 },
64 	{ 32, 0x7 },
65 };
66 
67 static int st_lsm6dsx_get_decimator_val(u8 val)
68 {
69 	const int max_size = ARRAY_SIZE(st_lsm6dsx_decimator_table);
70 	int i;
71 
72 	for (i = 0; i < max_size; i++)
73 		if (st_lsm6dsx_decimator_table[i].decimator == val)
74 			break;
75 
76 	return i == max_size ? 0 : st_lsm6dsx_decimator_table[i].val;
77 }
78 
79 static void st_lsm6dsx_get_max_min_odr(struct st_lsm6dsx_hw *hw,
80 				       u16 *max_odr, u16 *min_odr)
81 {
82 	struct st_lsm6dsx_sensor *sensor;
83 	int i;
84 
85 	*max_odr = 0, *min_odr = ~0;
86 	for (i = 0; i < ST_LSM6DSX_ID_MAX; i++) {
87 		sensor = iio_priv(hw->iio_devs[i]);
88 
89 		if (!(hw->enable_mask & BIT(sensor->id)))
90 			continue;
91 
92 		*max_odr = max_t(u16, *max_odr, sensor->odr);
93 		*min_odr = min_t(u16, *min_odr, sensor->odr);
94 	}
95 }
96 
97 static int st_lsm6dsx_update_decimators(struct st_lsm6dsx_hw *hw)
98 {
99 	struct st_lsm6dsx_sensor *sensor;
100 	u16 max_odr, min_odr, sip = 0;
101 	int err, i;
102 	u8 data;
103 
104 	st_lsm6dsx_get_max_min_odr(hw, &max_odr, &min_odr);
105 
106 	for (i = 0; i < ST_LSM6DSX_ID_MAX; i++) {
107 		const struct st_lsm6dsx_reg *dec_reg;
108 
109 		sensor = iio_priv(hw->iio_devs[i]);
110 		/* update fifo decimators and sample in pattern */
111 		if (hw->enable_mask & BIT(sensor->id)) {
112 			sensor->sip = sensor->odr / min_odr;
113 			sensor->decimator = max_odr / sensor->odr;
114 			data = st_lsm6dsx_get_decimator_val(sensor->decimator);
115 		} else {
116 			sensor->sip = 0;
117 			sensor->decimator = 0;
118 			data = 0;
119 		}
120 
121 		dec_reg = &hw->settings->decimator[sensor->id];
122 		if (dec_reg->addr) {
123 			err = st_lsm6dsx_write_with_mask(hw, dec_reg->addr,
124 							 dec_reg->mask, data);
125 			if (err < 0)
126 				return err;
127 		}
128 		sip += sensor->sip;
129 	}
130 	hw->sip = sip;
131 
132 	return 0;
133 }
134 
135 int st_lsm6dsx_set_fifo_mode(struct st_lsm6dsx_hw *hw,
136 			     enum st_lsm6dsx_fifo_mode fifo_mode)
137 {
138 	int err;
139 
140 	err = st_lsm6dsx_write_with_mask(hw, ST_LSM6DSX_REG_FIFO_MODE_ADDR,
141 					 ST_LSM6DSX_FIFO_MODE_MASK, fifo_mode);
142 	if (err < 0)
143 		return err;
144 
145 	hw->fifo_mode = fifo_mode;
146 
147 	return 0;
148 }
149 
150 static int st_lsm6dsx_set_fifo_odr(struct st_lsm6dsx_sensor *sensor,
151 				   bool enable)
152 {
153 	struct st_lsm6dsx_hw *hw = sensor->hw;
154 	u8 data;
155 
156 	data = hw->enable_mask ? ST_LSM6DSX_MAX_FIFO_ODR_VAL : 0;
157 	return st_lsm6dsx_write_with_mask(hw, ST_LSM6DSX_REG_FIFO_MODE_ADDR,
158 					  ST_LSM6DSX_FIFO_ODR_MASK, data);
159 }
160 
161 int st_lsm6dsx_update_watermark(struct st_lsm6dsx_sensor *sensor, u16 watermark)
162 {
163 	u16 fifo_watermark = ~0, cur_watermark, sip = 0, fifo_th_mask;
164 	struct st_lsm6dsx_hw *hw = sensor->hw;
165 	struct st_lsm6dsx_sensor *cur_sensor;
166 	__le16 wdata;
167 	int i, err;
168 	u8 data;
169 
170 	for (i = 0; i < ST_LSM6DSX_ID_MAX; i++) {
171 		cur_sensor = iio_priv(hw->iio_devs[i]);
172 
173 		if (!(hw->enable_mask & BIT(cur_sensor->id)))
174 			continue;
175 
176 		cur_watermark = (cur_sensor == sensor) ? watermark
177 						       : cur_sensor->watermark;
178 
179 		fifo_watermark = min_t(u16, fifo_watermark, cur_watermark);
180 		sip += cur_sensor->sip;
181 	}
182 
183 	if (!sip)
184 		return 0;
185 
186 	fifo_watermark = max_t(u16, fifo_watermark, sip);
187 	fifo_watermark = (fifo_watermark / sip) * sip;
188 	fifo_watermark = fifo_watermark * hw->settings->fifo_ops.th_wl;
189 
190 	mutex_lock(&hw->lock);
191 
192 	err = hw->tf->read(hw->dev, hw->settings->fifo_ops.fifo_th.addr + 1,
193 			   sizeof(data), &data);
194 	if (err < 0)
195 		goto out;
196 
197 	fifo_th_mask = hw->settings->fifo_ops.fifo_th.mask;
198 	fifo_watermark = ((data << 8) & ~fifo_th_mask) |
199 			 (fifo_watermark & fifo_th_mask);
200 
201 	wdata = cpu_to_le16(fifo_watermark);
202 	err = hw->tf->write(hw->dev, hw->settings->fifo_ops.fifo_th.addr,
203 			    sizeof(wdata), (u8 *)&wdata);
204 out:
205 	mutex_unlock(&hw->lock);
206 
207 	return err < 0 ? err : 0;
208 }
209 
210 /**
211  * st_lsm6dsx_read_fifo() - LSM6DS3-LSM6DS3H-LSM6DSL-LSM6DSM read FIFO routine
212  * @hw: Pointer to instance of struct st_lsm6dsx_hw.
213  *
214  * Read samples from the hw FIFO and push them to IIO buffers.
215  *
216  * Return: Number of bytes read from the FIFO
217  */
218 static int st_lsm6dsx_read_fifo(struct st_lsm6dsx_hw *hw)
219 {
220 	u16 fifo_len, pattern_len = hw->sip * ST_LSM6DSX_SAMPLE_SIZE;
221 	u16 fifo_diff_mask = hw->settings->fifo_ops.fifo_diff.mask;
222 	int err, acc_sip, gyro_sip, read_len, samples, offset;
223 	struct st_lsm6dsx_sensor *acc_sensor, *gyro_sensor;
224 	s64 acc_ts, acc_delta_ts, gyro_ts, gyro_delta_ts;
225 	u8 iio_buff[ALIGN(ST_LSM6DSX_SAMPLE_SIZE, sizeof(s64)) + sizeof(s64)];
226 	u8 buff[pattern_len];
227 	__le16 fifo_status;
228 
229 	err = hw->tf->read(hw->dev, hw->settings->fifo_ops.fifo_diff.addr,
230 			   sizeof(fifo_status), (u8 *)&fifo_status);
231 	if (err < 0)
232 		return err;
233 
234 	if (fifo_status & cpu_to_le16(ST_LSM6DSX_FIFO_EMPTY_MASK))
235 		return 0;
236 
237 	fifo_len = (le16_to_cpu(fifo_status) & fifo_diff_mask) *
238 		   ST_LSM6DSX_CHAN_SIZE;
239 	samples = fifo_len / ST_LSM6DSX_SAMPLE_SIZE;
240 	fifo_len = (fifo_len / pattern_len) * pattern_len;
241 
242 	/*
243 	 * compute delta timestamp between two consecutive samples
244 	 * in order to estimate queueing time of data generated
245 	 * by the sensor
246 	 */
247 	acc_sensor = iio_priv(hw->iio_devs[ST_LSM6DSX_ID_ACC]);
248 	acc_ts = acc_sensor->ts - acc_sensor->delta_ts;
249 	acc_delta_ts = div_s64(acc_sensor->delta_ts * acc_sensor->decimator,
250 			       samples);
251 
252 	gyro_sensor = iio_priv(hw->iio_devs[ST_LSM6DSX_ID_GYRO]);
253 	gyro_ts = gyro_sensor->ts - gyro_sensor->delta_ts;
254 	gyro_delta_ts = div_s64(gyro_sensor->delta_ts * gyro_sensor->decimator,
255 				samples);
256 
257 	for (read_len = 0; read_len < fifo_len; read_len += pattern_len) {
258 		err = hw->tf->read(hw->dev, ST_LSM6DSX_REG_FIFO_OUTL_ADDR,
259 				   sizeof(buff), buff);
260 		if (err < 0)
261 			return err;
262 
263 		/*
264 		 * Data are written to the FIFO with a specific pattern
265 		 * depending on the configured ODRs. The first sequence of data
266 		 * stored in FIFO contains the data of all enabled sensors
267 		 * (e.g. Gx, Gy, Gz, Ax, Ay, Az), then data are repeated
268 		 * depending on the value of the decimation factor set for each
269 		 * sensor.
270 		 *
271 		 * Supposing the FIFO is storing data from gyroscope and
272 		 * accelerometer at different ODRs:
273 		 *   - gyroscope ODR = 208Hz, accelerometer ODR = 104Hz
274 		 * Since the gyroscope ODR is twice the accelerometer one, the
275 		 * following pattern is repeated every 9 samples:
276 		 *   - Gx, Gy, Gz, Ax, Ay, Az, Gx, Gy, Gz
277 		 */
278 		gyro_sip = gyro_sensor->sip;
279 		acc_sip = acc_sensor->sip;
280 		offset = 0;
281 
282 		while (acc_sip > 0 || gyro_sip > 0) {
283 			if (gyro_sip-- > 0) {
284 				memcpy(iio_buff, &buff[offset],
285 				       ST_LSM6DSX_SAMPLE_SIZE);
286 				iio_push_to_buffers_with_timestamp(
287 					hw->iio_devs[ST_LSM6DSX_ID_GYRO],
288 					iio_buff, gyro_ts);
289 				offset += ST_LSM6DSX_SAMPLE_SIZE;
290 				gyro_ts += gyro_delta_ts;
291 			}
292 
293 			if (acc_sip-- > 0) {
294 				memcpy(iio_buff, &buff[offset],
295 				       ST_LSM6DSX_SAMPLE_SIZE);
296 				iio_push_to_buffers_with_timestamp(
297 					hw->iio_devs[ST_LSM6DSX_ID_ACC],
298 					iio_buff, acc_ts);
299 				offset += ST_LSM6DSX_SAMPLE_SIZE;
300 				acc_ts += acc_delta_ts;
301 			}
302 		}
303 	}
304 
305 	return read_len;
306 }
307 
308 int st_lsm6dsx_flush_fifo(struct st_lsm6dsx_hw *hw)
309 {
310 	int err;
311 
312 	mutex_lock(&hw->fifo_lock);
313 
314 	st_lsm6dsx_read_fifo(hw);
315 	err = st_lsm6dsx_set_fifo_mode(hw, ST_LSM6DSX_FIFO_BYPASS);
316 
317 	mutex_unlock(&hw->fifo_lock);
318 
319 	return err;
320 }
321 
322 static int st_lsm6dsx_update_fifo(struct iio_dev *iio_dev, bool enable)
323 {
324 	struct st_lsm6dsx_sensor *sensor = iio_priv(iio_dev);
325 	struct st_lsm6dsx_hw *hw = sensor->hw;
326 	int err;
327 
328 	if (hw->fifo_mode != ST_LSM6DSX_FIFO_BYPASS) {
329 		err = st_lsm6dsx_flush_fifo(hw);
330 		if (err < 0)
331 			return err;
332 	}
333 
334 	if (enable) {
335 		err = st_lsm6dsx_sensor_enable(sensor);
336 		if (err < 0)
337 			return err;
338 	} else {
339 		err = st_lsm6dsx_sensor_disable(sensor);
340 		if (err < 0)
341 			return err;
342 	}
343 
344 	err = st_lsm6dsx_set_fifo_odr(sensor, enable);
345 	if (err < 0)
346 		return err;
347 
348 	err = st_lsm6dsx_update_decimators(hw);
349 	if (err < 0)
350 		return err;
351 
352 	err = st_lsm6dsx_update_watermark(sensor, sensor->watermark);
353 	if (err < 0)
354 		return err;
355 
356 	if (hw->enable_mask) {
357 		err = st_lsm6dsx_set_fifo_mode(hw, ST_LSM6DSX_FIFO_CONT);
358 		if (err < 0)
359 			return err;
360 
361 		/*
362 		 * store enable buffer timestamp as reference to compute
363 		 * first delta timestamp
364 		 */
365 		sensor->ts = iio_get_time_ns(iio_dev);
366 	}
367 
368 	return 0;
369 }
370 
371 static irqreturn_t st_lsm6dsx_handler_irq(int irq, void *private)
372 {
373 	struct st_lsm6dsx_hw *hw = private;
374 	struct st_lsm6dsx_sensor *sensor;
375 	int i;
376 
377 	if (!hw->sip)
378 		return IRQ_NONE;
379 
380 	for (i = 0; i < ST_LSM6DSX_ID_MAX; i++) {
381 		sensor = iio_priv(hw->iio_devs[i]);
382 
383 		if (sensor->sip > 0) {
384 			s64 timestamp;
385 
386 			timestamp = iio_get_time_ns(hw->iio_devs[i]);
387 			sensor->delta_ts = timestamp - sensor->ts;
388 			sensor->ts = timestamp;
389 		}
390 	}
391 
392 	return IRQ_WAKE_THREAD;
393 }
394 
395 static irqreturn_t st_lsm6dsx_handler_thread(int irq, void *private)
396 {
397 	struct st_lsm6dsx_hw *hw = private;
398 	int count;
399 
400 	mutex_lock(&hw->fifo_lock);
401 	count = st_lsm6dsx_read_fifo(hw);
402 	mutex_unlock(&hw->fifo_lock);
403 
404 	return !count ? IRQ_NONE : IRQ_HANDLED;
405 }
406 
407 static int st_lsm6dsx_buffer_preenable(struct iio_dev *iio_dev)
408 {
409 	return st_lsm6dsx_update_fifo(iio_dev, true);
410 }
411 
412 static int st_lsm6dsx_buffer_postdisable(struct iio_dev *iio_dev)
413 {
414 	return st_lsm6dsx_update_fifo(iio_dev, false);
415 }
416 
417 static const struct iio_buffer_setup_ops st_lsm6dsx_buffer_ops = {
418 	.preenable = st_lsm6dsx_buffer_preenable,
419 	.postdisable = st_lsm6dsx_buffer_postdisable,
420 };
421 
422 int st_lsm6dsx_fifo_setup(struct st_lsm6dsx_hw *hw)
423 {
424 	struct device_node *np = hw->dev->of_node;
425 	struct st_sensors_platform_data *pdata;
426 	struct iio_buffer *buffer;
427 	unsigned long irq_type;
428 	bool irq_active_low;
429 	int i, err;
430 
431 	irq_type = irqd_get_trigger_type(irq_get_irq_data(hw->irq));
432 
433 	switch (irq_type) {
434 	case IRQF_TRIGGER_HIGH:
435 	case IRQF_TRIGGER_RISING:
436 		irq_active_low = false;
437 		break;
438 	case IRQF_TRIGGER_LOW:
439 	case IRQF_TRIGGER_FALLING:
440 		irq_active_low = true;
441 		break;
442 	default:
443 		dev_info(hw->dev, "mode %lx unsupported\n", irq_type);
444 		return -EINVAL;
445 	}
446 
447 	err = st_lsm6dsx_write_with_mask(hw, ST_LSM6DSX_REG_HLACTIVE_ADDR,
448 					 ST_LSM6DSX_REG_HLACTIVE_MASK,
449 					 irq_active_low);
450 	if (err < 0)
451 		return err;
452 
453 	pdata = (struct st_sensors_platform_data *)hw->dev->platform_data;
454 	if ((np && of_property_read_bool(np, "drive-open-drain")) ||
455 	    (pdata && pdata->open_drain)) {
456 		err = st_lsm6dsx_write_with_mask(hw, ST_LSM6DSX_REG_PP_OD_ADDR,
457 						 ST_LSM6DSX_REG_PP_OD_MASK, 1);
458 		if (err < 0)
459 			return err;
460 
461 		irq_type |= IRQF_SHARED;
462 	}
463 
464 	err = devm_request_threaded_irq(hw->dev, hw->irq,
465 					st_lsm6dsx_handler_irq,
466 					st_lsm6dsx_handler_thread,
467 					irq_type | IRQF_ONESHOT,
468 					"lsm6dsx", hw);
469 	if (err) {
470 		dev_err(hw->dev, "failed to request trigger irq %d\n",
471 			hw->irq);
472 		return err;
473 	}
474 
475 	for (i = 0; i < ST_LSM6DSX_ID_MAX; i++) {
476 		buffer = devm_iio_kfifo_allocate(hw->dev);
477 		if (!buffer)
478 			return -ENOMEM;
479 
480 		iio_device_attach_buffer(hw->iio_devs[i], buffer);
481 		hw->iio_devs[i]->modes |= INDIO_BUFFER_SOFTWARE;
482 		hw->iio_devs[i]->setup_ops = &st_lsm6dsx_buffer_ops;
483 	}
484 
485 	return 0;
486 }
487