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