diff mbox series

[v4,4/8] iio: light: Add gain-time-scale helpers

Message ID e5b93a3d2424b16d842e847c98f05f1a9befb2e1.1679062529.git.mazziesaccount@gmail.com (mailing list archive)
State Changes Requested
Headers show
Series Support ROHM BU27034 ALS sensor | expand

Commit Message

Matti Vaittinen March 17, 2023, 2:43 p.m. UTC
Some light sensors can adjust both the HW-gain and integration time.
There are cases where adjusting the integration time has similar impact
to the scale of the reported values as gain setting has.

IIO users do typically expect to handle scale by a single writable 'scale'
entry. Driver should then adjust the gain/time accordingly.

It however is difficult for a driver to know whether it should change
gain or integration time to meet the requested scale. Usually it is
preferred to have longer integration time which usually improves
accuracy, but there may be use-cases where long measurement times can be
an issue. Thus it can be preferable to allow also changing the
integration time - but mitigate the scale impact by also changing the gain
underneath. Eg, if integration time change doubles the measured values,
the driver can reduce the HW-gain to half.

The theory of the computations of gain-time-scale is simple. However,
some people (undersigned) got that implemented wrong for more than once.

Add some gain-time-scale helpers in order to not dublicate errors in all
drivers needing these computations.

Signed-off-by: Matti Vaittinen <mazziesaccount@gmail.com>

---
Currently it is only BU27034 using these in this series. I am however working
with drivers for RGB sensors BU27008 and BU27010 which have similar
[gain - integration time - scale] - relation. I hope sending those
follows soon after the BU27034 is done.

Changes:
v3 => v4:
- doc styling
- use memset to zero the helper struct at init
- drop unnecessary min calculation at iio_find_closest_gain_low()
- use namespace to all exports
- many minor stylings
- make available outside iio/light (move code to drivers/iio and move the
  header under include
- rename to look like other files under drivers/iio (s/iio/industrialio)
- drop unused functions
- don't export only internally used functions and make them static
  Note, I decided to keep iio_gts_total_gain_to_scale() exported as it is
  currently needed by the tests outside the helpers.

v2 => v3: (mostly fixes based on review by Andy)
- Fix typos
- Styling fixes
- Use namespace for exported symbols
- Protect allocs against argument overflow
- Fix include protection name
- add types.h inclusion and struct device forward declaration

RFCv1 => v2:
- fix include guardian
- Improve kernel doc for iio_init_iio_gts.
- Add iio_gts_scale_to_total_gain
- Add iio_gts_total_gain_to_scale
- Fix review comments from Jonathan
  - add documentation to few functions
  - replace 0xffffffffffffffffLLU by U64_MAX
  - some styling fixes
  - drop unnecessary NULL checks
  - order function arguments by  in / out purpose
  - drop GAIN_SCALE_ITIME_MS()
- Add helpers for available scales and times
- Rename to iio-gts-helpers
---
 drivers/iio/Kconfig                   |   3 +
 drivers/iio/Makefile                  |   1 +
 drivers/iio/industrialio-gts-helper.c | 990 ++++++++++++++++++++++++++
 include/linux/iio/iio-gts-helper.h    | 113 +++
 4 files changed, 1107 insertions(+)
 create mode 100644 drivers/iio/industrialio-gts-helper.c
 create mode 100644 include/linux/iio/iio-gts-helper.h

Comments

Jonathan Cameron March 19, 2023, 6:08 p.m. UTC | #1
On Fri, 17 Mar 2023 16:43:23 +0200
Matti Vaittinen <mazziesaccount@gmail.com> wrote:

> Some light sensors can adjust both the HW-gain and integration time.
> There are cases where adjusting the integration time has similar impact
> to the scale of the reported values as gain setting has.
> 
> IIO users do typically expect to handle scale by a single writable 'scale'
> entry. Driver should then adjust the gain/time accordingly.
> 
> It however is difficult for a driver to know whether it should change
> gain or integration time to meet the requested scale. Usually it is
> preferred to have longer integration time which usually improves
> accuracy, but there may be use-cases where long measurement times can be
> an issue. Thus it can be preferable to allow also changing the
> integration time - but mitigate the scale impact by also changing the gain
> underneath. Eg, if integration time change doubles the measured values,
> the driver can reduce the HW-gain to half.
> 
> The theory of the computations of gain-time-scale is simple. However,
> some people (undersigned) got that implemented wrong for more than once.
> 
> Add some gain-time-scale helpers in order to not dublicate errors in all
> drivers needing these computations.
> 
> Signed-off-by: Matti Vaittinen <mazziesaccount@gmail.com>

Whilst you use it in the tests currently I'm not convinced there is a good
reason to separate iio_init_iio_gts() from devm_iio_gts_build_avail_tables()
as I'd expect them to be called as a pair in all drivers that use this.

Perhaps it's worth reworking the tests to do that even if it's not strictly
necessary for specific tests.

I think a bit more care is need with storage of time (unsigned) + decide
whether to allow for negative gains. Whilst they happen I'm not that bothered
if that subtlety becomes a device driver problem when calling this.  I'm not
sure I've seen a sensor that does both positive and negative gains for a single
channel.

> 
> ---
> Currently it is only BU27034 using these in this series. I am however working
> with drivers for RGB sensors BU27008 and BU27010 which have similar
> [gain - integration time - scale] - relation. I hope sending those
> follows soon after the BU27034 is done.
> 
> Changes:
> v3 => v4:
> - doc styling
> - use memset to zero the helper struct at init
> - drop unnecessary min calculation at iio_find_closest_gain_low()
> - use namespace to all exports
> - many minor stylings
> - make available outside iio/light (move code to drivers/iio and move the
>   header under include
> - rename to look like other files under drivers/iio (s/iio/industrialio)

Ah. I've always regretted not using iio_ for the prefix on those so I'm fine
if you would prefer to stick to iio_


> - drop unused functions
> - don't export only internally used functions and make them static
>   Note, I decided to keep iio_gts_total_gain_to_scale() exported as it is
>   currently needed by the tests outside the helpers.
> 
> v2 => v3: (mostly fixes based on review by Andy)
> - Fix typos
> - Styling fixes
> - Use namespace for exported symbols
> - Protect allocs against argument overflow
> - Fix include protection name
> - add types.h inclusion and struct device forward declaration
> 
> RFCv1 => v2:
> - fix include guardian
> - Improve kernel doc for iio_init_iio_gts.
> - Add iio_gts_scale_to_total_gain
> - Add iio_gts_total_gain_to_scale
> - Fix review comments from Jonathan
>   - add documentation to few functions
>   - replace 0xffffffffffffffffLLU by U64_MAX
>   - some styling fixes
>   - drop unnecessary NULL checks
>   - order function arguments by  in / out purpose
>   - drop GAIN_SCALE_ITIME_MS()
> - Add helpers for available scales and times
> - Rename to iio-gts-helpers

> diff --git a/drivers/iio/industrialio-gts-helper.c b/drivers/iio/industrialio-gts-helper.c
> new file mode 100644
> index 000000000000..9494ea7cdbcf
> --- /dev/null
> +++ b/drivers/iio/industrialio-gts-helper.c
> @@ -0,0 +1,990 @@
...

> +
> +static const struct iio_itime_sel_mul *
> +iio_gts_find_itime_by_time(struct iio_gts *gts, int time)

Time going to be positive (I hope!)
So as below, I'd make all time values unsigned.

> +{
> +	int i;
> +
> +	if (!gts->num_itime)
> +		return NULL;
> +
> +	for (i = 0; i < gts->num_itime; i++)
> +		if (gts->itime_table[i].time_us == time)
> +			return &gts->itime_table[i];
> +
> +	return NULL;
> +}

...

> +/**
> + * iio_gts_purge_avail_scale_table - free-up the available scale tables
> + * @gts:	Gain time scale descriptor
> + *
> + * Free the space reserved by iio_gts_build_avail_scale_table(). Please note
> + * that the helpers for getting available scales like the
> + * iio_gts_all_avail_scales() are not usable after this call. Thus, this should
> + * be only called after these helpers can no longer be called (Eg. after
> + * the iio-device has been deregistered).

Whilst I'm not that keen on the comment in general, if you really really want to
have it we need to figure out one place to put it rather than lots of duplicates.

> + */
...


> +static int gain_to_scaletables(struct iio_gts *gts, int **gains, int **scales)
> +{
> +	int ret, i, j, new_idx, time_idx;
> +	int *all_gains;
> +	size_t gain_bytes;
> +
> +	for (i = 0; i < gts->num_itime; i++) {
> +		/*
> +		 * Sort the tables for nice output and for easier finding of
> +		 * unique values.
> +		 */
> +		sort(gains[i], gts->num_hwgain, sizeof(int), iio_gts_gain_cmp,
> +		     NULL);
> +
> +		/* Convert gains to scales */
> +		for (j = 0; j < gts->num_hwgain; j++) {
> +			ret = iio_gts_total_gain_to_scale(gts, gains[i][j],
> +							  &scales[i][2 * j],
> +							  &scales[i][2 * j + 1]);
> +			if (ret)
> +				return ret;
> +		}
> +	}
> +
> +	gain_bytes = array_size(gts->num_hwgain, sizeof(int));
> +	all_gains = kcalloc(gts->num_itime, gain_bytes, GFP_KERNEL);
> +	if (!all_gains)
> +		return -ENOMEM;
> +
> +	/*
> +	 * We assume all the gains for same integration time were unique.
> +	 * It is likely the first time table had greatest time multiplier as
> +	 * the times are in the order of preference and greater times are
> +	 * usually preferred. Hence we start from the last table which is likely
> +	 * to have the smallest total gains.
> +	 */
> +	time_idx = gts->num_itime - 1;
> +	memcpy(all_gains, gains[time_idx], gain_bytes);
> +	new_idx = gts->num_hwgain;
> +
> +	while (time_idx--) {
> +		for (j = 0; j < gts->num_hwgain; j++) {
> +			int candidate = gains[time_idx][j];
> +			int chk;
> +
> +			if (candidate > all_gains[new_idx - 1]) {
> +				all_gains[new_idx] = candidate;
> +				new_idx++;
> +
> +				continue;
> +			}
> +			for (chk = 0; chk < new_idx; chk++)
> +				if (candidate <= all_gains[chk])
> +					break;
> +
> +			if (candidate == all_gains[chk])
> +				continue;
> +
> +			memmove(&all_gains[chk + 1], &all_gains[chk],
> +				(new_idx - chk) * sizeof(int));
> +			all_gains[chk] = candidate;
> +			new_idx++;
> +		}
> +	}
> +
> +	gts->num_avail_all_scales = new_idx;
> +	gts->avail_all_scales_table = kcalloc(gts->num_avail_all_scales,
> +					      2 * sizeof(int), GFP_KERNEL);
> +	if (!gts->avail_all_scales_table)
> +		ret = -ENOMEM;
> +	else
> +		for (i = 0; !ret && i < gts->num_avail_all_scales; i++)
> +			ret = iio_gts_total_gain_to_scale(gts, all_gains[i],
> +					&gts->avail_all_scales_table[i * 2],
> +					&gts->avail_all_scales_table[i * 2 + 1]);
> +
> +	kfree(all_gains);
> +	if (ret)
> +		kfree(gts->avail_all_scales_table);

This is getting too clever.  I'd have an error handling block and gotos
even though it duplicates one line.  
> +
> +	return ret;
> +}
> +
> +/**
> + * iio_gts_build_avail_scale_table - create tables of available scales
> + * @gts:	Gain time scale descriptor
> + *
> + * Build the tables which can represent the available scales based on the
> + * originally given gain and time tables. When both time and gain tables are
> + * given this results:
> + * 1. A set of tables representing available scales for each supported
> + *    integration time.
> + * 2. A single table listing all the unique scales that any combination of
> + *    supported gains and times can provide.
> + *
> + * NOTE: Space allocated for the tables must be freed using
> + * iio_gts_purge_avail_scale_table() when the tables are no longer needed.
> + *
> + * Return: 0 on success.
> + */
> +static int iio_gts_build_avail_scale_table(struct iio_gts *gts)
> +{
> +	int **per_time_gains, **per_time_scales, i, j, ret = -ENOMEM;
> +
> +	per_time_gains = kcalloc(gts->num_itime, sizeof(int *), GFP_KERNEL);

As per other thread, I much prefer reviewing code with sizeof(*per_time_gains)
as it requires fewer brain cells.

> +	if (!per_time_gains)
> +		return ret;
> +
> +	per_time_scales = kcalloc(gts->num_itime, sizeof(int *), GFP_KERNEL);
> +	if (!per_time_scales)
> +		goto free_gains;
> +
> +	for (i = 0; i < gts->num_itime; i++) {
> +		per_time_scales[i] = kcalloc(gts->num_hwgain, 2 * sizeof(int),
> +					     GFP_KERNEL);
> +		if (!per_time_scales[i])
> +			goto err_free_out;
> +
> +		per_time_gains[i] = kcalloc(gts->num_hwgain, sizeof(int),
> +					    GFP_KERNEL);
> +		if (!per_time_gains[i])
> +			goto err_free_scale_out;

As below. I'd put kfree(per_time_scales[i]); here to simplify the paths to
the error handling block.

> +
> +
> +		for (j = 0; j < gts->num_hwgain; j++)
> +			per_time_gains[i][j] = gts->hwgain_table[j].gain *
> +					       gts->itime_table[i].mul;
> +	}
> +
> +	ret = gain_to_scaletables(gts, per_time_gains, per_time_scales);
> +	if (ret)
> +		goto err_free_out;

I'm not a fan of dancing backwards and forwards with exit paths. As such I'd move
the kfree(per_time_scales[i]) to the one condition where it matters above.

> +
> +	kfree(per_time_gains);
> +	gts->per_time_avail_scale_tables = per_time_scales;
> +
> +	return 0;
> +
> +err_free_scale_out:
> +	kfree(per_time_scales[i]);
> +err_free_out:
> +	for (i--; i; i--) {
> +		kfree(per_time_scales[i]);
> +		kfree(per_time_gains[i]);
> +	}
> +	kfree(per_time_scales);
> +free_gains:
> +	kfree(per_time_gains);
> +
> +	return ret;
> +}
> +
> +/**
> + * iio_gts_build_avail_time_table - build table of available integration times
> + * @gts:	Gain time scale descriptor
> + *
> + * Build the table which can represent the available times to be returned
> + * to users using the read_avail-callback.
> + *
> + * NOTE: Space allocated for the tables must be freed using
> + * iio_gts_purge_avail_time_table() when the tables are no longer needed.
> + *
> + * Return: 0 on success.
> + */
> +static int iio_gts_build_avail_time_table(struct iio_gts *gts)
> +{
> +	int *times, i, j, idx = 0;
> +
> +	if (!gts->num_itime)
> +		return 0;
> +
> +	times = kcalloc(gts->num_itime, sizeof(int), GFP_KERNEL);
> +	if (!times)
> +		return -ENOMEM;
> +
> +	for (i = gts->num_itime - 1; i >= 0; i--) {
> +		int new = gts->itime_table[i].time_us;
> +

This looks like a sort routine.  Don't we have something generic that will work?

> +		if (times[idx] < new) {
> +			times[idx++] = new;
> +			continue;
> +		}
> +
> +		for (j = 0; j <= idx; j++) {
> +			if (times[j] > new) {
> +				memmove(&times[j + 1], &times[j],
> +					(idx - j) * sizeof(int));
> +				times[j] = new;
> +				idx++;
> +			}
> +		}
> +	}
> +	gts->avail_time_tables = times;
> +	/*
> +	 * This is just to survive a unlikely corner-case where times in the
> +	 * given time table were not unique. Else we could just trust the
> +	 * gts->num_itime.

If integration times aren't unique I'd count it as driver bug and error out
/scream.  Papering over things like this just make code harder to review
to deal with what is probably a driver bug.

> +	 */
> +	gts->num_avail_time_tables = idx;
> +
> +	return 0;
> +}

...

> +/**
> + * iio_gts_purge_avail_tables - free-up the availability tables
> + * @gts:	Gain time scale descriptor
> + *
> + * Free the space reserved by iio_gts_build_avail_tables(). Frees both the
> + * integration time and scale tables.
> + *
> + * Note  that the helpers for getting available integration times or scales
> + * like the iio_gts_avail_times() are not usable after this call. Thus, this
> + * should be only called after these helpers can no longer be called (Eg.
> + * after the iio-device has been deregistered).
As below, I'm not sure the note adds much over normal use after free...
Also different formatting to the one below.

> + */
> +static void iio_gts_purge_avail_tables(struct iio_gts *gts)
> +{
> +	iio_gts_purge_avail_time_table(gts);
> +	iio_gts_purge_avail_scale_table(gts);
> +}
> +
> +static void devm_iio_gts_avail_all_drop(void *res)
> +{
> +	iio_gts_purge_avail_tables(res);
> +}
> +
> +/**
> + * devm_iio_gts_build_avail_tables - manged add availability tables
> + * @dev:	Pointer to the device whose lifetime tables are bound
> + * @gts:	Gain time scale descriptor
> + *
> + * Build the tables which can represent the available scales and available
> + * integration times. Availability tables are built based on the originally
> + * given gain and given time tables.
> + *
> + * When both time and gain tables are
> + * given this results:

odd line break.

> + * 1. A set of sorted tables representing available scales for each supported
> + *    integration time.
> + * 2. A single sorted table listing all the unique scales that any combination
> + *    of supported gains and times can provide.
> + * 3. A sorted table of supported integration times
> + *
> + * After these tables are built one can use the iio_gts_all_avail_scales(),
> + * iio_gts_avail_scales_for_time() and iio_gts_avail_times() helpers to
> + * implement the read_avail opeations.
> + *
> + * The tables are automatically released upon device detach.
> + *
> + * NOTE: after the tables have been purged, the helpers for getting
> + * available scales / integration times are no longer usable. Care must be
> + * taken that unwinding is done in correct order (iio device is deregistered
> + * prior purging the tables).

Hmm. I think this note is calling out one potential path (even if it's the most
common one). I'd not bother with it as a driver should use no resources after
they've been freed and this is typically one of many.

> + *
> + * Return: 0 on success.
> + */
> +int devm_iio_gts_build_avail_tables(struct device *dev, struct iio_gts *gts)
> +{
> +	int ret;
> +
> +	ret = iio_gts_build_avail_tables(gts);
> +	if (ret)
> +		return ret;
> +
> +	return devm_add_action_or_reset(dev, devm_iio_gts_avail_all_drop, gts);
> +}
> +EXPORT_SYMBOL_GPL(devm_iio_gts_build_avail_tables);

> +/**
> + * iio_gts_valid_time - check if given integration time is valid
> + * @gts:	Gain time scale descriptor
> + * @time_us:	Integration time to check
> + *
> + * Return:	True if given time is supported by device. False if not.
> + */
> +bool iio_gts_valid_time(struct iio_gts *gts, int time_us)
> +{
> +	return iio_gts_find_itime_by_time(gts, time_us);
I'd make this a little more explicit as implicit casting pointer to bool is
rather unusual.
	!= NULL; maybe?

	
> +}
> +EXPORT_SYMBOL_GPL(iio_gts_valid_time);
> +
> +int iio_gts_find_sel_by_gain(struct iio_gts *gts, int gain)
> +{
> +	int i;
> +
> +	for (i = 0; i < gts->num_hwgain; i++)
> +		if (gts->hwgain_table[i].gain == gain)
> +			return gts->hwgain_table[i].sel;
> +
> +	return -EINVAL;
> +}
> +EXPORT_SYMBOL_GPL(iio_gts_find_sel_by_gain);
> +
> +bool iio_gts_valid_gain(struct iio_gts *gts, int gain)
> +{
> +	return iio_gts_find_sel_by_gain(gts, gain) >= 0;
> +}
> +EXPORT_SYMBOL_GPL(iio_gts_valid_gain);

For the _valid_xxx functions, I wonder if you shouldn't just
push them to the header as static inline

> +
> +int iio_gts_find_gain_by_sel(struct iio_gts *gts, int sel)
> +{
> +	int i;
> +
> +	for (i = 0; i < gts->num_hwgain; i++)
> +		if (gts->hwgain_table[i].sel == sel)
> +			return gts->hwgain_table[i].gain;
> +
> +	return -EINVAL;
> +}
> +EXPORT_SYMBOL_GPL(iio_gts_find_gain_by_sel);
> +
> +int iio_gts_get_min_gain(struct iio_gts *gts)

Could just use min = INT_MAX;
(indirectly from linux/limits.h, it's actually in vdso/limits.h
but should not include that directly I think)
then I don't hink you need the special casing for the
first entry.

> +{
> +	int i, min = -EINVAL;
> +
> +	for (i = 0; i < gts->num_hwgain; i++) {
> +		int gain = gts->hwgain_table[i].gain;
> +
> +		if (min == -EINVAL)
> +			min = gain;
> +		else
> +			min = min(min, gain);
> +	}
> +
> +	return min;
> +}
> +EXPORT_SYMBOL_GPL(iio_gts_get_min_gain);
> +
> +/**
> + * iio_find_closest_gain_low - Find the closest lower matching gain
> + * @gts:	Gain time scale descriptor
> + * @gain:	reference gain for which the closest match is searched
> + * @in_range:	indicate if the reference gain was actually in the range of
> + *		supported gains.
> + *
> + * Search for closest supported gain that is lower than or equal to the
> + * gain given as a parameter. This is usable for drivers which do not require
> + * user to request exact matching gain but rather fo rounding to a supported
> + * gain value which is equal or lower (setting lower gain is typical for
> + * avoiding saturation)
> + *
> + * Return:	The closest matching supported gain or -EINVAL is reference

Maybe just say @gain was smaller.  reference gain does not have clear meaning to me.

> + *		gain was smaller than the smallest supported gain.
> + */
> +int iio_find_closest_gain_low(struct iio_gts *gts, int gain, bool *in_range)
> +{
> +	int i, diff = 0;
> +	int best = -1;
> +
> +	*in_range = false;
> +
> +	for (i = 0; i < gts->num_hwgain; i++) {
> +		/*
> +		 * It is not expected this function is called for an exactly
> +		 * matching gain.
I'd not mark it unlikely even so (or comment on it).
This is unlikely to be a particularly hot path so this unlikely() seems like a
premature optimization which adds complexity to the code.

> +		 */
> +		if (unlikely(gain == gts->hwgain_table[i].gain)) {
> +			*in_range = true;
> +			return gain;
> +		}
> +
> +		if (gain > gts->hwgain_table[i].gain) {
> +			if (!diff) {
> +				diff = gain - gts->hwgain_table[i].gain;
> +				best = i;
> +			} else {
> +				int tmp = gain - gts->hwgain_table[i].gain;
> +
> +				if (tmp < diff) {
> +					diff = tmp;
> +					best = i;
> +				}
> +			}
> +		} else {
> +			/*
> +			 * We found valid hwgain which is greater than
> +			 * reference. So, unless we return a failure below we
> +			 * will have found an in-range gain
> +			 */
> +			*in_range = true;
> +		}
> +	}
> +	/* The requested gain was smaller than anything we support */
> +	if (!diff) {
> +		*in_range = false;
> +
> +		return -EINVAL;
> +	}
> +
> +	return gts->hwgain_table[best].gain;
> +}
> +EXPORT_SYMBOL_GPL(iio_find_closest_gain_low);


...


> +/*
> + * iio_gts_find_gain_sel_for_scale_using_time - Fetch gain selector.
> + * See iio_gts_find_gain_for_scale_using_time() for more information

This is exported, so I'd rather see kernel-doc style comments.

> + */
> +int iio_gts_find_gain_sel_for_scale_using_time(struct iio_gts *gts, int time_sel,
> +					       int scale_int, int scale_nano,
> +					       int *gain_sel)
> +{
> +	int gain, ret;
> +
> +	ret = iio_gts_find_gain_for_scale_using_time(gts, time_sel, scale_int,
> +						     scale_nano, &gain);
> +	if (ret)
> +		return ret;
> +
> +	ret = iio_gts_find_sel_by_gain(gts, gain);
> +	if (ret < 0)
> +		return ret;
> +
> +	*gain_sel = ret;
> +
> +	return 0;
> +}
> +EXPORT_SYMBOL_GPL(iio_gts_find_gain_sel_for_scale_using_time);
> +
> +int iio_gts_find_int_time_by_sel(struct iio_gts *gts, int sel)
> +{
> +	const struct iio_itime_sel_mul *itime;
> +
> +	itime = iio_gts_find_itime_by_sel(gts, sel);
> +	if (!itime)
> +		return -EINVAL;
> +
> +	return itime->time_us;

Currently can be negative.  Even when you stop that being the case
by makign time unsigned, you need to be careful with ranges here.
You may be better off separating the error handling from the values
to avoid any issues even though that makes it a little harder to use.

> +}
> +EXPORT_SYMBOL_GPL(iio_gts_find_int_time_by_sel);
> +
> +int iio_gts_find_sel_by_int_time(struct iio_gts *gts, int time)
> +{
> +	const struct iio_itime_sel_mul *itime;
> +
> +	itime = iio_gts_find_itime_by_time(gts, time);
> +	if (!itime)
> +		return -EINVAL;
> +
> +	return itime->sel;

itime->sel can be negative.  I wonder if you should just make that
u16 so that you can always return it as a positive integer but
having it as unsigned in the structure.

Otherwise you need to add some docs on those limits and probably
sanity check them during the _init()


> +}
> +EXPORT_SYMBOL_GPL(iio_gts_find_sel_by_int_time);
> +
> +static int iio_gts_get_total_gain(struct iio_gts *gts, int gain, int time)
> +{
> +	const struct iio_itime_sel_mul *itime;
> +
> +	if (!iio_gts_valid_gain(gts, gain))
> +		return -EINVAL;
> +
> +	if (!gts->num_itime)
> +		return gain;
> +
> +	itime = iio_gts_find_itime_by_time(gts, time);
> +	if (!itime)
> +		return -EINVAL;
> +
> +	return gain * itime->mul;

Check for overflow perhaps?

> +}
> +
> +static int iio_gts_get_scale_linear(struct iio_gts *gts, int gain, int time,
> +				    u64 *scale)
> +{
> +	int total_gain;
> +	u64 tmp
> +
> +	total_gain = iio_gts_get_total_gain(gts, gain, time);
> +	if (total_gain < 0)
> +		return total_gain;
> +
> +	tmp = gts->max_scale;
> +
> +	do_div(tmp, total_gain);
> +
> +	*scale = tmp;
> +
> +	return 0;
> +}
> +
> +int iio_gts_get_scale(struct iio_gts *gts, int gain, int time, int *scale_int,
> +		      int *scale_nano)
> +{
> +	u64 lin_scale;
> +	int ret;
> +
> +	ret = iio_gts_get_scale_linear(gts, gain, time, &lin_scale);
> +	if (ret)
> +		return ret;
> +
> +	return iio_gts_delinearize(lin_scale, NANO, scale_int, scale_nano);
> +}
> +EXPORT_SYMBOL_GPL(iio_gts_get_scale);

It is good practice to add kernel-doc for all the exported functions,
even if some of them will be fairly obvious.  In this case the function
definition doesn't make it clear how time and gain are specified.
usecs? an index into a set of provided values?

If you can make the units explicit in the parameter that's even better.
I will note that negative times seem unlikely so maybe that should always
be unsigned?  gain probably can be negative even if that's unusual.
That may lead to problems though as lin_scale is in turn unsigned.

> +
> +/**
> + * iio_gts_find_new_gain_sel_by_old_gain_time - compensate time change

compensate for time change

> + * @gts:		Gain time scale descriptor
> + * @old_gain:		Previously set gain
> + * @old_time_sel:	Selector corresponding previously set time
> + * @new_time_sel:	Selector corresponding new time to be set
> + * @new_gain:		Pointer to value where new gain is to be written
> + *
> + * We may want to mitigate the scale change caused by setting a new integration
> + * time (for a light sensor) by also updating the (HW)gain. This helper computes
> + * new gain value to maintain the scale with new integration time.
> + *
> + * Return: 0 on success. -EINVAL if gain matching the new time is not found.
> + */
> +int iio_gts_find_new_gain_sel_by_old_gain_time(struct iio_gts *gts,
> +					       int old_gain, int old_time_sel,
> +					       int new_time_sel, int *new_gain)
> +{
> +	const struct iio_itime_sel_mul *itime_old, *itime_new;
> +	u64 scale;
> +	int ret;
> +
> +	itime_old = iio_gts_find_itime_by_sel(gts, old_time_sel);
> +	if (!itime_old)
> +		return -EINVAL;
> +
> +	itime_new = iio_gts_find_itime_by_sel(gts, new_time_sel);
> +	if (!itime_new)
> +		return -EINVAL;
> +
> +	ret = iio_gts_get_scale_linear(gts, old_gain, itime_old->time_us,
> +				       &scale);
> +	if (ret)
> +		return ret;
> +
> +	ret = gain_get_scale_fraction(gts->max_scale, scale, itime_new->mul,
> +				      new_gain);
> +	if (ret)
> +		return -EINVAL;
> +
> +	if (!iio_gts_valid_gain(gts, *new_gain))
> +		return -EINVAL;
> +
> +	return 0;
> +}
> +EXPORT_SYMBOL_GPL(iio_gts_find_new_gain_sel_by_old_gain_time);
Matti Vaittinen March 20, 2023, 12:01 p.m. UTC | #2
On 3/19/23 20:08, Jonathan Cameron wrote:
> On Fri, 17 Mar 2023 16:43:23 +0200
> Matti Vaittinen <mazziesaccount@gmail.com> wrote:
> 
>> Some light sensors can adjust both the HW-gain and integration time.
>> There are cases where adjusting the integration time has similar impact
>> to the scale of the reported values as gain setting has.
>>
>> IIO users do typically expect to handle scale by a single writable 'scale'
>> entry. Driver should then adjust the gain/time accordingly.
>>
>> It however is difficult for a driver to know whether it should change
>> gain or integration time to meet the requested scale. Usually it is
>> preferred to have longer integration time which usually improves
>> accuracy, but there may be use-cases where long measurement times can be
>> an issue. Thus it can be preferable to allow also changing the
>> integration time - but mitigate the scale impact by also changing the gain
>> underneath. Eg, if integration time change doubles the measured values,
>> the driver can reduce the HW-gain to half.
>>
>> The theory of the computations of gain-time-scale is simple. However,
>> some people (undersigned) got that implemented wrong for more than once.
>>
>> Add some gain-time-scale helpers in order to not dublicate errors in all
>> drivers needing these computations.
>>
>> Signed-off-by: Matti Vaittinen <mazziesaccount@gmail.com>
> 
> Whilst you use it in the tests currently I'm not convinced there is a good
> reason to separate iio_init_iio_gts() from devm_iio_gts_build_avail_tables()
> as I'd expect them to be called as a pair in all drivers that use this.

I was wondering if I should only provide the:

[devm_]iio_init_iio_gts() and always unconditionally allocate and build 
the tables inside the initialization routine.

I don't really care so much about how the tests are done. In my opinion 
the testability needs should rarely be determining what the production 
code looks like. In this case it is a waste of time / resources for 
drivers which do not tell the available scales/times to user-space, or 
do need some special routine for this. This is why I did make 
build_avail_tables() optional. Still not sure what would be the best 
approach though.

> Perhaps it's worth reworking the tests to do that even if it's not strictly
> necessary for specific tests.
> 
> I think a bit more care is need with storage of time (unsigned) + decide
> whether to allow for negative gains.

My approach was just pretty simple "int is big enough for the times" 
(2000+ seconds when using usec as time units felt like more than enough 
for light sensors) and "gains are always positive".

I have not tested the negative gains at all - but I agree this should've 
been documented. Currently there is no gts-helper users who need 
negative gain (or large times for that matter) - so I was not handling them.

I'll try to check what it would mean code-wise if we converted times to 
unsigned. Negative times make no sense but allowing negative error 
values is a simple way to go.

As for the negative gains - I have no problem of someone adding a 
support for those if needed, but I don't currently see much point in 
investing time in that...

> Whilst they happen I'm not that bothered
> if that subtlety becomes a device driver problem when calling this.  I'm not
> sure I've seen a sensor that does both positive and negative gains for a single
> channel.

I agree. If driver needs negative gains, then the driver needs to deal 
with it. I have no objections if driver authors want to improve these 
helpers by adding support for negative gains, but if they don't, then 
they have the exactly same problem they would have without these helpers :)

>> ---
>> Currently it is only BU27034 using these in this series. I am however working
>> with drivers for RGB sensors BU27008 and BU27010 which have similar
>> [gain - integration time - scale] - relation. I hope sending those
>> follows soon after the BU27034 is done.
>>
>> Changes:
>> v3 => v4:
>> - doc styling
>> - use memset to zero the helper struct at init
>> - drop unnecessary min calculation at iio_find_closest_gain_low()
>> - use namespace to all exports
>> - many minor stylings
>> - make available outside iio/light (move code to drivers/iio and move the
>>    header under include
>> - rename to look like other files under drivers/iio (s/iio/industrialio)
> 
> Ah. I've always regretted not using iio_ for the prefix on those so I'm fine
> if you would prefer to stick to iio_

I do like iio better. However, I think we should have common prefix for 
these files. Having both iio- and industrialio- will be confusing for 
newcomers. If I saw just one iio- prefixed file I would have assumed it 
is for a specific use, not for common use as the other "IIO-core" files.

One option would be converting all these industrialio-*.c files to 
iio_*.c - but I am not sure if it is worth the hassle.

>> - drop unused functions
>> - don't export only internally used functions and make them static
>>    Note, I decided to keep iio_gts_total_gain_to_scale() exported as it is
>>    currently needed by the tests outside the helpers.
>>
>> v2 => v3: (mostly fixes based on review by Andy)
>> - Fix typos
>> - Styling fixes
>> - Use namespace for exported symbols
>> - Protect allocs against argument overflow
>> - Fix include protection name
>> - add types.h inclusion and struct device forward declaration
>>
>> RFCv1 => v2:
>> - fix include guardian
>> - Improve kernel doc for iio_init_iio_gts.
>> - Add iio_gts_scale_to_total_gain
>> - Add iio_gts_total_gain_to_scale
>> - Fix review comments from Jonathan
>>    - add documentation to few functions
>>    - replace 0xffffffffffffffffLLU by U64_MAX
>>    - some styling fixes
>>    - drop unnecessary NULL checks
>>    - order function arguments by  in / out purpose
>>    - drop GAIN_SCALE_ITIME_MS()
>> - Add helpers for available scales and times
>> - Rename to iio-gts-helpers
> 
>> diff --git a/drivers/iio/industrialio-gts-helper.c b/drivers/iio/industrialio-gts-helper.c
>> new file mode 100644
>> index 000000000000..9494ea7cdbcf
>> --- /dev/null
>> +++ b/drivers/iio/industrialio-gts-helper.c
>> @@ -0,0 +1,990 @@
> ...
> 
>> +
>> +static const struct iio_itime_sel_mul *
>> +iio_gts_find_itime_by_time(struct iio_gts *gts, int time)
> 
> Time going to be positive (I hope!)
> So as below, I'd make all time values unsigned.

I'll see what this would result. But as I said below, I am not sure it's 
worth the added complexity.

> 
>> +{
>> +	int i;
>> +
>> +	if (!gts->num_itime)
>> +		return NULL;
>> +
>> +	for (i = 0; i < gts->num_itime; i++)
>> +		if (gts->itime_table[i].time_us == time)
>> +			return &gts->itime_table[i];
>> +
>> +	return NULL;
>> +}
> 
> ...
> 
>> +/**
>> + * iio_gts_purge_avail_scale_table - free-up the available scale tables
>> + * @gts:	Gain time scale descriptor
>> + *
>> + * Free the space reserved by iio_gts_build_avail_scale_table(). Please note
>> + * that the helpers for getting available scales like the
>> + * iio_gts_all_avail_scales() are not usable after this call. Thus, this should
>> + * be only called after these helpers can no longer be called (Eg. after
>> + * the iio-device has been deregistered).
> 
> Whilst I'm not that keen on the comment in general, if you really really want to
> have it we need to figure out one place to put it rather than lots of duplicates.

I have seen way too many bugs with the unwinding errors. Usually with 
the IRQs but also when user-space has access to driver stuff. I placed 
this comment here hoping it would prevent at least one such bug as those 
tend to be really nasty to debug. If we avoid one, it is well worth of 
few lines of comment (IMO).


>> +	if (!gts->avail_all_scales_table)
>> +		ret = -ENOMEM;
>> +	else
>> +		for (i = 0; !ret && i < gts->num_avail_all_scales; i++)
>> +			ret = iio_gts_total_gain_to_scale(gts, all_gains[i],
>> +					&gts->avail_all_scales_table[i * 2],
>> +					&gts->avail_all_scales_table[i * 2 + 1]);
>> +
>> +	kfree(all_gains);
>> +	if (ret)
>> +		kfree(gts->avail_all_scales_table);
> 
> This is getting too clever.  I'd have an error handling block and gotos
> even though it duplicates one line.

gah. As I discussed with Andy, I do hate changing this. Well, I guess I 
have no choice.

>> +
>> +	return ret;
>> +}
>> +
>> +/**
>> + * iio_gts_build_avail_scale_table - create tables of available scales
>> + * @gts:	Gain time scale descriptor
>> + *
>> + * Build the tables which can represent the available scales based on the
>> + * originally given gain and time tables. When both time and gain tables are
>> + * given this results:
>> + * 1. A set of tables representing available scales for each supported
>> + *    integration time.
>> + * 2. A single table listing all the unique scales that any combination of
>> + *    supported gains and times can provide.
>> + *
>> + * NOTE: Space allocated for the tables must be freed using
>> + * iio_gts_purge_avail_scale_table() when the tables are no longer needed.
>> + *
>> + * Return: 0 on success.
>> + */
>> +static int iio_gts_build_avail_scale_table(struct iio_gts *gts)
>> +{
>> +	int **per_time_gains, **per_time_scales, i, j, ret = -ENOMEM;
>> +
>> +	per_time_gains = kcalloc(gts->num_itime, sizeof(int *), GFP_KERNEL);
> 
> As per other thread, I much prefer reviewing code with sizeof(*per_time_gains)
> as it requires fewer brain cells.

Hm. I think it depends on whether one wants to understand how many bytes 
the sizeof() is actually referring. Well, again, I guess I have no 
choice here.

>> +	if (!per_time_gains)
>> +		return ret;
>> +
>> +	per_time_scales = kcalloc(gts->num_itime, sizeof(int *), GFP_KERNEL);
>> +	if (!per_time_scales)
>> +		goto free_gains;
>> +
>> +	for (i = 0; i < gts->num_itime; i++) {
>> +		per_time_scales[i] = kcalloc(gts->num_hwgain, 2 * sizeof(int),
>> +					     GFP_KERNEL);
>> +		if (!per_time_scales[i])
>> +			goto err_free_out;
>> +
>> +		per_time_gains[i] = kcalloc(gts->num_hwgain, sizeof(int),
>> +					    GFP_KERNEL);
>> +		if (!per_time_gains[i])
>> +			goto err_free_scale_out;
> 
> As below. I'd put kfree(per_time_scales[i]); here to simplify the paths to
> the error handling block.
> 
>> +
>> +
>> +		for (j = 0; j < gts->num_hwgain; j++)
>> +			per_time_gains[i][j] = gts->hwgain_table[j].gain *
>> +					       gts->itime_table[i].mul;
>> +	}
>> +
>> +	ret = gain_to_scaletables(gts, per_time_gains, per_time_scales);
>> +	if (ret)
>> +		goto err_free_out;
> 
> I'm not a fan of dancing backwards and forwards with exit paths. As such I'd move
> the kfree(per_time_scales[i]) to the one condition where it matters above.

Ok.

> 
>> +
>> +	kfree(per_time_gains);
>> +	gts->per_time_avail_scale_tables = per_time_scales;
>> +
>> +	return 0;
>> +
>> +err_free_scale_out:
>> +	kfree(per_time_scales[i]);
>> +err_free_out:
>> +	for (i--; i; i--) {
>> +		kfree(per_time_scales[i]);
>> +		kfree(per_time_gains[i]);
>> +	}
>> +	kfree(per_time_scales);
>> +free_gains:
>> +	kfree(per_time_gains);
>> +
>> +	return ret;
>> +}
>> +
>> +/**
>> + * iio_gts_build_avail_time_table - build table of available integration times
>> + * @gts:	Gain time scale descriptor
>> + *
>> + * Build the table which can represent the available times to be returned
>> + * to users using the read_avail-callback.
>> + *
>> + * NOTE: Space allocated for the tables must be freed using
>> + * iio_gts_purge_avail_time_table() when the tables are no longer needed.
>> + *
>> + * Return: 0 on success.
>> + */
>> +static int iio_gts_build_avail_time_table(struct iio_gts *gts)
>> +{
>> +	int *times, i, j, idx = 0;
>> +
>> +	if (!gts->num_itime)
>> +		return 0;
>> +
>> +	times = kcalloc(gts->num_itime, sizeof(int), GFP_KERNEL);
>> +	if (!times)
>> +		return -ENOMEM;
>> +
>> +	for (i = gts->num_itime - 1; i >= 0; i--) {
>> +		int new = gts->itime_table[i].time_us;
>> +
> 
> This looks like a sort routine.  Don't we have something generic that will work?

I think this is "combine and sort many tables into one while dropping 
duplicates". I must admit I don't know what sort routines we have 
in-kernel. If we have one which removes duplicates, then we could 
probably copy all the tables into one array and run such sort on it.

Or then we can leave this as is and add a comment about telling is going 
on here :)

> 
>> +		if (times[idx] < new) {
>> +			times[idx++] = new;
>> +			continue;
>> +		}
>> +
>> +		for (j = 0; j <= idx; j++) {
>> +			if (times[j] > new) {
>> +				memmove(&times[j + 1], &times[j],
>> +					(idx - j) * sizeof(int));
>> +				times[j] = new;
>> +				idx++;
>> +			}
>> +		}
>> +	}
>> +	gts->avail_time_tables = times;
>> +	/*
>> +	 * This is just to survive a unlikely corner-case where times in the
>> +	 * given time table were not unique. Else we could just trust the
>> +	 * gts->num_itime.
> 
> If integration times aren't unique I'd count it as driver bug and error out
> /scream.  Papering over things like this just make code harder to review
> to deal with what is probably a driver bug.

I am not entirely sure. I don't know the sensor ICs in details, but I've 
seen plenty of other ICs where we may have different register values 
that mean same physical measure. One such example is almost all ROHM 
PMICs, where we often see voltage selection registers like:

register val 0 to <foo>:
  - 1.0V + (val * 10 mV)
register val <A> to <MAX>:
  - 3.3 V

If we have similar registers for the time, then it may be good idea to 
accept selectors A...MAX to have the same time. This allows the 
gts-helpers to be used to convert the register values to times also for 
such devices. If we don't allow same times to be in the tables, then 
there may be unknown but valid register values read from the IC.

>> +	 */
>> +	gts->num_avail_time_tables = idx;
>> +
>> +	return 0;
>> +}
> 
> ...
> 
>> +/**
>> + * iio_gts_purge_avail_tables - free-up the availability tables
>> + * @gts:	Gain time scale descriptor
>> + *
>> + * Free the space reserved by iio_gts_build_avail_tables(). Frees both the
>> + * integration time and scale tables.
>> + *
>> + * Note  that the helpers for getting available integration times or scales
>> + * like the iio_gts_avail_times() are not usable after this call. Thus, this
>> + * should be only called after these helpers can no longer be called (Eg.
>> + * after the iio-device has been deregistered).
> As below, I'm not sure the note adds much over normal use after free...

It is just use-after-free indeed. But people keep making these mistakes 
- and when they involve devive removal + unfortunate timing of 
user-space action to trigger they get really nasty to debug. Hence I 
hoped we could stop the code writer for a moment and ask him/her to take 
a look at his/her rewinding routine for this type of errors... Avoiding 
even one such bug is well worth couple of lines of text don't you think ;)

> Also different formatting to the one below.
> 
>> + */
>> +static void iio_gts_purge_avail_tables(struct iio_gts *gts)
>> +{
>> +	iio_gts_purge_avail_time_table(gts);
>> +	iio_gts_purge_avail_scale_table(gts);
>> +}
>> +
>> +static void devm_iio_gts_avail_all_drop(void *res)
>> +{
>> +	iio_gts_purge_avail_tables(res);
>> +}
>> +
>> +/**
>> + * devm_iio_gts_build_avail_tables - manged add availability tables
>> + * @dev:	Pointer to the device whose lifetime tables are bound
>> + * @gts:	Gain time scale descriptor
>> + *
>> + * Build the tables which can represent the available scales and available
>> + * integration times. Availability tables are built based on the originally
>> + * given gain and given time tables.
>> + *
>> + * When both time and gain tables are
>> + * given this results:
> 
> odd line break.
> 
>> + * 1. A set of sorted tables representing available scales for each supported
>> + *    integration time.
>> + * 2. A single sorted table listing all the unique scales that any combination
>> + *    of supported gains and times can provide.
>> + * 3. A sorted table of supported integration times
>> + *
>> + * After these tables are built one can use the iio_gts_all_avail_scales(),
>> + * iio_gts_avail_scales_for_time() and iio_gts_avail_times() helpers to
>> + * implement the read_avail opeations.
>> + *
>> + * The tables are automatically released upon device detach.
>> + *
>> + * NOTE: after the tables have been purged, the helpers for getting
>> + * available scales / integration times are no longer usable. Care must be
>> + * taken that unwinding is done in correct order (iio device is deregistered
>> + * prior purging the tables).
> 
> Hmm. I think this note is calling out one potential path (even if it's the most
> common one). I'd not bother with it as a driver should use no resources after
> they've been freed and this is typically one of many.

Well, I guess we both know by now why I added the note :) Hence I won't 
repeat my reasoning. I can drop the note if you think it serves no purpose.

> 
>> + *
>> + * Return: 0 on success.
>> + */
>> +int devm_iio_gts_build_avail_tables(struct device *dev, struct iio_gts *gts)
>> +{
>> +	int ret;
>> +
>> +	ret = iio_gts_build_avail_tables(gts);
>> +	if (ret)
>> +		return ret;
>> +
>> +	return devm_add_action_or_reset(dev, devm_iio_gts_avail_all_drop, gts);
>> +}
>> +EXPORT_SYMBOL_GPL(devm_iio_gts_build_avail_tables);
> 
>> +/**
>> + * iio_gts_valid_time - check if given integration time is valid
>> + * @gts:	Gain time scale descriptor
>> + * @time_us:	Integration time to check
>> + *
>> + * Return:	True if given time is supported by device. False if not.
>> + */
>> +bool iio_gts_valid_time(struct iio_gts *gts, int time_us)
>> +{
>> +	return iio_gts_find_itime_by_time(gts, time_us);
> I'd make this a little more explicit as implicit casting pointer to bool is
> rather unusual.
> 	!= NULL; maybe?

I think I may have had the !! here in the beginning. Yes, I can do != NULL.

> 
> 	
>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_valid_time);
>> +
>> +int iio_gts_find_sel_by_gain(struct iio_gts *gts, int gain)
>> +{
>> +	int i;
>> +
>> +	for (i = 0; i < gts->num_hwgain; i++)
>> +		if (gts->hwgain_table[i].gain == gain)
>> +			return gts->hwgain_table[i].sel;
>> +
>> +	return -EINVAL;
>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_find_sel_by_gain);
>> +
>> +bool iio_gts_valid_gain(struct iio_gts *gts, int gain)
>> +{
>> +	return iio_gts_find_sel_by_gain(gts, gain) >= 0;
>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_valid_gain);
> 
> For the _valid_xxx functions, I wonder if you shouldn't just
> push them to the header as static inline

Well, I guess I can. No problem.

> 
>> +
>> +int iio_gts_find_gain_by_sel(struct iio_gts *gts, int sel)
>> +{
>> +	int i;
>> +
>> +	for (i = 0; i < gts->num_hwgain; i++)
>> +		if (gts->hwgain_table[i].sel == sel)
>> +			return gts->hwgain_table[i].gain;
>> +
>> +	return -EINVAL;
>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_find_gain_by_sel);
>> +
>> +int iio_gts_get_min_gain(struct iio_gts *gts)
> 
> Could just use min = INT_MAX;
> (indirectly from linux/limits.h, it's actually in vdso/limits.h
> but should not include that directly I think)
> then I don't hink you need the special casing for the
> first entry.

Hmm. I guess you think we don't need to handle case num_hwgain == 0 here 
as it should be checked in the initialization routine. Not sure what to 
think about it.

> 
>> +{
>> +	int i, min = -EINVAL;
>> +
>> +	for (i = 0; i < gts->num_hwgain; i++) {
>> +		int gain = gts->hwgain_table[i].gain;
>> +
>> +		if (min == -EINVAL)
>> +			min = gain;
>> +		else
>> +			min = min(min, gain);
>> +	}
>> +
>> +	return min;
>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_get_min_gain);
>> +
>> +/**
>> + * iio_find_closest_gain_low - Find the closest lower matching gain
>> + * @gts:	Gain time scale descriptor
>> + * @gain:	reference gain for which the closest match is searched
>> + * @in_range:	indicate if the reference gain was actually in the range of
>> + *		supported gains.
>> + *
>> + * Search for closest supported gain that is lower than or equal to the
>> + * gain given as a parameter. This is usable for drivers which do not require
>> + * user to request exact matching gain but rather fo rounding to a supported
>> + * gain value which is equal or lower (setting lower gain is typical for
>> + * avoiding saturation)
>> + *
>> + * Return:	The closest matching supported gain or -EINVAL is reference
> 
> Maybe just say @gain was smaller.  reference gain does not have clear meaning to me.

Ok.

> 
>> + *		gain was smaller than the smallest supported gain.
>> + */
>> +int iio_find_closest_gain_low(struct iio_gts *gts, int gain, bool *in_range)
>> +{
>> +	int i, diff = 0;
>> +	int best = -1;
>> +
>> +	*in_range = false;
>> +
>> +	for (i = 0; i < gts->num_hwgain; i++) {
>> +		/*
>> +		 * It is not expected this function is called for an exactly
>> +		 * matching gain.
> I'd not mark it unlikely even so (or comment on it).
> This is unlikely to be a particularly hot path so this unlikely() seems like a
> premature optimization which adds complexity to the code.

Hm. I don't really see the increased complexity here - but I don't also 
think this is going to be very performance critical either. So, I can 
drop this even though I personally think that small optimizations here 
and there (when not really adding extra complexity) should actually be 
encouraged.

>> +/*
>> + * iio_gts_find_gain_sel_for_scale_using_time - Fetch gain selector.
>> + * See iio_gts_find_gain_for_scale_using_time() for more information
> 
> This is exported, so I'd rather see kernel-doc style comments.

Ok.

> 
>> + */
>> +int iio_gts_find_gain_sel_for_scale_using_time(struct iio_gts *gts, int time_sel,
>> +					       int scale_int, int scale_nano,
>> +					       int *gain_sel)
>> +{
>> +	int gain, ret;
>> +
>> +	ret = iio_gts_find_gain_for_scale_using_time(gts, time_sel, scale_int,
>> +						     scale_nano, &gain);
>> +	if (ret)
>> +		return ret;
>> +
>> +	ret = iio_gts_find_sel_by_gain(gts, gain);
>> +	if (ret < 0)
>> +		return ret;
>> +
>> +	*gain_sel = ret;
>> +
>> +	return 0;
>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_find_gain_sel_for_scale_using_time);
>> +
>> +int iio_gts_find_int_time_by_sel(struct iio_gts *gts, int sel)
>> +{
>> +	const struct iio_itime_sel_mul *itime;
>> +
>> +	itime = iio_gts_find_itime_by_sel(gts, sel);
>> +	if (!itime)
>> +		return -EINVAL;
>> +
>> +	return itime->time_us;
> 
> Currently can be negative.  Even when you stop that being the case
> by makign time unsigned, you need to be careful with ranges here.
> You may be better off separating the error handling from the values
> to avoid any issues even though that makes it a little harder to use.

Yes. As I wrote above, I thought that the driver author needs to ensure 
the valid times would always be positive. I was guessing usec is going 
to be used as unit for most cases and 2000+ seconds is probably 
sufficient. But yes, I guess I should have documented this.

Hmm. Do you think we should support times larger than can be represented 
by signed int? I'd rather not support that if it is not needed as it 
will make this quite a bit more complex.

>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_find_int_time_by_sel);
>> +
>> +int iio_gts_find_sel_by_int_time(struct iio_gts *gts, int time)
>> +{
>> +	const struct iio_itime_sel_mul *itime;
>> +
>> +	itime = iio_gts_find_itime_by_time(gts, time);
>> +	if (!itime)
>> +		return -EINVAL;
>> +
>> +	return itime->sel;
> 
> itime->sel can be negative.  I wonder if you should just make that
> u16 so that you can always return it as a positive integer but
> having it as unsigned in the structure.

Here I did the same assumption of sel sizes. I don't expect we to see 32 
bit selectors. To tell the truth, I just followed the linear_ranges 
logic which is heavily used in the regulator drivers.

> Otherwise you need to add some docs on those limits and probably
> sanity check them during the _init()

I am almost certain the sanity check is going to be an overkill, but it 
sure is doable. The onlu corner case I can think of is if register 
really accepts the time itself as a "selector" - but even then having 
such large values they would use the whole 32bits would be unlikely.

>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_find_sel_by_int_time);
>> +
>> +static int iio_gts_get_total_gain(struct iio_gts *gts, int gain, int time)
>> +{
>> +	const struct iio_itime_sel_mul *itime;
>> +
>> +	if (!iio_gts_valid_gain(gts, gain))
>> +		return -EINVAL;
>> +
>> +	if (!gts->num_itime)
>> +		return gain;
>> +
>> +	itime = iio_gts_find_itime_by_time(gts, time);
>> +	if (!itime)
>> +		return -EINVAL;
>> +
>> +	return gain * itime->mul;
> 
> Check for overflow perhaps?

I think that if we want to add the overflow checks, we should do that 
already in init. That way we can check all the combinations before they 
are used - so that the driver authors get the errors even if they did 
not test all the times/gains their HW is supporting. I am not really 
convinced it's worth though.

>> +}
>> +
>> +static int iio_gts_get_scale_linear(struct iio_gts *gts, int gain, int time,
>> +				    u64 *scale)
>> +{
>> +	int total_gain;
>> +	u64 tmp
>> +
>> +	total_gain = iio_gts_get_total_gain(gts, gain, time);
>> +	if (total_gain < 0)
>> +		return total_gain;
>> +
>> +	tmp = gts->max_scale;
>> +
>> +	do_div(tmp, total_gain);
>> +
>> +	*scale = tmp;
>> +
>> +	return 0;
>> +}
>> +
>> +int iio_gts_get_scale(struct iio_gts *gts, int gain, int time, int *scale_int,
>> +		      int *scale_nano)
>> +{
>> +	u64 lin_scale;
>> +	int ret;
>> +
>> +	ret = iio_gts_get_scale_linear(gts, gain, time, &lin_scale);
>> +	if (ret)
>> +		return ret;
>> +
>> +	return iio_gts_delinearize(lin_scale, NANO, scale_int, scale_nano);
>> +}
>> +EXPORT_SYMBOL_GPL(iio_gts_get_scale);
> 
> It is good practice to add kernel-doc for all the exported functions,
> even if some of them will be fairly obvious.

Makes sense. I'll add docs to all exported ones.

> If you can make the units explicit in the parameter that's even better.

My very initial idea was that the driver should know the units and that 
these helpers would do no unit conversions. I am unsure what road to 
take here now. I kind of like fixing the units - but on the other hand, 
allowing driver authors to decide the units makes this more flexible (as 
units can be chosen so that times won't overflow).

OTOH, now that there is the iio_gts_avail_times() - helper, it would be 
good to have the returned times in correct units. I guess we have same 
integration-time unit specified for all types of sensors? If yes, then 
it would be cleanest to require units in this format, especially if it 
is not likely to cause problems with the overflows.

> I will note that negative times seem unlikely so maybe that should always
> be unsigned?  gain probably can be negative even if that's unusual.
> That may lead to problems though as lin_scale is in turn unsigned.

Yes. I plan to support only positive gains. At least for now.

> 
>> +
>> +/**
>> + * iio_gts_find_new_gain_sel_by_old_gain_time - compensate time change
> 
> compensate for time change

thanks :)

Oh, and by the way - I appreciate the review and suggestions even when I 
do not always agree with them. So, thanks again for all the effort!

Yours,
	-- Matti
Matti Vaittinen March 22, 2023, 9:10 a.m. UTC | #3
On 3/20/23 14:01, Matti Vaittinen wrote:
> On 3/19/23 20:08, Jonathan Cameron wrote:
>> On Fri, 17 Mar 2023 16:43:23 +0200
>> Matti Vaittinen <mazziesaccount@gmail.com> wrote:
>>
>> I think a bit more care is need with storage of time (unsigned) + decide
>> whether to allow for negative gains.
> 
> My approach was just pretty simple "int is big enough for the times" 
> (2000+ seconds when using usec as time units felt like more than enough 
> for light sensors) and "gains are always positive".
> 
> I have not tested the negative gains at all - but I agree this should've 
> been documented. Currently there is no gts-helper users who need 
> negative gain (or large times for that matter) - so I was not handling 
> them.
> 
> I'll try to check what it would mean code-wise if we converted times to 
> unsigned. Negative times make no sense but allowing negative error 
> values is a simple way to go.
> 
> As for the negative gains - I have no problem of someone adding a 
> support for those if needed, but I don't currently see much point in 
> investing time in that...
> 
>> Whilst they happen I'm not that bothered
>> if that subtlety becomes a device driver problem when calling this.  
>> I'm not
>> sure I've seen a sensor that does both positive and negative gains for 
>> a single
>> channel.
> 
> I agree. If driver needs negative gains, then the driver needs to deal 
> with it. I have no objections if driver authors want to improve these 
> helpers by adding support for negative gains, but if they don't, then 
> they have the exactly same problem they would have without these helpers :)

Back at this. I started reworking things to use unsigned times / gains 
but I am not really happy about how it starts to look like. Using the 
int values but reserving negative values to denote errors keeps things 
cleaner. Also, I don't think we need the extra bit for extending the 
range of supported values - It's hard for me to think we would really 
need gains or times exceeding the maximum signed int. I think negative 
gains are actually more likely so keeping int as type may help one who 
wants to add support for negative gains.

(Although, I assume the integration time multiplying logic with negative 
gains would not work in a same way as with positive gains - so 
supporting negative gains would probably require more than that, or work 
only as a dummy selector <=> gain converter without the time tables).

So, the v5 will likely still use int as type for times and gain but also 
have a check in initialization enforcing this. I will also document this 
restriction in the gain/time struct and init function documentation.

I don't think the v5 is final version, especially because it will be the 
first version looping in the Kunit people. So we can keep iterating this 
for v6 if you still feel using ints is unacceptable :)

Yours,
	-- Matti
Jonathan Cameron March 25, 2023, 6:29 p.m. UTC | #4
On Mon, 20 Mar 2023 14:01:55 +0200
Matti Vaittinen <mazziesaccount@gmail.com> wrote:

> On 3/19/23 20:08, Jonathan Cameron wrote:
> > On Fri, 17 Mar 2023 16:43:23 +0200
> > Matti Vaittinen <mazziesaccount@gmail.com> wrote:
> >   
> >> Some light sensors can adjust both the HW-gain and integration time.
> >> There are cases where adjusting the integration time has similar impact
> >> to the scale of the reported values as gain setting has.
> >>
> >> IIO users do typically expect to handle scale by a single writable 'scale'
> >> entry. Driver should then adjust the gain/time accordingly.
> >>
> >> It however is difficult for a driver to know whether it should change
> >> gain or integration time to meet the requested scale. Usually it is
> >> preferred to have longer integration time which usually improves
> >> accuracy, but there may be use-cases where long measurement times can be
> >> an issue. Thus it can be preferable to allow also changing the
> >> integration time - but mitigate the scale impact by also changing the gain
> >> underneath. Eg, if integration time change doubles the measured values,
> >> the driver can reduce the HW-gain to half.
> >>
> >> The theory of the computations of gain-time-scale is simple. However,
> >> some people (undersigned) got that implemented wrong for more than once.
> >>
> >> Add some gain-time-scale helpers in order to not dublicate errors in all
> >> drivers needing these computations.
> >>
> >> Signed-off-by: Matti Vaittinen <mazziesaccount@gmail.com>  
> > 
> > Whilst you use it in the tests currently I'm not convinced there is a good
> > reason to separate iio_init_iio_gts() from devm_iio_gts_build_avail_tables()
> > as I'd expect them to be called as a pair in all drivers that use this.  
> 
> I was wondering if I should only provide the:
> 
> [devm_]iio_init_iio_gts() and always unconditionally allocate and build 
> the tables inside the initialization routine.
> 
> I don't really care so much about how the tests are done. In my opinion 
> the testability needs should rarely be determining what the production 
> code looks like. In this case it is a waste of time / resources for 
> drivers which do not tell the available scales/times to user-space, or 
> do need some special routine for this. This is why I did make 
> build_avail_tables() optional. Still not sure what would be the best 
> approach though.

Given it should be 'easy to do' after you have this infrastructure, why would
a driver not provide the _available tables?

> 
> > Perhaps it's worth reworking the tests to do that even if it's not strictly
> > necessary for specific tests.
> > 
> > I think a bit more care is need with storage of time (unsigned) + decide
> > whether to allow for negative gains.  
> 
> My approach was just pretty simple "int is big enough for the times" 
> (2000+ seconds when using usec as time units felt like more than enough 
> for light sensors) and "gains are always positive".
> 
> I have not tested the negative gains at all - but I agree this should've 
> been documented. Currently there is no gts-helper users who need 
> negative gain (or large times for that matter) - so I was not handling them.
> 
> I'll try to check what it would mean code-wise if we converted times to 
> unsigned. Negative times make no sense but allowing negative error 
> values is a simple way to go.
> 
> As for the negative gains - I have no problem of someone adding a 
> support for those if needed, but I don't currently see much point in 
> investing time in that...

I'm fine with keeping them all signed, but you probably need some checks
to ensure the data provided isn't negative.

> 
> > Whilst they happen I'm not that bothered
> > if that subtlety becomes a device driver problem when calling this.  I'm not
> > sure I've seen a sensor that does both positive and negative gains for a single
> > channel.  
> 
> I agree. If driver needs negative gains, then the driver needs to deal 
> with it. I have no objections if driver authors want to improve these 
> helpers by adding support for negative gains, but if they don't, then 
> they have the exactly same problem they would have without these helpers :)
> 
> >> ---
> >> Currently it is only BU27034 using these in this series. I am however working
> >> with drivers for RGB sensors BU27008 and BU27010 which have similar
> >> [gain - integration time - scale] - relation. I hope sending those
> >> follows soon after the BU27034 is done.
> >>
> >> Changes:
> >> v3 => v4:
> >> - doc styling
> >> - use memset to zero the helper struct at init
> >> - drop unnecessary min calculation at iio_find_closest_gain_low()
> >> - use namespace to all exports
> >> - many minor stylings
> >> - make available outside iio/light (move code to drivers/iio and move the
> >>    header under include
> >> - rename to look like other files under drivers/iio (s/iio/industrialio)  
> > 
> > Ah. I've always regretted not using iio_ for the prefix on those so I'm fine
> > if you would prefer to stick to iio_  
> 
> I do like iio better. However, I think we should have common prefix for 
> these files. Having both iio- and industrialio- will be confusing for 
> newcomers. If I saw just one iio- prefixed file I would have assumed it 
> is for a specific use, not for common use as the other "IIO-core" files.
> 
> One option would be converting all these industrialio-*.c files to 
> iio_*.c - but I am not sure if it is worth the hassle.

It gets messy because then you have to fix up the module names. People get
annoyed if those change.


...

> >   
> >> +/**
> >> + * iio_gts_purge_avail_scale_table - free-up the available scale tables
> >> + * @gts:	Gain time scale descriptor
> >> + *
> >> + * Free the space reserved by iio_gts_build_avail_scale_table(). Please note
> >> + * that the helpers for getting available scales like the
> >> + * iio_gts_all_avail_scales() are not usable after this call. Thus, this should
> >> + * be only called after these helpers can no longer be called (Eg. after
> >> + * the iio-device has been deregistered).  
> > 
> > Whilst I'm not that keen on the comment in general, if you really really want to
> > have it we need to figure out one place to put it rather than lots of duplicates.  
> 
> I have seen way too many bugs with the unwinding errors. Usually with 
> the IRQs but also when user-space has access to driver stuff. I placed 
> this comment here hoping it would prevent at least one such bug as those 
> tend to be really nasty to debug. If we avoid one, it is well worth of 
> few lines of comment (IMO).

I'd argue this particular code doesn't have the subtleties that irqs and stuff
directly accessed from userspace has (where such comments would sometimes be
helpful!).  Meh I don't care that much.


> >> +
> >> +/**
> >> + * iio_gts_build_avail_scale_table - create tables of available scales
> >> + * @gts:	Gain time scale descriptor
> >> + *
> >> + * Build the tables which can represent the available scales based on the
> >> + * originally given gain and time tables. When both time and gain tables are
> >> + * given this results:
> >> + * 1. A set of tables representing available scales for each supported
> >> + *    integration time.
> >> + * 2. A single table listing all the unique scales that any combination of
> >> + *    supported gains and times can provide.
> >> + *
> >> + * NOTE: Space allocated for the tables must be freed using
> >> + * iio_gts_purge_avail_scale_table() when the tables are no longer needed.
> >> + *
> >> + * Return: 0 on success.
> >> + */
> >> +static int iio_gts_build_avail_scale_table(struct iio_gts *gts)
> >> +{
> >> +	int **per_time_gains, **per_time_scales, i, j, ret = -ENOMEM;
> >> +
> >> +	per_time_gains = kcalloc(gts->num_itime, sizeof(int *), GFP_KERNEL);  
> > 
> > As per other thread, I much prefer reviewing code with sizeof(*per_time_gains)
> > as it requires fewer brain cells.  
> 
> Hm. I think it depends on whether one wants to understand how many bytes 
> the sizeof() is actually referring. Well, again, I guess I have no 
> choice here.

Why would one care?  You care about the number of objects, for a kcalloc call
but the size is rarely useful to have immediately visible.


> >> +
> >> +/**
> >> + * iio_gts_build_avail_time_table - build table of available integration times
> >> + * @gts:	Gain time scale descriptor
> >> + *
> >> + * Build the table which can represent the available times to be returned
> >> + * to users using the read_avail-callback.
> >> + *
> >> + * NOTE: Space allocated for the tables must be freed using
> >> + * iio_gts_purge_avail_time_table() when the tables are no longer needed.
> >> + *
> >> + * Return: 0 on success.
> >> + */
> >> +static int iio_gts_build_avail_time_table(struct iio_gts *gts)
> >> +{
> >> +	int *times, i, j, idx = 0;
> >> +
> >> +	if (!gts->num_itime)
> >> +		return 0;
> >> +
> >> +	times = kcalloc(gts->num_itime, sizeof(int), GFP_KERNEL);
> >> +	if (!times)
> >> +		return -ENOMEM;
> >> +
> >> +	for (i = gts->num_itime - 1; i >= 0; i--) {
> >> +		int new = gts->itime_table[i].time_us;
> >> +  
> > 
> > This looks like a sort routine.  Don't we have something generic that will work?  
> 
> I think this is "combine and sort many tables into one while dropping 
> duplicates". I must admit I don't know what sort routines we have 
> in-kernel. If we have one which removes duplicates, then we could 
> probably copy all the tables into one array and run such sort on it.
> 
> Or then we can leave this as is and add a comment about telling is going 
> on here :)

Perfect.

> 
> >   
> >> +		if (times[idx] < new) {
> >> +			times[idx++] = new;
> >> +			continue;
> >> +		}
> >> +
> >> +		for (j = 0; j <= idx; j++) {
> >> +			if (times[j] > new) {
> >> +				memmove(&times[j + 1], &times[j],
> >> +					(idx - j) * sizeof(int));
> >> +				times[j] = new;
> >> +				idx++;
> >> +			}
> >> +		}
> >> +	}
> >> +	gts->avail_time_tables = times;
> >> +	/*
> >> +	 * This is just to survive a unlikely corner-case where times in the
> >> +	 * given time table were not unique. Else we could just trust the
> >> +	 * gts->num_itime.  
> > 
> > If integration times aren't unique I'd count it as driver bug and error out
> > /scream.  Papering over things like this just make code harder to review
> > to deal with what is probably a driver bug.  
> 
> I am not entirely sure. I don't know the sensor ICs in details, but I've 
> seen plenty of other ICs where we may have different register values 
> that mean same physical measure. One such example is almost all ROHM 
> PMICs, where we often see voltage selection registers like:

> 
> register val 0 to <foo>:
>   - 1.0V + (val * 10 mV)
> register val <A> to <MAX>:
>   - 3.3 V
> 
> If we have similar registers for the time, then it may be good idea to 
> accept selectors A...MAX to have the same time. This allows the 
> gts-helpers to be used to convert the register values to times also for 
> such devices. If we don't allow same times to be in the tables, then 
> there may be unknown but valid register values read from the IC.

That I agree with.  Should the driver support more that one such option.
No it shouldn't.   Snarky comments about repeated values are fine ;)
I'd argue the driver has a bug if it hasn't hammered the device into a
known state (typically via a documented reset value).   We always have
fun corners where devices will accept reserved values and driver very
rarely handle reading them back right - because we arrange that they are
definitely not set by resetting the device.



> >> +
> >> +int iio_gts_find_gain_by_sel(struct iio_gts *gts, int sel)
> >> +{
> >> +	int i;
> >> +
> >> +	for (i = 0; i < gts->num_hwgain; i++)
> >> +		if (gts->hwgain_table[i].sel == sel)
> >> +			return gts->hwgain_table[i].gain;
> >> +
> >> +	return -EINVAL;
> >> +}
> >> +EXPORT_SYMBOL_GPL(iio_gts_find_gain_by_sel);
> >> +
> >> +int iio_gts_get_min_gain(struct iio_gts *gts)  
> > 
> > Could just use min = INT_MAX;
> > (indirectly from linux/limits.h, it's actually in vdso/limits.h
> > but should not include that directly I think)
> > then I don't hink you need the special casing for the
> > first entry.  
> 
> Hmm. I guess you think we don't need to handle case num_hwgain == 0 here 
> as it should be checked in the initialization routine. Not sure what to 
> think about it.

Yup. Using this code without having multiple hardware gains would be odd.
Even if you did I still feel that num_hwgain == 1 would be correct setting.


....

> > 
> > Currently can be negative.  Even when you stop that being the case
> > by makign time unsigned, you need to be careful with ranges here.
> > You may be better off separating the error handling from the values
> > to avoid any issues even though that makes it a little harder to use.  
> 
> Yes. As I wrote above, I thought that the driver author needs to ensure 
> the valid times would always be positive. I was guessing usec is going 
> to be used as unit for most cases and 2000+ seconds is probably 
> sufficient. But yes, I guess I should have documented this.

Why not just check this at init?  Otherwise this will be a tricky bug
to track down. Documentation is good, but code that tells you no is even
better.

> 
> Hmm. Do you think we should support times larger than can be represented 
> by signed int? I'd rather not support that if it is not needed as it 
> will make this quite a bit more complex.

Probably not - if needed by someone else they can add it.

> 
> >> +}
> >> +EXPORT_SYMBOL_GPL(iio_gts_find_int_time_by_sel);
> >> +
> >> +int iio_gts_find_sel_by_int_time(struct iio_gts *gts, int time)
> >> +{
> >> +	const struct iio_itime_sel_mul *itime;
> >> +
> >> +	itime = iio_gts_find_itime_by_time(gts, time);
> >> +	if (!itime)
> >> +		return -EINVAL;
> >> +
> >> +	return itime->sel;  
> > 
> > itime->sel can be negative.  I wonder if you should just make that
> > u16 so that you can always return it as a positive integer but
> > having it as unsigned in the structure.  
> 
> Here I did the same assumption of sel sizes. I don't expect we to see 32 
> bit selectors. To tell the truth, I just followed the linear_ranges 
> logic which is heavily used in the regulator drivers.
> 
> > Otherwise you need to add some docs on those limits and probably
> > sanity check them during the _init()  
> 
> I am almost certain the sanity check is going to be an overkill, but it 
> sure is doable. The onlu corner case I can think of is if register 
> really accepts the time itself as a "selector" - but even then having 
> such large values they would use the whole 32bits would be unlikely.

I'd be fine with clear documentation of the limits, but it it's trivial
to check they are being obeyed, that makes for an easier to use bit
of code.

> 
> >> +}
> >> +EXPORT_SYMBOL_GPL(iio_gts_find_sel_by_int_time);
> >> +
> >> +static int iio_gts_get_total_gain(struct iio_gts *gts, int gain, int time)
> >> +{
> >> +	const struct iio_itime_sel_mul *itime;
> >> +
> >> +	if (!iio_gts_valid_gain(gts, gain))
> >> +		return -EINVAL;
> >> +
> >> +	if (!gts->num_itime)
> >> +		return gain;
> >> +
> >> +	itime = iio_gts_find_itime_by_time(gts, time);
> >> +	if (!itime)
> >> +		return -EINVAL;
> >> +
> >> +	return gain * itime->mul;  
> > 
> > Check for overflow perhaps?  
> 
> I think that if we want to add the overflow checks, we should do that 
> already in init. That way we can check all the combinations before they 
> are used - so that the driver authors get the errors even if they did 
> not test all the times/gains their HW is supporting. I am not really 
> convinced it's worth though.

Gains can get very very large, so in this one case I'd check it. Fine
to do it at init though.  Note the large gains sometimes come about because
SI units sometimes mean the obvious base unit is very small or very big.



> 
> > If you can make the units explicit in the parameter that's even better.  
> 
> My very initial idea was that the driver should know the units and that 
> these helpers would do no unit conversions. I am unsure what road to 
> take here now. I kind of like fixing the units - but on the other hand, 
> allowing driver authors to decide the units makes this more flexible (as 
> units can be chosen so that times won't overflow).
> 
> OTOH, now that there is the iio_gts_avail_times() - helper, it would be 
> good to have the returned times in correct units. I guess we have same 
> integration-time unit specified for all types of sensors? If yes, then 
> it would be cleanest to require units in this format, especially if it 
> is not likely to cause problems with the overflows.
> 
> > I will note that negative times seem unlikely so maybe that should always
> > be unsigned?  gain probably can be negative even if that's unusual.
> > That may lead to problems though as lin_scale is in turn unsigned.  
> 
> Yes. I plan to support only positive gains. At least for now.
> 
> >   
> >> +
> >> +/**
> >> + * iio_gts_find_new_gain_sel_by_old_gain_time - compensate time change  
> > 
> > compensate for time change  
> 
> thanks :)
> 
> Oh, and by the way - I appreciate the review and suggestions even when I 
> do not always agree with them. So, thanks again for all the effort!

No problem

J
> 
> Yours,
> 	-- Matti
>
Vaittinen, Matti March 27, 2023, 6:47 a.m. UTC | #5
On 3/25/23 20:29, Jonathan Cameron wrote:
> On Mon, 20 Mar 2023 14:01:55 +0200
> Matti Vaittinen <mazziesaccount@gmail.com> wrote:
> 
>> On 3/19/23 20:08, Jonathan Cameron wrote:
>>> On Fri, 17 Mar 2023 16:43:23 +0200
>>> Matti Vaittinen <mazziesaccount@gmail.com> wrote:
>>>    
>>>> Some light sensors can adjust both the HW-gain and integration time.
>>>> There are cases where adjusting the integration time has similar impact
>>>> to the scale of the reported values as gain setting has.
>>>>
>>>> IIO users do typically expect to handle scale by a single writable 'scale'
>>>> entry. Driver should then adjust the gain/time accordingly.
>>>>
>>>> It however is difficult for a driver to know whether it should change
>>>> gain or integration time to meet the requested scale. Usually it is
>>>> preferred to have longer integration time which usually improves
>>>> accuracy, but there may be use-cases where long measurement times can be
>>>> an issue. Thus it can be preferable to allow also changing the
>>>> integration time - but mitigate the scale impact by also changing the gain
>>>> underneath. Eg, if integration time change doubles the measured values,
>>>> the driver can reduce the HW-gain to half.
>>>>
>>>> The theory of the computations of gain-time-scale is simple. However,
>>>> some people (undersigned) got that implemented wrong for more than once.
>>>>
>>>> Add some gain-time-scale helpers in order to not dublicate errors in all
>>>> drivers needing these computations.
>>>>
>>>> Signed-off-by: Matti Vaittinen <mazziesaccount@gmail.com>
>>>
>>> Whilst you use it in the tests currently I'm not convinced there is a good
>>> reason to separate iio_init_iio_gts() from devm_iio_gts_build_avail_tables()
>>> as I'd expect them to be called as a pair in all drivers that use this.
>>
>> I was wondering if I should only provide the:
>>
>> [devm_]iio_init_iio_gts() and always unconditionally allocate and build
>> the tables inside the initialization routine.
>>
>> I don't really care so much about how the tests are done. In my opinion
>> the testability needs should rarely be determining what the production
>> code looks like. In this case it is a waste of time / resources for
>> drivers which do not tell the available scales/times to user-space, or
>> do need some special routine for this. This is why I did make
>> build_avail_tables() optional. Still not sure what would be the best
>> approach though.
> 
> Given it should be 'easy to do' after you have this infrastructure, why would
> a driver not provide the _available tables?

Pretty much the only thing I can think of is when a HW has some "funny" 
limitations regarding available values. Eg, when the device supports 
only certain values depending on a seemingly unrelated config X.

In such case the driver might not want to always advertise all the 
available values - and in such case the driver could not use the tables.

And as this is probably really unlikely scenario - In v5 I did just put 
the table building unconditionally in gts-init as you suggested.

>>> Perhaps it's worth reworking the tests to do that even if it's not strictly
>>> necessary for specific tests.
>>>
>>> I think a bit more care is need with storage of time (unsigned) + decide
>>> whether to allow for negative gains.
>>
>> My approach was just pretty simple "int is big enough for the times"
>> (2000+ seconds when using usec as time units felt like more than enough
>> for light sensors) and "gains are always positive".
>>
>> I have not tested the negative gains at all - but I agree this should've
>> been documented. Currently there is no gts-helper users who need
>> negative gain (or large times for that matter) - so I was not handling them.
>>
>> I'll try to check what it would mean code-wise if we converted times to
>> unsigned. Negative times make no sense but allowing negative error
>> values is a simple way to go.
>>
>> As for the negative gains - I have no problem of someone adding a
>> support for those if needed, but I don't currently see much point in
>> investing time in that...
> 
> I'm fine with keeping them all signed, but you probably need some checks
> to ensure the data provided isn't negative.

Yep. I agree. Added the checks to init in v5 :)

>>> Whilst they happen I'm not that bothered
>>> if that subtlety becomes a device driver problem when calling this.  I'm not
>>> sure I've seen a sensor that does both positive and negative gains for a single
>>> channel.
>>
>> I agree. If driver needs negative gains, then the driver needs to deal
>> with it. I have no objections if driver authors want to improve these
>> helpers by adding support for negative gains, but if they don't, then
>> they have the exactly same problem they would have without these helpers :)
>>
>>>> ---
>>>> Currently it is only BU27034 using these in this series. I am however working
>>>> with drivers for RGB sensors BU27008 and BU27010 which have similar
>>>> [gain - integration time - scale] - relation. I hope sending those
>>>> follows soon after the BU27034 is done.
>>>>
>>>> Changes:
>>>> v3 => v4:
>>>> - doc styling
>>>> - use memset to zero the helper struct at init
>>>> - drop unnecessary min calculation at iio_find_closest_gain_low()
>>>> - use namespace to all exports
>>>> - many minor stylings
>>>> - make available outside iio/light (move code to drivers/iio and move the
>>>>     header under include
>>>> - rename to look like other files under drivers/iio (s/iio/industrialio)
>>>
>>> Ah. I've always regretted not using iio_ for the prefix on those so I'm fine
>>> if you would prefer to stick to iio_
>>
>> I do like iio better. However, I think we should have common prefix for
>> these files. Having both iio- and industrialio- will be confusing for
>> newcomers. If I saw just one iio- prefixed file I would have assumed it
>> is for a specific use, not for common use as the other "IIO-core" files.
>>
>> One option would be converting all these industrialio-*.c files to
>> iio_*.c - but I am not sure if it is worth the hassle.
> 
> It gets messy because then you have to fix up the module names. People get
> annoyed if those change.

Ah. Very valid point. I should've seen that.

So, I'll keep the long filename just for the sake of the consistency - 
unless you object.

> ...
> 
>>>    
>>>> +/**
>>>> + * iio_gts_purge_avail_scale_table - free-up the available scale tables
>>>> + * @gts:	Gain time scale descriptor
>>>> + *
>>>> + * Free the space reserved by iio_gts_build_avail_scale_table(). Please note
>>>> + * that the helpers for getting available scales like the
>>>> + * iio_gts_all_avail_scales() are not usable after this call. Thus, this should
>>>> + * be only called after these helpers can no longer be called (Eg. after
>>>> + * the iio-device has been deregistered).
>>>
>>> Whilst I'm not that keen on the comment in general, if you really really want to
>>> have it we need to figure out one place to put it rather than lots of duplicates.
>>
>> I have seen way too many bugs with the unwinding errors. Usually with
>> the IRQs but also when user-space has access to driver stuff. I placed
>> this comment here hoping it would prevent at least one such bug as those
>> tend to be really nasty to debug. If we avoid one, it is well worth of
>> few lines of comment (IMO).
> 
> I'd argue this particular code doesn't have the subtleties that irqs and stuff
> directly accessed from userspace has (where such comments would sometimes be
> helpful!).  Meh I don't care that much.

Hm. I didn't check how IIO handles the user-space request to available 
scales/times - but I thought that would go directly to the tables for as 
long as the IIO-device stays registered.

In any case, moving the table creation in gts-init made these functions 
internal - so I think this piece of doc should go now.

> 
> 
>>>> +
>>>> +/**
>>>> + * iio_gts_build_avail_scale_table - create tables of available scales
>>>> + * @gts:	Gain time scale descriptor
>>>> + *
>>>> + * Build the tables which can represent the available scales based on the
>>>> + * originally given gain and time tables. When both time and gain tables are
>>>> + * given this results:
>>>> + * 1. A set of tables representing available scales for each supported
>>>> + *    integration time.
>>>> + * 2. A single table listing all the unique scales that any combination of
>>>> + *    supported gains and times can provide.
>>>> + *
>>>> + * NOTE: Space allocated for the tables must be freed using
>>>> + * iio_gts_purge_avail_scale_table() when the tables are no longer needed.
>>>> + *
>>>> + * Return: 0 on success.
>>>> + */
>>>> +static int iio_gts_build_avail_scale_table(struct iio_gts *gts)
>>>> +{
>>>> +	int **per_time_gains, **per_time_scales, i, j, ret = -ENOMEM;
>>>> +
>>>> +	per_time_gains = kcalloc(gts->num_itime, sizeof(int *), GFP_KERNEL);
>>>
>>> As per other thread, I much prefer reviewing code with sizeof(*per_time_gains)
>>> as it requires fewer brain cells.
>>
>> Hm. I think it depends on whether one wants to understand how many bytes
>> the sizeof() is actually referring. Well, again, I guess I have no
>> choice here.
> 
> Why would one care?  You care about the number of objects, for a kcalloc call
> but the size is rarely useful to have immediately visible.

I think this is just how my mind works. I do like to see not only how 
many "items" there is, but also the size of the "items". I guess it 
rarely plays a big role, but sometimes it's nice knowing for example how 
much memory an array takes (especially in cases where the array is from 
the stack, but sometimes also for heap allocations). Furthermore, 
occasionally seeing the alignment is nice too.

Yes, yes - this is not relevant here - but this is probably why I prefer 
seeing the sizeof(type *) instead of the sizeof(variable) - when the 
variable is a pointer.

I think I changed this to sizeof(*per_time_gains) for v5.

>>>> +
>>>> +/**
>>>> + * iio_gts_build_avail_time_table - build table of available integration times
>>>> + * @gts:	Gain time scale descriptor
>>>> + *
>>>> + * Build the table which can represent the available times to be returned
>>>> + * to users using the read_avail-callback.
>>>> + *
>>>> + * NOTE: Space allocated for the tables must be freed using
>>>> + * iio_gts_purge_avail_time_table() when the tables are no longer needed.
>>>> + *
>>>> + * Return: 0 on success.
>>>> + */
>>>> +static int iio_gts_build_avail_time_table(struct iio_gts *gts)
>>>> +{
>>>> +	int *times, i, j, idx = 0;
>>>> +
>>>> +	if (!gts->num_itime)
>>>> +		return 0;
>>>> +
>>>> +	times = kcalloc(gts->num_itime, sizeof(int), GFP_KERNEL);
>>>> +	if (!times)
>>>> +		return -ENOMEM;
>>>> +
>>>> +	for (i = gts->num_itime - 1; i >= 0; i--) {
>>>> +		int new = gts->itime_table[i].time_us;
>>>> +
>>>
>>> This looks like a sort routine.  Don't we have something generic that will work?
>>
>> I think this is "combine and sort many tables into one while dropping
>> duplicates". I must admit I don't know what sort routines we have
>> in-kernel. If we have one which removes duplicates, then we could
>> probably copy all the tables into one array and run such sort on it.
>>
>> Or then we can leave this as is and add a comment about telling is going
>> on here :)
> 
> Perfect.

Now I wonder if I remembered to actually add the comment...

> 
>>
>>>    
>>>> +		if (times[idx] < new) {
>>>> +			times[idx++] = new;
>>>> +			continue;
>>>> +		}
>>>> +
>>>> +		for (j = 0; j <= idx; j++) {
>>>> +			if (times[j] > new) {
>>>> +				memmove(&times[j + 1], &times[j],
>>>> +					(idx - j) * sizeof(int));
>>>> +				times[j] = new;
>>>> +				idx++;
>>>> +			}
>>>> +		}
>>>> +	}
>>>> +	gts->avail_time_tables = times;
>>>> +	/*
>>>> +	 * This is just to survive a unlikely corner-case where times in the
>>>> +	 * given time table were not unique. Else we could just trust the
>>>> +	 * gts->num_itime.
>>>
>>> If integration times aren't unique I'd count it as driver bug and error out
>>> /scream.  Papering over things like this just make code harder to review
>>> to deal with what is probably a driver bug.
>>
>> I am not entirely sure. I don't know the sensor ICs in details, but I've
>> seen plenty of other ICs where we may have different register values
>> that mean same physical measure. One such example is almost all ROHM
>> PMICs, where we often see voltage selection registers like:
> 
>>
>> register val 0 to <foo>:
>>    - 1.0V + (val * 10 mV)
>> register val <A> to <MAX>:
>>    - 3.3 V
>>
>> If we have similar registers for the time, then it may be good idea to
>> accept selectors A...MAX to have the same time. This allows the
>> gts-helpers to be used to convert the register values to times also for
>> such devices. If we don't allow same times to be in the tables, then
>> there may be unknown but valid register values read from the IC.
> 
> That I agree with.  Should the driver support more that one such option.
> No it shouldn't.   Snarky comments about repeated values are fine ;)
> I'd argue the driver has a bug if it hasn't hammered the device into a
> known state (typically via a documented reset value).   We always have
> fun corners where devices will accept reserved values and driver very
> rarely handle reading them back right - because we arrange that they are
> definitely not set by resetting the device.

Hm. I guess the fundamental difference compared to PMICs here is the 
ability to reset the device at probe. PMICs can't really be reset as 
boot may have already changed the values.

I am still not sure supporting all register values hurts. Again, being 
worked a while with the ROHM PMICs I can't help of thinking situation 
where 'default values' for a device are load from OTP at device start. 
(This is usually how 'power-on' voltages are handled in PMICs). I think 
it is quite standard thing to change the default voltages for variants 
targeted to different systems. And when this is done, no one guarantees 
the same register value is used for default that is set in driver to 
represent certain voltage. Thus it is (in my opinion) better to support 
all known register values. Here a big thing is that regulators do often 
use 'linear-ranges' - which means supporting all the register values 
does not really consume much of memory - unlike with the table based 
implementation we have with the times here.

Furthermore, there are user-space tools to write register values past 
the driver. And yes, If this is done then th euser should be prepared 
for the driver to fail. Still, it does not mean we shouldn't handle this 
gracefully (best we can) in driver(s) - when it does not cost much.

>>>> +
>>>> +int iio_gts_find_gain_by_sel(struct iio_gts *gts, int sel)
>>>> +{
>>>> +	int i;
>>>> +
>>>> +	for (i = 0; i < gts->num_hwgain; i++)
>>>> +		if (gts->hwgain_table[i].sel == sel)
>>>> +			return gts->hwgain_table[i].gain;
>>>> +
>>>> +	return -EINVAL;
>>>> +}
>>>> +EXPORT_SYMBOL_GPL(iio_gts_find_gain_by_sel);
>>>> +
>>>> +int iio_gts_get_min_gain(struct iio_gts *gts)
>>>
>>> Could just use min = INT_MAX;
>>> (indirectly from linux/limits.h, it's actually in vdso/limits.h
>>> but should not include that directly I think)
>>> then I don't hink you need the special casing for the
>>> first entry.
>>
>> Hmm. I guess you think we don't need to handle case num_hwgain == 0 here
>> as it should be checked in the initialization routine. Not sure what to
>> think about it.
> 
> Yup. Using this code without having multiple hardware gains would be odd.
> Even if you did I still feel that num_hwgain == 1 would be correct setting.

The only case I can think of would be not providing hardware-gains at 
all and only using the times to support the 'reg <=> time' conversions. 
But yes, in that case ending up in this routine would probably be odd - 
and I think using these helpers just for the 'reg <=> time' conversion 
might be an overkill.

> ....
> 
>>>
>>> Currently can be negative.  Even when you stop that being the case
>>> by makign time unsigned, you need to be careful with ranges here.
>>> You may be better off separating the error handling from the values
>>> to avoid any issues even though that makes it a little harder to use.
>>
>> Yes. As I wrote above, I thought that the driver author needs to ensure
>> the valid times would always be positive. I was guessing usec is going
>> to be used as unit for most cases and 2000+ seconds is probably
>> sufficient. But yes, I guess I should have documented this.
> 
> Why not just check this at init?  Otherwise this will be a tricky bug
> to track down. Documentation is good, but code that tells you no is even
> better.
> 

I agree. And I added these checks in init at v5 :)

>>>> +}
>>>> +EXPORT_SYMBOL_GPL(iio_gts_find_int_time_by_sel);
>>>> +
>>>> +int iio_gts_find_sel_by_int_time(struct iio_gts *gts, int time)
>>>> +{
>>>> +	const struct iio_itime_sel_mul *itime;
>>>> +
>>>> +	itime = iio_gts_find_itime_by_time(gts, time);
>>>> +	if (!itime)
>>>> +		return -EINVAL;
>>>> +
>>>> +	return itime->sel;
>>>
>>> itime->sel can be negative.  I wonder if you should just make that
>>> u16 so that you can always return it as a positive integer but
>>> having it as unsigned in the structure.
>>
>> Here I did the same assumption of sel sizes. I don't expect we to see 32
>> bit selectors. To tell the truth, I just followed the linear_ranges
>> logic which is heavily used in the regulator drivers.
>>
>>> Otherwise you need to add some docs on those limits and probably
>>> sanity check them during the _init()
>>
>> I am almost certain the sanity check is going to be an overkill, but it
>> sure is doable. The onlu corner case I can think of is if register
>> really accepts the time itself as a "selector" - but even then having
>> such large values they would use the whole 32bits would be unlikely.
> 
> I'd be fine with clear documentation of the limits, but it it's trivial
> to check they are being obeyed, that makes for an easier to use bit
> of code.

True.

> 
>>
>>>> +}
>>>> +EXPORT_SYMBOL_GPL(iio_gts_find_sel_by_int_time);
>>>> +
>>>> +static int iio_gts_get_total_gain(struct iio_gts *gts, int gain, int time)
>>>> +{
>>>> +	const struct iio_itime_sel_mul *itime;
>>>> +
>>>> +	if (!iio_gts_valid_gain(gts, gain))
>>>> +		return -EINVAL;
>>>> +
>>>> +	if (!gts->num_itime)
>>>> +		return gain;
>>>> +
>>>> +	itime = iio_gts_find_itime_by_time(gts, time);
>>>> +	if (!itime)
>>>> +		return -EINVAL;
>>>> +
>>>> +	return gain * itime->mul;
>>>
>>> Check for overflow perhaps?
>>
>> I think that if we want to add the overflow checks, we should do that
>> already in init. That way we can check all the combinations before they
>> are used - so that the driver authors get the errors even if they did
>> not test all the times/gains their HW is supporting. I am not really
>> convinced it's worth though.
> 
> Gains can get very very large, so in this one case I'd check it. Fine
> to do it at init though.  Note the large gains sometimes come about because
> SI units sometimes mean the obvious base unit is very small or very big.

I think I added the check to init in v5 :)

Thanks again!

Yours,
	--Matti
diff mbox series

Patch

diff --git a/drivers/iio/Kconfig b/drivers/iio/Kconfig
index b190846c3dc2..52eb46ef84c1 100644
--- a/drivers/iio/Kconfig
+++ b/drivers/iio/Kconfig
@@ -30,6 +30,9 @@  config IIO_CONFIGFS
 	  (e.g. software triggers). For more info see
 	  Documentation/iio/iio_configfs.rst.
 
+config IIO_GTS_HELPER
+	tristate
+
 config IIO_TRIGGER
 	bool "Enable triggered sampling support"
 	help
diff --git a/drivers/iio/Makefile b/drivers/iio/Makefile
index 3be08cdadd7e..9622347a1c1b 100644
--- a/drivers/iio/Makefile
+++ b/drivers/iio/Makefile
@@ -9,6 +9,7 @@  industrialio-$(CONFIG_IIO_BUFFER) += industrialio-buffer.o
 industrialio-$(CONFIG_IIO_TRIGGER) += industrialio-trigger.o
 
 obj-$(CONFIG_IIO_CONFIGFS) += industrialio-configfs.o
+obj-$(CONFIG_IIO_GTS_HELPER) += industrialio-gts-helper.o
 obj-$(CONFIG_IIO_SW_DEVICE) += industrialio-sw-device.o
 obj-$(CONFIG_IIO_SW_TRIGGER) += industrialio-sw-trigger.o
 obj-$(CONFIG_IIO_TRIGGERED_EVENT) += industrialio-triggered-event.o
diff --git a/drivers/iio/industrialio-gts-helper.c b/drivers/iio/industrialio-gts-helper.c
new file mode 100644
index 000000000000..9494ea7cdbcf
--- /dev/null
+++ b/drivers/iio/industrialio-gts-helper.c
@@ -0,0 +1,990 @@ 
+// SPDX-License-Identifier: GPL-2.0-only
+/* gain-time-scale conversion helpers for IIO light sensors
+ *
+ * Copyright (c) 2023 Matti Vaittinen <mazziesaccount@gmail.com>
+ */
+
+#include <linux/device.h>
+#include <linux/errno.h>
+#include <linux/export.h>
+#include <linux/minmax.h>
+#include <linux/module.h>
+#include <linux/slab.h>
+#include <linux/sort.h>
+#include <linux/types.h>
+#include <linux/units.h>
+
+#include <linux/iio/iio-gts-helper.h>
+#include <linux/iio/types.h>
+
+#define DEFAULT_SYMBOL_NAMESPACE IIO_GTS_HELPER
+
+/**
+ * iio_gts_get_gain - Convert scale to total gain
+ *
+ * Internal helper for converting scale to total gain.
+ *
+ * @max:	Maximum linearized scale. As an example, when scale is created
+ *		in magnitude of NANOs and max scale is 64.1 - The linearized
+ *		scale is 64 100 000 000.
+ * @scale:	Linearized scale to compte the gain for.
+ *
+ * Return:	(floored) gain corresponding to the scale. -EINVAL if scale
+ *		is invalid.
+ */
+static int iio_gts_get_gain(const u64 max, const u64 scale)
+{
+	u64 full = max;
+	int tmp = 1;
+
+	if (scale > full || !scale)
+		return -EINVAL;
+
+	if (U64_MAX - full < scale) {
+		/* Risk of overflow */
+		if (full - scale < scale)
+			return 1;
+
+		full -= scale;
+		tmp++;
+	}
+
+	while (full > scale * (u64)tmp)
+		tmp++;
+
+	return tmp;
+}
+
+/**
+ * gain_get_scale_fraction - get the gain or time based on scale and known one
+ *
+ * @max:	Maximum linearized scale. As an example, when scale is created
+ *		in magnitude of NANOs and max scale is 64.1 - The linearized
+ *		scale is 64 100 000 000.
+ * @scale:	Linearized scale to compute the gain/time for.
+ * @known:	Either integration time or gain depending on which one is known
+ * @unknown:	Pointer to variable where the computed gain/time is stored
+ *
+ * Internal helper for computing unknown fraction of total gain.
+ * Compute either gain or time based on scale and either the gain or time
+ * depending on which one is known.
+ *
+ * Return:	0 on success.
+ */
+static int gain_get_scale_fraction(const u64 max, u64 scale, int known,
+				   int *unknown)
+{
+	int tot_gain;
+
+	tot_gain = iio_gts_get_gain(max, scale);
+	if (tot_gain < 0)
+		return tot_gain;
+
+	*unknown = tot_gain / known;
+
+	/* We require total gain to be exact multiple of known * unknown */
+	if (!*unknown || *unknown * known != tot_gain)
+		return -EINVAL;
+
+	return 0;
+}
+
+static const struct iio_itime_sel_mul *
+iio_gts_find_itime_by_time(struct iio_gts *gts, int time)
+{
+	int i;
+
+	if (!gts->num_itime)
+		return NULL;
+
+	for (i = 0; i < gts->num_itime; i++)
+		if (gts->itime_table[i].time_us == time)
+			return &gts->itime_table[i];
+
+	return NULL;
+}
+
+static const struct iio_itime_sel_mul *
+iio_gts_find_itime_by_sel(struct iio_gts *gts, int sel)
+{
+	int i;
+
+	for (i = 0; i < gts->num_itime; i++)
+		if (gts->itime_table[i].sel == sel)
+			return &gts->itime_table[i];
+
+	return NULL;
+}
+
+static int iio_gts_delinearize(u64 lin_scale, unsigned long scaler,
+			       int *scale_whole, int *scale_nano)
+{
+	int frac;
+
+	if (scaler > NANO)
+		return -EOVERFLOW;
+
+	if (!scaler)
+		return -EINVAL;
+
+	frac = do_div(lin_scale, scaler);
+
+	*scale_whole = lin_scale;
+	*scale_nano = frac * (NANO / scaler);
+
+	return 0;
+}
+
+static int iio_gts_linearize(int scale_whole, int scale_nano,
+			     unsigned long scaler, u64 *lin_scale)
+{
+	/*
+	 * Expect scale to be (mostly) NANO or MICRO. Divide divider instead of
+	 * multiplication followed by division to avoid overflow.
+	 */
+	if (scaler > NANO || !scaler)
+		return -EINVAL;
+
+	*lin_scale = (u64)scale_whole * (u64)scaler +
+		     (u64)(scale_nano / (NANO / scaler));
+
+	return 0;
+}
+
+/**
+ * iio_gts_total_gain_to_scale - convert gain to scale
+ * @gts:	Gain time scale descriptor
+ * @total_gain:	the gain to be converted
+ * @scale_int:	Pointer to integral part of the scale (typically val1)
+ * @scale_nano:	Pointer to fractional part of the scale (nano or ppb)
+ *
+ * Convert the total gain value to scale. NOTE: This does not separate gain
+ * generated by hwgain or integration time. It is up to caller to decide what
+ * part of the total gain is due to integration time and what due to hw-gain.
+ *
+ * Return: 0 on success. Negative errno on failure.
+ */
+int iio_gts_total_gain_to_scale(struct iio_gts *gts, int total_gain,
+				int *scale_int, int *scale_nano)
+{
+	u64 tmp;
+
+	tmp = gts->max_scale;
+
+	do_div(tmp, total_gain);
+
+	return iio_gts_delinearize(tmp, NANO, scale_int, scale_nano);
+}
+EXPORT_SYMBOL_GPL(iio_gts_total_gain_to_scale);
+
+/**
+ * iio_init_iio_gts - Initialize the gain-time-scale helper
+ * @max_scale_int:	integer part of the maximum scale value
+ * @max_scale_nano:	fraction part of the maximum scale value
+ * @gain_tbl:		table describing supported gains
+ * @num_gain:		number of gains in the gaintable
+ * @tim_tbl:		table describing supported integration times. Provide
+ *			the integration time table sorted so that the preferred
+ *			integration time is in the first array index. The search
+ *			functions like the
+ *			iio_gts_find_time_and_gain_sel_for_scale() start search
+ *			from first provided time.
+ * @num_times:		number of times in the time table
+ * @gts:		pointer to the helper struct
+ *
+ * Initialize the gain-time-scale helper for use.
+ *
+ * Return: 0 on success.
+ */
+int iio_init_iio_gts(int max_scale_int, int max_scale_nano,
+		     const struct iio_gain_sel_pair *gain_tbl, int num_gain,
+		     const struct iio_itime_sel_mul *tim_tbl, int num_times,
+		     struct iio_gts *gts)
+{
+	int ret;
+
+	memset(gts, 0, sizeof(*gts));
+
+	ret = iio_gts_linearize(max_scale_int, max_scale_nano, NANO,
+				   &gts->max_scale);
+	if (ret)
+		return ret;
+
+	gts->hwgain_table = gain_tbl;
+	gts->num_hwgain = num_gain;
+	gts->itime_table = tim_tbl;
+	gts->num_itime = num_times;
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(iio_init_iio_gts);
+
+/**
+ * iio_gts_purge_avail_scale_table - free-up the available scale tables
+ * @gts:	Gain time scale descriptor
+ *
+ * Free the space reserved by iio_gts_build_avail_scale_table(). Please note
+ * that the helpers for getting available scales like the
+ * iio_gts_all_avail_scales() are not usable after this call. Thus, this should
+ * be only called after these helpers can no longer be called (Eg. after
+ * the iio-device has been deregistered).
+ */
+static void iio_gts_purge_avail_scale_table(struct iio_gts *gts)
+{
+	int i;
+
+	if (gts->per_time_avail_scale_tables) {
+		for (i = 0; i < gts->num_itime; i++)
+			kfree(gts->per_time_avail_scale_tables[i]);
+
+		kfree(gts->per_time_avail_scale_tables);
+		gts->per_time_avail_scale_tables = NULL;
+	}
+
+	kfree(gts->avail_all_scales_table);
+	gts->avail_all_scales_table = NULL;
+
+	gts->num_avail_all_scales = 0;
+}
+
+static int iio_gts_gain_cmp(const void *a, const void *b)
+{
+	return *(int *)a - *(int *)b;
+}
+
+static int gain_to_scaletables(struct iio_gts *gts, int **gains, int **scales)
+{
+	int ret, i, j, new_idx, time_idx;
+	int *all_gains;
+	size_t gain_bytes;
+
+	for (i = 0; i < gts->num_itime; i++) {
+		/*
+		 * Sort the tables for nice output and for easier finding of
+		 * unique values.
+		 */
+		sort(gains[i], gts->num_hwgain, sizeof(int), iio_gts_gain_cmp,
+		     NULL);
+
+		/* Convert gains to scales */
+		for (j = 0; j < gts->num_hwgain; j++) {
+			ret = iio_gts_total_gain_to_scale(gts, gains[i][j],
+							  &scales[i][2 * j],
+							  &scales[i][2 * j + 1]);
+			if (ret)
+				return ret;
+		}
+	}
+
+	gain_bytes = array_size(gts->num_hwgain, sizeof(int));
+	all_gains = kcalloc(gts->num_itime, gain_bytes, GFP_KERNEL);
+	if (!all_gains)
+		return -ENOMEM;
+
+	/*
+	 * We assume all the gains for same integration time were unique.
+	 * It is likely the first time table had greatest time multiplier as
+	 * the times are in the order of preference and greater times are
+	 * usually preferred. Hence we start from the last table which is likely
+	 * to have the smallest total gains.
+	 */
+	time_idx = gts->num_itime - 1;
+	memcpy(all_gains, gains[time_idx], gain_bytes);
+	new_idx = gts->num_hwgain;
+
+	while (time_idx--) {
+		for (j = 0; j < gts->num_hwgain; j++) {
+			int candidate = gains[time_idx][j];
+			int chk;
+
+			if (candidate > all_gains[new_idx - 1]) {
+				all_gains[new_idx] = candidate;
+				new_idx++;
+
+				continue;
+			}
+			for (chk = 0; chk < new_idx; chk++)
+				if (candidate <= all_gains[chk])
+					break;
+
+			if (candidate == all_gains[chk])
+				continue;
+
+			memmove(&all_gains[chk + 1], &all_gains[chk],
+				(new_idx - chk) * sizeof(int));
+			all_gains[chk] = candidate;
+			new_idx++;
+		}
+	}
+
+	gts->num_avail_all_scales = new_idx;
+	gts->avail_all_scales_table = kcalloc(gts->num_avail_all_scales,
+					      2 * sizeof(int), GFP_KERNEL);
+	if (!gts->avail_all_scales_table)
+		ret = -ENOMEM;
+	else
+		for (i = 0; !ret && i < gts->num_avail_all_scales; i++)
+			ret = iio_gts_total_gain_to_scale(gts, all_gains[i],
+					&gts->avail_all_scales_table[i * 2],
+					&gts->avail_all_scales_table[i * 2 + 1]);
+
+	kfree(all_gains);
+	if (ret)
+		kfree(gts->avail_all_scales_table);
+
+	return ret;
+}
+
+/**
+ * iio_gts_build_avail_scale_table - create tables of available scales
+ * @gts:	Gain time scale descriptor
+ *
+ * Build the tables which can represent the available scales based on the
+ * originally given gain and time tables. When both time and gain tables are
+ * given this results:
+ * 1. A set of tables representing available scales for each supported
+ *    integration time.
+ * 2. A single table listing all the unique scales that any combination of
+ *    supported gains and times can provide.
+ *
+ * NOTE: Space allocated for the tables must be freed using
+ * iio_gts_purge_avail_scale_table() when the tables are no longer needed.
+ *
+ * Return: 0 on success.
+ */
+static int iio_gts_build_avail_scale_table(struct iio_gts *gts)
+{
+	int **per_time_gains, **per_time_scales, i, j, ret = -ENOMEM;
+
+	per_time_gains = kcalloc(gts->num_itime, sizeof(int *), GFP_KERNEL);
+	if (!per_time_gains)
+		return ret;
+
+	per_time_scales = kcalloc(gts->num_itime, sizeof(int *), GFP_KERNEL);
+	if (!per_time_scales)
+		goto free_gains;
+
+	for (i = 0; i < gts->num_itime; i++) {
+		per_time_scales[i] = kcalloc(gts->num_hwgain, 2 * sizeof(int),
+					     GFP_KERNEL);
+		if (!per_time_scales[i])
+			goto err_free_out;
+
+		per_time_gains[i] = kcalloc(gts->num_hwgain, sizeof(int),
+					    GFP_KERNEL);
+		if (!per_time_gains[i])
+			goto err_free_scale_out;
+
+
+		for (j = 0; j < gts->num_hwgain; j++)
+			per_time_gains[i][j] = gts->hwgain_table[j].gain *
+					       gts->itime_table[i].mul;
+	}
+
+	ret = gain_to_scaletables(gts, per_time_gains, per_time_scales);
+	if (ret)
+		goto err_free_out;
+
+	kfree(per_time_gains);
+	gts->per_time_avail_scale_tables = per_time_scales;
+
+	return 0;
+
+err_free_scale_out:
+	kfree(per_time_scales[i]);
+err_free_out:
+	for (i--; i; i--) {
+		kfree(per_time_scales[i]);
+		kfree(per_time_gains[i]);
+	}
+	kfree(per_time_scales);
+free_gains:
+	kfree(per_time_gains);
+
+	return ret;
+}
+
+/**
+ * iio_gts_build_avail_time_table - build table of available integration times
+ * @gts:	Gain time scale descriptor
+ *
+ * Build the table which can represent the available times to be returned
+ * to users using the read_avail-callback.
+ *
+ * NOTE: Space allocated for the tables must be freed using
+ * iio_gts_purge_avail_time_table() when the tables are no longer needed.
+ *
+ * Return: 0 on success.
+ */
+static int iio_gts_build_avail_time_table(struct iio_gts *gts)
+{
+	int *times, i, j, idx = 0;
+
+	if (!gts->num_itime)
+		return 0;
+
+	times = kcalloc(gts->num_itime, sizeof(int), GFP_KERNEL);
+	if (!times)
+		return -ENOMEM;
+
+	for (i = gts->num_itime - 1; i >= 0; i--) {
+		int new = gts->itime_table[i].time_us;
+
+		if (times[idx] < new) {
+			times[idx++] = new;
+			continue;
+		}
+
+		for (j = 0; j <= idx; j++) {
+			if (times[j] > new) {
+				memmove(&times[j + 1], &times[j],
+					(idx - j) * sizeof(int));
+				times[j] = new;
+				idx++;
+			}
+		}
+	}
+	gts->avail_time_tables = times;
+	/*
+	 * This is just to survive a unlikely corner-case where times in the
+	 * given time table were not unique. Else we could just trust the
+	 * gts->num_itime.
+	 */
+	gts->num_avail_time_tables = idx;
+
+	return 0;
+}
+
+/**
+ * iio_gts_purge_avail_time_table - free-up the available integration time table
+ * @gts:	Gain time scale descriptor
+ *
+ * Free the space reserved by iio_gts_build_avail_time_table(). Please note
+ * that the helpers for getting available integration times like the
+ * iio_gts_avail_times() are not usable after this call. Thus, this should
+ * be only called after these helpers can no longer be called (Eg. after
+ * the iio-device has been deregistered).
+ */
+static void iio_gts_purge_avail_time_table(struct iio_gts *gts)
+{
+	if (gts->num_avail_time_tables) {
+		kfree(gts->avail_time_tables);
+		gts->avail_time_tables = NULL;
+		gts->num_avail_time_tables = 0;
+	}
+}
+
+/**
+ * iio_gts_build_avail_tables - create tables of available scales and int times
+ * @gts:	Gain time scale descriptor
+ *
+ * Build the tables which can represent the available scales and available
+ * integration times. Availability tables are built based on the originally
+ * given gain and given time tables.
+ *
+ * When both time and gain tables are
+ * given this results:
+ * 1. A set of sorted tables representing available scales for each supported
+ *    integration time.
+ * 2. A single sorted table listing all the unique scales that any combination
+ *    of supported gains and times can provide.
+ * 3. A sorted table of supported integration times
+ *
+ * After these tables are built one can use the iio_gts_all_avail_scales(),
+ * iio_gts_avail_scales_for_time() and iio_gts_avail_times() helpers to
+ * implement the read_avail opeations.
+ *
+ * NOTE: Space allocated for the tables must be freed using
+ * iio_gts_purge_avail_tables() when the tables are no longer needed.
+ *
+ * Return: 0 on success.
+ */
+static int iio_gts_build_avail_tables(struct iio_gts *gts)
+{
+	int ret;
+
+	ret = iio_gts_build_avail_scale_table(gts);
+	if (ret)
+		return ret;
+
+	ret = iio_gts_build_avail_time_table(gts);
+	if (ret)
+		iio_gts_purge_avail_scale_table(gts);
+
+	return ret;
+}
+
+/**
+ * iio_gts_purge_avail_tables - free-up the availability tables
+ * @gts:	Gain time scale descriptor
+ *
+ * Free the space reserved by iio_gts_build_avail_tables(). Frees both the
+ * integration time and scale tables.
+ *
+ * Note  that the helpers for getting available integration times or scales
+ * like the iio_gts_avail_times() are not usable after this call. Thus, this
+ * should be only called after these helpers can no longer be called (Eg.
+ * after the iio-device has been deregistered).
+ */
+static void iio_gts_purge_avail_tables(struct iio_gts *gts)
+{
+	iio_gts_purge_avail_time_table(gts);
+	iio_gts_purge_avail_scale_table(gts);
+}
+
+static void devm_iio_gts_avail_all_drop(void *res)
+{
+	iio_gts_purge_avail_tables(res);
+}
+
+/**
+ * devm_iio_gts_build_avail_tables - manged add availability tables
+ * @dev:	Pointer to the device whose lifetime tables are bound
+ * @gts:	Gain time scale descriptor
+ *
+ * Build the tables which can represent the available scales and available
+ * integration times. Availability tables are built based on the originally
+ * given gain and given time tables.
+ *
+ * When both time and gain tables are
+ * given this results:
+ * 1. A set of sorted tables representing available scales for each supported
+ *    integration time.
+ * 2. A single sorted table listing all the unique scales that any combination
+ *    of supported gains and times can provide.
+ * 3. A sorted table of supported integration times
+ *
+ * After these tables are built one can use the iio_gts_all_avail_scales(),
+ * iio_gts_avail_scales_for_time() and iio_gts_avail_times() helpers to
+ * implement the read_avail opeations.
+ *
+ * The tables are automatically released upon device detach.
+ *
+ * NOTE: after the tables have been purged, the helpers for getting
+ * available scales / integration times are no longer usable. Care must be
+ * taken that unwinding is done in correct order (iio device is deregistered
+ * prior purging the tables).
+ *
+ * Return: 0 on success.
+ */
+int devm_iio_gts_build_avail_tables(struct device *dev, struct iio_gts *gts)
+{
+	int ret;
+
+	ret = iio_gts_build_avail_tables(gts);
+	if (ret)
+		return ret;
+
+	return devm_add_action_or_reset(dev, devm_iio_gts_avail_all_drop, gts);
+}
+EXPORT_SYMBOL_GPL(devm_iio_gts_build_avail_tables);
+
+/**
+ * iio_gts_all_avail_scales - helper for listing all available scales
+ * @gts:	Gain time scale descriptor
+ * @vals:	Returned array of supported scales
+ * @type:	Type of returned scale values
+ * @length:	Amount of returned values in array
+ *
+ * Return: a value suitable to be returned from read_avail or a negative error.
+ */
+int iio_gts_all_avail_scales(struct iio_gts *gts, const int **vals, int *type,
+			     int *length)
+{
+	if (!gts->num_avail_all_scales)
+		return -EINVAL;
+
+	*vals = gts->avail_all_scales_table;
+	*type = IIO_VAL_INT_PLUS_NANO;
+	*length = gts->num_avail_all_scales * 2;
+
+	return IIO_AVAIL_LIST;
+}
+EXPORT_SYMBOL_GPL(iio_gts_all_avail_scales);
+
+/**
+ * iio_gts_avail_scales_for_time - list scales for integration time
+ * @gts:	Gain time scale descriptor
+ * @time:	Integration time for which the scales are listed
+ * @vals:	Returned array of supported scales
+ * @type:	Type of returned scale values
+ * @length:	Amount of returned values in array
+ *
+ * Drivers which do not allow scale setting to change integration time can
+ * use this helper to list only the scales whic are valid for given integration
+ * time.
+ *
+ * Return: a value suitable to be returned from read_avail or a negative error.
+ */
+int iio_gts_avail_scales_for_time(struct iio_gts *gts, int time,
+				  const int **vals, int *type, int *length)
+{
+	int i;
+
+	for (i = 0; i < gts->num_itime; i++)
+		if (gts->itime_table[i].time_us == time)
+			break;
+
+	if (i == gts->num_itime)
+		return -EINVAL;
+
+	*vals = gts->per_time_avail_scale_tables[i];
+	*type = IIO_VAL_INT_PLUS_NANO;
+	*length = gts->num_hwgain * 2;
+
+	return IIO_AVAIL_LIST;
+}
+EXPORT_SYMBOL_GPL(iio_gts_avail_scales_for_time);
+
+/**
+ * iio_gts_avail_times - helper for listing available integration times
+ * @gts:	Gain time scale descriptor
+ * @vals:	Returned array of supported timees
+ * @type:	Type of returned scale values
+ * @length:	Amount of returned values in array
+ *
+ * Return: a value suitable to be returned from read_avail or a negative error.
+ */
+int iio_gts_avail_times(struct iio_gts *gts,  const int **vals, int *type,
+			int *length)
+{
+	if (!gts->num_avail_time_tables)
+		return -EINVAL;
+
+	*vals = gts->avail_time_tables;
+	*type = IIO_VAL_INT;
+	*length = gts->num_avail_time_tables;
+
+	return IIO_AVAIL_LIST;
+}
+EXPORT_SYMBOL_GPL(iio_gts_avail_times);
+
+/**
+ * iio_gts_valid_time - check if given integration time is valid
+ * @gts:	Gain time scale descriptor
+ * @time_us:	Integration time to check
+ *
+ * Return:	True if given time is supported by device. False if not.
+ */
+bool iio_gts_valid_time(struct iio_gts *gts, int time_us)
+{
+	return iio_gts_find_itime_by_time(gts, time_us);
+}
+EXPORT_SYMBOL_GPL(iio_gts_valid_time);
+
+int iio_gts_find_sel_by_gain(struct iio_gts *gts, int gain)
+{
+	int i;
+
+	for (i = 0; i < gts->num_hwgain; i++)
+		if (gts->hwgain_table[i].gain == gain)
+			return gts->hwgain_table[i].sel;
+
+	return -EINVAL;
+}
+EXPORT_SYMBOL_GPL(iio_gts_find_sel_by_gain);
+
+bool iio_gts_valid_gain(struct iio_gts *gts, int gain)
+{
+	return iio_gts_find_sel_by_gain(gts, gain) >= 0;
+}
+EXPORT_SYMBOL_GPL(iio_gts_valid_gain);
+
+int iio_gts_find_gain_by_sel(struct iio_gts *gts, int sel)
+{
+	int i;
+
+	for (i = 0; i < gts->num_hwgain; i++)
+		if (gts->hwgain_table[i].sel == sel)
+			return gts->hwgain_table[i].gain;
+
+	return -EINVAL;
+}
+EXPORT_SYMBOL_GPL(iio_gts_find_gain_by_sel);
+
+int iio_gts_get_min_gain(struct iio_gts *gts)
+{
+	int i, min = -EINVAL;
+
+	for (i = 0; i < gts->num_hwgain; i++) {
+		int gain = gts->hwgain_table[i].gain;
+
+		if (min == -EINVAL)
+			min = gain;
+		else
+			min = min(min, gain);
+	}
+
+	return min;
+}
+EXPORT_SYMBOL_GPL(iio_gts_get_min_gain);
+
+/**
+ * iio_find_closest_gain_low - Find the closest lower matching gain
+ * @gts:	Gain time scale descriptor
+ * @gain:	reference gain for which the closest match is searched
+ * @in_range:	indicate if the reference gain was actually in the range of
+ *		supported gains.
+ *
+ * Search for closest supported gain that is lower than or equal to the
+ * gain given as a parameter. This is usable for drivers which do not require
+ * user to request exact matching gain but rather fo rounding to a supported
+ * gain value which is equal or lower (setting lower gain is typical for
+ * avoiding saturation)
+ *
+ * Return:	The closest matching supported gain or -EINVAL is reference
+ *		gain was smaller than the smallest supported gain.
+ */
+int iio_find_closest_gain_low(struct iio_gts *gts, int gain, bool *in_range)
+{
+	int i, diff = 0;
+	int best = -1;
+
+	*in_range = false;
+
+	for (i = 0; i < gts->num_hwgain; i++) {
+		/*
+		 * It is not expected this function is called for an exactly
+		 * matching gain.
+		 */
+		if (unlikely(gain == gts->hwgain_table[i].gain)) {
+			*in_range = true;
+			return gain;
+		}
+
+		if (gain > gts->hwgain_table[i].gain) {
+			if (!diff) {
+				diff = gain - gts->hwgain_table[i].gain;
+				best = i;
+			} else {
+				int tmp = gain - gts->hwgain_table[i].gain;
+
+				if (tmp < diff) {
+					diff = tmp;
+					best = i;
+				}
+			}
+		} else {
+			/*
+			 * We found valid hwgain which is greater than
+			 * reference. So, unless we return a failure below we
+			 * will have found an in-range gain
+			 */
+			*in_range = true;
+		}
+	}
+	/* The requested gain was smaller than anything we support */
+	if (!diff) {
+		*in_range = false;
+
+		return -EINVAL;
+	}
+
+	return gts->hwgain_table[best].gain;
+}
+EXPORT_SYMBOL_GPL(iio_find_closest_gain_low);
+
+static int iio_gts_get_int_time_gain_multiplier_by_sel(struct iio_gts *gts,
+						       int sel)
+{
+	const struct iio_itime_sel_mul *time;
+
+	time = iio_gts_find_itime_by_sel(gts, sel);
+	if (!time)
+		return -EINVAL;
+
+	return time->mul;
+}
+
+/**
+ * iio_gts_find_gain_for_scale_using_time - Find gain by time and scale
+ * @gts:	Gain time scale descriptor
+ * @time_sel:	Integration time selector correspondig to the time gain is
+ *		searhed for
+ * @scale_int:	Integral part of the scale (typically val1)
+ * @scale_nano:	Fractional part of the scale (nano or ppb)
+ * @gain:	Pointer to value where gain is stored.
+ *
+ * In some cases the light sensors may want to find a gain setting which
+ * corresponds given scale and integration time. Sensors which fill the
+ * gain and time tables may use this helper to retrieve the gain.
+ *
+ * Return:	0 on success. -EINVAL if gain matching the parameters is not
+ *		found.
+ */
+static int iio_gts_find_gain_for_scale_using_time(struct iio_gts *gts, int time_sel,
+						  int scale_int, int scale_nano,
+						  int *gain)
+{
+	u64 scale_linear;
+	int ret, mul;
+
+	ret = iio_gts_linearize(scale_int, scale_nano, NANO, &scale_linear);
+	if (ret)
+		return ret;
+
+	ret = iio_gts_get_int_time_gain_multiplier_by_sel(gts, time_sel);
+	if (ret < 0)
+		return ret;
+
+	mul = ret;
+
+	ret = gain_get_scale_fraction(gts->max_scale, scale_linear, mul, gain);
+	if (ret)
+		return ret;
+
+	if (!iio_gts_valid_gain(gts, *gain))
+		return -EINVAL;
+
+	return 0;
+}
+
+/*
+ * iio_gts_find_gain_sel_for_scale_using_time - Fetch gain selector.
+ * See iio_gts_find_gain_for_scale_using_time() for more information
+ */
+int iio_gts_find_gain_sel_for_scale_using_time(struct iio_gts *gts, int time_sel,
+					       int scale_int, int scale_nano,
+					       int *gain_sel)
+{
+	int gain, ret;
+
+	ret = iio_gts_find_gain_for_scale_using_time(gts, time_sel, scale_int,
+						     scale_nano, &gain);
+	if (ret)
+		return ret;
+
+	ret = iio_gts_find_sel_by_gain(gts, gain);
+	if (ret < 0)
+		return ret;
+
+	*gain_sel = ret;
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(iio_gts_find_gain_sel_for_scale_using_time);
+
+int iio_gts_find_int_time_by_sel(struct iio_gts *gts, int sel)
+{
+	const struct iio_itime_sel_mul *itime;
+
+	itime = iio_gts_find_itime_by_sel(gts, sel);
+	if (!itime)
+		return -EINVAL;
+
+	return itime->time_us;
+}
+EXPORT_SYMBOL_GPL(iio_gts_find_int_time_by_sel);
+
+int iio_gts_find_sel_by_int_time(struct iio_gts *gts, int time)
+{
+	const struct iio_itime_sel_mul *itime;
+
+	itime = iio_gts_find_itime_by_time(gts, time);
+	if (!itime)
+		return -EINVAL;
+
+	return itime->sel;
+}
+EXPORT_SYMBOL_GPL(iio_gts_find_sel_by_int_time);
+
+static int iio_gts_get_total_gain(struct iio_gts *gts, int gain, int time)
+{
+	const struct iio_itime_sel_mul *itime;
+
+	if (!iio_gts_valid_gain(gts, gain))
+		return -EINVAL;
+
+	if (!gts->num_itime)
+		return gain;
+
+	itime = iio_gts_find_itime_by_time(gts, time);
+	if (!itime)
+		return -EINVAL;
+
+	return gain * itime->mul;
+}
+
+static int iio_gts_get_scale_linear(struct iio_gts *gts, int gain, int time,
+				    u64 *scale)
+{
+	int total_gain;
+	u64 tmp;
+
+	total_gain = iio_gts_get_total_gain(gts, gain, time);
+	if (total_gain < 0)
+		return total_gain;
+
+	tmp = gts->max_scale;
+
+	do_div(tmp, total_gain);
+
+	*scale = tmp;
+
+	return 0;
+}
+
+int iio_gts_get_scale(struct iio_gts *gts, int gain, int time, int *scale_int,
+		      int *scale_nano)
+{
+	u64 lin_scale;
+	int ret;
+
+	ret = iio_gts_get_scale_linear(gts, gain, time, &lin_scale);
+	if (ret)
+		return ret;
+
+	return iio_gts_delinearize(lin_scale, NANO, scale_int, scale_nano);
+}
+EXPORT_SYMBOL_GPL(iio_gts_get_scale);
+
+/**
+ * iio_gts_find_new_gain_sel_by_old_gain_time - compensate time change
+ * @gts:		Gain time scale descriptor
+ * @old_gain:		Previously set gain
+ * @old_time_sel:	Selector corresponding previously set time
+ * @new_time_sel:	Selector corresponding new time to be set
+ * @new_gain:		Pointer to value where new gain is to be written
+ *
+ * We may want to mitigate the scale change caused by setting a new integration
+ * time (for a light sensor) by also updating the (HW)gain. This helper computes
+ * new gain value to maintain the scale with new integration time.
+ *
+ * Return: 0 on success. -EINVAL if gain matching the new time is not found.
+ */
+int iio_gts_find_new_gain_sel_by_old_gain_time(struct iio_gts *gts,
+					       int old_gain, int old_time_sel,
+					       int new_time_sel, int *new_gain)
+{
+	const struct iio_itime_sel_mul *itime_old, *itime_new;
+	u64 scale;
+	int ret;
+
+	itime_old = iio_gts_find_itime_by_sel(gts, old_time_sel);
+	if (!itime_old)
+		return -EINVAL;
+
+	itime_new = iio_gts_find_itime_by_sel(gts, new_time_sel);
+	if (!itime_new)
+		return -EINVAL;
+
+	ret = iio_gts_get_scale_linear(gts, old_gain, itime_old->time_us,
+				       &scale);
+	if (ret)
+		return ret;
+
+	ret = gain_get_scale_fraction(gts->max_scale, scale, itime_new->mul,
+				      new_gain);
+	if (ret)
+		return -EINVAL;
+
+	if (!iio_gts_valid_gain(gts, *new_gain))
+		return -EINVAL;
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(iio_gts_find_new_gain_sel_by_old_gain_time);
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Matti Vaittinen <mazziesaccount@gmail.com>");
+MODULE_DESCRIPTION("IIO light sensor gain-time-scale helpers");
diff --git a/include/linux/iio/iio-gts-helper.h b/include/linux/iio/iio-gts-helper.h
new file mode 100644
index 000000000000..95c712007962
--- /dev/null
+++ b/include/linux/iio/iio-gts-helper.h
@@ -0,0 +1,113 @@ 
+/* SPDX-License-Identifier: GPL-2.0-only */
+/* gain-time-scale conversion helpers for IIO light sensors
+ *
+ * Copyright (c) 2023 Matti Vaittinen <mazziesaccount@gmail.com>
+ */
+
+#ifndef __IIO_GTS_HELPER__
+#define __IIO_GTS_HELPER__
+
+#include <linux/types.h>
+
+struct device;
+
+/**
+ * struct iio_gain_sel_pair - gain - selector values
+ *
+ * In many cases devices like light sensors allow setting signal amplification
+ * (gain) using a register interface. This structure describes amplification
+ * and corresponding selector (register value)
+ *
+ * @gain:	Gain (multiplication) value.
+ * @sel:	Selector (usually register value) used to indicate this gain
+ */
+struct iio_gain_sel_pair {
+	int gain;
+	int sel;
+};
+
+/**
+ * struct iio_itime_sel_mul - integration time description
+ *
+ * In many cases devices like light sensors allow setting the duration of
+ * collecting data. Typically this duration has also an impact to the magnitude
+ * of measured values (gain). This structure describes the relation of
+ * integration time and amplification as well as corresponding selector
+ * (register value).
+ *
+ * An example could be a sensor allowing 50, 100, 200 and 400 mS times. The
+ * respective multiplication values could be 50 mS => 1, 100 mS => 2,
+ * 200 mS => 4 and 400 mS => 8 assuming the impact of integration time would be
+ * linear in a way that when collecting data for 50 mS caused value X, doubling
+ * the data collection time caused value 2X etc..
+ *
+ * @time_us:	Integration time in microseconds.
+ * @sel:	Selector (usually register value) used to indicate this time
+ * @mul:	Multiplication to the values caused by this time.
+ */
+struct iio_itime_sel_mul {
+	int time_us;
+	int sel;
+	int mul;
+};
+
+struct iio_gts {
+	u64 max_scale;
+	const struct iio_gain_sel_pair *hwgain_table;
+	int num_hwgain;
+	const struct iio_itime_sel_mul *itime_table;
+	int num_itime;
+	int **per_time_avail_scale_tables;
+	int *avail_all_scales_table;
+	int num_avail_all_scales;
+	int *avail_time_tables;
+	int num_avail_time_tables;
+};
+
+#define GAIN_SCALE_GAIN(_gain, _sel)			\
+{							\
+	.gain = (_gain),				\
+	.sel = (_sel),					\
+}
+
+#define GAIN_SCALE_ITIME_US(_itime, _sel, _mul)		\
+{							\
+	.time_us = (_itime),				\
+	.sel = (_sel),					\
+	.mul = (_mul),					\
+}
+
+int iio_init_iio_gts(int max_scale_int, int max_scale_nano,
+		     const struct iio_gain_sel_pair *gain_tbl, int num_gain,
+		     const struct iio_itime_sel_mul *tim_tbl, int num_times,
+		     struct iio_gts *gts);
+
+bool iio_gts_valid_gain(struct iio_gts *gts, int gain);
+bool iio_gts_valid_time(struct iio_gts *gts, int time_us);
+
+int iio_find_closest_gain_low(struct iio_gts *gts, int gain, bool *in_range);
+int iio_gts_find_gain_by_sel(struct iio_gts *gts, int sel);
+int iio_gts_find_sel_by_gain(struct iio_gts *gts, int gain);
+int iio_gts_get_min_gain(struct iio_gts *gts);
+int iio_gts_find_int_time_by_sel(struct iio_gts *gts, int sel);
+int iio_gts_find_sel_by_int_time(struct iio_gts *gts, int time);
+
+int iio_gts_total_gain_to_scale(struct iio_gts *gts, int total_gain,
+				int *scale_int, int *scale_nano);
+int iio_gts_find_gain_sel_for_scale_using_time(struct iio_gts *gts, int time_sel,
+					       int scale_int, int scale_nano,
+					       int *gain_sel);
+int iio_gts_get_scale(struct iio_gts *gts, int gain, int time, int *scale_int,
+		      int *scale_nano);
+int iio_gts_find_new_gain_sel_by_old_gain_time(struct iio_gts *gts,
+					       int old_gain, int old_time_sel,
+					       int new_time_sel, int *new_gain);
+int devm_iio_gts_build_avail_tables(struct device *dev, struct iio_gts *gts);
+int iio_gts_avail_times(struct iio_gts *gts,  const int **vals, int *type,
+			int *length);
+int iio_gts_all_avail_scales(struct iio_gts *gts, const int **vals, int *type,
+			     int *length);
+int iio_gts_avail_scales_for_time(struct iio_gts *gts, int time,
+				  const int **vals, int *type, int *length);
+
+#endif