1 // SPDX-License-Identifier: GPL-2.0-only
2 /* gain-time-scale conversion helpers for IIO light sensors
3  *
4  * Copyright (c) 2023 Matti Vaittinen <mazziesaccount@gmail.com>
5  */
6 
7 #include <linux/device.h>
8 #include <linux/errno.h>
9 #include <linux/export.h>
10 #include <linux/minmax.h>
11 #include <linux/module.h>
12 #include <linux/overflow.h>
13 #include <linux/slab.h>
14 #include <linux/sort.h>
15 #include <linux/types.h>
16 #include <linux/units.h>
17 
18 #include <linux/iio/iio-gts-helper.h>
19 #include <linux/iio/types.h>
20 
21 /**
22  * iio_gts_get_gain - Convert scale to total gain
23  *
24  * Internal helper for converting scale to total gain.
25  *
26  * @max:	Maximum linearized scale. As an example, when scale is created
27  *		in magnitude of NANOs and max scale is 64.1 - The linearized
28  *		scale is 64 100 000 000.
29  * @scale:	Linearized scale to compute the gain for.
30  *
31  * Return:	(floored) gain corresponding to the scale. -EINVAL if scale
32  *		is invalid.
33  */
iio_gts_get_gain(const u64 max,const u64 scale)34 static int iio_gts_get_gain(const u64 max, const u64 scale)
35 {
36 	u64 full = max;
37 
38 	if (scale > full || !scale)
39 		return -EINVAL;
40 
41 	return div64_u64(full, scale);
42 }
43 
44 /**
45  * gain_get_scale_fraction - get the gain or time based on scale and known one
46  *
47  * @max:	Maximum linearized scale. As an example, when scale is created
48  *		in magnitude of NANOs and max scale is 64.1 - The linearized
49  *		scale is 64 100 000 000.
50  * @scale:	Linearized scale to compute the gain/time for.
51  * @known:	Either integration time or gain depending on which one is known
52  * @unknown:	Pointer to variable where the computed gain/time is stored
53  *
54  * Internal helper for computing unknown fraction of total gain.
55  * Compute either gain or time based on scale and either the gain or time
56  * depending on which one is known.
57  *
58  * Return:	0 on success.
59  */
gain_get_scale_fraction(const u64 max,u64 scale,int known,int * unknown)60 static int gain_get_scale_fraction(const u64 max, u64 scale, int known,
61 				   int *unknown)
62 {
63 	int tot_gain;
64 
65 	tot_gain = iio_gts_get_gain(max, scale);
66 	if (tot_gain < 0)
67 		return tot_gain;
68 
69 	*unknown = tot_gain / known;
70 
71 	/* We require total gain to be exact multiple of known * unknown */
72 	if (!*unknown || *unknown * known != tot_gain)
73 		return -EINVAL;
74 
75 	return 0;
76 }
77 
iio_gts_delinearize(u64 lin_scale,unsigned long scaler,int * scale_whole,int * scale_nano)78 static int iio_gts_delinearize(u64 lin_scale, unsigned long scaler,
79 			       int *scale_whole, int *scale_nano)
80 {
81 	int frac;
82 
83 	if (scaler > NANO)
84 		return -EOVERFLOW;
85 
86 	if (!scaler)
87 		return -EINVAL;
88 
89 	frac = do_div(lin_scale, scaler);
90 
91 	*scale_whole = lin_scale;
92 	*scale_nano = frac * (NANO / scaler);
93 
94 	return 0;
95 }
96 
iio_gts_linearize(int scale_whole,int scale_nano,unsigned long scaler,u64 * lin_scale)97 static int iio_gts_linearize(int scale_whole, int scale_nano,
98 			     unsigned long scaler, u64 *lin_scale)
99 {
100 	/*
101 	 * Expect scale to be (mostly) NANO or MICRO. Divide divider instead of
102 	 * multiplication followed by division to avoid overflow.
103 	 */
104 	if (scaler > NANO || !scaler)
105 		return -EINVAL;
106 
107 	*lin_scale = (u64)scale_whole * (u64)scaler +
108 		     (u64)(scale_nano / (NANO / scaler));
109 
110 	return 0;
111 }
112 
113 /**
114  * iio_gts_total_gain_to_scale - convert gain to scale
115  * @gts:	Gain time scale descriptor
116  * @total_gain:	the gain to be converted
117  * @scale_int:	Pointer to integral part of the scale (typically val1)
118  * @scale_nano:	Pointer to fractional part of the scale (nano or ppb)
119  *
120  * Convert the total gain value to scale. NOTE: This does not separate gain
121  * generated by HW-gain or integration time. It is up to caller to decide what
122  * part of the total gain is due to integration time and what due to HW-gain.
123  *
124  * Return: 0 on success. Negative errno on failure.
125  */
iio_gts_total_gain_to_scale(struct iio_gts * gts,int total_gain,int * scale_int,int * scale_nano)126 int iio_gts_total_gain_to_scale(struct iio_gts *gts, int total_gain,
127 				int *scale_int, int *scale_nano)
128 {
129 	u64 tmp;
130 
131 	tmp = gts->max_scale;
132 
133 	do_div(tmp, total_gain);
134 
135 	return iio_gts_delinearize(tmp, NANO, scale_int, scale_nano);
136 }
137 EXPORT_SYMBOL_NS_GPL(iio_gts_total_gain_to_scale, IIO_GTS_HELPER);
138 
139 /**
140  * iio_gts_purge_avail_scale_table - free-up the available scale tables
141  * @gts:	Gain time scale descriptor
142  *
143  * Free the space reserved by iio_gts_build_avail_scale_table().
144  */
iio_gts_purge_avail_scale_table(struct iio_gts * gts)145 static void iio_gts_purge_avail_scale_table(struct iio_gts *gts)
146 {
147 	int i;
148 
149 	if (gts->per_time_avail_scale_tables) {
150 		for (i = 0; i < gts->num_itime; i++)
151 			kfree(gts->per_time_avail_scale_tables[i]);
152 
153 		kfree(gts->per_time_avail_scale_tables);
154 		gts->per_time_avail_scale_tables = NULL;
155 	}
156 
157 	kfree(gts->avail_all_scales_table);
158 	gts->avail_all_scales_table = NULL;
159 
160 	gts->num_avail_all_scales = 0;
161 }
162 
iio_gts_gain_cmp(const void * a,const void * b)163 static int iio_gts_gain_cmp(const void *a, const void *b)
164 {
165 	return *(int *)a - *(int *)b;
166 }
167 
gain_to_scaletables(struct iio_gts * gts,int ** gains,int ** scales)168 static int gain_to_scaletables(struct iio_gts *gts, int **gains, int **scales)
169 {
170 	int ret, i, j, new_idx, time_idx;
171 	int *all_gains;
172 	size_t gain_bytes;
173 
174 	for (i = 0; i < gts->num_itime; i++) {
175 		/*
176 		 * Sort the tables for nice output and for easier finding of
177 		 * unique values.
178 		 */
179 		sort(gains[i], gts->num_hwgain, sizeof(int), iio_gts_gain_cmp,
180 		     NULL);
181 
182 		/* Convert gains to scales */
183 		for (j = 0; j < gts->num_hwgain; j++) {
184 			ret = iio_gts_total_gain_to_scale(gts, gains[i][j],
185 							  &scales[i][2 * j],
186 							  &scales[i][2 * j + 1]);
187 			if (ret)
188 				return ret;
189 		}
190 	}
191 
192 	gain_bytes = array_size(gts->num_hwgain, sizeof(int));
193 	all_gains = kcalloc(gts->num_itime, gain_bytes, GFP_KERNEL);
194 	if (!all_gains)
195 		return -ENOMEM;
196 
197 	/*
198 	 * We assume all the gains for same integration time were unique.
199 	 * It is likely the first time table had greatest time multiplier as
200 	 * the times are in the order of preference and greater times are
201 	 * usually preferred. Hence we start from the last table which is likely
202 	 * to have the smallest total gains.
203 	 */
204 	time_idx = gts->num_itime - 1;
205 	memcpy(all_gains, gains[time_idx], gain_bytes);
206 	new_idx = gts->num_hwgain;
207 
208 	while (time_idx--) {
209 		for (j = 0; j < gts->num_hwgain; j++) {
210 			int candidate = gains[time_idx][j];
211 			int chk;
212 
213 			if (candidate > all_gains[new_idx - 1]) {
214 				all_gains[new_idx] = candidate;
215 				new_idx++;
216 
217 				continue;
218 			}
219 			for (chk = 0; chk < new_idx; chk++)
220 				if (candidate <= all_gains[chk])
221 					break;
222 
223 			if (candidate == all_gains[chk])
224 				continue;
225 
226 			memmove(&all_gains[chk + 1], &all_gains[chk],
227 				(new_idx - chk) * sizeof(int));
228 			all_gains[chk] = candidate;
229 			new_idx++;
230 		}
231 	}
232 
233 	gts->avail_all_scales_table = kcalloc(new_idx, 2 * sizeof(int),
234 					      GFP_KERNEL);
235 	if (!gts->avail_all_scales_table) {
236 		ret = -ENOMEM;
237 		goto free_out;
238 	}
239 	gts->num_avail_all_scales = new_idx;
240 
241 	for (i = 0; i < gts->num_avail_all_scales; i++) {
242 		ret = iio_gts_total_gain_to_scale(gts, all_gains[i],
243 					&gts->avail_all_scales_table[i * 2],
244 					&gts->avail_all_scales_table[i * 2 + 1]);
245 
246 		if (ret) {
247 			kfree(gts->avail_all_scales_table);
248 			gts->num_avail_all_scales = 0;
249 			goto free_out;
250 		}
251 	}
252 
253 free_out:
254 	kfree(all_gains);
255 
256 	return ret;
257 }
258 
259 /**
260  * iio_gts_build_avail_scale_table - create tables of available scales
261  * @gts:	Gain time scale descriptor
262  *
263  * Build the tables which can represent the available scales based on the
264  * originally given gain and time tables. When both time and gain tables are
265  * given this results:
266  * 1. A set of tables representing available scales for each supported
267  *    integration time.
268  * 2. A single table listing all the unique scales that any combination of
269  *    supported gains and times can provide.
270  *
271  * NOTE: Space allocated for the tables must be freed using
272  * iio_gts_purge_avail_scale_table() when the tables are no longer needed.
273  *
274  * Return: 0 on success.
275  */
iio_gts_build_avail_scale_table(struct iio_gts * gts)276 static int iio_gts_build_avail_scale_table(struct iio_gts *gts)
277 {
278 	int **per_time_gains, **per_time_scales, i, j, ret = -ENOMEM;
279 
280 	per_time_gains = kcalloc(gts->num_itime, sizeof(*per_time_gains), GFP_KERNEL);
281 	if (!per_time_gains)
282 		return ret;
283 
284 	per_time_scales = kcalloc(gts->num_itime, sizeof(*per_time_scales), GFP_KERNEL);
285 	if (!per_time_scales)
286 		goto free_gains;
287 
288 	for (i = 0; i < gts->num_itime; i++) {
289 		per_time_scales[i] = kcalloc(gts->num_hwgain, 2 * sizeof(int),
290 					     GFP_KERNEL);
291 		if (!per_time_scales[i])
292 			goto err_free_out;
293 
294 		per_time_gains[i] = kcalloc(gts->num_hwgain, sizeof(int),
295 					    GFP_KERNEL);
296 		if (!per_time_gains[i]) {
297 			kfree(per_time_scales[i]);
298 			goto err_free_out;
299 		}
300 
301 		for (j = 0; j < gts->num_hwgain; j++)
302 			per_time_gains[i][j] = gts->hwgain_table[j].gain *
303 					       gts->itime_table[i].mul;
304 	}
305 
306 	ret = gain_to_scaletables(gts, per_time_gains, per_time_scales);
307 	if (ret)
308 		goto err_free_out;
309 
310 	kfree(per_time_gains);
311 	gts->per_time_avail_scale_tables = per_time_scales;
312 
313 	return 0;
314 
315 err_free_out:
316 	for (i--; i; i--) {
317 		kfree(per_time_scales[i]);
318 		kfree(per_time_gains[i]);
319 	}
320 	kfree(per_time_scales);
321 free_gains:
322 	kfree(per_time_gains);
323 
324 	return ret;
325 }
326 
iio_gts_us_to_int_micro(int * time_us,int * int_micro_times,int num_times)327 static void iio_gts_us_to_int_micro(int *time_us, int *int_micro_times,
328 				    int num_times)
329 {
330 	int i;
331 
332 	for (i = 0; i < num_times; i++) {
333 		int_micro_times[i * 2] = time_us[i] / 1000000;
334 		int_micro_times[i * 2 + 1] = time_us[i] % 1000000;
335 	}
336 }
337 
338 /**
339  * iio_gts_build_avail_time_table - build table of available integration times
340  * @gts:	Gain time scale descriptor
341  *
342  * Build the table which can represent the available times to be returned
343  * to users using the read_avail-callback.
344  *
345  * NOTE: Space allocated for the tables must be freed using
346  * iio_gts_purge_avail_time_table() when the tables are no longer needed.
347  *
348  * Return: 0 on success.
349  */
iio_gts_build_avail_time_table(struct iio_gts * gts)350 static int iio_gts_build_avail_time_table(struct iio_gts *gts)
351 {
352 	int *times, i, j, idx = 0, *int_micro_times;
353 
354 	if (!gts->num_itime)
355 		return 0;
356 
357 	times = kcalloc(gts->num_itime, sizeof(int), GFP_KERNEL);
358 	if (!times)
359 		return -ENOMEM;
360 
361 	/* Sort times from all tables to one and remove duplicates */
362 	for (i = gts->num_itime - 1; i >= 0; i--) {
363 		int new = gts->itime_table[i].time_us;
364 
365 		if (idx == 0 || times[idx - 1] < new) {
366 			times[idx++] = new;
367 			continue;
368 		}
369 
370 		for (j = 0; j < idx; j++) {
371 			if (times[j] == new)
372 				break;
373 			if (times[j] > new) {
374 				memmove(&times[j + 1], &times[j],
375 					(idx - j) * sizeof(int));
376 				times[j] = new;
377 				idx++;
378 				break;
379 			}
380 		}
381 	}
382 
383 	/* create a list of times formatted as list of IIO_VAL_INT_PLUS_MICRO */
384 	int_micro_times = kcalloc(idx, sizeof(int) * 2, GFP_KERNEL);
385 	if (int_micro_times) {
386 		/*
387 		 * This is just to survive a unlikely corner-case where times in
388 		 * the given time table were not unique. Else we could just
389 		 * trust the gts->num_itime.
390 		 */
391 		gts->num_avail_time_tables = idx;
392 		iio_gts_us_to_int_micro(times, int_micro_times, idx);
393 	}
394 
395 	gts->avail_time_tables = int_micro_times;
396 	kfree(times);
397 
398 	if (!int_micro_times)
399 		return -ENOMEM;
400 
401 	return 0;
402 }
403 
404 /**
405  * iio_gts_purge_avail_time_table - free-up the available integration time table
406  * @gts:	Gain time scale descriptor
407  *
408  * Free the space reserved by iio_gts_build_avail_time_table().
409  */
iio_gts_purge_avail_time_table(struct iio_gts * gts)410 static void iio_gts_purge_avail_time_table(struct iio_gts *gts)
411 {
412 	if (gts->num_avail_time_tables) {
413 		kfree(gts->avail_time_tables);
414 		gts->avail_time_tables = NULL;
415 		gts->num_avail_time_tables = 0;
416 	}
417 }
418 
419 /**
420  * iio_gts_build_avail_tables - create tables of available scales and int times
421  * @gts:	Gain time scale descriptor
422  *
423  * Build the tables which can represent the available scales and available
424  * integration times. Availability tables are built based on the originally
425  * given gain and given time tables.
426  *
427  * When both time and gain tables are
428  * given this results:
429  * 1. A set of sorted tables representing available scales for each supported
430  *    integration time.
431  * 2. A single sorted table listing all the unique scales that any combination
432  *    of supported gains and times can provide.
433  * 3. A sorted table of supported integration times
434  *
435  * After these tables are built one can use the iio_gts_all_avail_scales(),
436  * iio_gts_avail_scales_for_time() and iio_gts_avail_times() helpers to
437  * implement the read_avail operations.
438  *
439  * NOTE: Space allocated for the tables must be freed using
440  * iio_gts_purge_avail_tables() when the tables are no longer needed.
441  *
442  * Return: 0 on success.
443  */
iio_gts_build_avail_tables(struct iio_gts * gts)444 static int iio_gts_build_avail_tables(struct iio_gts *gts)
445 {
446 	int ret;
447 
448 	ret = iio_gts_build_avail_scale_table(gts);
449 	if (ret)
450 		return ret;
451 
452 	ret = iio_gts_build_avail_time_table(gts);
453 	if (ret)
454 		iio_gts_purge_avail_scale_table(gts);
455 
456 	return ret;
457 }
458 
459 /**
460  * iio_gts_purge_avail_tables - free-up the availability tables
461  * @gts:	Gain time scale descriptor
462  *
463  * Free the space reserved by iio_gts_build_avail_tables(). Frees both the
464  * integration time and scale tables.
465  */
iio_gts_purge_avail_tables(struct iio_gts * gts)466 static void iio_gts_purge_avail_tables(struct iio_gts *gts)
467 {
468 	iio_gts_purge_avail_time_table(gts);
469 	iio_gts_purge_avail_scale_table(gts);
470 }
471 
devm_iio_gts_avail_all_drop(void * res)472 static void devm_iio_gts_avail_all_drop(void *res)
473 {
474 	iio_gts_purge_avail_tables(res);
475 }
476 
477 /**
478  * devm_iio_gts_build_avail_tables - manged add availability tables
479  * @dev:	Pointer to the device whose lifetime tables are bound
480  * @gts:	Gain time scale descriptor
481  *
482  * Build the tables which can represent the available scales and available
483  * integration times. Availability tables are built based on the originally
484  * given gain and given time tables.
485  *
486  * When both time and gain tables are given this results:
487  * 1. A set of sorted tables representing available scales for each supported
488  *    integration time.
489  * 2. A single sorted table listing all the unique scales that any combination
490  *    of supported gains and times can provide.
491  * 3. A sorted table of supported integration times
492  *
493  * After these tables are built one can use the iio_gts_all_avail_scales(),
494  * iio_gts_avail_scales_for_time() and iio_gts_avail_times() helpers to
495  * implement the read_avail operations.
496  *
497  * The tables are automatically released upon device detach.
498  *
499  * Return: 0 on success.
500  */
devm_iio_gts_build_avail_tables(struct device * dev,struct iio_gts * gts)501 static int devm_iio_gts_build_avail_tables(struct device *dev,
502 					   struct iio_gts *gts)
503 {
504 	int ret;
505 
506 	ret = iio_gts_build_avail_tables(gts);
507 	if (ret)
508 		return ret;
509 
510 	return devm_add_action_or_reset(dev, devm_iio_gts_avail_all_drop, gts);
511 }
512 
sanity_check_time(const struct iio_itime_sel_mul * t)513 static int sanity_check_time(const struct iio_itime_sel_mul *t)
514 {
515 	if (t->sel < 0 || t->time_us < 0 || t->mul <= 0)
516 		return -EINVAL;
517 
518 	return 0;
519 }
520 
sanity_check_gain(const struct iio_gain_sel_pair * g)521 static int sanity_check_gain(const struct iio_gain_sel_pair *g)
522 {
523 	if (g->sel < 0 || g->gain <= 0)
524 		return -EINVAL;
525 
526 	return 0;
527 }
528 
iio_gts_sanity_check(struct iio_gts * gts)529 static int iio_gts_sanity_check(struct iio_gts *gts)
530 {
531 	int g, t, ret;
532 
533 	if (!gts->num_hwgain && !gts->num_itime)
534 		return -EINVAL;
535 
536 	for (t = 0; t < gts->num_itime; t++) {
537 		ret = sanity_check_time(&gts->itime_table[t]);
538 		if (ret)
539 			return ret;
540 	}
541 
542 	for (g = 0; g < gts->num_hwgain; g++) {
543 		ret = sanity_check_gain(&gts->hwgain_table[g]);
544 		if (ret)
545 			return ret;
546 	}
547 
548 	for (g = 0; g < gts->num_hwgain; g++) {
549 		for (t = 0; t < gts->num_itime; t++) {
550 			int gain, mul, res;
551 
552 			gain = gts->hwgain_table[g].gain;
553 			mul = gts->itime_table[t].mul;
554 
555 			if (check_mul_overflow(gain, mul, &res))
556 				return -EOVERFLOW;
557 		}
558 	}
559 
560 	return 0;
561 }
562 
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)563 static int iio_init_iio_gts(int max_scale_int, int max_scale_nano,
564 			const struct iio_gain_sel_pair *gain_tbl, int num_gain,
565 			const struct iio_itime_sel_mul *tim_tbl, int num_times,
566 			struct iio_gts *gts)
567 {
568 	int ret;
569 
570 	memset(gts, 0, sizeof(*gts));
571 
572 	ret = iio_gts_linearize(max_scale_int, max_scale_nano, NANO,
573 				   &gts->max_scale);
574 	if (ret)
575 		return ret;
576 
577 	gts->hwgain_table = gain_tbl;
578 	gts->num_hwgain = num_gain;
579 	gts->itime_table = tim_tbl;
580 	gts->num_itime = num_times;
581 
582 	return iio_gts_sanity_check(gts);
583 }
584 
585 /**
586  * devm_iio_init_iio_gts - Initialize the gain-time-scale helper
587  * @dev:		Pointer to the device whose lifetime gts resources are
588  *			bound
589  * @max_scale_int:	integer part of the maximum scale value
590  * @max_scale_nano:	fraction part of the maximum scale value
591  * @gain_tbl:		table describing supported gains
592  * @num_gain:		number of gains in the gain table
593  * @tim_tbl:		table describing supported integration times. Provide
594  *			the integration time table sorted so that the preferred
595  *			integration time is in the first array index. The search
596  *			functions like the
597  *			iio_gts_find_time_and_gain_sel_for_scale() start search
598  *			from first provided time.
599  * @num_times:		number of times in the time table
600  * @gts:		pointer to the helper struct
601  *
602  * Initialize the gain-time-scale helper for use. Note, gains, times, selectors
603  * and multipliers must be positive. Negative values are reserved for error
604  * checking. The total gain (maximum gain * maximum time multiplier) must not
605  * overflow int. The allocated resources will be released upon device detach.
606  *
607  * Return: 0 on success.
608  */
devm_iio_init_iio_gts(struct device * dev,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)609 int devm_iio_init_iio_gts(struct device *dev, int max_scale_int, int max_scale_nano,
610 			  const struct iio_gain_sel_pair *gain_tbl, int num_gain,
611 			  const struct iio_itime_sel_mul *tim_tbl, int num_times,
612 			  struct iio_gts *gts)
613 {
614 	int ret;
615 
616 	ret = iio_init_iio_gts(max_scale_int, max_scale_nano, gain_tbl,
617 			       num_gain, tim_tbl, num_times, gts);
618 	if (ret)
619 		return ret;
620 
621 	return devm_iio_gts_build_avail_tables(dev, gts);
622 }
623 EXPORT_SYMBOL_NS_GPL(devm_iio_init_iio_gts, IIO_GTS_HELPER);
624 
625 /**
626  * iio_gts_all_avail_scales - helper for listing all available scales
627  * @gts:	Gain time scale descriptor
628  * @vals:	Returned array of supported scales
629  * @type:	Type of returned scale values
630  * @length:	Amount of returned values in array
631  *
632  * Return: a value suitable to be returned from read_avail or a negative error.
633  */
iio_gts_all_avail_scales(struct iio_gts * gts,const int ** vals,int * type,int * length)634 int iio_gts_all_avail_scales(struct iio_gts *gts, const int **vals, int *type,
635 			     int *length)
636 {
637 	if (!gts->num_avail_all_scales)
638 		return -EINVAL;
639 
640 	*vals = gts->avail_all_scales_table;
641 	*type = IIO_VAL_INT_PLUS_NANO;
642 	*length = gts->num_avail_all_scales * 2;
643 
644 	return IIO_AVAIL_LIST;
645 }
646 EXPORT_SYMBOL_NS_GPL(iio_gts_all_avail_scales, IIO_GTS_HELPER);
647 
648 /**
649  * iio_gts_avail_scales_for_time - list scales for integration time
650  * @gts:	Gain time scale descriptor
651  * @time:	Integration time for which the scales are listed
652  * @vals:	Returned array of supported scales
653  * @type:	Type of returned scale values
654  * @length:	Amount of returned values in array
655  *
656  * Drivers which do not allow scale setting to change integration time can
657  * use this helper to list only the scales which are valid for given integration
658  * time.
659  *
660  * Return: a value suitable to be returned from read_avail or a negative error.
661  */
iio_gts_avail_scales_for_time(struct iio_gts * gts,int time,const int ** vals,int * type,int * length)662 int iio_gts_avail_scales_for_time(struct iio_gts *gts, int time,
663 				  const int **vals, int *type, int *length)
664 {
665 	int i;
666 
667 	for (i = 0; i < gts->num_itime; i++)
668 		if (gts->itime_table[i].time_us == time)
669 			break;
670 
671 	if (i == gts->num_itime)
672 		return -EINVAL;
673 
674 	*vals = gts->per_time_avail_scale_tables[i];
675 	*type = IIO_VAL_INT_PLUS_NANO;
676 	*length = gts->num_hwgain * 2;
677 
678 	return IIO_AVAIL_LIST;
679 }
680 EXPORT_SYMBOL_NS_GPL(iio_gts_avail_scales_for_time, IIO_GTS_HELPER);
681 
682 /**
683  * iio_gts_avail_times - helper for listing available integration times
684  * @gts:	Gain time scale descriptor
685  * @vals:	Returned array of supported times
686  * @type:	Type of returned scale values
687  * @length:	Amount of returned values in array
688  *
689  * Return: a value suitable to be returned from read_avail or a negative error.
690  */
iio_gts_avail_times(struct iio_gts * gts,const int ** vals,int * type,int * length)691 int iio_gts_avail_times(struct iio_gts *gts,  const int **vals, int *type,
692 			int *length)
693 {
694 	if (!gts->num_avail_time_tables)
695 		return -EINVAL;
696 
697 	*vals = gts->avail_time_tables;
698 	*type = IIO_VAL_INT_PLUS_MICRO;
699 	*length = gts->num_avail_time_tables * 2;
700 
701 	return IIO_AVAIL_LIST;
702 }
703 EXPORT_SYMBOL_NS_GPL(iio_gts_avail_times, IIO_GTS_HELPER);
704 
705 /**
706  * iio_gts_find_sel_by_gain - find selector corresponding to a HW-gain
707  * @gts:	Gain time scale descriptor
708  * @gain:	HW-gain for which matching selector is searched for
709  *
710  * Return:	a selector matching given HW-gain or -EINVAL if selector was
711  *		not found.
712  */
iio_gts_find_sel_by_gain(struct iio_gts * gts,int gain)713 int iio_gts_find_sel_by_gain(struct iio_gts *gts, int gain)
714 {
715 	int i;
716 
717 	for (i = 0; i < gts->num_hwgain; i++)
718 		if (gts->hwgain_table[i].gain == gain)
719 			return gts->hwgain_table[i].sel;
720 
721 	return -EINVAL;
722 }
723 EXPORT_SYMBOL_NS_GPL(iio_gts_find_sel_by_gain, IIO_GTS_HELPER);
724 
725 /**
726  * iio_gts_find_gain_by_sel - find HW-gain corresponding to a selector
727  * @gts:	Gain time scale descriptor
728  * @sel:	selector for which matching HW-gain is searched for
729  *
730  * Return:	a HW-gain matching given selector or -EINVAL if HW-gain was not
731  *		found.
732  */
iio_gts_find_gain_by_sel(struct iio_gts * gts,int sel)733 int iio_gts_find_gain_by_sel(struct iio_gts *gts, int sel)
734 {
735 	int i;
736 
737 	for (i = 0; i < gts->num_hwgain; i++)
738 		if (gts->hwgain_table[i].sel == sel)
739 			return gts->hwgain_table[i].gain;
740 
741 	return -EINVAL;
742 }
743 EXPORT_SYMBOL_NS_GPL(iio_gts_find_gain_by_sel, IIO_GTS_HELPER);
744 
745 /**
746  * iio_gts_get_min_gain - find smallest valid HW-gain
747  * @gts:	Gain time scale descriptor
748  *
749  * Return:	The smallest HW-gain -EINVAL if no HW-gains were in the tables.
750  */
iio_gts_get_min_gain(struct iio_gts * gts)751 int iio_gts_get_min_gain(struct iio_gts *gts)
752 {
753 	int i, min = -EINVAL;
754 
755 	for (i = 0; i < gts->num_hwgain; i++) {
756 		int gain = gts->hwgain_table[i].gain;
757 
758 		if (min == -EINVAL)
759 			min = gain;
760 		else
761 			min = min(min, gain);
762 	}
763 
764 	return min;
765 }
766 EXPORT_SYMBOL_NS_GPL(iio_gts_get_min_gain, IIO_GTS_HELPER);
767 
768 /**
769  * iio_find_closest_gain_low - Find the closest lower matching gain
770  * @gts:	Gain time scale descriptor
771  * @gain:	HW-gain for which the closest match is searched
772  * @in_range:	indicate if the @gain was actually in the range of
773  *		supported gains.
774  *
775  * Search for closest supported gain that is lower than or equal to the
776  * gain given as a parameter. This is usable for drivers which do not require
777  * user to request exact matching gain but rather for rounding to a supported
778  * gain value which is equal or lower (setting lower gain is typical for
779  * avoiding saturation)
780  *
781  * Return:	The closest matching supported gain or -EINVAL if @gain
782  *		was smaller than the smallest supported gain.
783  */
iio_find_closest_gain_low(struct iio_gts * gts,int gain,bool * in_range)784 int iio_find_closest_gain_low(struct iio_gts *gts, int gain, bool *in_range)
785 {
786 	int i, diff = 0;
787 	int best = -1;
788 
789 	*in_range = false;
790 
791 	for (i = 0; i < gts->num_hwgain; i++) {
792 		if (gain == gts->hwgain_table[i].gain) {
793 			*in_range = true;
794 			return gain;
795 		}
796 
797 		if (gain > gts->hwgain_table[i].gain) {
798 			if (!diff) {
799 				diff = gain - gts->hwgain_table[i].gain;
800 				best = i;
801 			} else {
802 				int tmp = gain - gts->hwgain_table[i].gain;
803 
804 				if (tmp < diff) {
805 					diff = tmp;
806 					best = i;
807 				}
808 			}
809 		} else {
810 			/*
811 			 * We found valid HW-gain which is greater than
812 			 * reference. So, unless we return a failure below we
813 			 * will have found an in-range gain
814 			 */
815 			*in_range = true;
816 		}
817 	}
818 	/* The requested gain was smaller than anything we support */
819 	if (!diff) {
820 		*in_range = false;
821 
822 		return -EINVAL;
823 	}
824 
825 	return gts->hwgain_table[best].gain;
826 }
827 EXPORT_SYMBOL_NS_GPL(iio_find_closest_gain_low, IIO_GTS_HELPER);
828 
iio_gts_get_int_time_gain_multiplier_by_sel(struct iio_gts * gts,int sel)829 static int iio_gts_get_int_time_gain_multiplier_by_sel(struct iio_gts *gts,
830 						       int sel)
831 {
832 	const struct iio_itime_sel_mul *time;
833 
834 	time = iio_gts_find_itime_by_sel(gts, sel);
835 	if (!time)
836 		return -EINVAL;
837 
838 	return time->mul;
839 }
840 
841 /**
842  * iio_gts_find_gain_for_scale_using_time - Find gain by time and scale
843  * @gts:	Gain time scale descriptor
844  * @time_sel:	Integration time selector corresponding to the time gain is
845  *		searched for
846  * @scale_int:	Integral part of the scale (typically val1)
847  * @scale_nano:	Fractional part of the scale (nano or ppb)
848  * @gain:	Pointer to value where gain is stored.
849  *
850  * In some cases the light sensors may want to find a gain setting which
851  * corresponds given scale and integration time. Sensors which fill the
852  * gain and time tables may use this helper to retrieve the gain.
853  *
854  * Return:	0 on success. -EINVAL if gain matching the parameters is not
855  *		found.
856  */
iio_gts_find_gain_for_scale_using_time(struct iio_gts * gts,int time_sel,int scale_int,int scale_nano,int * gain)857 static int iio_gts_find_gain_for_scale_using_time(struct iio_gts *gts, int time_sel,
858 						  int scale_int, int scale_nano,
859 						  int *gain)
860 {
861 	u64 scale_linear;
862 	int ret, mul;
863 
864 	ret = iio_gts_linearize(scale_int, scale_nano, NANO, &scale_linear);
865 	if (ret)
866 		return ret;
867 
868 	ret = iio_gts_get_int_time_gain_multiplier_by_sel(gts, time_sel);
869 	if (ret < 0)
870 		return ret;
871 
872 	mul = ret;
873 
874 	ret = gain_get_scale_fraction(gts->max_scale, scale_linear, mul, gain);
875 	if (ret)
876 		return ret;
877 
878 	if (!iio_gts_valid_gain(gts, *gain))
879 		return -EINVAL;
880 
881 	return 0;
882 }
883 
884 /**
885  * iio_gts_find_gain_sel_for_scale_using_time - Fetch gain selector.
886  * @gts:	Gain time scale descriptor
887  * @time_sel:	Integration time selector corresponding to the time gain is
888  *		searched for
889  * @scale_int:	Integral part of the scale (typically val1)
890  * @scale_nano:	Fractional part of the scale (nano or ppb)
891  * @gain_sel:	Pointer to value where gain selector is stored.
892  *
893  * See iio_gts_find_gain_for_scale_using_time() for more information
894  */
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)895 int iio_gts_find_gain_sel_for_scale_using_time(struct iio_gts *gts, int time_sel,
896 					       int scale_int, int scale_nano,
897 					       int *gain_sel)
898 {
899 	int gain, ret;
900 
901 	ret = iio_gts_find_gain_for_scale_using_time(gts, time_sel, scale_int,
902 						     scale_nano, &gain);
903 	if (ret)
904 		return ret;
905 
906 	ret = iio_gts_find_sel_by_gain(gts, gain);
907 	if (ret < 0)
908 		return ret;
909 
910 	*gain_sel = ret;
911 
912 	return 0;
913 }
914 EXPORT_SYMBOL_NS_GPL(iio_gts_find_gain_sel_for_scale_using_time, IIO_GTS_HELPER);
915 
iio_gts_get_total_gain(struct iio_gts * gts,int gain,int time)916 static int iio_gts_get_total_gain(struct iio_gts *gts, int gain, int time)
917 {
918 	const struct iio_itime_sel_mul *itime;
919 
920 	if (!iio_gts_valid_gain(gts, gain))
921 		return -EINVAL;
922 
923 	if (!gts->num_itime)
924 		return gain;
925 
926 	itime = iio_gts_find_itime_by_time(gts, time);
927 	if (!itime)
928 		return -EINVAL;
929 
930 	return gain * itime->mul;
931 }
932 
iio_gts_get_scale_linear(struct iio_gts * gts,int gain,int time,u64 * scale)933 static int iio_gts_get_scale_linear(struct iio_gts *gts, int gain, int time,
934 				    u64 *scale)
935 {
936 	int total_gain;
937 	u64 tmp;
938 
939 	total_gain = iio_gts_get_total_gain(gts, gain, time);
940 	if (total_gain < 0)
941 		return total_gain;
942 
943 	tmp = gts->max_scale;
944 
945 	do_div(tmp, total_gain);
946 
947 	*scale = tmp;
948 
949 	return 0;
950 }
951 
952 /**
953  * iio_gts_get_scale - get scale based on integration time and HW-gain
954  * @gts:	Gain time scale descriptor
955  * @gain:	HW-gain for which the scale is computed
956  * @time:	Integration time for which the scale is computed
957  * @scale_int:	Integral part of the scale (typically val1)
958  * @scale_nano:	Fractional part of the scale (nano or ppb)
959  *
960  * Compute scale matching the integration time and HW-gain given as parameter.
961  *
962  * Return: 0 on success.
963  */
iio_gts_get_scale(struct iio_gts * gts,int gain,int time,int * scale_int,int * scale_nano)964 int iio_gts_get_scale(struct iio_gts *gts, int gain, int time, int *scale_int,
965 		      int *scale_nano)
966 {
967 	u64 lin_scale;
968 	int ret;
969 
970 	ret = iio_gts_get_scale_linear(gts, gain, time, &lin_scale);
971 	if (ret)
972 		return ret;
973 
974 	return iio_gts_delinearize(lin_scale, NANO, scale_int, scale_nano);
975 }
976 EXPORT_SYMBOL_NS_GPL(iio_gts_get_scale, IIO_GTS_HELPER);
977 
978 /**
979  * iio_gts_find_new_gain_sel_by_old_gain_time - compensate for time change
980  * @gts:		Gain time scale descriptor
981  * @old_gain:		Previously set gain
982  * @old_time_sel:	Selector corresponding previously set time
983  * @new_time_sel:	Selector corresponding new time to be set
984  * @new_gain:		Pointer to value where new gain is to be written
985  *
986  * We may want to mitigate the scale change caused by setting a new integration
987  * time (for a light sensor) by also updating the (HW)gain. This helper computes
988  * new gain value to maintain the scale with new integration time.
989  *
990  * Return: 0 if an exactly matching supported new gain was found. When a
991  * non-zero value is returned, the @new_gain will be set to a negative or
992  * positive value. The negative value means that no gain could be computed.
993  * Positive value will be the "best possible new gain there could be". There
994  * can be two reasons why finding the "best possible" new gain is not deemed
995  * successful. 1) This new value cannot be supported by the hardware. 2) The new
996  * gain required to maintain the scale would not be an integer. In this case,
997  * the "best possible" new gain will be a floored optimal gain, which may or
998  * may not be supported by the hardware.
999  */
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)1000 int iio_gts_find_new_gain_sel_by_old_gain_time(struct iio_gts *gts,
1001 					       int old_gain, int old_time_sel,
1002 					       int new_time_sel, int *new_gain)
1003 {
1004 	const struct iio_itime_sel_mul *itime_old, *itime_new;
1005 	u64 scale;
1006 	int ret;
1007 
1008 	*new_gain = -1;
1009 
1010 	itime_old = iio_gts_find_itime_by_sel(gts, old_time_sel);
1011 	if (!itime_old)
1012 		return -EINVAL;
1013 
1014 	itime_new = iio_gts_find_itime_by_sel(gts, new_time_sel);
1015 	if (!itime_new)
1016 		return -EINVAL;
1017 
1018 	ret = iio_gts_get_scale_linear(gts, old_gain, itime_old->time_us,
1019 				       &scale);
1020 	if (ret)
1021 		return ret;
1022 
1023 	ret = gain_get_scale_fraction(gts->max_scale, scale, itime_new->mul,
1024 				      new_gain);
1025 	if (ret)
1026 		return ret;
1027 
1028 	if (!iio_gts_valid_gain(gts, *new_gain))
1029 		return -EINVAL;
1030 
1031 	return 0;
1032 }
1033 EXPORT_SYMBOL_NS_GPL(iio_gts_find_new_gain_sel_by_old_gain_time, IIO_GTS_HELPER);
1034 
1035 /**
1036  * iio_gts_find_new_gain_by_old_gain_time - compensate for time change
1037  * @gts:		Gain time scale descriptor
1038  * @old_gain:		Previously set gain
1039  * @old_time:		Selector corresponding previously set time
1040  * @new_time:		Selector corresponding new time to be set
1041  * @new_gain:		Pointer to value where new gain is to be written
1042  *
1043  * We may want to mitigate the scale change caused by setting a new integration
1044  * time (for a light sensor) by also updating the (HW)gain. This helper computes
1045  * new gain value to maintain the scale with new integration time.
1046  *
1047  * Return: 0 if an exactly matching supported new gain was found. When a
1048  * non-zero value is returned, the @new_gain will be set to a negative or
1049  * positive value. The negative value means that no gain could be computed.
1050  * Positive value will be the "best possible new gain there could be". There
1051  * can be two reasons why finding the "best possible" new gain is not deemed
1052  * successful. 1) This new value cannot be supported by the hardware. 2) The new
1053  * gain required to maintain the scale would not be an integer. In this case,
1054  * the "best possible" new gain will be a floored optimal gain, which may or
1055  * may not be supported by the hardware.
1056  */
iio_gts_find_new_gain_by_old_gain_time(struct iio_gts * gts,int old_gain,int old_time,int new_time,int * new_gain)1057 int iio_gts_find_new_gain_by_old_gain_time(struct iio_gts *gts, int old_gain,
1058 					   int old_time, int new_time,
1059 					   int *new_gain)
1060 {
1061 	const struct iio_itime_sel_mul *itime_new;
1062 	u64 scale;
1063 	int ret;
1064 
1065 	*new_gain = -1;
1066 
1067 	itime_new = iio_gts_find_itime_by_time(gts, new_time);
1068 	if (!itime_new)
1069 		return -EINVAL;
1070 
1071 	ret = iio_gts_get_scale_linear(gts, old_gain, old_time, &scale);
1072 	if (ret)
1073 		return ret;
1074 
1075 	ret = gain_get_scale_fraction(gts->max_scale, scale, itime_new->mul,
1076 				      new_gain);
1077 	if (ret)
1078 		return ret;
1079 
1080 	if (!iio_gts_valid_gain(gts, *new_gain))
1081 		return -EINVAL;
1082 
1083 	return 0;
1084 }
1085 EXPORT_SYMBOL_NS_GPL(iio_gts_find_new_gain_by_old_gain_time, IIO_GTS_HELPER);
1086 
1087 MODULE_LICENSE("GPL");
1088 MODULE_AUTHOR("Matti Vaittinen <mazziesaccount@gmail.com>");
1089 MODULE_DESCRIPTION("IIO light sensor gain-time-scale helpers");
1090