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