Skip to contentSkip to conversation

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

RFC PATCH Superseded Rodrigo Alencar 4 participants 12 messages Oct 13 – Oct 17

Subsystems (2)

v2 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v2 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. Digits beyond the resulting precision are truncated, matching the existing kstrtodec64() behaviour. Overflow is reported as -ERANGE and a malformed exponent ("1e", "1e+") as -EINVAL.

---
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 (4):
lib: kstrtox: support E notation in kstrtoudec64() and kstrtodec64()
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           | 168 +++++++-------
 drivers/iio/test/Kconfig                  |  14 ++
 drivers/iio/test/Makefile                 |   1 +
 drivers/iio/test/iio-test-channel-write.c | 352 ++++++++++++++++++++++++++++++
 lib/kstrtox.c                             |  64 ++++--
 lib/test-kstrtox.c                        |  58 +++++
 8 files changed, 557 insertions(+), 104 deletions(-)

---
base-commit: a22dc7ebb21a6bd4c8b63bc2c1dd46a24945aae7
change-id: 20261001-e-notation-0f07757910e5

Best regards,

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

RFC PATCH v2 1/4 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 | 64 +++++++++++++++++++++++++++++++++++++++--------------------
 1 file changed, 42 insertions(+), 22 deletions(-)
lib/kstrtox.c +42 -22
index bac1c057e1b0..4755fc78a62c 100644
@@ -397,39 +397,59 @@ EXPORT_SYMBOL(kstrtobool);
 
 static int _kstrtoudec64(const char *s, unsigned int scale, u64 *res)
 {
-	unsigned int rv_int, rv_frac;
+	const char *s_int, *s_frac;
+	int exp = 0, len_int = 0;
+	unsigned int rv;
 	u64 _res = 0;
+	int ret;
 
-	rv_int = _parse_integer(s, 10, &_res);
-	if (rv_int & KSTRTOX_OVERFLOW)
-		return -ERANGE;
-	s += rv_int;
+	s_int = s;
+	while (isdigit(*s)) {
+		s++;
+		len_int++;
+	}
 
 	if (*s == '.')
 		s++; /* skip decimal point */
 
-	rv_frac = _parse_integer(s, 10, &_res, scale, _res);
-	if (rv_frac & KSTRTOX_OVERFLOW)
+	s_frac = s;
+	while (isdigit(*s))
+		s++;
+
+	if (!len_int && s_frac == s)
+		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 v2 1/4] lib: kstrtox: support E notation in kstrtoudec64() and kstrtodec64()

Quoted 10 lines · On Tue, Oct 13, 2026 at 10:36:44AM -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.

...

static int skip_digits(const char **s)

{
	const char *start = *s;

	while (isdigit(**s))
		(*s)++;

	return *s - start;
}

lib/kstrtox.c EXPORT_SYMBOL(kstrtobool); · line 401

Quoted 5 lines

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

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

lib/kstrtox.c EXPORT_SYMBOL(kstrtobool); · line 432

Quoted 10 lines
lib/kstrtox.c +5 -3
-	if (rv_int & KSTRTOX_OVERFLOW)
-		return -ERANGE;
-	s += rv_int;
 
+	s_int = s;
 
+	while (isdigit(*s)) {
+		s++;
+		len_int++;
+	}
	len_int = skip_digits(&s);

lib/kstrtox.c EXPORT_SYMBOL(kstrtobool); · line 417

Quoted 8 lines
lib/kstrtox.c +3 -2
 	if (*s == '.')
 		s++; /* skip decimal point */
 
-	rv_frac = _parse_integer(s, 10, &_res, scale, _res);
-	if (rv_frac & KSTRTOX_OVERFLOW)
+	s_frac = s;
+	while (isdigit(*s))
+		s++;
	len_frac = skip_digits(&s);

lib/kstrtox.c EXPORT_SYMBOL(kstrtobool); · line 419

Quoted 1 line
lib/kstrtox.c +1 -0
+	if (!len_int && s_frac == s)
	if (!len_int && !len_frac)
Quoted 51 lines
lib/kstrtox.c +28 -15
+		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 · 2 lines
With Best Regards,
Andy Shevchenko
#3 lore raw

RFC PATCH v2 2/4 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, truncation of integer digits by negative exponents, large values, and failures for overflowing and invalid inputs.

---
 lib/test-kstrtox.c | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 58 insertions(+)
lib/test-kstrtox.c +58 -0
index 9255234752db..02f42a12647e 100644
@@ -769,6 +769,28 @@ static void __init test_kstrtoudec64_ok(void)
 		/* truncation with many excess digits */
 		{"0.00000000000000000000000000000000423",	34,	42},
 		{"1.99999999999999999999999999999999999",	3,	1999},
+		/* 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,	271ULL},
+		{"270e-2",		3,	2700ULL},
+		/* E notation: negative exponent that truncates integer digits */
+		{"27e-4",		3,	2ULL},
+		/* E notation: negative exponent below 1 ULP truncates to 0 */
+		{"1e-5",		3,	0ULL},
+		/* E notation: large value (27 GHz in micro Hz) */
+		{"2.7e10",		6,	27000000000000000ULL},
 	};
 	TEST_OK(kstrtoudec64, u64, "%llu", test_udec64_ok);
 }
@@ -801,6 +823,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);
 }
@@ -853,6 +886,21 @@ 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 truncates to 0 */
+		{"1e-5",		3,	0LL},
+		{"-1e-5",		3,	0LL},
 	};
 	TEST_OK(kstrtodec64, s64, "%lld", test_dec64_ok);
 }
@@ -881,6 +929,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
Reviewed-by on v2 2/4
#4 lore raw

Re: [PATCH RFC v2 2/4] lib: test-kstrtox: add E notation tests for kstrto[u]dec64()

Quoted 4 lines · On Tue, Oct 13, 2026 at 10:36:45AM -0300, Rodrigo Alencar via B4 Relay wrote:

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

Always a green light for the test cases.

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

RFC PATCH v2 3/4 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 truncated to 1, matching how kstrtodec64() drops digits beyond the requested scale.

---
 drivers/iio/industrialio-core.c | 159 ++++++++++++++++++++--------------------
 1 file changed, 81 insertions(+), 78 deletions(-)
drivers/iio/industrialio-core.c +81 -78
index d73f2541375f..616bfea711e0 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
@@ -1075,13 +1004,79 @@ static int __iio_str_to_fixpoint(const char *str, int fract_mult,
  * Returns:
  * 0 on success, or a negative error code if the string could not be parsed.
  */
-int iio_str_to_fixpoint(const char *str, int fract_mult,
-			int *integer, int *fract)
+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);
+	/* fract_mult = 10^n, so ffs(10^n) = ffs(2^n * 5^n) = n + 1 */
+	unsigned int scale = ffs(fract_mult);
+	s64 dec64;
+	int ret;
+
+	if (fract_mult) {
+		ret = kstrtodec64(str, scale, &dec64);
+	} else {
+		/* keep hex/octal support for integers */
+		ret = kstrtoll(str, 0, &dec64);
+		if (ret == -EINVAL)
+			ret = kstrtodec64(str, scale, &dec64);
+	}
+	if (ret)
+		return ret;
+
+	if (fract_mult > 0)
+		dec64 = div_s64_rem(dec64, fract_mult * 10, fract);
+	else
+		*fract = 0;
+
+	if (dec64 > INT_MAX || dec64 < INT_MIN)
+		return -ERANGE;
+
+	*integer = (int)dec64;
+	/* only carry the sign in the fractional part if the integer is zero */
+	if (*integer)
+		*fract = abs(*fract);
+
+	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 num_len = strlen(str);
+	const char *dec_str = str;
+	char buf[64];
+
+	if (num_len && str[num_len - 1] == '\n')
+		num_len--;
+
+	if (num_len > units_len &&
+	    !strncmp(str + num_len - units_len, units, units_len)) {
+		num_len -= units_len;
+		if (str[num_len - 1] == ' ')
+			num_len--;
+		if (num_len >= sizeof(buf))
+			return -EINVAL;
+		memcpy(buf, str, num_len);
+		buf[num_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
#6 lore raw

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

Quoted 18 lines · On Tue, Oct 13, 2026 at 10:36:46AM -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 truncated to 1, matching how kstrtodec64() drops digits beyond the requested scale.

...

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

Quoted 4 lines
drivers/iio/industrialio-core.c +2 -2
-int iio_str_to_fixpoint(const char *str, int fract_mult,
-			int *integer, int *fract)
+int iio_str_to_fixpoint(const char *str, int fract_mult, int *integer,
+			int *fract)

Keep the logical split, id est don't touch these lines, there are no changes.

...

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

Quoted 12 lines
drivers/iio/industrialio-core.c +11 -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 num_len = strlen(str);
+	const char *dec_str = str;
+	char buf[64];
 
+	if (num_len && str[num_len - 1] == '\n')
+		num_len--;
+	if (num_len > units_len &&
+	    !strncmp(str + num_len - units_len, units, units_len)) {

Hmm... We have strends()... Do you expect string to have garbage at the end? In such a case dB and dBm won't be distinguishable.

Quoted 12 lines
drivers/iio/industrialio-core.c +12 -0
+		num_len -= units_len;
+		if (str[num_len - 1] == ' ')
+			num_len--;
+		if (num_len >= sizeof(buf))
+			return -EINVAL;
+		memcpy(buf, str, num_len);
+		buf[num_len] = '\0';
+		dec_str = buf;
+	}
+
+	return iio_str_to_fixpoint(dec_str, fract_mult, integer, fract);
+}
Signature · 2 lines
With Best Regards,
Andy Shevchenko
#7 lore raw

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

Quoted 20 lines · Andy Shevchenko
Quoted 18 lines · On Tue, Oct 13, 2026 at 10:36:46AM -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 truncated to 1, matching how kstrtodec64() drops digits beyond the requested scale.

...

Quoted 7 lines

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

Quoted 7 lines
drivers/iio/industrialio-core.c +7 -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 num_len = strlen(str);
+	const char *dec_str = str;
+	char buf[64];

before strncmp(), num_len is adjusted to skip '\n'

Quoted 7 lines

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

Quoted 4 lines
drivers/iio/industrialio-core.c +4 -0
+	if (num_len && str[num_len - 1] == '\n')
+		num_len--;
+	if (num_len > units_len &&
+	    !strncmp(str + num_len - units_len, units, units_len)) {

Hmm... We have strends()... Do you expect string to have garbage at the end? In such a case dB and dBm won't be distinguishable.

It might end with '\n' (see above). It would have to test for both "dB" and "dB\n" with strends(), having to prepare a separate buffer just for "dB\n".

The current logic will not accept "dBm" in case units = "dB". because it would compare "dB" with "Bm" from "dBm", i.e. an input of "10 dBm\n" would fail comparison and pass "10 dBm\n" (original string) to iio_str_to_fixpoint(), which would fail for EINVAL.

Another fail case would be "10 ddB\n", which would pass the comparison, having "10 d" passed to iio_str_to_fixpoint(), which again, will fail for EINVAL.

Will add the requested test case.

Quoted 1 line

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

Quoted 1 line
drivers/iio/industrialio-core.c +1 -0
+		num_len -= units_len;

before the memcpy() num_len is adjusted again to skip ' '

Quoted 11 lines
Quoted 11 lines
drivers/iio/industrialio-core.c +11 -0
+		if (str[num_len - 1] == ' ')
+			num_len--;
+		if (num_len >= sizeof(buf))
+			return -EINVAL;
+		memcpy(buf, str, num_len);
+		buf[num_len] = '\0';
+		dec_str = buf;
+	}
+
+	return iio_str_to_fixpoint(dec_str, fract_mult, integer, fract);
+}
Signature · 3 lines
Kind regards,

Rodrigo Alencar
#8 lore raw

RFC PATCH v2 4/4 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 truncation and E notation, and 32-bit range checks.
- IIO_VAL_INT_PLUS_MICRO / IIO_VAL_INT_PLUS_NANO: sign handling, truncation of extra digits, 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 | 352 ++++++++++++++++++++++++++++++
 6 files changed, 376 insertions(+), 4 deletions(-)
MAINTAINERS +1 -0
index 3a2dfd1a4fd8..5ef5caf3b88f 100644
@@ -12757,6 +12757,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 616bfea711e0..7e41668591f6 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 +352 -0

352 lines not on this page · raw message

Signature · 1 line
2.43.0
#9 lore raw

Re: [PATCH RFC v2 4/4] iio: test: add kunit tests for channel info writes

Quoted 20 lines · On Tue, Oct 13, 2026 at 10:36:47AM -0300, Rodrigo Alencar via B4 Relay wrote:

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 truncation and E notation, and 32-bit range checks.
- IIO_VAL_INT_PLUS_MICRO / IIO_VAL_INT_PLUS_NANO: sign handling, truncation of extra digits, 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.

Quoted 3 lines

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().

Please, add 'dBm' to the test cases.

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

Re: [PATCH RFC v2 4/4] iio: test: add kunit tests for channel info writes

In reply to Rodrigo Alencar
Quoted 22 lines · On Tue, 13 Oct 2026 10:36:47 -0300 Rodrigo Alencar via B4 Relay…

From: Rodrigo Alencar <[email protected]>

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 truncation and E notation, and 32-bit range checks.
- IIO_VAL_INT_PLUS_MICRO / IIO_VAL_INT_PLUS_NANO: sign handling, truncation of extra digits, 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.

Quoted 5 lines

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().

Very pleased to see these given our still somewhat complex parsers!

Thanks for doing this.
Note I mostly defer to Andy for review of parsing code as I've messed it up far too many times in the past ;)

Jonathan

maintainer
#11 lore raw
In reply to Rodrigo Alencar
Quoted 42 lines · On Tue, 13 Oct 2026 10:36:43 -0300 Rodrigo Alencar via B4 Relay…

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.

Quoted 4 lines

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.

FWIW reason for the feature looks sensible to me. Thanks for laying out all this detail.

Jonathan