Skip to content

rtc: macsmc: fix ntp sync_hw_clock hrtimer retry storm - #2197

Draft
joshuaswarren wants to merge 2 commits into
mainfrom
w88/rtc-macsmc-ntp-sync-retry
Draft

joshuaswarren wants to merge 2 commits into
mainfrom
w88/rtc-macsmc-ntp-sync-retry

Conversation

@joshuaswarren

Copy link
Copy Markdown

W88 clock-sync rider (mailbox q107 is PR 2196). Draft only — not run on M5.

Problem (measured on daily a3m 04:17): 5s ftrace settle — adjtimex 0, sync_hw_clock ~488/s; sync hrtimer retry arms in the past when set_offset_nsec uses class default 1.005s.

Fix: macsmc-rtc set_offset_nsec = 5 ms; ntp sched_sync_hw_clock never arms exp <= now on retry.

Test plan: 5s trace (adjtimex, sync_hw_clock, sync_timer_expire counts) + 3x60s power @763 before/after vs mailbox-only kernel.

Head: a95794f

The RTC class default set_offset_nsec is one second plus five milliseconds,
which makes rtc_tv_nsec_ok fail outside a narrow window. sync_hw_clock then
re-arms its retry hrtimer at second + 2s - offset, which is already in the
past, so the timer and workqueue spin at hundreds per second with no adjtimex
calls (measured: 0 adjtimex vs ~488/s sync work in 5s).

Set macsmc-rtc to the five millisecond transport offset the class documents,
and never arm the sync hrtimer in the past when offset_nsec is mis-sized.
@joshuaswarren

Copy link
Copy Markdown
Author

CHANGES on a95794f
Model: devin/swe-2-flash-medium

[Joshua's agent]

Reviewed the two-hunk diff against kernel/time/ntp.c and drivers/rtc/rtc-macsmc.c at this head.

Finding 1 (blocking): the ntp.c guard is dead code — cross-clock comparison.
sched_sync_hw_clock builds exp from ktime_get_real_seconds(), and sync_hrtimer is CLOCK_REALTIME/HRTIMER_MODE_ABS (ntp.c:935). The new now = ktime_get() is CLOCK_MONOTONIC — nanoseconds since boot (~1e14), versus the realtime-domain exp (~1.7e18). ktime_compare(exp, now) <= 0 can never be true, so exp = ktime_add_ns(now, NSEC_PER_MSEC) never runs and past-arming continues exactly as before. The correct clock is ktime_get_real() (or ktime_get_real_fast_ns()). As written this hunk changes nothing.

Finding 2 (blocking): even fixed, the fallback does not bound the retry rate.
exp = now + 1ms re-arms a persistently failing rtc_tv_nsec_ok/update_rtc path at ~1 kHz — the same workqueue spin, just metered. Convergence still depends entirely on the macsmc offset change making the check pass.

Finding 3 (needs hardware evidence): set_offset_nsec = 5ms likely leaves the RTC ~1s slow.
macsmc's RTC is a free-running 32.768 kHz counter (CLKM); macsmc_rtc_set_time writes an absolute offset, so the RTC displays the written whole second immediately and counts real time forward from it — there is no write-triggered second increment for set_offset_nsec to model. to_set = now - 1s + offset: with the class default (~1s + transport) to_set lands on the current second edge; with 5 ms it lands ~1 s in the past, so every successful 11-minute sync writes a stale second and the RTC reads ~1 s behind realtime until the next write. If 5 ms is claimed as macsmc's true transport, it needs a read-back receipt showing the RTC within tolerance of realtime after update_rtc.

On the review questions: the macsmc hunk does stop the spin structurally — 2s - 5ms can never be <= now's sub-second fraction, so the retry can never arm in the past. But it buys that by writing a stale second (finding 3), and the generic ntp.c half fixes nothing as written. A mis-sized offset on any other RTC keeping the class default still produces the same storm, so the durable fix belongs in sched_sync_hw_clock — with the correct realtime clock — plus per-device offset validation.

wAX: past-arm guard used ktime_get() (MONOTONIC) against CLOCK_REALTIME
expiry — guard never fired. Compare and slip forward on ktime_get_real();
on retry roll to the next second slot instead of a 1 ms tight loop.

wAX: 5 ms set_offset_nsec is wrong for macsmc free-running CLKM+nvmem.
Drop transport offset; use NSEC_PER_SEC/2 systohc phase window like CMOS.

M5 pre-fix (daily): adjtimex 1/5s (checkpoint), sync_hw_clock+timer 2158/5s
(~432/s) — kernel sched_sync_hw_clock re-arm, not userspace adjtimex.
@joshuaswarren

Copy link
Copy Markdown
Author

GREEN on 33958ff
Model: devin/swe-2-flash-medium

[Joshua's agent]

Re-reviewed at the new head; both prior findings addressed.

ntp.c — verified fixed. now is now ktime_get_real(), same CLOCK_REALTIME base as exp and the hrtimer, so the past-arm guard actually fires. On retry it slides to the next second slot (floor_sec+1s + 2s - offset) rather than re-arming the same past instant, and the now + 1ms fallback is unreachable for any sane offset (<2 s). For offset values in the class-default range this makes the re-arm cadence ~1 s instead of an immediate-refire spin, for every RTC — the generic fix. Non-retry now anchors to now instead of the second boundary, which can cost one failed rtc_tv_nsec_ok per 11-minute cycle; harmless.

macsmc — disclosed tradeoff, acceptable for a draft. NSEC_PER_SEC/2 writes to_set ~0.5 s before the edge, so the RTC reads ~0.5 s behind wall after each systohc write versus ~+5 ms with the class default. One correction to the stated rationale: rtc_tv_nsec_ok's window width is offset-invariant (it is always ~2×FUZZ centered on the scheduled instant) — the offset does not widen the window, it selects which whole second gets written. The choice is still defensible as CMOS parity, and a follow-up can narrow it if post-fix traces show the skew matters.

Evidence status (honest): all existing traces are pre-fix daily kernels; no post-fix steady-state exists yet, which is expected while the PR stays draft. The code-level argument for storm elimination is sound: under the new guard the fastest legal re-arm is ~1 s, so the ~430/s re-arm loop cannot persist. Post-merge-on-next2 trace showing ~≤1/s retry cadence (or the 11-min period after a successful sync) plus rtc0 readback is the right receipt to collect before undrafting.

@RyanTheTide

Copy link
Copy Markdown

Thanks for chasing the sync_hw_clock rate. Before a fix lands, the cause needs pinning down. With the class default offset (drivers/rtc/class.c:223, 1 s + 5 ms) the retry target in sched_sync_hw_clock() is floor(now) + 0.995 s. That lands in the past only during the last 5 ms of a second, so it cannot sustain ~488 rearms/s. Could you trace res from sync_hw_clock()/update_rtc() and the exp/now pair on each rearm? If rtc_set_time() fails on every pass, or the work runs late, the fix belongs there.

The kernel/time/ntp.c change also moves the 11-minute sync off the second boundary for every RTC. If a generic problem remains after that trace, it should go upstream with a reproducer on a non-Apple RTC rather than live in this tree.

rtc-macsmc.c:447-453: the driver writes an absolute counter offset, so set_offset_nsec should be the measured write latency. A half-second CMOS phase leaves the RTC about 0.5 s behind after each sync.

Row: any macsmc machine, NTP synced. Use 60 s of ftrace in steady state, with at most 1 retry per second and 1 call per 660 s after a success. Then hwclock --get against date +%s.%N within 10 ms after a sync, x3.

@joshuaswarren

Copy link
Copy Markdown
Author

[Joshua's agent]

Root cause pinning: Agreed the class default 1 s + 5 ms (class.c:223) cannot alone explain ~488 rearms/s — retry target floor(now)+0.995s only falls in the past in the last 5 ms of each second. We owe the ftrace you asked for: sync_hw_clock → sched_sync_hw_clock res, exp/now each rearm, and whether update_rtc() / rtc_set_time() fails every pass. wAX's review on 33958ff already caught one dead ntp.c guard (mixed clocks); that fix is in this head.

set_offset_nsec: Agreed for Apple SMC absolute-offset writes — next push sets offset from measured macsmc_write() latency, not 500 ms phase guess.

Generic ntp.c: If ftrace shows a class-wide pattern survives SMC fix, we will upstream with a non-Apple reproducer instead of carrying a broad shim here.

Measured: Check page green at 33958ff (wAX GREEN). No 60 s ftrace row or hwclock --get vs date +%s.%N triple yet.

Hardware row (any macsmc): trace_event=rtc:*,macsmc:*,hrtimer:* 60 s steady NTP; then 3× post-sync hwclock --get vs date +%s.%N within 10 ms.

@RyanTheTide

Copy link
Copy Markdown

Thanks for the plan. The head is still 33958ff, so the points from the last review are open:

  • The ftrace of res from sync_hw_clock()/update_rtc() and the exp/now pair on each rearm. That decides where the fix goes. The class default (1 s + 5 ms) only lands in the past during the last 5 ms of a second, so something else is driving ~488 rearms/s.
  • kernel/time/ntp.c: please drop that hunk from this PR. It moves the 11-minute sync off the second boundary for every RTC. If a generic problem remains after the trace, it belongs upstream with a non-Apple reproducer.
  • rtc-macsmc.c:447-453: set set_offset_nsec to the measured write latency, not NSEC_PER_SEC / 2.

Row, on any macsmc machine: 60 s steady-state ftrace, at most 1 retry/s and one call per 660 s after a success, then hwclock --get vs date +%s.%N within 10 ms, x3.

@joshuaswarren

Copy link
Copy Markdown
Author

Note

w7H/wAK (AI assistant) responding on behalf of joshuaswarren

33958ff95c is unchanged and stays Draft. The trace-enabled kernel build is queued behind a build-host disk-space gate, so we don’t yet have the requested sync_hw_clock()/update_rtc() return values, realtime exp/now pairs, or measured macsmc write latency. The host-test pass does not establish the cause of the retry rate.

I’ll drop the generic kernel/time/ntp.c hunk from this PR and use the measured write latency for set_offset_nsec, not the half-second value. If the trace points to a generic RTC issue, I’ll keep it separate and bring a non-Apple reproducer. The corrected head still needs the 60-second steady-state trace (at most one retry per second), one call per 660 seconds after a successful sync, and three hwclock --get versus date +%s.%N checks within 10 ms. None of those measurements has run on the corrected head.

@joshuaswarren

Copy link
Copy Markdown
Author

J775c (lobata) row request — RTC trace (sheet row R)

Posted by Joshua's lane (wB4) from the 2026-11-20 K114c row set. We supply no image for this; it needs a tree with the J775c DTB (an off-host build of the head plus the J775c board DTB, booked only once that DTB exists for the head). Studio preflight before booking: cat /sys/power/suspend_stats/{success,fail}, then sudo rtcwake -m freeze -s 20 under the sheet's recovery rules, boot ID unchanged and desktop usable; timedatectl show -p NTPSynchronized --value must print yes. Record uname -r and the boot ID.

Head: the trace-only derivative of the reviewed 33958ff95c0847134bbecddf794e306951e7ec77, then the corrected head. Any macsmc machine qualifies per the sheet.

Commands: qualify the trace build off-machine (signed res at the sync_hw_clock() rearm path including paths that bypass update_rtc(), signed update_rtc() result, final exp and sampled now at the hrtimer_start() call in sched_sync_hw_clock(), RTC write return and elapsed ns). Isolated ftrace instance, 60 s contiguous baseline, then capture across three scheduled successful writes on the corrected head. Measure RTC phase after each write against CLOCK_REALTIME with the prequalified second-edge tool; hwclock --get and date +%s.%N are context only.

Pass: first trace identifies the retry cause; corrected head has at most one retry per second and one call per 660 s after success; three phase measurements within 10 ms. A trace without RTC writes does not pass. About 36 min, no fixture.

@satchlj

satchlj commented Nov 20, 2026

Copy link
Copy Markdown
Member

Claude Opus 5.5 on @satchlj's behalf.

J775c (lobata) row for sheet row R: the trace identifies the retry cause. The corrected head (33958ff9) fails the row; a one-line driver fix passes it. Details: #2616.

All builds are cand-10 (integration/aurora df62a8c4d38d + 84) with RTC_SYSTOHC=y, plus a trace-only patch (an isolated ntp_sync ftrace instance). The patch records:

  • the result on every sync_hw_clock() path, including the ones that bypass update_rtc();
  • the update_rtc() result;
  • the final expiry and a CLOCK_REALTIME sample at hrtimer_start();
  • the rtc_set_time() return and its elapsed time.

The procedure was a 60 s baseline, then capture until three successful writes, as one-shot trials by ordinary reboot. RTC−REALTIME was read at the RTC's own tick edge.

Build Re-arms in first 60 s Successful writes RTC−REALTIME
Trace only (pre-fix) 3774 0 in 35 min (62,337 retries) —
This PR's head 33958ff9 42 0 counted (2,143 retries) —
33958ff9 + #2616's commit 1 2 3, 661 s apart −0.501 s
#2616's commit 1 alone 2 3, 658 s apart, 2 retries in all +0.004 s

Retry cause. macsmc_rtc_set_time() returns nvmem_cell_write()'s byte count (6), so update_rtc() reports every successful write as a failure. The traces show rtc_set_time err=6 … elapsed ≈ 0.4–0.8 ms followed by an immediate retry.

  • Pre-fix: every ~0.8 ms inside the window. Outside it, the retry expiry lands in the past, because set_offset_nsec is the class default 1.005 s.
  • With this PR: once a second, indefinitely. The past-arm guard and the next-slot roll work as intended, but the write keeps failing in the kernel's eyes.

set_offset_nsec. This driver makes the set second begin at the write (off = (tm << RTC_SEC_SHIFT) - ctr), so the class default of about 1 s is the right offset. With NSEC_PER_SEC / 2, the RTC's second ticks half a second late (−0.501 s measured), which fails the row's 10 ms phase criterion. With the default and the return-value fix, it's +4 ms.

Suggestion: drop the rtc-macsmc.c offset change from this PR. With #2616 the storm is gone without it, and whether the ntp.c guard is still wanted is your call. The phase above is measured with the RTC tick-edge method, not with the sheet's prequalified second-edge tool, which isn't on lobata. If you want the sheet's tool on the final head, point me to it.

Evidence (row logs, 60 s baselines, full captures) is in lobata's session notes: joshua-rows-20261120/evidence/{row2197pre,row2197,row2197fix,rtcfix}-out.

@joshuaswarren

Copy link
Copy Markdown
Author

[Joshua's agent] Thanks for tracing the successful writes, not just counting timer re-arms. The tick-offset branch returns the six bytes written; NTP treats that positive return as failure and retries a write that already succeeded. Our K114c daily-tree trace showed the kernel retry loop, but it did not prove this cause or qualify this PR head. Your J775c row shows that our guard slows the loop without fixing it, and that our half-second offset moves the RTC edge about 501 ms late. The RTC-only change in #2616 preserves negative errors and reports success as zero, matching the seconds-offset branch; with the default offset, your row saw successful writes about 658 s apart and a +4 ms edge.

We will adopt the RTC change through #2616, keep the class default, and leave the generic NTP guard out unless there is a separate reproducer. We will confirm on the 16-inch M1 Max with RTC_SYSTOHC enabled and NTP synchronized: trace baseline and candidate, require three successful writes at roughly the 11-minute cadence, measure the RTC edge with the row sheet tool (within 10 ms), and record regressions. No boot has been run for this reply.

@RyanTheTide

Copy link
Copy Markdown

The J775c trace above shows the retries come from macsmc_rtc_set_time() reporting the 6 written bytes as a failure, which #2616 fixes. With that fix and the default offset, writes land about 658 s apart and the RTC edge is +4 ms. The half-second set_offset_nsec here moves the edge 0.5 s late, and the ntp.c guard has no reproducer left once #2616 is in. Once #2616 is merged, this PR can be closed, unless a separate trace shows the guard is still needed.

@joshuaswarren

Copy link
Copy Markdown
Author

Thanks, Ryan - agreed. The retry storm is the macsmc_rtc_set_time failure that #2616 fixes, and with that fix in, the default offset lands writes about 658 s apart, so the half-second set_offset_nsec and the ntp.c guard lose their reproducer. We will close this once #2616 merges; if a later trace shows the guard is still needed, the trace comes with it.

Assisted-by: LLM (Anthropic:claude-opus-5.5)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants