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 <asm/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 	mutex_lock(&data->lock);
208 	ret = regmap_write(regmap, RM3100_REG_POLL, BIT(4 + idx));
209 	if (ret < 0)
210 		goto unlock_return;
211 
212 	ret = rm3100_wait_measurement(data);
213 	if (ret < 0)
214 		goto unlock_return;
215 
216 	ret = regmap_bulk_read(regmap, RM3100_REG_MX2 + 3 * idx, buffer, 3);
217 	if (ret < 0)
218 		goto unlock_return;
219 	mutex_unlock(&data->lock);
220 
221 	*val = sign_extend32(get_unaligned_be24(&buffer[0]), 23);
222 
223 	return IIO_VAL_INT;
224 
225 unlock_return:
226 	mutex_unlock(&data->lock);
227 	return ret;
228 }
229 
230 #define RM3100_CHANNEL(axis, idx)					\
231 	{								\
232 		.type = IIO_MAGN,					\
233 		.modified = 1,						\
234 		.channel2 = IIO_MOD_##axis,				\
235 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
236 		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |	\
237 			BIT(IIO_CHAN_INFO_SAMP_FREQ),			\
238 		.scan_index = idx,					\
239 		.scan_type = {						\
240 			.sign = 's',					\
241 			.realbits = 24,					\
242 			.storagebits = 32,				\
243 			.shift = 8,					\
244 			.endianness = IIO_BE,				\
245 		},							\
246 	}
247 
248 static const struct iio_chan_spec rm3100_channels[] = {
249 	RM3100_CHANNEL(X, 0),
250 	RM3100_CHANNEL(Y, 1),
251 	RM3100_CHANNEL(Z, 2),
252 	IIO_CHAN_SOFT_TIMESTAMP(3),
253 };
254 
255 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL(
256 	"600 300 150 75 37 18 9 4.5 2.3 1.2 0.6 0.3 0.015 0.075"
257 );
258 
259 static struct attribute *rm3100_attributes[] = {
260 	&iio_const_attr_sampling_frequency_available.dev_attr.attr,
261 	NULL,
262 };
263 
264 static const struct attribute_group rm3100_attribute_group = {
265 	.attrs = rm3100_attributes,
266 };
267 
268 #define RM3100_SAMP_NUM			14
269 
270 /*
271  * Frequency : rm3100_samp_rates[][0].rm3100_samp_rates[][1]Hz.
272  * Time between reading: rm3100_sam_rates[][2]ms.
273  * The first one is actually 1.7ms.
274  */
275 static const int rm3100_samp_rates[RM3100_SAMP_NUM][3] = {
276 	{600, 0, 2}, {300, 0, 3}, {150, 0, 7}, {75, 0, 13}, {37, 0, 27},
277 	{18, 0, 55}, {9, 0, 110}, {4, 500000, 220}, {2, 300000, 440},
278 	{1, 200000, 800}, {0, 600000, 1600}, {0, 300000, 3300},
279 	{0, 15000, 6700},  {0, 75000, 13000}
280 };
281 
282 static int rm3100_get_samp_freq(struct rm3100_data *data, int *val, int *val2)
283 {
284 	unsigned int tmp;
285 	int ret;
286 
287 	mutex_lock(&data->lock);
288 	ret = regmap_read(data->regmap, RM3100_REG_TMRC, &tmp);
289 	mutex_unlock(&data->lock);
290 	if (ret < 0)
291 		return ret;
292 	*val = rm3100_samp_rates[tmp - RM3100_TMRC_OFFSET][0];
293 	*val2 = rm3100_samp_rates[tmp - RM3100_TMRC_OFFSET][1];
294 
295 	return IIO_VAL_INT_PLUS_MICRO;
296 }
297 
298 static int rm3100_set_cycle_count(struct rm3100_data *data, int val)
299 {
300 	int ret;
301 	u8 i;
302 
303 	for (i = 0; i < 3; i++) {
304 		ret = regmap_write(data->regmap, RM3100_REG_CC_X + 2 * i, val);
305 		if (ret < 0)
306 			return ret;
307 	}
308 
309 	/*
310 	 * The scale of this sensor depends on the cycle count value, these
311 	 * three values are corresponding to the cycle count value 50, 100,
312 	 * 200. scale = output / gain * 10^4.
313 	 */
314 	switch (val) {
315 	case 50:
316 		data->scale = 500;
317 		break;
318 	case 100:
319 		data->scale = 263;
320 		break;
321 	/*
322 	 * case 200:
323 	 * This function will never be called by users' code, so here we
324 	 * assume that it will never get a wrong parameter.
325 	 */
326 	default:
327 		data->scale = 133;
328 	}
329 
330 	return 0;
331 }
332 
333 static int rm3100_set_samp_freq(struct iio_dev *indio_dev, int val, int val2)
334 {
335 	struct rm3100_data *data = iio_priv(indio_dev);
336 	struct regmap *regmap = data->regmap;
337 	unsigned int cycle_count;
338 	int ret;
339 	int i;
340 
341 	mutex_lock(&data->lock);
342 	/* All cycle count registers use the same value. */
343 	ret = regmap_read(regmap, RM3100_REG_CC_X, &cycle_count);
344 	if (ret < 0)
345 		goto unlock_return;
346 
347 	for (i = 0; i < RM3100_SAMP_NUM; i++) {
348 		if (val == rm3100_samp_rates[i][0] &&
349 		    val2 == rm3100_samp_rates[i][1])
350 			break;
351 	}
352 	if (i == RM3100_SAMP_NUM) {
353 		ret = -EINVAL;
354 		goto unlock_return;
355 	}
356 
357 	ret = regmap_write(regmap, RM3100_REG_TMRC, i + RM3100_TMRC_OFFSET);
358 	if (ret < 0)
359 		goto unlock_return;
360 
361 	/* Checking if cycle count registers need changing. */
362 	if (val == 600 && cycle_count == 200) {
363 		ret = rm3100_set_cycle_count(data, 100);
364 		if (ret < 0)
365 			goto unlock_return;
366 	} else if (val != 600 && cycle_count == 100) {
367 		ret = rm3100_set_cycle_count(data, 200);
368 		if (ret < 0)
369 			goto unlock_return;
370 	}
371 
372 	if (iio_buffer_enabled(indio_dev)) {
373 		/* Writing TMRC registers requires CMM reset. */
374 		ret = regmap_write(regmap, RM3100_REG_CMM, 0);
375 		if (ret < 0)
376 			goto unlock_return;
377 		ret = regmap_write(data->regmap, RM3100_REG_CMM,
378 			(*indio_dev->active_scan_mask & 0x7) <<
379 			RM3100_CMM_AXIS_SHIFT | RM3100_CMM_START);
380 		if (ret < 0)
381 			goto unlock_return;
382 	}
383 	mutex_unlock(&data->lock);
384 
385 	data->conversion_time = rm3100_samp_rates[i][2] * 2;
386 	return 0;
387 
388 unlock_return:
389 	mutex_unlock(&data->lock);
390 	return ret;
391 }
392 
393 static int rm3100_read_raw(struct iio_dev *indio_dev,
394 			   const struct iio_chan_spec *chan,
395 			   int *val, int *val2, long mask)
396 {
397 	struct rm3100_data *data = iio_priv(indio_dev);
398 	int ret;
399 
400 	switch (mask) {
401 	case IIO_CHAN_INFO_RAW:
402 		ret = iio_device_claim_direct_mode(indio_dev);
403 		if (ret < 0)
404 			return ret;
405 
406 		ret = rm3100_read_mag(data, chan->scan_index, val);
407 		iio_device_release_direct_mode(indio_dev);
408 
409 		return ret;
410 	case IIO_CHAN_INFO_SCALE:
411 		*val = 0;
412 		*val2 = data->scale;
413 
414 		return IIO_VAL_INT_PLUS_MICRO;
415 	case IIO_CHAN_INFO_SAMP_FREQ:
416 		return rm3100_get_samp_freq(data, val, val2);
417 	default:
418 		return -EINVAL;
419 	}
420 }
421 
422 static int rm3100_write_raw(struct iio_dev *indio_dev,
423 			    struct iio_chan_spec const *chan,
424 			    int val, int val2, long mask)
425 {
426 	switch (mask) {
427 	case IIO_CHAN_INFO_SAMP_FREQ:
428 		return rm3100_set_samp_freq(indio_dev, val, val2);
429 	default:
430 		return -EINVAL;
431 	}
432 }
433 
434 static const struct iio_info rm3100_info = {
435 	.attrs = &rm3100_attribute_group,
436 	.read_raw = rm3100_read_raw,
437 	.write_raw = rm3100_write_raw,
438 };
439 
440 static int rm3100_buffer_preenable(struct iio_dev *indio_dev)
441 {
442 	struct rm3100_data *data = iio_priv(indio_dev);
443 
444 	/* Starting channels enabled. */
445 	return regmap_write(data->regmap, RM3100_REG_CMM,
446 		(*indio_dev->active_scan_mask & 0x7) << RM3100_CMM_AXIS_SHIFT |
447 		RM3100_CMM_START);
448 }
449 
450 static int rm3100_buffer_postdisable(struct iio_dev *indio_dev)
451 {
452 	struct rm3100_data *data = iio_priv(indio_dev);
453 
454 	return regmap_write(data->regmap, RM3100_REG_CMM, 0);
455 }
456 
457 static const struct iio_buffer_setup_ops rm3100_buffer_ops = {
458 	.preenable = rm3100_buffer_preenable,
459 	.postdisable = rm3100_buffer_postdisable,
460 };
461 
462 static irqreturn_t rm3100_trigger_handler(int irq, void *p)
463 {
464 	struct iio_poll_func *pf = p;
465 	struct iio_dev *indio_dev = pf->indio_dev;
466 	unsigned long scan_mask = *indio_dev->active_scan_mask;
467 	unsigned int mask_len = indio_dev->masklength;
468 	struct rm3100_data *data = iio_priv(indio_dev);
469 	struct regmap *regmap = data->regmap;
470 	int ret, i, bit;
471 
472 	mutex_lock(&data->lock);
473 	switch (scan_mask) {
474 	case BIT(0) | BIT(1) | BIT(2):
475 		ret = regmap_bulk_read(regmap, RM3100_REG_MX2, data->buffer, 9);
476 		mutex_unlock(&data->lock);
477 		if (ret < 0)
478 			goto done;
479 		/* Convert XXXYYYZZZxxx to XXXxYYYxZZZx. x for paddings. */
480 		for (i = 2; i > 0; i--)
481 			memmove(data->buffer + i * 4, data->buffer + i * 3, 3);
482 		break;
483 	case BIT(0) | BIT(1):
484 		ret = regmap_bulk_read(regmap, RM3100_REG_MX2, data->buffer, 6);
485 		mutex_unlock(&data->lock);
486 		if (ret < 0)
487 			goto done;
488 		memmove(data->buffer + 4, data->buffer + 3, 3);
489 		break;
490 	case BIT(1) | BIT(2):
491 		ret = regmap_bulk_read(regmap, RM3100_REG_MY2, data->buffer, 6);
492 		mutex_unlock(&data->lock);
493 		if (ret < 0)
494 			goto done;
495 		memmove(data->buffer + 4, data->buffer + 3, 3);
496 		break;
497 	case BIT(0) | BIT(2):
498 		ret = regmap_bulk_read(regmap, RM3100_REG_MX2, data->buffer, 9);
499 		mutex_unlock(&data->lock);
500 		if (ret < 0)
501 			goto done;
502 		memmove(data->buffer + 4, data->buffer + 6, 3);
503 		break;
504 	default:
505 		for_each_set_bit(bit, &scan_mask, mask_len) {
506 			ret = regmap_bulk_read(regmap, RM3100_REG_MX2 + 3 * bit,
507 					       data->buffer, 3);
508 			if (ret < 0) {
509 				mutex_unlock(&data->lock);
510 				goto done;
511 			}
512 		}
513 		mutex_unlock(&data->lock);
514 	}
515 	/*
516 	 * Always using the same buffer so that we wouldn't need to set the
517 	 * paddings to 0 in case of leaking any data.
518 	 */
519 	iio_push_to_buffers_with_timestamp(indio_dev, data->buffer,
520 					   pf->timestamp);
521 done:
522 	iio_trigger_notify_done(indio_dev->trig);
523 
524 	return IRQ_HANDLED;
525 }
526 
527 int rm3100_common_probe(struct device *dev, struct regmap *regmap, int irq)
528 {
529 	struct iio_dev *indio_dev;
530 	struct rm3100_data *data;
531 	unsigned int tmp;
532 	int ret;
533 
534 	indio_dev = devm_iio_device_alloc(dev, sizeof(*data));
535 	if (!indio_dev)
536 		return -ENOMEM;
537 
538 	data = iio_priv(indio_dev);
539 	data->regmap = regmap;
540 
541 	mutex_init(&data->lock);
542 
543 	indio_dev->name = "rm3100";
544 	indio_dev->info = &rm3100_info;
545 	indio_dev->channels = rm3100_channels;
546 	indio_dev->num_channels = ARRAY_SIZE(rm3100_channels);
547 	indio_dev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_TRIGGERED;
548 
549 	if (!irq)
550 		data->use_interrupt = false;
551 	else {
552 		data->use_interrupt = true;
553 
554 		init_completion(&data->measuring_done);
555 		ret = devm_request_threaded_irq(dev,
556 						irq,
557 						rm3100_irq_handler,
558 						rm3100_thread_fn,
559 						IRQF_TRIGGER_HIGH |
560 						IRQF_ONESHOT,
561 						indio_dev->name,
562 						indio_dev);
563 		if (ret < 0) {
564 			dev_err(dev, "request irq line failed.\n");
565 			return ret;
566 		}
567 
568 		data->drdy_trig = devm_iio_trigger_alloc(dev, "%s-drdy%d",
569 							 indio_dev->name,
570 							 iio_device_id(indio_dev));
571 		if (!data->drdy_trig)
572 			return -ENOMEM;
573 
574 		ret = devm_iio_trigger_register(dev, data->drdy_trig);
575 		if (ret < 0)
576 			return ret;
577 	}
578 
579 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
580 					      &iio_pollfunc_store_time,
581 					      rm3100_trigger_handler,
582 					      &rm3100_buffer_ops);
583 	if (ret < 0)
584 		return ret;
585 
586 	ret = regmap_read(regmap, RM3100_REG_TMRC, &tmp);
587 	if (ret < 0)
588 		return ret;
589 	/* Initializing max wait time, which is double conversion time. */
590 	data->conversion_time = rm3100_samp_rates[tmp - RM3100_TMRC_OFFSET][2]
591 				* 2;
592 
593 	/* Cycle count values may not be what we want. */
594 	if ((tmp - RM3100_TMRC_OFFSET) == 0)
595 		rm3100_set_cycle_count(data, 100);
596 	else
597 		rm3100_set_cycle_count(data, 200);
598 
599 	return devm_iio_device_register(dev, indio_dev);
600 }
601 EXPORT_SYMBOL_NS_GPL(rm3100_common_probe, IIO_RM3100);
602 
603 MODULE_AUTHOR("Song Qiang <songqiang1304521@gmail.com>");
604 MODULE_DESCRIPTION("PNI RM3100 3-axis magnetometer i2c driver");
605 MODULE_LICENSE("GPL v2");
606