xref: /linux/drivers/iio/magnetometer/rm3100-core.c (revision 5a6249110e0f845bfe181ccc0c275995f26469cf)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * PNI RM3100 3-axis geomagnetic sensor driver core.
4  *
5  * Copyright (C) 2018 Song Qiang <songqiang1304521@gmail.com>
6  *
7  * User Manual available at
8  * <https://www.pnicorp.com/download/rm3100-user-manual/>
9  *
10  * TODO: event generation, pm.
11  */
12 
13 #include <linux/delay.h>
14 #include <linux/interrupt.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 
18 #include <linux/iio/buffer.h>
19 #include <linux/iio/iio.h>
20 #include <linux/iio/sysfs.h>
21 #include <linux/iio/trigger.h>
22 #include <linux/iio/triggered_buffer.h>
23 #include <linux/iio/trigger_consumer.h>
24 
25 #include <linux/unaligned.h>
26 
27 #include "rm3100.h"
28 
29 /* Cycle Count Registers. */
30 #define RM3100_REG_CC_X			0x05
31 #define RM3100_REG_CC_Y			0x07
32 #define RM3100_REG_CC_Z			0x09
33 
34 /* Poll Measurement Mode register. */
35 #define RM3100_REG_POLL			0x00
36 #define		RM3100_POLL_X		BIT(4)
37 #define		RM3100_POLL_Y		BIT(5)
38 #define		RM3100_POLL_Z		BIT(6)
39 
40 /* Continuous Measurement Mode register. */
41 #define RM3100_REG_CMM			0x01
42 #define		RM3100_CMM_START	BIT(0)
43 #define		RM3100_CMM_X		BIT(4)
44 #define		RM3100_CMM_Y		BIT(5)
45 #define		RM3100_CMM_Z		BIT(6)
46 
47 /* TiMe Rate Configuration register. */
48 #define RM3100_REG_TMRC			0x0B
49 #define RM3100_TMRC_OFFSET		0x92
50 
51 /* Result Status register. */
52 #define RM3100_REG_STATUS		0x34
53 #define		RM3100_STATUS_DRDY	BIT(7)
54 
55 /* Measurement result registers. */
56 #define RM3100_REG_MX2			0x24
57 #define RM3100_REG_MY2			0x27
58 #define RM3100_REG_MZ2			0x2a
59 
60 #define RM3100_W_REG_START		RM3100_REG_POLL
61 #define RM3100_W_REG_END		RM3100_REG_TMRC
62 #define RM3100_R_REG_START		RM3100_REG_POLL
63 #define RM3100_R_REG_END		RM3100_REG_STATUS
64 #define RM3100_V_REG_START		RM3100_REG_POLL
65 #define RM3100_V_REG_END		RM3100_REG_STATUS
66 
67 /*
68  * This is computed by hand, is the sum of channel storage bits and padding
69  * bits, which is 4+4+4+12=24 in here.
70  */
71 #define RM3100_SCAN_BYTES		24
72 
73 #define RM3100_CMM_AXIS_SHIFT		4
74 
75 struct rm3100_data {
76 	struct regmap *regmap;
77 	struct completion measuring_done;
78 	bool use_interrupt;
79 	int conversion_time;
80 	int scale;
81 	/* Ensure naturally aligned timestamp */
82 	u8 buffer[RM3100_SCAN_BYTES] __aligned(8);
83 	struct iio_trigger *drdy_trig;
84 
85 	/*
86 	 * This lock is for protecting the consistency of series of i2c
87 	 * operations, that is, to make sure a measurement process will
88 	 * not be interrupted by a set frequency operation, which should
89 	 * be taken where a series of i2c operation starts, released where
90 	 * the operation ends.
91 	 */
92 	struct mutex lock;
93 };
94 
95 static const struct regmap_range rm3100_readable_ranges[] = {
96 	regmap_reg_range(RM3100_R_REG_START, RM3100_R_REG_END),
97 };
98 
99 const struct regmap_access_table rm3100_readable_table = {
100 	.yes_ranges = rm3100_readable_ranges,
101 	.n_yes_ranges = ARRAY_SIZE(rm3100_readable_ranges),
102 };
103 EXPORT_SYMBOL_NS_GPL(rm3100_readable_table, "IIO_RM3100");
104 
105 static const struct regmap_range rm3100_writable_ranges[] = {
106 	regmap_reg_range(RM3100_W_REG_START, RM3100_W_REG_END),
107 };
108 
109 const struct regmap_access_table rm3100_writable_table = {
110 	.yes_ranges = rm3100_writable_ranges,
111 	.n_yes_ranges = ARRAY_SIZE(rm3100_writable_ranges),
112 };
113 EXPORT_SYMBOL_NS_GPL(rm3100_writable_table, "IIO_RM3100");
114 
115 static const struct regmap_range rm3100_volatile_ranges[] = {
116 	regmap_reg_range(RM3100_V_REG_START, RM3100_V_REG_END),
117 };
118 
119 const struct regmap_access_table rm3100_volatile_table = {
120 	.yes_ranges = rm3100_volatile_ranges,
121 	.n_yes_ranges = ARRAY_SIZE(rm3100_volatile_ranges),
122 };
123 EXPORT_SYMBOL_NS_GPL(rm3100_volatile_table, "IIO_RM3100");
124 
125 static irqreturn_t rm3100_thread_fn(int irq, void *d)
126 {
127 	struct iio_dev *indio_dev = d;
128 	struct rm3100_data *data = iio_priv(indio_dev);
129 
130 	/*
131 	 * Write operation to any register or read operation
132 	 * to first byte of results will clear the interrupt.
133 	 */
134 	regmap_write(data->regmap, RM3100_REG_POLL, 0);
135 
136 	return IRQ_HANDLED;
137 }
138 
139 static irqreturn_t rm3100_irq_handler(int irq, void *d)
140 {
141 	struct iio_dev *indio_dev = d;
142 	struct rm3100_data *data = iio_priv(indio_dev);
143 
144 	if (!iio_buffer_enabled(indio_dev))
145 		complete(&data->measuring_done);
146 	else
147 		iio_trigger_poll(data->drdy_trig);
148 
149 	return IRQ_WAKE_THREAD;
150 }
151 
152 static int rm3100_wait_measurement(struct rm3100_data *data)
153 {
154 	struct regmap *regmap = data->regmap;
155 	unsigned int val;
156 	int tries = 20;
157 	int ret;
158 
159 	/*
160 	 * A read cycle of 400kbits i2c bus is about 20us, plus the time
161 	 * used for scheduling, a read cycle of fast mode of this device
162 	 * can reach 1.7ms, it may be possible for data to arrive just
163 	 * after we check the RM3100_REG_STATUS. In this case, irq_handler is
164 	 * called before measuring_done is reinitialized, it will wait
165 	 * forever for data that has already been ready.
166 	 * Reinitialize measuring_done before looking up makes sure we
167 	 * will always capture interrupt no matter when it happens.
168 	 */
169 	if (data->use_interrupt)
170 		reinit_completion(&data->measuring_done);
171 
172 	ret = regmap_read(regmap, RM3100_REG_STATUS, &val);
173 	if (ret < 0)
174 		return ret;
175 
176 	if ((val & RM3100_STATUS_DRDY) != RM3100_STATUS_DRDY) {
177 		if (data->use_interrupt) {
178 			ret = wait_for_completion_timeout(&data->measuring_done,
179 				msecs_to_jiffies(data->conversion_time));
180 			if (!ret)
181 				return -ETIMEDOUT;
182 		} else {
183 			do {
184 				usleep_range(1000, 5000);
185 
186 				ret = regmap_read(regmap, RM3100_REG_STATUS,
187 						  &val);
188 				if (ret < 0)
189 					return ret;
190 
191 				if (val & RM3100_STATUS_DRDY)
192 					break;
193 			} while (--tries);
194 			if (!tries)
195 				return -ETIMEDOUT;
196 		}
197 	}
198 	return 0;
199 }
200 
201 static int rm3100_read_mag(struct rm3100_data *data, int idx, int *val)
202 {
203 	struct regmap *regmap = data->regmap;
204 	u8 buffer[3];
205 	int ret;
206 
207 	guard(mutex)(&data->lock);
208 
209 	ret = regmap_write(regmap, RM3100_REG_POLL, BIT(4 + idx));
210 	if (ret < 0)
211 		return ret;
212 
213 	ret = rm3100_wait_measurement(data);
214 	if (ret < 0)
215 		return ret;
216 
217 	ret = regmap_bulk_read(regmap, RM3100_REG_MX2 + 3 * idx, buffer, 3);
218 	if (ret < 0)
219 		return ret;
220 
221 	*val = sign_extend32(get_unaligned_be24(&buffer[0]), 23);
222 
223 	return IIO_VAL_INT;
224 }
225 
226 #define RM3100_CHANNEL(axis, idx)					\
227 	{								\
228 		.type = IIO_MAGN,					\
229 		.modified = 1,						\
230 		.channel2 = IIO_MOD_##axis,				\
231 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
232 		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |	\
233 			BIT(IIO_CHAN_INFO_SAMP_FREQ),			\
234 		.scan_index = idx,					\
235 		.scan_type = {						\
236 			.sign = 's',					\
237 			.realbits = 24,					\
238 			.storagebits = 32,				\
239 			.shift = 8,					\
240 			.endianness = IIO_BE,				\
241 		},							\
242 	}
243 
244 static const struct iio_chan_spec rm3100_channels[] = {
245 	RM3100_CHANNEL(X, 0),
246 	RM3100_CHANNEL(Y, 1),
247 	RM3100_CHANNEL(Z, 2),
248 	IIO_CHAN_SOFT_TIMESTAMP(3),
249 };
250 
251 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL(
252 	"600 300 150 75 37 18 9 4.5 2.3 1.2 0.6 0.3 0.015 0.075"
253 );
254 
255 static struct attribute *rm3100_attributes[] = {
256 	&iio_const_attr_sampling_frequency_available.dev_attr.attr,
257 	NULL,
258 };
259 
260 static const struct attribute_group rm3100_attribute_group = {
261 	.attrs = rm3100_attributes,
262 };
263 
264 #define RM3100_SAMP_NUM			14
265 
266 /*
267  * Frequency : rm3100_samp_rates[][0].rm3100_samp_rates[][1]Hz.
268  * Time between reading: rm3100_sam_rates[][2]ms.
269  * The first one is actually 1.7ms.
270  */
271 static const int rm3100_samp_rates[RM3100_SAMP_NUM][3] = {
272 	{600, 0, 2}, {300, 0, 3}, {150, 0, 7}, {75, 0, 13}, {37, 0, 27},
273 	{18, 0, 55}, {9, 0, 110}, {4, 500000, 220}, {2, 300000, 440},
274 	{1, 200000, 800}, {0, 600000, 1600}, {0, 300000, 3300},
275 	{0, 15000, 6700},  {0, 75000, 13000}
276 };
277 
278 static int rm3100_get_samp_freq(struct rm3100_data *data, int *val, int *val2)
279 {
280 	unsigned int tmp;
281 	int ret;
282 
283 	guard(mutex)(&data->lock);
284 
285 	ret = regmap_read(data->regmap, RM3100_REG_TMRC, &tmp);
286 	if (ret < 0)
287 		return ret;
288 
289 	*val = rm3100_samp_rates[tmp - RM3100_TMRC_OFFSET][0];
290 	*val2 = rm3100_samp_rates[tmp - RM3100_TMRC_OFFSET][1];
291 
292 	return IIO_VAL_INT_PLUS_MICRO;
293 }
294 
295 static int rm3100_set_cycle_count(struct rm3100_data *data, int val)
296 {
297 	int ret;
298 	u8 i;
299 
300 	for (i = 0; i < 3; i++) {
301 		ret = regmap_write(data->regmap, RM3100_REG_CC_X + 2 * i, val);
302 		if (ret < 0)
303 			return ret;
304 	}
305 
306 	/*
307 	 * The scale of this sensor depends on the cycle count value, these
308 	 * three values are corresponding to the cycle count value 50, 100,
309 	 * 200. scale = output / gain * 10^4.
310 	 */
311 	switch (val) {
312 	case 50:
313 		data->scale = 500;
314 		break;
315 	case 100:
316 		data->scale = 263;
317 		break;
318 	/*
319 	 * case 200:
320 	 * This function will never be called by users' code, so here we
321 	 * assume that it will never get a wrong parameter.
322 	 */
323 	default:
324 		data->scale = 133;
325 	}
326 
327 	return 0;
328 }
329 
330 static int rm3100_set_samp_freq(struct iio_dev *indio_dev, int val, int val2)
331 {
332 	struct rm3100_data *data = iio_priv(indio_dev);
333 	struct regmap *regmap = data->regmap;
334 	unsigned int cycle_count;
335 	int ret;
336 	int i;
337 
338 	guard(mutex)(&data->lock);
339 
340 	/* All cycle count registers use the same value. */
341 	ret = regmap_read(regmap, RM3100_REG_CC_X, &cycle_count);
342 	if (ret < 0)
343 		return ret;
344 
345 	for (i = 0; i < RM3100_SAMP_NUM; i++) {
346 		if (val == rm3100_samp_rates[i][0] &&
347 		    val2 == rm3100_samp_rates[i][1])
348 			break;
349 	}
350 	if (i == RM3100_SAMP_NUM)
351 		return -EINVAL;
352 
353 	ret = regmap_write(regmap, RM3100_REG_TMRC, i + RM3100_TMRC_OFFSET);
354 	if (ret < 0)
355 		return ret;
356 
357 	/* Checking if cycle count registers need changing. */
358 	if (val == 600 && cycle_count == 200) {
359 		ret = rm3100_set_cycle_count(data, 100);
360 		if (ret < 0)
361 			return ret;
362 	} else if (val != 600 && cycle_count == 100) {
363 		ret = rm3100_set_cycle_count(data, 200);
364 		if (ret < 0)
365 			return ret;
366 	}
367 
368 	if (iio_buffer_enabled(indio_dev)) {
369 		/* Writing TMRC registers requires CMM reset. */
370 		ret = regmap_write(regmap, RM3100_REG_CMM, 0);
371 		if (ret < 0)
372 			return ret;
373 		ret = regmap_write(data->regmap, RM3100_REG_CMM,
374 			(*indio_dev->active_scan_mask & 0x7) <<
375 			RM3100_CMM_AXIS_SHIFT | RM3100_CMM_START);
376 		if (ret < 0)
377 			return ret;
378 	}
379 
380 	data->conversion_time = rm3100_samp_rates[i][2] * 2;
381 	return 0;
382 }
383 
384 static int rm3100_read_raw(struct iio_dev *indio_dev,
385 			   const struct iio_chan_spec *chan,
386 			   int *val, int *val2, long mask)
387 {
388 	struct rm3100_data *data = iio_priv(indio_dev);
389 	int ret;
390 
391 	switch (mask) {
392 	case IIO_CHAN_INFO_RAW:
393 		if (!iio_device_claim_direct(indio_dev))
394 			return -EBUSY;
395 
396 		ret = rm3100_read_mag(data, chan->scan_index, val);
397 		iio_device_release_direct(indio_dev);
398 
399 		return ret;
400 	case IIO_CHAN_INFO_SCALE:
401 		*val = 0;
402 		*val2 = data->scale;
403 
404 		return IIO_VAL_INT_PLUS_MICRO;
405 	case IIO_CHAN_INFO_SAMP_FREQ:
406 		return rm3100_get_samp_freq(data, val, val2);
407 	default:
408 		return -EINVAL;
409 	}
410 }
411 
412 static int rm3100_write_raw(struct iio_dev *indio_dev,
413 			    struct iio_chan_spec const *chan,
414 			    int val, int val2, long mask)
415 {
416 	switch (mask) {
417 	case IIO_CHAN_INFO_SAMP_FREQ:
418 		return rm3100_set_samp_freq(indio_dev, val, val2);
419 	default:
420 		return -EINVAL;
421 	}
422 }
423 
424 static const struct iio_info rm3100_info = {
425 	.attrs = &rm3100_attribute_group,
426 	.read_raw = rm3100_read_raw,
427 	.write_raw = rm3100_write_raw,
428 };
429 
430 static int rm3100_buffer_preenable(struct iio_dev *indio_dev)
431 {
432 	struct rm3100_data *data = iio_priv(indio_dev);
433 
434 	/* Starting channels enabled. */
435 	return regmap_write(data->regmap, RM3100_REG_CMM,
436 		(*indio_dev->active_scan_mask & 0x7) << RM3100_CMM_AXIS_SHIFT |
437 		RM3100_CMM_START);
438 }
439 
440 static int rm3100_buffer_postdisable(struct iio_dev *indio_dev)
441 {
442 	struct rm3100_data *data = iio_priv(indio_dev);
443 
444 	return regmap_write(data->regmap, RM3100_REG_CMM, 0);
445 }
446 
447 static const struct iio_buffer_setup_ops rm3100_buffer_ops = {
448 	.preenable = rm3100_buffer_preenable,
449 	.postdisable = rm3100_buffer_postdisable,
450 };
451 
452 /**
453  * rm3100_regmap_bulk_read_locked() - Wrapper around regmap_bulk_read() with a mutex
454  *
455  * @data: Data structure containing regmap and mutex
456  * @reg: First register to be read from, passed to regmap_bulk_read()
457  * @val: Pointer to store read value, in native register size for device,
458  * passed to regmap_bulk_read()
459  * @val_count: Number of registers to read, passed to regmap_bulk_read()
460  *
461  * Intended for use only in rm3100_trigger_handler().
462  *
463  * Return:
464  * A value of zero on success, a negative errno in error cases.
465  */
466 static int rm3100_regmap_bulk_read_locked(struct rm3100_data *data, unsigned int reg,
467 					  void *val, size_t val_count)
468 {
469 	guard(mutex)(&data->lock);
470 	return regmap_bulk_read(data->regmap, reg, val, val_count);
471 }
472 
473 static irqreturn_t rm3100_trigger_handler(int irq, void *p)
474 {
475 	struct iio_poll_func *pf = p;
476 	struct iio_dev *indio_dev = pf->indio_dev;
477 	unsigned long scan_mask = *indio_dev->active_scan_mask;
478 	unsigned int mask_len = iio_get_masklength(indio_dev);
479 	struct rm3100_data *data = iio_priv(indio_dev);
480 	int ret, i, bit;
481 
482 	switch (scan_mask) {
483 	case BIT(0) | BIT(1) | BIT(2):
484 		ret = rm3100_regmap_bulk_read_locked(data, RM3100_REG_MX2,
485 						     data->buffer, 9);
486 		if (ret < 0)
487 			goto done;
488 		/* Convert XXXYYYZZZxxx to XXXxYYYxZZZx. x for paddings. */
489 		for (i = 2; i > 0; i--)
490 			memmove(data->buffer + i * 4, data->buffer + i * 3, 3);
491 		break;
492 	case BIT(0) | BIT(1):
493 		ret = rm3100_regmap_bulk_read_locked(data, RM3100_REG_MX2,
494 						     data->buffer, 6);
495 		if (ret < 0)
496 			goto done;
497 		memmove(data->buffer + 4, data->buffer + 3, 3);
498 		break;
499 	case BIT(1) | BIT(2):
500 		ret = rm3100_regmap_bulk_read_locked(data, RM3100_REG_MY2,
501 						     data->buffer, 6);
502 		if (ret < 0)
503 			goto done;
504 		memmove(data->buffer + 4, data->buffer + 3, 3);
505 		break;
506 	case BIT(0) | BIT(2):
507 		ret = rm3100_regmap_bulk_read_locked(data, RM3100_REG_MX2,
508 						     data->buffer, 9);
509 		if (ret < 0)
510 			goto done;
511 		memmove(data->buffer + 4, data->buffer + 6, 3);
512 		break;
513 	default:
514 		for_each_set_bit(bit, &scan_mask, mask_len) {
515 			ret = rm3100_regmap_bulk_read_locked(data,
516 							     RM3100_REG_MX2 + 3 * bit,
517 							     data->buffer, 3);
518 			if (ret < 0)
519 				goto done;
520 		}
521 	}
522 	/*
523 	 * Always using the same buffer so that we wouldn't need to set the
524 	 * paddings to 0 in case of leaking any data.
525 	 */
526 	iio_push_to_buffers_with_ts(indio_dev, data->buffer, sizeof(data->buffer),
527 				    pf->timestamp);
528 done:
529 	iio_trigger_notify_done(indio_dev->trig);
530 
531 	return IRQ_HANDLED;
532 }
533 
534 int rm3100_common_probe(struct device *dev, struct regmap *regmap, int irq)
535 {
536 	struct iio_dev *indio_dev;
537 	struct rm3100_data *data;
538 	unsigned int tmp;
539 	int ret;
540 	int samp_rate_index;
541 
542 	indio_dev = devm_iio_device_alloc(dev, sizeof(*data));
543 	if (!indio_dev)
544 		return -ENOMEM;
545 
546 	data = iio_priv(indio_dev);
547 	data->regmap = regmap;
548 
549 	mutex_init(&data->lock);
550 
551 	indio_dev->name = "rm3100";
552 	indio_dev->info = &rm3100_info;
553 	indio_dev->channels = rm3100_channels;
554 	indio_dev->num_channels = ARRAY_SIZE(rm3100_channels);
555 	indio_dev->modes = INDIO_DIRECT_MODE;
556 
557 	if (!irq)
558 		data->use_interrupt = false;
559 	else {
560 		data->use_interrupt = true;
561 
562 		init_completion(&data->measuring_done);
563 		ret = devm_request_threaded_irq(dev,
564 						irq,
565 						rm3100_irq_handler,
566 						rm3100_thread_fn,
567 						IRQF_TRIGGER_HIGH |
568 						IRQF_ONESHOT,
569 						indio_dev->name,
570 						indio_dev);
571 		if (ret < 0) {
572 			dev_err(dev, "request irq line failed.\n");
573 			return ret;
574 		}
575 
576 		data->drdy_trig = devm_iio_trigger_alloc(dev, "%s-drdy%d",
577 							 indio_dev->name,
578 							 iio_device_id(indio_dev));
579 		if (!data->drdy_trig)
580 			return -ENOMEM;
581 
582 		ret = devm_iio_trigger_register(dev, data->drdy_trig);
583 		if (ret < 0)
584 			return ret;
585 	}
586 
587 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
588 					      &iio_pollfunc_store_time,
589 					      rm3100_trigger_handler,
590 					      &rm3100_buffer_ops);
591 	if (ret < 0)
592 		return ret;
593 
594 	ret = regmap_read(regmap, RM3100_REG_TMRC, &tmp);
595 	if (ret < 0)
596 		return ret;
597 
598 	samp_rate_index = tmp - RM3100_TMRC_OFFSET;
599 	if (samp_rate_index < 0 || samp_rate_index >=  RM3100_SAMP_NUM) {
600 		dev_err(dev, "The value read from RM3100_REG_TMRC is invalid!\n");
601 		return -EINVAL;
602 	}
603 	/* Initializing max wait time, which is double conversion time. */
604 	data->conversion_time = rm3100_samp_rates[samp_rate_index][2] * 2;
605 
606 	/* Cycle count values may not be what we want. */
607 	if ((tmp - RM3100_TMRC_OFFSET) == 0)
608 		rm3100_set_cycle_count(data, 100);
609 	else
610 		rm3100_set_cycle_count(data, 200);
611 
612 	return devm_iio_device_register(dev, indio_dev);
613 }
614 EXPORT_SYMBOL_NS_GPL(rm3100_common_probe, "IIO_RM3100");
615 
616 MODULE_AUTHOR("Song Qiang <songqiang1304521@gmail.com>");
617 MODULE_DESCRIPTION("PNI RM3100 3-axis magnetometer i2c driver");
618 MODULE_LICENSE("GPL v2");
619