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