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