Skip to content

sys/div64 recip - #476

Closed
nashif wants to merge 27 commits into
zephyrproject-rtos:mainfrom
nashif:sys/div64-recip
Closed

nashif wants to merge 27 commits into
zephyrproject-rtos:mainfrom
nashif:sys/div64-recip

Conversation

@nashif

@nashif nashif commented Nov 5, 2026

Copy link
Copy Markdown
Member
  • lib: os: add 64-by-32 division by reciprocal
  • tests: lib: div64: test division by a constant
  • lib: os: div64: add reciprocals of run-time divisors
  • tests: lib: div64: test reciprocals of run-time divisors
  • sys: time_units: divide by reciprocal on 32-bit targets
  • tests: unit: time_units: check conversions divided by reciprocal
  • lib: os: clock: divide by reciprocal on 32-bit targets
  • lib: utils: timeutil: divide the year by reciprocal
  • shell: kernel_service: uptime: divide by reciprocal
  • lib: os: div64: share the reciprocals of common divisors
  • tests: lib: div64: check constant folding and reciprocal use
  • doc: kernel: add a page on 64-bit division by reciprocal

nashif and others added 27 commits November 4, 2026 22:26
Build a branch with every pull request the merge list reports as ready
for a target branch, push it and open a draft PR so the full CI suite
runs on the combined result before the PRs are merged individually.

scripts/ci/integration_train.py reads the merge list JSON feed, fetches
each ready PR head and merges them in ascending order with --no-ff onto
the target tip, skipping PRs that conflict. It writes a JSON report with
the head SHA of every PR as tested and a Markdown PR body with a table
of what was merged and what was not. The PRs and the target branch are
fetched from a remote name or URL, so the script can run in a repository
other than the one the PRs belong to.

The workflow runs daily and on dispatch. It fetches from source_repo
(default zephyrproject-rtos/zephyr), force-pushes integration/<target>
to the repository running it, and creates or refreshes a DNM draft PR
against that repository's <target> branch, which is assumed to track
the source. This allows staging the train in a separate repository such
as zephyr-testing.

Assisted-by: Claude Fable 5 (Claude Code)
Signed-off-by: Anas Nashif <nashif@planux.com>
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Add a "Merge Criteria" check run that stays in progress until a pull
request meets the merge criteria and completes successfully afterwards:

- none of the labels DNM, DNM (manifest), TSC or Architecture Review,
- at least two approvals by users with write access, one of them by an
  assignee unless the author is an assignee, and no changes requested
  by an assignee,
- a review period of 2 business days, 4 hours with the Trivial label
  and none with the Hotfix label, counted from the last time the pull
  request was marked ready for review.

The check run output lists every criterion, whether it is met and what
is still needed, which a commit status description cannot hold.

Draft pull requests are not evaluated. The check run is updated on pull
request events, on reviews relayed through a separate workflow because
pull_request_review runs get a read-only token for forks, and hourly for
all open pull requests to report ended review periods.

Assisted-by: Claude:claude-opus-5
Add a boolean area key for areas whose maintainers must approve every
pull request changing files in the area, also when the pull request is
assigned to the maintainer of another area. It is validated, exposed as
Area.requires_maintainer_approval and documented in MAINTAINERS.yml.

Assisted-by: Claude:claude-opus-5
With --maintainer-file, map the changed files of a pull request to
areas, leaving out meta areas and areas that cover a file only through
a deferring file group while another area covers it too:

- a pull request changing more than --system-wide-areas areas (default
  5) gets the System Wide Change label, which extends the review period
  to --system-wide-review-days business days (default 5),
- every changed area with requires-maintainer-approval needs the
  approval of one of its maintainers, unless one of them is an assignee
  or the author. The changed files of an area still waiting for that
  approval are annotated in the check run.

The check run output also lists the changed areas.

The workflow enables these criteria with the repository variable
MERGE_CRITERIA_USE_MAINTAINERS and then checks out the full tree, as
loading MAINTAINERS.yml checks its file patterns against it. PyYAML and
tabulate, needed by get_maintainer.py, are added to the basic actions
requirements.

Assisted-by: Claude:claude-opus-5
Mark the Kernel area with requires-maintainer-approval so that pull
requests changing kernel files need the approval of a kernel
maintainer.

Assisted-by: Claude:claude-opus-5
Subsets were contiguous slices of the instance list, which is sorted by
test suite name, so each subset held one alphabetical slab of the tree.
Slabs differ widely in build cost: a recent push run to main ranged from
5.9 to 19.7 build hours per subset.

Pack whole test suites into whichever subset is lightest instead. That
run's heaviest subset drops to 14.2 build hours.

Suites are packed whole to keep the spirit of commit 5a09900
("twister: subsets: when creating subsets, sort by tests"): a suite
failing on many platforms should fail one subset, not most of them.
That gets better, not worse: 26 suites were split across subsets
before, one is now. A suite too big to fit in a subset is still cut up,
as slicing already did.

Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
Assisted-by: Claude:claude-opus-5
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Review pull requests with zephyr-review-agent. The workflow runs under
pull_request_target so forked pull requests reach the OpenRouter secret;
it checks out the base branch only, the action fetches the head commit
by SHA and reads it through git plumbing, and nothing from the pull
request is executed.

Reviews are opt-in through the ai-review label, or on demand for one
pull request through workflow_dispatch, which can also save the review
as an artifact instead of posting it. A pull request whose current head
was already reviewed is skipped. The review artifacts are uploaded for
30 days.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Do not run assigner script on anything but zephyrproject-rtos/zephyr.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Add PR size labels to each PR.

  size: XS  -- 1 commit, ≤1 line changed, no manifest file touched
  size: S   -- ≤9 lines changed
  size: M   -- ≤49 lines changed
  size: L   -- ≤499 lines changed
  size: XL  -- >499 lines changed

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
On 32-bit targets, dividing a 64-bit value calls libgcc: __udivmoddi4 is
700 bytes on Cortex-M3, __udivdi3 1068 bytes on rv32. That happens even
for a constant divisor, and nearly every such division in the tree has
one: 10, 1000, 60000, the tick rate.

Add sys_div64_u32_const(), which multiplies by a reciprocal of the
divisor instead. The reciprocal is derived inline and folded by the
optimizer. A
constant dividend folds to a constant, in a static initializer or once
inlined, in C and C++. The multiplication is a shared out-of-line
helper, so a call site costs about what the libgcc call did. It is
inline with CONFIG_SPEED_OPTIMIZATIONS, and sys_div64_u32_const_inline()
forces that for hot paths. sys_mod64_u32_const() and
sys_sdiv64_u32_const() cover the remainder and signed dividends. Without
the optimizer, division stays plain.

The builtins this needs are checked with HAS_BUILTIN(), and a compiler
without them divides plainly. A conditional on __builtin_constant_p()
picks the plain division for a constant dividend. GCC and clang, in C
and C++, and IAR iccarm fold it, in a static initializer too. iccarm
answers __builtin_constant_p() before inlining, so it divides plainly
by a constant divisor, as it did before. Checked with iccarm 10.10.2.

64-bit targets keep plain division.

The algorithm is the one in Linux's __div64_const32() in
include/asm-generic/div64.h (Copyright (C) 2006-2015 Nicolas Pitre). It
has been in Linux since 2006 on ARM and in the generic header since
2015. As its author I contribute it here under Apache-2.0. The exactness
test is a closed form here instead of a trial multiplication, checked
against the latter for every 32-bit divisor.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Check the constant divisor helpers against plain division: divisors with
and without the bias and the short multiply, powers of two and their
neighbors, and the rates time conversions use. Dividends include the
edge cases next to the largest multiple of the divisor. Constant
dividends must fold to constants, and arguments are evaluated once.

The speed scenario covers the inline default, and the no-optimization
one the plain fallback.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
A divisor fixed only at run time, such as a rate read from the hardware,
still goes through libgcc on each division.

Add struct sys_div64_recip. sys_div64_recip_init() derives the same
reciprocal as for a constant divisor, once, with four 32-bit divisions:
Knuth's algorithm D on 16-bit digits. sys_div64_recip_div() and
sys_div64_recip_mod() then multiply by it. SYS_DIV64_RECIP_INIT() does
the derivation at build time. A power of two divisor is a shift.

On 64-bit targets, and with a compiler that lacks the builtins, the
reciprocal holds only the divisor, and division stays plain.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Check SYS_DIV64_RECIP_INIT() against plain division for the same
divisors as the constant tests, and that sys_div64_recip_init() derives
the same reciprocal. Check sys_div64_recip_init() over the whole 32-bit
range: small divisors, powers of two and their neighbors, and random
ones. A power of two must be a shift, both at run time and statically.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The 64-bit conversions, and the 32-bit ones with a 64-bit intermediate,
divide by a rate that is a build-time constant. On 32-bit targets each
one still calls libgcc. k_uptime_get() at a 10 kHz tick is ticks / 10,
and on nRF every K_MSEC() with a run-time argument is
(ms * 32768 + 999) / 1000.

Use the div64 helpers for those. A run-time cycle rate still divides
plainly. A conversion picks plain C or the helpers once, on whether its
argument is a constant, rather than at each division, which would repeat
the argument of a nested conversion three times per division. A
static initializer gets plain C, as before.

tests/kernel/tickless/tickless_concept nests conversions three deep. Its
main.c now preprocesses to 18 MB instead of 2.6 MB, and compiles in the
same time.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Check that the conversion macros give the same result with the div64
helpers as with the C operator, for each conversion form and rounding
mode, over rates with and without an integer ratio.

Unit tests build without optimization, which keeps plain division, so
build this file with -Os.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Splitting ticks into seconds divides by the tick rate, and the
nanosleep remainder by NSEC_PER_SEC. Both are constants, yet each calls
libgcc on 32-bit targets. Use sys_div64_u32_const() and
sys_mod64_u32_const() instead.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
time_days_from_civil() divides a 64-bit year by 400, which calls libgcc
on 32-bit targets. Use sys_sdiv64_u32_const() instead.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Only the split into days needs 64 bits. Do it with
sys_div64_u32_const() and sys_mod64_u32_const(), and the rest in 32
bits, so the pretty uptime no longer calls libgcc on 32-bit targets.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
A call to the out-of-line helper loads a 64-bit m and the flags at each
call site. On ARM the flags go on the stack.

Define the reciprocals of the common divisors once: the time units, the
tick and cycle rates, and the ratios between them that time conversions
divide by. A constant divisor that matches one passes a pointer to it
instead. The match folds at build time and unused ones are dropped by
the linker. The shared reciprocals never change, so their helper is
const and a quotient and remainder pair still makes one call.

Text size change in bytes:

                              cortex-m3  cortex-m0  riscv32  nrf52840
  samples/hello_world                 0          0        0
  shell_module                       -4        +20      -18
  logger                              0          0        0
  tests/lib/timespec_util            +8        +36      +12
  tests/kernel/timer/timer_api     -784       -168     -154
  bluetooth/peripheral                                            -36
  net/sockets/echo_server                                -176     -440

Each image pays for a 16-byte object per divisor used and a small
wrapper, so a few call sites are needed to break even.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
A division with a constant dividend and a constant divisor must leave no
code behind, whether the dividend is a literal or only becomes constant
once inlined. Check this for the division helpers and for the 64-bit
time conversions, in C and in C++. A value that does not fold keeps a
reference to an undefined function and fails the link.

Conversions involving cycles are only checked when the cycle rate is a
constant.

Also check that a division by a constant uses the reciprocal: src/recip.c
is built on its own, and its object may not call a 64-bit division
routine. Without the optimizer it must call one, which the
no_optimizations scenario checks, so the test is seen to catch a plain
division. 64-bit targets have nothing to check. A compiler without nm
fails the build.

Every compiler is checked except IAR iccarm, which is skipped with a
warning. iccarm answers __builtin_constant_p() before inlining, so a
constant divisor passed to the inline helper does not look constant, and
div64.h divides plainly there. Its optimizer also does not fold the
reciprocal's derivation once the divisor is known, so testing the divisor
in the macro instead would not help. Seen with iccarm 10.10.2.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Explain in simple terms how dividing by a reciprocal works and why it is
exact, why it is smaller and faster than libgcc's 64-bit division on
32-bit targets, and how to use the div64 helpers with constant and
run-time divisors.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown

🤖 AI review (advisory)

💬 Comment: worth a look, nothing blocking.

Findings: 3 · Highest severity: medium · Confidence: high

The 64-by-32 division by reciprocal implementation is functionally sound, but contains minor test build/validation inconsistencies when built with compilers lacking specific builtins or when executing unit tests on 64-bit host environments.

3 finding(s) are posted as inline comments on the changed lines (1 medium, 1 low, 1 suggestion).

Test gaps

tests/unit/time_units/reciprocal.c compares plain division against itself when executed on 64-bit host platforms because Z_DIV64_PLAIN is defined under CONFIG_64BIT, bypassing the reciprocal path.


This review is generated by a language model with tool access to the source tree. It is advisory; verify before acting on it.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 inline note(s) from the AI review.

X(1) X(2) X(3) X(4) X(5) X(6) X(7) X(8) X(10) X(12) X(60) X(100) X(400) X(641) X(1000) \
X(3600) X(10000) X(15625) X(32767) X(32768) X(32769) X(60000) X(86400) X(1000000) \
X(6700417) X(19200000) X(24000000) X(32000000) X(1000000000) X(0x55555555) X(0x7fffffff) \
X(0x80000000) X(0x80000001) X(0xaaaaaaab) X(3000000000) X(0xfffffffe) X(0xffffffff)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unsigned hexadecimal integer constants lack U suffix (Rule 7.2) · ⚪ suggestion

Hexadecimal integer constants with values that do not fit in signed 32-bit int lack a 'U' suffix. Happens when compiling tests/lib/div64/src/main.c. Non-compliance with MISRA C:2012 Rule 7.2 / Zephyr Rule 40.

Fix: Add a 'U' suffix to unsigned hexadecimal integer constants in the divisor list and fold test.

Suggested change
X(0x80000000) X(0x80000001) X(0xaaaaaaab) X(3000000000) X(0xfffffffe) X(0xffffffff)
X(0x80000000U) X(0x80000001U) X(0xaaaaaaabU) X(3000000000U) X(0xfffffffeU) X(0xffffffffU)

AI review, advisory; verify before acting on it.

Comment on lines +22 to +26
if(CONFIG_NO_OPTIMIZATIONS)
set(expect plain)
else()
set(expect recip)
endif()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tests/lib/div64 reciprocal check fails when compiler lacks required builtins · 🟡 medium (speculative)

The division-by-reciprocal check in tests/lib/div64 expects reciprocal division whenever CONFIG_NO_OPTIMIZATIONS is not set, ignoring the Z_DIV64_NO_BUILTINS fallback in div64.h that forces plain division when the compiler lacks builtins. Happens when building tests/lib/div64 on a 32-bit compiler that does not support __has_builtin or does not provide the builtins required by sys/div64.h. Building tests/lib/div64 on a 32-bit target with a compiler where HAS_BUILTIN evaluates to false fails the build at check_recip.cmake.

Fix: Account for the lack of builtins in CMakeLists.txt (or check the macro definition from compile definitions / skip the reciprocal check like IAR) so EXPECT is not set to recip when div64.h falls back to plain division.

Suggested change
if(CONFIG_NO_OPTIMIZATIONS)
set(expect plain)
else()
set(expect recip)
endif()
if(CONFIG_NO_OPTIMIZATIONS)
set(expect plain)
else()
set(expect recip)
endif()

AI review, advisory; verify before acting on it.

Comment on lines +21 to +24
zassert_equal(z_tmcvt_gen_64_slow(z_tmcvt_r, t, from, to, up, off), \
z_tmcvt_gen_64_slow(z_tmcvt_c, t, from, to, up, off)); \
zassert_equal(z_tmcvt_gen_32(z_tmcvt_r, t32, from, to, up, off), \
z_tmcvt_gen_32(z_tmcvt_c, t32, from, to, up, off)); \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unit test compares plain division with plain division on 64-bit hosts · 🔵 low

On a 64-bit host where CONFIG_64BIT is defined, Z_DIV64_PLAIN is set, causing the reciprocal macro path (z_tmcvt_r) to expand to standard division; this results in the test comparing plain division against plain division. Happens when executing tests/unit/time_units on a 64-bit unit test host where CONFIG_64BIT is enabled. The unit test passes unconditionally on 64-bit hosts without executing the reciprocal division algorithms, leaving the reciprocal path unvalidated in unit test execution unless tested on a 32-bit architecture.

Fix: In tests/unit/time_units/reciprocal.c, verify that Z_DIV64_PLAIN is not defined or force 32-bit mode in tests.yaml so the reciprocal algorithm is actually exercised.

Suggested change
zassert_equal(z_tmcvt_gen_64_slow(z_tmcvt_r, t, from, to, up, off), \
z_tmcvt_gen_64_slow(z_tmcvt_c, t, from, to, up, off)); \
zassert_equal(z_tmcvt_gen_32(z_tmcvt_r, t32, from, to, up, off), \
z_tmcvt_gen_32(z_tmcvt_c, t32, from, to, up, off)); \
#if defined(Z_DIV64_PLAIN)
#warning "Unit test is running on a 64-bit target where reciprocal division reduces to plain division"
#endif

AI review, advisory; verify before acting on it.

@sonarqubecloud

sonarqubecloud Bot commented Nov 5, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
D Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants