Skip to contentSkip to conversation

Add E notation support to kstrtodec64() and IIO sysfs writes

RFC PATCH Superseded Rodrigo Alencar 3 participants 13 messages Oct 20 – Oct 21

Subsystems (2)

v3 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v3 cover Add E notation support to kstrtodec64() and IIO sysfs writes

This series lets kstrtoudec64() and kstrtodec64() accept numbers in E notation (scientific notation), such as "2.7e9", "1.5E-3" or "1e+16". It then moves the IIO core fixed-point parser over to kstrtodec64(), so every IIO channel attribute written through iio_write_channel_info() accepts that format as well.

There are two main motivations:

1. Shell usage of sysfs attributes

Some IIO devices take values that are long to type and easy to get wrong in plain decimal. A frequency synthesizer or DDS might be programmed in the GHz range, and a scale might be a tiny fraction. With this series one can write:

echo 2.7e9 > out_altvoltage0_frequency
echo 1.5e-6 > in_voltage0_scale

instead of counting zeros in "2700000000" or "0.0000015". It also works with shell tools that print in E notation by default, such as printf's %g conversion ("printf '%g' 2700000000" prints "2.7e+09") and awk, whose default output format ("%.6g") prints non-integral values like 1234567.5 as "1.23457e+06".

2. Userspace software that formats numbers automatically

Many languages and libraries switch to E notation when converting floating point numbers to strings, without the caller asking for it:

- Python: str() and repr() of a float use E notation for exponents

     below -4 or from 16 up, e.g. str(0.00001) == '1e-05' and
     str(1e16) == '1e+16'. Writing such a value straight to an attribute
     with open(...).write(str(value)) currently fails with -EINVAL.
     The same applies to NumPy scalars and to f-strings with the 'g'
     format spec (f"{2.7e9:g}" == '2.7e+09').

- JavaScript/Node.js: Number.prototype.toString() uses E notation for magnitudes from 1e21 up or below 1e-6, e.g. String(1e-7) gives '1e-7'.
- C/C++ applications and bindings that use printf("%g") or std::to_chars() with general formatting, as well as MATLAB/Octave and other numeric environments that print in a "short" form.

Today these values have to be reformatted by the application, or are rejected by the kernel without warning. Accepting E notation in the kernel makes the IIO sysfs ABI more robust to this common behaviour.

The exponent is folded into the requested decimal scale, so no floating point arithmetic is involved. Overflow is reported as -ERANGE and a malformed exponent ("1e", "1e+") as -EINVAL.

Digits beyond the resulting precision are now rounded to nearest, ties to even, instead of truncated (new patch 2). This follows from the second motivation: floating point values printed by userspace often end just below the intended decimal value. "%.17g" of 0.3 gives "0.29999999999999999", which truncation turns into 299999 at micro precision instead of 300000. E notation makes this more visible, since a negative exponent can drop integer digits: with truncation, "19e-1" written to an integer attribute gives 1. Round-half-even is the IEEE 754 default, as used by strtod() and printf(), it is unbiased and symmetric for negative values, and inputs that fit the precision (including values read back from sysfs) are parsed exactly as before. The rounding is done before the IIO core conversion, so IIO fixed-point writes change behaviour only once.

This changes existing kstrtodec64() behaviour, so feedback is welcome on whether it should stay in this series or be sent as a follow-up.

---
Changes in v3:
- New patch: round to nearest, ties to even, instead of truncating.
- Amend kstrtox E notation tests and IIO channel write tests for rounding.
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- More test cases on test-kstrtox.c.
- Rework fallback logic when parsing integers.
- Add iio kunit test cases for iio_write_channel_info()
- Link to v1: https://patch.msgid.link/[email protected]

---
Rodrigo Alencar (5):
lib: kstrtox: support E notation in kstrtoudec64() and kstrtodec64()
lib: kstrtox: round to nearest, ties to even in kstrto[u]dec64()
lib: test-kstrtox: add E notation tests for kstrto[u]dec64()
iio: core: use kstrtodec64() to parse fixed-point values
iio: test: add kunit tests for channel info writes

 MAINTAINERS                               |   1 +
 drivers/iio/iio_core.h                    |   3 +
 drivers/iio/industrialio-core.c           | 164 +++++++-------
 drivers/iio/test/Kconfig                  |  14 ++
 drivers/iio/test/Makefile                 |   1 +
 drivers/iio/test/iio-test-channel-write.c | 360 ++++++++++++++++++++++++++++++
 lib/kstrtox.c                             | 107 ++++++---
 lib/test-kstrtox.c                        | 119 ++++++++--
 8 files changed, 650 insertions(+), 119 deletions(-)

---
base-commit: 43ffda3c7f8456bbe641ae8249a077a361b97880
change-id: 20261001-e-notation-0f07757910e5

Best regards,

Signature · 1 line
Rodrigo Alencar <[email protected]>
#1 lore raw

RFC PATCH v3 1/5 lib: kstrtox: support E notation in kstrtoudec64() and kstrtodec64()

Allow decimal strings to carry an exponent suffix, such as "2.7e10" or "271828e-5", in kstrtoudec64() and kstrtodec64(). The exponent is added to the requested scale to work out how many integer and fractional digits are consumed. A negative effective exponent drops integer digits. Digits beyond the resulting precision are truncated, as before.

The digits are now scanned first and the string termination is checked before any conversion. A missing or malformed exponent ("1e", "1e+") returns -EINVAL. An exponent that overflows when added to the scale, or that makes the result exceed 64 bits, returns -ERANGE.

---
 lib/kstrtox.c | 71 +++++++++++++++++++++++++++++++++++++++++------------------
 1 file changed, 49 insertions(+), 22 deletions(-)
lib/kstrtox.c +49 -22
index bac1c057e1b0..730b0c002d44 100644
@@ -395,41 +395,68 @@ int kstrtobool(const char *s, bool *res)
 }
 EXPORT_SYMBOL(kstrtobool);
 
+static int _skip_digits(const char **s)
+{
+	const char *start = *s;
+
+	while (isdigit(**s))
+		(*s)++;
+
+	return *s - start;
+}
+
 static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res)
 {
-	unsigned int rv_int, rv_frac;
+	const char *s_int, *s_frac;
+	int len_int, len_frac;
+	unsigned int rv;
 	u64 _res = 0;
+	int exp = 0;
+	int ret;
 
-	rv_int = _parse_integer(s, 10, &_res);
-	if (rv_int & KSTRTOX_OVERFLOW)
-		return -ERANGE;
-	s += rv_int;
+	s_int = s;
+	len_int = _skip_digits(&s);
 
 	if (*s == '.')
 		s++; /* skip decimal point */
 
-	rv_frac = _parse_integer(s, 10, &_res, scale, _res);
-	if (rv_frac & KSTRTOX_OVERFLOW)
+	s_frac = s;
+	len_frac = _skip_digits(&s);
+
+	if (!len_int && !len_frac)
+		return -EINVAL;
+
+	if (*s == 'e' || *s == 'E') { /* E Notation */
+		s++;
+		ret = kstrtoint(s, 10, &exp);
+		if (ret)
+			return ret;
+	} else { /* verify termination */
+		if (*s == '\n')
+			s++;
+		if (*s)
+			return -EINVAL;
+	}
+
+	if (check_add_overflow(exp, (int)scale, &exp))
 		return -ERANGE;
-	s += rv_frac;
 
-	/*
-	 * Check input beyond rv_int and rv_frac to cover cases like ".5" with
-	 * scale 0, which is considered a valid input, being parsed as 0.
-	 */
-	if (!rv_int && !rv_frac && !isdigit(*s))
-		return -EINVAL;
+	if (exp < 0) {
+		len_int = max(len_int + exp, 0);
+		exp = 0;
+	}
 
-	while (isdigit(*s)) /* truncate digits */
-		s++;
+	rv = _parse_integer(s_int, 10, &_res, len_int);
+	if (rv & KSTRTOX_OVERFLOW)
+		return -ERANGE;
 
-	if (*s == '\n')
-		s++;
-	if (*s)
-		return -EINVAL;
+	rv = _parse_integer(s_frac, 10, &_res, exp, _res);
+	if (rv & KSTRTOX_OVERFLOW)
+		return -ERANGE;
 
-	if (_res && ((scale - rv_frac) > 19 /* log10(2^64) = 19.26 */ ||
-		     check_mul_overflow(_res, int_pow(10, scale - rv_frac), &_res)))
+	exp -= rv;
+	if (_res && (exp > 19 /* log10(2^64) = 19.26 */ ||
+		     check_mul_overflow(_res, int_pow(10, exp), &_res)))
 		return -ERANGE;
 
 	*res = _res;
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH RFC v3 1/5] lib: kstrtox: support E notation in kstrtoudec64() and kstrtodec64()

Quoted 11 lines · On Tue, Oct 20, 2026 at 09:26:59AM -0300, Rodrigo Alencar via B4 Relay wrote:

Allow decimal strings to carry an exponent suffix, such as "2.7e10" or "271828e-5", in kstrtoudec64() and kstrtodec64(). The exponent is added to the requested scale to work out how many integer and fractional digits are consumed. A negative effective exponent drops integer digits. Digits beyond the resulting precision are truncated, as before.

The digits are now scanned first and the string termination is checked before any conversion. A missing or malformed exponent ("1e", "1e+") returns -EINVAL. An exponent that overflows when added to the scale, or that makes the result exceed 64 bits, returns -ERANGE.

...

Quoted 1 line

+static int _skip_digits(const char **s)

Leading underscore is unneeded here.

...

Quoted 9 lines

static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res) {

lib/kstrtox.c +5 -1
-	unsigned int rv_int, rv_frac;
+	const char *s_int, *s_frac;
+	int len_int, len_frac;
+	unsigned int rv;
 	u64 _res = 0;
+	int exp = 0;
+	int ret;

lib/kstrtox.c int kstrtobool(const char *s, bool *res) · line 421

Quoted 10 lines
lib/kstrtox.c +2 -4
 
-	rv_int = _parse_integer(s, 10, &_res);
-	if (rv_int & KSTRTOX_OVERFLOW)
-		return -ERANGE;
-	s += rv_int;
+	s_int = s;
+	len_int = _skip_digits(&s);
 
 	if (*s == '.')
 		s++; /* skip decimal point */

So, I know that '.NNN' is valid notation, but is 'NNN.'?

lib/kstrtox.c int kstrtobool(const char *s, bool *res) · line 429

Quoted 9 lines
lib/kstrtox.c +7 -2
-	rv_frac = _parse_integer(s, 10, &_res, scale, _res);
-	if (rv_frac & KSTRTOX_OVERFLOW)
+	s_frac = s;
+	len_frac = _skip_digits(&s);
+
+	if (!len_int && !len_frac)
+		return -EINVAL;
+
+	if (*s == 'e' || *s == 'E') { /* E Notation */

You may use _tolower() helper (yes, the one with a single leading underscore).

lib/kstrtox.c int kstrtobool(const char *s, bool *res) · line 433

Quoted 4 lines
lib/kstrtox.c +4 -0
+		s++;
+		ret = kstrtoint(s, 10, &exp);
+		if (ret)
+			return ret;

So, with the above in mind, this may lead to 'NNN.e10' input which I find a bit confusing.

Quoted 42 lines
lib/kstrtox.c +21 -15
+	} else { /* verify termination */
+		if (*s == '\n')
+			s++;
+		if (*s)
+			return -EINVAL;
+	}
+
+	if (check_add_overflow(exp, (int)scale, &exp))
 		return -ERANGE;
-	s += rv_frac;
 
-	/*
-	 * Check input beyond rv_int and rv_frac to cover cases like ".5" with
-	 * scale 0, which is considered a valid input, being parsed as 0.
-	 */
-	if (!rv_int && !rv_frac && !isdigit(*s))
-		return -EINVAL;
+	if (exp < 0) {
+		len_int = max(len_int + exp, 0);
+		exp = 0;
+	}
 
-	while (isdigit(*s)) /* truncate digits */
-		s++;
+	rv = _parse_integer(s_int, 10, &_res, len_int);
+	if (rv & KSTRTOX_OVERFLOW)
+		return -ERANGE;
 
-	if (*s == '\n')
-		s++;
-	if (*s)
-		return -EINVAL;
+	rv = _parse_integer(s_frac, 10, &_res, exp, _res);
+	if (rv & KSTRTOX_OVERFLOW)
+		return -ERANGE;
 
-	if (_res && ((scale - rv_frac) > 19 /* log10(2^64) = 19.26 */ ||
-		     check_mul_overflow(_res, int_pow(10, scale - rv_frac), &_res)))
+	exp -= rv;
+	if (_res && (exp > 19 /* log10(2^64) = 19.26 */ ||
+		     check_mul_overflow(_res, int_pow(10, exp), &_res)))
 		return -ERANGE;
Signature · 2 lines
With Best Regards,
Andy Shevchenko
#3 lore raw

Re: [PATCH RFC v3 1/5] lib: kstrtox: support E notation in kstrtoudec64() and kstrtodec64()

Quoted 12 lines · Andy Shevchenko
Quoted 11 lines · On Tue, Oct 20, 2026 at 09:26:59AM -0300, Rodrigo Alencar via B4 Relay wrote:

Allow decimal strings to carry an exponent suffix, such as "2.7e10" or "271828e-5", in kstrtoudec64() and kstrtodec64(). The exponent is added to the requested scale to work out how many integer and fractional digits are consumed. A negative effective exponent drops integer digits. Digits beyond the resulting precision are truncated, as before.

The digits are now scanned first and the string termination is checked before any conversion. A missing or malformed exponent ("1e", "1e+") returns -EINVAL. An exponent that overflows when added to the scale, or that makes the result exceed 64 bits, returns -ERANGE.

...

Quoted 17 lines
Quoted 17 lines

static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res) {

lib/kstrtox.c +7 -5
-	unsigned int rv_int, rv_frac;
+	const char *s_int, *s_frac;
+	int len_int, len_frac;
+	unsigned int rv;
 	u64 _res = 0;
+	int exp = 0;
+	int ret;
 
-	rv_int = _parse_integer(s, 10, &_res);
-	if (rv_int & KSTRTOX_OVERFLOW)
-		return -ERANGE;
-	s += rv_int;
+	s_int = s;
+	len_int = _skip_digits(&s);
Quoted 4 lines

lib/kstrtox.c int kstrtobool(const char *s, bool *res) · line 421

Quoted 2 lines
lib/kstrtox.c +0 -0
 	if (*s == '.')
 		s++; /* skip decimal point */

So, I know that '.NNN' is valid notation, but is 'NNN.'?

It looks weird, but that is also valid notation.

Quoted 12 lines

lib/kstrtox.c int kstrtobool(const char *s, bool *res) · line 429

Quoted 10 lines
lib/kstrtox.c +7 -2
-	rv_frac = _parse_integer(s, 10, &_res, scale, _res);
-	if (rv_frac & KSTRTOX_OVERFLOW)
+	s_frac = s;
+	len_frac = _skip_digits(&s);
+
+	if (!len_int && !len_frac)
+		return -EINVAL;
+
+	if (*s == 'e' || *s == 'E') { /* E Notation */

You may use _tolower() helper (yes, the one with a single leading underscore).

ok, so we only check for _tolower(*s) == 'e'

Quoted 7 lines

lib/kstrtox.c int kstrtobool(const char *s, bool *res) · line 433

Quoted 4 lines
lib/kstrtox.c +4 -0
+		s++;
+		ret = kstrtoint(s, 10, &exp);
+		if (ret)
+			return ret;

So, with the above in mind, this may lead to 'NNN.e10' input which I find a bit confusing.

might be, but as mentioned, it is considered valid, e.g.:

- python:

	>>> x = 2.e10
	>>> print(x)
	20000000000.0
	>>> y = .5e-3
	>>> print(y)
	0.0005

- c++

	int main()
	{
	    float x = 2.e3;
	    std::cout<<"x = " << x << std::endl;

	    return 0;
	}

	x = 2000
Signature · 3 lines
Kind regards,

Rodrigo Alencar
#4 lore raw

RFC PATCH v3 2/5 lib: kstrtox: round to nearest, ties to even in kstrto[u]dec64()

In reply to Rodrigo Alencar

kstrtoudec64() and kstrtodec64() drop the digits beyond the requested scale, which truncates the result toward zero. The error is up to one unit in the last place and is always in the same direction.

This is easy to hit with values produced by userspace floating point formatting. Printing 0.3 with "%.17g" gives "0.29999999999999999", which is parsed as 299999 with a scale of 6 instead of 300000. With E notation a negative exponent can also drop integer digits, so "19e-1" with a scale of 0 gives 1 instead of 2.

Round the result to nearest instead, with ties to even. This is the IEEE 754 default rounding mode, as used by strtod() and printf(), and it does not bias results in either direction. The first discarded digit is known from where parsing stopped, so no extra pass over the string is
needed: the remaining digits are only checked when the first discarded digit is a 5. Since round-half-even is symmetric, kstrtodec64() keeps rounding the magnitude and negates it.

Inputs that fit within the scale are parsed exactly as before. An input that rounds up past the type limit, such as "18446744073.7095516155" with a scale of 9, now returns -ERANGE.

Update the existing truncation test cases and add cases for ties and for rounding at the type limits.

---
 lib/kstrtox.c      | 40 ++++++++++++++++++++++++++++++++++------
 lib/test-kstrtox.c | 48 +++++++++++++++++++++++++++++++++++-------------
 2 files changed, 69 insertions(+), 19 deletions(-)
lib/kstrtox.c +34 -6
index 730b0c002d44..be193b95b8c7 100644
@@ -405,9 +405,22 @@ static int _skip_digits(const char **s)
 	return *s - start;
 }
 
+static bool _round_half_even(const char *p, const char *end, u64 res)
+{
+	if (p == end || *p < '5')
+		return false;
+	if (*p++ > '5')
+		return true;
+	/* tie: any nonzero digit after it breaks it, skipping the decimal point */
+	for (; p < end; p++)
+		if (*p != '0' && *p != '.')
+			return true;
+	return res & 1;
+}
+
 static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res)
 {
-	const char *s_int, *s_frac;
+	const char *s_int, *s_frac, *s_end, *s_round;
 	int len_int, len_frac;
 	unsigned int rv;
 	u64 _res = 0;
@@ -422,6 +435,7 @@ static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res)
 
 	s_frac = s;
 	len_frac = _skip_digits(&s);
+	s_end = s;
 
 	if (!len_int && !len_frac)
 		return -EINVAL;
@@ -442,8 +456,16 @@ static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res)
 		return -ERANGE;
 
 	if (exp < 0) {
-		len_int = max(len_int + exp, 0);
+		len_int += exp;
 		exp = 0;
+		if (len_int < 0) {
+			s_round = s_end;
+			len_int = 0;
+		} else {
+			s_round = s_int + len_int;
+		}
+	} else {
+		s_round = s_frac;
 	}
 
 	rv = _parse_integer(s_int, 10, &_res, len_int);
@@ -454,6 +476,10 @@ static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res)
 	if (rv & KSTRTOX_OVERFLOW)
 		return -ERANGE;
 
+	if (_round_half_even(s_round + rv, s_end, _res) &&
+	    check_add_overflow(_res, 1, &_res))
+		return -ERANGE;
+
 	exp -= rv;
 	if (_res && (exp > 19 /* log10(2^64) = 19.26 */ ||
 		     check_mul_overflow(_res, int_pow(10, exp), &_res)))
@@ -473,7 +499,8 @@ static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res)
  *
  * For example, a scale of 3 with input "123.45" results in 123450. Note that
  * trailing zeros in the fractional part input to match the scale are not
- * required. Also, digits beyond the specified scale are ignored.
+ * required. Also, digits beyond the specified scale are rounded to nearest,
+ * ties to even.
  *
  * Return: 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
  */
@@ -494,9 +521,10 @@ EXPORT_SYMBOL(kstrtoudec64);
  * @scale: The number of digits to the right of the decimal point.
  * @res: Where to write the result of the conversion on success.
  *
- * For example, a scale of 4 with input "-3.141592" results in -31415. Note
- * that digits beyond the specified scale are ignored. Also, trailing zeros in
- * the fractional part input to match the scale are not required.
+ * For example, a scale of 4 with input "-3.141592" results in -31416. Note
+ * that digits beyond the specified scale are rounded to nearest, ties to
+ * even. Also, trailing zeros in the fractional part input to match the scale
+ * are not required.
  *
  * Return: 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
  */
lib/test-kstrtox.c +35 -13

91 lines not on this page · raw message

Signature · 1 line
2.43.0
#5 lore raw

Re: [PATCH RFC v3 2/5] lib: kstrtox: round to nearest, ties to even in kstrto[u]dec64()

Quoted 24 lines · On Tue, Oct 20, 2026 at 09:27:00AM -0300, Rodrigo Alencar via B4 Relay wrote:

kstrtoudec64() and kstrtodec64() drop the digits beyond the requested scale, which truncates the result toward zero. The error is up to one unit in the last place and is always in the same direction.

This is easy to hit with values produced by userspace floating point formatting. Printing 0.3 with "%.17g" gives "0.29999999999999999", which is parsed as 299999 with a scale of 6 instead of 300000. With E notation a negative exponent can also drop integer digits, so "19e-1" with a scale of 0 gives 1 instead of 2.

Round the result to nearest instead, with ties to even. This is the IEEE 754 default rounding mode, as used by strtod() and printf(), and it does not bias results in either direction. The first discarded digit is known from where parsing stopped, so no extra pass over the string is
needed: the remaining digits are only checked when the first discarded digit is a 5. Since round-half-even is symmetric, kstrtodec64() keeps rounding the magnitude and negates it.

Inputs that fit within the scale are parsed exactly as before. An input that rounds up past the type limit, such as "18446744073.7095516155" with a scale of 9, now returns -ERANGE.

Update the existing truncation test cases and add cases for ties and for rounding at the type limits.

...

lib/kstrtox.c static int _skip_digits(const char **s) · line 412

Quoted 5 lines
lib/kstrtox.c +5 -0
+static bool _round_half_even(const char *p, const char *end, u64 res)
+{
+	if (p == end || *p < '5')
+		return false;
+	if (*p++ > '5')

This hidden ++ makes the whole if chain to be strict in order, gives less readability and flexibility in my opinion.

Review

Quoted 1 line
(quoted diff) +1 -0
+		return true;

So, this can be split to

	// Does this need to be first?
	if (p == end)
		return false;

	if (*p < '5')
		return false;
	if (*p > '5')
		return true;

	while (++p < end) {
		...
	}

lib/kstrtox.c static int _skip_digits(const char **s) · line 416

Quoted 3 lines
lib/kstrtox.c +3 -0
+	/* tie: any nonzero digit after it breaks it, skipping the decimal point */
+	for (; p < end; p++)
+		if (*p != '0' && *p != '.')

This is a loop, so this also passes '.0.0.' case and some other similar to it. Is this a problem?

Review

Quoted 2 lines
(quoted diff) +2 -0
+			return true;
+	return res & 1;

So, this res is used only once to get a parity. But this doesn't semantically sound like boolean to me. What if we actually return 0 or 1 from this function and use its output directly in the check_add_overflow()?

Quoted 1 line

+}

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#6 lore raw

Re: [PATCH RFC v3 2/5] lib: kstrtox: round to nearest, ties to even in kstrto[u]dec64()

Quoted 30 lines · Andy Shevchenko
Quoted 24 lines · On Tue, Oct 20, 2026 at 09:27:00AM -0300, Rodrigo Alencar via B4 Relay wrote:

kstrtoudec64() and kstrtodec64() drop the digits beyond the requested scale, which truncates the result toward zero. The error is up to one unit in the last place and is always in the same direction.

This is easy to hit with values produced by userspace floating point formatting. Printing 0.3 with "%.17g" gives "0.29999999999999999", which is parsed as 299999 with a scale of 6 instead of 300000. With E notation a negative exponent can also drop integer digits, so "19e-1" with a scale of 0 gives 1 instead of 2.

Round the result to nearest instead, with ties to even. This is the IEEE 754 default rounding mode, as used by strtod() and printf(), and it does not bias results in either direction. The first discarded digit is known from where parsing stopped, so no extra pass over the string is
needed: the remaining digits are only checked when the first discarded digit is a 5. Since round-half-even is symmetric, kstrtodec64() keeps rounding the magnitude and negates it.

Inputs that fit within the scale are parsed exactly as before. An input that rounds up past the type limit, such as "18446744073.7095516155" with a scale of 9, now returns -ERANGE.

Update the existing truncation test cases and add cases for ties and for rounding at the type limits.

...

Quoted 1 line

+static bool _round_half_even(const char *p, const char *end, u64 res)

...

Quoted 6 lines

lib/kstrtox.c static int _skip_digits(const char **s) · line 416

Quoted 3 lines
lib/kstrtox.c +3 -0
+	/* tie: any nonzero digit after it breaks it, skipping the decimal point */
+	for (; p < end; p++)
+		if (*p != '0' && *p != '.')

This is a loop, so this also passes '.0.0.' case and some other similar to it. Is this a problem?

no, string validation has been done before at this point.

Quoted 7 lines

Review

Quoted 3 lines
(quoted diff) +2 -0
+			return true;
+	return res & 1;

So, this res is used only once to get a parity. But this doesn't semantically sound like boolean to me. What if we actually return 0 or 1 from this function and use its output directly in the check_add_overflow()?

Yes, if it is fine to always take the path to check_add_overflow().

Signature · 3 lines
Kind regards,

Rodrigo Alencar
#7 lore raw

RFC PATCH v3 3/5 lib: test-kstrtox: add E notation tests for kstrto[u]dec64()

In reply to Rodrigo Alencar

Cover E notation parsing in kstrtoudec64() and kstrtodec64(): positive, zero and negative exponents, upper case 'E', an explicit '+' sign, rounding (ties to even) of integer digits dropped by negative exponents, large values, and failures for overflowing and invalid inputs.

---
 lib/test-kstrtox.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 72 insertions(+), 1 deletion(-)
lib/test-kstrtox.c +72 -1
index 1f176b232085..5365d020746d 100644
@@ -780,7 +780,36 @@ static void __init test_kstrtoudec64_ok(void)
 		{"0.0000000000000000000012345",	23,	123},
 		/* rounding with many excess digits */
 		{"0.00000000000000000000000000000000423",	34,	42},
-		{"1.99999999999999999999999999999999999",	3,	2000},
+		/* E notation: positive exponent, no fraction */
+		{"1e3",			3,	1000000ULL},
+		{"42e2",		3,	4200000ULL},
+		/* E notation: positive exponent with fraction */
+		{"2.718e3",		3,	2718000ULL},
+		{"1.5e2",		1,	1500ULL},
+		/* E notation: uppercase E */
+		{"1E3",			3,	1000000ULL},
+		/* E notation: explicit positive exponent sign */
+		{"1e+3",		3,	1000000ULL},
+		/* E notation: zero exponent */
+		{"1.5e0",		1,	15ULL},
+		/* E notation: negative exponent shifts decimal left */
+		{"271828e-5",		3,	2718ULL},
+		{"2.71828e-1",		3,	272ULL},
+		{"270e-2",		3,	2700ULL},
+		/* E notation: negative exponent that rounds integer digits */
+		{"27e-4",		3,	3ULL},
+		{"19e-1",		0,	2ULL},
+		/* E notation: ties to even on integer digits */
+		{"125e-1",		0,	12ULL},
+		{"135e-1",		0,	14ULL},
+		{"25.0001e-1",		0,	3ULL},
+		/* E notation: negative exponent below 1 ULP rounds to 0 */
+		{"1e-5",		3,	0ULL},
+		{"5e-1",		0,	0ULL},
+		{"5e-2",		0,	0ULL},
+		{"6e-1",		0,	1ULL},
+		/* E notation: large value (27 GHz in micro Hz) */
+		{"2.7e10",		6,	27000000000000000ULL},
 	};
 	TEST_OK(kstrtoudec64, u64, "%llu", test_udec64_ok);
 }
@@ -814,6 +843,17 @@ static void __init test_kstrtoudec64_fail(void)
 		{"0.2",				20},
 		{"0.18446744073709551616",	20},
 		{"1",				20},
+		/* E notation: exponent causes overflow */
+		{"1e21",			1},
+		{"2e20",			1},
+		/* E notation: no digits after exponent marker */
+		{"1e",			3},
+		/* E notation: sign only after exponent marker */
+		{"1e+",			3},
+		{"1e-",			3},
+		/* E notation: misc */
+		{"1ee",			3}, /* double 'e' */
+		{"1e+0b",		3}, /* hex character after exponent */
 	};
 	TEST_FAIL(kstrtoudec64, u64, "%llu", test_udec64_fail);
 }
@@ -873,6 +913,27 @@ static void __init test_kstrtodec64_ok(void)
 		{"-0.00000000000000000001",	20,	-1},
 		{"0.009223372036854775807",	21,	LLONG_MAX},
 		{"-0.009223372036854775808",	21,	LLONG_MIN},
+		/* E notation: positive number */
+		{"1e3",			3,	1000000LL},
+		{"2.7e3",		3,	2700000LL},
+		{"1.5e0",		1,	15LL},
+		/* E notation: negative number with positive exponent */
+		{"-1e3",		3,	-1000000LL},
+		{"-2.7e3",		3,	-2700000LL},
+		/* E notation: negative exponent */
+		{"27e-1",		3,	2700LL},
+		{"-27e-1",		3,	-2700LL},
+		{"2.7e-1",		3,	270LL},
+		{"-2.7e-1",		3,	-270LL},
+		/* E notation: negative exponent rounds integer digits */
+		{"-27e-4",		3,	-3LL},
+		{"-125e-1",		0,	-12LL},
+		{"-135e-1",		0,	-14LL},
+		/* E notation: negative exponent below 1 ULP rounds to 0 */
+		{"1e-5",		3,	0LL},
+		{"-1e-5",		3,	0LL},
+		{"-5e-1",		0,	0LL},
+		{"-6e-1",		0,	-1LL},
 	};
 	TEST_OK(kstrtodec64, s64, "%lld", test_dec64_ok);
 }
@@ -903,6 +964,16 @@ static void __init test_kstrtodec64_fail(void)
 		{"-0.1",			20},
 		{"0.09223372036854775808",	20},
 		{"-0.09223372036854775809",	20},
+		/* E notation: exponent causes overflow */
+		{"1e21",		1},
+		{"-1e21",		1},
+		/* E notation: no digits after exponent marker */
+		{"1e",			3},
+		{"1e+",			3},
+		{"1e-",			3},
+		/* E notation: misc */
+		{"1Ee+3",		3}, /* double 'e' with mixed case */
+		{"1e+0xa",		3}, /* hex number exponent */
 	};
 	TEST_FAIL(kstrtodec64, s64, "%lld", test_dec64_fail);
 }
Signature · 1 line
2.43.0
#8 lore raw

RFC PATCH v3 4/5 iio: core: use kstrtodec64() to parse fixed-point values

In reply to Rodrigo Alencar

Replace the open-coded __iio_str_to_fixpoint() parser with kstrtodec64(), so sysfs writes of fixed-point values also accept E notation.

The fractional part only keeps the sign when the integer part is zero, as before. The dB suffix for scale attributes is now handled by a separate __iio_str_to_fixpoint_units() helper. It strips an optional trailing newline and the "dB" or " dB" suffix before parsing.

When there is no fractional part (fract_mult == 0, or dec_scale == 0 for 64-bit values), try base-autodetecting kstrtoll() first so hexadecimal and octal input keeps its meaning ("010" is still 8). Fall back to kstrtodec64() on -EINVAL to accept E notation.

As a side effect, inputs that used to be rejected for integer-only attributes are now accepted. An invalid octal number such as "08" is parsed as decimal 8, and a fractional value such as "1.5" is rounded to 2.

---
 drivers/iio/industrialio-core.c | 155 ++++++++++++++++++++--------------------
 1 file changed, 79 insertions(+), 76 deletions(-)
drivers/iio/industrialio-core.c +79 -76
index d73f2541375f..ce5391b1ca34 100644
@@ -994,77 +994,6 @@ static ssize_t iio_read_channel_info_avail(struct device *dev,
 	}
 }
 
-/**
- * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
- * @str: The string to parse
- * @fract_mult: Multiplier for the first decimal place, should be a power of 10
- * @integer: The integer part of the number
- * @fract: The fractional part of the number
- * @scale_db: True if this should parse as dB
- *
- * Returns:
- * 0 on success, or a negative error code if the string could not be parsed.
- */
-static int __iio_str_to_fixpoint(const char *str, int fract_mult,
-				 int *integer, int *fract, bool scale_db)
-{
-	int i = 0, f = 0;
-	bool integer_part = true, negative = false;
-
-	if (fract_mult == 0) {
-		*fract = 0;
-
-		return kstrtoint(str, 0, integer);
-	}
-
-	if (str[0] == '-') {
-		negative = true;
-		str++;
-	} else if (str[0] == '+') {
-		str++;
-	}
-
-	while (*str) {
-		if ('0' <= *str && *str <= '9') {
-			if (integer_part) {
-				i = i * 10 + *str - '0';
-			} else {
-				f += fract_mult * (*str - '0');
-				fract_mult /= 10;
-			}
-		} else if (*str == '\n') {
-			if (*(str + 1) == '\0')
-				break;
-			return -EINVAL;
-		} else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
-			/* Ignore the dB suffix */
-			str += sizeof(" dB") - 1;
-			continue;
-		} else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
-			/* Ignore the dB suffix */
-			str += sizeof("dB") - 1;
-			continue;
-		} else if (*str == '.' && integer_part) {
-			integer_part = false;
-		} else {
-			return -EINVAL;
-		}
-		str++;
-	}
-
-	if (negative) {
-		if (i)
-			i = -i;
-		else
-			f = -f;
-	}
-
-	*integer = i;
-	*fract = f;
-
-	return 0;
-}
-
 /**
  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
  * @str: The string to parse
@@ -1078,10 +1007,76 @@ static int __iio_str_to_fixpoint(const char *str, int fract_mult,
 int iio_str_to_fixpoint(const char *str, int fract_mult,
 			int *integer, int *fract)
 {
-	return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
+	s64 dec64;
+	int ret;
+
+	if (fract_mult) {
+		/* scale = ffs(fract_mult) = ffs(10^n) = ffs(2^n * 5^n) = n + 1 */
+		ret = kstrtodec64(str, ffs(fract_mult), &dec64);
+		if (ret)
+			return ret;
+
+		dec64 = div_s64_rem(dec64, fract_mult * 10, fract);
+		/* only carry the sign in fract if the integer is zero */
+		if (dec64)
+			*fract = abs(*fract);
+	} else {
+		/* keep hex/octal support for integers */
+		ret = kstrtoll(str, 0, &dec64);
+		if (ret == -EINVAL)
+			ret = kstrtodec64(str, 0, &dec64);
+		if (ret)
+			return ret;
+
+		*fract = 0;
+	}
+
+	if (dec64 > INT_MAX || dec64 < INT_MIN)
+		return -ERANGE;
+
+	*integer = (int)dec64;
+
+	return 0;
 }
 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
 
+/**
+ * __iio_str_to_fixpoint_units() - Parse a fixed-point number with units from a string
+ * @str: The string to parse
+ * @units: The units to expect at the end of the string
+ * @fract_mult: Multiplier for the first decimal place, should be a power of 10
+ * @integer: The integer part of the number
+ * @fract: The fractional part of the number
+ *
+ * Returns:
+ * 0 on success, or a negative error code if the string could not be parsed.
+ */
+static int __iio_str_to_fixpoint_units(const char *str, const char *units,
+				       int fract_mult, int *integer, int *fract)
+{
+	size_t units_len = strlen(units);
+	size_t s_len = strlen(str);
+	const char *dec_str = str;
+	char buf[64];
+
+	if (s_len && str[s_len - 1] == '\n')
+		s_len--;
+
+	if (s_len > units_len &&
+	    !strncmp(str + s_len - units_len, units, units_len)) {
+		s_len -= units_len;
+		if (str[s_len - 1] == ' ')
+			s_len--;
+		if (s_len >= sizeof(buf))
+			return -EINVAL;
+		memcpy(buf, str, s_len);
+		buf[s_len] = '\0';
+		dec_str = buf;
+	}
+
+	return iio_str_to_fixpoint(dec_str, fract_mult, integer, fract);
+}
+
 static ssize_t iio_write_channel_info(struct device *dev,
 				      struct device_attribute *attr,
 				      const char *buf,
@@ -1143,17 +1138,25 @@ static ssize_t iio_write_channel_info(struct device *dev,
 			return -EINVAL;
 		integer = ch;
 	} else if (is_64bit) {
-		if (dec_scale)
+		if (dec_scale) {
 			ret = kstrtodec64(buf, dec_scale, &integer64);
-		else
+		} else {
+			/* keep hex/octal support for integers */
 			ret = kstrtoll(buf, 0, &integer64);
+			if (ret == -EINVAL)
+				ret = kstrtodec64(buf, dec_scale, &integer64);
+		}
 		if (ret)
 			return ret;
 
 		iio_val_s64_decompose(integer64, &integer, &fract);
 	} else {
-		ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
-					    scale_db);
+		if (scale_db)
+			ret = __iio_str_to_fixpoint_units(buf, "dB", fract_mult,
+							  &integer, &fract);
+		else
+			ret = iio_str_to_fixpoint(buf, fract_mult, &integer,
+						  &fract);
 		if (ret)
 			return ret;
 	}
Signature · 1 line
2.43.0
#9 lore raw

Re: [PATCH RFC v3 4/5] iio: core: use kstrtodec64() to parse fixed-point values

Quoted 19 lines · On 20/10/26 09:27, Rodrigo Alencar via B4 Relay wrote:

From: Rodrigo Alencar <[email protected]>

Replace the open-coded __iio_str_to_fixpoint() parser with kstrtodec64(), so sysfs writes of fixed-point values also accept E notation.

The fractional part only keeps the sign when the integer part is zero, as before. The dB suffix for scale attributes is now handled by a separate __iio_str_to_fixpoint_units() helper. It strips an optional trailing newline and the "dB" or " dB" suffix before parsing.

When there is no fractional part (fract_mult == 0, or dec_scale == 0 for 64-bit values), try base-autodetecting kstrtoll() first so hexadecimal and octal input keeps its meaning ("010" is still 8). Fall back to kstrtodec64() on -EINVAL to accept E notation.

As a side effect, inputs that used to be rejected for integer-only attributes are now accepted. An invalid octal number such as "08" is parsed as decimal 8, and a fractional value such as "1.5" is rounded to 2.

...

drivers/iio/industrialio-core.c static int __iio_str_to_fixpoint(const char *str, int fract_mult, · line 1015

Quoted 10 lines

int iio_str_to_fixpoint(const char *str, int fract_mult,

drivers/iio/industrialio-core.c +6 -1
 			int *integer, int *fract)
 {
-	return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
+	s64 dec64;
+	int ret;
+
+	if (fract_mult) {
+		/* scale = ffs(fract_mult) = ffs(10^n) = ffs(2^n * 5^n) = n + 1 */
+		ret = kstrtodec64(str, ffs(fract_mult), &dec64);

As sashiko pointed out, this is breaking some test cases under drivers/iio/test/iio-test-rescale.c because of the rounding case change. That is in fact an issue within the test itself, witch limits the parsing on 9 fractional digits only, requiring a relative ppm of a scaled value to be zero. I will have that test fixed in a precursor patch.

Quoted 3 lines
drivers/iio/industrialio-core.c +3 -0
+		if (ret)
+			return ret;
+

...

Signature · 3 lines
Kind regards,

Rodrigo Alencar
#10 lore raw

Re: [PATCH RFC v3 4/5] iio: core: use kstrtodec64() to parse fixed-point values

In reply to Rodrigo Alencar
Quoted 17 lines · On Tue, Oct 20, 2026 at 09:27:02AM -0300, Rodrigo Alencar via B4 Relay wrote:

Replace the open-coded __iio_str_to_fixpoint() parser with kstrtodec64(), so sysfs writes of fixed-point values also accept E notation.

The fractional part only keeps the sign when the integer part is zero, as before. The dB suffix for scale attributes is now handled by a separate __iio_str_to_fixpoint_units() helper. It strips an optional trailing newline and the "dB" or " dB" suffix before parsing.

When there is no fractional part (fract_mult == 0, or dec_scale == 0 for 64-bit values), try base-autodetecting kstrtoll() first so hexadecimal and octal input keeps its meaning ("010" is still 8). Fall back to kstrtodec64() on -EINVAL to accept E notation.

As a side effect, inputs that used to be rejected for integer-only attributes are now accepted. An invalid octal number such as "08" is parsed as decimal 8, and a fractional value such as "1.5" is rounded to 2.

...

Quoted 7 lines
drivers/iio/industrialio-core.c +7 -0
+	s64 dec64;
+	int ret;
+
+	if (fract_mult) {
+		/* scale = ffs(fract_mult) = ffs(10^n) = ffs(2^n * 5^n) = n + 1 */
+		ret = kstrtodec64(str, ffs(fract_mult), &dec64);
+		if (ret)

drivers/iio/industrialio-core.c static int __iio_str_to_fixpoint(const char *str, int fract_mult, · line 1026

Quoted 10 lines
drivers/iio/industrialio-core.c +10 -0
+			return ret;
+
+		dec64 = div_s64_rem(dec64, fract_mult * 10, fract);
+		/* only carry the sign in fract if the integer is zero */
+		if (dec64)
+			*fract = abs(*fract);
+	} else {
+		/* keep hex/octal support for integers */
+		ret = kstrtoll(str, 0, &dec64);
+		if (ret == -EINVAL)

The ret can be something else as well. Why only -EINVAL? Perhaps add a comment on top of if ()?

drivers/iio/industrialio-core.c static int __iio_str_to_fixpoint(const char *str, int fract_mult, · line 1037

Quoted 11 lines
drivers/iio/industrialio-core.c +11 -0
+			ret = kstrtodec64(str, 0, &dec64);
+		if (ret)
+			return ret;
+
+		*fract = 0;
+	}
+
+	if (dec64 > INT_MAX || dec64 < INT_MIN)
+		return -ERANGE;
+
+	*integer = (int)dec64;

Do you need casting?

...

Quoted 8 lines

+/**
+ * __iio_str_to_fixpoint_units() - Parse a fixed-point number with units from a string
+ * @str: The string to parse
+ * @units: The units to expect at the end of the string
+ * @fract_mult: Multiplier for the first decimal place, should be a power of 10
+ * @integer: The integer part of the number
+ * @fract: The fractional part of the number
+ *

Add a description with the examples, what can be the input and what is expected output.

Quoted 28 lines

+ * Returns:
+ * 0 on success, or a negative error code if the string could not be parsed.
+ */

drivers/iio/industrialio-core.c +25 -0
+static int __iio_str_to_fixpoint_units(const char *str, const char *units,
+				       int fract_mult, int *integer, int *fract)
+{
+	size_t units_len = strlen(units);
+	size_t s_len = strlen(str);
+	const char *dec_str = str;
+	char buf[64];
+
+	if (s_len && str[s_len - 1] == '\n')
+		s_len--;
+
+	if (s_len > units_len &&
+	    !strncmp(str + s_len - units_len, units, units_len)) {
+		s_len -= units_len;
+		if (str[s_len - 1] == ' ')
+			s_len--;
+		if (s_len >= sizeof(buf))
+			return -EINVAL;
+		memcpy(buf, str, s_len);
+		buf[s_len] = '\0';
+		dec_str = buf;
+	}
+
+	return iio_str_to_fixpoint(dec_str, fract_mult, integer, fract);
+}

...

drivers/iio/industrialio-core.c static ssize_t iio_write_channel_info(struct device *dev, · line 1150

Quoted 10 lines
drivers/iio/industrialio-core.c +6 -0
+		if (dec_scale) {
 			ret = kstrtodec64(buf, dec_scale, &integer64);
+		} else {
+			/* keep hex/octal support for integers */
 			ret = kstrtoll(buf, 0, &integer64);
+			if (ret == -EINVAL)
+				ret = kstrtodec64(buf, dec_scale, &integer64);
+		}
 		if (ret)
 			return ret;

This is a dup with the above, can we have a common helper?

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#11 lore raw

RFC PATCH v3 5/5 iio: test: add kunit tests for channel info writes

In reply to Rodrigo Alencar

Add a KUnit test suite covering iio_write_channel_info(), the sysfs store handler that parses a channel info value according to the format reported by write_raw_get_fmt() and hands it to write_raw(). The function is made visible to KUnit through VISIBLE_IF_KUNIT and EXPORT_SYMBOL_IF_KUNIT, so it stays static in regular builds.

The suite uses an unregistered iio_dev allocated on a KUnit device, with stub write_raw_get_fmt() and write_raw() callbacks that select the format under test and capture the parsed values. Cases are grouped by format:

- IIO_VAL_INT: decimal, hex and octal input, decimal fallback with rounding and E notation, and 32-bit range checks.
- IIO_VAL_INT_PLUS_MICRO / IIO_VAL_INT_PLUS_NANO: sign handling, rounding of extra digits (ties to even), E notation and malformed input.
- IIO_VAL_INT_PLUS_MICRO_DB: optional "dB" / " dB" suffix.
- IIO_VAL_CHAR: single character input.
- IIO_VAL_INT_64 and IIO_VAL_DECIMAL64_*: 64-bit values split into val/val2, including the S64_MAX / S64_MIN boundaries.

Further cases cover unsupported formats, the default micro precision used when write_raw_get_fmt() is absent, a missing write_raw(), and error propagation from write_raw().

---
 MAINTAINERS                               |   1 +
 drivers/iio/iio_core.h                    |   3 +
 drivers/iio/industrialio-core.c           |   9 +-
 drivers/iio/test/Kconfig                  |  14 ++
 drivers/iio/test/Makefile                 |   1 +
 drivers/iio/test/iio-test-channel-write.c | 360 ++++++++++++++++++++++++++++++
 6 files changed, 384 insertions(+), 4 deletions(-)
MAINTAINERS +1 -0
index 52024397dc78..ef8b912f593b 100644
@@ -12758,6 +12758,7 @@ M:	Rodrigo Alencar <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	drivers/iio/test/iio-test-channel-prefix.c
+F:	drivers/iio/test/iio-test-channel-write.c
 F:	drivers/iio/test/iio-test-format.c
 
 IIO UNIT CONVERTER
drivers/iio/iio_core.h +3 -0
index 59fa1bd9924b..08f0cc28ad8c 100644
@@ -114,6 +114,9 @@ ssize_t __iio_chan_prefix_emit(struct device *dev,
 			       const struct iio_chan_spec *chan,
 			       enum iio_shared_by shared_by,
 			       char *buf, size_t len);
+ssize_t iio_write_channel_info(struct device *dev,
+			       struct device_attribute *attr,
+			       const char *buf, size_t len);
 #endif
 
 #endif
drivers/iio/industrialio-core.c +5 -4
index ce5391b1ca34..6c8fe0949a06 100644
@@ -1077,10 +1077,10 @@ static int __iio_str_to_fixpoint_units(const char *str, const char *units,
 	return iio_str_to_fixpoint(dec_str, fract_mult, integer, fract);
 }
 
-static ssize_t iio_write_channel_info(struct device *dev,
-				      struct device_attribute *attr,
-				      const char *buf,
-				      size_t len)
+VISIBLE_IF_KUNIT
+ssize_t iio_write_channel_info(struct device *dev,
+			       struct device_attribute *attr,
+			       const char *buf, size_t len)
 {
 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
@@ -1168,6 +1168,7 @@ static ssize_t iio_write_channel_info(struct device *dev,
 
 	return len;
 }
+EXPORT_SYMBOL_IF_KUNIT(iio_write_channel_info);
 
 static
 int __iio_device_attr_init(struct device *dev,
drivers/iio/test/Kconfig +14 -0
index 04930b4fdd5d..af75c032a330 100644
@@ -17,6 +17,20 @@ config IIO_CHANNEL_PREFIX_KUNIT_TEST
 
 	  If unsure, say N.
 
+config IIO_CHANNEL_WRITE_KUNIT_TEST
+	tristate "Test IIO channel info write" if !KUNIT_ALL_TESTS
+	depends on KUNIT && IIO
+	default KUNIT_ALL_TESTS
+	help
+	  Build unit tests for iio_write_channel_info(), the sysfs store
+	  handler that parses channel info values according to the format
+	  reported by write_raw_get_fmt() and passes them to write_raw().
+
+	  For more information on KUnit and unit tests in general, please refer
+	  to the KUnit documentation in Documentation/dev-tools/kunit/.
+
+	  If unsure, say N.
+
 config IIO_GTS_KUNIT_TEST
 	tristate "Test IIO gain-time-scale helpers" if !KUNIT_ALL_TESTS
 	depends on KUNIT
drivers/iio/test/Makefile +1 -0
index ba08afa7f3f2..bcaf82ffd9c1 100644
@@ -5,6 +5,7 @@
 
 # Keep in alphabetical order
 obj-$(CONFIG_IIO_CHANNEL_PREFIX_KUNIT_TEST) += iio-test-channel-prefix.o
+obj-$(CONFIG_IIO_CHANNEL_WRITE_KUNIT_TEST) += iio-test-channel-write.o
 obj-$(CONFIG_IIO_RESCALE_KUNIT_TEST) += iio-test-rescale.o
 obj-$(CONFIG_IIO_FORMAT_KUNIT_TEST) += iio-test-format.o
 obj-$(CONFIG_IIO_GTS_KUNIT_TEST) += iio-test-gts.o
drivers/iio/test/iio-test-channel-write.c new file +360 -0

360 lines not on this page · raw message

Signature · 1 line
2.43.0
#12 lore raw
In reply to Rodrigo Alencar
Quoted 5 lines · On 20/10/26 09:26, Rodrigo Alencar via B4 Relay wrote:

This series lets kstrtoudec64() and kstrtodec64() accept numbers in E notation (scientific notation), such as "2.7e9", "1.5E-3" or "1e+16". It then moves the IIO core fixed-point parser over to kstrtodec64(), so every IIO channel attribute written through iio_write_channel_info() accepts that format as well.

...

Quoted 14 lines

Digits beyond the resulting precision are now rounded to nearest, ties to even, instead of truncated (new patch 2). This follows from the second motivation: floating point values printed by userspace often end just below the intended decimal value. "%.17g" of 0.3 gives "0.29999999999999999", which truncation turns into 299999 at micro precision instead of 300000. E notation makes this more visible, since a negative exponent can drop integer digits: with truncation, "19e-1" written to an integer attribute gives 1. Round-half-even is the IEEE 754 default, as used by strtod() and printf(), it is unbiased and symmetric for negative values, and inputs that fit the precision (including values read back from sysfs) are parsed exactly as before. The rounding is done before the IIO core conversion, so IIO fixed-point writes change behaviour only once.

Quoted 2 lines

This changes existing kstrtodec64() behaviour, so feedback is welcome on whether it should stay in this series or be sent as a follow-up.

This might not sound good, but I have increased the scope of the series a bit. I think it was a good fit and it would not produce anything unexpected.

Quoted 7 lines

---
Changes in v3:
- New patch: round to nearest, ties to even, instead of truncating.
- Amend kstrtox E notation tests and IIO channel write tests for rounding.
- Link to v2: https://patch.msgid.link/[email protected]

...

Signature · 3 lines
Kind regards,

Rodrigo Alencar