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