1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Driver for the Yamaha YAS magnetic sensors, often used in Samsung
4  * mobile phones. While all are not yet handled because of lacking
5  * hardware, expand this driver to handle the different variants:
6  *
7  * YAS530 MS-3E (2011 Samsung Galaxy S Advance)
8  * YAS532 MS-3R (2011 Samsung Galaxy S4)
9  * YAS533 MS-3F (Vivo 1633, 1707, V3, Y21L)
10  * (YAS534 is a magnetic switch, not handled)
11  * YAS535 MS-6C
12  * YAS536 MS-3W
13  * YAS537 MS-3T (2015 Samsung Galaxy S6, Note 5, Xiaomi)
14  * YAS539 MS-3S (2018 Samsung Galaxy A7 SM-A750FN)
15  *
16  * Code functions found in the MPU3050 YAS530 and YAS532 drivers
17  * named "inv_compass" in the Tegra Android kernel tree.
18  * Copyright (C) 2012 InvenSense Corporation
19  *
20  * Author: Linus Walleij <linus.walleij@linaro.org>
21  */
22 #include <linux/bitfield.h>
23 #include <linux/bitops.h>
24 #include <linux/delay.h>
25 #include <linux/err.h>
26 #include <linux/gpio/consumer.h>
27 #include <linux/i2c.h>
28 #include <linux/module.h>
29 #include <linux/mod_devicetable.h>
30 #include <linux/mutex.h>
31 #include <linux/pm_runtime.h>
32 #include <linux/regmap.h>
33 #include <linux/regulator/consumer.h>
34 #include <linux/random.h>
35 
36 #include <linux/iio/buffer.h>
37 #include <linux/iio/iio.h>
38 #include <linux/iio/trigger_consumer.h>
39 #include <linux/iio/triggered_buffer.h>
40 
41 #include <asm/unaligned.h>
42 
43 /* This register map covers YAS530 and YAS532 but differs in YAS 537 and YAS539 */
44 #define YAS5XX_DEVICE_ID		0x80
45 #define YAS5XX_ACTUATE_INIT_COIL	0x81
46 #define YAS5XX_MEASURE			0x82
47 #define YAS5XX_CONFIG			0x83
48 #define YAS5XX_MEASURE_INTERVAL		0x84
49 #define YAS5XX_OFFSET_X			0x85 /* [-31 .. 31] */
50 #define YAS5XX_OFFSET_Y1		0x86 /* [-31 .. 31] */
51 #define YAS5XX_OFFSET_Y2		0x87 /* [-31 .. 31] */
52 #define YAS5XX_TEST1			0x88
53 #define YAS5XX_TEST2			0x89
54 #define YAS5XX_CAL			0x90
55 #define YAS5XX_MEASURE_DATA		0xB0
56 
57 /* Bits in the YAS5xx config register */
58 #define YAS5XX_CONFIG_INTON		BIT(0) /* Interrupt on? */
59 #define YAS5XX_CONFIG_INTHACT		BIT(1) /* Interrupt active high? */
60 #define YAS5XX_CONFIG_CCK_MASK		GENMASK(4, 2)
61 #define YAS5XX_CONFIG_CCK_SHIFT		2
62 
63 /* Bits in the measure command register */
64 #define YAS5XX_MEASURE_START		BIT(0)
65 #define YAS5XX_MEASURE_LDTC		BIT(1)
66 #define YAS5XX_MEASURE_FORS		BIT(2)
67 #define YAS5XX_MEASURE_DLYMES		BIT(4)
68 
69 /* Bits in the measure data register */
70 #define YAS5XX_MEASURE_DATA_BUSY	BIT(7)
71 
72 #define YAS530_DEVICE_ID		0x01 /* YAS530 (MS-3E) */
73 #define YAS530_VERSION_A		0 /* YAS530 (MS-3E A) */
74 #define YAS530_VERSION_B		1 /* YAS530B (MS-3E B) */
75 #define YAS530_VERSION_A_COEF		380
76 #define YAS530_VERSION_B_COEF		550
77 #define YAS530_DATA_BITS		12
78 #define YAS530_DATA_CENTER		BIT(YAS530_DATA_BITS - 1)
79 #define YAS530_DATA_OVERFLOW		(BIT(YAS530_DATA_BITS) - 1)
80 
81 #define YAS532_DEVICE_ID		0x02 /* YAS532/YAS533 (MS-3R/F) */
82 #define YAS532_VERSION_AB		0 /* YAS532/533 AB (MS-3R/F AB) */
83 #define YAS532_VERSION_AC		1 /* YAS532/533 AC (MS-3R/F AC) */
84 #define YAS532_VERSION_AB_COEF		1800
85 #define YAS532_VERSION_AC_COEF_X	850
86 #define YAS532_VERSION_AC_COEF_Y1	750
87 #define YAS532_VERSION_AC_COEF_Y2	750
88 #define YAS532_DATA_BITS		13
89 #define YAS532_DATA_CENTER		BIT(YAS532_DATA_BITS - 1)
90 #define YAS532_DATA_OVERFLOW		(BIT(YAS532_DATA_BITS) - 1)
91 #define YAS532_20DEGREES		390 /* Looks like Kelvin */
92 
93 /* These variant IDs are known from code dumps */
94 #define YAS537_DEVICE_ID		0x07 /* YAS537 (MS-3T) */
95 #define YAS539_DEVICE_ID		0x08 /* YAS539 (MS-3S) */
96 
97 /* Turn off device regulators etc after 5 seconds of inactivity */
98 #define YAS5XX_AUTOSUSPEND_DELAY_MS	5000
99 
100 struct yas5xx_calibration {
101 	/* Linearization calibration x, y1, y2 */
102 	s32 r[3];
103 	u32 f[3];
104 	/* Temperature compensation calibration */
105 	s32 Cx, Cy1, Cy2;
106 	/* Misc calibration coefficients */
107 	s32 a2, a3, a4, a5, a6, a7, a8, a9, k;
108 	/* clock divider */
109 	u8 dck;
110 };
111 
112 /**
113  * struct yas5xx - state container for the YAS5xx driver
114  * @dev: parent device pointer
115  * @devid: device ID number
116  * @version: device version
117  * @name: device name
118  * @calibration: calibration settings from the OTP storage
119  * @hard_offsets: offsets for each axis measured with initcoil actuated
120  * @orientation: mounting matrix, flipped axis etc
121  * @map: regmap to access the YAX5xx registers over I2C
122  * @regs: the vdd and vddio power regulators
123  * @reset: optional GPIO line used for handling RESET
124  * @lock: locks the magnetometer for exclusive use during a measurement (which
125  * involves several register transactions so the regmap lock is not enough)
126  * so that measurements get serialized in a first-come-first serve manner
127  * @scan: naturally aligned measurements
128  */
129 struct yas5xx {
130 	struct device *dev;
131 	unsigned int devid;
132 	unsigned int version;
133 	char name[16];
134 	struct yas5xx_calibration calibration;
135 	u8 hard_offsets[3];
136 	struct iio_mount_matrix orientation;
137 	struct regmap *map;
138 	struct regulator_bulk_data regs[2];
139 	struct gpio_desc *reset;
140 	struct mutex lock;
141 	/*
142 	 * The scanout is 4 x 32 bits in CPU endianness.
143 	 * Ensure timestamp is naturally aligned
144 	 */
145 	struct {
146 		s32 channels[4];
147 		s64 ts __aligned(8);
148 	} scan;
149 };
150 
151 /* On YAS530 the x, y1 and y2 values are 12 bits */
152 static u16 yas530_extract_axis(u8 *data)
153 {
154 	u16 val;
155 
156 	/*
157 	 * These are the bits used in a 16bit word:
158 	 * 15 14 13 12 11 10 9  8  7  6  5  4  3  2  1  0
159 	 *    x  x  x  x  x  x  x  x  x  x  x  x
160 	 */
161 	val = get_unaligned_be16(&data[0]);
162 	val = FIELD_GET(GENMASK(14, 3), val);
163 	return val;
164 }
165 
166 /* On YAS532 the x, y1 and y2 values are 13 bits */
167 static u16 yas532_extract_axis(u8 *data)
168 {
169 	u16 val;
170 
171 	/*
172 	 * These are the bits used in a 16bit word:
173 	 * 15 14 13 12 11 10 9  8  7  6  5  4  3  2  1  0
174 	 *    x  x  x  x  x  x  x  x  x  x  x  x  x
175 	 */
176 	val = get_unaligned_be16(&data[0]);
177 	val = FIELD_GET(GENMASK(14, 2), val);
178 	return val;
179 }
180 
181 /**
182  * yas5xx_measure() - Make a measure from the hardware
183  * @yas5xx: The device state
184  * @t: the raw temperature measurement
185  * @x: the raw x axis measurement
186  * @y1: the y1 axis measurement
187  * @y2: the y2 axis measurement
188  * @return: 0 on success or error code
189  */
190 static int yas5xx_measure(struct yas5xx *yas5xx, u16 *t, u16 *x, u16 *y1, u16 *y2)
191 {
192 	unsigned int busy;
193 	u8 data[8];
194 	int ret;
195 	u16 val;
196 
197 	mutex_lock(&yas5xx->lock);
198 	ret = regmap_write(yas5xx->map, YAS5XX_MEASURE, YAS5XX_MEASURE_START);
199 	if (ret < 0)
200 		goto out_unlock;
201 
202 	/*
203 	 * Typical time to measure 1500 us, max 2000 us so wait min 500 us
204 	 * and at most 20000 us (one magnitude more than the datsheet max)
205 	 * before timeout.
206 	 */
207 	ret = regmap_read_poll_timeout(yas5xx->map, YAS5XX_MEASURE_DATA, busy,
208 				       !(busy & YAS5XX_MEASURE_DATA_BUSY),
209 				       500, 20000);
210 	if (ret) {
211 		dev_err(yas5xx->dev, "timeout waiting for measurement\n");
212 		goto out_unlock;
213 	}
214 
215 	ret = regmap_bulk_read(yas5xx->map, YAS5XX_MEASURE_DATA,
216 			       data, sizeof(data));
217 	if (ret)
218 		goto out_unlock;
219 
220 	mutex_unlock(&yas5xx->lock);
221 
222 	switch (yas5xx->devid) {
223 	case YAS530_DEVICE_ID:
224 		/*
225 		 * The t value is 9 bits in big endian format
226 		 * These are the bits used in a 16bit word:
227 		 * 15 14 13 12 11 10 9  8  7  6  5  4  3  2  1  0
228 		 *    x  x  x  x  x  x  x  x  x
229 		 */
230 		val = get_unaligned_be16(&data[0]);
231 		val = FIELD_GET(GENMASK(14, 6), val);
232 		*t = val;
233 		*x = yas530_extract_axis(&data[2]);
234 		*y1 = yas530_extract_axis(&data[4]);
235 		*y2 = yas530_extract_axis(&data[6]);
236 		break;
237 	case YAS532_DEVICE_ID:
238 		/*
239 		 * The t value is 10 bits in big endian format
240 		 * These are the bits used in a 16bit word:
241 		 * 15 14 13 12 11 10 9  8  7  6  5  4  3  2  1  0
242 		 *    x  x  x  x  x  x  x  x  x  x
243 		 */
244 		val = get_unaligned_be16(&data[0]);
245 		val = FIELD_GET(GENMASK(14, 5), val);
246 		*t = val;
247 		*x = yas532_extract_axis(&data[2]);
248 		*y1 = yas532_extract_axis(&data[4]);
249 		*y2 = yas532_extract_axis(&data[6]);
250 		break;
251 	default:
252 		dev_err(yas5xx->dev, "unknown data format\n");
253 		ret = -EINVAL;
254 		break;
255 	}
256 
257 	return ret;
258 
259 out_unlock:
260 	mutex_unlock(&yas5xx->lock);
261 	return ret;
262 }
263 
264 static s32 yas5xx_linearize(struct yas5xx *yas5xx, u16 val, int axis)
265 {
266 	struct yas5xx_calibration *c = &yas5xx->calibration;
267 	static const s32 yas532ac_coef[] = {
268 		YAS532_VERSION_AC_COEF_X,
269 		YAS532_VERSION_AC_COEF_Y1,
270 		YAS532_VERSION_AC_COEF_Y2,
271 	};
272 	s32 coef;
273 
274 	/* Select coefficients */
275 	switch (yas5xx->devid) {
276 	case YAS530_DEVICE_ID:
277 		if (yas5xx->version == YAS530_VERSION_A)
278 			coef = YAS530_VERSION_A_COEF;
279 		else
280 			coef = YAS530_VERSION_B_COEF;
281 		break;
282 	case YAS532_DEVICE_ID:
283 		if (yas5xx->version == YAS532_VERSION_AB)
284 			coef = YAS532_VERSION_AB_COEF;
285 		else
286 			/* Elaborate coefficients */
287 			coef = yas532ac_coef[axis];
288 		break;
289 	default:
290 		dev_err(yas5xx->dev, "unknown device type\n");
291 		return val;
292 	}
293 	/*
294 	 * Linearization formula:
295 	 *
296 	 * x' = x - (3721 + 50 * f) + (xoffset - r) * c
297 	 *
298 	 * Where f and r are calibration values, c is a per-device
299 	 * and sometimes per-axis coefficient.
300 	 */
301 	return val - (3721 + 50 * c->f[axis]) +
302 		(yas5xx->hard_offsets[axis] - c->r[axis]) * coef;
303 }
304 
305 /**
306  * yas5xx_get_measure() - Measure a sample of all axis and process
307  * @yas5xx: The device state
308  * @to: Temperature out
309  * @xo: X axis out
310  * @yo: Y axis out
311  * @zo: Z axis out
312  * @return: 0 on success or error code
313  *
314  * Returned values are in nanotesla according to some code.
315  */
316 static int yas5xx_get_measure(struct yas5xx *yas5xx, s32 *to, s32 *xo, s32 *yo, s32 *zo)
317 {
318 	struct yas5xx_calibration *c = &yas5xx->calibration;
319 	u16 t, x, y1, y2;
320 	/* These are "signed x, signed y1 etc */
321 	s32 sx, sy1, sy2, sy, sz;
322 	int ret;
323 
324 	/* We first get raw data that needs to be translated to [x,y,z] */
325 	ret = yas5xx_measure(yas5xx, &t, &x, &y1, &y2);
326 	if (ret)
327 		return ret;
328 
329 	/* Do some linearization if available */
330 	sx = yas5xx_linearize(yas5xx, x, 0);
331 	sy1 = yas5xx_linearize(yas5xx, y1, 1);
332 	sy2 = yas5xx_linearize(yas5xx, y2, 2);
333 
334 	/*
335 	 * Temperature compensation for x, y1, y2 respectively:
336 	 *
337 	 *          Cx * t
338 	 * x' = x - ------
339 	 *           100
340 	 */
341 	sx = sx - (c->Cx * t) / 100;
342 	sy1 = sy1 - (c->Cy1 * t) / 100;
343 	sy2 = sy2 - (c->Cy2 * t) / 100;
344 
345 	/*
346 	 * Break y1 and y2 into y and z, y1 and y2 are apparently encoding
347 	 * y and z.
348 	 */
349 	sy = sy1 - sy2;
350 	sz = -sy1 - sy2;
351 
352 	/*
353 	 * FIXME: convert to Celsius? Just guessing this is given
354 	 * as 1/10:s of degrees so multiply by 100 to get millicentigrades.
355 	 */
356 	*to = t * 100;
357 	/*
358 	 * Calibrate [x,y,z] with some formulas like this:
359 	 *
360 	 *            100 * x + a_2 * y + a_3 * z
361 	 *  x' = k *  ---------------------------
362 	 *                        10
363 	 *
364 	 *           a_4 * x + a_5 * y + a_6 * z
365 	 *  y' = k * ---------------------------
366 	 *                        10
367 	 *
368 	 *           a_7 * x + a_8 * y + a_9 * z
369 	 *  z' = k * ---------------------------
370 	 *                        10
371 	 */
372 	*xo = c->k * ((100 * sx + c->a2 * sy + c->a3 * sz) / 10);
373 	*yo = c->k * ((c->a4 * sx + c->a5 * sy + c->a6 * sz) / 10);
374 	*zo = c->k * ((c->a7 * sx + c->a8 * sy + c->a9 * sz) / 10);
375 
376 	return 0;
377 }
378 
379 static int yas5xx_read_raw(struct iio_dev *indio_dev,
380 			   struct iio_chan_spec const *chan,
381 			   int *val, int *val2,
382 			   long mask)
383 {
384 	struct yas5xx *yas5xx = iio_priv(indio_dev);
385 	s32 t, x, y, z;
386 	int ret;
387 
388 	switch (mask) {
389 	case IIO_CHAN_INFO_RAW:
390 		pm_runtime_get_sync(yas5xx->dev);
391 		ret = yas5xx_get_measure(yas5xx, &t, &x, &y, &z);
392 		pm_runtime_mark_last_busy(yas5xx->dev);
393 		pm_runtime_put_autosuspend(yas5xx->dev);
394 		if (ret)
395 			return ret;
396 		switch (chan->address) {
397 		case 0:
398 			*val = t;
399 			break;
400 		case 1:
401 			*val = x;
402 			break;
403 		case 2:
404 			*val = y;
405 			break;
406 		case 3:
407 			*val = z;
408 			break;
409 		default:
410 			dev_err(yas5xx->dev, "unknown channel\n");
411 			return -EINVAL;
412 		}
413 		return IIO_VAL_INT;
414 	case IIO_CHAN_INFO_SCALE:
415 		if (chan->address == 0) {
416 			/* Temperature is unscaled */
417 			*val = 1;
418 			return IIO_VAL_INT;
419 		}
420 		/*
421 		 * The axis values are in nanotesla according to the vendor
422 		 * drivers, but is clearly in microtesla according to
423 		 * experiments. Since 1 uT = 0.01 Gauss, we need to divide
424 		 * by 100000000 (10^8) to get to Gauss from the raw value.
425 		 */
426 		*val = 1;
427 		*val2 = 100000000;
428 		return IIO_VAL_FRACTIONAL;
429 	default:
430 		/* Unknown request */
431 		return -EINVAL;
432 	}
433 }
434 
435 static void yas5xx_fill_buffer(struct iio_dev *indio_dev)
436 {
437 	struct yas5xx *yas5xx = iio_priv(indio_dev);
438 	s32 t, x, y, z;
439 	int ret;
440 
441 	pm_runtime_get_sync(yas5xx->dev);
442 	ret = yas5xx_get_measure(yas5xx, &t, &x, &y, &z);
443 	pm_runtime_mark_last_busy(yas5xx->dev);
444 	pm_runtime_put_autosuspend(yas5xx->dev);
445 	if (ret) {
446 		dev_err(yas5xx->dev, "error refilling buffer\n");
447 		return;
448 	}
449 	yas5xx->scan.channels[0] = t;
450 	yas5xx->scan.channels[1] = x;
451 	yas5xx->scan.channels[2] = y;
452 	yas5xx->scan.channels[3] = z;
453 	iio_push_to_buffers_with_timestamp(indio_dev, &yas5xx->scan,
454 					   iio_get_time_ns(indio_dev));
455 }
456 
457 static irqreturn_t yas5xx_handle_trigger(int irq, void *p)
458 {
459 	const struct iio_poll_func *pf = p;
460 	struct iio_dev *indio_dev = pf->indio_dev;
461 
462 	yas5xx_fill_buffer(indio_dev);
463 	iio_trigger_notify_done(indio_dev->trig);
464 
465 	return IRQ_HANDLED;
466 }
467 
468 
469 static const struct iio_mount_matrix *
470 yas5xx_get_mount_matrix(const struct iio_dev *indio_dev,
471 			const struct iio_chan_spec *chan)
472 {
473 	struct yas5xx *yas5xx = iio_priv(indio_dev);
474 
475 	return &yas5xx->orientation;
476 }
477 
478 static const struct iio_chan_spec_ext_info yas5xx_ext_info[] = {
479 	IIO_MOUNT_MATRIX(IIO_SHARED_BY_DIR, yas5xx_get_mount_matrix),
480 	{ }
481 };
482 
483 #define YAS5XX_AXIS_CHANNEL(axis, index)				\
484 	{								\
485 		.type = IIO_MAGN,					\
486 		.modified = 1,						\
487 		.channel2 = IIO_MOD_##axis,				\
488 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |		\
489 			BIT(IIO_CHAN_INFO_SCALE),			\
490 		.ext_info = yas5xx_ext_info,				\
491 		.address = index,					\
492 		.scan_index = index,					\
493 		.scan_type = {						\
494 			.sign = 's',					\
495 			.realbits = 32,					\
496 			.storagebits = 32,				\
497 			.endianness = IIO_CPU,				\
498 		},							\
499 	}
500 
501 static const struct iio_chan_spec yas5xx_channels[] = {
502 	{
503 		.type = IIO_TEMP,
504 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),
505 		.address = 0,
506 		.scan_index = 0,
507 		.scan_type = {
508 			.sign = 'u',
509 			.realbits = 32,
510 			.storagebits = 32,
511 			.endianness = IIO_CPU,
512 		},
513 	},
514 	YAS5XX_AXIS_CHANNEL(X, 1),
515 	YAS5XX_AXIS_CHANNEL(Y, 2),
516 	YAS5XX_AXIS_CHANNEL(Z, 3),
517 	IIO_CHAN_SOFT_TIMESTAMP(4),
518 };
519 
520 static const unsigned long yas5xx_scan_masks[] = { GENMASK(3, 0), 0 };
521 
522 static const struct iio_info yas5xx_info = {
523 	.read_raw = &yas5xx_read_raw,
524 };
525 
526 static bool yas5xx_volatile_reg(struct device *dev, unsigned int reg)
527 {
528 	return reg == YAS5XX_ACTUATE_INIT_COIL ||
529 		reg == YAS5XX_MEASURE ||
530 		(reg >= YAS5XX_MEASURE_DATA && reg <= YAS5XX_MEASURE_DATA + 8);
531 }
532 
533 /* TODO: enable regmap cache, using mark dirty and sync at runtime resume */
534 static const struct regmap_config yas5xx_regmap_config = {
535 	.reg_bits = 8,
536 	.val_bits = 8,
537 	.max_register = 0xff,
538 	.volatile_reg = yas5xx_volatile_reg,
539 };
540 
541 /**
542  * yas53x_extract_calibration() - extracts the a2-a9 and k calibration
543  * @data: the bitfield to use
544  * @c: the calibration to populate
545  */
546 static void yas53x_extract_calibration(u8 *data, struct yas5xx_calibration *c)
547 {
548 	u64 val = get_unaligned_be64(data);
549 
550 	/*
551 	 * Bitfield layout for the axis calibration data, for factor
552 	 * a2 = 2 etc, k = k, c = clock divider
553 	 *
554 	 * n   7 6 5 4 3 2 1 0
555 	 * 0 [ 2 2 2 2 2 2 3 3 ] bits 63 .. 56
556 	 * 1 [ 3 3 4 4 4 4 4 4 ] bits 55 .. 48
557 	 * 2 [ 5 5 5 5 5 5 6 6 ] bits 47 .. 40
558 	 * 3 [ 6 6 6 6 7 7 7 7 ] bits 39 .. 32
559 	 * 4 [ 7 7 7 8 8 8 8 8 ] bits 31 .. 24
560 	 * 5 [ 8 9 9 9 9 9 9 9 ] bits 23 .. 16
561 	 * 6 [ 9 k k k k k c c ] bits 15 .. 8
562 	 * 7 [ c x x x x x x x ] bits  7 .. 0
563 	 */
564 	c->a2 = FIELD_GET(GENMASK_ULL(63, 58), val) - 32;
565 	c->a3 = FIELD_GET(GENMASK_ULL(57, 54), val) - 8;
566 	c->a4 = FIELD_GET(GENMASK_ULL(53, 48), val) - 32;
567 	c->a5 = FIELD_GET(GENMASK_ULL(47, 42), val) + 38;
568 	c->a6 = FIELD_GET(GENMASK_ULL(41, 36), val) - 32;
569 	c->a7 = FIELD_GET(GENMASK_ULL(35, 29), val) - 64;
570 	c->a8 = FIELD_GET(GENMASK_ULL(28, 23), val) - 32;
571 	c->a9 = FIELD_GET(GENMASK_ULL(22, 15), val);
572 	c->k = FIELD_GET(GENMASK_ULL(14, 10), val) + 10;
573 	c->dck = FIELD_GET(GENMASK_ULL(9, 7), val);
574 }
575 
576 static int yas530_get_calibration_data(struct yas5xx *yas5xx)
577 {
578 	struct yas5xx_calibration *c = &yas5xx->calibration;
579 	u8 data[16];
580 	u32 val;
581 	int ret;
582 
583 	/* Dummy read, first read is ALWAYS wrong */
584 	ret = regmap_bulk_read(yas5xx->map, YAS5XX_CAL, data, sizeof(data));
585 	if (ret)
586 		return ret;
587 
588 	/* Actual calibration readout */
589 	ret = regmap_bulk_read(yas5xx->map, YAS5XX_CAL, data, sizeof(data));
590 	if (ret)
591 		return ret;
592 	dev_dbg(yas5xx->dev, "calibration data: %*ph\n", 14, data);
593 
594 	add_device_randomness(data, sizeof(data));
595 	yas5xx->version = data[15] & GENMASK(1, 0);
596 
597 	/* Extract the calibration from the bitfield */
598 	c->Cx = data[0] * 6 - 768;
599 	c->Cy1 = data[1] * 6 - 768;
600 	c->Cy2 = data[2] * 6 - 768;
601 	yas53x_extract_calibration(&data[3], c);
602 
603 	/*
604 	 * Extract linearization:
605 	 * Linearization layout in the 32 bits at byte 11:
606 	 * The r factors are 6 bit values where bit 5 is the sign
607 	 *
608 	 * n    7  6  5  4  3  2  1  0
609 	 * 0 [ xx xx xx r0 r0 r0 r0 r0 ] bits 31 .. 24
610 	 * 1 [ r0 f0 f0 r1 r1 r1 r1 r1 ] bits 23 .. 16
611 	 * 2 [ r1 f1 f1 r2 r2 r2 r2 r2 ] bits 15 .. 8
612 	 * 3 [ r2 f2 f2 xx xx xx xx xx ] bits  7 .. 0
613 	 */
614 	val = get_unaligned_be32(&data[11]);
615 	c->f[0] = FIELD_GET(GENMASK(22, 21), val);
616 	c->f[1] = FIELD_GET(GENMASK(14, 13), val);
617 	c->f[2] = FIELD_GET(GENMASK(6, 5), val);
618 	c->r[0] = sign_extend32(FIELD_GET(GENMASK(28, 23), val), 5);
619 	c->r[1] = sign_extend32(FIELD_GET(GENMASK(20, 15), val), 5);
620 	c->r[2] = sign_extend32(FIELD_GET(GENMASK(12, 7), val), 5);
621 	return 0;
622 }
623 
624 static int yas532_get_calibration_data(struct yas5xx *yas5xx)
625 {
626 	struct yas5xx_calibration *c = &yas5xx->calibration;
627 	u8 data[14];
628 	u32 val;
629 	int ret;
630 
631 	/* Dummy read, first read is ALWAYS wrong */
632 	ret = regmap_bulk_read(yas5xx->map, YAS5XX_CAL, data, sizeof(data));
633 	if (ret)
634 		return ret;
635 	/* Actual calibration readout */
636 	ret = regmap_bulk_read(yas5xx->map, YAS5XX_CAL, data, sizeof(data));
637 	if (ret)
638 		return ret;
639 	dev_dbg(yas5xx->dev, "calibration data: %*ph\n", 14, data);
640 
641 	/* Sanity check, is this all zeroes? */
642 	if (memchr_inv(data, 0x00, 13)) {
643 		if (!(data[13] & BIT(7)))
644 			dev_warn(yas5xx->dev, "calibration is blank!\n");
645 	}
646 
647 	add_device_randomness(data, sizeof(data));
648 	/* Only one bit of version info reserved here as far as we know */
649 	yas5xx->version = data[13] & BIT(0);
650 
651 	/* Extract calibration from the bitfield */
652 	c->Cx = data[0] * 10 - 1280;
653 	c->Cy1 = data[1] * 10 - 1280;
654 	c->Cy2 = data[2] * 10 - 1280;
655 	yas53x_extract_calibration(&data[3], c);
656 	/*
657 	 * Extract linearization:
658 	 * Linearization layout in the 32 bits at byte 10:
659 	 * The r factors are 6 bit values where bit 5 is the sign
660 	 *
661 	 * n    7  6  5  4  3  2  1  0
662 	 * 0 [ xx r0 r0 r0 r0 r0 r0 f0 ] bits 31 .. 24
663 	 * 1 [ f0 r1 r1 r1 r1 r1 r1 f1 ] bits 23 .. 16
664 	 * 2 [ f1 r2 r2 r2 r2 r2 r2 f2 ] bits 15 .. 8
665 	 * 3 [ f2 xx xx xx xx xx xx xx ] bits  7 .. 0
666 	 */
667 	val = get_unaligned_be32(&data[10]);
668 	c->f[0] = FIELD_GET(GENMASK(24, 23), val);
669 	c->f[1] = FIELD_GET(GENMASK(16, 15), val);
670 	c->f[2] = FIELD_GET(GENMASK(8, 7), val);
671 	c->r[0] = sign_extend32(FIELD_GET(GENMASK(30, 25), val), 5);
672 	c->r[1] = sign_extend32(FIELD_GET(GENMASK(22, 17), val), 5);
673 	c->r[2] = sign_extend32(FIELD_GET(GENMASK(14, 7), val), 5);
674 
675 	return 0;
676 }
677 
678 static void yas5xx_dump_calibration(struct yas5xx *yas5xx)
679 {
680 	struct yas5xx_calibration *c = &yas5xx->calibration;
681 
682 	dev_dbg(yas5xx->dev, "f[] = [%d, %d, %d]\n",
683 		c->f[0], c->f[1], c->f[2]);
684 	dev_dbg(yas5xx->dev, "r[] = [%d, %d, %d]\n",
685 		c->r[0], c->r[1], c->r[2]);
686 	dev_dbg(yas5xx->dev, "Cx = %d\n", c->Cx);
687 	dev_dbg(yas5xx->dev, "Cy1 = %d\n", c->Cy1);
688 	dev_dbg(yas5xx->dev, "Cy2 = %d\n", c->Cy2);
689 	dev_dbg(yas5xx->dev, "a2 = %d\n", c->a2);
690 	dev_dbg(yas5xx->dev, "a3 = %d\n", c->a3);
691 	dev_dbg(yas5xx->dev, "a4 = %d\n", c->a4);
692 	dev_dbg(yas5xx->dev, "a5 = %d\n", c->a5);
693 	dev_dbg(yas5xx->dev, "a6 = %d\n", c->a6);
694 	dev_dbg(yas5xx->dev, "a7 = %d\n", c->a7);
695 	dev_dbg(yas5xx->dev, "a8 = %d\n", c->a8);
696 	dev_dbg(yas5xx->dev, "a9 = %d\n", c->a9);
697 	dev_dbg(yas5xx->dev, "k = %d\n", c->k);
698 	dev_dbg(yas5xx->dev, "dck = %d\n", c->dck);
699 }
700 
701 static int yas5xx_set_offsets(struct yas5xx *yas5xx, s8 ox, s8 oy1, s8 oy2)
702 {
703 	int ret;
704 
705 	ret = regmap_write(yas5xx->map, YAS5XX_OFFSET_X, ox);
706 	if (ret)
707 		return ret;
708 	ret = regmap_write(yas5xx->map, YAS5XX_OFFSET_Y1, oy1);
709 	if (ret)
710 		return ret;
711 	return regmap_write(yas5xx->map, YAS5XX_OFFSET_Y2, oy2);
712 }
713 
714 static s8 yas5xx_adjust_offset(s8 old, int bit, u16 center, u16 measure)
715 {
716 	if (measure > center)
717 		return old + BIT(bit);
718 	if (measure < center)
719 		return old - BIT(bit);
720 	return old;
721 }
722 
723 static int yas5xx_meaure_offsets(struct yas5xx *yas5xx)
724 {
725 	int ret;
726 	u16 center;
727 	u16 t, x, y1, y2;
728 	s8 ox, oy1, oy2;
729 	int i;
730 
731 	/* Actuate the init coil and measure offsets */
732 	ret = regmap_write(yas5xx->map, YAS5XX_ACTUATE_INIT_COIL, 0);
733 	if (ret)
734 		return ret;
735 
736 	/* When the initcoil is active this should be around the center */
737 	switch (yas5xx->devid) {
738 	case YAS530_DEVICE_ID:
739 		center = YAS530_DATA_CENTER;
740 		break;
741 	case YAS532_DEVICE_ID:
742 		center = YAS532_DATA_CENTER;
743 		break;
744 	default:
745 		dev_err(yas5xx->dev, "unknown device type\n");
746 		return -EINVAL;
747 	}
748 
749 	/*
750 	 * We set offsets in the interval +-31 by iterating
751 	 * +-16, +-8, +-4, +-2, +-1 adjusting the offsets each
752 	 * time, then writing the final offsets into the
753 	 * registers.
754 	 *
755 	 * NOTE: these offsets are NOT in the same unit or magnitude
756 	 * as the values for [x, y1, y2]. The value is +/-31
757 	 * but the effect on the raw values is much larger.
758 	 * The effect of the offset is to bring the measure
759 	 * rougly to the center.
760 	 */
761 	ox = 0;
762 	oy1 = 0;
763 	oy2 = 0;
764 
765 	for (i = 4; i >= 0; i--) {
766 		ret = yas5xx_set_offsets(yas5xx, ox, oy1, oy2);
767 		if (ret)
768 			return ret;
769 
770 		ret = yas5xx_measure(yas5xx, &t, &x, &y1, &y2);
771 		if (ret)
772 			return ret;
773 		dev_dbg(yas5xx->dev, "measurement %d: x=%d, y1=%d, y2=%d\n",
774 			5-i, x, y1, y2);
775 
776 		ox = yas5xx_adjust_offset(ox, i, center, x);
777 		oy1 = yas5xx_adjust_offset(oy1, i, center, y1);
778 		oy2 = yas5xx_adjust_offset(oy2, i, center, y2);
779 	}
780 
781 	/* Needed for calibration algorithm */
782 	yas5xx->hard_offsets[0] = ox;
783 	yas5xx->hard_offsets[1] = oy1;
784 	yas5xx->hard_offsets[2] = oy2;
785 	ret = yas5xx_set_offsets(yas5xx, ox, oy1, oy2);
786 	if (ret)
787 		return ret;
788 
789 	dev_info(yas5xx->dev, "discovered hard offsets: x=%d, y1=%d, y2=%d\n",
790 		 ox, oy1, oy2);
791 	return 0;
792 }
793 
794 static int yas5xx_power_on(struct yas5xx *yas5xx)
795 {
796 	unsigned int val;
797 	int ret;
798 
799 	/* Zero the test registers */
800 	ret = regmap_write(yas5xx->map, YAS5XX_TEST1, 0);
801 	if (ret)
802 		return ret;
803 	ret = regmap_write(yas5xx->map, YAS5XX_TEST2, 0);
804 	if (ret)
805 		return ret;
806 
807 	/* Set up for no interrupts, calibrated clock divider */
808 	val = FIELD_PREP(YAS5XX_CONFIG_CCK_MASK, yas5xx->calibration.dck);
809 	ret = regmap_write(yas5xx->map, YAS5XX_CONFIG, val);
810 	if (ret)
811 		return ret;
812 
813 	/* Measure interval 0 (back-to-back?)  */
814 	return regmap_write(yas5xx->map, YAS5XX_MEASURE_INTERVAL, 0);
815 }
816 
817 static int yas5xx_probe(struct i2c_client *i2c,
818 			const struct i2c_device_id *id)
819 {
820 	struct iio_dev *indio_dev;
821 	struct device *dev = &i2c->dev;
822 	struct yas5xx *yas5xx;
823 	int ret;
824 
825 	indio_dev = devm_iio_device_alloc(dev, sizeof(*yas5xx));
826 	if (!indio_dev)
827 		return -ENOMEM;
828 
829 	yas5xx = iio_priv(indio_dev);
830 	i2c_set_clientdata(i2c, indio_dev);
831 	yas5xx->dev = dev;
832 	mutex_init(&yas5xx->lock);
833 
834 	ret = iio_read_mount_matrix(dev, &yas5xx->orientation);
835 	if (ret)
836 		return ret;
837 
838 	yas5xx->regs[0].supply = "vdd";
839 	yas5xx->regs[1].supply = "iovdd";
840 	ret = devm_regulator_bulk_get(dev, ARRAY_SIZE(yas5xx->regs),
841 				      yas5xx->regs);
842 	if (ret)
843 		return dev_err_probe(dev, ret, "cannot get regulators\n");
844 
845 	ret = regulator_bulk_enable(ARRAY_SIZE(yas5xx->regs), yas5xx->regs);
846 	if (ret) {
847 		dev_err(dev, "cannot enable regulators\n");
848 		return ret;
849 	}
850 
851 	/* See comment in runtime resume callback */
852 	usleep_range(31000, 40000);
853 
854 	/* This will take the device out of reset if need be */
855 	yas5xx->reset = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_LOW);
856 	if (IS_ERR(yas5xx->reset)) {
857 		ret = dev_err_probe(dev, PTR_ERR(yas5xx->reset),
858 				    "failed to get reset line\n");
859 		goto reg_off;
860 	}
861 
862 	yas5xx->map = devm_regmap_init_i2c(i2c, &yas5xx_regmap_config);
863 	if (IS_ERR(yas5xx->map)) {
864 		dev_err(dev, "failed to allocate register map\n");
865 		ret = PTR_ERR(yas5xx->map);
866 		goto assert_reset;
867 	}
868 
869 	ret = regmap_read(yas5xx->map, YAS5XX_DEVICE_ID, &yas5xx->devid);
870 	if (ret)
871 		goto assert_reset;
872 
873 	switch (yas5xx->devid) {
874 	case YAS530_DEVICE_ID:
875 		ret = yas530_get_calibration_data(yas5xx);
876 		if (ret)
877 			goto assert_reset;
878 		dev_info(dev, "detected YAS530 MS-3E %s",
879 			 yas5xx->version ? "B" : "A");
880 		strncpy(yas5xx->name, "yas530", sizeof(yas5xx->name));
881 		break;
882 	case YAS532_DEVICE_ID:
883 		ret = yas532_get_calibration_data(yas5xx);
884 		if (ret)
885 			goto assert_reset;
886 		dev_info(dev, "detected YAS532/YAS533 MS-3R/F %s",
887 			 yas5xx->version ? "AC" : "AB");
888 		strncpy(yas5xx->name, "yas532", sizeof(yas5xx->name));
889 		break;
890 	default:
891 		ret = -ENODEV;
892 		dev_err(dev, "unhandled device ID %02x\n", yas5xx->devid);
893 		goto assert_reset;
894 	}
895 
896 	yas5xx_dump_calibration(yas5xx);
897 	ret = yas5xx_power_on(yas5xx);
898 	if (ret)
899 		goto assert_reset;
900 	ret = yas5xx_meaure_offsets(yas5xx);
901 	if (ret)
902 		goto assert_reset;
903 
904 	indio_dev->info = &yas5xx_info;
905 	indio_dev->available_scan_masks = yas5xx_scan_masks;
906 	indio_dev->modes = INDIO_DIRECT_MODE;
907 	indio_dev->name = yas5xx->name;
908 	indio_dev->channels = yas5xx_channels;
909 	indio_dev->num_channels = ARRAY_SIZE(yas5xx_channels);
910 
911 	ret = iio_triggered_buffer_setup(indio_dev, NULL,
912 					 yas5xx_handle_trigger,
913 					 NULL);
914 	if (ret) {
915 		dev_err(dev, "triggered buffer setup failed\n");
916 		goto assert_reset;
917 	}
918 
919 	ret = iio_device_register(indio_dev);
920 	if (ret) {
921 		dev_err(dev, "device register failed\n");
922 		goto cleanup_buffer;
923 	}
924 
925 	/* Take runtime PM online */
926 	pm_runtime_get_noresume(dev);
927 	pm_runtime_set_active(dev);
928 	pm_runtime_enable(dev);
929 
930 	pm_runtime_set_autosuspend_delay(dev, YAS5XX_AUTOSUSPEND_DELAY_MS);
931 	pm_runtime_use_autosuspend(dev);
932 	pm_runtime_put(dev);
933 
934 	return 0;
935 
936 cleanup_buffer:
937 	iio_triggered_buffer_cleanup(indio_dev);
938 assert_reset:
939 	gpiod_set_value_cansleep(yas5xx->reset, 1);
940 reg_off:
941 	regulator_bulk_disable(ARRAY_SIZE(yas5xx->regs), yas5xx->regs);
942 
943 	return ret;
944 }
945 
946 static int yas5xx_remove(struct i2c_client *i2c)
947 {
948 	struct iio_dev *indio_dev = i2c_get_clientdata(i2c);
949 	struct yas5xx *yas5xx = iio_priv(indio_dev);
950 	struct device *dev = &i2c->dev;
951 
952 	iio_device_unregister(indio_dev);
953 	iio_triggered_buffer_cleanup(indio_dev);
954 	/*
955 	 * Now we can't get any more reads from the device, which would
956 	 * also call pm_runtime* functions and race with our disable
957 	 * code. Disable PM runtime in orderly fashion and power down.
958 	 */
959 	pm_runtime_get_sync(dev);
960 	pm_runtime_put_noidle(dev);
961 	pm_runtime_disable(dev);
962 	gpiod_set_value_cansleep(yas5xx->reset, 1);
963 	regulator_bulk_disable(ARRAY_SIZE(yas5xx->regs), yas5xx->regs);
964 
965 	return 0;
966 }
967 
968 static int __maybe_unused yas5xx_runtime_suspend(struct device *dev)
969 {
970 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
971 	struct yas5xx *yas5xx = iio_priv(indio_dev);
972 
973 	gpiod_set_value_cansleep(yas5xx->reset, 1);
974 	regulator_bulk_disable(ARRAY_SIZE(yas5xx->regs), yas5xx->regs);
975 
976 	return 0;
977 }
978 
979 static int __maybe_unused yas5xx_runtime_resume(struct device *dev)
980 {
981 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
982 	struct yas5xx *yas5xx = iio_priv(indio_dev);
983 	int ret;
984 
985 	ret = regulator_bulk_enable(ARRAY_SIZE(yas5xx->regs), yas5xx->regs);
986 	if (ret) {
987 		dev_err(dev, "cannot enable regulators\n");
988 		return ret;
989 	}
990 
991 	/*
992 	 * The YAS530 datasheet says TVSKW is up to 30 ms, after that 1 ms
993 	 * for all voltages to settle. The YAS532 is 10ms then 4ms for the
994 	 * I2C to come online. Let's keep it safe and put this at 31ms.
995 	 */
996 	usleep_range(31000, 40000);
997 	gpiod_set_value_cansleep(yas5xx->reset, 0);
998 
999 	ret = yas5xx_power_on(yas5xx);
1000 	if (ret) {
1001 		dev_err(dev, "cannot power on\n");
1002 		goto out_reset;
1003 	}
1004 
1005 	return 0;
1006 
1007 out_reset:
1008 	gpiod_set_value_cansleep(yas5xx->reset, 1);
1009 	regulator_bulk_disable(ARRAY_SIZE(yas5xx->regs), yas5xx->regs);
1010 
1011 	return ret;
1012 }
1013 
1014 static const struct dev_pm_ops yas5xx_dev_pm_ops = {
1015 	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
1016 				pm_runtime_force_resume)
1017 	SET_RUNTIME_PM_OPS(yas5xx_runtime_suspend,
1018 			   yas5xx_runtime_resume, NULL)
1019 };
1020 
1021 static const struct i2c_device_id yas5xx_id[] = {
1022 	{"yas530", },
1023 	{"yas532", },
1024 	{"yas533", },
1025 	{}
1026 };
1027 MODULE_DEVICE_TABLE(i2c, yas5xx_id);
1028 
1029 static const struct of_device_id yas5xx_of_match[] = {
1030 	{ .compatible = "yamaha,yas530", },
1031 	{ .compatible = "yamaha,yas532", },
1032 	{ .compatible = "yamaha,yas533", },
1033 	{}
1034 };
1035 MODULE_DEVICE_TABLE(of, yas5xx_of_match);
1036 
1037 static struct i2c_driver yas5xx_driver = {
1038 	.driver	 = {
1039 		.name	= "yas5xx",
1040 		.of_match_table = yas5xx_of_match,
1041 		.pm = &yas5xx_dev_pm_ops,
1042 	},
1043 	.probe	  = yas5xx_probe,
1044 	.remove	  = yas5xx_remove,
1045 	.id_table = yas5xx_id,
1046 };
1047 module_i2c_driver(yas5xx_driver);
1048 
1049 MODULE_DESCRIPTION("Yamaha YAS53x 3-axis magnetometer driver");
1050 MODULE_AUTHOR("Linus Walleij");
1051 MODULE_LICENSE("GPL v2");
1052