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 	u8 buffer[RM3100_SCAN_BYTES];
82 	struct iio_trigger *drdy_trig;
83 
84 	/*
85 	 * This lock is for protecting the consistency of series of i2c
86 	 * operations, that is, to make sure a measurement process will
87 	 * not be interrupted by a set frequency operation, which should
88 	 * be taken where a series of i2c operation starts, released where
89 	 * the operation ends.
90 	 */
91 	struct mutex lock;
92 };
93 
94 static const struct regmap_range rm3100_readable_ranges[] = {
95 	regmap_reg_range(RM3100_R_REG_START, RM3100_R_REG_END),
96 };
97 
98 const struct regmap_access_table rm3100_readable_table = {
99 	.yes_ranges = rm3100_readable_ranges,
100 	.n_yes_ranges = ARRAY_SIZE(rm3100_readable_ranges),
101 };
102 EXPORT_SYMBOL_GPL(rm3100_readable_table);
103 
104 static const struct regmap_range rm3100_writable_ranges[] = {
105 	regmap_reg_range(RM3100_W_REG_START, RM3100_W_REG_END),
106 };
107 
108 const struct regmap_access_table rm3100_writable_table = {
109 	.yes_ranges = rm3100_writable_ranges,
110 	.n_yes_ranges = ARRAY_SIZE(rm3100_writable_ranges),
111 };
112 EXPORT_SYMBOL_GPL(rm3100_writable_table);
113 
114 static const struct regmap_range rm3100_volatile_ranges[] = {
115 	regmap_reg_range(RM3100_V_REG_START, RM3100_V_REG_END),
116 };
117 
118 const struct regmap_access_table rm3100_volatile_table = {
119 	.yes_ranges = rm3100_volatile_ranges,
120 	.n_yes_ranges = ARRAY_SIZE(rm3100_volatile_ranges),
121 };
122 EXPORT_SYMBOL_GPL(rm3100_volatile_table);
123 
rm3100_thread_fn(int irq,void * d)124 static irqreturn_t rm3100_thread_fn(int irq, void *d)
125 {
126 	struct iio_dev *indio_dev = d;
127 	struct rm3100_data *data = iio_priv(indio_dev);
128 
129 	/*
130 	 * Write operation to any register or read operation
131 	 * to first byte of results will clear the interrupt.
132 	 */
133 	regmap_write(data->regmap, RM3100_REG_POLL, 0);
134 
135 	return IRQ_HANDLED;
136 }
137 
rm3100_irq_handler(int irq,void * d)138 static irqreturn_t rm3100_irq_handler(int irq, void *d)
139 {
140 	struct iio_dev *indio_dev = d;
141 	struct rm3100_data *data = iio_priv(indio_dev);
142 
143 	switch (indio_dev->currentmode) {
144 	case INDIO_DIRECT_MODE:
145 		complete(&data->measuring_done);
146 		break;
147 	case INDIO_BUFFER_TRIGGERED:
148 		iio_trigger_poll(data->drdy_trig);
149 		break;
150 	default:
151 		dev_err(indio_dev->dev.parent,
152 			"device mode out of control, current mode: %d",
153 			indio_dev->currentmode);
154 	}
155 
156 	return IRQ_WAKE_THREAD;
157 }
158 
rm3100_wait_measurement(struct rm3100_data * data)159 static int rm3100_wait_measurement(struct rm3100_data *data)
160 {
161 	struct regmap *regmap = data->regmap;
162 	unsigned int val;
163 	int tries = 20;
164 	int ret;
165 
166 	/*
167 	 * A read cycle of 400kbits i2c bus is about 20us, plus the time
168 	 * used for scheduling, a read cycle of fast mode of this device
169 	 * can reach 1.7ms, it may be possible for data to arrive just
170 	 * after we check the RM3100_REG_STATUS. In this case, irq_handler is
171 	 * called before measuring_done is reinitialized, it will wait
172 	 * forever for data that has already been ready.
173 	 * Reinitialize measuring_done before looking up makes sure we
174 	 * will always capture interrupt no matter when it happens.
175 	 */
176 	if (data->use_interrupt)
177 		reinit_completion(&data->measuring_done);
178 
179 	ret = regmap_read(regmap, RM3100_REG_STATUS, &val);
180 	if (ret < 0)
181 		return ret;
182 
183 	if ((val & RM3100_STATUS_DRDY) != RM3100_STATUS_DRDY) {
184 		if (data->use_interrupt) {
185 			ret = wait_for_completion_timeout(&data->measuring_done,
186 				msecs_to_jiffies(data->conversion_time));
187 			if (!ret)
188 				return -ETIMEDOUT;
189 		} else {
190 			do {
191 				usleep_range(1000, 5000);
192 
193 				ret = regmap_read(regmap, RM3100_REG_STATUS,
194 						  &val);
195 				if (ret < 0)
196 					return ret;
197 
198 				if (val & RM3100_STATUS_DRDY)
199 					break;
200 			} while (--tries);
201 			if (!tries)
202 				return -ETIMEDOUT;
203 		}
204 	}
205 	return 0;
206 }
207 
rm3100_read_mag(struct rm3100_data * data,int idx,int * val)208 static int rm3100_read_mag(struct rm3100_data *data, int idx, int *val)
209 {
210 	struct regmap *regmap = data->regmap;
211 	u8 buffer[3];
212 	int ret;
213 
214 	mutex_lock(&data->lock);
215 	ret = regmap_write(regmap, RM3100_REG_POLL, BIT(4 + idx));
216 	if (ret < 0)
217 		goto unlock_return;
218 
219 	ret = rm3100_wait_measurement(data);
220 	if (ret < 0)
221 		goto unlock_return;
222 
223 	ret = regmap_bulk_read(regmap, RM3100_REG_MX2 + 3 * idx, buffer, 3);
224 	if (ret < 0)
225 		goto unlock_return;
226 	mutex_unlock(&data->lock);
227 
228 	*val = sign_extend32(get_unaligned_be24(&buffer[0]), 23);
229 
230 	return IIO_VAL_INT;
231 
232 unlock_return:
233 	mutex_unlock(&data->lock);
234 	return ret;
235 }
236 
237 #define RM3100_CHANNEL(axis, idx)					\
238 	{								\
239 		.type = IIO_MAGN,					\
240 		.modified = 1,						\
241 		.channel2 = IIO_MOD_##axis,				\
242 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
243 		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) |	\
244 			BIT(IIO_CHAN_INFO_SAMP_FREQ),			\
245 		.scan_index = idx,					\
246 		.scan_type = {						\
247 			.sign = 's',					\
248 			.realbits = 24,					\
249 			.storagebits = 32,				\
250 			.shift = 8,					\
251 			.endianness = IIO_BE,				\
252 		},							\
253 	}
254 
255 static const struct iio_chan_spec rm3100_channels[] = {
256 	RM3100_CHANNEL(X, 0),
257 	RM3100_CHANNEL(Y, 1),
258 	RM3100_CHANNEL(Z, 2),
259 	IIO_CHAN_SOFT_TIMESTAMP(3),
260 };
261 
262 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL(
263 	"600 300 150 75 37 18 9 4.5 2.3 1.2 0.6 0.3 0.015 0.075"
264 );
265 
266 static struct attribute *rm3100_attributes[] = {
267 	&iio_const_attr_sampling_frequency_available.dev_attr.attr,
268 	NULL,
269 };
270 
271 static const struct attribute_group rm3100_attribute_group = {
272 	.attrs = rm3100_attributes,
273 };
274 
275 #define RM3100_SAMP_NUM			14
276 
277 /*
278  * Frequency : rm3100_samp_rates[][0].rm3100_samp_rates[][1]Hz.
279  * Time between reading: rm3100_sam_rates[][2]ms.
280  * The first one is actually 1.7ms.
281  */
282 static const int rm3100_samp_rates[RM3100_SAMP_NUM][3] = {
283 	{600, 0, 2}, {300, 0, 3}, {150, 0, 7}, {75, 0, 13}, {37, 0, 27},
284 	{18, 0, 55}, {9, 0, 110}, {4, 500000, 220}, {2, 300000, 440},
285 	{1, 200000, 800}, {0, 600000, 1600}, {0, 300000, 3300},
286 	{0, 15000, 6700},  {0, 75000, 13000}
287 };
288 
rm3100_get_samp_freq(struct rm3100_data * data,int * val,int * val2)289 static int rm3100_get_samp_freq(struct rm3100_data *data, int *val, int *val2)
290 {
291 	unsigned int tmp;
292 	int ret;
293 
294 	mutex_lock(&data->lock);
295 	ret = regmap_read(data->regmap, RM3100_REG_TMRC, &tmp);
296 	mutex_unlock(&data->lock);
297 	if (ret < 0)
298 		return ret;
299 	*val = rm3100_samp_rates[tmp - RM3100_TMRC_OFFSET][0];
300 	*val2 = rm3100_samp_rates[tmp - RM3100_TMRC_OFFSET][1];
301 
302 	return IIO_VAL_INT_PLUS_MICRO;
303 }
304 
rm3100_set_cycle_count(struct rm3100_data * data,int val)305 static int rm3100_set_cycle_count(struct rm3100_data *data, int val)
306 {
307 	int ret;
308 	u8 i;
309 
310 	for (i = 0; i < 3; i++) {
311 		ret = regmap_write(data->regmap, RM3100_REG_CC_X + 2 * i, val);
312 		if (ret < 0)
313 			return ret;
314 	}
315 
316 	/*
317 	 * The scale of this sensor depends on the cycle count value, these
318 	 * three values are corresponding to the cycle count value 50, 100,
319 	 * 200. scale = output / gain * 10^4.
320 	 */
321 	switch (val) {
322 	case 50:
323 		data->scale = 500;
324 		break;
325 	case 100:
326 		data->scale = 263;
327 		break;
328 	/*
329 	 * case 200:
330 	 * This function will never be called by users' code, so here we
331 	 * assume that it will never get a wrong parameter.
332 	 */
333 	default:
334 		data->scale = 133;
335 	}
336 
337 	return 0;
338 }
339 
rm3100_set_samp_freq(struct iio_dev * indio_dev,int val,int val2)340 static int rm3100_set_samp_freq(struct iio_dev *indio_dev, int val, int val2)
341 {
342 	struct rm3100_data *data = iio_priv(indio_dev);
343 	struct regmap *regmap = data->regmap;
344 	unsigned int cycle_count;
345 	int ret;
346 	int i;
347 
348 	mutex_lock(&data->lock);
349 	/* All cycle count registers use the same value. */
350 	ret = regmap_read(regmap, RM3100_REG_CC_X, &cycle_count);
351 	if (ret < 0)
352 		goto unlock_return;
353 
354 	for (i = 0; i < RM3100_SAMP_NUM; i++) {
355 		if (val == rm3100_samp_rates[i][0] &&
356 		    val2 == rm3100_samp_rates[i][1])
357 			break;
358 	}
359 	if (i == RM3100_SAMP_NUM) {
360 		ret = -EINVAL;
361 		goto unlock_return;
362 	}
363 
364 	ret = regmap_write(regmap, RM3100_REG_TMRC, i + RM3100_TMRC_OFFSET);
365 	if (ret < 0)
366 		goto unlock_return;
367 
368 	/* Checking if cycle count registers need changing. */
369 	if (val == 600 && cycle_count == 200) {
370 		ret = rm3100_set_cycle_count(data, 100);
371 		if (ret < 0)
372 			goto unlock_return;
373 	} else if (val != 600 && cycle_count == 100) {
374 		ret = rm3100_set_cycle_count(data, 200);
375 		if (ret < 0)
376 			goto unlock_return;
377 	}
378 
379 	if (indio_dev->currentmode == INDIO_BUFFER_TRIGGERED) {
380 		/* Writing TMRC registers requires CMM reset. */
381 		ret = regmap_write(regmap, RM3100_REG_CMM, 0);
382 		if (ret < 0)
383 			goto unlock_return;
384 		ret = regmap_write(data->regmap, RM3100_REG_CMM,
385 			(*indio_dev->active_scan_mask & 0x7) <<
386 			RM3100_CMM_AXIS_SHIFT | RM3100_CMM_START);
387 		if (ret < 0)
388 			goto unlock_return;
389 	}
390 	mutex_unlock(&data->lock);
391 
392 	data->conversion_time = rm3100_samp_rates[i][2] * 2;
393 	return 0;
394 
395 unlock_return:
396 	mutex_unlock(&data->lock);
397 	return ret;
398 }
399 
rm3100_read_raw(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,int * val,int * val2,long mask)400 static int rm3100_read_raw(struct iio_dev *indio_dev,
401 			   const struct iio_chan_spec *chan,
402 			   int *val, int *val2, long mask)
403 {
404 	struct rm3100_data *data = iio_priv(indio_dev);
405 	int ret;
406 
407 	switch (mask) {
408 	case IIO_CHAN_INFO_RAW:
409 		ret = iio_device_claim_direct_mode(indio_dev);
410 		if (ret < 0)
411 			return ret;
412 
413 		ret = rm3100_read_mag(data, chan->scan_index, val);
414 		iio_device_release_direct_mode(indio_dev);
415 
416 		return ret;
417 	case IIO_CHAN_INFO_SCALE:
418 		*val = 0;
419 		*val2 = data->scale;
420 
421 		return IIO_VAL_INT_PLUS_MICRO;
422 	case IIO_CHAN_INFO_SAMP_FREQ:
423 		return rm3100_get_samp_freq(data, val, val2);
424 	default:
425 		return -EINVAL;
426 	}
427 }
428 
rm3100_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)429 static int rm3100_write_raw(struct iio_dev *indio_dev,
430 			    struct iio_chan_spec const *chan,
431 			    int val, int val2, long mask)
432 {
433 	switch (mask) {
434 	case IIO_CHAN_INFO_SAMP_FREQ:
435 		return rm3100_set_samp_freq(indio_dev, val, val2);
436 	default:
437 		return -EINVAL;
438 	}
439 }
440 
441 static const struct iio_info rm3100_info = {
442 	.attrs = &rm3100_attribute_group,
443 	.read_raw = rm3100_read_raw,
444 	.write_raw = rm3100_write_raw,
445 };
446 
rm3100_buffer_preenable(struct iio_dev * indio_dev)447 static int rm3100_buffer_preenable(struct iio_dev *indio_dev)
448 {
449 	struct rm3100_data *data = iio_priv(indio_dev);
450 
451 	/* Starting channels enabled. */
452 	return regmap_write(data->regmap, RM3100_REG_CMM,
453 		(*indio_dev->active_scan_mask & 0x7) << RM3100_CMM_AXIS_SHIFT |
454 		RM3100_CMM_START);
455 }
456 
rm3100_buffer_postdisable(struct iio_dev * indio_dev)457 static int rm3100_buffer_postdisable(struct iio_dev *indio_dev)
458 {
459 	struct rm3100_data *data = iio_priv(indio_dev);
460 
461 	return regmap_write(data->regmap, RM3100_REG_CMM, 0);
462 }
463 
464 static const struct iio_buffer_setup_ops rm3100_buffer_ops = {
465 	.preenable = rm3100_buffer_preenable,
466 	.postdisable = rm3100_buffer_postdisable,
467 };
468 
rm3100_trigger_handler(int irq,void * p)469 static irqreturn_t rm3100_trigger_handler(int irq, void *p)
470 {
471 	struct iio_poll_func *pf = p;
472 	struct iio_dev *indio_dev = pf->indio_dev;
473 	unsigned long scan_mask = *indio_dev->active_scan_mask;
474 	unsigned int mask_len = indio_dev->masklength;
475 	struct rm3100_data *data = iio_priv(indio_dev);
476 	struct regmap *regmap = data->regmap;
477 	int ret, i, bit;
478 
479 	mutex_lock(&data->lock);
480 	switch (scan_mask) {
481 	case BIT(0) | BIT(1) | BIT(2):
482 		ret = regmap_bulk_read(regmap, RM3100_REG_MX2, data->buffer, 9);
483 		mutex_unlock(&data->lock);
484 		if (ret < 0)
485 			goto done;
486 		/* Convert XXXYYYZZZxxx to XXXxYYYxZZZx. x for paddings. */
487 		for (i = 2; i > 0; i--)
488 			memmove(data->buffer + i * 4, data->buffer + i * 3, 3);
489 		break;
490 	case BIT(0) | BIT(1):
491 		ret = regmap_bulk_read(regmap, RM3100_REG_MX2, 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(1) | BIT(2):
498 		ret = regmap_bulk_read(regmap, RM3100_REG_MY2, data->buffer, 6);
499 		mutex_unlock(&data->lock);
500 		if (ret < 0)
501 			goto done;
502 		memmove(data->buffer + 4, data->buffer + 3, 3);
503 		break;
504 	case BIT(0) | BIT(2):
505 		ret = regmap_bulk_read(regmap, RM3100_REG_MX2, data->buffer, 9);
506 		mutex_unlock(&data->lock);
507 		if (ret < 0)
508 			goto done;
509 		memmove(data->buffer + 4, data->buffer + 6, 3);
510 		break;
511 	default:
512 		for_each_set_bit(bit, &scan_mask, mask_len) {
513 			ret = regmap_bulk_read(regmap, RM3100_REG_MX2 + 3 * bit,
514 					       data->buffer, 3);
515 			if (ret < 0) {
516 				mutex_unlock(&data->lock);
517 				goto done;
518 			}
519 		}
520 		mutex_unlock(&data->lock);
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_timestamp(indio_dev, data->buffer,
527 					   pf->timestamp);
528 done:
529 	iio_trigger_notify_done(indio_dev->trig);
530 
531 	return IRQ_HANDLED;
532 }
533 
rm3100_common_probe(struct device * dev,struct regmap * regmap,int irq)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 
541 	indio_dev = devm_iio_device_alloc(dev, sizeof(*data));
542 	if (!indio_dev)
543 		return -ENOMEM;
544 
545 	data = iio_priv(indio_dev);
546 	data->regmap = regmap;
547 
548 	mutex_init(&data->lock);
549 
550 	indio_dev->name = "rm3100";
551 	indio_dev->info = &rm3100_info;
552 	indio_dev->channels = rm3100_channels;
553 	indio_dev->num_channels = ARRAY_SIZE(rm3100_channels);
554 	indio_dev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_TRIGGERED;
555 	indio_dev->currentmode = 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 							 indio_dev->id);
579 		if (!data->drdy_trig)
580 			return -ENOMEM;
581 
582 		data->drdy_trig->dev.parent = dev;
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