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