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