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 		s64 ts __aligned(8);
200 	} scan;
201 };
202 
203 static const char ak8974_reg_avdd[] = "avdd";
204 static const char ak8974_reg_dvdd[] = "dvdd";
205 
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 
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 
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 
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 
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 
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_update_bits(ak8974->map,
330 				  AK8974_CTRL3,
331 				  AK8974_CTRL3_FORCE,
332 				  AK8974_CTRL3_FORCE);
333 }
334 
335 static int ak8974_await_drdy(struct ak8974 *ak8974)
336 {
337 	int timeout = 2;
338 	unsigned int val;
339 	int ret;
340 
341 	if (ak8974->drdy_irq) {
342 		ret = wait_for_completion_timeout(&ak8974->drdy_complete,
343 					1 + msecs_to_jiffies(1000));
344 		if (!ret) {
345 			dev_err(&ak8974->i2c->dev,
346 				"timeout waiting for DRDY IRQ\n");
347 			return -ETIMEDOUT;
348 		}
349 		return 0;
350 	}
351 
352 	/* Default delay-based poll loop */
353 	do {
354 		msleep(AK8974_MEASTIME);
355 		ret = regmap_read(ak8974->map, AK8974_STATUS, &val);
356 		if (ret < 0)
357 			return ret;
358 		if (val & AK8974_STATUS_DRDY)
359 			return 0;
360 	} while (--timeout);
361 
362 	dev_err(&ak8974->i2c->dev, "timeout waiting for DRDY\n");
363 	return -ETIMEDOUT;
364 }
365 
366 static int ak8974_getresult(struct ak8974 *ak8974, __le16 *result)
367 {
368 	unsigned int src;
369 	int ret;
370 
371 	ret = ak8974_await_drdy(ak8974);
372 	if (ret)
373 		return ret;
374 	ret = regmap_read(ak8974->map, AK8974_INT_SRC, &src);
375 	if (ret < 0)
376 		return ret;
377 
378 	/* Out of range overflow! Strong magnet close? */
379 	if (src & AK8974_INT_RANGE) {
380 		dev_err(&ak8974->i2c->dev,
381 			"range overflow in sensor\n");
382 		return -ERANGE;
383 	}
384 
385 	ret = regmap_bulk_read(ak8974->map, AK8974_DATA_X, result, 6);
386 	if (ret)
387 		return ret;
388 
389 	return ret;
390 }
391 
392 static irqreturn_t ak8974_drdy_irq(int irq, void *d)
393 {
394 	struct ak8974 *ak8974 = d;
395 
396 	if (!ak8974->drdy_irq)
397 		return IRQ_NONE;
398 
399 	/* TODO: timestamp here to get good measurement stamps */
400 	return IRQ_WAKE_THREAD;
401 }
402 
403 static irqreturn_t ak8974_drdy_irq_thread(int irq, void *d)
404 {
405 	struct ak8974 *ak8974 = d;
406 	unsigned int val;
407 	int ret;
408 
409 	/* Check if this was a DRDY from us */
410 	ret = regmap_read(ak8974->map, AK8974_STATUS, &val);
411 	if (ret < 0) {
412 		dev_err(&ak8974->i2c->dev, "error reading DRDY status\n");
413 		return IRQ_HANDLED;
414 	}
415 	if (val & AK8974_STATUS_DRDY) {
416 		/* Yes this was our IRQ */
417 		complete(&ak8974->drdy_complete);
418 		return IRQ_HANDLED;
419 	}
420 
421 	/* We may be on a shared IRQ, let the next client check */
422 	return IRQ_NONE;
423 }
424 
425 static int ak8974_selftest(struct ak8974 *ak8974)
426 {
427 	struct device *dev = &ak8974->i2c->dev;
428 	unsigned int val;
429 	int ret;
430 
431 	ret = regmap_read(ak8974->map, AK8974_SELFTEST, &val);
432 	if (ret)
433 		return ret;
434 	if (val != AK8974_SELFTEST_IDLE) {
435 		dev_err(dev, "selftest not idle before test\n");
436 		return -EIO;
437 	}
438 
439 	/* Trigger self-test */
440 	ret = regmap_update_bits(ak8974->map,
441 			AK8974_CTRL3,
442 			AK8974_CTRL3_SELFTEST,
443 			AK8974_CTRL3_SELFTEST);
444 	if (ret) {
445 		dev_err(dev, "could not write CTRL3\n");
446 		return ret;
447 	}
448 
449 	msleep(AK8974_SELFTEST_DELAY);
450 
451 	ret = regmap_read(ak8974->map, AK8974_SELFTEST, &val);
452 	if (ret)
453 		return ret;
454 	if (val != AK8974_SELFTEST_OK) {
455 		dev_err(dev, "selftest result NOT OK (%02x)\n", val);
456 		return -EIO;
457 	}
458 
459 	ret = regmap_read(ak8974->map, AK8974_SELFTEST, &val);
460 	if (ret)
461 		return ret;
462 	if (val != AK8974_SELFTEST_IDLE) {
463 		dev_err(dev, "selftest not idle after test (%02x)\n", val);
464 		return -EIO;
465 	}
466 	dev_dbg(dev, "passed self-test\n");
467 
468 	return 0;
469 }
470 
471 static void ak8974_read_calib_data(struct ak8974 *ak8974, unsigned int reg,
472 				   __le16 *tab, size_t tab_size)
473 {
474 	int ret = regmap_bulk_read(ak8974->map, reg, tab, tab_size);
475 	if (ret) {
476 		memset(tab, 0xFF, tab_size);
477 		dev_warn(&ak8974->i2c->dev,
478 			 "can't read calibration data (regs %u..%zu): %d\n",
479 			 reg, reg + tab_size - 1, ret);
480 	} else {
481 		add_device_randomness(tab, tab_size);
482 	}
483 }
484 
485 static int ak8974_detect(struct ak8974 *ak8974)
486 {
487 	unsigned int whoami;
488 	const char *name;
489 	int ret;
490 	unsigned int fw;
491 	u16 sn;
492 
493 	ret = regmap_read(ak8974->map, AK8974_WHOAMI, &whoami);
494 	if (ret)
495 		return ret;
496 
497 	name = "ami305";
498 
499 	switch (whoami) {
500 	case AK8974_WHOAMI_VALUE_AMI306:
501 		name = "ami306";
502 		/* fall-through */
503 	case AK8974_WHOAMI_VALUE_AMI305:
504 		ret = regmap_read(ak8974->map, AMI305_VER, &fw);
505 		if (ret)
506 			return ret;
507 		fw &= 0x7f; /* only bits 0 thru 6 valid */
508 		ret = ak8974_get_u16_val(ak8974, AMI305_SN, &sn);
509 		if (ret)
510 			return ret;
511 		add_device_randomness(&sn, sizeof(sn));
512 		dev_info(&ak8974->i2c->dev,
513 			 "detected %s, FW ver %02x, S/N: %04x\n",
514 			 name, fw, sn);
515 		break;
516 	case AK8974_WHOAMI_VALUE_AK8974:
517 		name = "ak8974";
518 		dev_info(&ak8974->i2c->dev, "detected AK8974\n");
519 		break;
520 	case AK8974_WHOAMI_VALUE_HSCDTD008A:
521 		name = "hscdtd008a";
522 		dev_info(&ak8974->i2c->dev, "detected hscdtd008a\n");
523 		break;
524 	default:
525 		dev_err(&ak8974->i2c->dev, "unsupported device (%02x) ",
526 			whoami);
527 		return -ENODEV;
528 	}
529 
530 	ak8974->name = name;
531 	ak8974->variant = whoami;
532 
533 	if (whoami == AK8974_WHOAMI_VALUE_AMI306) {
534 		__le16 fab_data1[9], fab_data2[3];
535 		int i;
536 
537 		ak8974_read_calib_data(ak8974, AMI306_FINEOUTPUT_X,
538 				       fab_data1, sizeof(fab_data1));
539 		ak8974_read_calib_data(ak8974, AMI306_OFFZERO_X,
540 				       fab_data2, sizeof(fab_data2));
541 
542 		for (i = 0; i < 3; ++i) {
543 			static const char axis[3] = "XYZ";
544 			static const char pgaxis[6] = "ZYZXYX";
545 			unsigned offz = le16_to_cpu(fab_data2[i]) & 0x7F;
546 			unsigned fine = le16_to_cpu(fab_data1[i]);
547 			unsigned sens = le16_to_cpu(fab_data1[i + 3]);
548 			unsigned pgain1 = le16_to_cpu(fab_data1[i + 6]);
549 			unsigned pgain2 = pgain1 >> 8;
550 
551 			pgain1 &= 0xFF;
552 
553 			dev_info(&ak8974->i2c->dev,
554 				 "factory calibration for axis %c: offz=%u sens=%u fine=%u pga%c=%u pga%c=%u\n",
555 				 axis[i], offz, sens, fine, pgaxis[i * 2],
556 				 pgain1, pgaxis[i * 2 + 1], pgain2);
557 		}
558 	}
559 
560 	return 0;
561 }
562 
563 static int ak8974_measure_channel(struct ak8974 *ak8974, unsigned long address,
564 				  int *val)
565 {
566 	__le16 hw_values[3];
567 	int ret;
568 
569 	pm_runtime_get_sync(&ak8974->i2c->dev);
570 	mutex_lock(&ak8974->lock);
571 
572 	/*
573 	 * We read all axes and discard all but one, for optimized
574 	 * reading, use the triggered buffer.
575 	 */
576 	ret = ak8974_trigmeas(ak8974);
577 	if (ret)
578 		goto out_unlock;
579 	ret = ak8974_getresult(ak8974, hw_values);
580 	if (ret)
581 		goto out_unlock;
582 	/*
583 	 * This explicit cast to (s16) is necessary as the measurement
584 	 * is done in 2's complement with positive and negative values.
585 	 * The follwing assignment to *val will then convert the signed
586 	 * s16 value to a signed int value.
587 	 */
588 	*val = (s16)le16_to_cpu(hw_values[address]);
589 out_unlock:
590 	mutex_unlock(&ak8974->lock);
591 	pm_runtime_mark_last_busy(&ak8974->i2c->dev);
592 	pm_runtime_put_autosuspend(&ak8974->i2c->dev);
593 
594 	return ret;
595 }
596 
597 static int ak8974_read_raw(struct iio_dev *indio_dev,
598 			   struct iio_chan_spec const *chan,
599 			   int *val, int *val2,
600 			   long mask)
601 {
602 	struct ak8974 *ak8974 = iio_priv(indio_dev);
603 	int ret;
604 
605 	switch (mask) {
606 	case IIO_CHAN_INFO_RAW:
607 		if (chan->address > 2) {
608 			dev_err(&ak8974->i2c->dev, "faulty channel address\n");
609 			return -EIO;
610 		}
611 		ret = ak8974_measure_channel(ak8974, chan->address, val);
612 		if (ret)
613 			return ret;
614 		return IIO_VAL_INT;
615 	case IIO_CHAN_INFO_SCALE:
616 		switch (ak8974->variant) {
617 		case AK8974_WHOAMI_VALUE_AMI306:
618 		case AK8974_WHOAMI_VALUE_AMI305:
619 			/*
620 			 * The datasheet for AMI305 and AMI306, page 6
621 			 * specifies the range of the sensor to be
622 			 * +/- 12 Gauss.
623 			 */
624 			*val = 12;
625 			/*
626 			 * 12 bits are used, +/- 2^11
627 			 * [ -2048 .. 2047 ] (manual page 20)
628 			 * [ 0xf800 .. 0x07ff ]
629 			 */
630 			*val2 = 11;
631 			return IIO_VAL_FRACTIONAL_LOG2;
632 		case AK8974_WHOAMI_VALUE_HSCDTD008A:
633 			/*
634 			 * The datasheet for HSCDTF008A, page 3 specifies the
635 			 * range of the sensor as +/- 2.4 mT per axis, which
636 			 * corresponds to +/- 2400 uT = +/- 24 Gauss.
637 			 */
638 			*val = 24;
639 			/*
640 			 * 15 bits are used (set up in CTRL4), +/- 2^14
641 			 * [ -16384 .. 16383 ] (manual page 24)
642 			 * [ 0xc000 .. 0x3fff ]
643 			 */
644 			*val2 = 14;
645 			return IIO_VAL_FRACTIONAL_LOG2;
646 		default:
647 			/* GUESSING +/- 12 Gauss */
648 			*val = 12;
649 			/* GUESSING 12 bits ADC +/- 2^11 */
650 			*val2 = 11;
651 			return IIO_VAL_FRACTIONAL_LOG2;
652 		}
653 		break;
654 	default:
655 		/* Unknown request */
656 		break;
657 	}
658 
659 	return -EINVAL;
660 }
661 
662 static void ak8974_fill_buffer(struct iio_dev *indio_dev)
663 {
664 	struct ak8974 *ak8974 = iio_priv(indio_dev);
665 	int ret;
666 
667 	pm_runtime_get_sync(&ak8974->i2c->dev);
668 	mutex_lock(&ak8974->lock);
669 
670 	ret = ak8974_trigmeas(ak8974);
671 	if (ret) {
672 		dev_err(&ak8974->i2c->dev, "error triggering measure\n");
673 		goto out_unlock;
674 	}
675 	ret = ak8974_getresult(ak8974, ak8974->scan.channels);
676 	if (ret) {
677 		dev_err(&ak8974->i2c->dev, "error getting measures\n");
678 		goto out_unlock;
679 	}
680 
681 	iio_push_to_buffers_with_timestamp(indio_dev, &ak8974->scan,
682 					   iio_get_time_ns(indio_dev));
683 
684  out_unlock:
685 	mutex_unlock(&ak8974->lock);
686 	pm_runtime_mark_last_busy(&ak8974->i2c->dev);
687 	pm_runtime_put_autosuspend(&ak8974->i2c->dev);
688 }
689 
690 static irqreturn_t ak8974_handle_trigger(int irq, void *p)
691 {
692 	const struct iio_poll_func *pf = p;
693 	struct iio_dev *indio_dev = pf->indio_dev;
694 
695 	ak8974_fill_buffer(indio_dev);
696 	iio_trigger_notify_done(indio_dev->trig);
697 
698 	return IRQ_HANDLED;
699 }
700 
701 static const struct iio_mount_matrix *
702 ak8974_get_mount_matrix(const struct iio_dev *indio_dev,
703 			const struct iio_chan_spec *chan)
704 {
705 	struct ak8974 *ak8974 = iio_priv(indio_dev);
706 
707 	return &ak8974->orientation;
708 }
709 
710 static const struct iio_chan_spec_ext_info ak8974_ext_info[] = {
711 	IIO_MOUNT_MATRIX(IIO_SHARED_BY_DIR, ak8974_get_mount_matrix),
712 	{ },
713 };
714 
715 #define AK8974_AXIS_CHANNEL(axis, index, bits)				\
716 	{								\
717 		.type = IIO_MAGN,					\
718 		.modified = 1,						\
719 		.channel2 = IIO_MOD_##axis,				\
720 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |		\
721 			BIT(IIO_CHAN_INFO_SCALE),			\
722 		.ext_info = ak8974_ext_info,				\
723 		.address = index,					\
724 		.scan_index = index,					\
725 		.scan_type = {						\
726 			.sign = 's',					\
727 			.realbits = bits,				\
728 			.storagebits = 16,				\
729 			.endianness = IIO_LE				\
730 		},							\
731 	}
732 
733 /*
734  * We have no datasheet for the AK8974 but we guess that its
735  * ADC is 12 bits. The AMI305 and AMI306 certainly has 12bit
736  * ADC.
737  */
738 static const struct iio_chan_spec ak8974_12_bits_channels[] = {
739 	AK8974_AXIS_CHANNEL(X, 0, 12),
740 	AK8974_AXIS_CHANNEL(Y, 1, 12),
741 	AK8974_AXIS_CHANNEL(Z, 2, 12),
742 	IIO_CHAN_SOFT_TIMESTAMP(3),
743 };
744 
745 /*
746  * The HSCDTD008A has 15 bits resolution the way we set it up
747  * in CTRL4.
748  */
749 static const struct iio_chan_spec ak8974_15_bits_channels[] = {
750 	AK8974_AXIS_CHANNEL(X, 0, 15),
751 	AK8974_AXIS_CHANNEL(Y, 1, 15),
752 	AK8974_AXIS_CHANNEL(Z, 2, 15),
753 	IIO_CHAN_SOFT_TIMESTAMP(3),
754 };
755 
756 static const unsigned long ak8974_scan_masks[] = { 0x7, 0 };
757 
758 static const struct iio_info ak8974_info = {
759 	.read_raw = &ak8974_read_raw,
760 };
761 
762 static bool ak8974_writeable_reg(struct device *dev, unsigned int reg)
763 {
764 	struct i2c_client *i2c = to_i2c_client(dev);
765 	struct iio_dev *indio_dev = i2c_get_clientdata(i2c);
766 	struct ak8974 *ak8974 = iio_priv(indio_dev);
767 
768 	switch (reg) {
769 	case AK8974_CTRL1:
770 	case AK8974_CTRL2:
771 	case AK8974_CTRL3:
772 	case AK8974_INT_CTRL:
773 	case AK8974_INT_THRES:
774 	case AK8974_INT_THRES + 1:
775 		return true;
776 	case AK8974_PRESET:
777 	case AK8974_PRESET + 1:
778 		return ak8974->variant != AK8974_WHOAMI_VALUE_HSCDTD008A;
779 	case AK8974_OFFSET_X:
780 	case AK8974_OFFSET_X + 1:
781 	case AK8974_OFFSET_Y:
782 	case AK8974_OFFSET_Y + 1:
783 	case AK8974_OFFSET_Z:
784 	case AK8974_OFFSET_Z + 1:
785 		return ak8974->variant == AK8974_WHOAMI_VALUE_AK8974 ||
786 		       ak8974->variant == AK8974_WHOAMI_VALUE_HSCDTD008A;
787 	case AMI305_OFFSET_X:
788 	case AMI305_OFFSET_X + 1:
789 	case AMI305_OFFSET_Y:
790 	case AMI305_OFFSET_Y + 1:
791 	case AMI305_OFFSET_Z:
792 	case AMI305_OFFSET_Z + 1:
793 		return ak8974->variant == AK8974_WHOAMI_VALUE_AMI305 ||
794 		       ak8974->variant == AK8974_WHOAMI_VALUE_AMI306;
795 	case AMI306_CTRL4:
796 	case AMI306_CTRL4 + 1:
797 		return ak8974->variant == AK8974_WHOAMI_VALUE_AMI306;
798 	default:
799 		return false;
800 	}
801 }
802 
803 static bool ak8974_precious_reg(struct device *dev, unsigned int reg)
804 {
805 	return reg == AK8974_INT_CLEAR;
806 }
807 
808 static const struct regmap_config ak8974_regmap_config = {
809 	.reg_bits = 8,
810 	.val_bits = 8,
811 	.max_register = 0xff,
812 	.writeable_reg = ak8974_writeable_reg,
813 	.precious_reg = ak8974_precious_reg,
814 };
815 
816 static int ak8974_probe(struct i2c_client *i2c,
817 			const struct i2c_device_id *id)
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, "mount-matrix",
836 				    &ak8974->orientation);
837 	if (ret)
838 		return ret;
839 
840 	ak8974->regs[0].supply = ak8974_reg_avdd;
841 	ak8974->regs[1].supply = ak8974_reg_dvdd;
842 
843 	ret = devm_regulator_bulk_get(&i2c->dev,
844 				      ARRAY_SIZE(ak8974->regs),
845 				      ak8974->regs);
846 	if (ret < 0) {
847 		if (ret != -EPROBE_DEFER)
848 			dev_err(&i2c->dev, "cannot get regulators: %d\n", ret);
849 		else
850 			dev_dbg(&i2c->dev,
851 				"regulators unavailable, deferring probe\n");
852 
853 		return ret;
854 	}
855 
856 	ret = regulator_bulk_enable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
857 	if (ret < 0) {
858 		dev_err(&i2c->dev, "cannot enable regulators\n");
859 		return ret;
860 	}
861 
862 	/* Take runtime PM online */
863 	pm_runtime_get_noresume(&i2c->dev);
864 	pm_runtime_set_active(&i2c->dev);
865 	pm_runtime_enable(&i2c->dev);
866 
867 	ak8974->map = devm_regmap_init_i2c(i2c, &ak8974_regmap_config);
868 	if (IS_ERR(ak8974->map)) {
869 		dev_err(&i2c->dev, "failed to allocate register map\n");
870 		pm_runtime_put_noidle(&i2c->dev);
871 		pm_runtime_disable(&i2c->dev);
872 		return PTR_ERR(ak8974->map);
873 	}
874 
875 	ret = ak8974_set_power(ak8974, AK8974_PWR_ON);
876 	if (ret) {
877 		dev_err(&i2c->dev, "could not power on\n");
878 		goto disable_pm;
879 	}
880 
881 	ret = ak8974_detect(ak8974);
882 	if (ret) {
883 		dev_err(&i2c->dev, "neither AK8974 nor AMI30x found\n");
884 		goto disable_pm;
885 	}
886 
887 	ret = ak8974_selftest(ak8974);
888 	if (ret)
889 		dev_err(&i2c->dev, "selftest failed (continuing anyway)\n");
890 
891 	ret = ak8974_reset(ak8974);
892 	if (ret) {
893 		dev_err(&i2c->dev, "AK8974 reset failed\n");
894 		goto disable_pm;
895 	}
896 
897 	switch (ak8974->variant) {
898 	case AK8974_WHOAMI_VALUE_AMI306:
899 	case AK8974_WHOAMI_VALUE_AMI305:
900 		indio_dev->channels = ak8974_12_bits_channels;
901 		indio_dev->num_channels = ARRAY_SIZE(ak8974_12_bits_channels);
902 		break;
903 	case AK8974_WHOAMI_VALUE_HSCDTD008A:
904 		indio_dev->channels = ak8974_15_bits_channels;
905 		indio_dev->num_channels = ARRAY_SIZE(ak8974_15_bits_channels);
906 		break;
907 	default:
908 		indio_dev->channels = ak8974_12_bits_channels;
909 		indio_dev->num_channels = ARRAY_SIZE(ak8974_12_bits_channels);
910 		break;
911 	}
912 	indio_dev->info = &ak8974_info;
913 	indio_dev->available_scan_masks = ak8974_scan_masks;
914 	indio_dev->modes = INDIO_DIRECT_MODE;
915 	indio_dev->name = ak8974->name;
916 
917 	ret = iio_triggered_buffer_setup(indio_dev, NULL,
918 					 ak8974_handle_trigger,
919 					 NULL);
920 	if (ret) {
921 		dev_err(&i2c->dev, "triggered buffer setup failed\n");
922 		goto disable_pm;
923 	}
924 
925 	/* If we have a valid DRDY IRQ, make use of it */
926 	if (irq > 0) {
927 		irq_trig = irqd_get_trigger_type(irq_get_irq_data(irq));
928 		if (irq_trig == IRQF_TRIGGER_RISING) {
929 			dev_info(&i2c->dev, "enable rising edge DRDY IRQ\n");
930 		} else if (irq_trig == IRQF_TRIGGER_FALLING) {
931 			ak8974->drdy_active_low = true;
932 			dev_info(&i2c->dev, "enable falling edge DRDY IRQ\n");
933 		} else {
934 			irq_trig = IRQF_TRIGGER_RISING;
935 		}
936 		irq_trig |= IRQF_ONESHOT;
937 		irq_trig |= IRQF_SHARED;
938 
939 		ret = devm_request_threaded_irq(&i2c->dev,
940 						irq,
941 						ak8974_drdy_irq,
942 						ak8974_drdy_irq_thread,
943 						irq_trig,
944 						ak8974->name,
945 						ak8974);
946 		if (ret) {
947 			dev_err(&i2c->dev, "unable to request DRDY IRQ "
948 				"- proceeding without IRQ\n");
949 			goto no_irq;
950 		}
951 		ak8974->drdy_irq = true;
952 	}
953 
954 no_irq:
955 	ret = iio_device_register(indio_dev);
956 	if (ret) {
957 		dev_err(&i2c->dev, "device register failed\n");
958 		goto cleanup_buffer;
959 	}
960 
961 	pm_runtime_set_autosuspend_delay(&i2c->dev,
962 					 AK8974_AUTOSUSPEND_DELAY);
963 	pm_runtime_use_autosuspend(&i2c->dev);
964 	pm_runtime_put(&i2c->dev);
965 
966 	return 0;
967 
968 cleanup_buffer:
969 	iio_triggered_buffer_cleanup(indio_dev);
970 disable_pm:
971 	pm_runtime_put_noidle(&i2c->dev);
972 	pm_runtime_disable(&i2c->dev);
973 	ak8974_set_power(ak8974, AK8974_PWR_OFF);
974 	regulator_bulk_disable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
975 
976 	return ret;
977 }
978 
979 static int ak8974_remove(struct i2c_client *i2c)
980 {
981 	struct iio_dev *indio_dev = i2c_get_clientdata(i2c);
982 	struct ak8974 *ak8974 = iio_priv(indio_dev);
983 
984 	iio_device_unregister(indio_dev);
985 	iio_triggered_buffer_cleanup(indio_dev);
986 	pm_runtime_get_sync(&i2c->dev);
987 	pm_runtime_put_noidle(&i2c->dev);
988 	pm_runtime_disable(&i2c->dev);
989 	ak8974_set_power(ak8974, AK8974_PWR_OFF);
990 	regulator_bulk_disable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
991 
992 	return 0;
993 }
994 
995 static int __maybe_unused ak8974_runtime_suspend(struct device *dev)
996 {
997 	struct ak8974 *ak8974 =
998 		iio_priv(i2c_get_clientdata(to_i2c_client(dev)));
999 
1000 	ak8974_set_power(ak8974, AK8974_PWR_OFF);
1001 	regulator_bulk_disable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
1002 
1003 	return 0;
1004 }
1005 
1006 static int __maybe_unused ak8974_runtime_resume(struct device *dev)
1007 {
1008 	struct ak8974 *ak8974 =
1009 		iio_priv(i2c_get_clientdata(to_i2c_client(dev)));
1010 	int ret;
1011 
1012 	ret = regulator_bulk_enable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
1013 	if (ret)
1014 		return ret;
1015 	msleep(AK8974_POWERON_DELAY);
1016 	ret = ak8974_set_power(ak8974, AK8974_PWR_ON);
1017 	if (ret)
1018 		goto out_regulator_disable;
1019 
1020 	ret = ak8974_configure(ak8974);
1021 	if (ret)
1022 		goto out_disable_power;
1023 
1024 	return 0;
1025 
1026 out_disable_power:
1027 	ak8974_set_power(ak8974, AK8974_PWR_OFF);
1028 out_regulator_disable:
1029 	regulator_bulk_disable(ARRAY_SIZE(ak8974->regs), ak8974->regs);
1030 
1031 	return ret;
1032 }
1033 
1034 static const struct dev_pm_ops ak8974_dev_pm_ops = {
1035 	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
1036 				pm_runtime_force_resume)
1037 	SET_RUNTIME_PM_OPS(ak8974_runtime_suspend,
1038 			   ak8974_runtime_resume, NULL)
1039 };
1040 
1041 static const struct i2c_device_id ak8974_id[] = {
1042 	{"ami305", 0 },
1043 	{"ami306", 0 },
1044 	{"ak8974", 0 },
1045 	{"hscdtd008a", 0 },
1046 	{}
1047 };
1048 MODULE_DEVICE_TABLE(i2c, ak8974_id);
1049 
1050 static const struct of_device_id ak8974_of_match[] = {
1051 	{ .compatible = "asahi-kasei,ak8974", },
1052 	{ .compatible = "alps,hscdtd008a", },
1053 	{}
1054 };
1055 MODULE_DEVICE_TABLE(of, ak8974_of_match);
1056 
1057 static struct i2c_driver ak8974_driver = {
1058 	.driver	 = {
1059 		.name	= "ak8974",
1060 		.pm = &ak8974_dev_pm_ops,
1061 		.of_match_table = of_match_ptr(ak8974_of_match),
1062 	},
1063 	.probe	  = ak8974_probe,
1064 	.remove	  = ak8974_remove,
1065 	.id_table = ak8974_id,
1066 };
1067 module_i2c_driver(ak8974_driver);
1068 
1069 MODULE_DESCRIPTION("AK8974 and AMI30x 3-axis magnetometer driver");
1070 MODULE_AUTHOR("Samu Onkalo");
1071 MODULE_AUTHOR("Linus Walleij");
1072 MODULE_LICENSE("GPL v2");
1073