xref: /linux/drivers/iio/accel/adxl345_core.c (revision 2c1ed907520c50326b8f604907a8478b27881a2e)
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/interrupt.h>
12 #include <linux/module.h>
13 #include <linux/property.h>
14 #include <linux/regmap.h>
15 #include <linux/units.h>
16 
17 #include <linux/iio/iio.h>
18 #include <linux/iio/sysfs.h>
19 #include <linux/iio/buffer.h>
20 #include <linux/iio/kfifo_buf.h>
21 
22 #include "adxl345.h"
23 
24 #define ADXL345_FIFO_BYPASS	0
25 #define ADXL345_FIFO_FIFO	1
26 #define ADXL345_FIFO_STREAM	2
27 
28 #define ADXL345_DIRS 3
29 
30 #define ADXL345_INT_NONE		0xff
31 #define ADXL345_INT1			0
32 #define ADXL345_INT2			1
33 
34 struct adxl345_state {
35 	const struct adxl345_chip_info *info;
36 	struct regmap *regmap;
37 	bool fifo_delay; /* delay: delay is needed for SPI */
38 	int irq;
39 	u8 intio;
40 	u8 int_map;
41 	u8 watermark;
42 	u8 fifo_mode;
43 	__le16 fifo_buf[ADXL345_DIRS * ADXL345_FIFO_SIZE + 1] __aligned(IIO_DMA_MINALIGN);
44 };
45 
46 #define ADXL345_CHANNEL(index, reg, axis) {					\
47 	.type = IIO_ACCEL,						\
48 	.modified = 1,							\
49 	.channel2 = IIO_MOD_##axis,					\
50 	.address = (reg),						\
51 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |			\
52 		BIT(IIO_CHAN_INFO_CALIBBIAS),				\
53 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |		\
54 		BIT(IIO_CHAN_INFO_SAMP_FREQ),				\
55 	.scan_index = (index),				\
56 	.scan_type = {					\
57 		.sign = 's',				\
58 		.realbits = 13,				\
59 		.storagebits = 16,			\
60 		.endianness = IIO_LE,			\
61 	},						\
62 }
63 
64 enum adxl345_chans {
65 	chan_x, chan_y, chan_z,
66 };
67 
68 static const struct iio_chan_spec adxl345_channels[] = {
69 	ADXL345_CHANNEL(0, chan_x, X),
70 	ADXL345_CHANNEL(1, chan_y, Y),
71 	ADXL345_CHANNEL(2, chan_z, Z),
72 };
73 
74 static const unsigned long adxl345_scan_masks[] = {
75 	BIT(chan_x) | BIT(chan_y) | BIT(chan_z),
76 	0
77 };
78 
adxl345_set_interrupts(struct adxl345_state * st)79 static int adxl345_set_interrupts(struct adxl345_state *st)
80 {
81 	int ret;
82 	unsigned int int_enable = st->int_map;
83 	unsigned int int_map;
84 
85 	/*
86 	 * Any bits set to 0 in the INT map register send their respective
87 	 * interrupts to the INT1 pin, whereas bits set to 1 send their respective
88 	 * interrupts to the INT2 pin. The intio shall convert this accordingly.
89 	 */
90 	int_map = FIELD_GET(ADXL345_REG_INT_SOURCE_MSK,
91 			    st->intio ? st->int_map : ~st->int_map);
92 
93 	ret = regmap_write(st->regmap, ADXL345_REG_INT_MAP, int_map);
94 	if (ret)
95 		return ret;
96 
97 	return regmap_write(st->regmap, ADXL345_REG_INT_ENABLE, int_enable);
98 }
99 
adxl345_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)100 static int adxl345_read_raw(struct iio_dev *indio_dev,
101 			    struct iio_chan_spec const *chan,
102 			    int *val, int *val2, long mask)
103 {
104 	struct adxl345_state *st = iio_priv(indio_dev);
105 	__le16 accel;
106 	long long samp_freq_nhz;
107 	unsigned int regval;
108 	int ret;
109 
110 	switch (mask) {
111 	case IIO_CHAN_INFO_RAW:
112 		/*
113 		 * Data is stored in adjacent registers:
114 		 * ADXL345_REG_DATA(X0/Y0/Z0) contain the least significant byte
115 		 * and ADXL345_REG_DATA(X0/Y0/Z0) + 1 the most significant byte
116 		 */
117 		ret = regmap_bulk_read(st->regmap,
118 				       ADXL345_REG_DATA_AXIS(chan->address),
119 				       &accel, sizeof(accel));
120 		if (ret < 0)
121 			return ret;
122 
123 		*val = sign_extend32(le16_to_cpu(accel), 12);
124 		return IIO_VAL_INT;
125 	case IIO_CHAN_INFO_SCALE:
126 		*val = 0;
127 		*val2 = st->info->uscale;
128 		return IIO_VAL_INT_PLUS_MICRO;
129 	case IIO_CHAN_INFO_CALIBBIAS:
130 		ret = regmap_read(st->regmap,
131 				  ADXL345_REG_OFS_AXIS(chan->address), &regval);
132 		if (ret < 0)
133 			return ret;
134 		/*
135 		 * 8-bit resolution at +/- 2g, that is 4x accel data scale
136 		 * factor
137 		 */
138 		*val = sign_extend32(regval, 7) * 4;
139 
140 		return IIO_VAL_INT;
141 	case IIO_CHAN_INFO_SAMP_FREQ:
142 		ret = regmap_read(st->regmap, ADXL345_REG_BW_RATE, &regval);
143 		if (ret < 0)
144 			return ret;
145 
146 		samp_freq_nhz = ADXL345_BASE_RATE_NANO_HZ <<
147 				(regval & ADXL345_BW_RATE);
148 		*val = div_s64_rem(samp_freq_nhz, NANOHZ_PER_HZ, val2);
149 
150 		return IIO_VAL_INT_PLUS_NANO;
151 	}
152 
153 	return -EINVAL;
154 }
155 
adxl345_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)156 static int adxl345_write_raw(struct iio_dev *indio_dev,
157 			     struct iio_chan_spec const *chan,
158 			     int val, int val2, long mask)
159 {
160 	struct adxl345_state *st = iio_priv(indio_dev);
161 	s64 n;
162 
163 	switch (mask) {
164 	case IIO_CHAN_INFO_CALIBBIAS:
165 		/*
166 		 * 8-bit resolution at +/- 2g, that is 4x accel data scale
167 		 * factor
168 		 */
169 		return regmap_write(st->regmap,
170 				    ADXL345_REG_OFS_AXIS(chan->address),
171 				    val / 4);
172 	case IIO_CHAN_INFO_SAMP_FREQ:
173 		n = div_s64(val * NANOHZ_PER_HZ + val2,
174 			    ADXL345_BASE_RATE_NANO_HZ);
175 
176 		return regmap_update_bits(st->regmap, ADXL345_REG_BW_RATE,
177 					  ADXL345_BW_RATE,
178 					  clamp_val(ilog2(n), 0,
179 						    ADXL345_BW_RATE));
180 	}
181 
182 	return -EINVAL;
183 }
184 
adxl345_set_watermark(struct iio_dev * indio_dev,unsigned int value)185 static int adxl345_set_watermark(struct iio_dev *indio_dev, unsigned int value)
186 {
187 	struct adxl345_state *st = iio_priv(indio_dev);
188 	unsigned int fifo_mask = 0x1F;
189 	int ret;
190 
191 	value = min(value, ADXL345_FIFO_SIZE - 1);
192 
193 	ret = regmap_update_bits(st->regmap, ADXL345_REG_FIFO_CTL, fifo_mask, value);
194 	if (ret)
195 		return ret;
196 
197 	st->watermark = value;
198 	st->int_map |= ADXL345_INT_WATERMARK;
199 
200 	return 0;
201 }
202 
adxl345_write_raw_get_fmt(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,long mask)203 static int adxl345_write_raw_get_fmt(struct iio_dev *indio_dev,
204 				     struct iio_chan_spec const *chan,
205 				     long mask)
206 {
207 	switch (mask) {
208 	case IIO_CHAN_INFO_CALIBBIAS:
209 		return IIO_VAL_INT;
210 	case IIO_CHAN_INFO_SAMP_FREQ:
211 		return IIO_VAL_INT_PLUS_NANO;
212 	default:
213 		return -EINVAL;
214 	}
215 }
216 
217 /**
218  * adxl345_set_measure_en() - Enable and disable measuring.
219  *
220  * @st: The device data.
221  * @en: Enable measurements, else standby mode.
222  *
223  * For lowest power operation, standby mode can be used. In standby mode,
224  * current consumption is supposed to be reduced to 0.1uA (typical). In this
225  * mode no measurements are made. Placing the device into standby mode
226  * preserves the contents of FIFO.
227  *
228  * Return: Returns 0 if successful, or a negative error value.
229  */
adxl345_set_measure_en(struct adxl345_state * st,bool en)230 static int adxl345_set_measure_en(struct adxl345_state *st, bool en)
231 {
232 	unsigned int val = en ? ADXL345_POWER_CTL_MEASURE : ADXL345_POWER_CTL_STANDBY;
233 
234 	return regmap_write(st->regmap, ADXL345_REG_POWER_CTL, val);
235 }
236 
adxl345_powerdown(void * ptr)237 static void adxl345_powerdown(void *ptr)
238 {
239 	struct adxl345_state *st = ptr;
240 
241 	adxl345_set_measure_en(st, false);
242 }
243 
244 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL(
245 "0.09765625 0.1953125 0.390625 0.78125 1.5625 3.125 6.25 12.5 25 50 100 200 400 800 1600 3200"
246 );
247 
248 static struct attribute *adxl345_attrs[] = {
249 	&iio_const_attr_sampling_frequency_available.dev_attr.attr,
250 	NULL
251 };
252 
253 static const struct attribute_group adxl345_attrs_group = {
254 	.attrs = adxl345_attrs,
255 };
256 
adxl345_set_fifo(struct adxl345_state * st)257 static int adxl345_set_fifo(struct adxl345_state *st)
258 {
259 	int ret;
260 
261 	/* FIFO should only be configured while in standby mode */
262 	ret = adxl345_set_measure_en(st, false);
263 	if (ret < 0)
264 		return ret;
265 
266 	ret = regmap_write(st->regmap, ADXL345_REG_FIFO_CTL,
267 			   FIELD_PREP(ADXL345_FIFO_CTL_SAMPLES_MSK,
268 				      st->watermark) |
269 			   FIELD_PREP(ADXL345_FIFO_CTL_TRIGGER_MSK,
270 				      st->intio) |
271 			   FIELD_PREP(ADXL345_FIFO_CTL_MODE_MSK,
272 				      st->fifo_mode));
273 	if (ret < 0)
274 		return ret;
275 
276 	return adxl345_set_measure_en(st, true);
277 }
278 
279 /**
280  * adxl345_get_samples() - Read number of FIFO entries.
281  * @st: The initialized state instance of this driver.
282  *
283  * The sensor does not support treating any axis individually, or exclude them
284  * from measuring.
285  *
286  * Return: negative error, or value.
287  */
adxl345_get_samples(struct adxl345_state * st)288 static int adxl345_get_samples(struct adxl345_state *st)
289 {
290 	unsigned int regval = 0;
291 	int ret;
292 
293 	ret = regmap_read(st->regmap, ADXL345_REG_FIFO_STATUS, &regval);
294 	if (ret < 0)
295 		return ret;
296 
297 	return FIELD_GET(ADXL345_REG_FIFO_STATUS_MSK, regval);
298 }
299 
300 /**
301  * adxl345_fifo_transfer() - Read samples number of elements.
302  * @st: The instance of the state object of this sensor.
303  * @samples: The number of lines in the FIFO referred to as fifo_entry.
304  *
305  * It is recommended that a multiple-byte read of all registers be performed to
306  * prevent a change in data between reads of sequential registers. That is to
307  * read out the data registers X0, X1, Y0, Y1, Z0, Z1, i.e. 6 bytes at once.
308  *
309  * Return: 0 or error value.
310  */
adxl345_fifo_transfer(struct adxl345_state * st,int samples)311 static int adxl345_fifo_transfer(struct adxl345_state *st, int samples)
312 {
313 	size_t count;
314 	int i, ret = 0;
315 
316 	/* count is the 3x the fifo_buf element size, hence 6B */
317 	count = sizeof(st->fifo_buf[0]) * ADXL345_DIRS;
318 	for (i = 0; i < samples; i++) {
319 		/* read 3x 2 byte elements from base address into next fifo_buf position */
320 		ret = regmap_bulk_read(st->regmap, ADXL345_REG_XYZ_BASE,
321 				       st->fifo_buf + (i * count / 2), count);
322 		if (ret < 0)
323 			return ret;
324 
325 		/*
326 		 * To ensure that the FIFO has completely popped, there must be at least 5
327 		 * us between the end of reading the data registers, signified by the
328 		 * transition to register 0x38 from 0x37 or the CS pin going high, and the
329 		 * start of new reads of the FIFO or reading the FIFO_STATUS register. For
330 		 * SPI operation at 1.5 MHz or lower, the register addressing portion of the
331 		 * transmission is sufficient delay to ensure the FIFO has completely
332 		 * popped. It is necessary for SPI operation greater than 1.5 MHz to
333 		 * de-assert the CS pin to ensure a total of 5 us, which is at most 3.4 us
334 		 * at 5 MHz operation.
335 		 */
336 		if (st->fifo_delay && samples > 1)
337 			udelay(3);
338 	}
339 	return ret;
340 }
341 
342 /**
343  * adxl345_fifo_reset() - Empty the FIFO in error condition.
344  * @st: The instance to the state object of the sensor.
345  *
346  * Read all elements of the FIFO. Reading the interrupt source register
347  * resets the sensor.
348  */
adxl345_fifo_reset(struct adxl345_state * st)349 static void adxl345_fifo_reset(struct adxl345_state *st)
350 {
351 	int regval;
352 	int samples;
353 
354 	adxl345_set_measure_en(st, false);
355 
356 	samples = adxl345_get_samples(st);
357 	if (samples > 0)
358 		adxl345_fifo_transfer(st, samples);
359 
360 	regmap_read(st->regmap, ADXL345_REG_INT_SOURCE, &regval);
361 
362 	adxl345_set_measure_en(st, true);
363 }
364 
adxl345_buffer_postenable(struct iio_dev * indio_dev)365 static int adxl345_buffer_postenable(struct iio_dev *indio_dev)
366 {
367 	struct adxl345_state *st = iio_priv(indio_dev);
368 	int ret;
369 
370 	ret = adxl345_set_interrupts(st);
371 	if (ret < 0)
372 		return ret;
373 
374 	st->fifo_mode = ADXL345_FIFO_STREAM;
375 	return adxl345_set_fifo(st);
376 }
377 
adxl345_buffer_predisable(struct iio_dev * indio_dev)378 static int adxl345_buffer_predisable(struct iio_dev *indio_dev)
379 {
380 	struct adxl345_state *st = iio_priv(indio_dev);
381 	int ret;
382 
383 	st->fifo_mode = ADXL345_FIFO_BYPASS;
384 	ret = adxl345_set_fifo(st);
385 	if (ret < 0)
386 		return ret;
387 
388 	st->int_map = 0x00;
389 	return adxl345_set_interrupts(st);
390 }
391 
392 static const struct iio_buffer_setup_ops adxl345_buffer_ops = {
393 	.postenable = adxl345_buffer_postenable,
394 	.predisable = adxl345_buffer_predisable,
395 };
396 
adxl345_get_status(struct adxl345_state * st)397 static int adxl345_get_status(struct adxl345_state *st)
398 {
399 	int ret;
400 	unsigned int regval;
401 
402 	ret = regmap_read(st->regmap, ADXL345_REG_INT_SOURCE, &regval);
403 	if (ret < 0)
404 		return ret;
405 
406 	return FIELD_GET(ADXL345_REG_INT_SOURCE_MSK, regval);
407 }
408 
adxl345_fifo_push(struct iio_dev * indio_dev,int samples)409 static int adxl345_fifo_push(struct iio_dev *indio_dev,
410 			     int samples)
411 {
412 	struct adxl345_state *st = iio_priv(indio_dev);
413 	int i, ret;
414 
415 	if (samples <= 0)
416 		return -EINVAL;
417 
418 	ret = adxl345_fifo_transfer(st, samples);
419 	if (ret)
420 		return ret;
421 
422 	for (i = 0; i < ADXL345_DIRS * samples; i += ADXL345_DIRS)
423 		iio_push_to_buffers(indio_dev, &st->fifo_buf[i]);
424 
425 	return 0;
426 }
427 
428 /**
429  * adxl345_irq_handler() - Handle irqs of the ADXL345.
430  * @irq: The irq being handled.
431  * @p: The struct iio_device pointer for the device.
432  *
433  * Return: The interrupt was handled.
434  */
adxl345_irq_handler(int irq,void * p)435 static irqreturn_t adxl345_irq_handler(int irq, void *p)
436 {
437 	struct iio_dev *indio_dev = p;
438 	struct adxl345_state *st = iio_priv(indio_dev);
439 	int int_stat;
440 	int samples;
441 
442 	int_stat = adxl345_get_status(st);
443 	if (int_stat <= 0)
444 		return IRQ_NONE;
445 
446 	if (int_stat & ADXL345_INT_OVERRUN)
447 		goto err;
448 
449 	if (int_stat & ADXL345_INT_WATERMARK) {
450 		samples = adxl345_get_samples(st);
451 		if (samples < 0)
452 			goto err;
453 
454 		if (adxl345_fifo_push(indio_dev, samples) < 0)
455 			goto err;
456 	}
457 	return IRQ_HANDLED;
458 
459 err:
460 	adxl345_fifo_reset(st);
461 
462 	return IRQ_HANDLED;
463 }
464 
465 static const struct iio_info adxl345_info = {
466 	.attrs		= &adxl345_attrs_group,
467 	.read_raw	= adxl345_read_raw,
468 	.write_raw	= adxl345_write_raw,
469 	.write_raw_get_fmt	= adxl345_write_raw_get_fmt,
470 	.hwfifo_set_watermark = adxl345_set_watermark,
471 };
472 
473 /**
474  * adxl345_core_probe() - Probe and setup for the accelerometer.
475  * @dev:	Driver model representation of the device
476  * @regmap:	Regmap instance for the device
477  * @fifo_delay_default: Using FIFO with SPI needs delay
478  * @setup:	Setup routine to be executed right before the standard device
479  *		setup
480  *
481  * For SPI operation greater than 1.6 MHz, it is necessary to deassert the CS
482  * pin to ensure a total delay of 5 us; otherwise, the delay is not sufficient.
483  * The total delay necessary for 5 MHz operation is at most 3.4 us. This is not
484  * a concern when using I2C mode because the communication rate is low enough
485  * to ensure a sufficient delay between FIFO reads.
486  * Ref: "Retrieving Data from FIFO", p. 21 of 36, Data Sheet ADXL345 Rev. G
487  *
488  * Return: 0 on success, negative errno on error
489  */
adxl345_core_probe(struct device * dev,struct regmap * regmap,bool fifo_delay_default,int (* setup)(struct device *,struct regmap *))490 int adxl345_core_probe(struct device *dev, struct regmap *regmap,
491 		       bool fifo_delay_default,
492 		       int (*setup)(struct device*, struct regmap*))
493 {
494 	struct adxl345_state *st;
495 	struct iio_dev *indio_dev;
496 	u32 regval;
497 	unsigned int data_format_mask = (ADXL345_DATA_FORMAT_RANGE |
498 					 ADXL345_DATA_FORMAT_JUSTIFY |
499 					 ADXL345_DATA_FORMAT_FULL_RES |
500 					 ADXL345_DATA_FORMAT_SELF_TEST);
501 	int ret;
502 
503 	indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
504 	if (!indio_dev)
505 		return -ENOMEM;
506 
507 	st = iio_priv(indio_dev);
508 	st->regmap = regmap;
509 	st->info = device_get_match_data(dev);
510 	if (!st->info)
511 		return -ENODEV;
512 	st->fifo_delay = fifo_delay_default;
513 
514 	indio_dev->name = st->info->name;
515 	indio_dev->info = &adxl345_info;
516 	indio_dev->modes = INDIO_DIRECT_MODE;
517 	indio_dev->channels = adxl345_channels;
518 	indio_dev->num_channels = ARRAY_SIZE(adxl345_channels);
519 	indio_dev->available_scan_masks = adxl345_scan_masks;
520 
521 	if (setup) {
522 		/* Perform optional initial bus specific configuration */
523 		ret = setup(dev, st->regmap);
524 		if (ret)
525 			return ret;
526 
527 		/* Enable full-resolution mode */
528 		ret = regmap_update_bits(st->regmap, ADXL345_REG_DATA_FORMAT,
529 					 data_format_mask,
530 					 ADXL345_DATA_FORMAT_FULL_RES);
531 		if (ret)
532 			return dev_err_probe(dev, ret,
533 					     "Failed to set data range\n");
534 
535 	} else {
536 		/* Enable full-resolution mode (init all data_format bits) */
537 		ret = regmap_write(st->regmap, ADXL345_REG_DATA_FORMAT,
538 				   ADXL345_DATA_FORMAT_FULL_RES);
539 		if (ret)
540 			return dev_err_probe(dev, ret,
541 					     "Failed to set data range\n");
542 	}
543 
544 	ret = regmap_read(st->regmap, ADXL345_REG_DEVID, &regval);
545 	if (ret < 0)
546 		return dev_err_probe(dev, ret, "Error reading device ID\n");
547 
548 	if (regval != ADXL345_DEVID)
549 		return dev_err_probe(dev, -ENODEV, "Invalid device ID: %x, expected %x\n",
550 				     regval, ADXL345_DEVID);
551 
552 	/* Enable measurement mode */
553 	ret = adxl345_set_measure_en(st, true);
554 	if (ret < 0)
555 		return dev_err_probe(dev, ret, "Failed to enable measurement mode\n");
556 
557 	ret = devm_add_action_or_reset(dev, adxl345_powerdown, st);
558 	if (ret < 0)
559 		return ret;
560 
561 	st->intio = ADXL345_INT1;
562 	st->irq = fwnode_irq_get_byname(dev_fwnode(dev), "INT1");
563 	if (st->irq < 0) {
564 		st->intio = ADXL345_INT2;
565 		st->irq = fwnode_irq_get_byname(dev_fwnode(dev), "INT2");
566 		if (st->irq < 0)
567 			st->intio = ADXL345_INT_NONE;
568 	}
569 
570 	if (st->intio != ADXL345_INT_NONE) {
571 		/* FIFO_STREAM mode is going to be activated later */
572 		ret = devm_iio_kfifo_buffer_setup(dev, indio_dev, &adxl345_buffer_ops);
573 		if (ret)
574 			return ret;
575 
576 		ret = devm_request_threaded_irq(dev, st->irq, NULL,
577 						&adxl345_irq_handler,
578 						IRQF_SHARED | IRQF_ONESHOT,
579 						indio_dev->name, indio_dev);
580 		if (ret)
581 			return ret;
582 	} else {
583 		ret = regmap_write(st->regmap, ADXL345_REG_FIFO_CTL,
584 				   FIELD_PREP(ADXL345_FIFO_CTL_MODE_MSK,
585 					      ADXL345_FIFO_BYPASS));
586 		if (ret < 0)
587 			return ret;
588 	}
589 
590 	return devm_iio_device_register(dev, indio_dev);
591 }
592 EXPORT_SYMBOL_NS_GPL(adxl345_core_probe, "IIO_ADXL345");
593 
594 MODULE_AUTHOR("Eva Rachel Retuya <eraretuya@gmail.com>");
595 MODULE_DESCRIPTION("ADXL345 3-Axis Digital Accelerometer core driver");
596 MODULE_LICENSE("GPL v2");
597