xref: /linux/drivers/iio/magnetometer/ak8974.c (revision 156010ed9c2ac1e9df6c11b1f688cf8a6e0152e6)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Driver for the Asahi Kasei EMD Corporation AK8974
4  * and Aichi Steel AMI305 magnetometer chips.
5  * Based on a patch from Samu Onkalo and the AK8975 IIO driver.
6  *
7  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
8  * Copyright (c) 2010 NVIDIA Corporation.
9  * Copyright (C) 2016 Linaro Ltd.
10  *
11  * Author: Samu Onkalo <samu.p.onkalo@nokia.com>
12  * Author: Linus Walleij <linus.walleij@linaro.org>
13  */
14 #include <linux/module.h>
15 #include <linux/mod_devicetable.h>
16 #include <linux/kernel.h>
17 #include <linux/i2c.h>
18 #include <linux/interrupt.h>
19 #include <linux/irq.h> /* For irq_get_irq_data() */
20 #include <linux/completion.h>
21 #include <linux/err.h>
22 #include <linux/mutex.h>
23 #include <linux/delay.h>
24 #include <linux/bitops.h>
25 #include <linux/random.h>
26 #include <linux/regmap.h>
27 #include <linux/regulator/consumer.h>
28 #include <linux/pm_runtime.h>
29 
30 #include <linux/iio/iio.h>
31 #include <linux/iio/sysfs.h>
32 #include <linux/iio/buffer.h>
33 #include <linux/iio/trigger.h>
34 #include <linux/iio/trigger_consumer.h>
35 #include <linux/iio/triggered_buffer.h>
36 
37 /*
38  * 16-bit registers are little-endian. LSB is at the address defined below
39  * and MSB is at the next higher address.
40  */
41 
42 /* These registers are common for AK8974 and AMI30x */
43 #define AK8974_SELFTEST		0x0C
44 #define AK8974_SELFTEST_IDLE	0x55
45 #define AK8974_SELFTEST_OK	0xAA
46 
47 #define AK8974_INFO		0x0D
48 
49 #define AK8974_WHOAMI		0x0F
50 #define AK8974_WHOAMI_VALUE_AMI306 0x46
51 #define AK8974_WHOAMI_VALUE_AMI305 0x47
52 #define AK8974_WHOAMI_VALUE_AK8974 0x48
53 #define AK8974_WHOAMI_VALUE_HSCDTD008A 0x49
54 
55 #define AK8974_DATA_X		0x10
56 #define AK8974_DATA_Y		0x12
57 #define AK8974_DATA_Z		0x14
58 #define AK8974_INT_SRC		0x16
59 #define AK8974_STATUS		0x18
60 #define AK8974_INT_CLEAR	0x1A
61 #define AK8974_CTRL1		0x1B
62 #define AK8974_CTRL2		0x1C
63 #define AK8974_CTRL3		0x1D
64 #define AK8974_INT_CTRL		0x1E
65 #define AK8974_INT_THRES	0x26  /* Absolute any axis value threshold */
66 #define AK8974_PRESET		0x30
67 
68 /* AK8974-specific offsets */
69 #define AK8974_OFFSET_X		0x20
70 #define AK8974_OFFSET_Y		0x22
71 #define AK8974_OFFSET_Z		0x24
72 /* AMI305-specific offsets */
73 #define AMI305_OFFSET_X		0x6C
74 #define AMI305_OFFSET_Y		0x72
75 #define AMI305_OFFSET_Z		0x78
76 
77 /* Different temperature registers */
78 #define AK8974_TEMP		0x31
79 #define AMI305_TEMP		0x60
80 
81 /* AMI306-specific control register */
82 #define AMI306_CTRL4		0x5C
83 
84 /* AMI306 factory calibration data */
85 
86 /* fine axis sensitivity */
87 #define AMI306_FINEOUTPUT_X	0x90
88 #define AMI306_FINEOUTPUT_Y	0x92
89 #define AMI306_FINEOUTPUT_Z	0x94
90 
91 /* axis sensitivity */
92 #define AMI306_SENS_X		0x96
93 #define AMI306_SENS_Y		0x98
94 #define AMI306_SENS_Z		0x9A
95 
96 /* axis cross-interference */
97 #define AMI306_GAIN_PARA_XZ	0x9C
98 #define AMI306_GAIN_PARA_XY	0x9D
99 #define AMI306_GAIN_PARA_YZ	0x9E
100 #define AMI306_GAIN_PARA_YX	0x9F
101 #define AMI306_GAIN_PARA_ZY	0xA0
102 #define AMI306_GAIN_PARA_ZX	0xA1
103 
104 /* offset at ZERO magnetic field */
105 #define AMI306_OFFZERO_X	0xF8
106 #define AMI306_OFFZERO_Y	0xFA
107 #define AMI306_OFFZERO_Z	0xFC
108 
109 
110 #define AK8974_INT_X_HIGH	BIT(7) /* Axis over +threshold  */
111 #define AK8974_INT_Y_HIGH	BIT(6)
112 #define AK8974_INT_Z_HIGH	BIT(5)
113 #define AK8974_INT_X_LOW	BIT(4) /* Axis below -threshold	*/
114 #define AK8974_INT_Y_LOW	BIT(3)
115 #define AK8974_INT_Z_LOW	BIT(2)
116 #define AK8974_INT_RANGE	BIT(1) /* Range overflow (any axis) */
117 
118 #define AK8974_STATUS_DRDY	BIT(6) /* Data ready */
119 #define AK8974_STATUS_OVERRUN	BIT(5) /* Data overrun */
120 #define AK8974_STATUS_INT	BIT(4) /* Interrupt occurred */
121 
122 #define AK8974_CTRL1_POWER	BIT(7) /* 0 = standby; 1 = active */
123 #define AK8974_CTRL1_RATE	BIT(4) /* 0 = 10 Hz; 1 = 20 Hz	 */
124 #define AK8974_CTRL1_FORCE_EN	BIT(1) /* 0 = normal; 1 = force	 */
125 #define AK8974_CTRL1_MODE2	BIT(0) /* 0 */
126 
127 #define AK8974_CTRL2_INT_EN	BIT(4)  /* 1 = enable interrupts	      */
128 #define AK8974_CTRL2_DRDY_EN	BIT(3)  /* 1 = enable data ready signal */
129 #define AK8974_CTRL2_DRDY_POL	BIT(2)  /* 1 = data ready active high   */
130 #define AK8974_CTRL2_RESDEF	(AK8974_CTRL2_DRDY_POL)
131 
132 #define AK8974_CTRL3_RESET	BIT(7) /* Software reset		  */
133 #define AK8974_CTRL3_FORCE	BIT(6) /* Start forced measurement */
134 #define AK8974_CTRL3_SELFTEST	BIT(4) /* Set selftest register	  */
135 #define AK8974_CTRL3_RESDEF	0x00
136 
137 #define AK8974_INT_CTRL_XEN	BIT(7) /* Enable interrupt for this axis */
138 #define AK8974_INT_CTRL_YEN	BIT(6)
139 #define AK8974_INT_CTRL_ZEN	BIT(5)
140 #define AK8974_INT_CTRL_XYZEN	(BIT(7)|BIT(6)|BIT(5))
141 #define AK8974_INT_CTRL_POL	BIT(3) /* 0 = active low; 1 = active high */
142 #define AK8974_INT_CTRL_PULSE	BIT(1) /* 0 = latched; 1 = pulse (50 usec) */
143 #define AK8974_INT_CTRL_RESDEF	(AK8974_INT_CTRL_XYZEN | AK8974_INT_CTRL_POL)
144 
145 /* HSCDTD008A-specific control register */
146 #define HSCDTD008A_CTRL4	0x1E
147 #define HSCDTD008A_CTRL4_MMD	BIT(7)	/* must be set to 1 */
148 #define HSCDTD008A_CTRL4_RANGE	BIT(4)	/* 0 = 14-bit output; 1 = 15-bit output */
149 #define HSCDTD008A_CTRL4_RESDEF	(HSCDTD008A_CTRL4_MMD | HSCDTD008A_CTRL4_RANGE)
150 
151 /* The AMI305 has elaborate FW version and serial number registers */
152 #define AMI305_VER		0xE8
153 #define AMI305_SN		0xEA
154 
155 #define AK8974_MAX_RANGE	2048
156 
157 #define AK8974_POWERON_DELAY	50
158 #define AK8974_ACTIVATE_DELAY	1
159 #define AK8974_SELFTEST_DELAY	1
160 /*
161  * Set the autosuspend to two orders of magnitude larger than the poweron
162  * delay to make sane reasonable power tradeoff savings (5 seconds in
163  * this case).
164  */
165 #define AK8974_AUTOSUSPEND_DELAY 5000
166 
167 #define AK8974_MEASTIME		3
168 
169 #define AK8974_PWR_ON		1
170 #define AK8974_PWR_OFF		0
171 
172 /**
173  * struct ak8974 - state container for the AK8974 driver
174  * @i2c: parent I2C client
175  * @orientation: mounting matrix, flipped axis etc
176  * @map: regmap to access the AK8974 registers over I2C
177  * @regs: the avdd and dvdd power regulators
178  * @name: the name of the part
179  * @variant: the whoami ID value (for selecting code paths)
180  * @lock: locks the magnetometer for exclusive use during a measurement
181  * @drdy_irq: uses the DRDY IRQ line
182  * @drdy_complete: completion for DRDY
183  * @drdy_active_low: the DRDY IRQ is active low
184  * @scan: timestamps
185  */
186 struct ak8974 {
187 	struct i2c_client *i2c;
188 	struct iio_mount_matrix orientation;
189 	struct regmap *map;
190 	struct regulator_bulk_data regs[2];
191 	const char *name;
192 	u8 variant;
193 	struct mutex lock;
194 	bool drdy_irq;
195 	struct completion drdy_complete;
196 	bool drdy_active_low;
197 	/* Ensure timestamp is naturally aligned */
198 	struct {
199 		__le16 channels[3];
200 		s64 ts __aligned(8);
201 	} scan;
202 };
203 
204 static const char ak8974_reg_avdd[] = "avdd";
205 static const char ak8974_reg_dvdd[] = "dvdd";
206 
207 static int ak8974_get_u16_val(struct ak8974 *ak8974, u8 reg, u16 *val)
208 {
209 	int ret;
210 	__le16 bulk;
211 
212 	ret = regmap_bulk_read(ak8974->map, reg, &bulk, 2);
213 	if (ret)
214 		return ret;
215 	*val = le16_to_cpu(bulk);
216 
217 	return 0;
218 }
219 
220 static int ak8974_set_u16_val(struct ak8974 *ak8974, u8 reg, u16 val)
221 {
222 	__le16 bulk = cpu_to_le16(val);
223 
224 	return regmap_bulk_write(ak8974->map, reg, &bulk, 2);
225 }
226 
227 static int ak8974_set_power(struct ak8974 *ak8974, bool mode)
228 {
229 	int ret;
230 	u8 val;
231 
232 	val = mode ? AK8974_CTRL1_POWER : 0;
233 	val |= AK8974_CTRL1_FORCE_EN;
234 	ret = regmap_write(ak8974->map, AK8974_CTRL1, val);
235 	if (ret < 0)
236 		return ret;
237 
238 	if (mode)
239 		msleep(AK8974_ACTIVATE_DELAY);
240 
241 	return 0;
242 }
243 
244 static int ak8974_reset(struct ak8974 *ak8974)
245 {
246 	int ret;
247 
248 	/* Power on to get register access. Sets CTRL1 reg to reset state */
249 	ret = ak8974_set_power(ak8974, AK8974_PWR_ON);
250 	if (ret)
251 		return ret;
252 	ret = regmap_write(ak8974->map, AK8974_CTRL2, AK8974_CTRL2_RESDEF);
253 	if (ret)
254 		return ret;
255 	ret = regmap_write(ak8974->map, AK8974_CTRL3, AK8974_CTRL3_RESDEF);
256 	if (ret)
257 		return ret;
258 	if (ak8974->variant != AK8974_WHOAMI_VALUE_HSCDTD008A) {
259 		ret = regmap_write(ak8974->map, AK8974_INT_CTRL,
260 				   AK8974_INT_CTRL_RESDEF);
261 		if (ret)
262 			return ret;
263 	} else {
264 		ret = regmap_write(ak8974->map, HSCDTD008A_CTRL4,
265 				   HSCDTD008A_CTRL4_RESDEF);
266 		if (ret)
267 			return ret;
268 	}
269 
270 	/* After reset, power off is default state */
271 	return ak8974_set_power(ak8974, AK8974_PWR_OFF);
272 }
273 
274 static int ak8974_configure(struct ak8974 *ak8974)
275 {
276 	int ret;
277 
278 	ret = regmap_write(ak8974->map, AK8974_CTRL2, AK8974_CTRL2_DRDY_EN |
279 			   AK8974_CTRL2_INT_EN);
280 	if (ret)
281 		return ret;
282 	ret = regmap_write(ak8974->map, AK8974_CTRL3, 0);
283 	if (ret)
284 		return ret;
285 	if (ak8974->variant == AK8974_WHOAMI_VALUE_AMI306) {
286 		/* magic from datasheet: set high-speed measurement mode */
287 		ret = ak8974_set_u16_val(ak8974, AMI306_CTRL4, 0xA07E);
288 		if (ret)
289 			return ret;
290 	}
291 	if (ak8974->variant == AK8974_WHOAMI_VALUE_HSCDTD008A)
292 		return 0;
293 	ret = regmap_write(ak8974->map, AK8974_INT_CTRL, AK8974_INT_CTRL_POL);
294 	if (ret)
295 		return ret;
296 
297 	return regmap_write(ak8974->map, AK8974_PRESET, 0);
298 }
299 
300 static int ak8974_trigmeas(struct ak8974 *ak8974)
301 {
302 	unsigned int clear;
303 	u8 mask;
304 	u8 val;
305 	int ret;
306 
307 	/* Clear any previous measurement overflow status */
308 	ret = regmap_read(ak8974->map, AK8974_INT_CLEAR, &clear);
309 	if (ret)
310 		return ret;
311 
312 	/* If we have a DRDY IRQ line, use it */
313 	if (ak8974->drdy_irq) {
314 		mask = AK8974_CTRL2_INT_EN |
315 			AK8974_CTRL2_DRDY_EN |
316 			AK8974_CTRL2_DRDY_POL;
317 		val = AK8974_CTRL2_DRDY_EN;
318 
319 		if (!ak8974->drdy_active_low)
320 			val |= AK8974_CTRL2_DRDY_POL;
321 
322 		init_completion(&ak8974->drdy_complete);
323 		ret = regmap_update_bits(ak8974->map, AK8974_CTRL2,
324 					 mask, val);
325 		if (ret)
326 			return ret;
327 	}
328 
329 	/* Force a measurement */
330 	return regmap_update_bits(ak8974->map,
331 				  AK8974_CTRL3,
332 				  AK8974_CTRL3_FORCE,
333 				  AK8974_CTRL3_FORCE);
334 }
335 
336 static int ak8974_await_drdy(struct ak8974 *ak8974)
337 {
338 	int timeout = 2;
339 	unsigned int val;
340 	int ret;
341 
342 	if (ak8974->drdy_irq) {
343 		ret = wait_for_completion_timeout(&ak8974->drdy_complete,
344 					1 + msecs_to_jiffies(1000));
345 		if (!ret) {
346 			dev_err(&ak8974->i2c->dev,
347 				"timeout waiting for DRDY IRQ\n");
348 			return -ETIMEDOUT;
349 		}
350 		return 0;
351 	}
352 
353 	/* Default delay-based poll loop */
354 	do {
355 		msleep(AK8974_MEASTIME);
356 		ret = regmap_read(ak8974->map, AK8974_STATUS, &val);
357 		if (ret < 0)
358 			return ret;
359 		if (val & AK8974_STATUS_DRDY)
360 			return 0;
361 	} while (--timeout);
362 
363 	dev_err(&ak8974->i2c->dev, "timeout waiting for DRDY\n");
364 	return -ETIMEDOUT;
365 }
366 
367 static int ak8974_getresult(struct ak8974 *ak8974, __le16 *result)
368 {
369 	unsigned int src;
370 	int ret;
371 
372 	ret = ak8974_await_drdy(ak8974);
373 	if (ret)
374 		return ret;
375 	ret = regmap_read(ak8974->map, AK8974_INT_SRC, &src);
376 	if (ret < 0)
377 		return ret;
378 
379 	/* Out of range overflow! Strong magnet close? */
380 	if (src & AK8974_INT_RANGE) {
381 		dev_err(&ak8974->i2c->dev,
382 			"range overflow in sensor\n");
383 		return -ERANGE;
384 	}
385 
386 	ret = regmap_bulk_read(ak8974->map, AK8974_DATA_X, result, 6);
387 	if (ret)
388 		return ret;
389 
390 	return ret;
391 }
392 
393 static irqreturn_t ak8974_drdy_irq(int irq, void *d)
394 {
395 	struct ak8974 *ak8974 = d;
396 
397 	if (!ak8974->drdy_irq)
398 		return IRQ_NONE;
399 
400 	/* TODO: timestamp here to get good measurement stamps */
401 	return IRQ_WAKE_THREAD;
402 }
403 
404 static irqreturn_t ak8974_drdy_irq_thread(int irq, void *d)
405 {
406 	struct ak8974 *ak8974 = d;
407 	unsigned int val;
408 	int ret;
409 
410 	/* Check if this was a DRDY from us */
411 	ret = regmap_read(ak8974->map, AK8974_STATUS, &val);
412 	if (ret < 0) {
413 		dev_err(&ak8974->i2c->dev, "error reading DRDY status\n");
414 		return IRQ_HANDLED;
415 	}
416 	if (val & AK8974_STATUS_DRDY) {
417 		/* Yes this was our IRQ */
418 		complete(&ak8974->drdy_complete);
419 		return IRQ_HANDLED;
420 	}
421 
422 	/* We may be on a shared IRQ, let the next client check */
423 	return IRQ_NONE;
424 }
425 
426 static int ak8974_selftest(struct ak8974 *ak8974)
427 {
428 	struct device *dev = &ak8974->i2c->dev;
429 	unsigned int val;
430 	int ret;
431 
432 	ret = regmap_read(ak8974->map, AK8974_SELFTEST, &val);
433 	if (ret)
434 		return ret;
435 	if (val != AK8974_SELFTEST_IDLE) {
436 		dev_err(dev, "selftest not idle before test\n");
437 		return -EIO;
438 	}
439 
440 	/* Trigger self-test */
441 	ret = regmap_update_bits(ak8974->map,
442 			AK8974_CTRL3,
443 			AK8974_CTRL3_SELFTEST,
444 			AK8974_CTRL3_SELFTEST);
445 	if (ret) {
446 		dev_err(dev, "could not write CTRL3\n");
447 		return ret;
448 	}
449 
450 	msleep(AK8974_SELFTEST_DELAY);
451 
452 	ret = regmap_read(ak8974->map, AK8974_SELFTEST, &val);
453 	if (ret)
454 		return ret;
455 	if (val != AK8974_SELFTEST_OK) {
456 		dev_err(dev, "selftest result NOT OK (%02x)\n", val);
457 		return -EIO;
458 	}
459 
460 	ret = regmap_read(ak8974->map, AK8974_SELFTEST, &val);
461 	if (ret)
462 		return ret;
463 	if (val != AK8974_SELFTEST_IDLE) {
464 		dev_err(dev, "selftest not idle after test (%02x)\n", val);
465 		return -EIO;
466 	}
467 	dev_dbg(dev, "passed self-test\n");
468 
469 	return 0;
470 }
471 
472 static void ak8974_read_calib_data(struct ak8974 *ak8974, unsigned int reg,
473 				   __le16 *tab, size_t tab_size)
474 {
475 	int ret = regmap_bulk_read(ak8974->map, reg, tab, tab_size);
476 	if (ret) {
477 		memset(tab, 0xFF, tab_size);
478 		dev_warn(&ak8974->i2c->dev,
479 			 "can't read calibration data (regs %u..%zu): %d\n",
480 			 reg, reg + tab_size - 1, ret);
481 	} else {
482 		add_device_randomness(tab, tab_size);
483 	}
484 }
485 
486 static int ak8974_detect(struct ak8974 *ak8974)
487 {
488 	unsigned int whoami;
489 	const char *name;
490 	int ret;
491 	unsigned int fw;
492 	u16 sn;
493 
494 	ret = regmap_read(ak8974->map, AK8974_WHOAMI, &whoami);
495 	if (ret)
496 		return ret;
497 
498 	name = "ami305";
499 
500 	switch (whoami) {
501 	case AK8974_WHOAMI_VALUE_AMI306:
502 		name = "ami306";
503 		fallthrough;
504 	case AK8974_WHOAMI_VALUE_AMI305:
505 		ret = regmap_read(ak8974->map, AMI305_VER, &fw);
506 		if (ret)
507 			return ret;
508 		fw &= 0x7f; /* only bits 0 thru 6 valid */
509 		ret = ak8974_get_u16_val(ak8974, AMI305_SN, &sn);
510 		if (ret)
511 			return ret;
512 		add_device_randomness(&sn, sizeof(sn));
513 		dev_info(&ak8974->i2c->dev,
514 			 "detected %s, FW ver %02x, S/N: %04x\n",
515 			 name, fw, sn);
516 		break;
517 	case AK8974_WHOAMI_VALUE_AK8974:
518 		name = "ak8974";
519 		dev_info(&ak8974->i2c->dev, "detected AK8974\n");
520 		break;
521 	case AK8974_WHOAMI_VALUE_HSCDTD008A:
522 		name = "hscdtd008a";
523 		dev_info(&ak8974->i2c->dev, "detected hscdtd008a\n");
524 		break;
525 	default:
526 		dev_err(&ak8974->i2c->dev, "unsupported device (%02x) ",
527 			whoami);
528 		return -ENODEV;
529 	}
530 
531 	ak8974->name = name;
532 	ak8974->variant = whoami;
533 
534 	if (whoami == AK8974_WHOAMI_VALUE_AMI306) {
535 		__le16 fab_data1[9], fab_data2[3];
536 		int i;
537 
538 		ak8974_read_calib_data(ak8974, AMI306_FINEOUTPUT_X,
539 				       fab_data1, sizeof(fab_data1));
540 		ak8974_read_calib_data(ak8974, AMI306_OFFZERO_X,
541 				       fab_data2, sizeof(fab_data2));
542 
543 		for (i = 0; i < 3; ++i) {
544 			static const char axis[3] = "XYZ";
545 			static const char pgaxis[6] = "ZYZXYX";
546 			unsigned offz = le16_to_cpu(fab_data2[i]) & 0x7F;
547 			unsigned fine = le16_to_cpu(fab_data1[i]);
548 			unsigned sens = le16_to_cpu(fab_data1[i + 3]);
549 			unsigned pgain1 = le16_to_cpu(fab_data1[i + 6]);
550 			unsigned pgain2 = pgain1 >> 8;
551 
552 			pgain1 &= 0xFF;
553 
554 			dev_info(&ak8974->i2c->dev,
555 				 "factory calibration for axis %c: offz=%u sens=%u fine=%u pga%c=%u pga%c=%u\n",
556 				 axis[i], offz, sens, fine, pgaxis[i * 2],
557 				 pgain1, pgaxis[i * 2 + 1], pgain2);
558 		}
559 	}
560 
561 	return 0;
562 }
563 
564 static int ak8974_measure_channel(struct ak8974 *ak8974, unsigned long address,
565 				  int *val)
566 {
567 	__le16 hw_values[3];
568 	int ret;
569 
570 	pm_runtime_get_sync(&ak8974->i2c->dev);
571 	mutex_lock(&ak8974->lock);
572 
573 	/*
574 	 * We read all axes and discard all but one, for optimized
575 	 * reading, use the triggered buffer.
576 	 */
577 	ret = ak8974_trigmeas(ak8974);
578 	if (ret)
579 		goto out_unlock;
580 	ret = ak8974_getresult(ak8974, hw_values);
581 	if (ret)
582 		goto out_unlock;
583 	/*
584 	 * This explicit cast to (s16) is necessary as the measurement
585 	 * is done in 2's complement with positive and negative values.
586 	 * The follwing assignment to *val will then convert the signed
587 	 * s16 value to a signed int value.
588 	 */
589 	*val = (s16)le16_to_cpu(hw_values[address]);
590 out_unlock:
591 	mutex_unlock(&ak8974->lock);
592 	pm_runtime_mark_last_busy(&ak8974->i2c->dev);
593 	pm_runtime_put_autosuspend(&ak8974->i2c->dev);
594 
595 	return ret;
596 }
597 
598 static int ak8974_read_raw(struct iio_dev *indio_dev,
599 			   struct iio_chan_spec const *chan,
600 			   int *val, int *val2,
601 			   long mask)
602 {
603 	struct ak8974 *ak8974 = iio_priv(indio_dev);
604 	int ret;
605 
606 	switch (mask) {
607 	case IIO_CHAN_INFO_RAW:
608 		if (chan->address > 2) {
609 			dev_err(&ak8974->i2c->dev, "faulty channel address\n");
610 			return -EIO;
611 		}
612 		ret = ak8974_measure_channel(ak8974, chan->address, val);
613 		if (ret)
614 			return ret;
615 		return IIO_VAL_INT;
616 	case IIO_CHAN_INFO_SCALE:
617 		switch (ak8974->variant) {
618 		case AK8974_WHOAMI_VALUE_AMI306:
619 		case AK8974_WHOAMI_VALUE_AMI305:
620 			/*
621 			 * The datasheet for AMI305 and AMI306, page 6
622 			 * specifies the range of the sensor to be
623 			 * +/- 12 Gauss.
624 			 */
625 			*val = 12;
626 			/*
627 			 * 12 bits are used, +/- 2^11
628 			 * [ -2048 .. 2047 ] (manual page 20)
629 			 * [ 0xf800 .. 0x07ff ]
630 			 */
631 			*val2 = 11;
632 			return IIO_VAL_FRACTIONAL_LOG2;
633 		case AK8974_WHOAMI_VALUE_HSCDTD008A:
634 			/*
635 			 * The datasheet for HSCDTF008A, page 3 specifies the
636 			 * range of the sensor as +/- 2.4 mT per axis, which
637 			 * corresponds to +/- 2400 uT = +/- 24 Gauss.
638 			 */
639 			*val = 24;
640 			/*
641 			 * 15 bits are used (set up in CTRL4), +/- 2^14
642 			 * [ -16384 .. 16383 ] (manual page 24)
643 			 * [ 0xc000 .. 0x3fff ]
644 			 */
645 			*val2 = 14;
646 			return IIO_VAL_FRACTIONAL_LOG2;
647 		default:
648 			/* GUESSING +/- 12 Gauss */
649 			*val = 12;
650 			/* GUESSING 12 bits ADC +/- 2^11 */
651 			*val2 = 11;
652 			return IIO_VAL_FRACTIONAL_LOG2;
653 		}
654 		break;
655 	default:
656 		/* Unknown request */
657 		break;
658 	}
659 
660 	return -EINVAL;
661 }
662 
663 static void ak8974_fill_buffer(struct iio_dev *indio_dev)
664 {
665 	struct ak8974 *ak8974 = iio_priv(indio_dev);
666 	int ret;
667 
668 	pm_runtime_get_sync(&ak8974->i2c->dev);
669 	mutex_lock(&ak8974->lock);
670 
671 	ret = ak8974_trigmeas(ak8974);
672 	if (ret) {
673 		dev_err(&ak8974->i2c->dev, "error triggering measure\n");
674 		goto out_unlock;
675 	}
676 	ret = ak8974_getresult(ak8974, ak8974->scan.channels);
677 	if (ret) {
678 		dev_err(&ak8974->i2c->dev, "error getting measures\n");
679 		goto out_unlock;
680 	}
681 
682 	iio_push_to_buffers_with_timestamp(indio_dev, &ak8974->scan,
683 					   iio_get_time_ns(indio_dev));
684 
685  out_unlock:
686 	mutex_unlock(&ak8974->lock);
687 	pm_runtime_mark_last_busy(&ak8974->i2c->dev);
688 	pm_runtime_put_autosuspend(&ak8974->i2c->dev);
689 }
690 
691 static irqreturn_t ak8974_handle_trigger(int irq, void *p)
692 {
693 	const struct iio_poll_func *pf = p;
694 	struct iio_dev *indio_dev = pf->indio_dev;
695 
696 	ak8974_fill_buffer(indio_dev);
697 	iio_trigger_notify_done(indio_dev->trig);
698 
699 	return IRQ_HANDLED;
700 }
701 
702 static const struct iio_mount_matrix *
703 ak8974_get_mount_matrix(const struct iio_dev *indio_dev,
704 			const struct iio_chan_spec *chan)
705 {
706 	struct ak8974 *ak8974 = iio_priv(indio_dev);
707 
708 	return &ak8974->orientation;
709 }
710 
711 static const struct iio_chan_spec_ext_info ak8974_ext_info[] = {
712 	IIO_MOUNT_MATRIX(IIO_SHARED_BY_DIR, ak8974_get_mount_matrix),
713 	{ },
714 };
715 
716 #define AK8974_AXIS_CHANNEL(axis, index, bits)				\
717 	{								\
718 		.type = IIO_MAGN,					\
719 		.modified = 1,						\
720 		.channel2 = IIO_MOD_##axis,				\
721 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |		\
722 			BIT(IIO_CHAN_INFO_SCALE),			\
723 		.ext_info = ak8974_ext_info,				\
724 		.address = index,					\
725 		.scan_index = index,					\
726 		.scan_type = {						\
727 			.sign = 's',					\
728 			.realbits = bits,				\
729 			.storagebits = 16,				\
730 			.endianness = IIO_LE				\
731 		},							\
732 	}
733 
734 /*
735  * We have no datasheet for the AK8974 but we guess that its
736  * ADC is 12 bits. The AMI305 and AMI306 certainly has 12bit
737  * ADC.
738  */
739 static const struct iio_chan_spec ak8974_12_bits_channels[] = {
740 	AK8974_AXIS_CHANNEL(X, 0, 12),
741 	AK8974_AXIS_CHANNEL(Y, 1, 12),
742 	AK8974_AXIS_CHANNEL(Z, 2, 12),
743 	IIO_CHAN_SOFT_TIMESTAMP(3),
744 };
745 
746 /*
747  * The HSCDTD008A has 15 bits resolution the way we set it up
748  * in CTRL4.
749  */
750 static const struct iio_chan_spec ak8974_15_bits_channels[] = {
751 	AK8974_AXIS_CHANNEL(X, 0, 15),
752 	AK8974_AXIS_CHANNEL(Y, 1, 15),
753 	AK8974_AXIS_CHANNEL(Z, 2, 15),
754 	IIO_CHAN_SOFT_TIMESTAMP(3),
755 };
756 
757 static const unsigned long ak8974_scan_masks[] = { 0x7, 0 };
758 
759 static const struct iio_info ak8974_info = {
760 	.read_raw = &ak8974_read_raw,
761 };
762 
763 static bool ak8974_writeable_reg(struct device *dev, unsigned int reg)
764 {
765 	struct i2c_client *i2c = to_i2c_client(dev);
766 	struct iio_dev *indio_dev = i2c_get_clientdata(i2c);
767 	struct ak8974 *ak8974 = iio_priv(indio_dev);
768 
769 	switch (reg) {
770 	case AK8974_CTRL1:
771 	case AK8974_CTRL2:
772 	case AK8974_CTRL3:
773 	case AK8974_INT_CTRL:
774 	case AK8974_INT_THRES:
775 	case AK8974_INT_THRES + 1:
776 		return true;
777 	case AK8974_PRESET:
778 	case AK8974_PRESET + 1:
779 		return ak8974->variant != AK8974_WHOAMI_VALUE_HSCDTD008A;
780 	case AK8974_OFFSET_X:
781 	case AK8974_OFFSET_X + 1:
782 	case AK8974_OFFSET_Y:
783 	case AK8974_OFFSET_Y + 1:
784 	case AK8974_OFFSET_Z:
785 	case AK8974_OFFSET_Z + 1:
786 		return ak8974->variant == AK8974_WHOAMI_VALUE_AK8974 ||
787 		       ak8974->variant == AK8974_WHOAMI_VALUE_HSCDTD008A;
788 	case AMI305_OFFSET_X:
789 	case AMI305_OFFSET_X + 1:
790 	case AMI305_OFFSET_Y:
791 	case AMI305_OFFSET_Y + 1:
792 	case AMI305_OFFSET_Z:
793 	case AMI305_OFFSET_Z + 1:
794 		return ak8974->variant == AK8974_WHOAMI_VALUE_AMI305 ||
795 		       ak8974->variant == AK8974_WHOAMI_VALUE_AMI306;
796 	case AMI306_CTRL4:
797 	case AMI306_CTRL4 + 1:
798 		return ak8974->variant == AK8974_WHOAMI_VALUE_AMI306;
799 	default:
800 		return false;
801 	}
802 }
803 
804 static bool ak8974_precious_reg(struct device *dev, unsigned int reg)
805 {
806 	return reg == AK8974_INT_CLEAR;
807 }
808 
809 static const struct regmap_config ak8974_regmap_config = {
810 	.reg_bits = 8,
811 	.val_bits = 8,
812 	.max_register = 0xff,
813 	.writeable_reg = ak8974_writeable_reg,
814 	.precious_reg = ak8974_precious_reg,
815 };
816 
817 static int ak8974_probe(struct i2c_client *i2c)
818 {
819 	struct iio_dev *indio_dev;
820 	struct ak8974 *ak8974;
821 	unsigned long irq_trig;
822 	int irq = i2c->irq;
823 	int ret;
824 
825 	/* Register with IIO */
826 	indio_dev = devm_iio_device_alloc(&i2c->dev, sizeof(*ak8974));
827 	if (indio_dev == NULL)
828 		return -ENOMEM;
829 
830 	ak8974 = iio_priv(indio_dev);
831 	i2c_set_clientdata(i2c, indio_dev);
832 	ak8974->i2c = i2c;
833 	mutex_init(&ak8974->lock);
834 
835 	ret = iio_read_mount_matrix(&i2c->dev, &ak8974->orientation);
836 	if (ret)
837 		return ret;
838 
839 	ak8974->regs[0].supply = ak8974_reg_avdd;
840 	ak8974->regs[1].supply = ak8974_reg_dvdd;
841 
842 	ret = devm_regulator_bulk_get(&i2c->dev,
843 				      ARRAY_SIZE(ak8974->regs),
844 				      ak8974->regs);
845 	if (ret < 0)
846 		return dev_err_probe(&i2c->dev, ret, "cannot get regulators\n");
847 
848 	ret = regulator_bulk_enable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
849 	if (ret < 0) {
850 		dev_err(&i2c->dev, "cannot enable regulators\n");
851 		return ret;
852 	}
853 
854 	/* Take runtime PM online */
855 	pm_runtime_get_noresume(&i2c->dev);
856 	pm_runtime_set_active(&i2c->dev);
857 	pm_runtime_enable(&i2c->dev);
858 
859 	ak8974->map = devm_regmap_init_i2c(i2c, &ak8974_regmap_config);
860 	if (IS_ERR(ak8974->map)) {
861 		dev_err(&i2c->dev, "failed to allocate register map\n");
862 		pm_runtime_put_noidle(&i2c->dev);
863 		pm_runtime_disable(&i2c->dev);
864 		return PTR_ERR(ak8974->map);
865 	}
866 
867 	ret = ak8974_set_power(ak8974, AK8974_PWR_ON);
868 	if (ret) {
869 		dev_err(&i2c->dev, "could not power on\n");
870 		goto disable_pm;
871 	}
872 
873 	ret = ak8974_detect(ak8974);
874 	if (ret) {
875 		dev_err(&i2c->dev, "neither AK8974 nor AMI30x found\n");
876 		goto disable_pm;
877 	}
878 
879 	ret = ak8974_selftest(ak8974);
880 	if (ret)
881 		dev_err(&i2c->dev, "selftest failed (continuing anyway)\n");
882 
883 	ret = ak8974_reset(ak8974);
884 	if (ret) {
885 		dev_err(&i2c->dev, "AK8974 reset failed\n");
886 		goto disable_pm;
887 	}
888 
889 	switch (ak8974->variant) {
890 	case AK8974_WHOAMI_VALUE_AMI306:
891 	case AK8974_WHOAMI_VALUE_AMI305:
892 		indio_dev->channels = ak8974_12_bits_channels;
893 		indio_dev->num_channels = ARRAY_SIZE(ak8974_12_bits_channels);
894 		break;
895 	case AK8974_WHOAMI_VALUE_HSCDTD008A:
896 		indio_dev->channels = ak8974_15_bits_channels;
897 		indio_dev->num_channels = ARRAY_SIZE(ak8974_15_bits_channels);
898 		break;
899 	default:
900 		indio_dev->channels = ak8974_12_bits_channels;
901 		indio_dev->num_channels = ARRAY_SIZE(ak8974_12_bits_channels);
902 		break;
903 	}
904 	indio_dev->info = &ak8974_info;
905 	indio_dev->available_scan_masks = ak8974_scan_masks;
906 	indio_dev->modes = INDIO_DIRECT_MODE;
907 	indio_dev->name = ak8974->name;
908 
909 	ret = iio_triggered_buffer_setup(indio_dev, NULL,
910 					 ak8974_handle_trigger,
911 					 NULL);
912 	if (ret) {
913 		dev_err(&i2c->dev, "triggered buffer setup failed\n");
914 		goto disable_pm;
915 	}
916 
917 	/* If we have a valid DRDY IRQ, make use of it */
918 	if (irq > 0) {
919 		irq_trig = irqd_get_trigger_type(irq_get_irq_data(irq));
920 		if (irq_trig == IRQF_TRIGGER_RISING) {
921 			dev_info(&i2c->dev, "enable rising edge DRDY IRQ\n");
922 		} else if (irq_trig == IRQF_TRIGGER_FALLING) {
923 			ak8974->drdy_active_low = true;
924 			dev_info(&i2c->dev, "enable falling edge DRDY IRQ\n");
925 		} else {
926 			irq_trig = IRQF_TRIGGER_RISING;
927 		}
928 		irq_trig |= IRQF_ONESHOT;
929 		irq_trig |= IRQF_SHARED;
930 
931 		ret = devm_request_threaded_irq(&i2c->dev,
932 						irq,
933 						ak8974_drdy_irq,
934 						ak8974_drdy_irq_thread,
935 						irq_trig,
936 						ak8974->name,
937 						ak8974);
938 		if (ret) {
939 			dev_err(&i2c->dev, "unable to request DRDY IRQ "
940 				"- proceeding without IRQ\n");
941 			goto no_irq;
942 		}
943 		ak8974->drdy_irq = true;
944 	}
945 
946 no_irq:
947 	ret = iio_device_register(indio_dev);
948 	if (ret) {
949 		dev_err(&i2c->dev, "device register failed\n");
950 		goto cleanup_buffer;
951 	}
952 
953 	pm_runtime_set_autosuspend_delay(&i2c->dev,
954 					 AK8974_AUTOSUSPEND_DELAY);
955 	pm_runtime_use_autosuspend(&i2c->dev);
956 	pm_runtime_put(&i2c->dev);
957 
958 	return 0;
959 
960 cleanup_buffer:
961 	iio_triggered_buffer_cleanup(indio_dev);
962 disable_pm:
963 	pm_runtime_put_noidle(&i2c->dev);
964 	pm_runtime_disable(&i2c->dev);
965 	ak8974_set_power(ak8974, AK8974_PWR_OFF);
966 	regulator_bulk_disable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
967 
968 	return ret;
969 }
970 
971 static void ak8974_remove(struct i2c_client *i2c)
972 {
973 	struct iio_dev *indio_dev = i2c_get_clientdata(i2c);
974 	struct ak8974 *ak8974 = iio_priv(indio_dev);
975 
976 	iio_device_unregister(indio_dev);
977 	iio_triggered_buffer_cleanup(indio_dev);
978 	pm_runtime_get_sync(&i2c->dev);
979 	pm_runtime_put_noidle(&i2c->dev);
980 	pm_runtime_disable(&i2c->dev);
981 	ak8974_set_power(ak8974, AK8974_PWR_OFF);
982 	regulator_bulk_disable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
983 }
984 
985 static int ak8974_runtime_suspend(struct device *dev)
986 {
987 	struct ak8974 *ak8974 =
988 		iio_priv(i2c_get_clientdata(to_i2c_client(dev)));
989 
990 	ak8974_set_power(ak8974, AK8974_PWR_OFF);
991 	regulator_bulk_disable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
992 
993 	return 0;
994 }
995 
996 static int ak8974_runtime_resume(struct device *dev)
997 {
998 	struct ak8974 *ak8974 =
999 		iio_priv(i2c_get_clientdata(to_i2c_client(dev)));
1000 	int ret;
1001 
1002 	ret = regulator_bulk_enable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
1003 	if (ret)
1004 		return ret;
1005 	msleep(AK8974_POWERON_DELAY);
1006 	ret = ak8974_set_power(ak8974, AK8974_PWR_ON);
1007 	if (ret)
1008 		goto out_regulator_disable;
1009 
1010 	ret = ak8974_configure(ak8974);
1011 	if (ret)
1012 		goto out_disable_power;
1013 
1014 	return 0;
1015 
1016 out_disable_power:
1017 	ak8974_set_power(ak8974, AK8974_PWR_OFF);
1018 out_regulator_disable:
1019 	regulator_bulk_disable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
1020 
1021 	return ret;
1022 }
1023 
1024 static DEFINE_RUNTIME_DEV_PM_OPS(ak8974_dev_pm_ops, ak8974_runtime_suspend,
1025 				 ak8974_runtime_resume, NULL);
1026 
1027 static const struct i2c_device_id ak8974_id[] = {
1028 	{"ami305", 0 },
1029 	{"ami306", 0 },
1030 	{"ak8974", 0 },
1031 	{"hscdtd008a", 0 },
1032 	{}
1033 };
1034 MODULE_DEVICE_TABLE(i2c, ak8974_id);
1035 
1036 static const struct of_device_id ak8974_of_match[] = {
1037 	{ .compatible = "asahi-kasei,ak8974", },
1038 	{ .compatible = "alps,hscdtd008a", },
1039 	{}
1040 };
1041 MODULE_DEVICE_TABLE(of, ak8974_of_match);
1042 
1043 static struct i2c_driver ak8974_driver = {
1044 	.driver	 = {
1045 		.name	= "ak8974",
1046 		.pm = pm_ptr(&ak8974_dev_pm_ops),
1047 		.of_match_table = ak8974_of_match,
1048 	},
1049 	.probe_new = ak8974_probe,
1050 	.remove	  = ak8974_remove,
1051 	.id_table = ak8974_id,
1052 };
1053 module_i2c_driver(ak8974_driver);
1054 
1055 MODULE_DESCRIPTION("AK8974 and AMI30x 3-axis magnetometer driver");
1056 MODULE_AUTHOR("Samu Onkalo");
1057 MODULE_AUTHOR("Linus Walleij");
1058 MODULE_LICENSE("GPL v2");
1059