xref: /linux/drivers/iio/light/as73211.c (revision 13845bdc869f136f92ad3d40ea09b867bb4ce467)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Support for AMS AS73211 JENCOLOR(R) Digital XYZ Sensor and AMS AS7331
4  * UVA, UVB and UVC (DUV) Ultraviolet Sensor
5  *
6  * Author: Christian Eggers <ceggers@arri.de>
7  *
8  * Copyright (c) 2020 ARRI Lighting
9  *
10  * Color light sensor with 16-bit channels for x, y, z and temperature);
11  * 7-bit I2C slave address 0x74 .. 0x77.
12  *
13  * Datasheets:
14  * AS73211: https://ams.com/documents/20143/36005/AS73211_DS000556_3-01.pdf
15  * AS7331: https://ams.com/documents/20143/9106314/AS7331_DS001047_4-00.pdf
16  */
17 
18 #include <linux/bitfield.h>
19 #include <linux/completion.h>
20 #include <linux/delay.h>
21 #include <linux/i2c.h>
22 #include <linux/iio/buffer.h>
23 #include <linux/iio/iio.h>
24 #include <linux/iio/sysfs.h>
25 #include <linux/iio/trigger_consumer.h>
26 #include <linux/iio/triggered_buffer.h>
27 #include <linux/module.h>
28 #include <linux/mutex.h>
29 #include <linux/pm.h>
30 #include <linux/units.h>
31 
32 #define AS73211_DRV_NAME "as73211"
33 
34 /* AS73211 configuration registers */
35 #define AS73211_REG_OSR    0x0
36 #define AS73211_REG_AGEN   0x2
37 #define AS73211_REG_CREG1  0x6
38 #define AS73211_REG_CREG2  0x7
39 #define AS73211_REG_CREG3  0x8
40 
41 /* AS73211 output register bank */
42 #define AS73211_OUT_OSR_STATUS    0
43 #define AS73211_OUT_TEMP          1
44 #define AS73211_OUT_MRES1         2
45 #define AS73211_OUT_MRES2         3
46 #define AS73211_OUT_MRES3         4
47 
48 #define AS73211_OSR_SS            BIT(7)
49 #define AS73211_OSR_PD            BIT(6)
50 #define AS73211_OSR_SW_RES        BIT(3)
51 #define AS73211_OSR_DOS_MASK      GENMASK(2, 0)
52 #define AS73211_OSR_DOS_CONFIG    FIELD_PREP(AS73211_OSR_DOS_MASK, 0x2)
53 #define AS73211_OSR_DOS_MEASURE   FIELD_PREP(AS73211_OSR_DOS_MASK, 0x3)
54 
55 #define AS73211_AGEN_DEVID_MASK   GENMASK(7, 4)
56 #define AS73211_AGEN_DEVID(x)     FIELD_PREP(AS73211_AGEN_DEVID_MASK, (x))
57 #define AS73211_AGEN_MUT_MASK     GENMASK(3, 0)
58 #define AS73211_AGEN_MUT(x)       FIELD_PREP(AS73211_AGEN_MUT_MASK, (x))
59 
60 #define AS73211_CREG1_GAIN_MASK   GENMASK(7, 4)
61 #define AS73211_CREG1_GAIN_1      11
62 #define AS73211_CREG1_TIME_MASK   GENMASK(3, 0)
63 
64 #define AS73211_CREG3_CCLK_MASK   GENMASK(1, 0)
65 
66 #define AS73211_OSR_STATUS_OUTCONVOF  BIT(15)
67 #define AS73211_OSR_STATUS_MRESOF     BIT(14)
68 #define AS73211_OSR_STATUS_ADCOF      BIT(13)
69 #define AS73211_OSR_STATUS_LDATA      BIT(12)
70 #define AS73211_OSR_STATUS_NDATA      BIT(11)
71 #define AS73211_OSR_STATUS_NOTREADY   BIT(10)
72 
73 #define AS73211_SAMPLE_FREQ_BASE      1024000
74 
75 #define AS73211_SAMPLE_TIME_NUM       15
76 #define AS73211_SAMPLE_TIME_MAX_MS    BIT(AS73211_SAMPLE_TIME_NUM - 1)
77 
78 /* Available sample frequencies are 1.024MHz multiplied by powers of two. */
79 static const int as73211_samp_freq_avail[] = {
80 	AS73211_SAMPLE_FREQ_BASE * 1,
81 	AS73211_SAMPLE_FREQ_BASE * 2,
82 	AS73211_SAMPLE_FREQ_BASE * 4,
83 	AS73211_SAMPLE_FREQ_BASE * 8,
84 };
85 
86 static const int as73211_hardwaregain_avail[] = {
87 	1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048,
88 };
89 
90 struct as73211_data;
91 
92 /**
93  * struct as73211_spec_dev_data - device-specific data
94  * @intensity_scale:  Function to retrieve intensity scale values.
95  * @channels:          Device channels.
96  * @num_channels:     Number of channels of the device.
97  */
98 struct as73211_spec_dev_data {
99 	int (*intensity_scale)(struct as73211_data *data, int chan, int *val, int *val2);
100 	struct iio_chan_spec const *channels;
101 	int num_channels;
102 };
103 
104 /**
105  * struct as73211_data - Instance data for one AS73211
106  * @client: I2C client.
107  * @osr:    Cached Operational State Register.
108  * @creg1:  Cached Configuration Register 1.
109  * @creg2:  Cached Configuration Register 2.
110  * @creg3:  Cached Configuration Register 3.
111  * @mutex:  Keeps cached registers in sync with the device.
112  * @completion: Completion to wait for interrupt.
113  * @int_time_avail: Available integration times (depend on sampling frequency).
114  * @spec_dev: device-specific configuration.
115  */
116 struct as73211_data {
117 	struct i2c_client *client;
118 	u8 osr;
119 	u8 creg1;
120 	u8 creg2;
121 	u8 creg3;
122 	struct mutex mutex;
123 	struct completion completion;
124 	int int_time_avail[AS73211_SAMPLE_TIME_NUM * 2];
125 	const struct as73211_spec_dev_data *spec_dev;
126 };
127 
128 #define AS73211_COLOR_CHANNEL(_color, _si, _addr) { \
129 	.type = IIO_INTENSITY, \
130 	.modified = 1, \
131 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE), \
132 	.info_mask_shared_by_type = \
133 		BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
134 		BIT(IIO_CHAN_INFO_HARDWAREGAIN) | \
135 		BIT(IIO_CHAN_INFO_INT_TIME), \
136 	.info_mask_shared_by_type_available = \
137 		BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
138 		BIT(IIO_CHAN_INFO_HARDWAREGAIN) | \
139 		BIT(IIO_CHAN_INFO_INT_TIME), \
140 	.channel2 = IIO_MOD_##_color, \
141 	.address = _addr, \
142 	.scan_index = _si, \
143 	.scan_type = { \
144 		.sign = 'u', \
145 		.realbits = 16, \
146 		.storagebits = 16, \
147 		.endianness = IIO_LE, \
148 	}, \
149 }
150 
151 #define AS73211_OFFSET_TEMP_INT    (-66)
152 #define AS73211_OFFSET_TEMP_MICRO  900000
153 #define AS73211_SCALE_TEMP_INT     0
154 #define AS73211_SCALE_TEMP_MICRO   50000
155 
156 #define AS73211_SCALE_X 277071108  /* nW/m^2 */
157 #define AS73211_SCALE_Y 298384270  /* nW/m^2 */
158 #define AS73211_SCALE_Z 160241927  /* nW/m^2 */
159 
160 #define AS7331_SCALE_UVA 340000  /* nW/cm^2 */
161 #define AS7331_SCALE_UVB 378000  /* nW/cm^2 */
162 #define AS7331_SCALE_UVC 166000  /* nW/cm^2 */
163 
164 /* Channel order MUST match devices result register order */
165 #define AS73211_SCAN_INDEX_TEMP 0
166 #define AS73211_SCAN_INDEX_X    1
167 #define AS73211_SCAN_INDEX_Y    2
168 #define AS73211_SCAN_INDEX_Z    3
169 #define AS73211_SCAN_INDEX_TS   4
170 
171 #define AS73211_SCAN_MASK_COLOR ( \
172 	BIT(AS73211_SCAN_INDEX_X) |   \
173 	BIT(AS73211_SCAN_INDEX_Y) |   \
174 	BIT(AS73211_SCAN_INDEX_Z))
175 
176 #define AS73211_SCAN_MASK_ALL (    \
177 	BIT(AS73211_SCAN_INDEX_TEMP) | \
178 	AS73211_SCAN_MASK_COLOR)
179 
180 static const unsigned long as73211_scan_masks[] = {
181 	AS73211_SCAN_MASK_COLOR,
182 	AS73211_SCAN_MASK_ALL,
183 	0
184 };
185 
186 static const struct iio_chan_spec as73211_channels[] = {
187 	{
188 		.type = IIO_TEMP,
189 		.info_mask_separate =
190 			BIT(IIO_CHAN_INFO_RAW) |
191 			BIT(IIO_CHAN_INFO_OFFSET) |
192 			BIT(IIO_CHAN_INFO_SCALE),
193 		.address = AS73211_OUT_TEMP,
194 		.scan_index = AS73211_SCAN_INDEX_TEMP,
195 		.scan_type = {
196 			.sign = 'u',
197 			.realbits = 16,
198 			.storagebits = 16,
199 			.endianness = IIO_LE,
200 		}
201 	},
202 	AS73211_COLOR_CHANNEL(X, AS73211_SCAN_INDEX_X, AS73211_OUT_MRES1),
203 	AS73211_COLOR_CHANNEL(Y, AS73211_SCAN_INDEX_Y, AS73211_OUT_MRES2),
204 	AS73211_COLOR_CHANNEL(Z, AS73211_SCAN_INDEX_Z, AS73211_OUT_MRES3),
205 	IIO_CHAN_SOFT_TIMESTAMP(AS73211_SCAN_INDEX_TS),
206 };
207 
208 static const struct iio_chan_spec as7331_channels[] = {
209 	{
210 		.type = IIO_TEMP,
211 		.info_mask_separate =
212 			BIT(IIO_CHAN_INFO_RAW) |
213 			BIT(IIO_CHAN_INFO_OFFSET) |
214 			BIT(IIO_CHAN_INFO_SCALE),
215 		.address = AS73211_OUT_TEMP,
216 		.scan_index = AS73211_SCAN_INDEX_TEMP,
217 		.scan_type = {
218 			.sign = 'u',
219 			.realbits = 16,
220 			.storagebits = 16,
221 			.endianness = IIO_LE,
222 		}
223 	},
224 	AS73211_COLOR_CHANNEL(LIGHT_UVA, AS73211_SCAN_INDEX_X, AS73211_OUT_MRES1),
225 	AS73211_COLOR_CHANNEL(LIGHT_UVB, AS73211_SCAN_INDEX_Y, AS73211_OUT_MRES2),
226 	AS73211_COLOR_CHANNEL(LIGHT_DUV, AS73211_SCAN_INDEX_Z, AS73211_OUT_MRES3),
227 	IIO_CHAN_SOFT_TIMESTAMP(AS73211_SCAN_INDEX_TS),
228 };
229 
230 static unsigned int as73211_integration_time_1024cyc(struct as73211_data *data)
231 {
232 	/*
233 	 * Return integration time in units of 1024 clock cycles. Integration time
234 	 * in CREG1 is in powers of 2 (x 1024 cycles).
235 	 */
236 	return BIT(FIELD_GET(AS73211_CREG1_TIME_MASK, data->creg1));
237 }
238 
239 static unsigned int as73211_integration_time_us(struct as73211_data *data,
240 						 unsigned int integration_time_1024cyc)
241 {
242 	/*
243 	 * f_samp is configured in CREG3 in powers of 2 (x 1.024 MHz)
244 	 * t_cycl is configured in CREG1 in powers of 2 (x 1024 cycles)
245 	 * t_int_us = 1 / (f_samp) * t_cycl * US_PER_SEC
246 	 *          = 1 / (2^CREG3_CCLK * 1,024,000) * 2^CREG1_CYCLES * 1,024 * US_PER_SEC
247 	 *          = 2^(-CREG3_CCLK) * 2^CREG1_CYCLES * 1,000
248 	 * In order to get rid of negative exponents, we extend the "fraction"
249 	 * by 2^3 (CREG3_CCLK,max = 3)
250 	 * t_int_us = 2^(3-CREG3_CCLK) * 2^CREG1_CYCLES * 125
251 	 */
252 	return BIT(3 - FIELD_GET(AS73211_CREG3_CCLK_MASK, data->creg3)) *
253 		integration_time_1024cyc * 125;
254 }
255 
256 static void as73211_integration_time_calc_avail(struct as73211_data *data)
257 {
258 	int i;
259 
260 	for (i = 0; i < ARRAY_SIZE(data->int_time_avail) / 2; i++) {
261 		unsigned int time_us = as73211_integration_time_us(data, BIT(i));
262 
263 		data->int_time_avail[i * 2 + 0] = time_us / USEC_PER_SEC;
264 		data->int_time_avail[i * 2 + 1] = time_us % USEC_PER_SEC;
265 	}
266 }
267 
268 static unsigned int as73211_gain(struct as73211_data *data)
269 {
270 	/* gain can be calculated from CREG1 as 2^(11 - CREG1_GAIN) */
271 	return BIT(AS73211_CREG1_GAIN_1 - FIELD_GET(AS73211_CREG1_GAIN_MASK, data->creg1));
272 }
273 
274 /* must be called with as73211_data::mutex held. */
275 static int as73211_req_data(struct as73211_data *data)
276 {
277 	unsigned int time_us = as73211_integration_time_us(data,
278 							    as73211_integration_time_1024cyc(data));
279 	struct device *dev = &data->client->dev;
280 	union i2c_smbus_data smbus_data;
281 	u16 osr_status;
282 	int ret;
283 
284 	if (data->client->irq)
285 		reinit_completion(&data->completion);
286 
287 	/*
288 	 * During measurement, there should be no traffic on the i2c bus as the
289 	 * electrical noise would disturb the measurement process.
290 	 */
291 	i2c_lock_bus(data->client->adapter, I2C_LOCK_SEGMENT);
292 
293 	data->osr &= ~AS73211_OSR_DOS_MASK;
294 	data->osr |= AS73211_OSR_DOS_MEASURE | AS73211_OSR_SS;
295 
296 	smbus_data.byte = data->osr;
297 	ret = __i2c_smbus_xfer(data->client->adapter, data->client->addr,
298 			data->client->flags, I2C_SMBUS_WRITE,
299 			AS73211_REG_OSR, I2C_SMBUS_BYTE_DATA, &smbus_data);
300 	if (ret < 0) {
301 		i2c_unlock_bus(data->client->adapter, I2C_LOCK_SEGMENT);
302 		return ret;
303 	}
304 
305 	/*
306 	 * Reset AS73211_OSR_SS (is self clearing) in order to avoid unintentional
307 	 * triggering of further measurements later.
308 	 */
309 	data->osr &= ~AS73211_OSR_SS;
310 
311 	/*
312 	 * Add 33% extra margin for the timeout. fclk,min = fclk,typ - 27%.
313 	 */
314 	time_us += time_us / 3;
315 	if (data->client->irq) {
316 		ret = wait_for_completion_timeout(&data->completion, usecs_to_jiffies(time_us));
317 		if (!ret) {
318 			dev_err(dev, "timeout waiting for READY IRQ\n");
319 			i2c_unlock_bus(data->client->adapter, I2C_LOCK_SEGMENT);
320 			return -ETIMEDOUT;
321 		}
322 	} else {
323 		/* Wait integration time */
324 		usleep_range(time_us, 2 * time_us);
325 	}
326 
327 	i2c_unlock_bus(data->client->adapter, I2C_LOCK_SEGMENT);
328 
329 	ret = i2c_smbus_read_word_data(data->client, AS73211_OUT_OSR_STATUS);
330 	if (ret < 0)
331 		return ret;
332 
333 	osr_status = ret;
334 	if (osr_status != (AS73211_OSR_DOS_MEASURE | AS73211_OSR_STATUS_NDATA)) {
335 		if (osr_status & AS73211_OSR_SS) {
336 			dev_err(dev, "%s() Measurement has not stopped\n", __func__);
337 			return -ETIME;
338 		}
339 		if (osr_status & AS73211_OSR_STATUS_NOTREADY) {
340 			dev_err(dev, "%s() Data is not ready\n", __func__);
341 			return -ENODATA;
342 		}
343 		if (!(osr_status & AS73211_OSR_STATUS_NDATA)) {
344 			dev_err(dev, "%s() No new data available\n", __func__);
345 			return -ENODATA;
346 		}
347 		if (osr_status & AS73211_OSR_STATUS_LDATA) {
348 			dev_err(dev, "%s() Result buffer overrun\n", __func__);
349 			return -ENOBUFS;
350 		}
351 		if (osr_status & AS73211_OSR_STATUS_ADCOF) {
352 			dev_err(dev, "%s() ADC overflow\n", __func__);
353 			return -EOVERFLOW;
354 		}
355 		if (osr_status & AS73211_OSR_STATUS_MRESOF) {
356 			dev_err(dev, "%s() Measurement result overflow\n", __func__);
357 			return -EOVERFLOW;
358 		}
359 		if (osr_status & AS73211_OSR_STATUS_OUTCONVOF) {
360 			dev_err(dev, "%s() Timer overflow\n", __func__);
361 			return -EOVERFLOW;
362 		}
363 		dev_err(dev, "%s() Unexpected status value\n", __func__);
364 		return -EIO;
365 	}
366 
367 	return 0;
368 }
369 
370 static int as73211_intensity_scale(struct as73211_data *data, int chan,
371 				   int *val, int *val2)
372 {
373 	switch (chan) {
374 	case IIO_MOD_X:
375 		*val = AS73211_SCALE_X;
376 		break;
377 	case IIO_MOD_Y:
378 		*val = AS73211_SCALE_Y;
379 		break;
380 	case IIO_MOD_Z:
381 		*val = AS73211_SCALE_Z;
382 		break;
383 	default:
384 		return -EINVAL;
385 	}
386 	*val2 = as73211_integration_time_1024cyc(data) * as73211_gain(data);
387 
388 	return IIO_VAL_FRACTIONAL;
389 }
390 
391 static int as7331_intensity_scale(struct as73211_data *data, int chan,
392 				  int *val, int *val2)
393 {
394 	switch (chan) {
395 	case IIO_MOD_LIGHT_UVA:
396 		*val = AS7331_SCALE_UVA;
397 		break;
398 	case IIO_MOD_LIGHT_UVB:
399 		*val = AS7331_SCALE_UVB;
400 		break;
401 	case IIO_MOD_LIGHT_DUV:
402 		*val = AS7331_SCALE_UVC;
403 		break;
404 	default:
405 		return -EINVAL;
406 	}
407 	*val2 = as73211_integration_time_1024cyc(data) * as73211_gain(data);
408 
409 	return IIO_VAL_FRACTIONAL;
410 }
411 
412 static int as73211_read_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan,
413 			     int *val, int *val2, long mask)
414 {
415 	struct as73211_data *data = iio_priv(indio_dev);
416 
417 	switch (mask) {
418 	case IIO_CHAN_INFO_RAW: {
419 		int ret;
420 
421 		ret = iio_device_claim_direct_mode(indio_dev);
422 		if (ret < 0)
423 			return ret;
424 
425 		ret = as73211_req_data(data);
426 		if (ret < 0) {
427 			iio_device_release_direct_mode(indio_dev);
428 			return ret;
429 		}
430 
431 		ret = i2c_smbus_read_word_data(data->client, chan->address);
432 		iio_device_release_direct_mode(indio_dev);
433 		if (ret < 0)
434 			return ret;
435 
436 		*val = ret;
437 		return IIO_VAL_INT;
438 	}
439 	case IIO_CHAN_INFO_OFFSET:
440 		*val = AS73211_OFFSET_TEMP_INT;
441 		*val2 = AS73211_OFFSET_TEMP_MICRO;
442 		return IIO_VAL_INT_PLUS_MICRO;
443 
444 	case IIO_CHAN_INFO_SCALE:
445 		switch (chan->type) {
446 		case IIO_TEMP:
447 			*val = AS73211_SCALE_TEMP_INT;
448 			*val2 = AS73211_SCALE_TEMP_MICRO;
449 			return IIO_VAL_INT_PLUS_MICRO;
450 
451 		case IIO_INTENSITY:
452 			return data->spec_dev->intensity_scale(data, chan->channel2,
453 							       val, val2);
454 
455 		default:
456 			return -EINVAL;
457 		}
458 
459 	case IIO_CHAN_INFO_SAMP_FREQ:
460 		/* f_samp is configured in CREG3 in powers of 2 (x 1.024 MHz) */
461 		*val = BIT(FIELD_GET(AS73211_CREG3_CCLK_MASK, data->creg3)) *
462 			AS73211_SAMPLE_FREQ_BASE;
463 		return IIO_VAL_INT;
464 
465 	case IIO_CHAN_INFO_HARDWAREGAIN:
466 		*val = as73211_gain(data);
467 		return IIO_VAL_INT;
468 
469 	case IIO_CHAN_INFO_INT_TIME: {
470 		unsigned int time_us;
471 
472 		mutex_lock(&data->mutex);
473 		time_us = as73211_integration_time_us(data, as73211_integration_time_1024cyc(data));
474 		mutex_unlock(&data->mutex);
475 		*val = time_us / USEC_PER_SEC;
476 		*val2 = time_us % USEC_PER_SEC;
477 		return IIO_VAL_INT_PLUS_MICRO;
478 
479 	default:
480 		return -EINVAL;
481 	}}
482 }
483 
484 static int as73211_read_avail(struct iio_dev *indio_dev, struct iio_chan_spec const *chan,
485 			       const int **vals, int *type, int *length, long mask)
486 {
487 	struct as73211_data *data = iio_priv(indio_dev);
488 
489 	switch (mask) {
490 	case IIO_CHAN_INFO_SAMP_FREQ:
491 		*length = ARRAY_SIZE(as73211_samp_freq_avail);
492 		*vals = as73211_samp_freq_avail;
493 		*type = IIO_VAL_INT;
494 		return IIO_AVAIL_LIST;
495 
496 	case IIO_CHAN_INFO_HARDWAREGAIN:
497 		*length = ARRAY_SIZE(as73211_hardwaregain_avail);
498 		*vals = as73211_hardwaregain_avail;
499 		*type = IIO_VAL_INT;
500 		return IIO_AVAIL_LIST;
501 
502 	case IIO_CHAN_INFO_INT_TIME:
503 		*length = ARRAY_SIZE(data->int_time_avail);
504 		*vals = data->int_time_avail;
505 		*type = IIO_VAL_INT_PLUS_MICRO;
506 		return IIO_AVAIL_LIST;
507 
508 	default:
509 		return -EINVAL;
510 	}
511 }
512 
513 static int _as73211_write_raw(struct iio_dev *indio_dev,
514 			       struct iio_chan_spec const *chan __always_unused,
515 			       int val, int val2, long mask)
516 {
517 	struct as73211_data *data = iio_priv(indio_dev);
518 	int ret;
519 
520 	switch (mask) {
521 	case IIO_CHAN_INFO_SAMP_FREQ: {
522 		int reg_bits, freq_kHz = val / HZ_PER_KHZ;  /* 1024, 2048, ... */
523 
524 		/* val must be 1024 * 2^x */
525 		if (val < 0 || (freq_kHz * HZ_PER_KHZ) != val ||
526 				!is_power_of_2(freq_kHz) || val2)
527 			return -EINVAL;
528 
529 		/* f_samp is configured in CREG3 in powers of 2 (x 1.024 MHz (=2^10)) */
530 		reg_bits = ilog2(freq_kHz) - 10;
531 		if (!FIELD_FIT(AS73211_CREG3_CCLK_MASK, reg_bits))
532 			return -EINVAL;
533 
534 		data->creg3 &= ~AS73211_CREG3_CCLK_MASK;
535 		data->creg3 |= FIELD_PREP(AS73211_CREG3_CCLK_MASK, reg_bits);
536 		as73211_integration_time_calc_avail(data);
537 
538 		ret = i2c_smbus_write_byte_data(data->client, AS73211_REG_CREG3, data->creg3);
539 		if (ret < 0)
540 			return ret;
541 
542 		return 0;
543 	}
544 	case IIO_CHAN_INFO_HARDWAREGAIN: {
545 		unsigned int reg_bits;
546 
547 		if (val < 0 || !is_power_of_2(val) || val2)
548 			return -EINVAL;
549 
550 		/* gain can be calculated from CREG1 as 2^(11 - CREG1_GAIN) */
551 		reg_bits = AS73211_CREG1_GAIN_1 - ilog2(val);
552 		if (!FIELD_FIT(AS73211_CREG1_GAIN_MASK, reg_bits))
553 			return -EINVAL;
554 
555 		data->creg1 &= ~AS73211_CREG1_GAIN_MASK;
556 		data->creg1 |= FIELD_PREP(AS73211_CREG1_GAIN_MASK, reg_bits);
557 
558 		ret = i2c_smbus_write_byte_data(data->client, AS73211_REG_CREG1, data->creg1);
559 		if (ret < 0)
560 			return ret;
561 
562 		return 0;
563 	}
564 	case IIO_CHAN_INFO_INT_TIME: {
565 		int val_us = val * USEC_PER_SEC + val2;
566 		int time_ms;
567 		int reg_bits;
568 
569 		/* f_samp is configured in CREG3 in powers of 2 (x 1.024 MHz) */
570 		int f_samp_1_024mhz = BIT(FIELD_GET(AS73211_CREG3_CCLK_MASK, data->creg3));
571 
572 		/*
573 		 * time_ms = time_us * US_PER_MS * f_samp_1_024mhz / MHZ_PER_HZ
574 		 *         = time_us * f_samp_1_024mhz / 1000
575 		 */
576 		time_ms = (val_us * f_samp_1_024mhz) / 1000;  /* 1 ms, 2 ms, ... (power of two) */
577 		if (time_ms < 0 || !is_power_of_2(time_ms) || time_ms > AS73211_SAMPLE_TIME_MAX_MS)
578 			return -EINVAL;
579 
580 		reg_bits = ilog2(time_ms);
581 		if (!FIELD_FIT(AS73211_CREG1_TIME_MASK, reg_bits))
582 			return -EINVAL;  /* not possible due to previous tests */
583 
584 		data->creg1 &= ~AS73211_CREG1_TIME_MASK;
585 		data->creg1 |= FIELD_PREP(AS73211_CREG1_TIME_MASK, reg_bits);
586 
587 		ret = i2c_smbus_write_byte_data(data->client, AS73211_REG_CREG1, data->creg1);
588 		if (ret < 0)
589 			return ret;
590 
591 		return 0;
592 
593 	default:
594 		return -EINVAL;
595 	}}
596 }
597 
598 static int as73211_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan,
599 			      int val, int val2, long mask)
600 {
601 	struct as73211_data *data = iio_priv(indio_dev);
602 	int ret;
603 
604 	mutex_lock(&data->mutex);
605 
606 	ret = iio_device_claim_direct_mode(indio_dev);
607 	if (ret < 0)
608 		goto error_unlock;
609 
610 	/* Need to switch to config mode ... */
611 	if ((data->osr & AS73211_OSR_DOS_MASK) != AS73211_OSR_DOS_CONFIG) {
612 		data->osr &= ~AS73211_OSR_DOS_MASK;
613 		data->osr |= AS73211_OSR_DOS_CONFIG;
614 
615 		ret = i2c_smbus_write_byte_data(data->client, AS73211_REG_OSR, data->osr);
616 		if (ret < 0)
617 			goto error_release;
618 	}
619 
620 	ret = _as73211_write_raw(indio_dev, chan, val, val2, mask);
621 
622 error_release:
623 	iio_device_release_direct_mode(indio_dev);
624 error_unlock:
625 	mutex_unlock(&data->mutex);
626 	return ret;
627 }
628 
629 static irqreturn_t as73211_ready_handler(int irq __always_unused, void *priv)
630 {
631 	struct as73211_data *data = iio_priv(priv);
632 
633 	complete(&data->completion);
634 
635 	return IRQ_HANDLED;
636 }
637 
638 static irqreturn_t as73211_trigger_handler(int irq __always_unused, void *p)
639 {
640 	struct iio_poll_func *pf = p;
641 	struct iio_dev *indio_dev = pf->indio_dev;
642 	struct as73211_data *data = iio_priv(indio_dev);
643 	struct {
644 		__le16 chan[4];
645 		aligned_s64 ts;
646 	} scan;
647 	int data_result, ret;
648 
649 	mutex_lock(&data->mutex);
650 
651 	data_result = as73211_req_data(data);
652 	if (data_result < 0 && data_result != -EOVERFLOW)
653 		goto done;  /* don't push any data for errors other than EOVERFLOW */
654 
655 	if (*indio_dev->active_scan_mask == AS73211_SCAN_MASK_ALL) {
656 		/* Optimization for reading all (color + temperature) channels */
657 		u8 addr = as73211_channels[0].address;
658 		struct i2c_msg msgs[] = {
659 			{
660 				.addr = data->client->addr,
661 				.flags = 0,
662 				.len = 1,
663 				.buf = &addr,
664 			},
665 			{
666 				.addr = data->client->addr,
667 				.flags = I2C_M_RD,
668 				.len = sizeof(scan.chan),
669 				.buf = (u8 *)&scan.chan,
670 			},
671 		};
672 
673 		ret = i2c_transfer(data->client->adapter, msgs, ARRAY_SIZE(msgs));
674 		if (ret < 0)
675 			goto done;
676 	} else {
677 		/* Optimization for reading only color channels */
678 
679 		/* AS73211 starts reading at address 2 */
680 		ret = i2c_master_recv(data->client,
681 				(char *)&scan.chan[0], 3 * sizeof(scan.chan[0]));
682 		if (ret < 0)
683 			goto done;
684 
685 		/* Avoid pushing uninitialized data */
686 		scan.chan[3] = 0;
687 	}
688 
689 	if (data_result) {
690 		/*
691 		 * Saturate all channels (in case of overflows). Temperature channel
692 		 * is not affected by overflows.
693 		 */
694 		if (*indio_dev->active_scan_mask == AS73211_SCAN_MASK_ALL) {
695 			scan.chan[1] = cpu_to_le16(U16_MAX);
696 			scan.chan[2] = cpu_to_le16(U16_MAX);
697 			scan.chan[3] = cpu_to_le16(U16_MAX);
698 		} else {
699 			scan.chan[0] = cpu_to_le16(U16_MAX);
700 			scan.chan[1] = cpu_to_le16(U16_MAX);
701 			scan.chan[2] = cpu_to_le16(U16_MAX);
702 		}
703 	}
704 
705 	iio_push_to_buffers_with_timestamp(indio_dev, &scan, iio_get_time_ns(indio_dev));
706 
707 done:
708 	mutex_unlock(&data->mutex);
709 	iio_trigger_notify_done(indio_dev->trig);
710 
711 	return IRQ_HANDLED;
712 }
713 
714 static const struct iio_info as73211_info = {
715 	.read_raw = as73211_read_raw,
716 	.read_avail = as73211_read_avail,
717 	.write_raw = as73211_write_raw,
718 };
719 
720 static int as73211_power(struct iio_dev *indio_dev, bool state)
721 {
722 	struct as73211_data *data = iio_priv(indio_dev);
723 	int ret;
724 
725 	mutex_lock(&data->mutex);
726 
727 	if (state)
728 		data->osr &= ~AS73211_OSR_PD;
729 	else
730 		data->osr |= AS73211_OSR_PD;
731 
732 	ret = i2c_smbus_write_byte_data(data->client, AS73211_REG_OSR, data->osr);
733 
734 	mutex_unlock(&data->mutex);
735 
736 	if (ret < 0)
737 		return ret;
738 
739 	return 0;
740 }
741 
742 static void as73211_power_disable(void *data)
743 {
744 	struct iio_dev *indio_dev = data;
745 
746 	as73211_power(indio_dev, false);
747 }
748 
749 static int as73211_probe(struct i2c_client *client)
750 {
751 	struct device *dev = &client->dev;
752 	struct as73211_data *data;
753 	struct iio_dev *indio_dev;
754 	int ret;
755 
756 	indio_dev = devm_iio_device_alloc(dev, sizeof(*data));
757 	if (!indio_dev)
758 		return -ENOMEM;
759 
760 	data = iio_priv(indio_dev);
761 	i2c_set_clientdata(client, indio_dev);
762 	data->client = client;
763 
764 	data->spec_dev = i2c_get_match_data(client);
765 	if (!data->spec_dev)
766 		return -EINVAL;
767 
768 	mutex_init(&data->mutex);
769 	init_completion(&data->completion);
770 
771 	indio_dev->info = &as73211_info;
772 	indio_dev->name = AS73211_DRV_NAME;
773 	indio_dev->channels = data->spec_dev->channels;
774 	indio_dev->num_channels = data->spec_dev->num_channels;
775 	indio_dev->modes = INDIO_DIRECT_MODE;
776 	indio_dev->available_scan_masks = as73211_scan_masks;
777 
778 	ret = i2c_smbus_read_byte_data(data->client, AS73211_REG_OSR);
779 	if (ret < 0)
780 		return ret;
781 	data->osr = ret;
782 
783 	/* reset device */
784 	data->osr |= AS73211_OSR_SW_RES;
785 	ret = i2c_smbus_write_byte_data(data->client, AS73211_REG_OSR, data->osr);
786 	if (ret < 0)
787 		return ret;
788 
789 	ret = i2c_smbus_read_byte_data(data->client, AS73211_REG_OSR);
790 	if (ret < 0)
791 		return ret;
792 	data->osr = ret;
793 
794 	/*
795 	 * Reading AGEN is only possible after reset (AGEN is not available if
796 	 * device is in measurement mode).
797 	 */
798 	ret = i2c_smbus_read_byte_data(data->client, AS73211_REG_AGEN);
799 	if (ret < 0)
800 		return ret;
801 
802 	/* At the time of writing this driver, only DEVID 2 and MUT 1 are known. */
803 	if ((ret & AS73211_AGEN_DEVID_MASK) != AS73211_AGEN_DEVID(2) ||
804 	    (ret & AS73211_AGEN_MUT_MASK) != AS73211_AGEN_MUT(1))
805 		return -ENODEV;
806 
807 	ret = i2c_smbus_read_byte_data(data->client, AS73211_REG_CREG1);
808 	if (ret < 0)
809 		return ret;
810 	data->creg1 = ret;
811 
812 	ret = i2c_smbus_read_byte_data(data->client, AS73211_REG_CREG2);
813 	if (ret < 0)
814 		return ret;
815 	data->creg2 = ret;
816 
817 	ret = i2c_smbus_read_byte_data(data->client, AS73211_REG_CREG3);
818 	if (ret < 0)
819 		return ret;
820 	data->creg3 = ret;
821 	as73211_integration_time_calc_avail(data);
822 
823 	ret = as73211_power(indio_dev, true);
824 	if (ret < 0)
825 		return ret;
826 
827 	ret = devm_add_action_or_reset(dev, as73211_power_disable, indio_dev);
828 	if (ret)
829 		return ret;
830 
831 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev, NULL, as73211_trigger_handler, NULL);
832 	if (ret)
833 		return ret;
834 
835 	if (client->irq) {
836 		ret = devm_request_threaded_irq(&client->dev, client->irq,
837 				NULL,
838 				as73211_ready_handler,
839 				IRQF_ONESHOT,
840 				client->name, indio_dev);
841 		if (ret)
842 			return ret;
843 	}
844 
845 	return devm_iio_device_register(dev, indio_dev);
846 }
847 
848 static int as73211_suspend(struct device *dev)
849 {
850 	struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
851 
852 	return as73211_power(indio_dev, false);
853 }
854 
855 static int as73211_resume(struct device *dev)
856 {
857 	struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
858 
859 	return as73211_power(indio_dev, true);
860 }
861 
862 static DEFINE_SIMPLE_DEV_PM_OPS(as73211_pm_ops, as73211_suspend,
863 				as73211_resume);
864 
865 static const struct as73211_spec_dev_data as73211_spec = {
866 	.intensity_scale = as73211_intensity_scale,
867 	.channels = as73211_channels,
868 	.num_channels = ARRAY_SIZE(as73211_channels),
869 };
870 
871 static const struct as73211_spec_dev_data as7331_spec = {
872 	.intensity_scale = as7331_intensity_scale,
873 	.channels = as7331_channels,
874 	.num_channels = ARRAY_SIZE(as7331_channels),
875 };
876 
877 static const struct of_device_id as73211_of_match[] = {
878 	{ .compatible = "ams,as73211", &as73211_spec },
879 	{ .compatible = "ams,as7331", &as7331_spec },
880 	{ }
881 };
882 MODULE_DEVICE_TABLE(of, as73211_of_match);
883 
884 static const struct i2c_device_id as73211_id[] = {
885 	{ "as73211", (kernel_ulong_t)&as73211_spec },
886 	{ "as7331", (kernel_ulong_t)&as7331_spec },
887 	{ }
888 };
889 MODULE_DEVICE_TABLE(i2c, as73211_id);
890 
891 static struct i2c_driver as73211_driver = {
892 	.driver = {
893 		.name           = AS73211_DRV_NAME,
894 		.of_match_table = as73211_of_match,
895 		.pm             = pm_sleep_ptr(&as73211_pm_ops),
896 	},
897 	.probe      = as73211_probe,
898 	.id_table   = as73211_id,
899 };
900 module_i2c_driver(as73211_driver);
901 
902 MODULE_AUTHOR("Christian Eggers <ceggers@arri.de>");
903 MODULE_DESCRIPTION("AS73211 XYZ True Color Sensor driver");
904 MODULE_LICENSE("GPL");
905