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