1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2022 ROHM Semiconductors
4  *
5  * ROHM/KIONIX KX022A accelerometer driver
6  */
7 
8 #include <linux/delay.h>
9 #include <linux/device.h>
10 #include <linux/interrupt.h>
11 #include <linux/module.h>
12 #include <linux/moduleparam.h>
13 #include <linux/mutex.h>
14 #include <linux/property.h>
15 #include <linux/regmap.h>
16 #include <linux/regulator/consumer.h>
17 #include <linux/slab.h>
18 #include <linux/string_helpers.h>
19 #include <linux/units.h>
20 
21 #include <linux/iio/iio.h>
22 #include <linux/iio/sysfs.h>
23 #include <linux/iio/trigger.h>
24 #include <linux/iio/trigger_consumer.h>
25 #include <linux/iio/triggered_buffer.h>
26 
27 #include "kionix-kx022a.h"
28 
29 /*
30  * The KX022A has FIFO which can store 43 samples of HiRes data from 2
31  * channels. This equals to 43 (samples) * 3 (channels) * 2 (bytes/sample) to
32  * 258 bytes of sample data. The quirk to know is that the amount of bytes in
33  * the FIFO is advertised via 8 bit register (max value 255). The thing to note
34  * is that full 258 bytes of data is indicated using the max value 255.
35  */
36 #define KX022A_FIFO_LENGTH			43
37 #define KX022A_FIFO_FULL_VALUE			255
38 #define KX022A_SOFT_RESET_WAIT_TIME_US		(5 * USEC_PER_MSEC)
39 #define KX022A_SOFT_RESET_TOTAL_WAIT_TIME_US	(500 * USEC_PER_MSEC)
40 
41 /* 3 axis, 2 bytes of data for each of the axis */
42 #define KX022A_FIFO_SAMPLES_SIZE_BYTES		6
43 #define KX022A_FIFO_MAX_BYTES					\
44 	(KX022A_FIFO_LENGTH * KX022A_FIFO_SAMPLES_SIZE_BYTES)
45 
46 enum {
47 	KX022A_STATE_SAMPLE,
48 	KX022A_STATE_FIFO,
49 };
50 
51 /* Regmap configs */
52 static const struct regmap_range kx022a_volatile_ranges[] = {
53 	{
54 		.range_min = KX022A_REG_XHP_L,
55 		.range_max = KX022A_REG_COTR,
56 	}, {
57 		.range_min = KX022A_REG_TSCP,
58 		.range_max = KX022A_REG_INT_REL,
59 	}, {
60 		/* The reset bit will be cleared by sensor */
61 		.range_min = KX022A_REG_CNTL2,
62 		.range_max = KX022A_REG_CNTL2,
63 	}, {
64 		.range_min = KX022A_REG_BUF_STATUS_1,
65 		.range_max = KX022A_REG_BUF_READ,
66 	},
67 };
68 
69 static const struct regmap_access_table kx022a_volatile_regs = {
70 	.yes_ranges = &kx022a_volatile_ranges[0],
71 	.n_yes_ranges = ARRAY_SIZE(kx022a_volatile_ranges),
72 };
73 
74 static const struct regmap_range kx022a_precious_ranges[] = {
75 	{
76 		.range_min = KX022A_REG_INT_REL,
77 		.range_max = KX022A_REG_INT_REL,
78 	},
79 };
80 
81 static const struct regmap_access_table kx022a_precious_regs = {
82 	.yes_ranges = &kx022a_precious_ranges[0],
83 	.n_yes_ranges = ARRAY_SIZE(kx022a_precious_ranges),
84 };
85 
86 /*
87  * The HW does not set WHO_AM_I reg as read-only but we don't want to write it
88  * so we still include it in the read-only ranges.
89  */
90 static const struct regmap_range kx022a_read_only_ranges[] = {
91 	{
92 		.range_min = KX022A_REG_XHP_L,
93 		.range_max = KX022A_REG_INT_REL,
94 	}, {
95 		.range_min = KX022A_REG_BUF_STATUS_1,
96 		.range_max = KX022A_REG_BUF_STATUS_2,
97 	}, {
98 		.range_min = KX022A_REG_BUF_READ,
99 		.range_max = KX022A_REG_BUF_READ,
100 	},
101 };
102 
103 static const struct regmap_access_table kx022a_ro_regs = {
104 	.no_ranges = &kx022a_read_only_ranges[0],
105 	.n_no_ranges = ARRAY_SIZE(kx022a_read_only_ranges),
106 };
107 
108 static const struct regmap_range kx022a_write_only_ranges[] = {
109 	{
110 		.range_min = KX022A_REG_BTS_WUF_TH,
111 		.range_max = KX022A_REG_BTS_WUF_TH,
112 	}, {
113 		.range_min = KX022A_REG_MAN_WAKE,
114 		.range_max = KX022A_REG_MAN_WAKE,
115 	}, {
116 		.range_min = KX022A_REG_SELF_TEST,
117 		.range_max = KX022A_REG_SELF_TEST,
118 	}, {
119 		.range_min = KX022A_REG_BUF_CLEAR,
120 		.range_max = KX022A_REG_BUF_CLEAR,
121 	},
122 };
123 
124 static const struct regmap_access_table kx022a_wo_regs = {
125 	.no_ranges = &kx022a_write_only_ranges[0],
126 	.n_no_ranges = ARRAY_SIZE(kx022a_write_only_ranges),
127 };
128 
129 static const struct regmap_range kx022a_noinc_read_ranges[] = {
130 	{
131 		.range_min = KX022A_REG_BUF_READ,
132 		.range_max = KX022A_REG_BUF_READ,
133 	},
134 };
135 
136 static const struct regmap_access_table kx022a_nir_regs = {
137 	.yes_ranges = &kx022a_noinc_read_ranges[0],
138 	.n_yes_ranges = ARRAY_SIZE(kx022a_noinc_read_ranges),
139 };
140 
141 const struct regmap_config kx022a_regmap = {
142 	.reg_bits = 8,
143 	.val_bits = 8,
144 	.volatile_table = &kx022a_volatile_regs,
145 	.rd_table = &kx022a_wo_regs,
146 	.wr_table = &kx022a_ro_regs,
147 	.rd_noinc_table = &kx022a_nir_regs,
148 	.precious_table = &kx022a_precious_regs,
149 	.max_register = KX022A_MAX_REGISTER,
150 	.cache_type = REGCACHE_RBTREE,
151 };
152 EXPORT_SYMBOL_NS_GPL(kx022a_regmap, IIO_KX022A);
153 
154 struct kx022a_data {
155 	struct regmap *regmap;
156 	struct iio_trigger *trig;
157 	struct device *dev;
158 	struct iio_mount_matrix orientation;
159 	int64_t timestamp, old_timestamp;
160 
161 	int irq;
162 	int inc_reg;
163 	int ien_reg;
164 
165 	unsigned int state;
166 	unsigned int odr_ns;
167 
168 	bool trigger_enabled;
169 	/*
170 	 * Prevent toggling the sensor stby/active state (PC1 bit) in the
171 	 * middle of a configuration, or when the fifo is enabled. Also,
172 	 * protect the data stored/retrieved from this structure from
173 	 * concurrent accesses.
174 	 */
175 	struct mutex mutex;
176 	u8 watermark;
177 
178 	/* 3 x 16bit accel data + timestamp */
179 	__le16 buffer[8] __aligned(IIO_DMA_MINALIGN);
180 	struct {
181 		__le16 channels[3];
182 		s64 ts __aligned(8);
183 	} scan;
184 };
185 
186 static const struct iio_mount_matrix *
187 kx022a_get_mount_matrix(const struct iio_dev *idev,
188 			const struct iio_chan_spec *chan)
189 {
190 	struct kx022a_data *data = iio_priv(idev);
191 
192 	return &data->orientation;
193 }
194 
195 enum {
196 	AXIS_X,
197 	AXIS_Y,
198 	AXIS_Z,
199 	AXIS_MAX
200 };
201 
202 static const unsigned long kx022a_scan_masks[] = {
203 	BIT(AXIS_X) | BIT(AXIS_Y) | BIT(AXIS_Z), 0
204 };
205 
206 static const struct iio_chan_spec_ext_info kx022a_ext_info[] = {
207 	IIO_MOUNT_MATRIX(IIO_SHARED_BY_TYPE, kx022a_get_mount_matrix),
208 	{ }
209 };
210 
211 #define KX022A_ACCEL_CHAN(axis, index)				\
212 {								\
213 	.type = IIO_ACCEL,					\
214 	.modified = 1,						\
215 	.channel2 = IIO_MOD_##axis,				\
216 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
217 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |	\
218 				BIT(IIO_CHAN_INFO_SAMP_FREQ),	\
219 	.info_mask_shared_by_type_available =			\
220 				BIT(IIO_CHAN_INFO_SCALE) |	\
221 				BIT(IIO_CHAN_INFO_SAMP_FREQ),	\
222 	.ext_info = kx022a_ext_info,				\
223 	.address = KX022A_REG_##axis##OUT_L,			\
224 	.scan_index = index,					\
225 	.scan_type = {                                          \
226 		.sign = 's',					\
227 		.realbits = 16,					\
228 		.storagebits = 16,				\
229 		.endianness = IIO_LE,				\
230 	},							\
231 }
232 
233 static const struct iio_chan_spec kx022a_channels[] = {
234 	KX022A_ACCEL_CHAN(X, 0),
235 	KX022A_ACCEL_CHAN(Y, 1),
236 	KX022A_ACCEL_CHAN(Z, 2),
237 	IIO_CHAN_SOFT_TIMESTAMP(3),
238 };
239 
240 /*
241  * The sensor HW can support ODR up to 1600 Hz, which is beyond what most of the
242  * Linux CPUs can handle without dropping samples. Also, the low power mode is
243  * not available for higher sample rates. Thus, the driver only supports 200 Hz
244  * and slower ODRs. The slowest is 0.78 Hz.
245  */
246 static const int kx022a_accel_samp_freq_table[][2] = {
247 	{ 0, 780000 },
248 	{ 1, 563000 },
249 	{ 3, 125000 },
250 	{ 6, 250000 },
251 	{ 12, 500000 },
252 	{ 25, 0 },
253 	{ 50, 0 },
254 	{ 100, 0 },
255 	{ 200, 0 },
256 };
257 
258 static const unsigned int kx022a_odrs[] = {
259 	1282051282,
260 	639795266,
261 	320 * MEGA,
262 	160 * MEGA,
263 	80 * MEGA,
264 	40 * MEGA,
265 	20 * MEGA,
266 	10 * MEGA,
267 	5 * MEGA,
268 };
269 
270 /*
271  * range is typically +-2G/4G/8G/16G, distributed over the amount of bits.
272  * The scale table can be calculated using
273  *	(range / 2^bits) * g = (range / 2^bits) * 9.80665 m/s^2
274  *	=> KX022A uses 16 bit (HiRes mode - assume the low 8 bits are zeroed
275  *	in low-power mode(?) )
276  *	=> +/-2G  => 4 / 2^16 * 9,80665 * 10^6 (to scale to micro)
277  *	=> +/-2G  - 598.550415
278  *	   +/-4G  - 1197.10083
279  *	   +/-8G  - 2394.20166
280  *	   +/-16G - 4788.40332
281  */
282 static const int kx022a_scale_table[][2] = {
283 	{ 598, 550415 },
284 	{ 1197, 100830 },
285 	{ 2394, 201660 },
286 	{ 4788, 403320 },
287 };
288 
289 static int kx022a_read_avail(struct iio_dev *indio_dev,
290 			     struct iio_chan_spec const *chan,
291 			     const int **vals, int *type, int *length,
292 			     long mask)
293 {
294 	switch (mask) {
295 	case IIO_CHAN_INFO_SAMP_FREQ:
296 		*vals = (const int *)kx022a_accel_samp_freq_table;
297 		*length = ARRAY_SIZE(kx022a_accel_samp_freq_table) *
298 			  ARRAY_SIZE(kx022a_accel_samp_freq_table[0]);
299 		*type = IIO_VAL_INT_PLUS_MICRO;
300 		return IIO_AVAIL_LIST;
301 	case IIO_CHAN_INFO_SCALE:
302 		*vals = (const int *)kx022a_scale_table;
303 		*length = ARRAY_SIZE(kx022a_scale_table) *
304 			  ARRAY_SIZE(kx022a_scale_table[0]);
305 		*type = IIO_VAL_INT_PLUS_MICRO;
306 		return IIO_AVAIL_LIST;
307 	default:
308 		return -EINVAL;
309 	}
310 }
311 
312 #define KX022A_DEFAULT_PERIOD_NS (20 * NSEC_PER_MSEC)
313 
314 static void kx022a_reg2freq(unsigned int val,  int *val1, int *val2)
315 {
316 	*val1 = kx022a_accel_samp_freq_table[val & KX022A_MASK_ODR][0];
317 	*val2 = kx022a_accel_samp_freq_table[val & KX022A_MASK_ODR][1];
318 }
319 
320 static void kx022a_reg2scale(unsigned int val, unsigned int *val1,
321 			     unsigned int *val2)
322 {
323 	val &= KX022A_MASK_GSEL;
324 	val >>= KX022A_GSEL_SHIFT;
325 
326 	*val1 = kx022a_scale_table[val][0];
327 	*val2 = kx022a_scale_table[val][1];
328 }
329 
330 static int kx022a_turn_on_off_unlocked(struct kx022a_data *data, bool on)
331 {
332 	int ret;
333 
334 	if (on)
335 		ret = regmap_set_bits(data->regmap, KX022A_REG_CNTL,
336 				      KX022A_MASK_PC1);
337 	else
338 		ret = regmap_clear_bits(data->regmap, KX022A_REG_CNTL,
339 					KX022A_MASK_PC1);
340 	if (ret)
341 		dev_err(data->dev, "Turn %s fail %d\n", str_on_off(on), ret);
342 
343 	return ret;
344 
345 }
346 
347 static int kx022a_turn_off_lock(struct kx022a_data *data)
348 {
349 	int ret;
350 
351 	mutex_lock(&data->mutex);
352 	ret = kx022a_turn_on_off_unlocked(data, false);
353 	if (ret)
354 		mutex_unlock(&data->mutex);
355 
356 	return ret;
357 }
358 
359 static int kx022a_turn_on_unlock(struct kx022a_data *data)
360 {
361 	int ret;
362 
363 	ret = kx022a_turn_on_off_unlocked(data, true);
364 	mutex_unlock(&data->mutex);
365 
366 	return ret;
367 }
368 
369 static int kx022a_write_raw(struct iio_dev *idev,
370 			    struct iio_chan_spec const *chan,
371 			    int val, int val2, long mask)
372 {
373 	struct kx022a_data *data = iio_priv(idev);
374 	int ret, n;
375 
376 	/*
377 	 * We should not allow changing scale or frequency when FIFO is running
378 	 * as it will mess the timestamp/scale for samples existing in the
379 	 * buffer. If this turns out to be an issue we can later change logic
380 	 * to internally flush the fifo before reconfiguring so the samples in
381 	 * fifo keep matching the freq/scale settings. (Such setup could cause
382 	 * issues if users trust the watermark to be reached within known
383 	 * time-limit).
384 	 */
385 	ret = iio_device_claim_direct_mode(idev);
386 	if (ret)
387 		return ret;
388 
389 	switch (mask) {
390 	case IIO_CHAN_INFO_SAMP_FREQ:
391 		n = ARRAY_SIZE(kx022a_accel_samp_freq_table);
392 
393 		while (n--)
394 			if (val == kx022a_accel_samp_freq_table[n][0] &&
395 			    val2 == kx022a_accel_samp_freq_table[n][1])
396 				break;
397 		if (n < 0) {
398 			ret = -EINVAL;
399 			goto unlock_out;
400 		}
401 		ret = kx022a_turn_off_lock(data);
402 		if (ret)
403 			break;
404 
405 		ret = regmap_update_bits(data->regmap,
406 					 KX022A_REG_ODCNTL,
407 					 KX022A_MASK_ODR, n);
408 		data->odr_ns = kx022a_odrs[n];
409 		kx022a_turn_on_unlock(data);
410 		break;
411 	case IIO_CHAN_INFO_SCALE:
412 		n = ARRAY_SIZE(kx022a_scale_table);
413 
414 		while (n-- > 0)
415 			if (val == kx022a_scale_table[n][0] &&
416 			    val2 == kx022a_scale_table[n][1])
417 				break;
418 		if (n < 0) {
419 			ret = -EINVAL;
420 			goto unlock_out;
421 		}
422 
423 		ret = kx022a_turn_off_lock(data);
424 		if (ret)
425 			break;
426 
427 		ret = regmap_update_bits(data->regmap, KX022A_REG_CNTL,
428 					 KX022A_MASK_GSEL,
429 					 n << KX022A_GSEL_SHIFT);
430 		kx022a_turn_on_unlock(data);
431 		break;
432 	default:
433 		ret = -EINVAL;
434 		break;
435 	}
436 
437 unlock_out:
438 	iio_device_release_direct_mode(idev);
439 
440 	return ret;
441 }
442 
443 static int kx022a_fifo_set_wmi(struct kx022a_data *data)
444 {
445 	u8 threshold;
446 
447 	threshold = data->watermark;
448 
449 	return regmap_update_bits(data->regmap, KX022A_REG_BUF_CNTL1,
450 				  KX022A_MASK_WM_TH, threshold);
451 }
452 
453 static int kx022a_get_axis(struct kx022a_data *data,
454 			   struct iio_chan_spec const *chan,
455 			   int *val)
456 {
457 	int ret;
458 
459 	ret = regmap_bulk_read(data->regmap, chan->address, &data->buffer[0],
460 			       sizeof(__le16));
461 	if (ret)
462 		return ret;
463 
464 	*val = le16_to_cpu(data->buffer[0]);
465 
466 	return IIO_VAL_INT;
467 }
468 
469 static int kx022a_read_raw(struct iio_dev *idev,
470 			   struct iio_chan_spec const *chan,
471 			   int *val, int *val2, long mask)
472 {
473 	struct kx022a_data *data = iio_priv(idev);
474 	unsigned int regval;
475 	int ret;
476 
477 	switch (mask) {
478 	case IIO_CHAN_INFO_RAW:
479 		ret = iio_device_claim_direct_mode(idev);
480 		if (ret)
481 			return ret;
482 
483 		mutex_lock(&data->mutex);
484 		ret = kx022a_get_axis(data, chan, val);
485 		mutex_unlock(&data->mutex);
486 
487 		iio_device_release_direct_mode(idev);
488 
489 		return ret;
490 
491 	case IIO_CHAN_INFO_SAMP_FREQ:
492 		ret = regmap_read(data->regmap, KX022A_REG_ODCNTL, &regval);
493 		if (ret)
494 			return ret;
495 
496 		if ((regval & KX022A_MASK_ODR) >
497 		    ARRAY_SIZE(kx022a_accel_samp_freq_table)) {
498 			dev_err(data->dev, "Invalid ODR\n");
499 			return -EINVAL;
500 		}
501 
502 		kx022a_reg2freq(regval, val, val2);
503 
504 		return IIO_VAL_INT_PLUS_MICRO;
505 
506 	case IIO_CHAN_INFO_SCALE:
507 		ret = regmap_read(data->regmap, KX022A_REG_CNTL, &regval);
508 		if (ret < 0)
509 			return ret;
510 
511 		kx022a_reg2scale(regval, val, val2);
512 
513 		return IIO_VAL_INT_PLUS_MICRO;
514 	}
515 
516 	return -EINVAL;
517 };
518 
519 static int kx022a_validate_trigger(struct iio_dev *idev,
520 				   struct iio_trigger *trig)
521 {
522 	struct kx022a_data *data = iio_priv(idev);
523 
524 	if (data->trig != trig)
525 		return -EINVAL;
526 
527 	return 0;
528 }
529 
530 static int kx022a_set_watermark(struct iio_dev *idev, unsigned int val)
531 {
532 	struct kx022a_data *data = iio_priv(idev);
533 
534 	if (val > KX022A_FIFO_LENGTH)
535 		val = KX022A_FIFO_LENGTH;
536 
537 	mutex_lock(&data->mutex);
538 	data->watermark = val;
539 	mutex_unlock(&data->mutex);
540 
541 	return 0;
542 }
543 
544 static ssize_t hwfifo_enabled_show(struct device *dev,
545 				   struct device_attribute *attr,
546 				   char *buf)
547 {
548 	struct iio_dev *idev = dev_to_iio_dev(dev);
549 	struct kx022a_data *data = iio_priv(idev);
550 	bool state;
551 
552 	mutex_lock(&data->mutex);
553 	state = data->state;
554 	mutex_unlock(&data->mutex);
555 
556 	return sysfs_emit(buf, "%d\n", state);
557 }
558 
559 static ssize_t hwfifo_watermark_show(struct device *dev,
560 				     struct device_attribute *attr,
561 				     char *buf)
562 {
563 	struct iio_dev *idev = dev_to_iio_dev(dev);
564 	struct kx022a_data *data = iio_priv(idev);
565 	int wm;
566 
567 	mutex_lock(&data->mutex);
568 	wm = data->watermark;
569 	mutex_unlock(&data->mutex);
570 
571 	return sysfs_emit(buf, "%d\n", wm);
572 }
573 
574 static IIO_DEVICE_ATTR_RO(hwfifo_enabled, 0);
575 static IIO_DEVICE_ATTR_RO(hwfifo_watermark, 0);
576 
577 static const struct iio_dev_attr *kx022a_fifo_attributes[] = {
578 	&iio_dev_attr_hwfifo_watermark,
579 	&iio_dev_attr_hwfifo_enabled,
580 	NULL
581 };
582 
583 static int kx022a_drop_fifo_contents(struct kx022a_data *data)
584 {
585 	/*
586 	 * We must clear the old time-stamp to avoid computing the timestamps
587 	 * based on samples acquired when buffer was last enabled.
588 	 *
589 	 * We don't need to protect the timestamp as long as we are only
590 	 * called from fifo-disable where we can guarantee the sensor is not
591 	 * triggering interrupts and where the mutex is locked to prevent the
592 	 * user-space access.
593 	 */
594 	data->timestamp = 0;
595 
596 	return regmap_write(data->regmap, KX022A_REG_BUF_CLEAR, 0x0);
597 }
598 
599 static int __kx022a_fifo_flush(struct iio_dev *idev, unsigned int samples,
600 			       bool irq)
601 {
602 	struct kx022a_data *data = iio_priv(idev);
603 	struct device *dev = regmap_get_device(data->regmap);
604 	__le16 buffer[KX022A_FIFO_LENGTH * 3];
605 	uint64_t sample_period;
606 	int count, fifo_bytes;
607 	bool renable = false;
608 	int64_t tstamp;
609 	int ret, i;
610 
611 	ret = regmap_read(data->regmap, KX022A_REG_BUF_STATUS_1, &fifo_bytes);
612 	if (ret) {
613 		dev_err(dev, "Error reading buffer status\n");
614 		return ret;
615 	}
616 
617 	/* Let's not overflow if we for some reason get bogus value from i2c */
618 	if (fifo_bytes == KX022A_FIFO_FULL_VALUE)
619 		fifo_bytes = KX022A_FIFO_MAX_BYTES;
620 
621 	if (fifo_bytes % KX022A_FIFO_SAMPLES_SIZE_BYTES)
622 		dev_warn(data->dev, "Bad FIFO alignment. Data may be corrupt\n");
623 
624 	count = fifo_bytes / KX022A_FIFO_SAMPLES_SIZE_BYTES;
625 	if (!count)
626 		return 0;
627 
628 	/*
629 	 * If we are being called from IRQ handler we know the stored timestamp
630 	 * is fairly accurate for the last stored sample. Otherwise, if we are
631 	 * called as a result of a read operation from userspace and hence
632 	 * before the watermark interrupt was triggered, take a timestamp
633 	 * now. We can fall anywhere in between two samples so the error in this
634 	 * case is at most one sample period.
635 	 */
636 	if (!irq) {
637 		/*
638 		 * We need to have the IRQ disabled or we risk of messing-up
639 		 * the timestamps. If we are ran from IRQ, then the
640 		 * IRQF_ONESHOT has us covered - but if we are ran by the
641 		 * user-space read we need to disable the IRQ to be on a safe
642 		 * side. We do this usng synchronous disable so that if the
643 		 * IRQ thread is being ran on other CPU we wait for it to be
644 		 * finished.
645 		 */
646 		disable_irq(data->irq);
647 		renable = true;
648 
649 		data->old_timestamp = data->timestamp;
650 		data->timestamp = iio_get_time_ns(idev);
651 	}
652 
653 	/*
654 	 * Approximate timestamps for each of the sample based on the sampling
655 	 * frequency, timestamp for last sample and number of samples.
656 	 *
657 	 * We'd better not use the current bandwidth settings to compute the
658 	 * sample period. The real sample rate varies with the device and
659 	 * small variation adds when we store a large number of samples.
660 	 *
661 	 * To avoid this issue we compute the actual sample period ourselves
662 	 * based on the timestamp delta between the last two flush operations.
663 	 */
664 	if (data->old_timestamp) {
665 		sample_period = data->timestamp - data->old_timestamp;
666 		do_div(sample_period, count);
667 	} else {
668 		sample_period = data->odr_ns;
669 	}
670 	tstamp = data->timestamp - (count - 1) * sample_period;
671 
672 	if (samples && count > samples) {
673 		/*
674 		 * Here we leave some old samples to the buffer. We need to
675 		 * adjust the timestamp to match the first sample in the buffer
676 		 * or we will miscalculate the sample_period at next round.
677 		 */
678 		data->timestamp -= (count - samples) * sample_period;
679 		count = samples;
680 	}
681 
682 	fifo_bytes = count * KX022A_FIFO_SAMPLES_SIZE_BYTES;
683 	ret = regmap_noinc_read(data->regmap, KX022A_REG_BUF_READ,
684 				&buffer[0], fifo_bytes);
685 	if (ret)
686 		goto renable_out;
687 
688 	for (i = 0; i < count; i++) {
689 		__le16 *sam = &buffer[i * 3];
690 		__le16 *chs;
691 		int bit;
692 
693 		chs = &data->scan.channels[0];
694 		for_each_set_bit(bit, idev->active_scan_mask, AXIS_MAX)
695 			chs[bit] = sam[bit];
696 
697 		iio_push_to_buffers_with_timestamp(idev, &data->scan, tstamp);
698 
699 		tstamp += sample_period;
700 	}
701 
702 	ret = count;
703 
704 renable_out:
705 	if (renable)
706 		enable_irq(data->irq);
707 
708 	return ret;
709 }
710 
711 static int kx022a_fifo_flush(struct iio_dev *idev, unsigned int samples)
712 {
713 	struct kx022a_data *data = iio_priv(idev);
714 	int ret;
715 
716 	mutex_lock(&data->mutex);
717 	ret = __kx022a_fifo_flush(idev, samples, false);
718 	mutex_unlock(&data->mutex);
719 
720 	return ret;
721 }
722 
723 static const struct iio_info kx022a_info = {
724 	.read_raw = &kx022a_read_raw,
725 	.write_raw = &kx022a_write_raw,
726 	.read_avail = &kx022a_read_avail,
727 
728 	.validate_trigger	= kx022a_validate_trigger,
729 	.hwfifo_set_watermark	= kx022a_set_watermark,
730 	.hwfifo_flush_to_buffer	= kx022a_fifo_flush,
731 };
732 
733 static int kx022a_set_drdy_irq(struct kx022a_data *data, bool en)
734 {
735 	if (en)
736 		return regmap_set_bits(data->regmap, KX022A_REG_CNTL,
737 				       KX022A_MASK_DRDY);
738 
739 	return regmap_clear_bits(data->regmap, KX022A_REG_CNTL,
740 				 KX022A_MASK_DRDY);
741 }
742 
743 static int kx022a_prepare_irq_pin(struct kx022a_data *data)
744 {
745 	/* Enable IRQ1 pin. Set polarity to active low */
746 	int mask = KX022A_MASK_IEN | KX022A_MASK_IPOL |
747 		   KX022A_MASK_ITYP;
748 	int val = KX022A_MASK_IEN | KX022A_IPOL_LOW |
749 		  KX022A_ITYP_LEVEL;
750 	int ret;
751 
752 	ret = regmap_update_bits(data->regmap, data->inc_reg, mask, val);
753 	if (ret)
754 		return ret;
755 
756 	/* We enable WMI to IRQ pin only at buffer_enable */
757 	mask = KX022A_MASK_INS2_DRDY;
758 
759 	return regmap_set_bits(data->regmap, data->ien_reg, mask);
760 }
761 
762 static int kx022a_fifo_disable(struct kx022a_data *data)
763 {
764 	int ret = 0;
765 
766 	ret = kx022a_turn_off_lock(data);
767 	if (ret)
768 		return ret;
769 
770 	ret = regmap_clear_bits(data->regmap, data->ien_reg, KX022A_MASK_WMI);
771 	if (ret)
772 		goto unlock_out;
773 
774 	ret = regmap_clear_bits(data->regmap, KX022A_REG_BUF_CNTL2,
775 				KX022A_MASK_BUF_EN);
776 	if (ret)
777 		goto unlock_out;
778 
779 	data->state &= ~KX022A_STATE_FIFO;
780 
781 	kx022a_drop_fifo_contents(data);
782 
783 	return kx022a_turn_on_unlock(data);
784 
785 unlock_out:
786 	mutex_unlock(&data->mutex);
787 
788 	return ret;
789 }
790 
791 static int kx022a_buffer_predisable(struct iio_dev *idev)
792 {
793 	struct kx022a_data *data = iio_priv(idev);
794 
795 	if (iio_device_get_current_mode(idev) == INDIO_BUFFER_TRIGGERED)
796 		return 0;
797 
798 	return kx022a_fifo_disable(data);
799 }
800 
801 static int kx022a_fifo_enable(struct kx022a_data *data)
802 {
803 	int ret;
804 
805 	ret = kx022a_turn_off_lock(data);
806 	if (ret)
807 		return ret;
808 
809 	/* Update watermark to HW */
810 	ret = kx022a_fifo_set_wmi(data);
811 	if (ret)
812 		goto unlock_out;
813 
814 	/* Enable buffer */
815 	ret = regmap_set_bits(data->regmap, KX022A_REG_BUF_CNTL2,
816 			      KX022A_MASK_BUF_EN);
817 	if (ret)
818 		goto unlock_out;
819 
820 	data->state |= KX022A_STATE_FIFO;
821 	ret = regmap_set_bits(data->regmap, data->ien_reg,
822 			      KX022A_MASK_WMI);
823 	if (ret)
824 		goto unlock_out;
825 
826 	return kx022a_turn_on_unlock(data);
827 
828 unlock_out:
829 	mutex_unlock(&data->mutex);
830 
831 	return ret;
832 }
833 
834 static int kx022a_buffer_postenable(struct iio_dev *idev)
835 {
836 	struct kx022a_data *data = iio_priv(idev);
837 
838 	/*
839 	 * If we use data-ready trigger, then the IRQ masks should be handled by
840 	 * trigger enable and the hardware buffer is not used but we just update
841 	 * results to the IIO fifo when data-ready triggers.
842 	 */
843 	if (iio_device_get_current_mode(idev) == INDIO_BUFFER_TRIGGERED)
844 		return 0;
845 
846 	return kx022a_fifo_enable(data);
847 }
848 
849 static const struct iio_buffer_setup_ops kx022a_buffer_ops = {
850 	.postenable = kx022a_buffer_postenable,
851 	.predisable = kx022a_buffer_predisable,
852 };
853 
854 static irqreturn_t kx022a_trigger_handler(int irq, void *p)
855 {
856 	struct iio_poll_func *pf = p;
857 	struct iio_dev *idev = pf->indio_dev;
858 	struct kx022a_data *data = iio_priv(idev);
859 	int ret;
860 
861 	ret = regmap_bulk_read(data->regmap, KX022A_REG_XOUT_L, data->buffer,
862 			       KX022A_FIFO_SAMPLES_SIZE_BYTES);
863 	if (ret < 0)
864 		goto err_read;
865 
866 	iio_push_to_buffers_with_timestamp(idev, data->buffer, data->timestamp);
867 err_read:
868 	iio_trigger_notify_done(idev->trig);
869 
870 	return IRQ_HANDLED;
871 }
872 
873 /* Get timestamps and wake the thread if we need to read data */
874 static irqreturn_t kx022a_irq_handler(int irq, void *private)
875 {
876 	struct iio_dev *idev = private;
877 	struct kx022a_data *data = iio_priv(idev);
878 
879 	data->old_timestamp = data->timestamp;
880 	data->timestamp = iio_get_time_ns(idev);
881 
882 	if (data->state & KX022A_STATE_FIFO || data->trigger_enabled)
883 		return IRQ_WAKE_THREAD;
884 
885 	return IRQ_NONE;
886 }
887 
888 /*
889  * WMI and data-ready IRQs are acked when results are read. If we add
890  * TILT/WAKE or other IRQs - then we may need to implement the acking
891  * (which is racy).
892  */
893 static irqreturn_t kx022a_irq_thread_handler(int irq, void *private)
894 {
895 	struct iio_dev *idev = private;
896 	struct kx022a_data *data = iio_priv(idev);
897 	irqreturn_t ret = IRQ_NONE;
898 
899 	mutex_lock(&data->mutex);
900 
901 	if (data->trigger_enabled) {
902 		iio_trigger_poll_nested(data->trig);
903 		ret = IRQ_HANDLED;
904 	}
905 
906 	if (data->state & KX022A_STATE_FIFO) {
907 		int ok;
908 
909 		ok = __kx022a_fifo_flush(idev, KX022A_FIFO_LENGTH, true);
910 		if (ok > 0)
911 			ret = IRQ_HANDLED;
912 	}
913 
914 	mutex_unlock(&data->mutex);
915 
916 	return ret;
917 }
918 
919 static int kx022a_trigger_set_state(struct iio_trigger *trig,
920 				    bool state)
921 {
922 	struct kx022a_data *data = iio_trigger_get_drvdata(trig);
923 	int ret = 0;
924 
925 	mutex_lock(&data->mutex);
926 
927 	if (data->trigger_enabled == state)
928 		goto unlock_out;
929 
930 	if (data->state & KX022A_STATE_FIFO) {
931 		dev_warn(data->dev, "Can't set trigger when FIFO enabled\n");
932 		ret = -EBUSY;
933 		goto unlock_out;
934 	}
935 
936 	ret = kx022a_turn_on_off_unlocked(data, false);
937 	if (ret)
938 		goto unlock_out;
939 
940 	data->trigger_enabled = state;
941 	ret = kx022a_set_drdy_irq(data, state);
942 	if (ret)
943 		goto unlock_out;
944 
945 	ret = kx022a_turn_on_off_unlocked(data, true);
946 
947 unlock_out:
948 	mutex_unlock(&data->mutex);
949 
950 	return ret;
951 }
952 
953 static const struct iio_trigger_ops kx022a_trigger_ops = {
954 	.set_trigger_state = kx022a_trigger_set_state,
955 };
956 
957 static int kx022a_chip_init(struct kx022a_data *data)
958 {
959 	int ret, val;
960 
961 	/* Reset the senor */
962 	ret = regmap_write(data->regmap, KX022A_REG_CNTL2, KX022A_MASK_SRST);
963 	if (ret)
964 		return ret;
965 
966 	/*
967 	 * I've seen I2C read failures if we poll too fast after the sensor
968 	 * reset. Slight delay gives I2C block the time to recover.
969 	 */
970 	msleep(1);
971 
972 	ret = regmap_read_poll_timeout(data->regmap, KX022A_REG_CNTL2, val,
973 				       !(val & KX022A_MASK_SRST),
974 				       KX022A_SOFT_RESET_WAIT_TIME_US,
975 				       KX022A_SOFT_RESET_TOTAL_WAIT_TIME_US);
976 	if (ret) {
977 		dev_err(data->dev, "Sensor reset %s\n",
978 			val & KX022A_MASK_SRST ? "timeout" : "fail#");
979 		return ret;
980 	}
981 
982 	ret = regmap_reinit_cache(data->regmap, &kx022a_regmap);
983 	if (ret) {
984 		dev_err(data->dev, "Failed to reinit reg cache\n");
985 		return ret;
986 	}
987 
988 	/* set data res 16bit */
989 	ret = regmap_set_bits(data->regmap, KX022A_REG_BUF_CNTL2,
990 			      KX022A_MASK_BRES16);
991 	if (ret) {
992 		dev_err(data->dev, "Failed to set data resolution\n");
993 		return ret;
994 	}
995 
996 	return kx022a_prepare_irq_pin(data);
997 }
998 
999 int kx022a_probe_internal(struct device *dev)
1000 {
1001 	static const char * const regulator_names[] = {"io-vdd", "vdd"};
1002 	struct iio_trigger *indio_trig;
1003 	struct fwnode_handle *fwnode;
1004 	struct kx022a_data *data;
1005 	struct regmap *regmap;
1006 	unsigned int chip_id;
1007 	struct iio_dev *idev;
1008 	int ret, irq;
1009 	char *name;
1010 
1011 	regmap = dev_get_regmap(dev, NULL);
1012 	if (!regmap) {
1013 		dev_err(dev, "no regmap\n");
1014 		return -EINVAL;
1015 	}
1016 
1017 	fwnode = dev_fwnode(dev);
1018 	if (!fwnode)
1019 		return -ENODEV;
1020 
1021 	idev = devm_iio_device_alloc(dev, sizeof(*data));
1022 	if (!idev)
1023 		return -ENOMEM;
1024 
1025 	data = iio_priv(idev);
1026 
1027 	/*
1028 	 * VDD is the analog and digital domain voltage supply and
1029 	 * IO_VDD is the digital I/O voltage supply.
1030 	 */
1031 	ret = devm_regulator_bulk_get_enable(dev, ARRAY_SIZE(regulator_names),
1032 					     regulator_names);
1033 	if (ret && ret != -ENODEV)
1034 		return dev_err_probe(dev, ret, "failed to enable regulator\n");
1035 
1036 	ret = regmap_read(regmap, KX022A_REG_WHO, &chip_id);
1037 	if (ret)
1038 		return dev_err_probe(dev, ret, "Failed to access sensor\n");
1039 
1040 	if (chip_id != KX022A_ID) {
1041 		dev_err(dev, "unsupported device 0x%x\n", chip_id);
1042 		return -EINVAL;
1043 	}
1044 
1045 	irq = fwnode_irq_get_byname(fwnode, "INT1");
1046 	if (irq > 0) {
1047 		data->inc_reg = KX022A_REG_INC1;
1048 		data->ien_reg = KX022A_REG_INC4;
1049 	} else {
1050 		irq = fwnode_irq_get_byname(fwnode, "INT2");
1051 		if (irq <= 0)
1052 			return dev_err_probe(dev, irq, "No suitable IRQ\n");
1053 
1054 		data->inc_reg = KX022A_REG_INC5;
1055 		data->ien_reg = KX022A_REG_INC6;
1056 	}
1057 
1058 	data->regmap = regmap;
1059 	data->dev = dev;
1060 	data->irq = irq;
1061 	data->odr_ns = KX022A_DEFAULT_PERIOD_NS;
1062 	mutex_init(&data->mutex);
1063 
1064 	idev->channels = kx022a_channels;
1065 	idev->num_channels = ARRAY_SIZE(kx022a_channels);
1066 	idev->name = "kx022-accel";
1067 	idev->info = &kx022a_info;
1068 	idev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
1069 	idev->available_scan_masks = kx022a_scan_masks;
1070 
1071 	/* Read the mounting matrix, if present */
1072 	ret = iio_read_mount_matrix(dev, &data->orientation);
1073 	if (ret)
1074 		return ret;
1075 
1076 	/* The sensor must be turned off for configuration */
1077 	ret = kx022a_turn_off_lock(data);
1078 	if (ret)
1079 		return ret;
1080 
1081 	ret = kx022a_chip_init(data);
1082 	if (ret) {
1083 		mutex_unlock(&data->mutex);
1084 		return ret;
1085 	}
1086 
1087 	ret = kx022a_turn_on_unlock(data);
1088 	if (ret)
1089 		return ret;
1090 
1091 	ret = devm_iio_triggered_buffer_setup_ext(dev, idev,
1092 						  &iio_pollfunc_store_time,
1093 						  kx022a_trigger_handler,
1094 						  IIO_BUFFER_DIRECTION_IN,
1095 						  &kx022a_buffer_ops,
1096 						  kx022a_fifo_attributes);
1097 
1098 	if (ret)
1099 		return dev_err_probe(data->dev, ret,
1100 				     "iio_triggered_buffer_setup_ext FAIL\n");
1101 	indio_trig = devm_iio_trigger_alloc(dev, "%sdata-rdy-dev%d", idev->name,
1102 					    iio_device_id(idev));
1103 	if (!indio_trig)
1104 		return -ENOMEM;
1105 
1106 	data->trig = indio_trig;
1107 
1108 	indio_trig->ops = &kx022a_trigger_ops;
1109 	iio_trigger_set_drvdata(indio_trig, data);
1110 
1111 	/*
1112 	 * No need to check for NULL. request_threaded_irq() defaults to
1113 	 * dev_name() should the alloc fail.
1114 	 */
1115 	name = devm_kasprintf(data->dev, GFP_KERNEL, "%s-kx022a",
1116 			      dev_name(data->dev));
1117 
1118 	ret = devm_request_threaded_irq(data->dev, irq, kx022a_irq_handler,
1119 					&kx022a_irq_thread_handler,
1120 					IRQF_ONESHOT, name, idev);
1121 	if (ret)
1122 		return dev_err_probe(data->dev, ret, "Could not request IRQ\n");
1123 
1124 
1125 	ret = devm_iio_trigger_register(dev, indio_trig);
1126 	if (ret)
1127 		return dev_err_probe(data->dev, ret,
1128 				     "Trigger registration failed\n");
1129 
1130 	ret = devm_iio_device_register(data->dev, idev);
1131 	if (ret < 0)
1132 		return dev_err_probe(dev, ret,
1133 				     "Unable to register iio device\n");
1134 
1135 	return ret;
1136 }
1137 EXPORT_SYMBOL_NS_GPL(kx022a_probe_internal, IIO_KX022A);
1138 
1139 MODULE_DESCRIPTION("ROHM/Kionix KX022A accelerometer driver");
1140 MODULE_AUTHOR("Matti Vaittinen <matti.vaittinen@fi.rohmeurope.com>");
1141 MODULE_LICENSE("GPL");
1142