xref: /openbmc/linux/drivers/iio/accel/bma400_core.c (revision b9c19396)
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 		return ret;
810 	*val = get_unaligned_le24(steps_raw);
811 	kfree(steps_raw);
812 	return IIO_VAL_INT;
813 }
814 
815 static void bma400_init_tables(void)
816 {
817 	int raw;
818 	int i;
819 
820 	for (i = 0; i + 1 < ARRAY_SIZE(bma400_sample_freqs); i += 2) {
821 		raw = (i / 2) + 5;
822 		bma400_output_data_rate_from_raw(raw, &bma400_sample_freqs[i],
823 						 &bma400_sample_freqs[i + 1]);
824 	}
825 
826 	for (i = 0; i + 1 < ARRAY_SIZE(bma400_scales); i += 2) {
827 		raw = i / 2;
828 		bma400_scales[i] = 0;
829 		bma400_scales[i + 1] = BMA400_SCALE_MIN << raw;
830 	}
831 }
832 
833 static void bma400_regulators_disable(void *data_ptr)
834 {
835 	struct bma400_data *data = data_ptr;
836 
837 	regulator_bulk_disable(ARRAY_SIZE(data->regulators), data->regulators);
838 }
839 
840 static void bma400_power_disable(void *data_ptr)
841 {
842 	struct bma400_data *data = data_ptr;
843 	int ret;
844 
845 	mutex_lock(&data->mutex);
846 	ret = bma400_set_power_mode(data, POWER_MODE_SLEEP);
847 	mutex_unlock(&data->mutex);
848 	if (ret)
849 		dev_warn(data->dev, "Failed to put device into sleep mode (%pe)\n",
850 			 ERR_PTR(ret));
851 }
852 
853 static enum iio_modifier bma400_act_to_mod(enum bma400_activity activity)
854 {
855 	switch (activity) {
856 	case BMA400_STILL:
857 		return IIO_MOD_STILL;
858 	case BMA400_WALKING:
859 		return IIO_MOD_WALKING;
860 	case BMA400_RUNNING:
861 		return IIO_MOD_RUNNING;
862 	default:
863 		return IIO_NO_MOD;
864 	}
865 }
866 
867 static int bma400_init(struct bma400_data *data)
868 {
869 	unsigned int val;
870 	int ret;
871 
872 	data->regulators[BMA400_VDD_REGULATOR].supply = "vdd";
873 	data->regulators[BMA400_VDDIO_REGULATOR].supply = "vddio";
874 	ret = devm_regulator_bulk_get(data->dev,
875 				      ARRAY_SIZE(data->regulators),
876 				      data->regulators);
877 	if (ret) {
878 		if (ret != -EPROBE_DEFER)
879 			dev_err(data->dev,
880 				"Failed to get regulators: %d\n",
881 				ret);
882 
883 		return ret;
884 	}
885 	ret = regulator_bulk_enable(ARRAY_SIZE(data->regulators),
886 				    data->regulators);
887 	if (ret) {
888 		dev_err(data->dev, "Failed to enable regulators: %d\n",
889 			ret);
890 		return ret;
891 	}
892 
893 	ret = devm_add_action_or_reset(data->dev, bma400_regulators_disable, data);
894 	if (ret)
895 		return ret;
896 
897 	/* Try to read chip_id register. It must return 0x90. */
898 	ret = regmap_read(data->regmap, BMA400_CHIP_ID_REG, &val);
899 	if (ret) {
900 		dev_err(data->dev, "Failed to read chip id register\n");
901 		return ret;
902 	}
903 
904 	if (val != BMA400_ID_REG_VAL) {
905 		dev_err(data->dev, "Chip ID mismatch\n");
906 		return -ENODEV;
907 	}
908 
909 	ret = bma400_get_power_mode(data);
910 	if (ret) {
911 		dev_err(data->dev, "Failed to get the initial power-mode\n");
912 		return ret;
913 	}
914 
915 	if (data->power_mode != POWER_MODE_NORMAL) {
916 		ret = bma400_set_power_mode(data, POWER_MODE_NORMAL);
917 		if (ret) {
918 			dev_err(data->dev, "Failed to wake up the device\n");
919 			return ret;
920 		}
921 		/*
922 		 * TODO: The datasheet waits 1500us here in the example, but
923 		 * lists 2/ODR as the wakeup time.
924 		 */
925 		usleep_range(1500, 2000);
926 	}
927 
928 	ret = devm_add_action_or_reset(data->dev, bma400_power_disable, data);
929 	if (ret)
930 		return ret;
931 
932 	bma400_init_tables();
933 
934 	ret = bma400_get_accel_output_data_rate(data);
935 	if (ret)
936 		return ret;
937 
938 	ret = bma400_get_accel_oversampling_ratio(data);
939 	if (ret)
940 		return ret;
941 
942 	ret = bma400_get_accel_scale(data);
943 	if (ret)
944 		return ret;
945 
946 	/* Configure INT1 pin to open drain */
947 	ret = regmap_write(data->regmap, BMA400_INT_IO_CTRL_REG, 0x06);
948 	if (ret)
949 		return ret;
950 	/*
951 	 * Once the interrupt engine is supported we might use the
952 	 * data_src_reg, but for now ensure this is set to the
953 	 * variable ODR filter selectable by the sample frequency
954 	 * channel.
955 	 */
956 	return regmap_write(data->regmap, BMA400_ACC_CONFIG2_REG, 0x00);
957 }
958 
959 static int bma400_read_raw(struct iio_dev *indio_dev,
960 			   struct iio_chan_spec const *chan, int *val,
961 			   int *val2, long mask)
962 {
963 	struct bma400_data *data = iio_priv(indio_dev);
964 	unsigned int activity;
965 	int ret;
966 
967 	switch (mask) {
968 	case IIO_CHAN_INFO_PROCESSED:
969 		switch (chan->type) {
970 		case IIO_TEMP:
971 			mutex_lock(&data->mutex);
972 			ret = bma400_get_temp_reg(data, val, val2);
973 			mutex_unlock(&data->mutex);
974 			return ret;
975 		case IIO_STEPS:
976 			return bma400_get_steps_reg(data, val);
977 		case IIO_ACTIVITY:
978 			ret = regmap_read(data->regmap, BMA400_STEP_STAT_REG,
979 					  &activity);
980 			if (ret)
981 				return ret;
982 			/*
983 			 * The device does not support confidence value levels,
984 			 * so we will always have 100% for current activity and
985 			 * 0% for the others.
986 			 */
987 			if (chan->channel2 == bma400_act_to_mod(activity))
988 				*val = 100;
989 			else
990 				*val = 0;
991 			return IIO_VAL_INT;
992 		default:
993 			return -EINVAL;
994 		}
995 	case IIO_CHAN_INFO_RAW:
996 		mutex_lock(&data->mutex);
997 		ret = bma400_get_accel_reg(data, chan, val);
998 		mutex_unlock(&data->mutex);
999 		return ret;
1000 	case IIO_CHAN_INFO_SAMP_FREQ:
1001 		switch (chan->type) {
1002 		case IIO_ACCEL:
1003 			if (data->sample_freq.hz < 0)
1004 				return -EINVAL;
1005 
1006 			*val = data->sample_freq.hz;
1007 			*val2 = data->sample_freq.uhz;
1008 			return IIO_VAL_INT_PLUS_MICRO;
1009 		case IIO_TEMP:
1010 			/*
1011 			 * Runs at a fixed sampling frequency. See Section 4.4
1012 			 * of the datasheet.
1013 			 */
1014 			*val = 6;
1015 			*val2 = 250000;
1016 			return IIO_VAL_INT_PLUS_MICRO;
1017 		default:
1018 			return -EINVAL;
1019 		}
1020 	case IIO_CHAN_INFO_SCALE:
1021 		*val = 0;
1022 		*val2 = data->scale;
1023 		return IIO_VAL_INT_PLUS_MICRO;
1024 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1025 		/*
1026 		 * TODO: We could avoid this logic and returning -EINVAL here if
1027 		 * we set both the low-power and normal mode OSR registers when
1028 		 * we configure the device.
1029 		 */
1030 		if (data->oversampling_ratio < 0)
1031 			return -EINVAL;
1032 
1033 		*val = data->oversampling_ratio;
1034 		return IIO_VAL_INT;
1035 	case IIO_CHAN_INFO_ENABLE:
1036 		*val = data->steps_enabled;
1037 		return IIO_VAL_INT;
1038 	default:
1039 		return -EINVAL;
1040 	}
1041 }
1042 
1043 static int bma400_read_avail(struct iio_dev *indio_dev,
1044 			     struct iio_chan_spec const *chan,
1045 			     const int **vals, int *type, int *length,
1046 			     long mask)
1047 {
1048 	switch (mask) {
1049 	case IIO_CHAN_INFO_SCALE:
1050 		*type = IIO_VAL_INT_PLUS_MICRO;
1051 		*vals = bma400_scales;
1052 		*length = ARRAY_SIZE(bma400_scales);
1053 		return IIO_AVAIL_LIST;
1054 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1055 		*type = IIO_VAL_INT;
1056 		*vals = bma400_osr_range;
1057 		*length = ARRAY_SIZE(bma400_osr_range);
1058 		return IIO_AVAIL_RANGE;
1059 	case IIO_CHAN_INFO_SAMP_FREQ:
1060 		*type = IIO_VAL_INT_PLUS_MICRO;
1061 		*vals = bma400_sample_freqs;
1062 		*length = ARRAY_SIZE(bma400_sample_freqs);
1063 		return IIO_AVAIL_LIST;
1064 	default:
1065 		return -EINVAL;
1066 	}
1067 }
1068 
1069 static int bma400_write_raw(struct iio_dev *indio_dev,
1070 			    struct iio_chan_spec const *chan, int val, int val2,
1071 			    long mask)
1072 {
1073 	struct bma400_data *data = iio_priv(indio_dev);
1074 	int ret;
1075 
1076 	switch (mask) {
1077 	case IIO_CHAN_INFO_SAMP_FREQ:
1078 		/*
1079 		 * The sample frequency is readonly for the temperature
1080 		 * register and a fixed value in low-power mode.
1081 		 */
1082 		if (chan->type != IIO_ACCEL)
1083 			return -EINVAL;
1084 
1085 		mutex_lock(&data->mutex);
1086 		ret = bma400_set_accel_output_data_rate(data, val, val2);
1087 		mutex_unlock(&data->mutex);
1088 		return ret;
1089 	case IIO_CHAN_INFO_SCALE:
1090 		if (val != 0 ||
1091 		    val2 < BMA400_SCALE_MIN || val2 > BMA400_SCALE_MAX)
1092 			return -EINVAL;
1093 
1094 		mutex_lock(&data->mutex);
1095 		ret = bma400_set_accel_scale(data, val2);
1096 		mutex_unlock(&data->mutex);
1097 		return ret;
1098 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1099 		mutex_lock(&data->mutex);
1100 		ret = bma400_set_accel_oversampling_ratio(data, val);
1101 		mutex_unlock(&data->mutex);
1102 		return ret;
1103 	case IIO_CHAN_INFO_ENABLE:
1104 		mutex_lock(&data->mutex);
1105 		ret = bma400_enable_steps(data, val);
1106 		mutex_unlock(&data->mutex);
1107 		return ret;
1108 	default:
1109 		return -EINVAL;
1110 	}
1111 }
1112 
1113 static int bma400_write_raw_get_fmt(struct iio_dev *indio_dev,
1114 				    struct iio_chan_spec const *chan,
1115 				    long mask)
1116 {
1117 	switch (mask) {
1118 	case IIO_CHAN_INFO_SAMP_FREQ:
1119 		return IIO_VAL_INT_PLUS_MICRO;
1120 	case IIO_CHAN_INFO_SCALE:
1121 		return IIO_VAL_INT_PLUS_MICRO;
1122 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1123 		return IIO_VAL_INT;
1124 	case IIO_CHAN_INFO_ENABLE:
1125 		return IIO_VAL_INT;
1126 	default:
1127 		return -EINVAL;
1128 	}
1129 }
1130 
1131 static int bma400_read_event_config(struct iio_dev *indio_dev,
1132 				    const struct iio_chan_spec *chan,
1133 				    enum iio_event_type type,
1134 				    enum iio_event_direction dir)
1135 {
1136 	struct bma400_data *data = iio_priv(indio_dev);
1137 
1138 	switch (chan->type) {
1139 	case IIO_ACCEL:
1140 		switch (dir) {
1141 		case IIO_EV_DIR_RISING:
1142 			return FIELD_GET(BMA400_INT_GEN1_MSK,
1143 					 data->generic_event_en);
1144 		case IIO_EV_DIR_FALLING:
1145 			return FIELD_GET(BMA400_INT_GEN2_MSK,
1146 					 data->generic_event_en);
1147 		case IIO_EV_DIR_SINGLETAP:
1148 			return FIELD_GET(BMA400_S_TAP_MSK,
1149 					 data->tap_event_en_bitmask);
1150 		case IIO_EV_DIR_DOUBLETAP:
1151 			return FIELD_GET(BMA400_D_TAP_MSK,
1152 					 data->tap_event_en_bitmask);
1153 		default:
1154 			return -EINVAL;
1155 		}
1156 	case IIO_STEPS:
1157 		return data->step_event_en;
1158 	case IIO_ACTIVITY:
1159 		return data->activity_event_en;
1160 	default:
1161 		return -EINVAL;
1162 	}
1163 }
1164 
1165 static int bma400_steps_event_enable(struct bma400_data *data, int state)
1166 {
1167 	int ret;
1168 
1169 	ret = bma400_enable_steps(data, 1);
1170 	if (ret)
1171 		return ret;
1172 
1173 	ret = regmap_update_bits(data->regmap, BMA400_INT12_MAP_REG,
1174 				 BMA400_STEP_INT_MSK,
1175 				 FIELD_PREP(BMA400_STEP_INT_MSK,
1176 					    state));
1177 	if (ret)
1178 		return ret;
1179 	data->step_event_en = state;
1180 	return 0;
1181 }
1182 
1183 static int bma400_activity_event_en(struct bma400_data *data,
1184 				    enum iio_event_direction dir,
1185 				    int state)
1186 {
1187 	int ret, reg, msk, value;
1188 	int field_value = 0;
1189 
1190 	switch (dir) {
1191 	case IIO_EV_DIR_RISING:
1192 		reg = BMA400_GEN1INT_CONFIG0;
1193 		msk = BMA400_INT_GEN1_MSK;
1194 		value = 2;
1195 		set_mask_bits(&field_value, BMA400_INT_GEN1_MSK,
1196 			      FIELD_PREP(BMA400_INT_GEN1_MSK, state));
1197 		break;
1198 	case IIO_EV_DIR_FALLING:
1199 		reg = BMA400_GEN2INT_CONFIG0;
1200 		msk = BMA400_INT_GEN2_MSK;
1201 		value = 0;
1202 		set_mask_bits(&field_value, BMA400_INT_GEN2_MSK,
1203 			      FIELD_PREP(BMA400_INT_GEN2_MSK, state));
1204 		break;
1205 	default:
1206 		return -EINVAL;
1207 	}
1208 
1209 	/* Enabling all axis for interrupt evaluation */
1210 	ret = regmap_write(data->regmap, reg, 0xF8);
1211 	if (ret)
1212 		return ret;
1213 
1214 	/* OR combination of all axis for interrupt evaluation */
1215 	ret = regmap_write(data->regmap, reg + BMA400_GEN_CONFIG1_OFF, value);
1216 	if (ret)
1217 		return ret;
1218 
1219 	/* Initial value to avoid interrupts while enabling*/
1220 	ret = regmap_write(data->regmap, reg + BMA400_GEN_CONFIG2_OFF, 0x0A);
1221 	if (ret)
1222 		return ret;
1223 
1224 	/* Initial duration value to avoid interrupts while enabling*/
1225 	ret = regmap_write(data->regmap, reg + BMA400_GEN_CONFIG31_OFF, 0x0F);
1226 	if (ret)
1227 		return ret;
1228 
1229 	ret = regmap_update_bits(data->regmap, BMA400_INT1_MAP_REG, msk,
1230 				 field_value);
1231 	if (ret)
1232 		return ret;
1233 
1234 	ret = regmap_update_bits(data->regmap, BMA400_INT_CONFIG0_REG, msk,
1235 				 field_value);
1236 	if (ret)
1237 		return ret;
1238 
1239 	set_mask_bits(&data->generic_event_en, msk, field_value);
1240 	return 0;
1241 }
1242 
1243 static int bma400_tap_event_en(struct bma400_data *data,
1244 			       enum iio_event_direction dir, int state)
1245 {
1246 	unsigned int mask, field_value;
1247 	int ret;
1248 
1249 	/*
1250 	 * Tap interrupts can be configured only in normal mode.
1251 	 * See table in section 4.3 "Power modes - performance modes" of
1252 	 * datasheet v1.2.
1253 	 */
1254 	if (data->power_mode != POWER_MODE_NORMAL)
1255 		return -EINVAL;
1256 
1257 	/*
1258 	 * Tap interrupts are operating with a data rate of 200Hz.
1259 	 * See section 4.7 "Tap sensing interrupt" in datasheet v1.2.
1260 	 */
1261 	if (data->sample_freq.hz != 200 && state) {
1262 		dev_err(data->dev, "Invalid data rate for tap interrupts.\n");
1263 		return -EINVAL;
1264 	}
1265 
1266 	ret = regmap_update_bits(data->regmap, BMA400_INT12_MAP_REG,
1267 				 BMA400_S_TAP_MSK,
1268 				 FIELD_PREP(BMA400_S_TAP_MSK, state));
1269 	if (ret)
1270 		return ret;
1271 
1272 	switch (dir) {
1273 	case IIO_EV_DIR_SINGLETAP:
1274 		mask = BMA400_S_TAP_MSK;
1275 		set_mask_bits(&field_value, BMA400_S_TAP_MSK,
1276 			      FIELD_PREP(BMA400_S_TAP_MSK, state));
1277 		break;
1278 	case IIO_EV_DIR_DOUBLETAP:
1279 		mask = BMA400_D_TAP_MSK;
1280 		set_mask_bits(&field_value, BMA400_D_TAP_MSK,
1281 			      FIELD_PREP(BMA400_D_TAP_MSK, state));
1282 		break;
1283 	default:
1284 		return -EINVAL;
1285 	}
1286 
1287 	ret = regmap_update_bits(data->regmap, BMA400_INT_CONFIG1_REG, mask,
1288 				 field_value);
1289 	if (ret)
1290 		return ret;
1291 
1292 	set_mask_bits(&data->tap_event_en_bitmask, mask, field_value);
1293 
1294 	return 0;
1295 }
1296 
1297 static int bma400_disable_adv_interrupt(struct bma400_data *data)
1298 {
1299 	int ret;
1300 
1301 	ret = regmap_write(data->regmap, BMA400_INT_CONFIG0_REG, 0);
1302 	if (ret)
1303 		return ret;
1304 
1305 	ret = regmap_write(data->regmap, BMA400_INT_CONFIG1_REG, 0);
1306 	if (ret)
1307 		return ret;
1308 
1309 	data->tap_event_en_bitmask = 0;
1310 	data->generic_event_en = 0;
1311 	data->step_event_en = false;
1312 	data->activity_event_en = false;
1313 
1314 	return 0;
1315 }
1316 
1317 static int bma400_write_event_config(struct iio_dev *indio_dev,
1318 				     const struct iio_chan_spec *chan,
1319 				     enum iio_event_type type,
1320 				     enum iio_event_direction dir, int state)
1321 {
1322 	struct bma400_data *data = iio_priv(indio_dev);
1323 	int ret;
1324 
1325 	switch (chan->type) {
1326 	case IIO_ACCEL:
1327 		switch (type) {
1328 		case IIO_EV_TYPE_MAG:
1329 			mutex_lock(&data->mutex);
1330 			ret = bma400_activity_event_en(data, dir, state);
1331 			mutex_unlock(&data->mutex);
1332 			return ret;
1333 		case IIO_EV_TYPE_GESTURE:
1334 			mutex_lock(&data->mutex);
1335 			ret = bma400_tap_event_en(data, dir, state);
1336 			mutex_unlock(&data->mutex);
1337 			return ret;
1338 		default:
1339 			return -EINVAL;
1340 		}
1341 	case IIO_STEPS:
1342 		mutex_lock(&data->mutex);
1343 		ret = bma400_steps_event_enable(data, state);
1344 		mutex_unlock(&data->mutex);
1345 		return ret;
1346 	case IIO_ACTIVITY:
1347 		mutex_lock(&data->mutex);
1348 		if (!data->step_event_en) {
1349 			ret = bma400_steps_event_enable(data, true);
1350 			if (ret) {
1351 				mutex_unlock(&data->mutex);
1352 				return ret;
1353 			}
1354 		}
1355 		data->activity_event_en = state;
1356 		mutex_unlock(&data->mutex);
1357 		return 0;
1358 	default:
1359 		return -EINVAL;
1360 	}
1361 }
1362 
1363 static int get_gen_config_reg(enum iio_event_direction dir)
1364 {
1365 	switch (dir) {
1366 	case IIO_EV_DIR_FALLING:
1367 		return BMA400_GEN2INT_CONFIG0;
1368 	case IIO_EV_DIR_RISING:
1369 		return BMA400_GEN1INT_CONFIG0;
1370 	default:
1371 		return -EINVAL;
1372 	}
1373 }
1374 
1375 static int bma400_read_event_value(struct iio_dev *indio_dev,
1376 				   const struct iio_chan_spec *chan,
1377 				   enum iio_event_type type,
1378 				   enum iio_event_direction dir,
1379 				   enum iio_event_info info,
1380 				   int *val, int *val2)
1381 {
1382 	struct bma400_data *data = iio_priv(indio_dev);
1383 	int ret, reg, reg_val, raw;
1384 
1385 	if (chan->type != IIO_ACCEL)
1386 		return -EINVAL;
1387 
1388 	switch (type) {
1389 	case IIO_EV_TYPE_MAG:
1390 		reg = get_gen_config_reg(dir);
1391 		if (reg < 0)
1392 			return -EINVAL;
1393 
1394 		*val2 = 0;
1395 		switch (info) {
1396 		case IIO_EV_INFO_VALUE:
1397 			ret = regmap_read(data->regmap,
1398 					  reg + BMA400_GEN_CONFIG2_OFF,
1399 					  val);
1400 			if (ret)
1401 				return ret;
1402 			return IIO_VAL_INT;
1403 		case IIO_EV_INFO_PERIOD:
1404 			mutex_lock(&data->mutex);
1405 			ret = regmap_bulk_read(data->regmap,
1406 					       reg + BMA400_GEN_CONFIG3_OFF,
1407 					       &data->duration,
1408 					       sizeof(data->duration));
1409 			if (ret) {
1410 				mutex_unlock(&data->mutex);
1411 				return ret;
1412 			}
1413 			*val = be16_to_cpu(data->duration);
1414 			mutex_unlock(&data->mutex);
1415 			return IIO_VAL_INT;
1416 		case IIO_EV_INFO_HYSTERESIS:
1417 			ret = regmap_read(data->regmap, reg, val);
1418 			if (ret)
1419 				return ret;
1420 			*val = FIELD_GET(BMA400_GEN_HYST_MSK, *val);
1421 			return IIO_VAL_INT;
1422 		default:
1423 			return -EINVAL;
1424 		}
1425 	case IIO_EV_TYPE_GESTURE:
1426 		switch (info) {
1427 		case IIO_EV_INFO_VALUE:
1428 			ret = regmap_read(data->regmap, BMA400_TAP_CONFIG,
1429 					  &reg_val);
1430 			if (ret)
1431 				return ret;
1432 
1433 			*val = FIELD_GET(BMA400_TAP_SEN_MSK, reg_val);
1434 			return IIO_VAL_INT;
1435 		case IIO_EV_INFO_RESET_TIMEOUT:
1436 			ret = regmap_read(data->regmap, BMA400_TAP_CONFIG1,
1437 					  &reg_val);
1438 			if (ret)
1439 				return ret;
1440 
1441 			raw = FIELD_GET(BMA400_TAP_QUIET_MSK, reg_val);
1442 			*val = 0;
1443 			*val2 = tap_reset_timeout[raw];
1444 			return IIO_VAL_INT_PLUS_MICRO;
1445 		case IIO_EV_INFO_TAP2_MIN_DELAY:
1446 			ret = regmap_read(data->regmap, BMA400_TAP_CONFIG1,
1447 					  &reg_val);
1448 			if (ret)
1449 				return ret;
1450 
1451 			raw = FIELD_GET(BMA400_TAP_QUIETDT_MSK, reg_val);
1452 			*val = 0;
1453 			*val2 = double_tap2_min_delay[raw];
1454 			return IIO_VAL_INT_PLUS_MICRO;
1455 		default:
1456 			return -EINVAL;
1457 		}
1458 	default:
1459 		return -EINVAL;
1460 	}
1461 }
1462 
1463 static int bma400_write_event_value(struct iio_dev *indio_dev,
1464 				    const struct iio_chan_spec *chan,
1465 				    enum iio_event_type type,
1466 				    enum iio_event_direction dir,
1467 				    enum iio_event_info info,
1468 				    int val, int val2)
1469 {
1470 	struct bma400_data *data = iio_priv(indio_dev);
1471 	int reg, ret, raw;
1472 
1473 	if (chan->type != IIO_ACCEL)
1474 		return -EINVAL;
1475 
1476 	switch (type) {
1477 	case IIO_EV_TYPE_MAG:
1478 		reg = get_gen_config_reg(dir);
1479 		if (reg < 0)
1480 			return -EINVAL;
1481 
1482 		switch (info) {
1483 		case IIO_EV_INFO_VALUE:
1484 			if (val < 1 || val > 255)
1485 				return -EINVAL;
1486 
1487 			return regmap_write(data->regmap,
1488 					    reg + BMA400_GEN_CONFIG2_OFF,
1489 					    val);
1490 		case IIO_EV_INFO_PERIOD:
1491 			if (val < 1 || val > 65535)
1492 				return -EINVAL;
1493 
1494 			mutex_lock(&data->mutex);
1495 			put_unaligned_be16(val, &data->duration);
1496 			ret = regmap_bulk_write(data->regmap,
1497 						reg + BMA400_GEN_CONFIG3_OFF,
1498 						&data->duration,
1499 						sizeof(data->duration));
1500 			mutex_unlock(&data->mutex);
1501 			return ret;
1502 		case IIO_EV_INFO_HYSTERESIS:
1503 			if (val < 0 || val > 3)
1504 				return -EINVAL;
1505 
1506 			return regmap_update_bits(data->regmap, reg,
1507 						  BMA400_GEN_HYST_MSK,
1508 						  FIELD_PREP(BMA400_GEN_HYST_MSK,
1509 							     val));
1510 		default:
1511 			return -EINVAL;
1512 		}
1513 	case IIO_EV_TYPE_GESTURE:
1514 		switch (info) {
1515 		case IIO_EV_INFO_VALUE:
1516 			if (val < 0 || val > 7)
1517 				return -EINVAL;
1518 
1519 			return regmap_update_bits(data->regmap,
1520 						  BMA400_TAP_CONFIG,
1521 						  BMA400_TAP_SEN_MSK,
1522 						  FIELD_PREP(BMA400_TAP_SEN_MSK,
1523 							     val));
1524 		case IIO_EV_INFO_RESET_TIMEOUT:
1525 			raw = usec_to_tapreg_raw(val2, tap_reset_timeout);
1526 			if (raw < 0)
1527 				return -EINVAL;
1528 
1529 			return regmap_update_bits(data->regmap,
1530 						  BMA400_TAP_CONFIG1,
1531 						  BMA400_TAP_QUIET_MSK,
1532 						  FIELD_PREP(BMA400_TAP_QUIET_MSK,
1533 							     raw));
1534 		case IIO_EV_INFO_TAP2_MIN_DELAY:
1535 			raw = usec_to_tapreg_raw(val2, double_tap2_min_delay);
1536 			if (raw < 0)
1537 				return -EINVAL;
1538 
1539 			return regmap_update_bits(data->regmap,
1540 						  BMA400_TAP_CONFIG1,
1541 						  BMA400_TAP_QUIETDT_MSK,
1542 						  FIELD_PREP(BMA400_TAP_QUIETDT_MSK,
1543 							     raw));
1544 		default:
1545 			return -EINVAL;
1546 		}
1547 	default:
1548 		return -EINVAL;
1549 	}
1550 }
1551 
1552 static int bma400_data_rdy_trigger_set_state(struct iio_trigger *trig,
1553 					     bool state)
1554 {
1555 	struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig);
1556 	struct bma400_data *data = iio_priv(indio_dev);
1557 	int ret;
1558 
1559 	ret = regmap_update_bits(data->regmap, BMA400_INT_CONFIG0_REG,
1560 				 BMA400_INT_DRDY_MSK,
1561 				 FIELD_PREP(BMA400_INT_DRDY_MSK, state));
1562 	if (ret)
1563 		return ret;
1564 
1565 	return regmap_update_bits(data->regmap, BMA400_INT1_MAP_REG,
1566 				  BMA400_INT_DRDY_MSK,
1567 				  FIELD_PREP(BMA400_INT_DRDY_MSK, state));
1568 }
1569 
1570 static const unsigned long bma400_avail_scan_masks[] = {
1571 	BIT(BMA400_ACCL_X) | BIT(BMA400_ACCL_Y) | BIT(BMA400_ACCL_Z),
1572 	BIT(BMA400_ACCL_X) | BIT(BMA400_ACCL_Y) | BIT(BMA400_ACCL_Z)
1573 	| BIT(BMA400_TEMP),
1574 	0
1575 };
1576 
1577 static const struct iio_info bma400_info = {
1578 	.read_raw          = bma400_read_raw,
1579 	.read_avail        = bma400_read_avail,
1580 	.write_raw         = bma400_write_raw,
1581 	.write_raw_get_fmt = bma400_write_raw_get_fmt,
1582 	.read_event_config = bma400_read_event_config,
1583 	.write_event_config = bma400_write_event_config,
1584 	.write_event_value = bma400_write_event_value,
1585 	.read_event_value = bma400_read_event_value,
1586 	.event_attrs = &bma400_event_attribute_group,
1587 };
1588 
1589 static const struct iio_trigger_ops bma400_trigger_ops = {
1590 	.set_trigger_state = &bma400_data_rdy_trigger_set_state,
1591 	.validate_device = &iio_trigger_validate_own_device,
1592 };
1593 
1594 static irqreturn_t bma400_trigger_handler(int irq, void *p)
1595 {
1596 	struct iio_poll_func *pf = p;
1597 	struct iio_dev *indio_dev = pf->indio_dev;
1598 	struct bma400_data *data = iio_priv(indio_dev);
1599 	int ret, temp;
1600 
1601 	/* Lock to protect the data->buffer */
1602 	mutex_lock(&data->mutex);
1603 
1604 	/* bulk read six registers, with the base being the LSB register */
1605 	ret = regmap_bulk_read(data->regmap, BMA400_X_AXIS_LSB_REG,
1606 			       &data->buffer.buff, sizeof(data->buffer.buff));
1607 	if (ret)
1608 		goto unlock_err;
1609 
1610 	if (test_bit(BMA400_TEMP, indio_dev->active_scan_mask)) {
1611 		ret = regmap_read(data->regmap, BMA400_TEMP_DATA_REG, &temp);
1612 		if (ret)
1613 			goto unlock_err;
1614 
1615 		data->buffer.temperature = temp;
1616 	}
1617 
1618 	iio_push_to_buffers_with_timestamp(indio_dev, &data->buffer,
1619 					   iio_get_time_ns(indio_dev));
1620 
1621 	mutex_unlock(&data->mutex);
1622 	iio_trigger_notify_done(indio_dev->trig);
1623 	return IRQ_HANDLED;
1624 
1625 unlock_err:
1626 	mutex_unlock(&data->mutex);
1627 	return IRQ_NONE;
1628 }
1629 
1630 static irqreturn_t bma400_interrupt(int irq, void *private)
1631 {
1632 	struct iio_dev *indio_dev = private;
1633 	struct bma400_data *data = iio_priv(indio_dev);
1634 	s64 timestamp = iio_get_time_ns(indio_dev);
1635 	unsigned int act, ev_dir = IIO_EV_DIR_NONE;
1636 	int ret;
1637 
1638 	/* Lock to protect the data->status */
1639 	mutex_lock(&data->mutex);
1640 	ret = regmap_bulk_read(data->regmap, BMA400_INT_STAT0_REG,
1641 			       &data->status,
1642 			       sizeof(data->status));
1643 	/*
1644 	 * if none of the bit is set in the status register then it is
1645 	 * spurious interrupt.
1646 	 */
1647 	if (ret || !data->status)
1648 		goto unlock_err;
1649 
1650 	/*
1651 	 * Disable all advance interrupts if interrupt engine overrun occurs.
1652 	 * See section 4.7 "Interrupt engine overrun" in datasheet v1.2.
1653 	 */
1654 	if (FIELD_GET(BMA400_INT_ENG_OVRUN_MSK, le16_to_cpu(data->status))) {
1655 		bma400_disable_adv_interrupt(data);
1656 		dev_err(data->dev, "Interrupt engine overrun\n");
1657 		goto unlock_err;
1658 	}
1659 
1660 	if (FIELD_GET(BMA400_INT_S_TAP_MSK, le16_to_cpu(data->status)))
1661 		iio_push_event(indio_dev,
1662 			       IIO_MOD_EVENT_CODE(IIO_ACCEL, 0,
1663 						  IIO_MOD_X_OR_Y_OR_Z,
1664 						  IIO_EV_TYPE_GESTURE,
1665 						  IIO_EV_DIR_SINGLETAP),
1666 			       timestamp);
1667 
1668 	if (FIELD_GET(BMA400_INT_D_TAP_MSK, le16_to_cpu(data->status)))
1669 		iio_push_event(indio_dev,
1670 			       IIO_MOD_EVENT_CODE(IIO_ACCEL, 0,
1671 						  IIO_MOD_X_OR_Y_OR_Z,
1672 						  IIO_EV_TYPE_GESTURE,
1673 						  IIO_EV_DIR_DOUBLETAP),
1674 			       timestamp);
1675 
1676 	if (FIELD_GET(BMA400_INT_GEN1_MSK, le16_to_cpu(data->status)))
1677 		ev_dir = IIO_EV_DIR_RISING;
1678 
1679 	if (FIELD_GET(BMA400_INT_GEN2_MSK, le16_to_cpu(data->status)))
1680 		ev_dir = IIO_EV_DIR_FALLING;
1681 
1682 	if (ev_dir != IIO_EV_DIR_NONE) {
1683 		iio_push_event(indio_dev,
1684 			       IIO_MOD_EVENT_CODE(IIO_ACCEL, 0,
1685 						  IIO_MOD_X_OR_Y_OR_Z,
1686 						  IIO_EV_TYPE_MAG, ev_dir),
1687 			       timestamp);
1688 	}
1689 
1690 	if (FIELD_GET(BMA400_STEP_STAT_MASK, le16_to_cpu(data->status))) {
1691 		iio_push_event(indio_dev,
1692 			       IIO_MOD_EVENT_CODE(IIO_STEPS, 0, IIO_NO_MOD,
1693 						  IIO_EV_TYPE_CHANGE,
1694 						  IIO_EV_DIR_NONE),
1695 			       timestamp);
1696 
1697 		if (data->activity_event_en) {
1698 			ret = regmap_read(data->regmap, BMA400_STEP_STAT_REG,
1699 					  &act);
1700 			if (ret)
1701 				goto unlock_err;
1702 
1703 			iio_push_event(indio_dev,
1704 				       IIO_MOD_EVENT_CODE(IIO_ACTIVITY, 0,
1705 							  bma400_act_to_mod(act),
1706 							  IIO_EV_TYPE_CHANGE,
1707 							  IIO_EV_DIR_NONE),
1708 				       timestamp);
1709 		}
1710 	}
1711 
1712 	if (FIELD_GET(BMA400_INT_DRDY_MSK, le16_to_cpu(data->status))) {
1713 		mutex_unlock(&data->mutex);
1714 		iio_trigger_poll_chained(data->trig);
1715 		return IRQ_HANDLED;
1716 	}
1717 
1718 	mutex_unlock(&data->mutex);
1719 	return IRQ_HANDLED;
1720 
1721 unlock_err:
1722 	mutex_unlock(&data->mutex);
1723 	return IRQ_NONE;
1724 }
1725 
1726 int bma400_probe(struct device *dev, struct regmap *regmap, int irq,
1727 		 const char *name)
1728 {
1729 	struct iio_dev *indio_dev;
1730 	struct bma400_data *data;
1731 	int ret;
1732 
1733 	indio_dev = devm_iio_device_alloc(dev, sizeof(*data));
1734 	if (!indio_dev)
1735 		return -ENOMEM;
1736 
1737 	data = iio_priv(indio_dev);
1738 	data->regmap = regmap;
1739 	data->dev = dev;
1740 
1741 	ret = bma400_init(data);
1742 	if (ret)
1743 		return ret;
1744 
1745 	ret = iio_read_mount_matrix(dev, &data->orientation);
1746 	if (ret)
1747 		return ret;
1748 
1749 	mutex_init(&data->mutex);
1750 	indio_dev->name = name;
1751 	indio_dev->info = &bma400_info;
1752 	indio_dev->channels = bma400_channels;
1753 	indio_dev->num_channels = ARRAY_SIZE(bma400_channels);
1754 	indio_dev->available_scan_masks = bma400_avail_scan_masks;
1755 	indio_dev->modes = INDIO_DIRECT_MODE;
1756 
1757 	if (irq > 0) {
1758 		data->trig = devm_iio_trigger_alloc(dev, "%s-dev%d",
1759 						    indio_dev->name,
1760 						    iio_device_id(indio_dev));
1761 		if (!data->trig)
1762 			return -ENOMEM;
1763 
1764 		data->trig->ops = &bma400_trigger_ops;
1765 		iio_trigger_set_drvdata(data->trig, indio_dev);
1766 
1767 		ret = devm_iio_trigger_register(data->dev, data->trig);
1768 		if (ret)
1769 			return dev_err_probe(data->dev, ret,
1770 					     "iio trigger register fail\n");
1771 
1772 		indio_dev->trig = iio_trigger_get(data->trig);
1773 		ret = devm_request_threaded_irq(dev, irq, NULL,
1774 						&bma400_interrupt,
1775 						IRQF_TRIGGER_RISING | IRQF_ONESHOT,
1776 						indio_dev->name, indio_dev);
1777 		if (ret)
1778 			return dev_err_probe(data->dev, ret,
1779 					     "request irq %d failed\n", irq);
1780 	}
1781 
1782 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev, NULL,
1783 					      &bma400_trigger_handler, NULL);
1784 	if (ret)
1785 		return dev_err_probe(data->dev, ret,
1786 				     "iio triggered buffer setup failed\n");
1787 
1788 	return devm_iio_device_register(dev, indio_dev);
1789 }
1790 EXPORT_SYMBOL_NS(bma400_probe, IIO_BMA400);
1791 
1792 MODULE_AUTHOR("Dan Robertson <dan@dlrobertson.com>");
1793 MODULE_AUTHOR("Jagath Jog J <jagathjog1996@gmail.com>");
1794 MODULE_DESCRIPTION("Bosch BMA400 triaxial acceleration sensor core");
1795 MODULE_LICENSE("GPL");
1796