1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * A sensor driver for the magnetometer AK8975.
4  *
5  * Magnetic compass sensor driver for monitoring magnetic flux information.
6  *
7  * Copyright (c) 2010, NVIDIA Corporation.
8  */
9 
10 #include <linux/module.h>
11 #include <linux/mod_devicetable.h>
12 #include <linux/kernel.h>
13 #include <linux/slab.h>
14 #include <linux/i2c.h>
15 #include <linux/interrupt.h>
16 #include <linux/err.h>
17 #include <linux/mutex.h>
18 #include <linux/delay.h>
19 #include <linux/bitops.h>
20 #include <linux/gpio/consumer.h>
21 #include <linux/regulator/consumer.h>
22 #include <linux/pm_runtime.h>
23 
24 #include <linux/iio/iio.h>
25 #include <linux/iio/sysfs.h>
26 #include <linux/iio/buffer.h>
27 #include <linux/iio/trigger.h>
28 #include <linux/iio/trigger_consumer.h>
29 #include <linux/iio/triggered_buffer.h>
30 
31 /*
32  * Register definitions, as well as various shifts and masks to get at the
33  * individual fields of the registers.
34  */
35 #define AK8975_REG_WIA			0x00
36 #define AK8975_DEVICE_ID		0x48
37 
38 #define AK8975_REG_INFO			0x01
39 
40 #define AK8975_REG_ST1			0x02
41 #define AK8975_REG_ST1_DRDY_SHIFT	0
42 #define AK8975_REG_ST1_DRDY_MASK	(1 << AK8975_REG_ST1_DRDY_SHIFT)
43 
44 #define AK8975_REG_HXL			0x03
45 #define AK8975_REG_HXH			0x04
46 #define AK8975_REG_HYL			0x05
47 #define AK8975_REG_HYH			0x06
48 #define AK8975_REG_HZL			0x07
49 #define AK8975_REG_HZH			0x08
50 #define AK8975_REG_ST2			0x09
51 #define AK8975_REG_ST2_DERR_SHIFT	2
52 #define AK8975_REG_ST2_DERR_MASK	(1 << AK8975_REG_ST2_DERR_SHIFT)
53 
54 #define AK8975_REG_ST2_HOFL_SHIFT	3
55 #define AK8975_REG_ST2_HOFL_MASK	(1 << AK8975_REG_ST2_HOFL_SHIFT)
56 
57 #define AK8975_REG_CNTL			0x0A
58 #define AK8975_REG_CNTL_MODE_SHIFT	0
59 #define AK8975_REG_CNTL_MODE_MASK	(0xF << AK8975_REG_CNTL_MODE_SHIFT)
60 #define AK8975_REG_CNTL_MODE_POWER_DOWN	0x00
61 #define AK8975_REG_CNTL_MODE_ONCE	0x01
62 #define AK8975_REG_CNTL_MODE_SELF_TEST	0x08
63 #define AK8975_REG_CNTL_MODE_FUSE_ROM	0x0F
64 
65 #define AK8975_REG_RSVC			0x0B
66 #define AK8975_REG_ASTC			0x0C
67 #define AK8975_REG_TS1			0x0D
68 #define AK8975_REG_TS2			0x0E
69 #define AK8975_REG_I2CDIS		0x0F
70 #define AK8975_REG_ASAX			0x10
71 #define AK8975_REG_ASAY			0x11
72 #define AK8975_REG_ASAZ			0x12
73 
74 #define AK8975_MAX_REGS			AK8975_REG_ASAZ
75 
76 /*
77  * AK09912 Register definitions
78  */
79 #define AK09912_REG_WIA1		0x00
80 #define AK09912_REG_WIA2		0x01
81 #define AK09916_DEVICE_ID		0x09
82 #define AK09912_DEVICE_ID		0x04
83 #define AK09911_DEVICE_ID		0x05
84 
85 #define AK09911_REG_INFO1		0x02
86 #define AK09911_REG_INFO2		0x03
87 
88 #define AK09912_REG_ST1			0x10
89 
90 #define AK09912_REG_ST1_DRDY_SHIFT	0
91 #define AK09912_REG_ST1_DRDY_MASK	(1 << AK09912_REG_ST1_DRDY_SHIFT)
92 
93 #define AK09912_REG_HXL			0x11
94 #define AK09912_REG_HXH			0x12
95 #define AK09912_REG_HYL			0x13
96 #define AK09912_REG_HYH			0x14
97 #define AK09912_REG_HZL			0x15
98 #define AK09912_REG_HZH			0x16
99 #define AK09912_REG_TMPS		0x17
100 
101 #define AK09912_REG_ST2			0x18
102 #define AK09912_REG_ST2_HOFL_SHIFT	3
103 #define AK09912_REG_ST2_HOFL_MASK	(1 << AK09912_REG_ST2_HOFL_SHIFT)
104 
105 #define AK09912_REG_CNTL1		0x30
106 
107 #define AK09912_REG_CNTL2		0x31
108 #define AK09912_REG_CNTL_MODE_POWER_DOWN	0x00
109 #define AK09912_REG_CNTL_MODE_ONCE	0x01
110 #define AK09912_REG_CNTL_MODE_SELF_TEST	0x10
111 #define AK09912_REG_CNTL_MODE_FUSE_ROM	0x1F
112 #define AK09912_REG_CNTL2_MODE_SHIFT	0
113 #define AK09912_REG_CNTL2_MODE_MASK	(0x1F << AK09912_REG_CNTL2_MODE_SHIFT)
114 
115 #define AK09912_REG_CNTL3		0x32
116 
117 #define AK09912_REG_TS1			0x33
118 #define AK09912_REG_TS2			0x34
119 #define AK09912_REG_TS3			0x35
120 #define AK09912_REG_I2CDIS		0x36
121 #define AK09912_REG_TS4			0x37
122 
123 #define AK09912_REG_ASAX		0x60
124 #define AK09912_REG_ASAY		0x61
125 #define AK09912_REG_ASAZ		0x62
126 
127 #define AK09912_MAX_REGS		AK09912_REG_ASAZ
128 
129 /*
130  * Miscellaneous values.
131  */
132 #define AK8975_MAX_CONVERSION_TIMEOUT	500
133 #define AK8975_CONVERSION_DONE_POLL_TIME 10
134 #define AK8975_DATA_READY_TIMEOUT	((100*HZ)/1000)
135 
136 /*
137  * Precalculate scale factor (in Gauss units) for each axis and
138  * store in the device data.
139  *
140  * This scale factor is axis-dependent, and is derived from 3 calibration
141  * factors ASA(x), ASA(y), and ASA(z).
142  *
143  * These ASA values are read from the sensor device at start of day, and
144  * cached in the device context struct.
145  *
146  * Adjusting the flux value with the sensitivity adjustment value should be
147  * done via the following formula:
148  *
149  * Hadj = H * ( ( ( (ASA-128)*0.5 ) / 128 ) + 1 )
150  * where H is the raw value, ASA is the sensitivity adjustment, and Hadj
151  * is the resultant adjusted value.
152  *
153  * We reduce the formula to:
154  *
155  * Hadj = H * (ASA + 128) / 256
156  *
157  * H is in the range of -4096 to 4095.  The magnetometer has a range of
158  * +-1229uT.  To go from the raw value to uT is:
159  *
160  * HuT = H * 1229/4096, or roughly, 3/10.
161  *
162  * Since 1uT = 0.01 gauss, our final scale factor becomes:
163  *
164  * Hadj = H * ((ASA + 128) / 256) * 3/10 * 1/100
165  * Hadj = H * ((ASA + 128) * 0.003) / 256
166  *
167  * Since ASA doesn't change, we cache the resultant scale factor into the
168  * device context in ak8975_setup().
169  *
170  * Given we use IIO_VAL_INT_PLUS_MICRO bit when displaying the scale, we
171  * multiply the stored scale value by 1e6.
172  */
173 static long ak8975_raw_to_gauss(u16 data)
174 {
175 	return (((long)data + 128) * 3000) / 256;
176 }
177 
178 /*
179  * For AK8963 and AK09911, same calculation, but the device is less sensitive:
180  *
181  * H is in the range of +-8190.  The magnetometer has a range of
182  * +-4912uT.  To go from the raw value to uT is:
183  *
184  * HuT = H * 4912/8190, or roughly, 6/10, instead of 3/10.
185  */
186 
187 static long ak8963_09911_raw_to_gauss(u16 data)
188 {
189 	return (((long)data + 128) * 6000) / 256;
190 }
191 
192 /*
193  * For AK09912, same calculation, except the device is more sensitive:
194  *
195  * H is in the range of -32752 to 32752.  The magnetometer has a range of
196  * +-4912uT.  To go from the raw value to uT is:
197  *
198  * HuT = H * 4912/32752, or roughly, 3/20, instead of 3/10.
199  */
200 static long ak09912_raw_to_gauss(u16 data)
201 {
202 	return (((long)data + 128) * 1500) / 256;
203 }
204 
205 /* Compatible Asahi Kasei Compass parts */
206 enum asahi_compass_chipset {
207 	AK8975,
208 	AK8963,
209 	AK09911,
210 	AK09912,
211 	AK09916,
212 };
213 
214 enum ak_ctrl_reg_addr {
215 	ST1,
216 	ST2,
217 	CNTL,
218 	ASA_BASE,
219 	MAX_REGS,
220 	REGS_END,
221 };
222 
223 enum ak_ctrl_reg_mask {
224 	ST1_DRDY,
225 	ST2_HOFL,
226 	ST2_DERR,
227 	CNTL_MODE,
228 	MASK_END,
229 };
230 
231 enum ak_ctrl_mode {
232 	POWER_DOWN,
233 	MODE_ONCE,
234 	SELF_TEST,
235 	FUSE_ROM,
236 	MODE_END,
237 };
238 
239 struct ak_def {
240 	enum asahi_compass_chipset type;
241 	long (*raw_to_gauss)(u16 data);
242 	u16 range;
243 	u8 ctrl_regs[REGS_END];
244 	u8 ctrl_masks[MASK_END];
245 	u8 ctrl_modes[MODE_END];
246 	u8 data_regs[3];
247 };
248 
249 static const struct ak_def ak_def_array[] = {
250 	[AK8975] = {
251 		.type = AK8975,
252 		.raw_to_gauss = ak8975_raw_to_gauss,
253 		.range = 4096,
254 		.ctrl_regs = {
255 			AK8975_REG_ST1,
256 			AK8975_REG_ST2,
257 			AK8975_REG_CNTL,
258 			AK8975_REG_ASAX,
259 			AK8975_MAX_REGS},
260 		.ctrl_masks = {
261 			AK8975_REG_ST1_DRDY_MASK,
262 			AK8975_REG_ST2_HOFL_MASK,
263 			AK8975_REG_ST2_DERR_MASK,
264 			AK8975_REG_CNTL_MODE_MASK},
265 		.ctrl_modes = {
266 			AK8975_REG_CNTL_MODE_POWER_DOWN,
267 			AK8975_REG_CNTL_MODE_ONCE,
268 			AK8975_REG_CNTL_MODE_SELF_TEST,
269 			AK8975_REG_CNTL_MODE_FUSE_ROM},
270 		.data_regs = {
271 			AK8975_REG_HXL,
272 			AK8975_REG_HYL,
273 			AK8975_REG_HZL},
274 	},
275 	[AK8963] = {
276 		.type = AK8963,
277 		.raw_to_gauss = ak8963_09911_raw_to_gauss,
278 		.range = 8190,
279 		.ctrl_regs = {
280 			AK8975_REG_ST1,
281 			AK8975_REG_ST2,
282 			AK8975_REG_CNTL,
283 			AK8975_REG_ASAX,
284 			AK8975_MAX_REGS},
285 		.ctrl_masks = {
286 			AK8975_REG_ST1_DRDY_MASK,
287 			AK8975_REG_ST2_HOFL_MASK,
288 			0,
289 			AK8975_REG_CNTL_MODE_MASK},
290 		.ctrl_modes = {
291 			AK8975_REG_CNTL_MODE_POWER_DOWN,
292 			AK8975_REG_CNTL_MODE_ONCE,
293 			AK8975_REG_CNTL_MODE_SELF_TEST,
294 			AK8975_REG_CNTL_MODE_FUSE_ROM},
295 		.data_regs = {
296 			AK8975_REG_HXL,
297 			AK8975_REG_HYL,
298 			AK8975_REG_HZL},
299 	},
300 	[AK09911] = {
301 		.type = AK09911,
302 		.raw_to_gauss = ak8963_09911_raw_to_gauss,
303 		.range = 8192,
304 		.ctrl_regs = {
305 			AK09912_REG_ST1,
306 			AK09912_REG_ST2,
307 			AK09912_REG_CNTL2,
308 			AK09912_REG_ASAX,
309 			AK09912_MAX_REGS},
310 		.ctrl_masks = {
311 			AK09912_REG_ST1_DRDY_MASK,
312 			AK09912_REG_ST2_HOFL_MASK,
313 			0,
314 			AK09912_REG_CNTL2_MODE_MASK},
315 		.ctrl_modes = {
316 			AK09912_REG_CNTL_MODE_POWER_DOWN,
317 			AK09912_REG_CNTL_MODE_ONCE,
318 			AK09912_REG_CNTL_MODE_SELF_TEST,
319 			AK09912_REG_CNTL_MODE_FUSE_ROM},
320 		.data_regs = {
321 			AK09912_REG_HXL,
322 			AK09912_REG_HYL,
323 			AK09912_REG_HZL},
324 	},
325 	[AK09912] = {
326 		.type = AK09912,
327 		.raw_to_gauss = ak09912_raw_to_gauss,
328 		.range = 32752,
329 		.ctrl_regs = {
330 			AK09912_REG_ST1,
331 			AK09912_REG_ST2,
332 			AK09912_REG_CNTL2,
333 			AK09912_REG_ASAX,
334 			AK09912_MAX_REGS},
335 		.ctrl_masks = {
336 			AK09912_REG_ST1_DRDY_MASK,
337 			AK09912_REG_ST2_HOFL_MASK,
338 			0,
339 			AK09912_REG_CNTL2_MODE_MASK},
340 		.ctrl_modes = {
341 			AK09912_REG_CNTL_MODE_POWER_DOWN,
342 			AK09912_REG_CNTL_MODE_ONCE,
343 			AK09912_REG_CNTL_MODE_SELF_TEST,
344 			AK09912_REG_CNTL_MODE_FUSE_ROM},
345 		.data_regs = {
346 			AK09912_REG_HXL,
347 			AK09912_REG_HYL,
348 			AK09912_REG_HZL},
349 	},
350 	[AK09916] = {
351 		.type = AK09916,
352 		.raw_to_gauss = ak09912_raw_to_gauss,
353 		.range = 32752,
354 		.ctrl_regs = {
355 			AK09912_REG_ST1,
356 			AK09912_REG_ST2,
357 			AK09912_REG_CNTL2,
358 			AK09912_REG_ASAX,
359 			AK09912_MAX_REGS},
360 		.ctrl_masks = {
361 			AK09912_REG_ST1_DRDY_MASK,
362 			AK09912_REG_ST2_HOFL_MASK,
363 			0,
364 			AK09912_REG_CNTL2_MODE_MASK},
365 		.ctrl_modes = {
366 			AK09912_REG_CNTL_MODE_POWER_DOWN,
367 			AK09912_REG_CNTL_MODE_ONCE,
368 			AK09912_REG_CNTL_MODE_SELF_TEST,
369 			AK09912_REG_CNTL_MODE_FUSE_ROM},
370 		.data_regs = {
371 			AK09912_REG_HXL,
372 			AK09912_REG_HYL,
373 			AK09912_REG_HZL},
374 	}
375 };
376 
377 /*
378  * Per-instance context data for the device.
379  */
380 struct ak8975_data {
381 	struct i2c_client	*client;
382 	const struct ak_def	*def;
383 	struct mutex		lock;
384 	u8			asa[3];
385 	long			raw_to_gauss[3];
386 	struct gpio_desc	*eoc_gpiod;
387 	struct gpio_desc	*reset_gpiod;
388 	int			eoc_irq;
389 	wait_queue_head_t	data_ready_queue;
390 	unsigned long		flags;
391 	u8			cntl_cache;
392 	struct iio_mount_matrix orientation;
393 	struct regulator	*vdd;
394 	struct regulator	*vid;
395 
396 	/* Ensure natural alignment of timestamp */
397 	struct {
398 		s16 channels[3];
399 		s64 ts __aligned(8);
400 	} scan;
401 };
402 
403 /* Enable attached power regulator if any. */
404 static int ak8975_power_on(const struct ak8975_data *data)
405 {
406 	int ret;
407 
408 	ret = regulator_enable(data->vdd);
409 	if (ret) {
410 		dev_warn(&data->client->dev,
411 			 "Failed to enable specified Vdd supply\n");
412 		return ret;
413 	}
414 	ret = regulator_enable(data->vid);
415 	if (ret) {
416 		dev_warn(&data->client->dev,
417 			 "Failed to enable specified Vid supply\n");
418 		regulator_disable(data->vdd);
419 		return ret;
420 	}
421 
422 	gpiod_set_value_cansleep(data->reset_gpiod, 0);
423 
424 	/*
425 	 * According to the datasheet the power supply rise time is 200us
426 	 * and the minimum wait time before mode setting is 100us, in
427 	 * total 300us. Add some margin and say minimum 500us here.
428 	 */
429 	usleep_range(500, 1000);
430 	return 0;
431 }
432 
433 /* Disable attached power regulator if any. */
434 static void ak8975_power_off(const struct ak8975_data *data)
435 {
436 	gpiod_set_value_cansleep(data->reset_gpiod, 1);
437 
438 	regulator_disable(data->vid);
439 	regulator_disable(data->vdd);
440 }
441 
442 /*
443  * Return 0 if the i2c device is the one we expect.
444  * return a negative error number otherwise
445  */
446 static int ak8975_who_i_am(struct i2c_client *client,
447 			   enum asahi_compass_chipset type)
448 {
449 	u8 wia_val[2];
450 	int ret;
451 
452 	/*
453 	 * Signature for each device:
454 	 * Device   |  WIA1      |  WIA2
455 	 * AK09916  |  DEVICE_ID_|  AK09916_DEVICE_ID
456 	 * AK09912  |  DEVICE_ID |  AK09912_DEVICE_ID
457 	 * AK09911  |  DEVICE_ID |  AK09911_DEVICE_ID
458 	 * AK8975   |  DEVICE_ID |  NA
459 	 * AK8963   |  DEVICE_ID |  NA
460 	 */
461 	ret = i2c_smbus_read_i2c_block_data_or_emulated(
462 			client, AK09912_REG_WIA1, 2, wia_val);
463 	if (ret < 0) {
464 		dev_err(&client->dev, "Error reading WIA\n");
465 		return ret;
466 	}
467 
468 	if (wia_val[0] != AK8975_DEVICE_ID)
469 		return -ENODEV;
470 
471 	switch (type) {
472 	case AK8975:
473 	case AK8963:
474 		return 0;
475 	case AK09911:
476 		if (wia_val[1] == AK09911_DEVICE_ID)
477 			return 0;
478 		break;
479 	case AK09912:
480 		if (wia_val[1] == AK09912_DEVICE_ID)
481 			return 0;
482 		break;
483 	case AK09916:
484 		if (wia_val[1] == AK09916_DEVICE_ID)
485 			return 0;
486 		break;
487 	default:
488 		dev_err(&client->dev, "Type %d unknown\n", type);
489 	}
490 	return -ENODEV;
491 }
492 
493 /*
494  * Helper function to write to CNTL register.
495  */
496 static int ak8975_set_mode(struct ak8975_data *data, enum ak_ctrl_mode mode)
497 {
498 	u8 regval;
499 	int ret;
500 
501 	regval = (data->cntl_cache & ~data->def->ctrl_masks[CNTL_MODE]) |
502 		 data->def->ctrl_modes[mode];
503 	ret = i2c_smbus_write_byte_data(data->client,
504 					data->def->ctrl_regs[CNTL], regval);
505 	if (ret < 0) {
506 		return ret;
507 	}
508 	data->cntl_cache = regval;
509 	/* After mode change wait atleast 100us */
510 	usleep_range(100, 500);
511 
512 	return 0;
513 }
514 
515 /*
516  * Handle data ready irq
517  */
518 static irqreturn_t ak8975_irq_handler(int irq, void *data)
519 {
520 	struct ak8975_data *ak8975 = data;
521 
522 	set_bit(0, &ak8975->flags);
523 	wake_up(&ak8975->data_ready_queue);
524 
525 	return IRQ_HANDLED;
526 }
527 
528 /*
529  * Install data ready interrupt handler
530  */
531 static int ak8975_setup_irq(struct ak8975_data *data)
532 {
533 	struct i2c_client *client = data->client;
534 	int rc;
535 	int irq;
536 
537 	init_waitqueue_head(&data->data_ready_queue);
538 	clear_bit(0, &data->flags);
539 	if (client->irq)
540 		irq = client->irq;
541 	else
542 		irq = gpiod_to_irq(data->eoc_gpiod);
543 
544 	rc = devm_request_irq(&client->dev, irq, ak8975_irq_handler,
545 			      IRQF_TRIGGER_RISING | IRQF_ONESHOT,
546 			      dev_name(&client->dev), data);
547 	if (rc < 0) {
548 		dev_err(&client->dev, "irq %d request failed: %d\n", irq, rc);
549 		return rc;
550 	}
551 
552 	data->eoc_irq = irq;
553 
554 	return rc;
555 }
556 
557 
558 /*
559  * Perform some start-of-day setup, including reading the asa calibration
560  * values and caching them.
561  */
562 static int ak8975_setup(struct i2c_client *client)
563 {
564 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
565 	struct ak8975_data *data = iio_priv(indio_dev);
566 	int ret;
567 
568 	/* Write the fused rom access mode. */
569 	ret = ak8975_set_mode(data, FUSE_ROM);
570 	if (ret < 0) {
571 		dev_err(&client->dev, "Error in setting fuse access mode\n");
572 		return ret;
573 	}
574 
575 	/* Get asa data and store in the device data. */
576 	ret = i2c_smbus_read_i2c_block_data_or_emulated(
577 			client, data->def->ctrl_regs[ASA_BASE],
578 			3, data->asa);
579 	if (ret < 0) {
580 		dev_err(&client->dev, "Not able to read asa data\n");
581 		return ret;
582 	}
583 
584 	/* After reading fuse ROM data set power-down mode */
585 	ret = ak8975_set_mode(data, POWER_DOWN);
586 	if (ret < 0) {
587 		dev_err(&client->dev, "Error in setting power-down mode\n");
588 		return ret;
589 	}
590 
591 	if (data->eoc_gpiod || client->irq > 0) {
592 		ret = ak8975_setup_irq(data);
593 		if (ret < 0) {
594 			dev_err(&client->dev,
595 				"Error setting data ready interrupt\n");
596 			return ret;
597 		}
598 	}
599 
600 	data->raw_to_gauss[0] = data->def->raw_to_gauss(data->asa[0]);
601 	data->raw_to_gauss[1] = data->def->raw_to_gauss(data->asa[1]);
602 	data->raw_to_gauss[2] = data->def->raw_to_gauss(data->asa[2]);
603 
604 	return 0;
605 }
606 
607 static int wait_conversion_complete_gpio(struct ak8975_data *data)
608 {
609 	struct i2c_client *client = data->client;
610 	u32 timeout_ms = AK8975_MAX_CONVERSION_TIMEOUT;
611 	int ret;
612 
613 	/* Wait for the conversion to complete. */
614 	while (timeout_ms) {
615 		msleep(AK8975_CONVERSION_DONE_POLL_TIME);
616 		if (gpiod_get_value(data->eoc_gpiod))
617 			break;
618 		timeout_ms -= AK8975_CONVERSION_DONE_POLL_TIME;
619 	}
620 	if (!timeout_ms) {
621 		dev_err(&client->dev, "Conversion timeout happened\n");
622 		return -EINVAL;
623 	}
624 
625 	ret = i2c_smbus_read_byte_data(client, data->def->ctrl_regs[ST1]);
626 	if (ret < 0)
627 		dev_err(&client->dev, "Error in reading ST1\n");
628 
629 	return ret;
630 }
631 
632 static int wait_conversion_complete_polled(struct ak8975_data *data)
633 {
634 	struct i2c_client *client = data->client;
635 	u8 read_status;
636 	u32 timeout_ms = AK8975_MAX_CONVERSION_TIMEOUT;
637 	int ret;
638 
639 	/* Wait for the conversion to complete. */
640 	while (timeout_ms) {
641 		msleep(AK8975_CONVERSION_DONE_POLL_TIME);
642 		ret = i2c_smbus_read_byte_data(client,
643 					       data->def->ctrl_regs[ST1]);
644 		if (ret < 0) {
645 			dev_err(&client->dev, "Error in reading ST1\n");
646 			return ret;
647 		}
648 		read_status = ret;
649 		if (read_status)
650 			break;
651 		timeout_ms -= AK8975_CONVERSION_DONE_POLL_TIME;
652 	}
653 	if (!timeout_ms) {
654 		dev_err(&client->dev, "Conversion timeout happened\n");
655 		return -EINVAL;
656 	}
657 
658 	return read_status;
659 }
660 
661 /* Returns 0 if the end of conversion interrupt occured or -ETIME otherwise */
662 static int wait_conversion_complete_interrupt(struct ak8975_data *data)
663 {
664 	int ret;
665 
666 	ret = wait_event_timeout(data->data_ready_queue,
667 				 test_bit(0, &data->flags),
668 				 AK8975_DATA_READY_TIMEOUT);
669 	clear_bit(0, &data->flags);
670 
671 	return ret > 0 ? 0 : -ETIME;
672 }
673 
674 static int ak8975_start_read_axis(struct ak8975_data *data,
675 				  const struct i2c_client *client)
676 {
677 	/* Set up the device for taking a sample. */
678 	int ret = ak8975_set_mode(data, MODE_ONCE);
679 
680 	if (ret < 0) {
681 		dev_err(&client->dev, "Error in setting operating mode\n");
682 		return ret;
683 	}
684 
685 	/* Wait for the conversion to complete. */
686 	if (data->eoc_irq)
687 		ret = wait_conversion_complete_interrupt(data);
688 	else if (data->eoc_gpiod)
689 		ret = wait_conversion_complete_gpio(data);
690 	else
691 		ret = wait_conversion_complete_polled(data);
692 	if (ret < 0)
693 		return ret;
694 
695 	/* Return with zero if the data is ready. */
696 	return !data->def->ctrl_regs[ST1_DRDY];
697 }
698 
699 /* Retrieve raw flux value for one of the x, y, or z axis.  */
700 static int ak8975_read_axis(struct iio_dev *indio_dev, int index, int *val)
701 {
702 	struct ak8975_data *data = iio_priv(indio_dev);
703 	const struct i2c_client *client = data->client;
704 	const struct ak_def *def = data->def;
705 	__le16 rval;
706 	u16 buff;
707 	int ret;
708 
709 	pm_runtime_get_sync(&data->client->dev);
710 
711 	mutex_lock(&data->lock);
712 
713 	ret = ak8975_start_read_axis(data, client);
714 	if (ret)
715 		goto exit;
716 
717 	ret = i2c_smbus_read_i2c_block_data_or_emulated(
718 			client, def->data_regs[index],
719 			sizeof(rval), (u8*)&rval);
720 	if (ret < 0)
721 		goto exit;
722 
723 	/* Read out ST2 for release lock on measurment data. */
724 	ret = i2c_smbus_read_byte_data(client, data->def->ctrl_regs[ST2]);
725 	if (ret < 0) {
726 		dev_err(&client->dev, "Error in reading ST2\n");
727 		goto exit;
728 	}
729 
730 	if (ret & (data->def->ctrl_masks[ST2_DERR] |
731 		   data->def->ctrl_masks[ST2_HOFL])) {
732 		dev_err(&client->dev, "ST2 status error 0x%x\n", ret);
733 		ret = -EINVAL;
734 		goto exit;
735 	}
736 
737 	mutex_unlock(&data->lock);
738 
739 	pm_runtime_mark_last_busy(&data->client->dev);
740 	pm_runtime_put_autosuspend(&data->client->dev);
741 
742 	/* Swap bytes and convert to valid range. */
743 	buff = le16_to_cpu(rval);
744 	*val = clamp_t(s16, buff, -def->range, def->range);
745 	return IIO_VAL_INT;
746 
747 exit:
748 	mutex_unlock(&data->lock);
749 	dev_err(&client->dev, "Error in reading axis\n");
750 	return ret;
751 }
752 
753 static int ak8975_read_raw(struct iio_dev *indio_dev,
754 			   struct iio_chan_spec const *chan,
755 			   int *val, int *val2,
756 			   long mask)
757 {
758 	struct ak8975_data *data = iio_priv(indio_dev);
759 
760 	switch (mask) {
761 	case IIO_CHAN_INFO_RAW:
762 		return ak8975_read_axis(indio_dev, chan->address, val);
763 	case IIO_CHAN_INFO_SCALE:
764 		*val = 0;
765 		*val2 = data->raw_to_gauss[chan->address];
766 		return IIO_VAL_INT_PLUS_MICRO;
767 	}
768 	return -EINVAL;
769 }
770 
771 static const struct iio_mount_matrix *
772 ak8975_get_mount_matrix(const struct iio_dev *indio_dev,
773 			const struct iio_chan_spec *chan)
774 {
775 	struct ak8975_data *data = iio_priv(indio_dev);
776 
777 	return &data->orientation;
778 }
779 
780 static const struct iio_chan_spec_ext_info ak8975_ext_info[] = {
781 	IIO_MOUNT_MATRIX(IIO_SHARED_BY_DIR, ak8975_get_mount_matrix),
782 	{ }
783 };
784 
785 #define AK8975_CHANNEL(axis, index)					\
786 	{								\
787 		.type = IIO_MAGN,					\
788 		.modified = 1,						\
789 		.channel2 = IIO_MOD_##axis,				\
790 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |		\
791 			     BIT(IIO_CHAN_INFO_SCALE),			\
792 		.address = index,					\
793 		.scan_index = index,					\
794 		.scan_type = {						\
795 			.sign = 's',					\
796 			.realbits = 16,					\
797 			.storagebits = 16,				\
798 			.endianness = IIO_CPU				\
799 		},							\
800 		.ext_info = ak8975_ext_info,				\
801 	}
802 
803 static const struct iio_chan_spec ak8975_channels[] = {
804 	AK8975_CHANNEL(X, 0), AK8975_CHANNEL(Y, 1), AK8975_CHANNEL(Z, 2),
805 	IIO_CHAN_SOFT_TIMESTAMP(3),
806 };
807 
808 static const unsigned long ak8975_scan_masks[] = { 0x7, 0 };
809 
810 static const struct iio_info ak8975_info = {
811 	.read_raw = &ak8975_read_raw,
812 };
813 
814 static const struct acpi_device_id ak_acpi_match[] = {
815 	{"AK8975", (kernel_ulong_t)&ak_def_array[AK8975] },
816 	{"AK8963", (kernel_ulong_t)&ak_def_array[AK8963] },
817 	{"INVN6500", (kernel_ulong_t)&ak_def_array[AK8963] },
818 	{"AK009911", (kernel_ulong_t)&ak_def_array[AK09911] },
819 	{"AK09911", (kernel_ulong_t)&ak_def_array[AK09911] },
820 	{"AKM9911", (kernel_ulong_t)&ak_def_array[AK09911] },
821 	{"AK09912", (kernel_ulong_t)&ak_def_array[AK09912] },
822 	{ }
823 };
824 MODULE_DEVICE_TABLE(acpi, ak_acpi_match);
825 
826 static void ak8975_fill_buffer(struct iio_dev *indio_dev)
827 {
828 	struct ak8975_data *data = iio_priv(indio_dev);
829 	const struct i2c_client *client = data->client;
830 	const struct ak_def *def = data->def;
831 	int ret;
832 	__le16 fval[3];
833 
834 	mutex_lock(&data->lock);
835 
836 	ret = ak8975_start_read_axis(data, client);
837 	if (ret)
838 		goto unlock;
839 
840 	/*
841 	 * For each axis, read the flux value from the appropriate register
842 	 * (the register is specified in the iio device attributes).
843 	 */
844 	ret = i2c_smbus_read_i2c_block_data_or_emulated(client,
845 							def->data_regs[0],
846 							3 * sizeof(fval[0]),
847 							(u8 *)fval);
848 	if (ret < 0)
849 		goto unlock;
850 
851 	mutex_unlock(&data->lock);
852 
853 	/* Clamp to valid range. */
854 	data->scan.channels[0] = clamp_t(s16, le16_to_cpu(fval[0]), -def->range, def->range);
855 	data->scan.channels[1] = clamp_t(s16, le16_to_cpu(fval[1]), -def->range, def->range);
856 	data->scan.channels[2] = clamp_t(s16, le16_to_cpu(fval[2]), -def->range, def->range);
857 
858 	iio_push_to_buffers_with_timestamp(indio_dev, &data->scan,
859 					   iio_get_time_ns(indio_dev));
860 
861 	return;
862 
863 unlock:
864 	mutex_unlock(&data->lock);
865 	dev_err(&client->dev, "Error in reading axes block\n");
866 }
867 
868 static irqreturn_t ak8975_handle_trigger(int irq, void *p)
869 {
870 	const struct iio_poll_func *pf = p;
871 	struct iio_dev *indio_dev = pf->indio_dev;
872 
873 	ak8975_fill_buffer(indio_dev);
874 	iio_trigger_notify_done(indio_dev->trig);
875 	return IRQ_HANDLED;
876 }
877 
878 static int ak8975_probe(struct i2c_client *client)
879 {
880 	const struct i2c_device_id *id = i2c_client_get_device_id(client);
881 	struct ak8975_data *data;
882 	struct iio_dev *indio_dev;
883 	struct gpio_desc *eoc_gpiod;
884 	struct gpio_desc *reset_gpiod;
885 	int err;
886 	const char *name = NULL;
887 
888 	/*
889 	 * Grab and set up the supplied GPIO.
890 	 * We may not have a GPIO based IRQ to scan, that is fine, we will
891 	 * poll if so.
892 	 */
893 	eoc_gpiod = devm_gpiod_get_optional(&client->dev, NULL, GPIOD_IN);
894 	if (IS_ERR(eoc_gpiod))
895 		return PTR_ERR(eoc_gpiod);
896 	if (eoc_gpiod)
897 		gpiod_set_consumer_name(eoc_gpiod, "ak_8975");
898 
899 	/*
900 	 * According to AK09911 datasheet, if reset GPIO is provided then
901 	 * deassert reset on ak8975_power_on() and assert reset on
902 	 * ak8975_power_off().
903 	 */
904 	reset_gpiod = devm_gpiod_get_optional(&client->dev,
905 					      "reset", GPIOD_OUT_HIGH);
906 	if (IS_ERR(reset_gpiod))
907 		return PTR_ERR(reset_gpiod);
908 
909 	/* Register with IIO */
910 	indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
911 	if (indio_dev == NULL)
912 		return -ENOMEM;
913 
914 	data = iio_priv(indio_dev);
915 	i2c_set_clientdata(client, indio_dev);
916 
917 	data->client = client;
918 	data->eoc_gpiod = eoc_gpiod;
919 	data->reset_gpiod = reset_gpiod;
920 	data->eoc_irq = 0;
921 
922 	err = iio_read_mount_matrix(&client->dev, &data->orientation);
923 	if (err)
924 		return err;
925 
926 	/* id will be NULL when enumerated via ACPI */
927 	data->def = i2c_get_match_data(client);
928 	if (!data->def)
929 		return -ENODEV;
930 
931 	/* If enumerated via firmware node, fix the ABI */
932 	if (dev_fwnode(&client->dev))
933 		name = dev_name(&client->dev);
934 	else
935 		name = id->name;
936 
937 	/* Fetch the regulators */
938 	data->vdd = devm_regulator_get(&client->dev, "vdd");
939 	if (IS_ERR(data->vdd))
940 		return PTR_ERR(data->vdd);
941 	data->vid = devm_regulator_get(&client->dev, "vid");
942 	if (IS_ERR(data->vid))
943 		return PTR_ERR(data->vid);
944 
945 	err = ak8975_power_on(data);
946 	if (err)
947 		return err;
948 
949 	err = ak8975_who_i_am(client, data->def->type);
950 	if (err < 0) {
951 		dev_err(&client->dev, "Unexpected device\n");
952 		goto power_off;
953 	}
954 	dev_dbg(&client->dev, "Asahi compass chip %s\n", name);
955 
956 	/* Perform some basic start-of-day setup of the device. */
957 	err = ak8975_setup(client);
958 	if (err < 0) {
959 		dev_err(&client->dev, "%s initialization fails\n", name);
960 		goto power_off;
961 	}
962 
963 	mutex_init(&data->lock);
964 	indio_dev->channels = ak8975_channels;
965 	indio_dev->num_channels = ARRAY_SIZE(ak8975_channels);
966 	indio_dev->info = &ak8975_info;
967 	indio_dev->available_scan_masks = ak8975_scan_masks;
968 	indio_dev->modes = INDIO_DIRECT_MODE;
969 	indio_dev->name = name;
970 
971 	err = iio_triggered_buffer_setup(indio_dev, NULL, ak8975_handle_trigger,
972 					 NULL);
973 	if (err) {
974 		dev_err(&client->dev, "triggered buffer setup failed\n");
975 		goto power_off;
976 	}
977 
978 	err = iio_device_register(indio_dev);
979 	if (err) {
980 		dev_err(&client->dev, "device register failed\n");
981 		goto cleanup_buffer;
982 	}
983 
984 	/* Enable runtime PM */
985 	pm_runtime_get_noresume(&client->dev);
986 	pm_runtime_set_active(&client->dev);
987 	pm_runtime_enable(&client->dev);
988 	/*
989 	 * The device comes online in 500us, so add two orders of magnitude
990 	 * of delay before autosuspending: 50 ms.
991 	 */
992 	pm_runtime_set_autosuspend_delay(&client->dev, 50);
993 	pm_runtime_use_autosuspend(&client->dev);
994 	pm_runtime_put(&client->dev);
995 
996 	return 0;
997 
998 cleanup_buffer:
999 	iio_triggered_buffer_cleanup(indio_dev);
1000 power_off:
1001 	ak8975_power_off(data);
1002 	return err;
1003 }
1004 
1005 static void ak8975_remove(struct i2c_client *client)
1006 {
1007 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
1008 	struct ak8975_data *data = iio_priv(indio_dev);
1009 
1010 	pm_runtime_get_sync(&client->dev);
1011 	pm_runtime_put_noidle(&client->dev);
1012 	pm_runtime_disable(&client->dev);
1013 	iio_device_unregister(indio_dev);
1014 	iio_triggered_buffer_cleanup(indio_dev);
1015 	ak8975_set_mode(data, POWER_DOWN);
1016 	ak8975_power_off(data);
1017 }
1018 
1019 static int ak8975_runtime_suspend(struct device *dev)
1020 {
1021 	struct i2c_client *client = to_i2c_client(dev);
1022 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
1023 	struct ak8975_data *data = iio_priv(indio_dev);
1024 	int ret;
1025 
1026 	/* Set the device in power down if it wasn't already */
1027 	ret = ak8975_set_mode(data, POWER_DOWN);
1028 	if (ret < 0) {
1029 		dev_err(&client->dev, "Error in setting power-down mode\n");
1030 		return ret;
1031 	}
1032 	/* Next cut the regulators */
1033 	ak8975_power_off(data);
1034 
1035 	return 0;
1036 }
1037 
1038 static int ak8975_runtime_resume(struct device *dev)
1039 {
1040 	struct i2c_client *client = to_i2c_client(dev);
1041 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
1042 	struct ak8975_data *data = iio_priv(indio_dev);
1043 	int ret;
1044 
1045 	/* Take up the regulators */
1046 	ak8975_power_on(data);
1047 	/*
1048 	 * We come up in powered down mode, the reading routines will
1049 	 * put us in the mode to read values later.
1050 	 */
1051 	ret = ak8975_set_mode(data, POWER_DOWN);
1052 	if (ret < 0) {
1053 		dev_err(&client->dev, "Error in setting power-down mode\n");
1054 		return ret;
1055 	}
1056 
1057 	return 0;
1058 }
1059 
1060 static DEFINE_RUNTIME_DEV_PM_OPS(ak8975_dev_pm_ops, ak8975_runtime_suspend,
1061 				 ak8975_runtime_resume, NULL);
1062 
1063 static const struct i2c_device_id ak8975_id[] = {
1064 	{"ak8975", (kernel_ulong_t)&ak_def_array[AK8975] },
1065 	{"ak8963", (kernel_ulong_t)&ak_def_array[AK8963] },
1066 	{"AK8963", (kernel_ulong_t)&ak_def_array[AK8963] },
1067 	{"ak09911", (kernel_ulong_t)&ak_def_array[AK09911] },
1068 	{"ak09912", (kernel_ulong_t)&ak_def_array[AK09912] },
1069 	{"ak09916", (kernel_ulong_t)&ak_def_array[AK09916] },
1070 	{}
1071 };
1072 
1073 MODULE_DEVICE_TABLE(i2c, ak8975_id);
1074 
1075 static const struct of_device_id ak8975_of_match[] = {
1076 	{ .compatible = "asahi-kasei,ak8975", .data = &ak_def_array[AK8975] },
1077 	{ .compatible = "ak8975", .data = &ak_def_array[AK8975] },
1078 	{ .compatible = "asahi-kasei,ak8963", .data = &ak_def_array[AK8963] },
1079 	{ .compatible = "ak8963", .data = &ak_def_array[AK8963] },
1080 	{ .compatible = "asahi-kasei,ak09911", .data = &ak_def_array[AK09911] },
1081 	{ .compatible = "ak09911", .data = &ak_def_array[AK09911] },
1082 	{ .compatible = "asahi-kasei,ak09912", .data = &ak_def_array[AK09912] },
1083 	{ .compatible = "ak09912", .data = &ak_def_array[AK09912] },
1084 	{ .compatible = "asahi-kasei,ak09916", .data = &ak_def_array[AK09916] },
1085 	{}
1086 };
1087 MODULE_DEVICE_TABLE(of, ak8975_of_match);
1088 
1089 static struct i2c_driver ak8975_driver = {
1090 	.driver = {
1091 		.name	= "ak8975",
1092 		.pm = pm_ptr(&ak8975_dev_pm_ops),
1093 		.of_match_table = ak8975_of_match,
1094 		.acpi_match_table = ak_acpi_match,
1095 	},
1096 	.probe		= ak8975_probe,
1097 	.remove		= ak8975_remove,
1098 	.id_table	= ak8975_id,
1099 };
1100 module_i2c_driver(ak8975_driver);
1101 
1102 MODULE_AUTHOR("Laxman Dewangan <ldewangan@nvidia.com>");
1103 MODULE_DESCRIPTION("AK8975 magnetometer driver");
1104 MODULE_LICENSE("GPL");
1105