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