xref: /openbmc/linux/drivers/iio/accel/bma400_core.c (revision 4cfb9080)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Core IIO driver for Bosch BMA400 triaxial acceleration sensor.
4  *
5  * Copyright 2019 Dan Robertson <dan@dlrobertson.com>
6  *
7  * TODO:
8  *  - Support for power management
9  *  - Support events and interrupts
10  *  - Create channel for step count
11  *  - Create channel for sensor time
12  */
13 
14 #include <linux/bitfield.h>
15 #include <linux/bitops.h>
16 #include <linux/device.h>
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/regmap.h>
21 #include <linux/regulator/consumer.h>
22 #include <linux/slab.h>
23 
24 #include <asm/unaligned.h>
25 
26 #include <linux/iio/iio.h>
27 #include <linux/iio/buffer.h>
28 #include <linux/iio/events.h>
29 #include <linux/iio/sysfs.h>
30 #include <linux/iio/trigger.h>
31 #include <linux/iio/trigger_consumer.h>
32 #include <linux/iio/triggered_buffer.h>
33 
34 #include "bma400.h"
35 
36 /*
37  * The G-range selection may be one of 2g, 4g, 8, or 16g. The scale may
38  * be selected with the acc_range bits of the ACC_CONFIG1 register.
39  * NB: This buffer is populated in the device init.
40  */
41 static int bma400_scales[8];
42 
43 /*
44  * See the ACC_CONFIG1 section of the datasheet.
45  * NB: This buffer is populated in the device init.
46  */
47 static int bma400_sample_freqs[14];
48 
49 static const int bma400_osr_range[] = { 0, 1, 3 };
50 
51 static int tap_reset_timeout[BMA400_TAP_TIM_LIST_LEN] = {
52 	300000,
53 	400000,
54 	500000,
55 	600000
56 };
57 
58 static int tap_max2min_time[BMA400_TAP_TIM_LIST_LEN] = {
59 	30000,
60 	45000,
61 	60000,
62 	90000
63 };
64 
65 static int double_tap2_min_delay[BMA400_TAP_TIM_LIST_LEN] = {
66 	20000,
67 	40000,
68 	60000,
69 	80000
70 };
71 
72 /* See the ACC_CONFIG0 section of the datasheet */
73 enum bma400_power_mode {
74 	POWER_MODE_SLEEP   = 0x00,
75 	POWER_MODE_LOW     = 0x01,
76 	POWER_MODE_NORMAL  = 0x02,
77 	POWER_MODE_INVALID = 0x03,
78 };
79 
80 enum bma400_scan {
81 	BMA400_ACCL_X,
82 	BMA400_ACCL_Y,
83 	BMA400_ACCL_Z,
84 	BMA400_TEMP,
85 };
86 
87 struct bma400_sample_freq {
88 	int hz;
89 	int uhz;
90 };
91 
92 enum bma400_activity {
93 	BMA400_STILL,
94 	BMA400_WALKING,
95 	BMA400_RUNNING,
96 };
97 
98 struct bma400_data {
99 	struct device *dev;
100 	struct regmap *regmap;
101 	struct mutex mutex; /* data register lock */
102 	struct iio_mount_matrix orientation;
103 	enum bma400_power_mode power_mode;
104 	struct bma400_sample_freq sample_freq;
105 	int oversampling_ratio;
106 	int scale;
107 	struct iio_trigger *trig;
108 	int steps_enabled;
109 	bool step_event_en;
110 	bool activity_event_en;
111 	unsigned int generic_event_en;
112 	unsigned int tap_event_en_bitmask;
113 	/* Correct time stamp alignment */
114 	struct {
115 		__le16 buff[3];
116 		u8 temperature;
117 		s64 ts __aligned(8);
118 	} buffer __aligned(IIO_DMA_MINALIGN);
119 	__le16 status;
120 	__be16 duration;
121 };
122 
123 static bool bma400_is_writable_reg(struct device *dev, unsigned int reg)
124 {
125 	switch (reg) {
126 	case BMA400_CHIP_ID_REG:
127 	case BMA400_ERR_REG:
128 	case BMA400_STATUS_REG:
129 	case BMA400_X_AXIS_LSB_REG:
130 	case BMA400_X_AXIS_MSB_REG:
131 	case BMA400_Y_AXIS_LSB_REG:
132 	case BMA400_Y_AXIS_MSB_REG:
133 	case BMA400_Z_AXIS_LSB_REG:
134 	case BMA400_Z_AXIS_MSB_REG:
135 	case BMA400_SENSOR_TIME0:
136 	case BMA400_SENSOR_TIME1:
137 	case BMA400_SENSOR_TIME2:
138 	case BMA400_EVENT_REG:
139 	case BMA400_INT_STAT0_REG:
140 	case BMA400_INT_STAT1_REG:
141 	case BMA400_INT_STAT2_REG:
142 	case BMA400_TEMP_DATA_REG:
143 	case BMA400_FIFO_LENGTH0_REG:
144 	case BMA400_FIFO_LENGTH1_REG:
145 	case BMA400_FIFO_DATA_REG:
146 	case BMA400_STEP_CNT0_REG:
147 	case BMA400_STEP_CNT1_REG:
148 	case BMA400_STEP_CNT3_REG:
149 	case BMA400_STEP_STAT_REG:
150 		return false;
151 	default:
152 		return true;
153 	}
154 }
155 
156 static bool bma400_is_volatile_reg(struct device *dev, unsigned int reg)
157 {
158 	switch (reg) {
159 	case BMA400_ERR_REG:
160 	case BMA400_STATUS_REG:
161 	case BMA400_X_AXIS_LSB_REG:
162 	case BMA400_X_AXIS_MSB_REG:
163 	case BMA400_Y_AXIS_LSB_REG:
164 	case BMA400_Y_AXIS_MSB_REG:
165 	case BMA400_Z_AXIS_LSB_REG:
166 	case BMA400_Z_AXIS_MSB_REG:
167 	case BMA400_SENSOR_TIME0:
168 	case BMA400_SENSOR_TIME1:
169 	case BMA400_SENSOR_TIME2:
170 	case BMA400_EVENT_REG:
171 	case BMA400_INT_STAT0_REG:
172 	case BMA400_INT_STAT1_REG:
173 	case BMA400_INT_STAT2_REG:
174 	case BMA400_TEMP_DATA_REG:
175 	case BMA400_FIFO_LENGTH0_REG:
176 	case BMA400_FIFO_LENGTH1_REG:
177 	case BMA400_FIFO_DATA_REG:
178 	case BMA400_STEP_CNT0_REG:
179 	case BMA400_STEP_CNT1_REG:
180 	case BMA400_STEP_CNT3_REG:
181 	case BMA400_STEP_STAT_REG:
182 		return true;
183 	default:
184 		return false;
185 	}
186 }
187 
188 const struct regmap_config bma400_regmap_config = {
189 	.reg_bits = 8,
190 	.val_bits = 8,
191 	.max_register = BMA400_CMD_REG,
192 	.cache_type = REGCACHE_RBTREE,
193 	.writeable_reg = bma400_is_writable_reg,
194 	.volatile_reg = bma400_is_volatile_reg,
195 };
196 EXPORT_SYMBOL_NS(bma400_regmap_config, IIO_BMA400);
197 
198 static const struct iio_mount_matrix *
199 bma400_accel_get_mount_matrix(const struct iio_dev *indio_dev,
200 			      const struct iio_chan_spec *chan)
201 {
202 	struct bma400_data *data = iio_priv(indio_dev);
203 
204 	return &data->orientation;
205 }
206 
207 static const struct iio_chan_spec_ext_info bma400_ext_info[] = {
208 	IIO_MOUNT_MATRIX(IIO_SHARED_BY_DIR, bma400_accel_get_mount_matrix),
209 	{ }
210 };
211 
212 static const struct iio_event_spec bma400_step_detect_event = {
213 	.type = IIO_EV_TYPE_CHANGE,
214 	.dir = IIO_EV_DIR_NONE,
215 	.mask_separate = BIT(IIO_EV_INFO_ENABLE),
216 };
217 
218 static const struct iio_event_spec bma400_activity_event = {
219 	.type = IIO_EV_TYPE_CHANGE,
220 	.dir = IIO_EV_DIR_NONE,
221 	.mask_shared_by_type = BIT(IIO_EV_INFO_ENABLE),
222 };
223 
224 static const struct iio_event_spec bma400_accel_event[] = {
225 	{
226 		.type = IIO_EV_TYPE_MAG,
227 		.dir = IIO_EV_DIR_FALLING,
228 		.mask_shared_by_type = BIT(IIO_EV_INFO_VALUE) |
229 				       BIT(IIO_EV_INFO_PERIOD) |
230 				       BIT(IIO_EV_INFO_HYSTERESIS) |
231 				       BIT(IIO_EV_INFO_ENABLE),
232 	},
233 	{
234 		.type = IIO_EV_TYPE_MAG,
235 		.dir = IIO_EV_DIR_RISING,
236 		.mask_shared_by_type = BIT(IIO_EV_INFO_VALUE) |
237 				       BIT(IIO_EV_INFO_PERIOD) |
238 				       BIT(IIO_EV_INFO_HYSTERESIS) |
239 				       BIT(IIO_EV_INFO_ENABLE),
240 	},
241 	{
242 		.type = IIO_EV_TYPE_GESTURE,
243 		.dir = IIO_EV_DIR_SINGLETAP,
244 		.mask_shared_by_type = BIT(IIO_EV_INFO_VALUE) |
245 				       BIT(IIO_EV_INFO_ENABLE) |
246 				       BIT(IIO_EV_INFO_RESET_TIMEOUT),
247 	},
248 	{
249 		.type = IIO_EV_TYPE_GESTURE,
250 		.dir = IIO_EV_DIR_DOUBLETAP,
251 		.mask_shared_by_type = BIT(IIO_EV_INFO_VALUE) |
252 				       BIT(IIO_EV_INFO_ENABLE) |
253 				       BIT(IIO_EV_INFO_RESET_TIMEOUT) |
254 				       BIT(IIO_EV_INFO_TAP2_MIN_DELAY),
255 	},
256 };
257 
258 static int usec_to_tapreg_raw(int usec, const int *time_list)
259 {
260 	int index;
261 
262 	for (index = 0; index < BMA400_TAP_TIM_LIST_LEN; index++) {
263 		if (usec == time_list[index])
264 			return index;
265 	}
266 	return -EINVAL;
267 }
268 
269 static ssize_t in_accel_gesture_tap_maxtomin_time_show(struct device *dev,
270 						       struct device_attribute *attr,
271 						       char *buf)
272 {
273 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
274 	struct bma400_data *data = iio_priv(indio_dev);
275 	int ret, reg_val, raw, vals[2];
276 
277 	ret = regmap_read(data->regmap, BMA400_TAP_CONFIG1, &reg_val);
278 	if (ret)
279 		return ret;
280 
281 	raw = FIELD_GET(BMA400_TAP_TICSTH_MSK, reg_val);
282 	vals[0] = 0;
283 	vals[1] = tap_max2min_time[raw];
284 
285 	return iio_format_value(buf, IIO_VAL_INT_PLUS_MICRO, 2, vals);
286 }
287 
288 static ssize_t in_accel_gesture_tap_maxtomin_time_store(struct device *dev,
289 							struct device_attribute *attr,
290 							const char *buf, size_t len)
291 {
292 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
293 	struct bma400_data *data = iio_priv(indio_dev);
294 	int ret, val_int, val_fract, raw;
295 
296 	ret = iio_str_to_fixpoint(buf, 100000, &val_int, &val_fract);
297 	if (ret)
298 		return ret;
299 
300 	raw = usec_to_tapreg_raw(val_fract, tap_max2min_time);
301 	if (raw < 0)
302 		return -EINVAL;
303 
304 	ret = regmap_update_bits(data->regmap, BMA400_TAP_CONFIG1,
305 				 BMA400_TAP_TICSTH_MSK,
306 				 FIELD_PREP(BMA400_TAP_TICSTH_MSK, raw));
307 	if (ret)
308 		return ret;
309 
310 	return len;
311 }
312 
313 static IIO_DEVICE_ATTR_RW(in_accel_gesture_tap_maxtomin_time, 0);
314 
315 /*
316  * Tap interrupts works with 200 Hz input data rate and the time based tap
317  * controls are in the terms of data samples so the below calculation is
318  * used to convert the configuration values into seconds.
319  * e.g.:
320  * 60 data samples * 0.005 ms = 0.3 seconds.
321  * 80 data samples * 0.005 ms = 0.4 seconds.
322  */
323 
324 /* quiet configuration values in seconds */
325 static IIO_CONST_ATTR(in_accel_gesture_tap_reset_timeout_available,
326 		      "0.3 0.4 0.5 0.6");
327 
328 /* tics_th configuration values in seconds */
329 static IIO_CONST_ATTR(in_accel_gesture_tap_maxtomin_time_available,
330 		      "0.03 0.045 0.06 0.09");
331 
332 /* quiet_dt configuration values in seconds */
333 static IIO_CONST_ATTR(in_accel_gesture_doubletap_tap2_min_delay_available,
334 		      "0.02 0.04 0.06 0.08");
335 
336 /* List of sensitivity values available to configure tap interrupts */
337 static IIO_CONST_ATTR(in_accel_gesture_tap_value_available, "0 1 2 3 4 5 6 7");
338 
339 static struct attribute *bma400_event_attributes[] = {
340 	&iio_const_attr_in_accel_gesture_tap_value_available.dev_attr.attr,
341 	&iio_const_attr_in_accel_gesture_tap_reset_timeout_available.dev_attr.attr,
342 	&iio_const_attr_in_accel_gesture_tap_maxtomin_time_available.dev_attr.attr,
343 	&iio_const_attr_in_accel_gesture_doubletap_tap2_min_delay_available.dev_attr.attr,
344 	&iio_dev_attr_in_accel_gesture_tap_maxtomin_time.dev_attr.attr,
345 	NULL
346 };
347 
348 static const struct attribute_group bma400_event_attribute_group = {
349 	.attrs = bma400_event_attributes,
350 };
351 
352 #define BMA400_ACC_CHANNEL(_index, _axis) { \
353 	.type = IIO_ACCEL, \
354 	.modified = 1, \
355 	.channel2 = IIO_MOD_##_axis, \
356 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \
357 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
358 		BIT(IIO_CHAN_INFO_SCALE) | \
359 		BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
360 	.info_mask_shared_by_type_available = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
361 		BIT(IIO_CHAN_INFO_SCALE) | \
362 		BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
363 	.ext_info = bma400_ext_info, \
364 	.scan_index = _index,	\
365 	.scan_type = {		\
366 		.sign = 's',	\
367 		.realbits = 12,		\
368 		.storagebits = 16,	\
369 		.endianness = IIO_LE,	\
370 	},				\
371 	.event_spec = bma400_accel_event,			\
372 	.num_event_specs = ARRAY_SIZE(bma400_accel_event)	\
373 }
374 
375 #define BMA400_ACTIVITY_CHANNEL(_chan2) {	\
376 	.type = IIO_ACTIVITY,			\
377 	.modified = 1,				\
378 	.channel2 = _chan2,			\
379 	.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),	\
380 	.scan_index = -1, /* No buffer support */		\
381 	.event_spec = &bma400_activity_event,			\
382 	.num_event_specs = 1,					\
383 }
384 
385 static const struct iio_chan_spec bma400_channels[] = {
386 	BMA400_ACC_CHANNEL(0, X),
387 	BMA400_ACC_CHANNEL(1, Y),
388 	BMA400_ACC_CHANNEL(2, Z),
389 	{
390 		.type = IIO_TEMP,
391 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
392 		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SAMP_FREQ),
393 		.scan_index = 3,
394 		.scan_type = {
395 			.sign = 's',
396 			.realbits = 8,
397 			.storagebits = 8,
398 			.endianness = IIO_LE,
399 		},
400 	},
401 	{
402 		.type = IIO_STEPS,
403 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED) |
404 				      BIT(IIO_CHAN_INFO_ENABLE),
405 		.scan_index = -1, /* No buffer support */
406 		.event_spec = &bma400_step_detect_event,
407 		.num_event_specs = 1,
408 	},
409 	BMA400_ACTIVITY_CHANNEL(IIO_MOD_STILL),
410 	BMA400_ACTIVITY_CHANNEL(IIO_MOD_WALKING),
411 	BMA400_ACTIVITY_CHANNEL(IIO_MOD_RUNNING),
412 	IIO_CHAN_SOFT_TIMESTAMP(4),
413 };
414 
415 static int bma400_get_temp_reg(struct bma400_data *data, int *val, int *val2)
416 {
417 	unsigned int raw_temp;
418 	int host_temp;
419 	int ret;
420 
421 	if (data->power_mode == POWER_MODE_SLEEP)
422 		return -EBUSY;
423 
424 	ret = regmap_read(data->regmap, BMA400_TEMP_DATA_REG, &raw_temp);
425 	if (ret)
426 		return ret;
427 
428 	host_temp = sign_extend32(raw_temp, 7);
429 	/*
430 	 * The formula for the TEMP_DATA register in the datasheet
431 	 * is: x * 0.5 + 23
432 	 */
433 	*val = (host_temp >> 1) + 23;
434 	*val2 = (host_temp & 0x1) * 500000;
435 	return IIO_VAL_INT_PLUS_MICRO;
436 }
437 
438 static int bma400_get_accel_reg(struct bma400_data *data,
439 				const struct iio_chan_spec *chan,
440 				int *val)
441 {
442 	__le16 raw_accel;
443 	int lsb_reg;
444 	int ret;
445 
446 	if (data->power_mode == POWER_MODE_SLEEP)
447 		return -EBUSY;
448 
449 	switch (chan->channel2) {
450 	case IIO_MOD_X:
451 		lsb_reg = BMA400_X_AXIS_LSB_REG;
452 		break;
453 	case IIO_MOD_Y:
454 		lsb_reg = BMA400_Y_AXIS_LSB_REG;
455 		break;
456 	case IIO_MOD_Z:
457 		lsb_reg = BMA400_Z_AXIS_LSB_REG;
458 		break;
459 	default:
460 		dev_err(data->dev, "invalid axis channel modifier\n");
461 		return -EINVAL;
462 	}
463 
464 	/* bulk read two registers, with the base being the LSB register */
465 	ret = regmap_bulk_read(data->regmap, lsb_reg, &raw_accel,
466 			       sizeof(raw_accel));
467 	if (ret)
468 		return ret;
469 
470 	*val = sign_extend32(le16_to_cpu(raw_accel), 11);
471 	return IIO_VAL_INT;
472 }
473 
474 static void bma400_output_data_rate_from_raw(int raw, unsigned int *val,
475 					     unsigned int *val2)
476 {
477 	*val = BMA400_ACC_ODR_MAX_HZ >> (BMA400_ACC_ODR_MAX_RAW - raw);
478 	if (raw > BMA400_ACC_ODR_MIN_RAW)
479 		*val2 = 0;
480 	else
481 		*val2 = 500000;
482 }
483 
484 static int bma400_get_accel_output_data_rate(struct bma400_data *data)
485 {
486 	unsigned int val;
487 	unsigned int odr;
488 	int ret;
489 
490 	switch (data->power_mode) {
491 	case POWER_MODE_LOW:
492 		/*
493 		 * Runs at a fixed rate in low-power mode. See section 4.3
494 		 * in the datasheet.
495 		 */
496 		bma400_output_data_rate_from_raw(BMA400_ACC_ODR_LP_RAW,
497 						 &data->sample_freq.hz,
498 						 &data->sample_freq.uhz);
499 		return 0;
500 	case POWER_MODE_NORMAL:
501 		/*
502 		 * In normal mode the ODR can be found in the ACC_CONFIG1
503 		 * register.
504 		 */
505 		ret = regmap_read(data->regmap, BMA400_ACC_CONFIG1_REG, &val);
506 		if (ret)
507 			goto error;
508 
509 		odr = val & BMA400_ACC_ODR_MASK;
510 		if (odr < BMA400_ACC_ODR_MIN_RAW ||
511 		    odr > BMA400_ACC_ODR_MAX_RAW) {
512 			ret = -EINVAL;
513 			goto error;
514 		}
515 
516 		bma400_output_data_rate_from_raw(odr, &data->sample_freq.hz,
517 						 &data->sample_freq.uhz);
518 		return 0;
519 	case POWER_MODE_SLEEP:
520 		data->sample_freq.hz = 0;
521 		data->sample_freq.uhz = 0;
522 		return 0;
523 	default:
524 		ret = 0;
525 		goto error;
526 	}
527 error:
528 	data->sample_freq.hz = -1;
529 	data->sample_freq.uhz = -1;
530 	return ret;
531 }
532 
533 static int bma400_set_accel_output_data_rate(struct bma400_data *data,
534 					     int hz, int uhz)
535 {
536 	unsigned int idx;
537 	unsigned int odr;
538 	unsigned int val;
539 	int ret;
540 
541 	if (hz >= BMA400_ACC_ODR_MIN_WHOLE_HZ) {
542 		if (uhz || hz > BMA400_ACC_ODR_MAX_HZ)
543 			return -EINVAL;
544 
545 		/* Note this works because MIN_WHOLE_HZ is odd */
546 		idx = __ffs(hz);
547 
548 		if (hz >> idx != BMA400_ACC_ODR_MIN_WHOLE_HZ)
549 			return -EINVAL;
550 
551 		idx += BMA400_ACC_ODR_MIN_RAW + 1;
552 	} else if (hz == BMA400_ACC_ODR_MIN_HZ && uhz == 500000) {
553 		idx = BMA400_ACC_ODR_MIN_RAW;
554 	} else {
555 		return -EINVAL;
556 	}
557 
558 	ret = regmap_read(data->regmap, BMA400_ACC_CONFIG1_REG, &val);
559 	if (ret)
560 		return ret;
561 
562 	/* preserve the range and normal mode osr */
563 	odr = (~BMA400_ACC_ODR_MASK & val) | idx;
564 
565 	ret = regmap_write(data->regmap, BMA400_ACC_CONFIG1_REG, odr);
566 	if (ret)
567 		return ret;
568 
569 	bma400_output_data_rate_from_raw(idx, &data->sample_freq.hz,
570 					 &data->sample_freq.uhz);
571 	return 0;
572 }
573 
574 static int bma400_get_accel_oversampling_ratio(struct bma400_data *data)
575 {
576 	unsigned int val;
577 	unsigned int osr;
578 	int ret;
579 
580 	/*
581 	 * The oversampling ratio is stored in a different register
582 	 * based on the power-mode. In normal mode the OSR is stored
583 	 * in ACC_CONFIG1. In low-power mode it is stored in
584 	 * ACC_CONFIG0.
585 	 */
586 	switch (data->power_mode) {
587 	case POWER_MODE_LOW:
588 		ret = regmap_read(data->regmap, BMA400_ACC_CONFIG0_REG, &val);
589 		if (ret) {
590 			data->oversampling_ratio = -1;
591 			return ret;
592 		}
593 
594 		osr = (val & BMA400_LP_OSR_MASK) >> BMA400_LP_OSR_SHIFT;
595 
596 		data->oversampling_ratio = osr;
597 		return 0;
598 	case POWER_MODE_NORMAL:
599 		ret = regmap_read(data->regmap, BMA400_ACC_CONFIG1_REG, &val);
600 		if (ret) {
601 			data->oversampling_ratio = -1;
602 			return ret;
603 		}
604 
605 		osr = (val & BMA400_NP_OSR_MASK) >> BMA400_NP_OSR_SHIFT;
606 
607 		data->oversampling_ratio = osr;
608 		return 0;
609 	case POWER_MODE_SLEEP:
610 		data->oversampling_ratio = 0;
611 		return 0;
612 	default:
613 		data->oversampling_ratio = -1;
614 		return -EINVAL;
615 	}
616 }
617 
618 static int bma400_set_accel_oversampling_ratio(struct bma400_data *data,
619 					       int val)
620 {
621 	unsigned int acc_config;
622 	int ret;
623 
624 	if (val & ~BMA400_TWO_BITS_MASK)
625 		return -EINVAL;
626 
627 	/*
628 	 * The oversampling ratio is stored in a different register
629 	 * based on the power-mode.
630 	 */
631 	switch (data->power_mode) {
632 	case POWER_MODE_LOW:
633 		ret = regmap_read(data->regmap, BMA400_ACC_CONFIG0_REG,
634 				  &acc_config);
635 		if (ret)
636 			return ret;
637 
638 		ret = regmap_write(data->regmap, BMA400_ACC_CONFIG0_REG,
639 				   (acc_config & ~BMA400_LP_OSR_MASK) |
640 				   (val << BMA400_LP_OSR_SHIFT));
641 		if (ret) {
642 			dev_err(data->dev, "Failed to write out OSR\n");
643 			return ret;
644 		}
645 
646 		data->oversampling_ratio = val;
647 		return 0;
648 	case POWER_MODE_NORMAL:
649 		ret = regmap_read(data->regmap, BMA400_ACC_CONFIG1_REG,
650 				  &acc_config);
651 		if (ret)
652 			return ret;
653 
654 		ret = regmap_write(data->regmap, BMA400_ACC_CONFIG1_REG,
655 				   (acc_config & ~BMA400_NP_OSR_MASK) |
656 				   (val << BMA400_NP_OSR_SHIFT));
657 		if (ret) {
658 			dev_err(data->dev, "Failed to write out OSR\n");
659 			return ret;
660 		}
661 
662 		data->oversampling_ratio = val;
663 		return 0;
664 	default:
665 		return -EINVAL;
666 	}
667 	return ret;
668 }
669 
670 static int bma400_accel_scale_to_raw(struct bma400_data *data,
671 				     unsigned int val)
672 {
673 	int raw;
674 
675 	if (val == 0)
676 		return -EINVAL;
677 
678 	/* Note this works because BMA400_SCALE_MIN is odd */
679 	raw = __ffs(val);
680 
681 	if (val >> raw != BMA400_SCALE_MIN)
682 		return -EINVAL;
683 
684 	return raw;
685 }
686 
687 static int bma400_get_accel_scale(struct bma400_data *data)
688 {
689 	unsigned int raw_scale;
690 	unsigned int val;
691 	int ret;
692 
693 	ret = regmap_read(data->regmap, BMA400_ACC_CONFIG1_REG, &val);
694 	if (ret)
695 		return ret;
696 
697 	raw_scale = (val & BMA400_ACC_SCALE_MASK) >> BMA400_SCALE_SHIFT;
698 	if (raw_scale > BMA400_TWO_BITS_MASK)
699 		return -EINVAL;
700 
701 	data->scale = BMA400_SCALE_MIN << raw_scale;
702 
703 	return 0;
704 }
705 
706 static int bma400_set_accel_scale(struct bma400_data *data, unsigned int val)
707 {
708 	unsigned int acc_config;
709 	int raw;
710 	int ret;
711 
712 	ret = regmap_read(data->regmap, BMA400_ACC_CONFIG1_REG, &acc_config);
713 	if (ret)
714 		return ret;
715 
716 	raw = bma400_accel_scale_to_raw(data, val);
717 	if (raw < 0)
718 		return raw;
719 
720 	ret = regmap_write(data->regmap, BMA400_ACC_CONFIG1_REG,
721 			   (acc_config & ~BMA400_ACC_SCALE_MASK) |
722 			   (raw << BMA400_SCALE_SHIFT));
723 	if (ret)
724 		return ret;
725 
726 	data->scale = val;
727 	return 0;
728 }
729 
730 static int bma400_get_power_mode(struct bma400_data *data)
731 {
732 	unsigned int val;
733 	int ret;
734 
735 	ret = regmap_read(data->regmap, BMA400_STATUS_REG, &val);
736 	if (ret) {
737 		dev_err(data->dev, "Failed to read status register\n");
738 		return ret;
739 	}
740 
741 	data->power_mode = (val >> 1) & BMA400_TWO_BITS_MASK;
742 	return 0;
743 }
744 
745 static int bma400_set_power_mode(struct bma400_data *data,
746 				 enum bma400_power_mode mode)
747 {
748 	unsigned int val;
749 	int ret;
750 
751 	ret = regmap_read(data->regmap, BMA400_ACC_CONFIG0_REG, &val);
752 	if (ret)
753 		return ret;
754 
755 	if (data->power_mode == mode)
756 		return 0;
757 
758 	if (mode == POWER_MODE_INVALID)
759 		return -EINVAL;
760 
761 	/* Preserve the low-power oversample ratio etc */
762 	ret = regmap_write(data->regmap, BMA400_ACC_CONFIG0_REG,
763 			   mode | (val & ~BMA400_TWO_BITS_MASK));
764 	if (ret) {
765 		dev_err(data->dev, "Failed to write to power-mode\n");
766 		return ret;
767 	}
768 
769 	data->power_mode = mode;
770 
771 	/*
772 	 * Update our cached osr and odr based on the new
773 	 * power-mode.
774 	 */
775 	bma400_get_accel_output_data_rate(data);
776 	bma400_get_accel_oversampling_ratio(data);
777 	return 0;
778 }
779 
780 static int bma400_enable_steps(struct bma400_data *data, int val)
781 {
782 	int ret;
783 
784 	if (data->steps_enabled == val)
785 		return 0;
786 
787 	ret = regmap_update_bits(data->regmap, BMA400_INT_CONFIG1_REG,
788 				 BMA400_STEP_INT_MSK,
789 				 FIELD_PREP(BMA400_STEP_INT_MSK, val ? 1 : 0));
790 	if (ret)
791 		return ret;
792 	data->steps_enabled = val;
793 	return ret;
794 }
795 
796 static int bma400_get_steps_reg(struct bma400_data *data, int *val)
797 {
798 	u8 *steps_raw;
799 	int ret;
800 
801 	steps_raw = kmalloc(BMA400_STEP_RAW_LEN, GFP_KERNEL);
802 	if (!steps_raw)
803 		return -ENOMEM;
804 
805 	ret = regmap_bulk_read(data->regmap, BMA400_STEP_CNT0_REG,
806 			       steps_raw, BMA400_STEP_RAW_LEN);
807 	if (ret) {
808 		kfree(steps_raw);
809 		return ret;
810 	}
811 	*val = get_unaligned_le24(steps_raw);
812 	kfree(steps_raw);
813 	return IIO_VAL_INT;
814 }
815 
816 static void bma400_init_tables(void)
817 {
818 	int raw;
819 	int i;
820 
821 	for (i = 0; i + 1 < ARRAY_SIZE(bma400_sample_freqs); i += 2) {
822 		raw = (i / 2) + 5;
823 		bma400_output_data_rate_from_raw(raw, &bma400_sample_freqs[i],
824 						 &bma400_sample_freqs[i + 1]);
825 	}
826 
827 	for (i = 0; i + 1 < ARRAY_SIZE(bma400_scales); i += 2) {
828 		raw = i / 2;
829 		bma400_scales[i] = 0;
830 		bma400_scales[i + 1] = BMA400_SCALE_MIN << raw;
831 	}
832 }
833 
834 static void bma400_power_disable(void *data_ptr)
835 {
836 	struct bma400_data *data = data_ptr;
837 	int ret;
838 
839 	mutex_lock(&data->mutex);
840 	ret = bma400_set_power_mode(data, POWER_MODE_SLEEP);
841 	mutex_unlock(&data->mutex);
842 	if (ret)
843 		dev_warn(data->dev, "Failed to put device into sleep mode (%pe)\n",
844 			 ERR_PTR(ret));
845 }
846 
847 static enum iio_modifier bma400_act_to_mod(enum bma400_activity activity)
848 {
849 	switch (activity) {
850 	case BMA400_STILL:
851 		return IIO_MOD_STILL;
852 	case BMA400_WALKING:
853 		return IIO_MOD_WALKING;
854 	case BMA400_RUNNING:
855 		return IIO_MOD_RUNNING;
856 	default:
857 		return IIO_NO_MOD;
858 	}
859 }
860 
861 static int bma400_init(struct bma400_data *data)
862 {
863 	static const char * const regulator_names[] = { "vdd", "vddio" };
864 	unsigned int val;
865 	int ret;
866 
867 	ret = devm_regulator_bulk_get_enable(data->dev,
868 					     ARRAY_SIZE(regulator_names),
869 					     regulator_names);
870 	if (ret)
871 		return dev_err_probe(data->dev, ret, "Failed to get regulators\n");
872 
873 	/* Try to read chip_id register. It must return 0x90. */
874 	ret = regmap_read(data->regmap, BMA400_CHIP_ID_REG, &val);
875 	if (ret) {
876 		dev_err(data->dev, "Failed to read chip id register\n");
877 		return ret;
878 	}
879 
880 	if (val != BMA400_ID_REG_VAL) {
881 		dev_err(data->dev, "Chip ID mismatch\n");
882 		return -ENODEV;
883 	}
884 
885 	ret = bma400_get_power_mode(data);
886 	if (ret) {
887 		dev_err(data->dev, "Failed to get the initial power-mode\n");
888 		return ret;
889 	}
890 
891 	if (data->power_mode != POWER_MODE_NORMAL) {
892 		ret = bma400_set_power_mode(data, POWER_MODE_NORMAL);
893 		if (ret) {
894 			dev_err(data->dev, "Failed to wake up the device\n");
895 			return ret;
896 		}
897 		/*
898 		 * TODO: The datasheet waits 1500us here in the example, but
899 		 * lists 2/ODR as the wakeup time.
900 		 */
901 		usleep_range(1500, 2000);
902 	}
903 
904 	ret = devm_add_action_or_reset(data->dev, bma400_power_disable, data);
905 	if (ret)
906 		return ret;
907 
908 	bma400_init_tables();
909 
910 	ret = bma400_get_accel_output_data_rate(data);
911 	if (ret)
912 		return ret;
913 
914 	ret = bma400_get_accel_oversampling_ratio(data);
915 	if (ret)
916 		return ret;
917 
918 	ret = bma400_get_accel_scale(data);
919 	if (ret)
920 		return ret;
921 
922 	/* Configure INT1 pin to open drain */
923 	ret = regmap_write(data->regmap, BMA400_INT_IO_CTRL_REG, 0x06);
924 	if (ret)
925 		return ret;
926 	/*
927 	 * Once the interrupt engine is supported we might use the
928 	 * data_src_reg, but for now ensure this is set to the
929 	 * variable ODR filter selectable by the sample frequency
930 	 * channel.
931 	 */
932 	return regmap_write(data->regmap, BMA400_ACC_CONFIG2_REG, 0x00);
933 }
934 
935 static int bma400_read_raw(struct iio_dev *indio_dev,
936 			   struct iio_chan_spec const *chan, int *val,
937 			   int *val2, long mask)
938 {
939 	struct bma400_data *data = iio_priv(indio_dev);
940 	unsigned int activity;
941 	int ret;
942 
943 	switch (mask) {
944 	case IIO_CHAN_INFO_PROCESSED:
945 		switch (chan->type) {
946 		case IIO_TEMP:
947 			mutex_lock(&data->mutex);
948 			ret = bma400_get_temp_reg(data, val, val2);
949 			mutex_unlock(&data->mutex);
950 			return ret;
951 		case IIO_STEPS:
952 			return bma400_get_steps_reg(data, val);
953 		case IIO_ACTIVITY:
954 			ret = regmap_read(data->regmap, BMA400_STEP_STAT_REG,
955 					  &activity);
956 			if (ret)
957 				return ret;
958 			/*
959 			 * The device does not support confidence value levels,
960 			 * so we will always have 100% for current activity and
961 			 * 0% for the others.
962 			 */
963 			if (chan->channel2 == bma400_act_to_mod(activity))
964 				*val = 100;
965 			else
966 				*val = 0;
967 			return IIO_VAL_INT;
968 		default:
969 			return -EINVAL;
970 		}
971 	case IIO_CHAN_INFO_RAW:
972 		mutex_lock(&data->mutex);
973 		ret = bma400_get_accel_reg(data, chan, val);
974 		mutex_unlock(&data->mutex);
975 		return ret;
976 	case IIO_CHAN_INFO_SAMP_FREQ:
977 		switch (chan->type) {
978 		case IIO_ACCEL:
979 			if (data->sample_freq.hz < 0)
980 				return -EINVAL;
981 
982 			*val = data->sample_freq.hz;
983 			*val2 = data->sample_freq.uhz;
984 			return IIO_VAL_INT_PLUS_MICRO;
985 		case IIO_TEMP:
986 			/*
987 			 * Runs at a fixed sampling frequency. See Section 4.4
988 			 * of the datasheet.
989 			 */
990 			*val = 6;
991 			*val2 = 250000;
992 			return IIO_VAL_INT_PLUS_MICRO;
993 		default:
994 			return -EINVAL;
995 		}
996 	case IIO_CHAN_INFO_SCALE:
997 		*val = 0;
998 		*val2 = data->scale;
999 		return IIO_VAL_INT_PLUS_MICRO;
1000 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1001 		/*
1002 		 * TODO: We could avoid this logic and returning -EINVAL here if
1003 		 * we set both the low-power and normal mode OSR registers when
1004 		 * we configure the device.
1005 		 */
1006 		if (data->oversampling_ratio < 0)
1007 			return -EINVAL;
1008 
1009 		*val = data->oversampling_ratio;
1010 		return IIO_VAL_INT;
1011 	case IIO_CHAN_INFO_ENABLE:
1012 		*val = data->steps_enabled;
1013 		return IIO_VAL_INT;
1014 	default:
1015 		return -EINVAL;
1016 	}
1017 }
1018 
1019 static int bma400_read_avail(struct iio_dev *indio_dev,
1020 			     struct iio_chan_spec const *chan,
1021 			     const int **vals, int *type, int *length,
1022 			     long mask)
1023 {
1024 	switch (mask) {
1025 	case IIO_CHAN_INFO_SCALE:
1026 		*type = IIO_VAL_INT_PLUS_MICRO;
1027 		*vals = bma400_scales;
1028 		*length = ARRAY_SIZE(bma400_scales);
1029 		return IIO_AVAIL_LIST;
1030 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1031 		*type = IIO_VAL_INT;
1032 		*vals = bma400_osr_range;
1033 		*length = ARRAY_SIZE(bma400_osr_range);
1034 		return IIO_AVAIL_RANGE;
1035 	case IIO_CHAN_INFO_SAMP_FREQ:
1036 		*type = IIO_VAL_INT_PLUS_MICRO;
1037 		*vals = bma400_sample_freqs;
1038 		*length = ARRAY_SIZE(bma400_sample_freqs);
1039 		return IIO_AVAIL_LIST;
1040 	default:
1041 		return -EINVAL;
1042 	}
1043 }
1044 
1045 static int bma400_write_raw(struct iio_dev *indio_dev,
1046 			    struct iio_chan_spec const *chan, int val, int val2,
1047 			    long mask)
1048 {
1049 	struct bma400_data *data = iio_priv(indio_dev);
1050 	int ret;
1051 
1052 	switch (mask) {
1053 	case IIO_CHAN_INFO_SAMP_FREQ:
1054 		/*
1055 		 * The sample frequency is readonly for the temperature
1056 		 * register and a fixed value in low-power mode.
1057 		 */
1058 		if (chan->type != IIO_ACCEL)
1059 			return -EINVAL;
1060 
1061 		mutex_lock(&data->mutex);
1062 		ret = bma400_set_accel_output_data_rate(data, val, val2);
1063 		mutex_unlock(&data->mutex);
1064 		return ret;
1065 	case IIO_CHAN_INFO_SCALE:
1066 		if (val != 0 ||
1067 		    val2 < BMA400_SCALE_MIN || val2 > BMA400_SCALE_MAX)
1068 			return -EINVAL;
1069 
1070 		mutex_lock(&data->mutex);
1071 		ret = bma400_set_accel_scale(data, val2);
1072 		mutex_unlock(&data->mutex);
1073 		return ret;
1074 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1075 		mutex_lock(&data->mutex);
1076 		ret = bma400_set_accel_oversampling_ratio(data, val);
1077 		mutex_unlock(&data->mutex);
1078 		return ret;
1079 	case IIO_CHAN_INFO_ENABLE:
1080 		mutex_lock(&data->mutex);
1081 		ret = bma400_enable_steps(data, val);
1082 		mutex_unlock(&data->mutex);
1083 		return ret;
1084 	default:
1085 		return -EINVAL;
1086 	}
1087 }
1088 
1089 static int bma400_write_raw_get_fmt(struct iio_dev *indio_dev,
1090 				    struct iio_chan_spec const *chan,
1091 				    long mask)
1092 {
1093 	switch (mask) {
1094 	case IIO_CHAN_INFO_SAMP_FREQ:
1095 		return IIO_VAL_INT_PLUS_MICRO;
1096 	case IIO_CHAN_INFO_SCALE:
1097 		return IIO_VAL_INT_PLUS_MICRO;
1098 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1099 		return IIO_VAL_INT;
1100 	case IIO_CHAN_INFO_ENABLE:
1101 		return IIO_VAL_INT;
1102 	default:
1103 		return -EINVAL;
1104 	}
1105 }
1106 
1107 static int bma400_read_event_config(struct iio_dev *indio_dev,
1108 				    const struct iio_chan_spec *chan,
1109 				    enum iio_event_type type,
1110 				    enum iio_event_direction dir)
1111 {
1112 	struct bma400_data *data = iio_priv(indio_dev);
1113 
1114 	switch (chan->type) {
1115 	case IIO_ACCEL:
1116 		switch (dir) {
1117 		case IIO_EV_DIR_RISING:
1118 			return FIELD_GET(BMA400_INT_GEN1_MSK,
1119 					 data->generic_event_en);
1120 		case IIO_EV_DIR_FALLING:
1121 			return FIELD_GET(BMA400_INT_GEN2_MSK,
1122 					 data->generic_event_en);
1123 		case IIO_EV_DIR_SINGLETAP:
1124 			return FIELD_GET(BMA400_S_TAP_MSK,
1125 					 data->tap_event_en_bitmask);
1126 		case IIO_EV_DIR_DOUBLETAP:
1127 			return FIELD_GET(BMA400_D_TAP_MSK,
1128 					 data->tap_event_en_bitmask);
1129 		default:
1130 			return -EINVAL;
1131 		}
1132 	case IIO_STEPS:
1133 		return data->step_event_en;
1134 	case IIO_ACTIVITY:
1135 		return data->activity_event_en;
1136 	default:
1137 		return -EINVAL;
1138 	}
1139 }
1140 
1141 static int bma400_steps_event_enable(struct bma400_data *data, int state)
1142 {
1143 	int ret;
1144 
1145 	ret = bma400_enable_steps(data, 1);
1146 	if (ret)
1147 		return ret;
1148 
1149 	ret = regmap_update_bits(data->regmap, BMA400_INT12_MAP_REG,
1150 				 BMA400_STEP_INT_MSK,
1151 				 FIELD_PREP(BMA400_STEP_INT_MSK,
1152 					    state));
1153 	if (ret)
1154 		return ret;
1155 	data->step_event_en = state;
1156 	return 0;
1157 }
1158 
1159 static int bma400_activity_event_en(struct bma400_data *data,
1160 				    enum iio_event_direction dir,
1161 				    int state)
1162 {
1163 	int ret, reg, msk, value;
1164 	int field_value = 0;
1165 
1166 	switch (dir) {
1167 	case IIO_EV_DIR_RISING:
1168 		reg = BMA400_GEN1INT_CONFIG0;
1169 		msk = BMA400_INT_GEN1_MSK;
1170 		value = 2;
1171 		set_mask_bits(&field_value, BMA400_INT_GEN1_MSK,
1172 			      FIELD_PREP(BMA400_INT_GEN1_MSK, state));
1173 		break;
1174 	case IIO_EV_DIR_FALLING:
1175 		reg = BMA400_GEN2INT_CONFIG0;
1176 		msk = BMA400_INT_GEN2_MSK;
1177 		value = 0;
1178 		set_mask_bits(&field_value, BMA400_INT_GEN2_MSK,
1179 			      FIELD_PREP(BMA400_INT_GEN2_MSK, state));
1180 		break;
1181 	default:
1182 		return -EINVAL;
1183 	}
1184 
1185 	/* Enabling all axis for interrupt evaluation */
1186 	ret = regmap_write(data->regmap, reg, 0xF8);
1187 	if (ret)
1188 		return ret;
1189 
1190 	/* OR combination of all axis for interrupt evaluation */
1191 	ret = regmap_write(data->regmap, reg + BMA400_GEN_CONFIG1_OFF, value);
1192 	if (ret)
1193 		return ret;
1194 
1195 	/* Initial value to avoid interrupts while enabling*/
1196 	ret = regmap_write(data->regmap, reg + BMA400_GEN_CONFIG2_OFF, 0x0A);
1197 	if (ret)
1198 		return ret;
1199 
1200 	/* Initial duration value to avoid interrupts while enabling*/
1201 	ret = regmap_write(data->regmap, reg + BMA400_GEN_CONFIG31_OFF, 0x0F);
1202 	if (ret)
1203 		return ret;
1204 
1205 	ret = regmap_update_bits(data->regmap, BMA400_INT1_MAP_REG, msk,
1206 				 field_value);
1207 	if (ret)
1208 		return ret;
1209 
1210 	ret = regmap_update_bits(data->regmap, BMA400_INT_CONFIG0_REG, msk,
1211 				 field_value);
1212 	if (ret)
1213 		return ret;
1214 
1215 	set_mask_bits(&data->generic_event_en, msk, field_value);
1216 	return 0;
1217 }
1218 
1219 static int bma400_tap_event_en(struct bma400_data *data,
1220 			       enum iio_event_direction dir, int state)
1221 {
1222 	unsigned int mask, field_value;
1223 	int ret;
1224 
1225 	/*
1226 	 * Tap interrupts can be configured only in normal mode.
1227 	 * See table in section 4.3 "Power modes - performance modes" of
1228 	 * datasheet v1.2.
1229 	 */
1230 	if (data->power_mode != POWER_MODE_NORMAL)
1231 		return -EINVAL;
1232 
1233 	/*
1234 	 * Tap interrupts are operating with a data rate of 200Hz.
1235 	 * See section 4.7 "Tap sensing interrupt" in datasheet v1.2.
1236 	 */
1237 	if (data->sample_freq.hz != 200 && state) {
1238 		dev_err(data->dev, "Invalid data rate for tap interrupts.\n");
1239 		return -EINVAL;
1240 	}
1241 
1242 	ret = regmap_update_bits(data->regmap, BMA400_INT12_MAP_REG,
1243 				 BMA400_S_TAP_MSK,
1244 				 FIELD_PREP(BMA400_S_TAP_MSK, state));
1245 	if (ret)
1246 		return ret;
1247 
1248 	switch (dir) {
1249 	case IIO_EV_DIR_SINGLETAP:
1250 		mask = BMA400_S_TAP_MSK;
1251 		set_mask_bits(&field_value, BMA400_S_TAP_MSK,
1252 			      FIELD_PREP(BMA400_S_TAP_MSK, state));
1253 		break;
1254 	case IIO_EV_DIR_DOUBLETAP:
1255 		mask = BMA400_D_TAP_MSK;
1256 		set_mask_bits(&field_value, BMA400_D_TAP_MSK,
1257 			      FIELD_PREP(BMA400_D_TAP_MSK, state));
1258 		break;
1259 	default:
1260 		return -EINVAL;
1261 	}
1262 
1263 	ret = regmap_update_bits(data->regmap, BMA400_INT_CONFIG1_REG, mask,
1264 				 field_value);
1265 	if (ret)
1266 		return ret;
1267 
1268 	set_mask_bits(&data->tap_event_en_bitmask, mask, field_value);
1269 
1270 	return 0;
1271 }
1272 
1273 static int bma400_disable_adv_interrupt(struct bma400_data *data)
1274 {
1275 	int ret;
1276 
1277 	ret = regmap_write(data->regmap, BMA400_INT_CONFIG0_REG, 0);
1278 	if (ret)
1279 		return ret;
1280 
1281 	ret = regmap_write(data->regmap, BMA400_INT_CONFIG1_REG, 0);
1282 	if (ret)
1283 		return ret;
1284 
1285 	data->tap_event_en_bitmask = 0;
1286 	data->generic_event_en = 0;
1287 	data->step_event_en = false;
1288 	data->activity_event_en = false;
1289 
1290 	return 0;
1291 }
1292 
1293 static int bma400_write_event_config(struct iio_dev *indio_dev,
1294 				     const struct iio_chan_spec *chan,
1295 				     enum iio_event_type type,
1296 				     enum iio_event_direction dir, int state)
1297 {
1298 	struct bma400_data *data = iio_priv(indio_dev);
1299 	int ret;
1300 
1301 	switch (chan->type) {
1302 	case IIO_ACCEL:
1303 		switch (type) {
1304 		case IIO_EV_TYPE_MAG:
1305 			mutex_lock(&data->mutex);
1306 			ret = bma400_activity_event_en(data, dir, state);
1307 			mutex_unlock(&data->mutex);
1308 			return ret;
1309 		case IIO_EV_TYPE_GESTURE:
1310 			mutex_lock(&data->mutex);
1311 			ret = bma400_tap_event_en(data, dir, state);
1312 			mutex_unlock(&data->mutex);
1313 			return ret;
1314 		default:
1315 			return -EINVAL;
1316 		}
1317 	case IIO_STEPS:
1318 		mutex_lock(&data->mutex);
1319 		ret = bma400_steps_event_enable(data, state);
1320 		mutex_unlock(&data->mutex);
1321 		return ret;
1322 	case IIO_ACTIVITY:
1323 		mutex_lock(&data->mutex);
1324 		if (!data->step_event_en) {
1325 			ret = bma400_steps_event_enable(data, true);
1326 			if (ret) {
1327 				mutex_unlock(&data->mutex);
1328 				return ret;
1329 			}
1330 		}
1331 		data->activity_event_en = state;
1332 		mutex_unlock(&data->mutex);
1333 		return 0;
1334 	default:
1335 		return -EINVAL;
1336 	}
1337 }
1338 
1339 static int get_gen_config_reg(enum iio_event_direction dir)
1340 {
1341 	switch (dir) {
1342 	case IIO_EV_DIR_FALLING:
1343 		return BMA400_GEN2INT_CONFIG0;
1344 	case IIO_EV_DIR_RISING:
1345 		return BMA400_GEN1INT_CONFIG0;
1346 	default:
1347 		return -EINVAL;
1348 	}
1349 }
1350 
1351 static int bma400_read_event_value(struct iio_dev *indio_dev,
1352 				   const struct iio_chan_spec *chan,
1353 				   enum iio_event_type type,
1354 				   enum iio_event_direction dir,
1355 				   enum iio_event_info info,
1356 				   int *val, int *val2)
1357 {
1358 	struct bma400_data *data = iio_priv(indio_dev);
1359 	int ret, reg, reg_val, raw;
1360 
1361 	if (chan->type != IIO_ACCEL)
1362 		return -EINVAL;
1363 
1364 	switch (type) {
1365 	case IIO_EV_TYPE_MAG:
1366 		reg = get_gen_config_reg(dir);
1367 		if (reg < 0)
1368 			return -EINVAL;
1369 
1370 		*val2 = 0;
1371 		switch (info) {
1372 		case IIO_EV_INFO_VALUE:
1373 			ret = regmap_read(data->regmap,
1374 					  reg + BMA400_GEN_CONFIG2_OFF,
1375 					  val);
1376 			if (ret)
1377 				return ret;
1378 			return IIO_VAL_INT;
1379 		case IIO_EV_INFO_PERIOD:
1380 			mutex_lock(&data->mutex);
1381 			ret = regmap_bulk_read(data->regmap,
1382 					       reg + BMA400_GEN_CONFIG3_OFF,
1383 					       &data->duration,
1384 					       sizeof(data->duration));
1385 			if (ret) {
1386 				mutex_unlock(&data->mutex);
1387 				return ret;
1388 			}
1389 			*val = be16_to_cpu(data->duration);
1390 			mutex_unlock(&data->mutex);
1391 			return IIO_VAL_INT;
1392 		case IIO_EV_INFO_HYSTERESIS:
1393 			ret = regmap_read(data->regmap, reg, val);
1394 			if (ret)
1395 				return ret;
1396 			*val = FIELD_GET(BMA400_GEN_HYST_MSK, *val);
1397 			return IIO_VAL_INT;
1398 		default:
1399 			return -EINVAL;
1400 		}
1401 	case IIO_EV_TYPE_GESTURE:
1402 		switch (info) {
1403 		case IIO_EV_INFO_VALUE:
1404 			ret = regmap_read(data->regmap, BMA400_TAP_CONFIG,
1405 					  &reg_val);
1406 			if (ret)
1407 				return ret;
1408 
1409 			*val = FIELD_GET(BMA400_TAP_SEN_MSK, reg_val);
1410 			return IIO_VAL_INT;
1411 		case IIO_EV_INFO_RESET_TIMEOUT:
1412 			ret = regmap_read(data->regmap, BMA400_TAP_CONFIG1,
1413 					  &reg_val);
1414 			if (ret)
1415 				return ret;
1416 
1417 			raw = FIELD_GET(BMA400_TAP_QUIET_MSK, reg_val);
1418 			*val = 0;
1419 			*val2 = tap_reset_timeout[raw];
1420 			return IIO_VAL_INT_PLUS_MICRO;
1421 		case IIO_EV_INFO_TAP2_MIN_DELAY:
1422 			ret = regmap_read(data->regmap, BMA400_TAP_CONFIG1,
1423 					  &reg_val);
1424 			if (ret)
1425 				return ret;
1426 
1427 			raw = FIELD_GET(BMA400_TAP_QUIETDT_MSK, reg_val);
1428 			*val = 0;
1429 			*val2 = double_tap2_min_delay[raw];
1430 			return IIO_VAL_INT_PLUS_MICRO;
1431 		default:
1432 			return -EINVAL;
1433 		}
1434 	default:
1435 		return -EINVAL;
1436 	}
1437 }
1438 
1439 static int bma400_write_event_value(struct iio_dev *indio_dev,
1440 				    const struct iio_chan_spec *chan,
1441 				    enum iio_event_type type,
1442 				    enum iio_event_direction dir,
1443 				    enum iio_event_info info,
1444 				    int val, int val2)
1445 {
1446 	struct bma400_data *data = iio_priv(indio_dev);
1447 	int reg, ret, raw;
1448 
1449 	if (chan->type != IIO_ACCEL)
1450 		return -EINVAL;
1451 
1452 	switch (type) {
1453 	case IIO_EV_TYPE_MAG:
1454 		reg = get_gen_config_reg(dir);
1455 		if (reg < 0)
1456 			return -EINVAL;
1457 
1458 		switch (info) {
1459 		case IIO_EV_INFO_VALUE:
1460 			if (val < 1 || val > 255)
1461 				return -EINVAL;
1462 
1463 			return regmap_write(data->regmap,
1464 					    reg + BMA400_GEN_CONFIG2_OFF,
1465 					    val);
1466 		case IIO_EV_INFO_PERIOD:
1467 			if (val < 1 || val > 65535)
1468 				return -EINVAL;
1469 
1470 			mutex_lock(&data->mutex);
1471 			put_unaligned_be16(val, &data->duration);
1472 			ret = regmap_bulk_write(data->regmap,
1473 						reg + BMA400_GEN_CONFIG3_OFF,
1474 						&data->duration,
1475 						sizeof(data->duration));
1476 			mutex_unlock(&data->mutex);
1477 			return ret;
1478 		case IIO_EV_INFO_HYSTERESIS:
1479 			if (val < 0 || val > 3)
1480 				return -EINVAL;
1481 
1482 			return regmap_update_bits(data->regmap, reg,
1483 						  BMA400_GEN_HYST_MSK,
1484 						  FIELD_PREP(BMA400_GEN_HYST_MSK,
1485 							     val));
1486 		default:
1487 			return -EINVAL;
1488 		}
1489 	case IIO_EV_TYPE_GESTURE:
1490 		switch (info) {
1491 		case IIO_EV_INFO_VALUE:
1492 			if (val < 0 || val > 7)
1493 				return -EINVAL;
1494 
1495 			return regmap_update_bits(data->regmap,
1496 						  BMA400_TAP_CONFIG,
1497 						  BMA400_TAP_SEN_MSK,
1498 						  FIELD_PREP(BMA400_TAP_SEN_MSK,
1499 							     val));
1500 		case IIO_EV_INFO_RESET_TIMEOUT:
1501 			raw = usec_to_tapreg_raw(val2, tap_reset_timeout);
1502 			if (raw < 0)
1503 				return -EINVAL;
1504 
1505 			return regmap_update_bits(data->regmap,
1506 						  BMA400_TAP_CONFIG1,
1507 						  BMA400_TAP_QUIET_MSK,
1508 						  FIELD_PREP(BMA400_TAP_QUIET_MSK,
1509 							     raw));
1510 		case IIO_EV_INFO_TAP2_MIN_DELAY:
1511 			raw = usec_to_tapreg_raw(val2, double_tap2_min_delay);
1512 			if (raw < 0)
1513 				return -EINVAL;
1514 
1515 			return regmap_update_bits(data->regmap,
1516 						  BMA400_TAP_CONFIG1,
1517 						  BMA400_TAP_QUIETDT_MSK,
1518 						  FIELD_PREP(BMA400_TAP_QUIETDT_MSK,
1519 							     raw));
1520 		default:
1521 			return -EINVAL;
1522 		}
1523 	default:
1524 		return -EINVAL;
1525 	}
1526 }
1527 
1528 static int bma400_data_rdy_trigger_set_state(struct iio_trigger *trig,
1529 					     bool state)
1530 {
1531 	struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig);
1532 	struct bma400_data *data = iio_priv(indio_dev);
1533 	int ret;
1534 
1535 	ret = regmap_update_bits(data->regmap, BMA400_INT_CONFIG0_REG,
1536 				 BMA400_INT_DRDY_MSK,
1537 				 FIELD_PREP(BMA400_INT_DRDY_MSK, state));
1538 	if (ret)
1539 		return ret;
1540 
1541 	return regmap_update_bits(data->regmap, BMA400_INT1_MAP_REG,
1542 				  BMA400_INT_DRDY_MSK,
1543 				  FIELD_PREP(BMA400_INT_DRDY_MSK, state));
1544 }
1545 
1546 static const unsigned long bma400_avail_scan_masks[] = {
1547 	BIT(BMA400_ACCL_X) | BIT(BMA400_ACCL_Y) | BIT(BMA400_ACCL_Z),
1548 	BIT(BMA400_ACCL_X) | BIT(BMA400_ACCL_Y) | BIT(BMA400_ACCL_Z)
1549 	| BIT(BMA400_TEMP),
1550 	0
1551 };
1552 
1553 static const struct iio_info bma400_info = {
1554 	.read_raw          = bma400_read_raw,
1555 	.read_avail        = bma400_read_avail,
1556 	.write_raw         = bma400_write_raw,
1557 	.write_raw_get_fmt = bma400_write_raw_get_fmt,
1558 	.read_event_config = bma400_read_event_config,
1559 	.write_event_config = bma400_write_event_config,
1560 	.write_event_value = bma400_write_event_value,
1561 	.read_event_value = bma400_read_event_value,
1562 	.event_attrs = &bma400_event_attribute_group,
1563 };
1564 
1565 static const struct iio_trigger_ops bma400_trigger_ops = {
1566 	.set_trigger_state = &bma400_data_rdy_trigger_set_state,
1567 	.validate_device = &iio_trigger_validate_own_device,
1568 };
1569 
1570 static irqreturn_t bma400_trigger_handler(int irq, void *p)
1571 {
1572 	struct iio_poll_func *pf = p;
1573 	struct iio_dev *indio_dev = pf->indio_dev;
1574 	struct bma400_data *data = iio_priv(indio_dev);
1575 	int ret, temp;
1576 
1577 	/* Lock to protect the data->buffer */
1578 	mutex_lock(&data->mutex);
1579 
1580 	/* bulk read six registers, with the base being the LSB register */
1581 	ret = regmap_bulk_read(data->regmap, BMA400_X_AXIS_LSB_REG,
1582 			       &data->buffer.buff, sizeof(data->buffer.buff));
1583 	if (ret)
1584 		goto unlock_err;
1585 
1586 	if (test_bit(BMA400_TEMP, indio_dev->active_scan_mask)) {
1587 		ret = regmap_read(data->regmap, BMA400_TEMP_DATA_REG, &temp);
1588 		if (ret)
1589 			goto unlock_err;
1590 
1591 		data->buffer.temperature = temp;
1592 	}
1593 
1594 	iio_push_to_buffers_with_timestamp(indio_dev, &data->buffer,
1595 					   iio_get_time_ns(indio_dev));
1596 
1597 	mutex_unlock(&data->mutex);
1598 	iio_trigger_notify_done(indio_dev->trig);
1599 	return IRQ_HANDLED;
1600 
1601 unlock_err:
1602 	mutex_unlock(&data->mutex);
1603 	return IRQ_NONE;
1604 }
1605 
1606 static irqreturn_t bma400_interrupt(int irq, void *private)
1607 {
1608 	struct iio_dev *indio_dev = private;
1609 	struct bma400_data *data = iio_priv(indio_dev);
1610 	s64 timestamp = iio_get_time_ns(indio_dev);
1611 	unsigned int act, ev_dir = IIO_EV_DIR_NONE;
1612 	int ret;
1613 
1614 	/* Lock to protect the data->status */
1615 	mutex_lock(&data->mutex);
1616 	ret = regmap_bulk_read(data->regmap, BMA400_INT_STAT0_REG,
1617 			       &data->status,
1618 			       sizeof(data->status));
1619 	/*
1620 	 * if none of the bit is set in the status register then it is
1621 	 * spurious interrupt.
1622 	 */
1623 	if (ret || !data->status)
1624 		goto unlock_err;
1625 
1626 	/*
1627 	 * Disable all advance interrupts if interrupt engine overrun occurs.
1628 	 * See section 4.7 "Interrupt engine overrun" in datasheet v1.2.
1629 	 */
1630 	if (FIELD_GET(BMA400_INT_ENG_OVRUN_MSK, le16_to_cpu(data->status))) {
1631 		bma400_disable_adv_interrupt(data);
1632 		dev_err(data->dev, "Interrupt engine overrun\n");
1633 		goto unlock_err;
1634 	}
1635 
1636 	if (FIELD_GET(BMA400_INT_S_TAP_MSK, le16_to_cpu(data->status)))
1637 		iio_push_event(indio_dev,
1638 			       IIO_MOD_EVENT_CODE(IIO_ACCEL, 0,
1639 						  IIO_MOD_X_OR_Y_OR_Z,
1640 						  IIO_EV_TYPE_GESTURE,
1641 						  IIO_EV_DIR_SINGLETAP),
1642 			       timestamp);
1643 
1644 	if (FIELD_GET(BMA400_INT_D_TAP_MSK, le16_to_cpu(data->status)))
1645 		iio_push_event(indio_dev,
1646 			       IIO_MOD_EVENT_CODE(IIO_ACCEL, 0,
1647 						  IIO_MOD_X_OR_Y_OR_Z,
1648 						  IIO_EV_TYPE_GESTURE,
1649 						  IIO_EV_DIR_DOUBLETAP),
1650 			       timestamp);
1651 
1652 	if (FIELD_GET(BMA400_INT_GEN1_MSK, le16_to_cpu(data->status)))
1653 		ev_dir = IIO_EV_DIR_RISING;
1654 
1655 	if (FIELD_GET(BMA400_INT_GEN2_MSK, le16_to_cpu(data->status)))
1656 		ev_dir = IIO_EV_DIR_FALLING;
1657 
1658 	if (ev_dir != IIO_EV_DIR_NONE) {
1659 		iio_push_event(indio_dev,
1660 			       IIO_MOD_EVENT_CODE(IIO_ACCEL, 0,
1661 						  IIO_MOD_X_OR_Y_OR_Z,
1662 						  IIO_EV_TYPE_MAG, ev_dir),
1663 			       timestamp);
1664 	}
1665 
1666 	if (FIELD_GET(BMA400_STEP_STAT_MASK, le16_to_cpu(data->status))) {
1667 		iio_push_event(indio_dev,
1668 			       IIO_MOD_EVENT_CODE(IIO_STEPS, 0, IIO_NO_MOD,
1669 						  IIO_EV_TYPE_CHANGE,
1670 						  IIO_EV_DIR_NONE),
1671 			       timestamp);
1672 
1673 		if (data->activity_event_en) {
1674 			ret = regmap_read(data->regmap, BMA400_STEP_STAT_REG,
1675 					  &act);
1676 			if (ret)
1677 				goto unlock_err;
1678 
1679 			iio_push_event(indio_dev,
1680 				       IIO_MOD_EVENT_CODE(IIO_ACTIVITY, 0,
1681 							  bma400_act_to_mod(act),
1682 							  IIO_EV_TYPE_CHANGE,
1683 							  IIO_EV_DIR_NONE),
1684 				       timestamp);
1685 		}
1686 	}
1687 
1688 	if (FIELD_GET(BMA400_INT_DRDY_MSK, le16_to_cpu(data->status))) {
1689 		mutex_unlock(&data->mutex);
1690 		iio_trigger_poll_nested(data->trig);
1691 		return IRQ_HANDLED;
1692 	}
1693 
1694 	mutex_unlock(&data->mutex);
1695 	return IRQ_HANDLED;
1696 
1697 unlock_err:
1698 	mutex_unlock(&data->mutex);
1699 	return IRQ_NONE;
1700 }
1701 
1702 int bma400_probe(struct device *dev, struct regmap *regmap, int irq,
1703 		 const char *name)
1704 {
1705 	struct iio_dev *indio_dev;
1706 	struct bma400_data *data;
1707 	int ret;
1708 
1709 	indio_dev = devm_iio_device_alloc(dev, sizeof(*data));
1710 	if (!indio_dev)
1711 		return -ENOMEM;
1712 
1713 	data = iio_priv(indio_dev);
1714 	data->regmap = regmap;
1715 	data->dev = dev;
1716 
1717 	ret = bma400_init(data);
1718 	if (ret)
1719 		return ret;
1720 
1721 	ret = iio_read_mount_matrix(dev, &data->orientation);
1722 	if (ret)
1723 		return ret;
1724 
1725 	mutex_init(&data->mutex);
1726 	indio_dev->name = name;
1727 	indio_dev->info = &bma400_info;
1728 	indio_dev->channels = bma400_channels;
1729 	indio_dev->num_channels = ARRAY_SIZE(bma400_channels);
1730 	indio_dev->available_scan_masks = bma400_avail_scan_masks;
1731 	indio_dev->modes = INDIO_DIRECT_MODE;
1732 
1733 	if (irq > 0) {
1734 		data->trig = devm_iio_trigger_alloc(dev, "%s-dev%d",
1735 						    indio_dev->name,
1736 						    iio_device_id(indio_dev));
1737 		if (!data->trig)
1738 			return -ENOMEM;
1739 
1740 		data->trig->ops = &bma400_trigger_ops;
1741 		iio_trigger_set_drvdata(data->trig, indio_dev);
1742 
1743 		ret = devm_iio_trigger_register(data->dev, data->trig);
1744 		if (ret)
1745 			return dev_err_probe(data->dev, ret,
1746 					     "iio trigger register fail\n");
1747 
1748 		indio_dev->trig = iio_trigger_get(data->trig);
1749 		ret = devm_request_threaded_irq(dev, irq, NULL,
1750 						&bma400_interrupt,
1751 						IRQF_TRIGGER_RISING | IRQF_ONESHOT,
1752 						indio_dev->name, indio_dev);
1753 		if (ret)
1754 			return dev_err_probe(data->dev, ret,
1755 					     "request irq %d failed\n", irq);
1756 	}
1757 
1758 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev, NULL,
1759 					      &bma400_trigger_handler, NULL);
1760 	if (ret)
1761 		return dev_err_probe(data->dev, ret,
1762 				     "iio triggered buffer setup failed\n");
1763 
1764 	return devm_iio_device_register(dev, indio_dev);
1765 }
1766 EXPORT_SYMBOL_NS(bma400_probe, IIO_BMA400);
1767 
1768 MODULE_AUTHOR("Dan Robertson <dan@dlrobertson.com>");
1769 MODULE_AUTHOR("Jagath Jog J <jagathjog1996@gmail.com>");
1770 MODULE_DESCRIPTION("Bosch BMA400 triaxial acceleration sensor core");
1771 MODULE_LICENSE("GPL");
1772