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 	AKXXXX		= 0,
208 	AK8975,
209 	AK8963,
210 	AK09911,
211 	AK09912,
212 	AK09916,
213 };
214 
215 enum ak_ctrl_reg_addr {
216 	ST1,
217 	ST2,
218 	CNTL,
219 	ASA_BASE,
220 	MAX_REGS,
221 	REGS_END,
222 };
223 
224 enum ak_ctrl_reg_mask {
225 	ST1_DRDY,
226 	ST2_HOFL,
227 	ST2_DERR,
228 	CNTL_MODE,
229 	MASK_END,
230 };
231 
232 enum ak_ctrl_mode {
233 	POWER_DOWN,
234 	MODE_ONCE,
235 	SELF_TEST,
236 	FUSE_ROM,
237 	MODE_END,
238 };
239 
240 struct ak_def {
241 	enum asahi_compass_chipset type;
242 	long (*raw_to_gauss)(u16 data);
243 	u16 range;
244 	u8 ctrl_regs[REGS_END];
245 	u8 ctrl_masks[MASK_END];
246 	u8 ctrl_modes[MODE_END];
247 	u8 data_regs[3];
248 };
249 
250 static const struct ak_def ak_def_array[] = {
251 	{
252 		.type = AK8975,
253 		.raw_to_gauss = ak8975_raw_to_gauss,
254 		.range = 4096,
255 		.ctrl_regs = {
256 			AK8975_REG_ST1,
257 			AK8975_REG_ST2,
258 			AK8975_REG_CNTL,
259 			AK8975_REG_ASAX,
260 			AK8975_MAX_REGS},
261 		.ctrl_masks = {
262 			AK8975_REG_ST1_DRDY_MASK,
263 			AK8975_REG_ST2_HOFL_MASK,
264 			AK8975_REG_ST2_DERR_MASK,
265 			AK8975_REG_CNTL_MODE_MASK},
266 		.ctrl_modes = {
267 			AK8975_REG_CNTL_MODE_POWER_DOWN,
268 			AK8975_REG_CNTL_MODE_ONCE,
269 			AK8975_REG_CNTL_MODE_SELF_TEST,
270 			AK8975_REG_CNTL_MODE_FUSE_ROM},
271 		.data_regs = {
272 			AK8975_REG_HXL,
273 			AK8975_REG_HYL,
274 			AK8975_REG_HZL},
275 	},
276 	{
277 		.type = AK8963,
278 		.raw_to_gauss = ak8963_09911_raw_to_gauss,
279 		.range = 8190,
280 		.ctrl_regs = {
281 			AK8975_REG_ST1,
282 			AK8975_REG_ST2,
283 			AK8975_REG_CNTL,
284 			AK8975_REG_ASAX,
285 			AK8975_MAX_REGS},
286 		.ctrl_masks = {
287 			AK8975_REG_ST1_DRDY_MASK,
288 			AK8975_REG_ST2_HOFL_MASK,
289 			0,
290 			AK8975_REG_CNTL_MODE_MASK},
291 		.ctrl_modes = {
292 			AK8975_REG_CNTL_MODE_POWER_DOWN,
293 			AK8975_REG_CNTL_MODE_ONCE,
294 			AK8975_REG_CNTL_MODE_SELF_TEST,
295 			AK8975_REG_CNTL_MODE_FUSE_ROM},
296 		.data_regs = {
297 			AK8975_REG_HXL,
298 			AK8975_REG_HYL,
299 			AK8975_REG_HZL},
300 	},
301 	{
302 		.type = AK09911,
303 		.raw_to_gauss = ak8963_09911_raw_to_gauss,
304 		.range = 8192,
305 		.ctrl_regs = {
306 			AK09912_REG_ST1,
307 			AK09912_REG_ST2,
308 			AK09912_REG_CNTL2,
309 			AK09912_REG_ASAX,
310 			AK09912_MAX_REGS},
311 		.ctrl_masks = {
312 			AK09912_REG_ST1_DRDY_MASK,
313 			AK09912_REG_ST2_HOFL_MASK,
314 			0,
315 			AK09912_REG_CNTL2_MODE_MASK},
316 		.ctrl_modes = {
317 			AK09912_REG_CNTL_MODE_POWER_DOWN,
318 			AK09912_REG_CNTL_MODE_ONCE,
319 			AK09912_REG_CNTL_MODE_SELF_TEST,
320 			AK09912_REG_CNTL_MODE_FUSE_ROM},
321 		.data_regs = {
322 			AK09912_REG_HXL,
323 			AK09912_REG_HYL,
324 			AK09912_REG_HZL},
325 	},
326 	{
327 		.type = AK09912,
328 		.raw_to_gauss = ak09912_raw_to_gauss,
329 		.range = 32752,
330 		.ctrl_regs = {
331 			AK09912_REG_ST1,
332 			AK09912_REG_ST2,
333 			AK09912_REG_CNTL2,
334 			AK09912_REG_ASAX,
335 			AK09912_MAX_REGS},
336 		.ctrl_masks = {
337 			AK09912_REG_ST1_DRDY_MASK,
338 			AK09912_REG_ST2_HOFL_MASK,
339 			0,
340 			AK09912_REG_CNTL2_MODE_MASK},
341 		.ctrl_modes = {
342 			AK09912_REG_CNTL_MODE_POWER_DOWN,
343 			AK09912_REG_CNTL_MODE_ONCE,
344 			AK09912_REG_CNTL_MODE_SELF_TEST,
345 			AK09912_REG_CNTL_MODE_FUSE_ROM},
346 		.data_regs = {
347 			AK09912_REG_HXL,
348 			AK09912_REG_HYL,
349 			AK09912_REG_HZL},
350 	},
351 	{
352 		.type = AK09916,
353 		.raw_to_gauss = ak09912_raw_to_gauss,
354 		.range = 32752,
355 		.ctrl_regs = {
356 			AK09912_REG_ST1,
357 			AK09912_REG_ST2,
358 			AK09912_REG_CNTL2,
359 			AK09912_REG_ASAX,
360 			AK09912_MAX_REGS},
361 		.ctrl_masks = {
362 			AK09912_REG_ST1_DRDY_MASK,
363 			AK09912_REG_ST2_HOFL_MASK,
364 			0,
365 			AK09912_REG_CNTL2_MODE_MASK},
366 		.ctrl_modes = {
367 			AK09912_REG_CNTL_MODE_POWER_DOWN,
368 			AK09912_REG_CNTL_MODE_ONCE,
369 			AK09912_REG_CNTL_MODE_SELF_TEST,
370 			AK09912_REG_CNTL_MODE_FUSE_ROM},
371 		.data_regs = {
372 			AK09912_REG_HXL,
373 			AK09912_REG_HYL,
374 			AK09912_REG_HZL},
375 	}
376 };
377 
378 /*
379  * Per-instance context data for the device.
380  */
381 struct ak8975_data {
382 	struct i2c_client	*client;
383 	const struct ak_def	*def;
384 	struct mutex		lock;
385 	u8			asa[3];
386 	long			raw_to_gauss[3];
387 	struct gpio_desc	*eoc_gpiod;
388 	struct gpio_desc	*reset_gpiod;
389 	int			eoc_irq;
390 	wait_queue_head_t	data_ready_queue;
391 	unsigned long		flags;
392 	u8			cntl_cache;
393 	struct iio_mount_matrix orientation;
394 	struct regulator	*vdd;
395 	struct regulator	*vid;
396 
397 	/* Ensure natural alignment of timestamp */
398 	struct {
399 		s16 channels[3];
400 		s64 ts __aligned(8);
401 	} scan;
402 };
403 
404 /* Enable attached power regulator if any. */
405 static int ak8975_power_on(const struct ak8975_data *data)
406 {
407 	int ret;
408 
409 	ret = regulator_enable(data->vdd);
410 	if (ret) {
411 		dev_warn(&data->client->dev,
412 			 "Failed to enable specified Vdd supply\n");
413 		return ret;
414 	}
415 	ret = regulator_enable(data->vid);
416 	if (ret) {
417 		dev_warn(&data->client->dev,
418 			 "Failed to enable specified Vid supply\n");
419 		regulator_disable(data->vdd);
420 		return ret;
421 	}
422 
423 	gpiod_set_value_cansleep(data->reset_gpiod, 0);
424 
425 	/*
426 	 * According to the datasheet the power supply rise time is 200us
427 	 * and the minimum wait time before mode setting is 100us, in
428 	 * total 300us. Add some margin and say minimum 500us here.
429 	 */
430 	usleep_range(500, 1000);
431 	return 0;
432 }
433 
434 /* Disable attached power regulator if any. */
435 static void ak8975_power_off(const struct ak8975_data *data)
436 {
437 	gpiod_set_value_cansleep(data->reset_gpiod, 1);
438 
439 	regulator_disable(data->vid);
440 	regulator_disable(data->vdd);
441 }
442 
443 /*
444  * Return 0 if the i2c device is the one we expect.
445  * return a negative error number otherwise
446  */
447 static int ak8975_who_i_am(struct i2c_client *client,
448 			   enum asahi_compass_chipset type)
449 {
450 	u8 wia_val[2];
451 	int ret;
452 
453 	/*
454 	 * Signature for each device:
455 	 * Device   |  WIA1      |  WIA2
456 	 * AK09916  |  DEVICE_ID_|  AK09916_DEVICE_ID
457 	 * AK09912  |  DEVICE_ID |  AK09912_DEVICE_ID
458 	 * AK09911  |  DEVICE_ID |  AK09911_DEVICE_ID
459 	 * AK8975   |  DEVICE_ID |  NA
460 	 * AK8963   |  DEVICE_ID |  NA
461 	 */
462 	ret = i2c_smbus_read_i2c_block_data_or_emulated(
463 			client, AK09912_REG_WIA1, 2, wia_val);
464 	if (ret < 0) {
465 		dev_err(&client->dev, "Error reading WIA\n");
466 		return ret;
467 	}
468 
469 	if (wia_val[0] != AK8975_DEVICE_ID)
470 		return -ENODEV;
471 
472 	switch (type) {
473 	case AK8975:
474 	case AK8963:
475 		return 0;
476 	case AK09911:
477 		if (wia_val[1] == AK09911_DEVICE_ID)
478 			return 0;
479 		break;
480 	case AK09912:
481 		if (wia_val[1] == AK09912_DEVICE_ID)
482 			return 0;
483 		break;
484 	case AK09916:
485 		if (wia_val[1] == AK09916_DEVICE_ID)
486 			return 0;
487 		break;
488 	default:
489 		dev_err(&client->dev, "Type %d unknown\n", type);
490 	}
491 	return -ENODEV;
492 }
493 
494 /*
495  * Helper function to write to CNTL register.
496  */
497 static int ak8975_set_mode(struct ak8975_data *data, enum ak_ctrl_mode mode)
498 {
499 	u8 regval;
500 	int ret;
501 
502 	regval = (data->cntl_cache & ~data->def->ctrl_masks[CNTL_MODE]) |
503 		 data->def->ctrl_modes[mode];
504 	ret = i2c_smbus_write_byte_data(data->client,
505 					data->def->ctrl_regs[CNTL], regval);
506 	if (ret < 0) {
507 		return ret;
508 	}
509 	data->cntl_cache = regval;
510 	/* After mode change wait atleast 100us */
511 	usleep_range(100, 500);
512 
513 	return 0;
514 }
515 
516 /*
517  * Handle data ready irq
518  */
519 static irqreturn_t ak8975_irq_handler(int irq, void *data)
520 {
521 	struct ak8975_data *ak8975 = data;
522 
523 	set_bit(0, &ak8975->flags);
524 	wake_up(&ak8975->data_ready_queue);
525 
526 	return IRQ_HANDLED;
527 }
528 
529 /*
530  * Install data ready interrupt handler
531  */
532 static int ak8975_setup_irq(struct ak8975_data *data)
533 {
534 	struct i2c_client *client = data->client;
535 	int rc;
536 	int irq;
537 
538 	init_waitqueue_head(&data->data_ready_queue);
539 	clear_bit(0, &data->flags);
540 	if (client->irq)
541 		irq = client->irq;
542 	else
543 		irq = gpiod_to_irq(data->eoc_gpiod);
544 
545 	rc = devm_request_irq(&client->dev, irq, ak8975_irq_handler,
546 			      IRQF_TRIGGER_RISING | IRQF_ONESHOT,
547 			      dev_name(&client->dev), data);
548 	if (rc < 0) {
549 		dev_err(&client->dev, "irq %d request failed: %d\n", irq, rc);
550 		return rc;
551 	}
552 
553 	data->eoc_irq = irq;
554 
555 	return rc;
556 }
557 
558 
559 /*
560  * Perform some start-of-day setup, including reading the asa calibration
561  * values and caching them.
562  */
563 static int ak8975_setup(struct i2c_client *client)
564 {
565 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
566 	struct ak8975_data *data = iio_priv(indio_dev);
567 	int ret;
568 
569 	/* Write the fused rom access mode. */
570 	ret = ak8975_set_mode(data, FUSE_ROM);
571 	if (ret < 0) {
572 		dev_err(&client->dev, "Error in setting fuse access mode\n");
573 		return ret;
574 	}
575 
576 	/* Get asa data and store in the device data. */
577 	ret = i2c_smbus_read_i2c_block_data_or_emulated(
578 			client, data->def->ctrl_regs[ASA_BASE],
579 			3, data->asa);
580 	if (ret < 0) {
581 		dev_err(&client->dev, "Not able to read asa data\n");
582 		return ret;
583 	}
584 
585 	/* After reading fuse ROM data set power-down mode */
586 	ret = ak8975_set_mode(data, POWER_DOWN);
587 	if (ret < 0) {
588 		dev_err(&client->dev, "Error in setting power-down mode\n");
589 		return ret;
590 	}
591 
592 	if (data->eoc_gpiod || client->irq > 0) {
593 		ret = ak8975_setup_irq(data);
594 		if (ret < 0) {
595 			dev_err(&client->dev,
596 				"Error setting data ready interrupt\n");
597 			return ret;
598 		}
599 	}
600 
601 	data->raw_to_gauss[0] = data->def->raw_to_gauss(data->asa[0]);
602 	data->raw_to_gauss[1] = data->def->raw_to_gauss(data->asa[1]);
603 	data->raw_to_gauss[2] = data->def->raw_to_gauss(data->asa[2]);
604 
605 	return 0;
606 }
607 
608 static int wait_conversion_complete_gpio(struct ak8975_data *data)
609 {
610 	struct i2c_client *client = data->client;
611 	u32 timeout_ms = AK8975_MAX_CONVERSION_TIMEOUT;
612 	int ret;
613 
614 	/* Wait for the conversion to complete. */
615 	while (timeout_ms) {
616 		msleep(AK8975_CONVERSION_DONE_POLL_TIME);
617 		if (gpiod_get_value(data->eoc_gpiod))
618 			break;
619 		timeout_ms -= AK8975_CONVERSION_DONE_POLL_TIME;
620 	}
621 	if (!timeout_ms) {
622 		dev_err(&client->dev, "Conversion timeout happened\n");
623 		return -EINVAL;
624 	}
625 
626 	ret = i2c_smbus_read_byte_data(client, data->def->ctrl_regs[ST1]);
627 	if (ret < 0)
628 		dev_err(&client->dev, "Error in reading ST1\n");
629 
630 	return ret;
631 }
632 
633 static int wait_conversion_complete_polled(struct ak8975_data *data)
634 {
635 	struct i2c_client *client = data->client;
636 	u8 read_status;
637 	u32 timeout_ms = AK8975_MAX_CONVERSION_TIMEOUT;
638 	int ret;
639 
640 	/* Wait for the conversion to complete. */
641 	while (timeout_ms) {
642 		msleep(AK8975_CONVERSION_DONE_POLL_TIME);
643 		ret = i2c_smbus_read_byte_data(client,
644 					       data->def->ctrl_regs[ST1]);
645 		if (ret < 0) {
646 			dev_err(&client->dev, "Error in reading ST1\n");
647 			return ret;
648 		}
649 		read_status = ret;
650 		if (read_status)
651 			break;
652 		timeout_ms -= AK8975_CONVERSION_DONE_POLL_TIME;
653 	}
654 	if (!timeout_ms) {
655 		dev_err(&client->dev, "Conversion timeout happened\n");
656 		return -EINVAL;
657 	}
658 
659 	return read_status;
660 }
661 
662 /* Returns 0 if the end of conversion interrupt occured or -ETIME otherwise */
663 static int wait_conversion_complete_interrupt(struct ak8975_data *data)
664 {
665 	int ret;
666 
667 	ret = wait_event_timeout(data->data_ready_queue,
668 				 test_bit(0, &data->flags),
669 				 AK8975_DATA_READY_TIMEOUT);
670 	clear_bit(0, &data->flags);
671 
672 	return ret > 0 ? 0 : -ETIME;
673 }
674 
675 static int ak8975_start_read_axis(struct ak8975_data *data,
676 				  const struct i2c_client *client)
677 {
678 	/* Set up the device for taking a sample. */
679 	int ret = ak8975_set_mode(data, MODE_ONCE);
680 
681 	if (ret < 0) {
682 		dev_err(&client->dev, "Error in setting operating mode\n");
683 		return ret;
684 	}
685 
686 	/* Wait for the conversion to complete. */
687 	if (data->eoc_irq)
688 		ret = wait_conversion_complete_interrupt(data);
689 	else if (data->eoc_gpiod)
690 		ret = wait_conversion_complete_gpio(data);
691 	else
692 		ret = wait_conversion_complete_polled(data);
693 	if (ret < 0)
694 		return ret;
695 
696 	/* This will be executed only for non-interrupt based waiting case */
697 	if (ret & data->def->ctrl_masks[ST1_DRDY]) {
698 		ret = i2c_smbus_read_byte_data(client,
699 					       data->def->ctrl_regs[ST2]);
700 		if (ret < 0) {
701 			dev_err(&client->dev, "Error in reading ST2\n");
702 			return ret;
703 		}
704 		if (ret & (data->def->ctrl_masks[ST2_DERR] |
705 			   data->def->ctrl_masks[ST2_HOFL])) {
706 			dev_err(&client->dev, "ST2 status error 0x%x\n", ret);
707 			return -EINVAL;
708 		}
709 	}
710 
711 	return 0;
712 }
713 
714 /* Retrieve raw flux value for one of the x, y, or z axis.  */
715 static int ak8975_read_axis(struct iio_dev *indio_dev, int index, int *val)
716 {
717 	struct ak8975_data *data = iio_priv(indio_dev);
718 	const struct i2c_client *client = data->client;
719 	const struct ak_def *def = data->def;
720 	__le16 rval;
721 	u16 buff;
722 	int ret;
723 
724 	pm_runtime_get_sync(&data->client->dev);
725 
726 	mutex_lock(&data->lock);
727 
728 	ret = ak8975_start_read_axis(data, client);
729 	if (ret)
730 		goto exit;
731 
732 	ret = i2c_smbus_read_i2c_block_data_or_emulated(
733 			client, def->data_regs[index],
734 			sizeof(rval), (u8*)&rval);
735 	if (ret < 0)
736 		goto exit;
737 
738 	mutex_unlock(&data->lock);
739 
740 	pm_runtime_mark_last_busy(&data->client->dev);
741 	pm_runtime_put_autosuspend(&data->client->dev);
742 
743 	/* Swap bytes and convert to valid range. */
744 	buff = le16_to_cpu(rval);
745 	*val = clamp_t(s16, buff, -def->range, def->range);
746 	return IIO_VAL_INT;
747 
748 exit:
749 	mutex_unlock(&data->lock);
750 	dev_err(&client->dev, "Error in reading axis\n");
751 	return ret;
752 }
753 
754 static int ak8975_read_raw(struct iio_dev *indio_dev,
755 			   struct iio_chan_spec const *chan,
756 			   int *val, int *val2,
757 			   long mask)
758 {
759 	struct ak8975_data *data = iio_priv(indio_dev);
760 
761 	switch (mask) {
762 	case IIO_CHAN_INFO_RAW:
763 		return ak8975_read_axis(indio_dev, chan->address, val);
764 	case IIO_CHAN_INFO_SCALE:
765 		*val = 0;
766 		*val2 = data->raw_to_gauss[chan->address];
767 		return IIO_VAL_INT_PLUS_MICRO;
768 	}
769 	return -EINVAL;
770 }
771 
772 static const struct iio_mount_matrix *
773 ak8975_get_mount_matrix(const struct iio_dev *indio_dev,
774 			const struct iio_chan_spec *chan)
775 {
776 	struct ak8975_data *data = iio_priv(indio_dev);
777 
778 	return &data->orientation;
779 }
780 
781 static const struct iio_chan_spec_ext_info ak8975_ext_info[] = {
782 	IIO_MOUNT_MATRIX(IIO_SHARED_BY_DIR, ak8975_get_mount_matrix),
783 	{ }
784 };
785 
786 #define AK8975_CHANNEL(axis, index)					\
787 	{								\
788 		.type = IIO_MAGN,					\
789 		.modified = 1,						\
790 		.channel2 = IIO_MOD_##axis,				\
791 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |		\
792 			     BIT(IIO_CHAN_INFO_SCALE),			\
793 		.address = index,					\
794 		.scan_index = index,					\
795 		.scan_type = {						\
796 			.sign = 's',					\
797 			.realbits = 16,					\
798 			.storagebits = 16,				\
799 			.endianness = IIO_CPU				\
800 		},							\
801 		.ext_info = ak8975_ext_info,				\
802 	}
803 
804 static const struct iio_chan_spec ak8975_channels[] = {
805 	AK8975_CHANNEL(X, 0), AK8975_CHANNEL(Y, 1), AK8975_CHANNEL(Z, 2),
806 	IIO_CHAN_SOFT_TIMESTAMP(3),
807 };
808 
809 static const unsigned long ak8975_scan_masks[] = { 0x7, 0 };
810 
811 static const struct iio_info ak8975_info = {
812 	.read_raw = &ak8975_read_raw,
813 };
814 
815 static const struct acpi_device_id ak_acpi_match[] = {
816 	{"AK8975", AK8975},
817 	{"AK8963", AK8963},
818 	{"INVN6500", AK8963},
819 	{"AK009911", AK09911},
820 	{"AK09911", AK09911},
821 	{"AKM9911", AK09911},
822 	{"AK09912", AK09912},
823 	{ }
824 };
825 MODULE_DEVICE_TABLE(acpi, ak_acpi_match);
826 
827 static void ak8975_fill_buffer(struct iio_dev *indio_dev)
828 {
829 	struct ak8975_data *data = iio_priv(indio_dev);
830 	const struct i2c_client *client = data->client;
831 	const struct ak_def *def = data->def;
832 	int ret;
833 	__le16 fval[3];
834 
835 	mutex_lock(&data->lock);
836 
837 	ret = ak8975_start_read_axis(data, client);
838 	if (ret)
839 		goto unlock;
840 
841 	/*
842 	 * For each axis, read the flux value from the appropriate register
843 	 * (the register is specified in the iio device attributes).
844 	 */
845 	ret = i2c_smbus_read_i2c_block_data_or_emulated(client,
846 							def->data_regs[0],
847 							3 * sizeof(fval[0]),
848 							(u8 *)fval);
849 	if (ret < 0)
850 		goto unlock;
851 
852 	mutex_unlock(&data->lock);
853 
854 	/* Clamp to valid range. */
855 	data->scan.channels[0] = clamp_t(s16, le16_to_cpu(fval[0]), -def->range, def->range);
856 	data->scan.channels[1] = clamp_t(s16, le16_to_cpu(fval[1]), -def->range, def->range);
857 	data->scan.channels[2] = clamp_t(s16, le16_to_cpu(fval[2]), -def->range, def->range);
858 
859 	iio_push_to_buffers_with_timestamp(indio_dev, &data->scan,
860 					   iio_get_time_ns(indio_dev));
861 
862 	return;
863 
864 unlock:
865 	mutex_unlock(&data->lock);
866 	dev_err(&client->dev, "Error in reading axes block\n");
867 }
868 
869 static irqreturn_t ak8975_handle_trigger(int irq, void *p)
870 {
871 	const struct iio_poll_func *pf = p;
872 	struct iio_dev *indio_dev = pf->indio_dev;
873 
874 	ak8975_fill_buffer(indio_dev);
875 	iio_trigger_notify_done(indio_dev->trig);
876 	return IRQ_HANDLED;
877 }
878 
879 static int ak8975_probe(struct i2c_client *client)
880 {
881 	const struct i2c_device_id *id = i2c_client_get_device_id(client);
882 	struct ak8975_data *data;
883 	struct iio_dev *indio_dev;
884 	struct gpio_desc *eoc_gpiod;
885 	struct gpio_desc *reset_gpiod;
886 	const void *match;
887 	unsigned int i;
888 	int err;
889 	enum asahi_compass_chipset chipset;
890 	const char *name = NULL;
891 
892 	/*
893 	 * Grab and set up the supplied GPIO.
894 	 * We may not have a GPIO based IRQ to scan, that is fine, we will
895 	 * poll if so.
896 	 */
897 	eoc_gpiod = devm_gpiod_get_optional(&client->dev, NULL, GPIOD_IN);
898 	if (IS_ERR(eoc_gpiod))
899 		return PTR_ERR(eoc_gpiod);
900 	if (eoc_gpiod)
901 		gpiod_set_consumer_name(eoc_gpiod, "ak_8975");
902 
903 	/*
904 	 * According to AK09911 datasheet, if reset GPIO is provided then
905 	 * deassert reset on ak8975_power_on() and assert reset on
906 	 * ak8975_power_off().
907 	 */
908 	reset_gpiod = devm_gpiod_get_optional(&client->dev,
909 					      "reset", GPIOD_OUT_HIGH);
910 	if (IS_ERR(reset_gpiod))
911 		return PTR_ERR(reset_gpiod);
912 
913 	/* Register with IIO */
914 	indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
915 	if (indio_dev == NULL)
916 		return -ENOMEM;
917 
918 	data = iio_priv(indio_dev);
919 	i2c_set_clientdata(client, indio_dev);
920 
921 	data->client = client;
922 	data->eoc_gpiod = eoc_gpiod;
923 	data->reset_gpiod = reset_gpiod;
924 	data->eoc_irq = 0;
925 
926 	err = iio_read_mount_matrix(&client->dev, &data->orientation);
927 	if (err)
928 		return err;
929 
930 	/* id will be NULL when enumerated via ACPI */
931 	match = device_get_match_data(&client->dev);
932 	if (match) {
933 		chipset = (uintptr_t)match;
934 		name = dev_name(&client->dev);
935 	} else if (id) {
936 		chipset = (enum asahi_compass_chipset)(id->driver_data);
937 		name = id->name;
938 	} else
939 		return -ENOSYS;
940 
941 	for (i = 0; i < ARRAY_SIZE(ak_def_array); i++)
942 		if (ak_def_array[i].type == chipset)
943 			break;
944 
945 	if (i == ARRAY_SIZE(ak_def_array)) {
946 		dev_err(&client->dev, "AKM device type unsupported: %d\n",
947 			chipset);
948 		return -ENODEV;
949 	}
950 
951 	data->def = &ak_def_array[i];
952 
953 	/* Fetch the regulators */
954 	data->vdd = devm_regulator_get(&client->dev, "vdd");
955 	if (IS_ERR(data->vdd))
956 		return PTR_ERR(data->vdd);
957 	data->vid = devm_regulator_get(&client->dev, "vid");
958 	if (IS_ERR(data->vid))
959 		return PTR_ERR(data->vid);
960 
961 	err = ak8975_power_on(data);
962 	if (err)
963 		return err;
964 
965 	err = ak8975_who_i_am(client, data->def->type);
966 	if (err < 0) {
967 		dev_err(&client->dev, "Unexpected device\n");
968 		goto power_off;
969 	}
970 	dev_dbg(&client->dev, "Asahi compass chip %s\n", name);
971 
972 	/* Perform some basic start-of-day setup of the device. */
973 	err = ak8975_setup(client);
974 	if (err < 0) {
975 		dev_err(&client->dev, "%s initialization fails\n", name);
976 		goto power_off;
977 	}
978 
979 	mutex_init(&data->lock);
980 	indio_dev->channels = ak8975_channels;
981 	indio_dev->num_channels = ARRAY_SIZE(ak8975_channels);
982 	indio_dev->info = &ak8975_info;
983 	indio_dev->available_scan_masks = ak8975_scan_masks;
984 	indio_dev->modes = INDIO_DIRECT_MODE;
985 	indio_dev->name = name;
986 
987 	err = iio_triggered_buffer_setup(indio_dev, NULL, ak8975_handle_trigger,
988 					 NULL);
989 	if (err) {
990 		dev_err(&client->dev, "triggered buffer setup failed\n");
991 		goto power_off;
992 	}
993 
994 	err = iio_device_register(indio_dev);
995 	if (err) {
996 		dev_err(&client->dev, "device register failed\n");
997 		goto cleanup_buffer;
998 	}
999 
1000 	/* Enable runtime PM */
1001 	pm_runtime_get_noresume(&client->dev);
1002 	pm_runtime_set_active(&client->dev);
1003 	pm_runtime_enable(&client->dev);
1004 	/*
1005 	 * The device comes online in 500us, so add two orders of magnitude
1006 	 * of delay before autosuspending: 50 ms.
1007 	 */
1008 	pm_runtime_set_autosuspend_delay(&client->dev, 50);
1009 	pm_runtime_use_autosuspend(&client->dev);
1010 	pm_runtime_put(&client->dev);
1011 
1012 	return 0;
1013 
1014 cleanup_buffer:
1015 	iio_triggered_buffer_cleanup(indio_dev);
1016 power_off:
1017 	ak8975_power_off(data);
1018 	return err;
1019 }
1020 
1021 static void ak8975_remove(struct i2c_client *client)
1022 {
1023 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
1024 	struct ak8975_data *data = iio_priv(indio_dev);
1025 
1026 	pm_runtime_get_sync(&client->dev);
1027 	pm_runtime_put_noidle(&client->dev);
1028 	pm_runtime_disable(&client->dev);
1029 	iio_device_unregister(indio_dev);
1030 	iio_triggered_buffer_cleanup(indio_dev);
1031 	ak8975_set_mode(data, POWER_DOWN);
1032 	ak8975_power_off(data);
1033 }
1034 
1035 static int ak8975_runtime_suspend(struct device *dev)
1036 {
1037 	struct i2c_client *client = to_i2c_client(dev);
1038 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
1039 	struct ak8975_data *data = iio_priv(indio_dev);
1040 	int ret;
1041 
1042 	/* Set the device in power down if it wasn't already */
1043 	ret = ak8975_set_mode(data, POWER_DOWN);
1044 	if (ret < 0) {
1045 		dev_err(&client->dev, "Error in setting power-down mode\n");
1046 		return ret;
1047 	}
1048 	/* Next cut the regulators */
1049 	ak8975_power_off(data);
1050 
1051 	return 0;
1052 }
1053 
1054 static int ak8975_runtime_resume(struct device *dev)
1055 {
1056 	struct i2c_client *client = to_i2c_client(dev);
1057 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
1058 	struct ak8975_data *data = iio_priv(indio_dev);
1059 	int ret;
1060 
1061 	/* Take up the regulators */
1062 	ak8975_power_on(data);
1063 	/*
1064 	 * We come up in powered down mode, the reading routines will
1065 	 * put us in the mode to read values later.
1066 	 */
1067 	ret = ak8975_set_mode(data, POWER_DOWN);
1068 	if (ret < 0) {
1069 		dev_err(&client->dev, "Error in setting power-down mode\n");
1070 		return ret;
1071 	}
1072 
1073 	return 0;
1074 }
1075 
1076 static DEFINE_RUNTIME_DEV_PM_OPS(ak8975_dev_pm_ops, ak8975_runtime_suspend,
1077 				 ak8975_runtime_resume, NULL);
1078 
1079 static const struct i2c_device_id ak8975_id[] = {
1080 	{"ak8975", AK8975},
1081 	{"ak8963", AK8963},
1082 	{"AK8963", AK8963},
1083 	{"ak09911", AK09911},
1084 	{"ak09912", AK09912},
1085 	{"ak09916", AK09916},
1086 	{}
1087 };
1088 
1089 MODULE_DEVICE_TABLE(i2c, ak8975_id);
1090 
1091 static const struct of_device_id ak8975_of_match[] = {
1092 	{ .compatible = "asahi-kasei,ak8975", },
1093 	{ .compatible = "ak8975", },
1094 	{ .compatible = "asahi-kasei,ak8963", },
1095 	{ .compatible = "ak8963", },
1096 	{ .compatible = "asahi-kasei,ak09911", },
1097 	{ .compatible = "ak09911", },
1098 	{ .compatible = "asahi-kasei,ak09912", },
1099 	{ .compatible = "ak09912", },
1100 	{ .compatible = "asahi-kasei,ak09916", },
1101 	{ .compatible = "ak09916", },
1102 	{}
1103 };
1104 MODULE_DEVICE_TABLE(of, ak8975_of_match);
1105 
1106 static struct i2c_driver ak8975_driver = {
1107 	.driver = {
1108 		.name	= "ak8975",
1109 		.pm = pm_ptr(&ak8975_dev_pm_ops),
1110 		.of_match_table = ak8975_of_match,
1111 		.acpi_match_table = ak_acpi_match,
1112 	},
1113 	.probe_new	= ak8975_probe,
1114 	.remove		= ak8975_remove,
1115 	.id_table	= ak8975_id,
1116 };
1117 module_i2c_driver(ak8975_driver);
1118 
1119 MODULE_AUTHOR("Laxman Dewangan <ldewangan@nvidia.com>");
1120 MODULE_DESCRIPTION("AK8975 magnetometer driver");
1121 MODULE_LICENSE("GPL");
1122