xref: /linux/drivers/iio/accel/adxl345_core.c (revision c26f4fbd58375bd6ef74f95eb73d61762ad97c59)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * ADXL345 3-Axis Digital Accelerometer IIO core driver
4  *
5  * Copyright (c) 2017 Eva Rachel Retuya <eraretuya@gmail.com>
6  *
7  * Datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf
8  */
9 
10 #include <linux/bitfield.h>
11 #include <linux/bitops.h>
12 #include <linux/interrupt.h>
13 #include <linux/module.h>
14 #include <linux/property.h>
15 #include <linux/regmap.h>
16 #include <linux/units.h>
17 
18 #include <linux/iio/iio.h>
19 #include <linux/iio/sysfs.h>
20 #include <linux/iio/buffer.h>
21 #include <linux/iio/events.h>
22 #include <linux/iio/kfifo_buf.h>
23 
24 #include "adxl345.h"
25 
26 #define ADXL345_FIFO_BYPASS	0
27 #define ADXL345_FIFO_FIFO	1
28 #define ADXL345_FIFO_STREAM	2
29 
30 #define ADXL345_DIRS 3
31 
32 #define ADXL345_INT_NONE		0xff
33 #define ADXL345_INT1			0
34 #define ADXL345_INT2			1
35 
36 #define ADXL345_REG_TAP_AXIS_MSK	GENMASK(2, 0)
37 #define ADXL345_REG_TAP_SUPPRESS_MSK	BIT(3)
38 #define ADXL345_REG_TAP_SUPPRESS	BIT(3)
39 
40 #define ADXL345_TAP_Z_EN		BIT(0)
41 #define ADXL345_TAP_Y_EN		BIT(1)
42 #define ADXL345_TAP_X_EN		BIT(2)
43 
44 /* single/double tap */
45 enum adxl345_tap_type {
46 	ADXL345_SINGLE_TAP,
47 	ADXL345_DOUBLE_TAP,
48 };
49 
50 static const unsigned int adxl345_tap_int_reg[] = {
51 	[ADXL345_SINGLE_TAP] = ADXL345_INT_SINGLE_TAP,
52 	[ADXL345_DOUBLE_TAP] = ADXL345_INT_DOUBLE_TAP,
53 };
54 
55 enum adxl345_tap_time_type {
56 	ADXL345_TAP_TIME_LATENT,
57 	ADXL345_TAP_TIME_WINDOW,
58 	ADXL345_TAP_TIME_DUR,
59 };
60 
61 static const unsigned int adxl345_tap_time_reg[] = {
62 	[ADXL345_TAP_TIME_LATENT] = ADXL345_REG_LATENT,
63 	[ADXL345_TAP_TIME_WINDOW] = ADXL345_REG_WINDOW,
64 	[ADXL345_TAP_TIME_DUR] = ADXL345_REG_DUR,
65 };
66 
67 struct adxl345_state {
68 	const struct adxl345_chip_info *info;
69 	struct regmap *regmap;
70 	bool fifo_delay; /* delay: delay is needed for SPI */
71 	int irq;
72 	u8 watermark;
73 	u8 fifo_mode;
74 
75 	u32 tap_duration_us;
76 	u32 tap_latent_us;
77 	u32 tap_window_us;
78 
79 	__le16 fifo_buf[ADXL345_DIRS * ADXL345_FIFO_SIZE + 1] __aligned(IIO_DMA_MINALIGN);
80 };
81 
82 static struct iio_event_spec adxl345_events[] = {
83 	{
84 		/* single tap */
85 		.type = IIO_EV_TYPE_GESTURE,
86 		.dir = IIO_EV_DIR_SINGLETAP,
87 		.mask_separate = BIT(IIO_EV_INFO_ENABLE),
88 		.mask_shared_by_type = BIT(IIO_EV_INFO_VALUE) |
89 			BIT(IIO_EV_INFO_TIMEOUT),
90 	},
91 	{
92 		/* double tap */
93 		.type = IIO_EV_TYPE_GESTURE,
94 		.dir = IIO_EV_DIR_DOUBLETAP,
95 		.mask_shared_by_type = BIT(IIO_EV_INFO_ENABLE) |
96 			BIT(IIO_EV_INFO_RESET_TIMEOUT) |
97 			BIT(IIO_EV_INFO_TAP2_MIN_DELAY),
98 	},
99 };
100 
101 #define ADXL345_CHANNEL(index, reg, axis) {					\
102 	.type = IIO_ACCEL,						\
103 	.modified = 1,							\
104 	.channel2 = IIO_MOD_##axis,					\
105 	.address = (reg),						\
106 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |			\
107 		BIT(IIO_CHAN_INFO_CALIBBIAS),				\
108 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |		\
109 		BIT(IIO_CHAN_INFO_SAMP_FREQ),				\
110 	.scan_index = (index),				\
111 	.scan_type = {					\
112 		.sign = 's',				\
113 		.realbits = 13,				\
114 		.storagebits = 16,			\
115 		.endianness = IIO_LE,			\
116 	},						\
117 	.event_spec = adxl345_events,			\
118 	.num_event_specs = ARRAY_SIZE(adxl345_events),	\
119 }
120 
121 enum adxl345_chans {
122 	chan_x, chan_y, chan_z,
123 };
124 
125 static const struct iio_chan_spec adxl345_channels[] = {
126 	ADXL345_CHANNEL(0, chan_x, X),
127 	ADXL345_CHANNEL(1, chan_y, Y),
128 	ADXL345_CHANNEL(2, chan_z, Z),
129 };
130 
131 static const unsigned long adxl345_scan_masks[] = {
132 	BIT(chan_x) | BIT(chan_y) | BIT(chan_z),
133 	0
134 };
135 
adxl345_is_volatile_reg(struct device * dev,unsigned int reg)136 bool adxl345_is_volatile_reg(struct device *dev, unsigned int reg)
137 {
138 	switch (reg) {
139 	case ADXL345_REG_DATA_AXIS(0):
140 	case ADXL345_REG_DATA_AXIS(1):
141 	case ADXL345_REG_DATA_AXIS(2):
142 	case ADXL345_REG_DATA_AXIS(3):
143 	case ADXL345_REG_DATA_AXIS(4):
144 	case ADXL345_REG_DATA_AXIS(5):
145 	case ADXL345_REG_ACT_TAP_STATUS:
146 	case ADXL345_REG_FIFO_STATUS:
147 	case ADXL345_REG_INT_SOURCE:
148 		return true;
149 	default:
150 		return false;
151 	}
152 }
153 EXPORT_SYMBOL_NS_GPL(adxl345_is_volatile_reg, "IIO_ADXL345");
154 
155 /**
156  * adxl345_set_measure_en() - Enable and disable measuring.
157  *
158  * @st: The device data.
159  * @en: Enable measurements, else standby mode.
160  *
161  * For lowest power operation, standby mode can be used. In standby mode,
162  * current consumption is supposed to be reduced to 0.1uA (typical). In this
163  * mode no measurements are made. Placing the device into standby mode
164  * preserves the contents of FIFO.
165  *
166  * Return: Returns 0 if successful, or a negative error value.
167  */
adxl345_set_measure_en(struct adxl345_state * st,bool en)168 static int adxl345_set_measure_en(struct adxl345_state *st, bool en)
169 {
170 	unsigned int val = en ? ADXL345_POWER_CTL_MEASURE : ADXL345_POWER_CTL_STANDBY;
171 
172 	return regmap_write(st->regmap, ADXL345_REG_POWER_CTL, val);
173 }
174 
175 /* tap */
176 
_adxl345_set_tap_int(struct adxl345_state * st,enum adxl345_tap_type type,bool state)177 static int _adxl345_set_tap_int(struct adxl345_state *st,
178 				enum adxl345_tap_type type, bool state)
179 {
180 	unsigned int int_map = 0x00;
181 	unsigned int tap_threshold;
182 	bool axis_valid;
183 	bool singletap_args_valid = false;
184 	bool doubletap_args_valid = false;
185 	bool en = false;
186 	u32 axis_ctrl;
187 	int ret;
188 
189 	ret = regmap_read(st->regmap, ADXL345_REG_TAP_AXIS, &axis_ctrl);
190 	if (ret)
191 		return ret;
192 
193 	axis_valid = FIELD_GET(ADXL345_REG_TAP_AXIS_MSK, axis_ctrl) > 0;
194 
195 	ret = regmap_read(st->regmap, ADXL345_REG_THRESH_TAP, &tap_threshold);
196 	if (ret)
197 		return ret;
198 
199 	/*
200 	 * Note: A value of 0 for threshold and/or dur may result in undesirable
201 	 *	 behavior if single tap/double tap interrupts are enabled.
202 	 */
203 	singletap_args_valid = tap_threshold > 0 && st->tap_duration_us > 0;
204 
205 	if (type == ADXL345_SINGLE_TAP) {
206 		en = axis_valid && singletap_args_valid;
207 	} else {
208 		/* doubletap: Window must be equal or greater than latent! */
209 		doubletap_args_valid = st->tap_latent_us > 0 &&
210 			st->tap_window_us > 0 &&
211 			st->tap_window_us >= st->tap_latent_us;
212 
213 		en = axis_valid && singletap_args_valid && doubletap_args_valid;
214 	}
215 
216 	if (state && en)
217 		int_map |= adxl345_tap_int_reg[type];
218 
219 	return regmap_update_bits(st->regmap, ADXL345_REG_INT_ENABLE,
220 				  adxl345_tap_int_reg[type], int_map);
221 }
222 
adxl345_is_tap_en(struct adxl345_state * st,enum iio_modifier axis,enum adxl345_tap_type type,bool * en)223 static int adxl345_is_tap_en(struct adxl345_state *st,
224 			     enum iio_modifier axis,
225 			     enum adxl345_tap_type type, bool *en)
226 {
227 	unsigned int regval;
228 	u32 axis_ctrl;
229 	int ret;
230 
231 	ret = regmap_read(st->regmap, ADXL345_REG_TAP_AXIS, &axis_ctrl);
232 	if (ret)
233 		return ret;
234 
235 	/* Verify if axis is enabled for the tap detection. */
236 	switch (axis) {
237 	case IIO_MOD_X:
238 		*en = FIELD_GET(ADXL345_TAP_X_EN, axis_ctrl);
239 		break;
240 	case IIO_MOD_Y:
241 		*en = FIELD_GET(ADXL345_TAP_Y_EN, axis_ctrl);
242 		break;
243 	case IIO_MOD_Z:
244 		*en = FIELD_GET(ADXL345_TAP_Z_EN, axis_ctrl);
245 		break;
246 	default:
247 		*en = false;
248 		return -EINVAL;
249 	}
250 
251 	if (*en) {
252 		/*
253 		 * If axis allow for tap detection, verify if the interrupt is
254 		 * enabled for tap detection.
255 		 */
256 		ret = regmap_read(st->regmap, ADXL345_REG_INT_ENABLE, &regval);
257 		if (ret)
258 			return ret;
259 
260 		*en = adxl345_tap_int_reg[type] & regval;
261 	}
262 
263 	return 0;
264 }
265 
adxl345_set_singletap_en(struct adxl345_state * st,enum iio_modifier axis,bool en)266 static int adxl345_set_singletap_en(struct adxl345_state *st,
267 				    enum iio_modifier axis, bool en)
268 {
269 	int ret;
270 	u32 axis_ctrl;
271 
272 	switch (axis) {
273 	case IIO_MOD_X:
274 		axis_ctrl = ADXL345_TAP_X_EN;
275 		break;
276 	case IIO_MOD_Y:
277 		axis_ctrl = ADXL345_TAP_Y_EN;
278 		break;
279 	case IIO_MOD_Z:
280 		axis_ctrl = ADXL345_TAP_Z_EN;
281 		break;
282 	default:
283 		return -EINVAL;
284 	}
285 
286 	if (en)
287 		ret = regmap_set_bits(st->regmap, ADXL345_REG_TAP_AXIS,
288 				      axis_ctrl);
289 	else
290 		ret = regmap_clear_bits(st->regmap, ADXL345_REG_TAP_AXIS,
291 					axis_ctrl);
292 	if (ret)
293 		return ret;
294 
295 	return _adxl345_set_tap_int(st, ADXL345_SINGLE_TAP, en);
296 }
297 
adxl345_set_doubletap_en(struct adxl345_state * st,bool en)298 static int adxl345_set_doubletap_en(struct adxl345_state *st, bool en)
299 {
300 	int ret;
301 
302 	/*
303 	 * Generally suppress detection of spikes during the latency period as
304 	 * double taps here, this is fully optional for double tap detection
305 	 */
306 	ret = regmap_update_bits(st->regmap, ADXL345_REG_TAP_AXIS,
307 				 ADXL345_REG_TAP_SUPPRESS_MSK,
308 				 en ? ADXL345_REG_TAP_SUPPRESS : 0x00);
309 	if (ret)
310 		return ret;
311 
312 	return _adxl345_set_tap_int(st, ADXL345_DOUBLE_TAP, en);
313 }
314 
_adxl345_set_tap_time(struct adxl345_state * st,enum adxl345_tap_time_type type,u32 val_us)315 static int _adxl345_set_tap_time(struct adxl345_state *st,
316 				 enum adxl345_tap_time_type type, u32 val_us)
317 {
318 	unsigned int regval;
319 
320 	switch (type) {
321 	case ADXL345_TAP_TIME_WINDOW:
322 		st->tap_window_us = val_us;
323 		break;
324 	case ADXL345_TAP_TIME_LATENT:
325 		st->tap_latent_us = val_us;
326 		break;
327 	case ADXL345_TAP_TIME_DUR:
328 		st->tap_duration_us = val_us;
329 		break;
330 	}
331 
332 	/*
333 	 * The scale factor is 1250us / LSB for tap_window_us and tap_latent_us.
334 	 * For tap_duration_us the scale factor is 625us / LSB.
335 	 */
336 	if (type == ADXL345_TAP_TIME_DUR)
337 		regval = DIV_ROUND_CLOSEST(val_us, 625);
338 	else
339 		regval = DIV_ROUND_CLOSEST(val_us, 1250);
340 
341 	return regmap_write(st->regmap, adxl345_tap_time_reg[type], regval);
342 }
343 
adxl345_set_tap_duration(struct adxl345_state * st,u32 val_int,u32 val_fract_us)344 static int adxl345_set_tap_duration(struct adxl345_state *st, u32 val_int,
345 				    u32 val_fract_us)
346 {
347 	/*
348 	 * Max value is 255 * 625 us = 0.159375 seconds
349 	 *
350 	 * Note: the scaling is similar to the scaling in the ADXL380
351 	 */
352 	if (val_int || val_fract_us > 159375)
353 		return -EINVAL;
354 
355 	return _adxl345_set_tap_time(st, ADXL345_TAP_TIME_DUR, val_fract_us);
356 }
357 
adxl345_set_tap_window(struct adxl345_state * st,u32 val_int,u32 val_fract_us)358 static int adxl345_set_tap_window(struct adxl345_state *st, u32 val_int,
359 				  u32 val_fract_us)
360 {
361 	/*
362 	 * Max value is 255 * 1250 us = 0.318750 seconds
363 	 *
364 	 * Note: the scaling is similar to the scaling in the ADXL380
365 	 */
366 	if (val_int || val_fract_us > 318750)
367 		return -EINVAL;
368 
369 	return _adxl345_set_tap_time(st, ADXL345_TAP_TIME_WINDOW, val_fract_us);
370 }
371 
adxl345_set_tap_latent(struct adxl345_state * st,u32 val_int,u32 val_fract_us)372 static int adxl345_set_tap_latent(struct adxl345_state *st, u32 val_int,
373 				  u32 val_fract_us)
374 {
375 	/*
376 	 * Max value is 255 * 1250 us = 0.318750 seconds
377 	 *
378 	 * Note: the scaling is similar to the scaling in the ADXL380
379 	 */
380 	if (val_int || val_fract_us > 318750)
381 		return -EINVAL;
382 
383 	return _adxl345_set_tap_time(st, ADXL345_TAP_TIME_LATENT, val_fract_us);
384 }
385 
adxl345_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)386 static int adxl345_read_raw(struct iio_dev *indio_dev,
387 			    struct iio_chan_spec const *chan,
388 			    int *val, int *val2, long mask)
389 {
390 	struct adxl345_state *st = iio_priv(indio_dev);
391 	__le16 accel;
392 	long long samp_freq_nhz;
393 	unsigned int regval;
394 	int ret;
395 
396 	switch (mask) {
397 	case IIO_CHAN_INFO_RAW:
398 		/*
399 		 * Data is stored in adjacent registers:
400 		 * ADXL345_REG_DATA(X0/Y0/Z0) contain the least significant byte
401 		 * and ADXL345_REG_DATA(X0/Y0/Z0) + 1 the most significant byte
402 		 */
403 		ret = regmap_bulk_read(st->regmap,
404 				       ADXL345_REG_DATA_AXIS(chan->address),
405 				       &accel, sizeof(accel));
406 		if (ret)
407 			return ret;
408 
409 		*val = sign_extend32(le16_to_cpu(accel), 12);
410 		return IIO_VAL_INT;
411 	case IIO_CHAN_INFO_SCALE:
412 		*val = 0;
413 		*val2 = st->info->uscale;
414 		return IIO_VAL_INT_PLUS_MICRO;
415 	case IIO_CHAN_INFO_CALIBBIAS:
416 		ret = regmap_read(st->regmap,
417 				  ADXL345_REG_OFS_AXIS(chan->address), &regval);
418 		if (ret)
419 			return ret;
420 		/*
421 		 * 8-bit resolution at +/- 2g, that is 4x accel data scale
422 		 * factor
423 		 */
424 		*val = sign_extend32(regval, 7) * 4;
425 
426 		return IIO_VAL_INT;
427 	case IIO_CHAN_INFO_SAMP_FREQ:
428 		ret = regmap_read(st->regmap, ADXL345_REG_BW_RATE, &regval);
429 		if (ret)
430 			return ret;
431 
432 		samp_freq_nhz = ADXL345_BASE_RATE_NANO_HZ <<
433 				(regval & ADXL345_BW_RATE);
434 		*val = div_s64_rem(samp_freq_nhz, NANOHZ_PER_HZ, val2);
435 
436 		return IIO_VAL_INT_PLUS_NANO;
437 	}
438 
439 	return -EINVAL;
440 }
441 
adxl345_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)442 static int adxl345_write_raw(struct iio_dev *indio_dev,
443 			     struct iio_chan_spec const *chan,
444 			     int val, int val2, long mask)
445 {
446 	struct adxl345_state *st = iio_priv(indio_dev);
447 	s64 n;
448 
449 	switch (mask) {
450 	case IIO_CHAN_INFO_CALIBBIAS:
451 		/*
452 		 * 8-bit resolution at +/- 2g, that is 4x accel data scale
453 		 * factor
454 		 */
455 		return regmap_write(st->regmap,
456 				    ADXL345_REG_OFS_AXIS(chan->address),
457 				    val / 4);
458 	case IIO_CHAN_INFO_SAMP_FREQ:
459 		n = div_s64(val * NANOHZ_PER_HZ + val2,
460 			    ADXL345_BASE_RATE_NANO_HZ);
461 
462 		return regmap_update_bits(st->regmap, ADXL345_REG_BW_RATE,
463 					  ADXL345_BW_RATE,
464 					  clamp_val(ilog2(n), 0,
465 						    ADXL345_BW_RATE));
466 	}
467 
468 	return -EINVAL;
469 }
470 
adxl345_read_event_config(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir)471 static int adxl345_read_event_config(struct iio_dev *indio_dev,
472 				     const struct iio_chan_spec *chan,
473 				     enum iio_event_type type,
474 				     enum iio_event_direction dir)
475 {
476 	struct adxl345_state *st = iio_priv(indio_dev);
477 	bool int_en;
478 	int ret;
479 
480 	switch (type) {
481 	case IIO_EV_TYPE_GESTURE:
482 		switch (dir) {
483 		case IIO_EV_DIR_SINGLETAP:
484 			ret = adxl345_is_tap_en(st, chan->channel2,
485 						ADXL345_SINGLE_TAP, &int_en);
486 			if (ret)
487 				return ret;
488 			return int_en;
489 		case IIO_EV_DIR_DOUBLETAP:
490 			ret = adxl345_is_tap_en(st, chan->channel2,
491 						ADXL345_DOUBLE_TAP, &int_en);
492 			if (ret)
493 				return ret;
494 			return int_en;
495 		default:
496 			return -EINVAL;
497 		}
498 	default:
499 		return -EINVAL;
500 	}
501 }
502 
adxl345_write_event_config(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,bool state)503 static int adxl345_write_event_config(struct iio_dev *indio_dev,
504 				      const struct iio_chan_spec *chan,
505 				      enum iio_event_type type,
506 				      enum iio_event_direction dir,
507 				      bool state)
508 {
509 	struct adxl345_state *st = iio_priv(indio_dev);
510 
511 	switch (type) {
512 	case IIO_EV_TYPE_GESTURE:
513 		switch (dir) {
514 		case IIO_EV_DIR_SINGLETAP:
515 			return adxl345_set_singletap_en(st, chan->channel2, state);
516 		case IIO_EV_DIR_DOUBLETAP:
517 			return adxl345_set_doubletap_en(st, state);
518 		default:
519 			return -EINVAL;
520 		}
521 	default:
522 		return -EINVAL;
523 	}
524 }
525 
adxl345_read_event_value(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,enum iio_event_info info,int * val,int * val2)526 static int adxl345_read_event_value(struct iio_dev *indio_dev,
527 				    const struct iio_chan_spec *chan,
528 				    enum iio_event_type type,
529 				    enum iio_event_direction dir,
530 				    enum iio_event_info info,
531 				    int *val, int *val2)
532 {
533 	struct adxl345_state *st = iio_priv(indio_dev);
534 	unsigned int tap_threshold;
535 	int ret;
536 
537 	switch (type) {
538 	case IIO_EV_TYPE_GESTURE:
539 		switch (info) {
540 		case IIO_EV_INFO_VALUE:
541 			/*
542 			 * The scale factor would be 62.5mg/LSB (i.e. 0xFF = 16g) but
543 			 * not applied here. In context of this general purpose sensor,
544 			 * what imports is rather signal intensity than the absolute
545 			 * measured g value.
546 			 */
547 			ret = regmap_read(st->regmap, ADXL345_REG_THRESH_TAP,
548 					  &tap_threshold);
549 			if (ret)
550 				return ret;
551 			*val = sign_extend32(tap_threshold, 7);
552 			return IIO_VAL_INT;
553 		case IIO_EV_INFO_TIMEOUT:
554 			*val = st->tap_duration_us;
555 			*val2 = 1000000;
556 			return IIO_VAL_FRACTIONAL;
557 		case IIO_EV_INFO_RESET_TIMEOUT:
558 			*val = st->tap_window_us;
559 			*val2 = 1000000;
560 			return IIO_VAL_FRACTIONAL;
561 		case IIO_EV_INFO_TAP2_MIN_DELAY:
562 			*val = st->tap_latent_us;
563 			*val2 = 1000000;
564 			return IIO_VAL_FRACTIONAL;
565 		default:
566 			return -EINVAL;
567 		}
568 	default:
569 		return -EINVAL;
570 	}
571 }
572 
adxl345_write_event_value(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,enum iio_event_info info,int val,int val2)573 static int adxl345_write_event_value(struct iio_dev *indio_dev,
574 				     const struct iio_chan_spec *chan,
575 				     enum iio_event_type type,
576 				     enum iio_event_direction dir,
577 				     enum iio_event_info info,
578 				     int val, int val2)
579 {
580 	struct adxl345_state *st = iio_priv(indio_dev);
581 	int ret;
582 
583 	ret = adxl345_set_measure_en(st, false);
584 	if (ret)
585 		return ret;
586 
587 	switch (type) {
588 	case IIO_EV_TYPE_GESTURE:
589 		switch (info) {
590 		case IIO_EV_INFO_VALUE:
591 			ret = regmap_write(st->regmap, ADXL345_REG_THRESH_TAP,
592 					   min(val, 0xFF));
593 			if (ret)
594 				return ret;
595 			break;
596 		case IIO_EV_INFO_TIMEOUT:
597 			ret = adxl345_set_tap_duration(st, val, val2);
598 			if (ret)
599 				return ret;
600 			break;
601 		case IIO_EV_INFO_RESET_TIMEOUT:
602 			ret = adxl345_set_tap_window(st, val, val2);
603 			if (ret)
604 				return ret;
605 			break;
606 		case IIO_EV_INFO_TAP2_MIN_DELAY:
607 			ret = adxl345_set_tap_latent(st, val, val2);
608 			if (ret)
609 				return ret;
610 			break;
611 		default:
612 			return -EINVAL;
613 		}
614 		break;
615 	default:
616 		return -EINVAL;
617 	}
618 
619 	return adxl345_set_measure_en(st, true);
620 }
621 
adxl345_reg_access(struct iio_dev * indio_dev,unsigned int reg,unsigned int writeval,unsigned int * readval)622 static int adxl345_reg_access(struct iio_dev *indio_dev, unsigned int reg,
623 			      unsigned int writeval, unsigned int *readval)
624 {
625 	struct adxl345_state *st = iio_priv(indio_dev);
626 
627 	if (readval)
628 		return regmap_read(st->regmap, reg, readval);
629 	return regmap_write(st->regmap, reg, writeval);
630 }
631 
adxl345_set_watermark(struct iio_dev * indio_dev,unsigned int value)632 static int adxl345_set_watermark(struct iio_dev *indio_dev, unsigned int value)
633 {
634 	struct adxl345_state *st = iio_priv(indio_dev);
635 	const unsigned int fifo_mask = 0x1F, watermark_mask = 0x02;
636 	int ret;
637 
638 	value = min(value, ADXL345_FIFO_SIZE - 1);
639 
640 	ret = regmap_update_bits(st->regmap, ADXL345_REG_FIFO_CTL, fifo_mask, value);
641 	if (ret)
642 		return ret;
643 
644 	st->watermark = value;
645 	return regmap_update_bits(st->regmap, ADXL345_REG_INT_ENABLE,
646 				  watermark_mask, ADXL345_INT_WATERMARK);
647 }
648 
adxl345_write_raw_get_fmt(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,long mask)649 static int adxl345_write_raw_get_fmt(struct iio_dev *indio_dev,
650 				     struct iio_chan_spec const *chan,
651 				     long mask)
652 {
653 	switch (mask) {
654 	case IIO_CHAN_INFO_CALIBBIAS:
655 		return IIO_VAL_INT;
656 	case IIO_CHAN_INFO_SAMP_FREQ:
657 		return IIO_VAL_INT_PLUS_NANO;
658 	default:
659 		return -EINVAL;
660 	}
661 }
662 
adxl345_powerdown(void * ptr)663 static void adxl345_powerdown(void *ptr)
664 {
665 	struct adxl345_state *st = ptr;
666 
667 	adxl345_set_measure_en(st, false);
668 }
669 
670 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL(
671 "0.09765625 0.1953125 0.390625 0.78125 1.5625 3.125 6.25 12.5 25 50 100 200 400 800 1600 3200"
672 );
673 
674 static struct attribute *adxl345_attrs[] = {
675 	&iio_const_attr_sampling_frequency_available.dev_attr.attr,
676 	NULL
677 };
678 
679 static const struct attribute_group adxl345_attrs_group = {
680 	.attrs = adxl345_attrs,
681 };
682 
adxl345_set_fifo(struct adxl345_state * st)683 static int adxl345_set_fifo(struct adxl345_state *st)
684 {
685 	unsigned int intio;
686 	int ret;
687 
688 	/* FIFO should only be configured while in standby mode */
689 	ret = adxl345_set_measure_en(st, false);
690 	if (ret)
691 		return ret;
692 
693 	ret = regmap_read(st->regmap, ADXL345_REG_INT_MAP, &intio);
694 	if (ret)
695 		return ret;
696 
697 	ret = regmap_write(st->regmap, ADXL345_REG_FIFO_CTL,
698 			   FIELD_PREP(ADXL345_FIFO_CTL_SAMPLES_MSK,
699 				      st->watermark) |
700 			   FIELD_PREP(ADXL345_FIFO_CTL_TRIGGER_MSK, intio) |
701 			   FIELD_PREP(ADXL345_FIFO_CTL_MODE_MSK,
702 				      st->fifo_mode));
703 	if (ret)
704 		return ret;
705 
706 	return adxl345_set_measure_en(st, true);
707 }
708 
709 /**
710  * adxl345_get_samples() - Read number of FIFO entries.
711  * @st: The initialized state instance of this driver.
712  *
713  * The sensor does not support treating any axis individually, or exclude them
714  * from measuring.
715  *
716  * Return: negative error, or value.
717  */
adxl345_get_samples(struct adxl345_state * st)718 static int adxl345_get_samples(struct adxl345_state *st)
719 {
720 	unsigned int regval = 0;
721 	int ret;
722 
723 	ret = regmap_read(st->regmap, ADXL345_REG_FIFO_STATUS, &regval);
724 	if (ret)
725 		return ret;
726 
727 	return FIELD_GET(ADXL345_REG_FIFO_STATUS_MSK, regval);
728 }
729 
730 /**
731  * adxl345_fifo_transfer() - Read samples number of elements.
732  * @st: The instance of the state object of this sensor.
733  * @samples: The number of lines in the FIFO referred to as fifo_entry.
734  *
735  * It is recommended that a multiple-byte read of all registers be performed to
736  * prevent a change in data between reads of sequential registers. That is to
737  * read out the data registers X0, X1, Y0, Y1, Z0, Z1, i.e. 6 bytes at once.
738  *
739  * Return: 0 or error value.
740  */
adxl345_fifo_transfer(struct adxl345_state * st,int samples)741 static int adxl345_fifo_transfer(struct adxl345_state *st, int samples)
742 {
743 	size_t count;
744 	int i, ret = 0;
745 
746 	/* count is the 3x the fifo_buf element size, hence 6B */
747 	count = sizeof(st->fifo_buf[0]) * ADXL345_DIRS;
748 	for (i = 0; i < samples; i++) {
749 		/* read 3x 2 byte elements from base address into next fifo_buf position */
750 		ret = regmap_bulk_read(st->regmap, ADXL345_REG_XYZ_BASE,
751 				       st->fifo_buf + (i * count / 2), count);
752 		if (ret)
753 			return ret;
754 
755 		/*
756 		 * To ensure that the FIFO has completely popped, there must be at least 5
757 		 * us between the end of reading the data registers, signified by the
758 		 * transition to register 0x38 from 0x37 or the CS pin going high, and the
759 		 * start of new reads of the FIFO or reading the FIFO_STATUS register. For
760 		 * SPI operation at 1.5 MHz or lower, the register addressing portion of the
761 		 * transmission is sufficient delay to ensure the FIFO has completely
762 		 * popped. It is necessary for SPI operation greater than 1.5 MHz to
763 		 * de-assert the CS pin to ensure a total of 5 us, which is at most 3.4 us
764 		 * at 5 MHz operation.
765 		 */
766 		if (st->fifo_delay && samples > 1)
767 			udelay(3);
768 	}
769 	return ret;
770 }
771 
772 /**
773  * adxl345_fifo_reset() - Empty the FIFO in error condition.
774  * @st: The instance to the state object of the sensor.
775  *
776  * Read all elements of the FIFO. Reading the interrupt source register
777  * resets the sensor.
778  */
adxl345_fifo_reset(struct adxl345_state * st)779 static void adxl345_fifo_reset(struct adxl345_state *st)
780 {
781 	int regval;
782 	int samples;
783 
784 	adxl345_set_measure_en(st, false);
785 
786 	samples = adxl345_get_samples(st);
787 	if (samples > 0)
788 		adxl345_fifo_transfer(st, samples);
789 
790 	regmap_read(st->regmap, ADXL345_REG_INT_SOURCE, &regval);
791 
792 	adxl345_set_measure_en(st, true);
793 }
794 
adxl345_buffer_postenable(struct iio_dev * indio_dev)795 static int adxl345_buffer_postenable(struct iio_dev *indio_dev)
796 {
797 	struct adxl345_state *st = iio_priv(indio_dev);
798 
799 	st->fifo_mode = ADXL345_FIFO_STREAM;
800 	return adxl345_set_fifo(st);
801 }
802 
adxl345_buffer_predisable(struct iio_dev * indio_dev)803 static int adxl345_buffer_predisable(struct iio_dev *indio_dev)
804 {
805 	struct adxl345_state *st = iio_priv(indio_dev);
806 	int ret;
807 
808 	st->fifo_mode = ADXL345_FIFO_BYPASS;
809 	ret = adxl345_set_fifo(st);
810 	if (ret)
811 		return ret;
812 
813 	return regmap_write(st->regmap, ADXL345_REG_INT_ENABLE, 0x00);
814 }
815 
816 static const struct iio_buffer_setup_ops adxl345_buffer_ops = {
817 	.postenable = adxl345_buffer_postenable,
818 	.predisable = adxl345_buffer_predisable,
819 };
820 
adxl345_fifo_push(struct iio_dev * indio_dev,int samples)821 static int adxl345_fifo_push(struct iio_dev *indio_dev,
822 			     int samples)
823 {
824 	struct adxl345_state *st = iio_priv(indio_dev);
825 	int i, ret;
826 
827 	if (samples <= 0)
828 		return -EINVAL;
829 
830 	ret = adxl345_fifo_transfer(st, samples);
831 	if (ret)
832 		return ret;
833 
834 	for (i = 0; i < ADXL345_DIRS * samples; i += ADXL345_DIRS)
835 		iio_push_to_buffers(indio_dev, &st->fifo_buf[i]);
836 
837 	return 0;
838 }
839 
adxl345_push_event(struct iio_dev * indio_dev,int int_stat,enum iio_modifier tap_dir)840 static int adxl345_push_event(struct iio_dev *indio_dev, int int_stat,
841 			      enum iio_modifier tap_dir)
842 {
843 	s64 ts = iio_get_time_ns(indio_dev);
844 	struct adxl345_state *st = iio_priv(indio_dev);
845 	int samples;
846 	int ret = -ENOENT;
847 
848 	if (FIELD_GET(ADXL345_INT_SINGLE_TAP, int_stat)) {
849 		ret = iio_push_event(indio_dev,
850 				     IIO_MOD_EVENT_CODE(IIO_ACCEL, 0, tap_dir,
851 							IIO_EV_TYPE_GESTURE,
852 							IIO_EV_DIR_SINGLETAP),
853 				     ts);
854 		if (ret)
855 			return ret;
856 	}
857 
858 	if (FIELD_GET(ADXL345_INT_DOUBLE_TAP, int_stat)) {
859 		ret = iio_push_event(indio_dev,
860 				     IIO_MOD_EVENT_CODE(IIO_ACCEL, 0, tap_dir,
861 							IIO_EV_TYPE_GESTURE,
862 							IIO_EV_DIR_DOUBLETAP),
863 				     ts);
864 		if (ret)
865 			return ret;
866 	}
867 
868 	if (FIELD_GET(ADXL345_INT_WATERMARK, int_stat)) {
869 		samples = adxl345_get_samples(st);
870 		if (samples < 0)
871 			return -EINVAL;
872 
873 		if (adxl345_fifo_push(indio_dev, samples) < 0)
874 			return -EINVAL;
875 
876 		ret = 0;
877 	}
878 
879 	return ret;
880 }
881 
882 /**
883  * adxl345_irq_handler() - Handle irqs of the ADXL345.
884  * @irq: The irq being handled.
885  * @p: The struct iio_device pointer for the device.
886  *
887  * Return: The interrupt was handled.
888  */
adxl345_irq_handler(int irq,void * p)889 static irqreturn_t adxl345_irq_handler(int irq, void *p)
890 {
891 	struct iio_dev *indio_dev = p;
892 	struct adxl345_state *st = iio_priv(indio_dev);
893 	unsigned int regval;
894 	enum iio_modifier tap_dir = IIO_NO_MOD;
895 	u32 axis_ctrl;
896 	int int_stat;
897 	int ret;
898 
899 	ret = regmap_read(st->regmap, ADXL345_REG_TAP_AXIS, &axis_ctrl);
900 	if (ret)
901 		return IRQ_NONE;
902 
903 	if (FIELD_GET(ADXL345_REG_TAP_AXIS_MSK, axis_ctrl)) {
904 		ret = regmap_read(st->regmap, ADXL345_REG_ACT_TAP_STATUS, &regval);
905 		if (ret)
906 			return IRQ_NONE;
907 
908 		if (FIELD_GET(ADXL345_TAP_Z_EN, regval))
909 			tap_dir = IIO_MOD_Z;
910 		else if (FIELD_GET(ADXL345_TAP_Y_EN, regval))
911 			tap_dir = IIO_MOD_Y;
912 		else if (FIELD_GET(ADXL345_TAP_X_EN, regval))
913 			tap_dir = IIO_MOD_X;
914 	}
915 
916 	if (regmap_read(st->regmap, ADXL345_REG_INT_SOURCE, &int_stat))
917 		return IRQ_NONE;
918 
919 	if (adxl345_push_event(indio_dev, int_stat, tap_dir))
920 		goto err;
921 
922 	if (FIELD_GET(ADXL345_INT_OVERRUN, int_stat))
923 		goto err;
924 
925 	return IRQ_HANDLED;
926 
927 err:
928 	adxl345_fifo_reset(st);
929 
930 	return IRQ_HANDLED;
931 }
932 
933 static const struct iio_info adxl345_info = {
934 	.attrs		= &adxl345_attrs_group,
935 	.read_raw	= adxl345_read_raw,
936 	.write_raw	= adxl345_write_raw,
937 	.write_raw_get_fmt	= adxl345_write_raw_get_fmt,
938 	.read_event_config = adxl345_read_event_config,
939 	.write_event_config = adxl345_write_event_config,
940 	.read_event_value = adxl345_read_event_value,
941 	.write_event_value = adxl345_write_event_value,
942 	.debugfs_reg_access = &adxl345_reg_access,
943 	.hwfifo_set_watermark = adxl345_set_watermark,
944 };
945 
946 /**
947  * adxl345_core_probe() - Probe and setup for the accelerometer.
948  * @dev:	Driver model representation of the device
949  * @regmap:	Regmap instance for the device
950  * @fifo_delay_default: Using FIFO with SPI needs delay
951  * @setup:	Setup routine to be executed right before the standard device
952  *		setup
953  *
954  * For SPI operation greater than 1.6 MHz, it is necessary to deassert the CS
955  * pin to ensure a total delay of 5 us; otherwise, the delay is not sufficient.
956  * The total delay necessary for 5 MHz operation is at most 3.4 us. This is not
957  * a concern when using I2C mode because the communication rate is low enough
958  * to ensure a sufficient delay between FIFO reads.
959  * Ref: "Retrieving Data from FIFO", p. 21 of 36, Data Sheet ADXL345 Rev. G
960  *
961  * Return: 0 on success, negative errno on error
962  */
adxl345_core_probe(struct device * dev,struct regmap * regmap,bool fifo_delay_default,int (* setup)(struct device *,struct regmap *))963 int adxl345_core_probe(struct device *dev, struct regmap *regmap,
964 		       bool fifo_delay_default,
965 		       int (*setup)(struct device*, struct regmap*))
966 {
967 	struct adxl345_state *st;
968 	struct iio_dev *indio_dev;
969 	u32 regval;
970 	u8 intio = ADXL345_INT1;
971 	unsigned int data_format_mask = (ADXL345_DATA_FORMAT_RANGE |
972 					 ADXL345_DATA_FORMAT_JUSTIFY |
973 					 ADXL345_DATA_FORMAT_FULL_RES |
974 					 ADXL345_DATA_FORMAT_SELF_TEST);
975 	unsigned int tap_threshold;
976 	int ret;
977 
978 	indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
979 	if (!indio_dev)
980 		return -ENOMEM;
981 
982 	st = iio_priv(indio_dev);
983 	st->regmap = regmap;
984 	st->info = device_get_match_data(dev);
985 	if (!st->info)
986 		return -ENODEV;
987 	st->fifo_delay = fifo_delay_default;
988 
989 	/* Init with reasonable values */
990 	tap_threshold = 48;			/*   48 [0x30] -> ~3g     */
991 	st->tap_duration_us = 16;		/*   16 [0x10] -> .010    */
992 	st->tap_window_us = 64;			/*   64 [0x40] -> .080    */
993 	st->tap_latent_us = 16;			/*   16 [0x10] -> .020    */
994 
995 	indio_dev->name = st->info->name;
996 	indio_dev->info = &adxl345_info;
997 	indio_dev->modes = INDIO_DIRECT_MODE;
998 	indio_dev->channels = adxl345_channels;
999 	indio_dev->num_channels = ARRAY_SIZE(adxl345_channels);
1000 	indio_dev->available_scan_masks = adxl345_scan_masks;
1001 
1002 	/* Reset interrupts at start up */
1003 	ret = regmap_write(st->regmap, ADXL345_REG_INT_ENABLE, 0x00);
1004 	if (ret)
1005 		return ret;
1006 
1007 	if (setup) {
1008 		/* Perform optional initial bus specific configuration */
1009 		ret = setup(dev, st->regmap);
1010 		if (ret)
1011 			return ret;
1012 
1013 		/* Enable full-resolution mode */
1014 		ret = regmap_update_bits(st->regmap, ADXL345_REG_DATA_FORMAT,
1015 					 data_format_mask,
1016 					 ADXL345_DATA_FORMAT_FULL_RES);
1017 		if (ret)
1018 			return dev_err_probe(dev, ret,
1019 					     "Failed to set data range\n");
1020 
1021 	} else {
1022 		/* Enable full-resolution mode (init all data_format bits) */
1023 		ret = regmap_write(st->regmap, ADXL345_REG_DATA_FORMAT,
1024 				   ADXL345_DATA_FORMAT_FULL_RES);
1025 		if (ret)
1026 			return dev_err_probe(dev, ret,
1027 					     "Failed to set data range\n");
1028 	}
1029 
1030 	ret = regmap_read(st->regmap, ADXL345_REG_DEVID, &regval);
1031 	if (ret)
1032 		return dev_err_probe(dev, ret, "Error reading device ID\n");
1033 
1034 	if (regval != ADXL345_DEVID)
1035 		return dev_err_probe(dev, -ENODEV, "Invalid device ID: %x, expected %x\n",
1036 				     regval, ADXL345_DEVID);
1037 
1038 	/* Enable measurement mode */
1039 	ret = adxl345_set_measure_en(st, true);
1040 	if (ret)
1041 		return dev_err_probe(dev, ret, "Failed to enable measurement mode\n");
1042 
1043 	ret = devm_add_action_or_reset(dev, adxl345_powerdown, st);
1044 	if (ret)
1045 		return ret;
1046 
1047 	st->irq = fwnode_irq_get_byname(dev_fwnode(dev), "INT1");
1048 	if (st->irq < 0) {
1049 		intio = ADXL345_INT2;
1050 		st->irq = fwnode_irq_get_byname(dev_fwnode(dev), "INT2");
1051 		if (st->irq < 0)
1052 			intio = ADXL345_INT_NONE;
1053 	}
1054 
1055 	if (intio != ADXL345_INT_NONE) {
1056 		/*
1057 		 * Any bits set to 0 in the INT map register send their respective
1058 		 * interrupts to the INT1 pin, whereas bits set to 1 send their respective
1059 		 * interrupts to the INT2 pin. The intio shall convert this accordingly.
1060 		 */
1061 		regval = intio ? 0xff : 0;
1062 
1063 		ret = regmap_write(st->regmap, ADXL345_REG_INT_MAP, regval);
1064 		if (ret)
1065 			return ret;
1066 
1067 		ret = regmap_write(st->regmap, ADXL345_REG_THRESH_TAP, tap_threshold);
1068 		if (ret)
1069 			return ret;
1070 
1071 		/* FIFO_STREAM mode is going to be activated later */
1072 		ret = devm_iio_kfifo_buffer_setup(dev, indio_dev, &adxl345_buffer_ops);
1073 		if (ret)
1074 			return ret;
1075 
1076 		ret = devm_request_threaded_irq(dev, st->irq, NULL,
1077 						&adxl345_irq_handler,
1078 						IRQF_SHARED | IRQF_ONESHOT,
1079 						indio_dev->name, indio_dev);
1080 		if (ret)
1081 			return ret;
1082 	} else {
1083 		ret = regmap_write(st->regmap, ADXL345_REG_FIFO_CTL,
1084 				   FIELD_PREP(ADXL345_FIFO_CTL_MODE_MSK,
1085 					      ADXL345_FIFO_BYPASS));
1086 		if (ret)
1087 			return ret;
1088 	}
1089 
1090 	return devm_iio_device_register(dev, indio_dev);
1091 }
1092 EXPORT_SYMBOL_NS_GPL(adxl345_core_probe, "IIO_ADXL345");
1093 
1094 MODULE_AUTHOR("Eva Rachel Retuya <eraretuya@gmail.com>");
1095 MODULE_DESCRIPTION("ADXL345 3-Axis Digital Accelerometer core driver");
1096 MODULE_LICENSE("GPL v2");
1097