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