1 /*
2  * mag3110.c - Support for Freescale MAG3110 magnetometer sensor
3  *
4  * Copyright (c) 2013 Peter Meerwald <pmeerw@pmeerw.net>
5  *
6  * This file is subject to the terms and conditions of version 2 of
7  * the GNU General Public License.  See the file COPYING in the main
8  * directory of this archive for more details.
9  *
10  * (7-bit I2C slave address 0x0e)
11  *
12  * TODO: irq, user offset, oversampling, continuous mode
13  */
14 
15 #include <linux/module.h>
16 #include <linux/i2c.h>
17 #include <linux/iio/iio.h>
18 #include <linux/iio/sysfs.h>
19 #include <linux/iio/trigger_consumer.h>
20 #include <linux/iio/buffer.h>
21 #include <linux/iio/triggered_buffer.h>
22 #include <linux/delay.h>
23 #include <linux/regulator/consumer.h>
24 
25 #define MAG3110_STATUS 0x00
26 #define MAG3110_OUT_X 0x01 /* MSB first */
27 #define MAG3110_OUT_Y 0x03
28 #define MAG3110_OUT_Z 0x05
29 #define MAG3110_WHO_AM_I 0x07
30 #define MAG3110_SYSMOD 0x08
31 #define MAG3110_OFF_X 0x09 /* MSB first */
32 #define MAG3110_OFF_Y 0x0b
33 #define MAG3110_OFF_Z 0x0d
34 #define MAG3110_DIE_TEMP 0x0f
35 #define MAG3110_CTRL_REG1 0x10
36 #define MAG3110_CTRL_REG2 0x11
37 
38 #define MAG3110_STATUS_DRDY (BIT(2) | BIT(1) | BIT(0))
39 
40 #define MAG3110_CTRL_DR_MASK (BIT(7) | BIT(6) | BIT(5))
41 #define MAG3110_CTRL_DR_SHIFT 5
42 #define MAG3110_CTRL_DR_DEFAULT 0
43 
44 #define MAG3110_SYSMOD_MODE_MASK GENMASK(1, 0)
45 
46 #define MAG3110_CTRL_TM BIT(1) /* trigger single measurement */
47 #define MAG3110_CTRL_AC BIT(0) /* continuous measurements */
48 
49 #define MAG3110_CTRL_AUTO_MRST_EN BIT(7) /* magnetic auto-reset */
50 #define MAG3110_CTRL_RAW BIT(5) /* measurements not user-offset corrected */
51 
52 #define MAG3110_DEVICE_ID 0xc4
53 
54 /* Each client has this additional data */
55 struct mag3110_data {
56 	struct i2c_client *client;
57 	struct mutex lock;
58 	u8 ctrl_reg1;
59 	int sleep_val;
60 	struct regulator *vdd_reg;
61 	struct regulator *vddio_reg;
62 };
63 
64 static int mag3110_request(struct mag3110_data *data)
65 {
66 	int ret, tries = 150;
67 
68 	if ((data->ctrl_reg1 & MAG3110_CTRL_AC) == 0) {
69 		/* trigger measurement */
70 		ret = i2c_smbus_write_byte_data(data->client, MAG3110_CTRL_REG1,
71 			data->ctrl_reg1 | MAG3110_CTRL_TM);
72 		if (ret < 0)
73 			return ret;
74 	}
75 
76 	while (tries-- > 0) {
77 		ret = i2c_smbus_read_byte_data(data->client, MAG3110_STATUS);
78 		if (ret < 0)
79 			return ret;
80 		/* wait for data ready */
81 		if ((ret & MAG3110_STATUS_DRDY) == MAG3110_STATUS_DRDY)
82 			break;
83 
84 		if (data->sleep_val <= 20)
85 			usleep_range(data->sleep_val * 250, data->sleep_val * 500);
86 		else
87 			msleep(20);
88 	}
89 
90 	if (tries < 0) {
91 		dev_err(&data->client->dev, "data not ready\n");
92 		return -EIO;
93 	}
94 
95 	return 0;
96 }
97 
98 static int mag3110_read(struct mag3110_data *data, __be16 buf[3])
99 {
100 	int ret;
101 
102 	mutex_lock(&data->lock);
103 	ret = mag3110_request(data);
104 	if (ret < 0) {
105 		mutex_unlock(&data->lock);
106 		return ret;
107 	}
108 	ret = i2c_smbus_read_i2c_block_data(data->client,
109 		MAG3110_OUT_X, 3 * sizeof(__be16), (u8 *) buf);
110 	mutex_unlock(&data->lock);
111 
112 	return ret;
113 }
114 
115 static ssize_t mag3110_show_int_plus_micros(char *buf,
116 	const int (*vals)[2], int n)
117 {
118 	size_t len = 0;
119 
120 	while (n-- > 0)
121 		len += scnprintf(buf + len, PAGE_SIZE - len,
122 			"%d.%06d ", vals[n][0], vals[n][1]);
123 
124 	/* replace trailing space by newline */
125 	buf[len - 1] = '\n';
126 
127 	return len;
128 }
129 
130 static int mag3110_get_int_plus_micros_index(const int (*vals)[2], int n,
131 					int val, int val2)
132 {
133 	while (n-- > 0)
134 		if (val == vals[n][0] && val2 == vals[n][1])
135 			return n;
136 
137 	return -EINVAL;
138 }
139 
140 static const int mag3110_samp_freq[8][2] = {
141 	{80, 0}, {40, 0}, {20, 0}, {10, 0}, {5, 0}, {2, 500000},
142 	{1, 250000}, {0, 625000}
143 };
144 
145 static ssize_t mag3110_show_samp_freq_avail(struct device *dev,
146 				struct device_attribute *attr, char *buf)
147 {
148 	return mag3110_show_int_plus_micros(buf, mag3110_samp_freq, 8);
149 }
150 
151 static IIO_DEV_ATTR_SAMP_FREQ_AVAIL(mag3110_show_samp_freq_avail);
152 
153 static int mag3110_get_samp_freq_index(struct mag3110_data *data,
154 	int val, int val2)
155 {
156 	return mag3110_get_int_plus_micros_index(mag3110_samp_freq, 8, val,
157 		val2);
158 }
159 
160 static int mag3110_calculate_sleep(struct mag3110_data *data)
161 {
162 	int ret, i = data->ctrl_reg1 >> MAG3110_CTRL_DR_SHIFT;
163 
164 	if (mag3110_samp_freq[i][0] > 0)
165 		ret = 1000 / mag3110_samp_freq[i][0];
166 	else
167 		ret = 1000;
168 
169 	return ret == 0 ? 1 : ret;
170 }
171 
172 static int mag3110_standby(struct mag3110_data *data)
173 {
174 	return i2c_smbus_write_byte_data(data->client, MAG3110_CTRL_REG1,
175 		data->ctrl_reg1 & ~MAG3110_CTRL_AC);
176 }
177 
178 static int mag3110_wait_standby(struct mag3110_data *data)
179 {
180 	int ret, tries = 30;
181 
182 	/*
183 	 * Takes up to 1/ODR to come out of active mode into stby
184 	 * Longest expected period is 12.5seconds.
185 	 * We'll sleep for 500ms between checks
186 	 */
187 	while (tries-- > 0) {
188 		ret = i2c_smbus_read_byte_data(data->client, MAG3110_SYSMOD);
189 		if (ret < 0) {
190 			dev_err(&data->client->dev, "i2c error\n");
191 			return ret;
192 		}
193 		/* wait for standby */
194 		if ((ret & MAG3110_SYSMOD_MODE_MASK) == 0)
195 			break;
196 
197 		msleep_interruptible(500);
198 	}
199 
200 	if (tries < 0) {
201 		dev_err(&data->client->dev, "device not entering standby mode\n");
202 		return -EIO;
203 	}
204 
205 	return 0;
206 }
207 
208 static int mag3110_active(struct mag3110_data *data)
209 {
210 	return i2c_smbus_write_byte_data(data->client, MAG3110_CTRL_REG1,
211 					 data->ctrl_reg1);
212 }
213 
214 /* returns >0 if active, 0 if in standby and <0 on error */
215 static int mag3110_is_active(struct mag3110_data *data)
216 {
217 	int reg;
218 
219 	reg = i2c_smbus_read_byte_data(data->client, MAG3110_CTRL_REG1);
220 	if (reg < 0)
221 		return reg;
222 
223 	return reg & MAG3110_CTRL_AC;
224 }
225 
226 static int mag3110_change_config(struct mag3110_data *data, u8 reg, u8 val)
227 {
228 	int ret;
229 	int is_active;
230 
231 	mutex_lock(&data->lock);
232 
233 	is_active = mag3110_is_active(data);
234 	if (is_active < 0) {
235 		ret = is_active;
236 		goto fail;
237 	}
238 
239 	/* config can only be changed when in standby */
240 	if (is_active > 0) {
241 		ret = mag3110_standby(data);
242 		if (ret < 0)
243 			goto fail;
244 	}
245 
246 	/*
247 	 * After coming out of active we must wait for the part
248 	 * to transition to STBY. This can take up to 1 /ODR to occur
249 	 */
250 	ret = mag3110_wait_standby(data);
251 	if (ret < 0)
252 		goto fail;
253 
254 	ret = i2c_smbus_write_byte_data(data->client, reg, val);
255 	if (ret < 0)
256 		goto fail;
257 
258 	if (is_active > 0) {
259 		ret = mag3110_active(data);
260 		if (ret < 0)
261 			goto fail;
262 	}
263 
264 	ret = 0;
265 fail:
266 	mutex_unlock(&data->lock);
267 
268 	return ret;
269 }
270 
271 static int mag3110_read_raw(struct iio_dev *indio_dev,
272 			    struct iio_chan_spec const *chan,
273 			    int *val, int *val2, long mask)
274 {
275 	struct mag3110_data *data = iio_priv(indio_dev);
276 	__be16 buffer[3];
277 	int i, ret;
278 
279 	switch (mask) {
280 	case IIO_CHAN_INFO_RAW:
281 		ret = iio_device_claim_direct_mode(indio_dev);
282 		if (ret)
283 			return ret;
284 
285 		switch (chan->type) {
286 		case IIO_MAGN: /* in 0.1 uT / LSB */
287 			ret = mag3110_read(data, buffer);
288 			if (ret < 0)
289 				goto release;
290 			*val = sign_extend32(
291 				be16_to_cpu(buffer[chan->scan_index]), 15);
292 			ret = IIO_VAL_INT;
293 			break;
294 		case IIO_TEMP: /* in 1 C / LSB */
295 			mutex_lock(&data->lock);
296 			ret = mag3110_request(data);
297 			if (ret < 0) {
298 				mutex_unlock(&data->lock);
299 				goto release;
300 			}
301 			ret = i2c_smbus_read_byte_data(data->client,
302 				MAG3110_DIE_TEMP);
303 			mutex_unlock(&data->lock);
304 			if (ret < 0)
305 				goto release;
306 			*val = sign_extend32(ret, 7);
307 			ret = IIO_VAL_INT;
308 			break;
309 		default:
310 			ret = -EINVAL;
311 		}
312 release:
313 		iio_device_release_direct_mode(indio_dev);
314 		return ret;
315 
316 	case IIO_CHAN_INFO_SCALE:
317 		switch (chan->type) {
318 		case IIO_MAGN:
319 			*val = 0;
320 			*val2 = 1000;
321 			return IIO_VAL_INT_PLUS_MICRO;
322 		case IIO_TEMP:
323 			*val = 1000;
324 			return IIO_VAL_INT;
325 		default:
326 			return -EINVAL;
327 		}
328 	case IIO_CHAN_INFO_SAMP_FREQ:
329 		i = data->ctrl_reg1 >> MAG3110_CTRL_DR_SHIFT;
330 		*val = mag3110_samp_freq[i][0];
331 		*val2 = mag3110_samp_freq[i][1];
332 		return IIO_VAL_INT_PLUS_MICRO;
333 	case IIO_CHAN_INFO_CALIBBIAS:
334 		ret = i2c_smbus_read_word_swapped(data->client,
335 			MAG3110_OFF_X +	2 * chan->scan_index);
336 		if (ret < 0)
337 			return ret;
338 		*val = sign_extend32(ret >> 1, 14);
339 		return IIO_VAL_INT;
340 	}
341 	return -EINVAL;
342 }
343 
344 static int mag3110_write_raw(struct iio_dev *indio_dev,
345 			     struct iio_chan_spec const *chan,
346 			     int val, int val2, long mask)
347 {
348 	struct mag3110_data *data = iio_priv(indio_dev);
349 	int rate, ret;
350 
351 	ret = iio_device_claim_direct_mode(indio_dev);
352 	if (ret)
353 		return ret;
354 
355 	switch (mask) {
356 	case IIO_CHAN_INFO_SAMP_FREQ:
357 		rate = mag3110_get_samp_freq_index(data, val, val2);
358 		if (rate < 0) {
359 			ret = -EINVAL;
360 			break;
361 		}
362 		data->ctrl_reg1 &= 0xff & ~MAG3110_CTRL_DR_MASK
363 					& ~MAG3110_CTRL_AC;
364 		data->ctrl_reg1 |= rate << MAG3110_CTRL_DR_SHIFT;
365 		data->sleep_val = mag3110_calculate_sleep(data);
366 		if (data->sleep_val < 40)
367 			data->ctrl_reg1 |= MAG3110_CTRL_AC;
368 
369 		ret = mag3110_change_config(data, MAG3110_CTRL_REG1,
370 					    data->ctrl_reg1);
371 		break;
372 	case IIO_CHAN_INFO_CALIBBIAS:
373 		if (val < -10000 || val > 10000) {
374 			ret = -EINVAL;
375 			break;
376 		}
377 		ret = i2c_smbus_write_word_swapped(data->client,
378 			MAG3110_OFF_X + 2 * chan->scan_index, val << 1);
379 		break;
380 	default:
381 		ret = -EINVAL;
382 		break;
383 	}
384 	iio_device_release_direct_mode(indio_dev);
385 	return ret;
386 }
387 
388 static irqreturn_t mag3110_trigger_handler(int irq, void *p)
389 {
390 	struct iio_poll_func *pf = p;
391 	struct iio_dev *indio_dev = pf->indio_dev;
392 	struct mag3110_data *data = iio_priv(indio_dev);
393 	u8 buffer[16]; /* 3 16-bit channels + 1 byte temp + padding + ts */
394 	int ret;
395 
396 	ret = mag3110_read(data, (__be16 *) buffer);
397 	if (ret < 0)
398 		goto done;
399 
400 	if (test_bit(3, indio_dev->active_scan_mask)) {
401 		ret = i2c_smbus_read_byte_data(data->client,
402 			MAG3110_DIE_TEMP);
403 		if (ret < 0)
404 			goto done;
405 		buffer[6] = ret;
406 	}
407 
408 	iio_push_to_buffers_with_timestamp(indio_dev, buffer,
409 		iio_get_time_ns(indio_dev));
410 
411 done:
412 	iio_trigger_notify_done(indio_dev->trig);
413 	return IRQ_HANDLED;
414 }
415 
416 #define MAG3110_CHANNEL(axis, idx) { \
417 	.type = IIO_MAGN, \
418 	.modified = 1, \
419 	.channel2 = IIO_MOD_##axis, \
420 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
421 		BIT(IIO_CHAN_INFO_CALIBBIAS), \
422 	.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
423 		BIT(IIO_CHAN_INFO_SCALE), \
424 	.scan_index = idx, \
425 	.scan_type = { \
426 		.sign = 's', \
427 		.realbits = 16, \
428 		.storagebits = 16, \
429 		.endianness = IIO_BE, \
430 	}, \
431 }
432 
433 static const struct iio_chan_spec mag3110_channels[] = {
434 	MAG3110_CHANNEL(X, 0),
435 	MAG3110_CHANNEL(Y, 1),
436 	MAG3110_CHANNEL(Z, 2),
437 	{
438 		.type = IIO_TEMP,
439 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
440 			BIT(IIO_CHAN_INFO_SCALE),
441 		.scan_index = 3,
442 		.scan_type = {
443 			.sign = 's',
444 			.realbits = 8,
445 			.storagebits = 8,
446 			},
447 	},
448 	IIO_CHAN_SOFT_TIMESTAMP(4),
449 };
450 
451 static struct attribute *mag3110_attributes[] = {
452 	&iio_dev_attr_sampling_frequency_available.dev_attr.attr,
453 	NULL
454 };
455 
456 static const struct attribute_group mag3110_group = {
457 	.attrs = mag3110_attributes,
458 };
459 
460 static const struct iio_info mag3110_info = {
461 	.attrs = &mag3110_group,
462 	.read_raw = &mag3110_read_raw,
463 	.write_raw = &mag3110_write_raw,
464 };
465 
466 static const unsigned long mag3110_scan_masks[] = {0x7, 0xf, 0};
467 
468 static int mag3110_probe(struct i2c_client *client,
469 			 const struct i2c_device_id *id)
470 {
471 	struct mag3110_data *data;
472 	struct iio_dev *indio_dev;
473 	int ret;
474 
475 	indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
476 	if (!indio_dev)
477 		return -ENOMEM;
478 
479 	data = iio_priv(indio_dev);
480 
481 	data->vdd_reg = devm_regulator_get(&client->dev, "vdd");
482 	if (IS_ERR(data->vdd_reg)) {
483 		if (PTR_ERR(data->vdd_reg) == -EPROBE_DEFER)
484 			return -EPROBE_DEFER;
485 
486 		dev_err(&client->dev, "failed to get VDD regulator!\n");
487 		return PTR_ERR(data->vdd_reg);
488 	}
489 
490 	data->vddio_reg = devm_regulator_get(&client->dev, "vddio");
491 	if (IS_ERR(data->vddio_reg)) {
492 		if (PTR_ERR(data->vddio_reg) == -EPROBE_DEFER)
493 			return -EPROBE_DEFER;
494 
495 		dev_err(&client->dev, "failed to get VDDIO regulator!\n");
496 		return PTR_ERR(data->vddio_reg);
497 	}
498 
499 	ret = regulator_enable(data->vdd_reg);
500 	if (ret) {
501 		dev_err(&client->dev, "failed to enable VDD regulator!\n");
502 		return ret;
503 	}
504 
505 	ret = regulator_enable(data->vddio_reg);
506 	if (ret) {
507 		dev_err(&client->dev, "failed to enable VDDIO regulator!\n");
508 		goto disable_regulator_vdd;
509 	}
510 
511 	ret = i2c_smbus_read_byte_data(client, MAG3110_WHO_AM_I);
512 	if (ret < 0)
513 		goto disable_regulators;
514 	if (ret != MAG3110_DEVICE_ID) {
515 		ret = -ENODEV;
516 		goto disable_regulators;
517 	}
518 
519 	data->client = client;
520 	mutex_init(&data->lock);
521 
522 	i2c_set_clientdata(client, indio_dev);
523 	indio_dev->info = &mag3110_info;
524 	indio_dev->name = id->name;
525 	indio_dev->dev.parent = &client->dev;
526 	indio_dev->modes = INDIO_DIRECT_MODE;
527 	indio_dev->channels = mag3110_channels;
528 	indio_dev->num_channels = ARRAY_SIZE(mag3110_channels);
529 	indio_dev->available_scan_masks = mag3110_scan_masks;
530 
531 	data->ctrl_reg1 = MAG3110_CTRL_DR_DEFAULT << MAG3110_CTRL_DR_SHIFT;
532 	data->sleep_val = mag3110_calculate_sleep(data);
533 	if (data->sleep_val < 40)
534 		data->ctrl_reg1 |= MAG3110_CTRL_AC;
535 
536 	ret = mag3110_change_config(data, MAG3110_CTRL_REG1, data->ctrl_reg1);
537 	if (ret < 0)
538 		goto disable_regulators;
539 
540 	ret = i2c_smbus_write_byte_data(client, MAG3110_CTRL_REG2,
541 		MAG3110_CTRL_AUTO_MRST_EN);
542 	if (ret < 0)
543 		goto standby_on_error;
544 
545 	ret = iio_triggered_buffer_setup(indio_dev, NULL,
546 		mag3110_trigger_handler, NULL);
547 	if (ret < 0)
548 		goto standby_on_error;
549 
550 	ret = iio_device_register(indio_dev);
551 	if (ret < 0)
552 		goto buffer_cleanup;
553 	return 0;
554 
555 buffer_cleanup:
556 	iio_triggered_buffer_cleanup(indio_dev);
557 standby_on_error:
558 	mag3110_standby(iio_priv(indio_dev));
559 disable_regulators:
560 	regulator_disable(data->vddio_reg);
561 disable_regulator_vdd:
562 	regulator_disable(data->vdd_reg);
563 
564 	return ret;
565 }
566 
567 static int mag3110_remove(struct i2c_client *client)
568 {
569 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
570 	struct mag3110_data *data = iio_priv(indio_dev);
571 
572 	iio_device_unregister(indio_dev);
573 	iio_triggered_buffer_cleanup(indio_dev);
574 	mag3110_standby(iio_priv(indio_dev));
575 	regulator_disable(data->vddio_reg);
576 	regulator_disable(data->vdd_reg);
577 
578 	return 0;
579 }
580 
581 #ifdef CONFIG_PM_SLEEP
582 static int mag3110_suspend(struct device *dev)
583 {
584 	struct mag3110_data *data = iio_priv(i2c_get_clientdata(
585 		to_i2c_client(dev)));
586 	int ret;
587 
588 	ret = mag3110_standby(iio_priv(i2c_get_clientdata(
589 		to_i2c_client(dev))));
590 	if (ret)
591 		return ret;
592 
593 	ret = regulator_disable(data->vddio_reg);
594 	if (ret) {
595 		dev_err(dev, "failed to disable VDDIO regulator\n");
596 		return ret;
597 	}
598 
599 	ret = regulator_disable(data->vdd_reg);
600 	if (ret) {
601 		dev_err(dev, "failed to disable VDD regulator\n");
602 		return ret;
603 	}
604 
605 	return 0;
606 }
607 
608 static int mag3110_resume(struct device *dev)
609 {
610 	struct mag3110_data *data = iio_priv(i2c_get_clientdata(
611 		to_i2c_client(dev)));
612 	int ret;
613 
614 	ret = regulator_enable(data->vdd_reg);
615 	if (ret) {
616 		dev_err(dev, "failed to enable VDD regulator\n");
617 		return ret;
618 	}
619 
620 	ret = regulator_enable(data->vddio_reg);
621 	if (ret) {
622 		dev_err(dev, "failed to enable VDDIO regulator\n");
623 		regulator_disable(data->vdd_reg);
624 		return ret;
625 	}
626 
627 	return i2c_smbus_write_byte_data(data->client, MAG3110_CTRL_REG1,
628 		data->ctrl_reg1);
629 }
630 
631 static SIMPLE_DEV_PM_OPS(mag3110_pm_ops, mag3110_suspend, mag3110_resume);
632 #define MAG3110_PM_OPS (&mag3110_pm_ops)
633 #else
634 #define MAG3110_PM_OPS NULL
635 #endif
636 
637 static const struct i2c_device_id mag3110_id[] = {
638 	{ "mag3110", 0 },
639 	{ }
640 };
641 MODULE_DEVICE_TABLE(i2c, mag3110_id);
642 
643 static const struct of_device_id mag3110_of_match[] = {
644 	{ .compatible = "fsl,mag3110" },
645 	{ }
646 };
647 MODULE_DEVICE_TABLE(of, mag3110_of_match);
648 
649 static struct i2c_driver mag3110_driver = {
650 	.driver = {
651 		.name	= "mag3110",
652 		.of_match_table = mag3110_of_match,
653 		.pm	= MAG3110_PM_OPS,
654 	},
655 	.probe = mag3110_probe,
656 	.remove = mag3110_remove,
657 	.id_table = mag3110_id,
658 };
659 module_i2c_driver(mag3110_driver);
660 
661 MODULE_AUTHOR("Peter Meerwald <pmeerw@pmeerw.net>");
662 MODULE_DESCRIPTION("Freescale MAG3110 magnetometer driver");
663 MODULE_LICENSE("GPL");
664