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