brintos

brintos / linux-shallow public Read only

0
0
Text · 33.0 KiB · 76711c3 Raw
1354 lines · c
1// SPDX-License-Identifier: GPL-2.0-only2/*3 * BU27034ANUC ROHM Ambient Light Sensor4 *5 * Copyright (c) 2023, ROHM Semiconductor.6 */7 8#include <linux/bitfield.h>9#include <linux/bits.h>10#include <linux/device.h>11#include <linux/i2c.h>12#include <linux/module.h>13#include <linux/property.h>14#include <linux/regmap.h>15#include <linux/regulator/consumer.h>16#include <linux/units.h>17 18#include <linux/iio/buffer.h>19#include <linux/iio/iio.h>20#include <linux/iio/iio-gts-helper.h>21#include <linux/iio/kfifo_buf.h>22 23#define BU27034_REG_SYSTEM_CONTROL	0x4024#define BU27034_MASK_SW_RESET		BIT(7)25#define BU27034_MASK_PART_ID		GENMASK(5, 0)26#define BU27034_ID			0x1927#define BU27034_REG_MODE_CONTROL1	0x4128#define BU27034_MASK_MEAS_MODE		GENMASK(2, 0)29 30#define BU27034_REG_MODE_CONTROL2	0x4231#define BU27034_MASK_D01_GAIN		GENMASK(7, 3)32 33#define BU27034_REG_MODE_CONTROL3	0x4334#define BU27034_REG_MODE_CONTROL4	0x4435#define BU27034_MASK_MEAS_EN		BIT(0)36#define BU27034_MASK_VALID		BIT(7)37#define BU27034_NUM_HW_DATA_CHANS	238#define BU27034_REG_DATA0_LO		0x5039#define BU27034_REG_DATA1_LO		0x5240#define BU27034_REG_DATA1_HI		0x5341#define BU27034_REG_MANUFACTURER_ID	0x9242#define BU27034_REG_MAX BU27034_REG_MANUFACTURER_ID43 44/*45 * The BU27034 does not have interrupt to trigger the data read when a46 * measurement has finished. Hence we poll the VALID bit in a thread. We will47 * try to wake the thread BU27034_MEAS_WAIT_PREMATURE_MS milliseconds before48 * the expected sampling time to prevent the drifting.49 *50 * If we constantly wake up a bit too late we would eventually skip a sample.51 * And because the sleep can't wake up _exactly_ at given time this would be52 * inevitable even if the sensor clock would be perfectly phase-locked to CPU53 * clock - which we can't say is the case.54 *55 * This is still fragile. No matter how big advance do we have, we will still56 * risk of losing a sample because things can in a rainy-day scenario be57 * delayed a lot. Yet, more we reserve the time for polling, more we also lose58 * the performance by spending cycles polling the register. So, selecting this59 * value is a balancing dance between severity of wasting CPU time and severity60 * of losing samples.61 *62 * In most cases losing the samples is not _that_ crucial because light levels63 * tend to change slowly.64 *65 * Other option that was pointed to me would be always sleeping 1/2 of the66 * measurement time, checking the VALID bit and just sleeping again if the bit67 * was not set. That should be pretty tolerant against missing samples due to68 * the scheduling delays while also not wasting much of cycles for polling.69 * Downside is that the time-stamps would be very inaccurate as the wake-up70 * would not really be tied to the sensor toggling the valid bit. This would also71 * result 'jumps' in the time-stamps when the delay drifted so that wake-up was72 * performed during the consecutive wake-ups (Or, when sensor and CPU clocks73 * were very different and scheduling the wake-ups was very close to given74 * timeout - and when the time-outs were very close to the actual sensor75 * sampling, Eg. once in a blue moon, two consecutive time-outs would occur76 * without having a sample ready).77 */78#define BU27034_MEAS_WAIT_PREMATURE_MS	579#define BU27034_DATA_WAIT_TIME_US	100080#define BU27034_TOTAL_DATA_WAIT_TIME_US (BU27034_MEAS_WAIT_PREMATURE_MS * 1000)81 82#define BU27034_RETRY_LIMIT 1883 84enum {85	BU27034_CHAN_ALS,86	BU27034_CHAN_DATA0,87	BU27034_CHAN_DATA1,88	BU27034_NUM_CHANS89};90 91static const unsigned long bu27034_scan_masks[] = {92	GENMASK(BU27034_CHAN_DATA1, BU27034_CHAN_DATA0),93	GENMASK(BU27034_CHAN_DATA1, BU27034_CHAN_ALS), 094};95 96/*97 * Available scales with gain 1x - 1024x, timings 55, 100, 200, 400 mS98 * Time impacts to gain: 1x, 2x, 4x, 8x.99 *100 * => Max total gain is HWGAIN * gain by integration time (8 * 1024) = 8192101 * if 1x gain is scale 1, scale for 2x gain is 0.5, 4x => 0.25,102 * ... 8192x => 0.0001220703125 => 122070.3125 nanos103 *104 * Using NANO precision for scale, we must use scale 16x corresponding gain 1x105 * to avoid precision loss. (8x would result scale 976 562.5(nanos).106 */107#define BU27034_SCALE_1X	16108 109/* See the data sheet for the "Gain Setting" table */110#define BU27034_GSEL_1X		0x00 /* 00000 */111#define BU27034_GSEL_4X		0x08 /* 01000 */112#define BU27034_GSEL_32X	0x0b /* 01011 */113#define BU27034_GSEL_256X	0x18 /* 11000 */114#define BU27034_GSEL_512X	0x19 /* 11001 */115#define BU27034_GSEL_1024X	0x1a /* 11010 */116 117/* Available gain settings */118static const struct iio_gain_sel_pair bu27034_gains[] = {119	GAIN_SCALE_GAIN(1, BU27034_GSEL_1X),120	GAIN_SCALE_GAIN(4, BU27034_GSEL_4X),121	GAIN_SCALE_GAIN(32, BU27034_GSEL_32X),122	GAIN_SCALE_GAIN(256, BU27034_GSEL_256X),123	GAIN_SCALE_GAIN(512, BU27034_GSEL_512X),124	GAIN_SCALE_GAIN(1024, BU27034_GSEL_1024X),125};126 127/*128 * Measurement modes are 55, 100, 200 and 400 mS modes - which do have direct129 * multiplying impact to the data register values (similar to gain).130 *131 * This means that if meas-mode is changed for example from 400 => 200,132 * the scale is doubled. Eg, time impact to total gain is x1, x2, x4, x8.133 */134#define BU27034_MEAS_MODE_100MS		0135#define BU27034_MEAS_MODE_55MS		1136#define BU27034_MEAS_MODE_200MS		2137#define BU27034_MEAS_MODE_400MS		4138 139static const struct iio_itime_sel_mul bu27034_itimes[] = {140	GAIN_SCALE_ITIME_US(400000, BU27034_MEAS_MODE_400MS, 8),141	GAIN_SCALE_ITIME_US(200000, BU27034_MEAS_MODE_200MS, 4),142	GAIN_SCALE_ITIME_US(100000, BU27034_MEAS_MODE_100MS, 2),143	GAIN_SCALE_ITIME_US(55000, BU27034_MEAS_MODE_55MS, 1),144};145 146#define BU27034_CHAN_DATA(_name)					\147{									\148	.type = IIO_INTENSITY,						\149	.channel = BU27034_CHAN_##_name,				\150	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |			\151			      BIT(IIO_CHAN_INFO_SCALE) |		\152			      BIT(IIO_CHAN_INFO_HARDWAREGAIN),		\153	.info_mask_separate_available = BIT(IIO_CHAN_INFO_SCALE),	\154	.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_INT_TIME),		\155	.info_mask_shared_by_all_available =				\156					BIT(IIO_CHAN_INFO_INT_TIME),	\157	.address = BU27034_REG_##_name##_LO,				\158	.scan_index = BU27034_CHAN_##_name,				\159	.scan_type = {							\160		.sign = 'u',						\161		.realbits = 16,						\162		.storagebits = 16,					\163		.endianness = IIO_LE,					\164	},								\165	.indexed = 1,							\166}167 168static const struct iio_chan_spec bu27034_channels[] = {169	{170		.type = IIO_LIGHT,171		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |172				      BIT(IIO_CHAN_INFO_SCALE),173		.channel = BU27034_CHAN_ALS,174		.scan_index = BU27034_CHAN_ALS,175		.scan_type = {176			.sign = 'u',177			.realbits = 32,178			.storagebits = 32,179			.endianness = IIO_CPU,180		},181	},182	/*183	 * The BU27034 DATA0 and DATA1 channels are both on the visible light184	 * area (mostly). The data0 sensitivity peaks at 500nm, DATA1 at 600nm.185	 * These wave lengths are cyan(ish) and orange(ish), making these186	 * sub-optiomal candidates for R/G/B standardization. Hence the187	 * colour modifier is omitted.188	 */189	BU27034_CHAN_DATA(DATA0),190	BU27034_CHAN_DATA(DATA1),191	IIO_CHAN_SOFT_TIMESTAMP(4),192};193 194struct bu27034_data {195	struct regmap *regmap;196	struct device *dev;197	/*198	 * Protect gain and time during scale adjustment and data reading.199	 * Protect measurement enabling/disabling.200	 */201	struct mutex mutex;202	struct iio_gts gts;203	struct task_struct *task;204	__le16 raw[BU27034_NUM_HW_DATA_CHANS];205	struct {206		u32 mlux;207		__le16 channels[BU27034_NUM_HW_DATA_CHANS];208		s64 ts __aligned(8);209	} scan;210};211 212static const struct regmap_range bu27034_volatile_ranges[] = {213	{214		.range_min = BU27034_REG_SYSTEM_CONTROL,215		.range_max = BU27034_REG_SYSTEM_CONTROL,216	}, {217		.range_min = BU27034_REG_MODE_CONTROL4,218		.range_max = BU27034_REG_MODE_CONTROL4,219	}, {220		.range_min = BU27034_REG_DATA0_LO,221		.range_max = BU27034_REG_DATA1_HI,222	},223};224 225static const struct regmap_access_table bu27034_volatile_regs = {226	.yes_ranges = &bu27034_volatile_ranges[0],227	.n_yes_ranges = ARRAY_SIZE(bu27034_volatile_ranges),228};229 230static const struct regmap_range bu27034_read_only_ranges[] = {231	{232		.range_min = BU27034_REG_DATA0_LO,233		.range_max = BU27034_REG_DATA1_HI,234	}, {235		.range_min = BU27034_REG_MANUFACTURER_ID,236		.range_max = BU27034_REG_MANUFACTURER_ID,237	}238};239 240static const struct regmap_access_table bu27034_ro_regs = {241	.no_ranges = &bu27034_read_only_ranges[0],242	.n_no_ranges = ARRAY_SIZE(bu27034_read_only_ranges),243};244 245static const struct regmap_config bu27034_regmap = {246	.reg_bits = 8,247	.val_bits = 8,248	.max_register = BU27034_REG_MAX,249	.cache_type = REGCACHE_RBTREE,250	.volatile_table = &bu27034_volatile_regs,251	.wr_table = &bu27034_ro_regs,252};253 254struct bu27034_gain_check {255	int old_gain;256	int new_gain;257	int chan;258};259 260static int bu27034_get_gain_sel(struct bu27034_data *data, int chan)261{262	int reg[] = {263		[BU27034_CHAN_DATA0] = BU27034_REG_MODE_CONTROL2,264		[BU27034_CHAN_DATA1] = BU27034_REG_MODE_CONTROL3,265	};266	int ret, val;267 268	ret = regmap_read(data->regmap, reg[chan], &val);269	if (ret)270		return ret;271 272	return FIELD_GET(BU27034_MASK_D01_GAIN, val);273}274 275static int bu27034_get_gain(struct bu27034_data *data, int chan, int *gain)276{277	int ret, sel;278 279	ret = bu27034_get_gain_sel(data, chan);280	if (ret < 0)281		return ret;282 283	sel = ret;284 285	ret = iio_gts_find_gain_by_sel(&data->gts, sel);286	if (ret < 0) {287		dev_err(data->dev, "chan %u: unknown gain value 0x%x\n", chan,288			sel);289 290		return ret;291	}292 293	*gain = ret;294 295	return 0;296}297 298static int bu27034_get_int_time(struct bu27034_data *data)299{300	int ret, sel;301 302	ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &sel);303	if (ret)304		return ret;305 306	return iio_gts_find_int_time_by_sel(&data->gts,307					    sel & BU27034_MASK_MEAS_MODE);308}309 310static int _bu27034_get_scale(struct bu27034_data *data, int channel, int *val,311			      int *val2)312{313	int gain, ret;314 315	ret = bu27034_get_gain(data, channel, &gain);316	if (ret)317		return ret;318 319	ret = bu27034_get_int_time(data);320	if (ret < 0)321		return ret;322 323	return iio_gts_get_scale(&data->gts, gain, ret, val, val2);324}325 326static int bu27034_get_scale(struct bu27034_data *data, int channel, int *val,327			      int *val2)328{329	int ret;330 331	if (channel == BU27034_CHAN_ALS) {332		*val = 0;333		*val2 = 1000;334		return IIO_VAL_INT_PLUS_MICRO;335	}336 337	mutex_lock(&data->mutex);338	ret = _bu27034_get_scale(data, channel, val, val2);339	mutex_unlock(&data->mutex);340	if (ret)341		return ret;342 343	return IIO_VAL_INT_PLUS_NANO;344}345 346/* Caller should hold the lock to protect lux reading */347static int bu27034_write_gain_sel(struct bu27034_data *data, int chan, int sel)348{349	static const int reg[] = {350		[BU27034_CHAN_DATA0] = BU27034_REG_MODE_CONTROL2,351		[BU27034_CHAN_DATA1] = BU27034_REG_MODE_CONTROL3,352	};353	int mask, val;354 355	val = FIELD_PREP(BU27034_MASK_D01_GAIN, sel);356	mask = BU27034_MASK_D01_GAIN;357 358	return regmap_update_bits(data->regmap, reg[chan], mask, val);359}360 361static int bu27034_set_gain(struct bu27034_data *data, int chan, int gain)362{363	int ret;364 365	ret = iio_gts_find_sel_by_gain(&data->gts, gain);366	if (ret < 0)367		return ret;368 369	return bu27034_write_gain_sel(data, chan, ret);370}371 372/* Caller should hold the lock to protect data->int_time */373static int bu27034_set_int_time(struct bu27034_data *data, int time)374{375	int ret;376 377	ret = iio_gts_find_sel_by_int_time(&data->gts, time);378	if (ret < 0)379		return ret;380 381	return regmap_update_bits(data->regmap, BU27034_REG_MODE_CONTROL1,382				 BU27034_MASK_MEAS_MODE, ret);383}384 385/*386 * We try to change the time in such way that the scale is maintained for387 * given channels by adjusting gain so that it compensates the time change.388 */389static int bu27034_try_set_int_time(struct bu27034_data *data, int time_us)390{391	struct bu27034_gain_check gains[] = {392		{ .chan = BU27034_CHAN_DATA0 },393		{ .chan = BU27034_CHAN_DATA1 },394	};395	int numg = ARRAY_SIZE(gains);396	int ret, int_time_old, i;397 398	mutex_lock(&data->mutex);399	ret = bu27034_get_int_time(data);400	if (ret < 0)401		goto unlock_out;402 403	int_time_old = ret;404 405	if (!iio_gts_valid_time(&data->gts, time_us)) {406		dev_err(data->dev, "Unsupported integration time %u\n",407			time_us);408		ret = -EINVAL;409 410		goto unlock_out;411	}412 413	if (time_us == int_time_old) {414		ret = 0;415		goto unlock_out;416	}417 418	for (i = 0; i < numg; i++) {419		ret = bu27034_get_gain(data, gains[i].chan, &gains[i].old_gain);420		if (ret)421			goto unlock_out;422 423		ret = iio_gts_find_new_gain_by_old_gain_time(&data->gts,424							     gains[i].old_gain,425							     int_time_old, time_us,426							     &gains[i].new_gain);427		if (ret) {428			int scale1, scale2;429			bool ok;430 431			_bu27034_get_scale(data, gains[i].chan, &scale1, &scale2);432			dev_dbg(data->dev,433				"chan %u, can't support time %u with scale %u %u\n",434				gains[i].chan, time_us, scale1, scale2);435 436			if (gains[i].new_gain < 0)437				goto unlock_out;438 439			/*440			 * If caller requests for integration time change and we441			 * can't support the scale - then the caller should be442			 * prepared to 'pick up the pieces and deal with the443			 * fact that the scale changed'.444			 */445			ret = iio_find_closest_gain_low(&data->gts,446							gains[i].new_gain, &ok);447 448			if (!ok)449				dev_dbg(data->dev,450					"optimal gain out of range for chan %u\n",451					gains[i].chan);452 453			if (ret < 0) {454				dev_dbg(data->dev,455					 "Total gain increase. Risk of saturation");456				ret = iio_gts_get_min_gain(&data->gts);457				if (ret < 0)458					goto unlock_out;459			}460			dev_dbg(data->dev, "chan %u scale changed\n",461				 gains[i].chan);462			gains[i].new_gain = ret;463			dev_dbg(data->dev, "chan %u new gain %u\n",464				gains[i].chan, gains[i].new_gain);465		}466	}467 468	for (i = 0; i < numg; i++) {469		ret = bu27034_set_gain(data, gains[i].chan, gains[i].new_gain);470		if (ret)471			goto unlock_out;472	}473 474	ret = bu27034_set_int_time(data, time_us);475 476unlock_out:477	mutex_unlock(&data->mutex);478 479	return ret;480}481 482static int bu27034_set_scale(struct bu27034_data *data, int chan,483			    int val, int val2)484{485	int ret, time_sel, gain_sel, i;486	bool found = false;487 488	if (chan == BU27034_CHAN_ALS) {489		if (val == 0 && val2 == 1000000)490			return 0;491 492		return -EINVAL;493	}494 495	mutex_lock(&data->mutex);496	ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &time_sel);497	if (ret)498		goto unlock_out;499 500	ret = iio_gts_find_gain_sel_for_scale_using_time(&data->gts, time_sel,501						val, val2, &gain_sel);502	if (ret) {503		/*504		 * Could not support scale with given time. Need to change time.505		 * We still want to maintain the scale for all channels506		 */507		struct bu27034_gain_check gain;508		int new_time_sel;509 510		/*511		 * Populate information for the other channel which should also512		 * maintain the scale.513		 */514		if (chan == BU27034_CHAN_DATA0)515			gain.chan = BU27034_CHAN_DATA1;516		else if (chan == BU27034_CHAN_DATA1)517			gain.chan = BU27034_CHAN_DATA0;518 519		ret = bu27034_get_gain(data, gain.chan, &gain.old_gain);520		if (ret)521			goto unlock_out;522 523		/*524		 * Iterate through all the times to see if we find one which525		 * can support requested scale for requested channel, while526		 * maintaining the scale for the other channel527		 */528		for (i = 0; i < data->gts.num_itime; i++) {529			new_time_sel = data->gts.itime_table[i].sel;530 531			if (new_time_sel == time_sel)532				continue;533 534			/* Can we provide requested scale with this time? */535			ret = iio_gts_find_gain_sel_for_scale_using_time(536				&data->gts, new_time_sel, val, val2,537				&gain_sel);538			if (ret)539				continue;540 541			/* Can the other channel maintain scale? */542			ret = iio_gts_find_new_gain_sel_by_old_gain_time(543				&data->gts, gain.old_gain, time_sel,544				new_time_sel, &gain.new_gain);545			if (!ret) {546				/* Yes - we found suitable time */547				found = true;548				break;549			}550		}551		if (!found) {552			dev_dbg(data->dev,553				"Can't set scale maintaining other channel\n");554			ret = -EINVAL;555 556			goto unlock_out;557		}558 559		ret = bu27034_set_gain(data, gain.chan, gain.new_gain);560		if (ret)561			goto unlock_out;562 563		ret = regmap_update_bits(data->regmap, BU27034_REG_MODE_CONTROL1,564				  BU27034_MASK_MEAS_MODE, new_time_sel);565		if (ret)566			goto unlock_out;567	}568 569	ret = bu27034_write_gain_sel(data, chan, gain_sel);570unlock_out:571	mutex_unlock(&data->mutex);572 573	return ret;574}575 576/*577 * for (D1/D0 < 1.5):578 *    lx = (0.001193 * D0 + (-0.0000747) * D1) * ((D1/D0 – 1.5) * (0.25) + 1)579 *580 *    => -0.000745625 * D0 + 0.0002515625 * D1 + -0.000018675 * D1 * D1 / D0581 *582 *    => (6.44 * ch1 / gain1 + 19.088 * ch0 / gain0 -583 *       0.47808 * ch1 * ch1 * gain0 / gain1 / gain1 / ch0) /584 *       mt585 *586 * Else587 *    lx = 0.001193 * D0 - 0.0000747 * D1588 *589 *    => (1.91232 * ch1 / gain1 + 30.5408 * ch0 / gain0 +590 *        [0 * ch1 * ch1 * gain0 / gain1 / gain1 / ch0] ) /591 *        mt592 *593 * This can be unified to format:594 * lx = [595 *	 A * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +596 *	 B * ch1 / gain1 +597 *	 C * ch0 / gain0598 *	] / mt599 *600 * For case 1:601 * A = -0.47808,602 * B = 6.44,603 * C = 19.088604 *605 * For case 2:606 * A = 0607 * B = 1.91232608 * C = 30.5408609 */610 611struct bu27034_lx_coeff {612	unsigned int A;613	unsigned int B;614	unsigned int C;615	/* Indicate which of the coefficients above are negative */616	bool is_neg[3];617};618 619static inline u64 gain_mul_div_helper(u64 val, unsigned int gain,620				      unsigned int div)621{622	/*623	 * Max gain for a channel is 4096. The max u64 (0xffffffffffffffffULL)624	 * divided by 4096 is 0xFFFFFFFFFFFFF (GENMASK_ULL(51, 0)) (floored).625	 * Thus, the 0xFFFFFFFFFFFFF is the largest value we can safely multiply626	 * with the gain, no matter what gain is set.627	 *628	 * So, multiplication with max gain may overflow if val is greater than629	 * 0xFFFFFFFFFFFFF (52 bits set)..630	 *631	 * If this is the case we divide first.632	 */633	if (val < GENMASK_ULL(51, 0)) {634		val *= gain;635		do_div(val, div);636	} else {637		do_div(val, div);638		val *= gain;639	}640 641	return val;642}643 644static u64 bu27034_fixp_calc_t1_64bit(unsigned int coeff, unsigned int ch0,645				      unsigned int ch1, unsigned int gain0,646				      unsigned int gain1)647{648	unsigned int helper;649	u64 helper64;650 651	helper64 = (u64)coeff * (u64)ch1 * (u64)ch1;652 653	helper = gain1 * gain1;654	if (helper > ch0) {655		do_div(helper64, helper);656 657		return gain_mul_div_helper(helper64, gain0, ch0);658	}659 660	do_div(helper64, ch0);661 662	return gain_mul_div_helper(helper64, gain0, helper);663 664}665 666static u64 bu27034_fixp_calc_t1(unsigned int coeff, unsigned int ch0,667				unsigned int ch1, unsigned int gain0,668				unsigned int gain1)669{670	unsigned int helper, tmp;671 672	/*673	 * Here we could overflow even the 64bit value. Hence we674	 * multiply with gain0 only after the divisions - even though675	 * it may result loss of accuracy676	 */677	helper = coeff * ch1 * ch1;678	tmp = helper * gain0;679 680	helper = ch1 * ch1;681 682	if (check_mul_overflow(helper, coeff, &helper))683		return bu27034_fixp_calc_t1_64bit(coeff, ch0, ch1, gain0, gain1);684 685	if (check_mul_overflow(helper, gain0, &tmp))686		return bu27034_fixp_calc_t1_64bit(coeff, ch0, ch1, gain0, gain1);687 688	return tmp / (gain1 * gain1) / ch0;689 690}691 692static u64 bu27034_fixp_calc_t23(unsigned int coeff, unsigned int ch,693				 unsigned int gain)694{695	unsigned int helper;696	u64 helper64;697 698	if (!check_mul_overflow(coeff, ch, &helper))699		return helper / gain;700 701	helper64 = (u64)coeff * (u64)ch;702	do_div(helper64, gain);703 704	return helper64;705}706 707static int bu27034_fixp_calc_lx(unsigned int ch0, unsigned int ch1,708				unsigned int gain0, unsigned int gain1,709				unsigned int meastime, int coeff_idx)710{711	static const struct bu27034_lx_coeff coeff[] = {712		{713			.A = 4780800,		/* -0.47808 */714			.B = 64400000,		/* 6.44 */715			.C = 190880000,		/* 19.088 */716			.is_neg = { true, false, false },717		}, {718			.A = 0,			/* 0 */719			.B = 19123200,		/* 1.91232 */720			.C = 305408000,		/* 30.5408 */721			/* All terms positive */722		},723	};724	const struct bu27034_lx_coeff *c = &coeff[coeff_idx];725	u64 res = 0, terms[3];726	int i;727 728	if (coeff_idx >= ARRAY_SIZE(coeff))729		return -EINVAL;730 731	terms[0] = bu27034_fixp_calc_t1(c->A, ch0, ch1, gain0, gain1);732	terms[1] = bu27034_fixp_calc_t23(c->B, ch1, gain1);733	terms[2] = bu27034_fixp_calc_t23(c->C, ch0, gain0);734 735	/* First, add positive terms */736	for (i = 0; i < 3; i++)737		if (!c->is_neg[i])738			res += terms[i];739 740	/* No positive term => zero lux */741	if (!res)742		return 0;743 744	/* Then, subtract negative terms (if any) */745	for (i = 0; i < 3; i++)746		if (c->is_neg[i]) {747			/*748			 * If the negative term is greater than positive - then749			 * the darkness has taken over and we are all doomed! Eh,750			 * I mean, then we can just return 0 lx and go out751			 */752			if (terms[i] >= res)753				return 0;754 755			res -= terms[i];756		}757 758	meastime *= 10;759	do_div(res, meastime);760 761	return (int) res;762}763 764static bool bu27034_has_valid_sample(struct bu27034_data *data)765{766	int ret, val;767 768	ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL4, &val);769	if (ret) {770		dev_err(data->dev, "Read failed %d\n", ret);771 772		return false;773	}774 775	return val & BU27034_MASK_VALID;776}777 778/*779 * Reading the register where VALID bit is clears this bit. (So does changing780 * any gain / integration time configuration registers) The bit gets781 * set when we have acquired new data. We use this bit to indicate data782 * validity.783 */784static void bu27034_invalidate_read_data(struct bu27034_data *data)785{786	bu27034_has_valid_sample(data);787}788 789static int bu27034_read_result(struct bu27034_data *data, int chan, int *res)790{791	int reg[] = {792		[BU27034_CHAN_DATA0] = BU27034_REG_DATA0_LO,793		[BU27034_CHAN_DATA1] = BU27034_REG_DATA1_LO,794	};795	int valid, ret;796	__le16 val;797 798	ret = regmap_read_poll_timeout(data->regmap, BU27034_REG_MODE_CONTROL4,799				       valid, (valid & BU27034_MASK_VALID),800				       BU27034_DATA_WAIT_TIME_US, 0);801	if (ret)802		return ret;803 804	ret = regmap_bulk_read(data->regmap, reg[chan], &val, sizeof(val));805	if (ret)806		return ret;807 808	*res = le16_to_cpu(val);809 810	return 0;811}812 813static int bu27034_get_result_unlocked(struct bu27034_data *data, __le16 *res,814				       int size)815{816	int ret = 0, retry_cnt = 0;817 818retry:819	/* Get new value from sensor if data is ready */820	if (bu27034_has_valid_sample(data)) {821		ret = regmap_bulk_read(data->regmap, BU27034_REG_DATA0_LO,822				       res, size);823		if (ret)824			return ret;825 826		bu27034_invalidate_read_data(data);827	} else {828		/* No new data in sensor. Wait and retry */829		retry_cnt++;830 831		if (retry_cnt > BU27034_RETRY_LIMIT) {832			dev_err(data->dev, "No data from sensor\n");833 834			return -ETIMEDOUT;835		}836 837		msleep(25);838 839		goto retry;840	}841 842	return ret;843}844 845static int bu27034_meas_set(struct bu27034_data *data, bool en)846{847	if (en)848		return regmap_set_bits(data->regmap, BU27034_REG_MODE_CONTROL4,849				       BU27034_MASK_MEAS_EN);850 851	return regmap_clear_bits(data->regmap, BU27034_REG_MODE_CONTROL4,852				 BU27034_MASK_MEAS_EN);853}854 855static int bu27034_get_single_result(struct bu27034_data *data, int chan,856				     int *val)857{858	int ret;859 860	if (chan < BU27034_CHAN_DATA0 || chan > BU27034_CHAN_DATA1)861		return -EINVAL;862 863	ret = bu27034_meas_set(data, true);864	if (ret)865		return ret;866 867	ret = bu27034_get_int_time(data);868	if (ret < 0)869		return ret;870 871	msleep(ret / 1000);872 873	return bu27034_read_result(data, chan, val);874}875 876/*877 * The formula given by vendor for computing luxes out of data0 and data1878 * (in open air) is as follows:879 *880 * Let's mark:881 * D0 = data0/ch0_gain/meas_time_ms * 25600882 * D1 = data1/ch1_gain/meas_time_ms * 25600883 *884 * Then:885 * If (D1/D0 < 1.5)886 *    lx = (0.001193 * D0 + (-0.0000747) * D1) * ((D1 / D0 – 1.5) * 0.25 + 1)887 * Else888 *    lx = (0.001193 * D0 + (-0.0000747) * D1)889 *890 * We use it here. Users who have for example some colored lens891 * need to modify the calculation but I hope this gives a starting point for892 * those working with such devices.893 */894 895static int bu27034_calc_mlux(struct bu27034_data *data, __le16 *res, int *val)896{897	unsigned int gain0, gain1, meastime;898	unsigned int d1_d0_ratio_scaled;899	u16 ch0, ch1;900	u64 helper64;901	int ret;902 903	/*904	 * We return 0 lux if calculation fails. This should be reasonably905	 * easy to spot from the buffers especially if raw-data channels show906	 * valid values907	 */908	*val = 0;909 910	ch0 = max_t(u16, 1, le16_to_cpu(res[0]));911	ch1 = max_t(u16, 1, le16_to_cpu(res[1]));912 913	ret = bu27034_get_gain(data, BU27034_CHAN_DATA0, &gain0);914	if (ret)915		return ret;916 917	ret = bu27034_get_gain(data, BU27034_CHAN_DATA1, &gain1);918	if (ret)919		return ret;920 921	ret = bu27034_get_int_time(data);922	if (ret < 0)923		return ret;924 925	meastime = ret;926 927	d1_d0_ratio_scaled = (unsigned int)ch1 * (unsigned int)gain0 * 100;928	helper64 = (u64)ch1 * (u64)gain0 * 100LLU;929 930	if (helper64 != d1_d0_ratio_scaled) {931		unsigned int div = (unsigned int)ch0 * gain1;932 933		do_div(helper64, div);934		d1_d0_ratio_scaled = helper64;935	} else {936		d1_d0_ratio_scaled /= ch0 * gain1;937	}938 939	if (d1_d0_ratio_scaled < 150)940		ret = bu27034_fixp_calc_lx(ch0, ch1, gain0, gain1, meastime, 0);941	else942		ret = bu27034_fixp_calc_lx(ch0, ch1, gain0, gain1, meastime, 1);943 944	if (ret < 0)945		return ret;946 947	*val = ret;948 949	return 0;950 951}952 953static int bu27034_get_mlux(struct bu27034_data *data, int chan, int *val)954{955	__le16 res[BU27034_NUM_HW_DATA_CHANS];956	int ret;957 958	ret = bu27034_meas_set(data, true);959	if (ret)960		return ret;961 962	ret = bu27034_get_result_unlocked(data, &res[0], sizeof(res));963	if (ret)964		return ret;965 966	ret = bu27034_calc_mlux(data, res, val);967	if (ret)968		return ret;969 970	ret = bu27034_meas_set(data, false);971	if (ret)972		dev_err(data->dev, "failed to disable measurement\n");973 974	return 0;975}976 977static int bu27034_read_raw(struct iio_dev *idev,978			   struct iio_chan_spec const *chan,979			   int *val, int *val2, long mask)980{981	struct bu27034_data *data = iio_priv(idev);982	int ret;983 984	switch (mask) {985	case IIO_CHAN_INFO_INT_TIME:986		*val = 0;987		*val2 = bu27034_get_int_time(data);988		if (*val2 < 0)989			return *val2;990 991		return IIO_VAL_INT_PLUS_MICRO;992 993	case IIO_CHAN_INFO_HARDWAREGAIN:994		ret = bu27034_get_gain(data, chan->channel, val);995		if (ret)996			return ret;997 998		return IIO_VAL_INT;999 1000	case IIO_CHAN_INFO_SCALE:1001		return bu27034_get_scale(data, chan->channel, val, val2);1002 1003	case IIO_CHAN_INFO_RAW:1004	{1005		int (*result_get)(struct bu27034_data *data, int chan, int *val);1006 1007		if (chan->type == IIO_INTENSITY)1008			result_get = bu27034_get_single_result;1009		else if (chan->type == IIO_LIGHT)1010			result_get = bu27034_get_mlux;1011		else1012			return -EINVAL;1013 1014		/* Don't mess with measurement enabling while buffering */1015		ret = iio_device_claim_direct_mode(idev);1016		if (ret)1017			return ret;1018 1019		mutex_lock(&data->mutex);1020		/*1021		 * Reading one channel at a time is inefficient but we1022		 * don't care here. Buffered version should be used if1023		 * performance is an issue.1024		 */1025		ret = result_get(data, chan->channel, val);1026 1027		mutex_unlock(&data->mutex);1028		iio_device_release_direct_mode(idev);1029 1030		if (ret)1031			return ret;1032 1033		return IIO_VAL_INT;1034	}1035	default:1036		return -EINVAL;1037	}1038}1039 1040static int bu27034_write_raw_get_fmt(struct iio_dev *indio_dev,1041				     struct iio_chan_spec const *chan,1042				     long mask)1043{1044	struct bu27034_data *data = iio_priv(indio_dev);1045 1046	switch (mask) {1047	case IIO_CHAN_INFO_SCALE:1048		return IIO_VAL_INT_PLUS_NANO;1049	case IIO_CHAN_INFO_INT_TIME:1050		return IIO_VAL_INT_PLUS_MICRO;1051	case IIO_CHAN_INFO_HARDWAREGAIN:1052		dev_dbg(data->dev,1053			"HARDWAREGAIN is read-only, use scale to set\n");1054		return -EINVAL;1055	default:1056		return -EINVAL;1057	}1058}1059 1060static int bu27034_write_raw(struct iio_dev *idev,1061			     struct iio_chan_spec const *chan,1062			     int val, int val2, long mask)1063{1064	struct bu27034_data *data = iio_priv(idev);1065	int ret;1066 1067	ret = iio_device_claim_direct_mode(idev);1068	if (ret)1069		return ret;1070 1071	switch (mask) {1072	case IIO_CHAN_INFO_SCALE:1073		ret = bu27034_set_scale(data, chan->channel, val, val2);1074		break;1075	case IIO_CHAN_INFO_INT_TIME:1076		if (!val)1077			ret = bu27034_try_set_int_time(data, val2);1078		else1079			ret = -EINVAL;1080		break;1081	default:1082		ret = -EINVAL;1083		break;1084	}1085 1086	iio_device_release_direct_mode(idev);1087 1088	return ret;1089}1090 1091static int bu27034_read_avail(struct iio_dev *idev,1092			      struct iio_chan_spec const *chan, const int **vals,1093			      int *type, int *length, long mask)1094{1095	struct bu27034_data *data = iio_priv(idev);1096 1097	switch (mask) {1098	case IIO_CHAN_INFO_INT_TIME:1099		return iio_gts_avail_times(&data->gts, vals, type, length);1100	case IIO_CHAN_INFO_SCALE:1101		return iio_gts_all_avail_scales(&data->gts, vals, type, length);1102	default:1103		return -EINVAL;1104	}1105}1106 1107static const struct iio_info bu27034_info = {1108	.read_raw = &bu27034_read_raw,1109	.write_raw = &bu27034_write_raw,1110	.write_raw_get_fmt = &bu27034_write_raw_get_fmt,1111	.read_avail = &bu27034_read_avail,1112};1113 1114static int bu27034_chip_init(struct bu27034_data *data)1115{1116	int ret, sel;1117 1118	/* Reset */1119	ret = regmap_write_bits(data->regmap, BU27034_REG_SYSTEM_CONTROL,1120			   BU27034_MASK_SW_RESET, BU27034_MASK_SW_RESET);1121	if (ret)1122		return dev_err_probe(data->dev, ret, "Sensor reset failed\n");1123 1124	msleep(1);1125 1126	ret = regmap_reinit_cache(data->regmap, &bu27034_regmap);1127	if (ret) {1128		dev_err(data->dev, "Failed to reinit reg cache\n");1129		return ret;1130	}1131 1132	/*1133	 * Read integration time here to ensure it is in regmap cache. We do1134	 * this to speed-up the int-time acquisition in the start of the buffer1135	 * handling thread where longer delays could make it more likely we end1136	 * up skipping a sample, and where the longer delays make timestamps1137	 * less accurate.1138	 */1139	ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &sel);1140	if (ret)1141		dev_err(data->dev, "reading integration time failed\n");1142 1143	return 0;1144}1145 1146static int bu27034_wait_for_data(struct bu27034_data *data)1147{1148	int ret, val;1149 1150	ret = regmap_read_poll_timeout(data->regmap, BU27034_REG_MODE_CONTROL4,1151				       val, val & BU27034_MASK_VALID,1152				       BU27034_DATA_WAIT_TIME_US,1153				       BU27034_TOTAL_DATA_WAIT_TIME_US);1154	if (ret) {1155		dev_err(data->dev, "data polling %s\n",1156			!(val & BU27034_MASK_VALID) ? "timeout" : "fail");1157 1158		return ret;1159	}1160 1161	ret = regmap_bulk_read(data->regmap, BU27034_REG_DATA0_LO,1162			       &data->scan.channels[0],1163			       sizeof(data->scan.channels));1164	if (ret)1165		return ret;1166 1167	bu27034_invalidate_read_data(data);1168 1169	return 0;1170}1171 1172static int bu27034_buffer_thread(void *arg)1173{1174	struct iio_dev *idev = arg;1175	struct bu27034_data *data;1176	int wait_ms;1177 1178	data = iio_priv(idev);1179 1180	wait_ms = bu27034_get_int_time(data);1181	wait_ms /= 1000;1182 1183	wait_ms -= BU27034_MEAS_WAIT_PREMATURE_MS;1184 1185	while (!kthread_should_stop()) {1186		int ret;1187		int64_t tstamp;1188 1189		msleep(wait_ms);1190		ret = bu27034_wait_for_data(data);1191		if (ret)1192			continue;1193 1194		tstamp = iio_get_time_ns(idev);1195 1196		if (test_bit(BU27034_CHAN_ALS, idev->active_scan_mask)) {1197			int mlux;1198 1199			ret = bu27034_calc_mlux(data, &data->scan.channels[0],1200					       &mlux);1201			if (ret)1202				dev_err(data->dev, "failed to calculate lux\n");1203 1204			/*1205			 * The maximum Milli lux value we get with gain 1x time1206			 * 55mS data ch0 = 0xffff ch1 = 0xffff fits in 26 bits1207			 * so there should be no problem returning int from1208			 * computations and casting it to u321209			 */1210			data->scan.mlux = (u32)mlux;1211		}1212		iio_push_to_buffers_with_timestamp(idev, &data->scan, tstamp);1213	}1214 1215	return 0;1216}1217 1218static int bu27034_buffer_enable(struct iio_dev *idev)1219{1220	struct bu27034_data *data = iio_priv(idev);1221	struct task_struct *task;1222	int ret;1223 1224	mutex_lock(&data->mutex);1225	ret = bu27034_meas_set(data, true);1226	if (ret)1227		goto unlock_out;1228 1229	task = kthread_run(bu27034_buffer_thread, idev,1230				 "bu27034-buffering-%u",1231				 iio_device_id(idev));1232	if (IS_ERR(task)) {1233		ret = PTR_ERR(task);1234		goto unlock_out;1235	}1236 1237	data->task = task;1238 1239unlock_out:1240	mutex_unlock(&data->mutex);1241 1242	return ret;1243}1244 1245static int bu27034_buffer_disable(struct iio_dev *idev)1246{1247	struct bu27034_data *data = iio_priv(idev);1248	int ret;1249 1250	mutex_lock(&data->mutex);1251	if (data->task) {1252		kthread_stop(data->task);1253		data->task = NULL;1254	}1255 1256	ret = bu27034_meas_set(data, false);1257	mutex_unlock(&data->mutex);1258 1259	return ret;1260}1261 1262static const struct iio_buffer_setup_ops bu27034_buffer_ops = {1263	.postenable = &bu27034_buffer_enable,1264	.predisable = &bu27034_buffer_disable,1265};1266 1267static int bu27034_probe(struct i2c_client *i2c)1268{1269	struct device *dev = &i2c->dev;1270	struct bu27034_data *data;1271	struct regmap *regmap;1272	struct iio_dev *idev;1273	unsigned int part_id, reg;1274	int ret;1275 1276	regmap = devm_regmap_init_i2c(i2c, &bu27034_regmap);1277	if (IS_ERR(regmap))1278		return dev_err_probe(dev, PTR_ERR(regmap),1279				     "Failed to initialize Regmap\n");1280 1281	idev = devm_iio_device_alloc(dev, sizeof(*data));1282	if (!idev)1283		return -ENOMEM;1284 1285	ret = devm_regulator_get_enable(dev, "vdd");1286	if (ret)1287		return dev_err_probe(dev, ret, "Failed to get regulator\n");1288 1289	data = iio_priv(idev);1290 1291	ret = regmap_read(regmap, BU27034_REG_SYSTEM_CONTROL, &reg);1292	if (ret)1293		return dev_err_probe(dev, ret, "Failed to access sensor\n");1294 1295	part_id = FIELD_GET(BU27034_MASK_PART_ID, reg);1296 1297	if (part_id != BU27034_ID)1298		dev_warn(dev, "unknown device 0x%x\n", part_id);1299 1300	ret = devm_iio_init_iio_gts(dev, BU27034_SCALE_1X, 0, bu27034_gains,1301				    ARRAY_SIZE(bu27034_gains), bu27034_itimes,1302				    ARRAY_SIZE(bu27034_itimes), &data->gts);1303	if (ret)1304		return ret;1305 1306	mutex_init(&data->mutex);1307	data->regmap = regmap;1308	data->dev = dev;1309 1310	idev->channels = bu27034_channels;1311	idev->num_channels = ARRAY_SIZE(bu27034_channels);1312	idev->name = "bu27034";1313	idev->info = &bu27034_info;1314 1315	idev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;1316	idev->available_scan_masks = bu27034_scan_masks;1317 1318	ret = bu27034_chip_init(data);1319	if (ret)1320		return ret;1321 1322	ret = devm_iio_kfifo_buffer_setup(dev, idev, &bu27034_buffer_ops);1323	if (ret)1324		return dev_err_probe(dev, ret, "buffer setup failed\n");1325 1326	ret = devm_iio_device_register(dev, idev);1327	if (ret < 0)1328		return dev_err_probe(dev, ret,1329				     "Unable to register iio device\n");1330 1331	return ret;1332}1333 1334static const struct of_device_id bu27034_of_match[] = {1335	{ .compatible = "rohm,bu27034anuc" },1336	{ }1337};1338MODULE_DEVICE_TABLE(of, bu27034_of_match);1339 1340static struct i2c_driver bu27034_i2c_driver = {1341	.driver = {1342		.name = "bu27034-als",1343		.of_match_table = bu27034_of_match,1344		.probe_type = PROBE_PREFER_ASYNCHRONOUS,1345	},1346	.probe = bu27034_probe,1347};1348module_i2c_driver(bu27034_i2c_driver);1349 1350MODULE_LICENSE("GPL");1351MODULE_AUTHOR("Matti Vaittinen <matti.vaittinen@fi.rohmeurope.com>");1352MODULE_DESCRIPTION("ROHM BU27034 ambient light sensor driver");1353MODULE_IMPORT_NS(IIO_GTS_HELPER);1354