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