Linux rtc_device Subsystem & snvs_rtc

Derive why an always-on 32.768 kHz coin-cell counter lives outside the gated SoC power island, trace /dev/rtc0 ioctls through Linux 6.12 struct rtc_device and two-phase managed registration, and eliminate 36.4-hour 47-bit carry tears and Year-2038 wraparound in snvs_rtc.

25 minfree previewLinux 6.12C11glibc 2.39→ module 1 lab
What you'll learn
  • Trace /dev/rtc0 RTC_RD_TIME ioctls from VFS into rtc_class_ops and snvs_rtc MMIO registers.
  • Configure devm_rtc_allocate_device() with range_min/range_max before devm_rtc_register_device().
  • Prove Y2038-safe time64_t conversion and double-read rollover protection for 47-bit SNVS counters.

Why Always-On Timekeeping Needs a Dedicated Power Domain and Kernel Class

Before inspecting a single rtc-snvs.c callback, ask the first-principles hardware question: why can't the Cortex-A7 core timer or CCM peripheral clocks keep wall-clock calendar time? When an industrial gateway loses mains power or enters deep power-off, the VDD_SOC and VDD_ARM rails drop to 0 V, stopping the 24 MHz main crystal and wiping every general-purpose register in RAM and CCM. Retaining UTC time across cold boots requires a tiny, isolated CMOS island—on i.MX6ULL, the Secure Non-Volatile Storage Low-Power (SNVS_LP) domain at physical base 0x020CC000—powered continuously by a 3 V coin cell (VDD_SNVS_IN) and driven by a tuning-fork 32.768 kHz quartz crystal that draws less than a few microamperes.

Why 32,768 Hz specifically rather than 10 kHz or 1 MHz? Because 32,768 = 2^15: fifteen cascaded toggle flip-flops divide 32,768 Hz down to exact 1 Hz whole seconds (1 tick = 30.517 us), and software converts raw ticks into seconds with a single bitwise right shift (ticks >> 15) requiring zero 64-bit integer division instructions on 32-bit ARMv7-A! Yet bridging that always-on counter into a running Linux kernel exposes three classic failure modes, all mapped in Figure 1.1a:

  1. Fragmented User-Space ABIs: Boards may carry the on-chip SNVS_LP counter, an external I2C DS1307/PCF8563 RTC, or both. If each driver invented private character-device ioctl commands, hwclock(8), systemd-timesyncd, and rtc_hctosys could not read wall time portably. The Linux RTC class subsystem (drivers/rtc/) solves this by wrapping every hardware clock inside struct rtc_device and const struct rtc_class_ops, exporting one uniform /dev/rtcN ioctl ABI and /sys/class/rtc/rtcN/ hierarchy.
  2. Cold-Boot Publication Races: Legacy drivers called devm_rtc_device_register() first—immediately creating /dev/rtc0 and firing a KOBJ_ADD uevent—and only afterwards populated rtc->range_max or private regmap state. Whenever udev or hctosys opened /dev/rtc0 in that microsecond window, .read_time raced uninitialized state (rtc0: failed to read time). Linux 6.12 eliminates that race with two-phase registration: allocate privately via devm_rtc_allocate_device(), populate rtc->ops, range_min, and range_max, and publish last via devm_rtc_register_device().
  3. 36.4-Hour Multi-Word Carry Tears: Because SNVS_LP counts 47-bit ticks across two 32-bit MMIO registers (SNVS_LPSRTCMR and SNVS_LPSRTCLR) on an asynchronous 32.768 kHz clock while the Cortex-A7 reads 32 bits at a time over the IPG bus, a single upper-then-lower read straddling a low-word carry (0xFFFF_FFFF -> 0x0000_0000) jumps 2^32 ticks = 131,072 seconds (36.4 hours) backward or forward!
fig_m01_l01_a.svg — Linux 6.12 RTC subsystem pipeline from /dev/rtc0 to the…

Figure 1.1a. Linux 6.12 RTC subsystem pipeline from /dev/rtc0 to the coin-cell SNVS_LP island (top) and why devm_rtc_allocate_device() + devm_rtc_register_device() closes the cold-boot probe race (bottom).

mental model: Reading a 47-bit hardware counter split across two 32-bit registers (LPSRTCMR and LPSRTCLR) is like reading a moving car's odometer through two separate peepholes—one for thousands and one for units. If the units wheel rolls from 999 to 000 between your two glances, combining the old upper digits with 000 produces a timestamp off by a full 1,000 (131,072 seconds in SNVS_LP).

Where it stops working: Unlike a mechanical wheel whose motion is visibly gradual, the SNVS_LP counter advances asynchronously every 30.52 microseconds with zero warning flag, so software must prove stability by sampling consecutive full pairs until two snapshots match.

definition (Linux rtc_device Class, Two-Phase Registration & Torn Counter Reads): A struct rtc_device is the Linux kernel class object representing one hardware real-time clock, backed by driver-supplied const struct rtc_class_ops callbacks (.read_time, .set_time, .read_alarm, .alarm_irq_enable) serialized under rtc->ops_lock and exported via /dev/rtcN and /sys/class/rtc/rtcN/. Drivers allocate the object privately with devm_rtc_allocate_device(), assign ops and range_min/range_max, and publish it atomically via devm_rtc_register_device(). A torn read occurs when software assembles a multi-register hardware counter from 32-bit reads sampled on opposite sides of an asynchronous bit-31-to-bit-32 carry.

Walk through the four-stage dispatch, registration, dual-read, and epoch-conversion sequence below:

ast_m01_l01.svg — Allocate devm_rtc_allocate_device() first, set const…step 1/4
  1. Step 1. Step 1: User-space hwclock opens /dev/rtc0 and issues RTC_RD_TIME; rtc-dev.c acquires rtc->ops_lock.
  2. Step 2. Step 2: Probe allocates rtc_device privately, sets ops and range_max = U32_MAX, and registers last.
  3. Step 3. Step 3: snvs_rtc loops reading 47-bit LPSRTCMR/LPSRTCLR pairs (bounded retries) until consecutive reads match.
  4. Step 4. Step 4: Shift ticks >> 15 into signed 64-bit time64_t and unpack struct rtc_time without Year-2038 overflow.

Figure 1.1b. Allocate devm_rtc_allocate_device() first, set const rtc_class_ops and U32_MAX range bounds before devm_rtc_register_device(), sample LPSRTCMR/LPSRTCLR until two consecutive pairs match, and convert via 64-bit time64_t.

47-Bit SNVS Register Geometry, Carry-Ripple Math & Y2038 Epoch Safety

Inspect Figure 1.1b to trace every bit slice inside SNVS_LP (0x020CC000, accessed via a syscon regmap shared cleanly with the snvs_pwrkey power-button driver). Bits [14:0] of SNVS_LPSRTCMR (+0x50) hold counter bits [46:32] (while reserved bits [31:15] are masked off with & 0x7FFFU), and SNVS_LPSRTCLR (+0x54) holds counter bits [31:0]. Joining both halves and shifting right by 15 ((((u64)(msb & 0x7FFFU) << 32) | lsb) >> 15) leaves 47 - 15 = 32 unsigned bits of whole seconds—explaining why rtc->range_max = U32_MAX (4,294,967,295 s, reaching 2106-02-07T06:28:15Z!).

Why does the low-word carry repeat every 36.4 hours, and why must the kernel use time64_t even on 32-bit ARMv7-A?

  1. Carry Period & Tear Magnitude: SNVS_LPSRTCLR wraps after 2^32 ticks at 2^15 Hz, which equals 2^32 / 2^15 = 2^17 = 131,072 seconds (36.408 hours). If regmap_read() latches msb = 0x357C just before lsb rolls from 0xFFFF_FFFF to 0x0000_0000, joining 0x357C with 0x0000_0000 yields a timestamp 131,072 seconds (1.5 days!) behind reality. Reading two complete (msb, lsb) pairs in a bounded loop until msb == msb2 && lsb == lsb2 proves zero carry occurred inside the read window.
  2. Y2038 Safety & struct rtc_time Offsets: Legacy 32-bit signed time_t overflows at 0x7FFF_FFFF (2038-01-19T03:14:07Z), wrapping negative to December 1901 while SNVS_LP hardware still has 68 years of headroom left! Linux 6.12 uses signed 64-bit time64_t with rtc_time64_to_tm() and rtc_tm_to_time64(), populating struct rtc_time where tm_year counts years since 1900 (2040 -> 140) and tm_mon spans 0..11 (January -> 0).
fig_m01_l01_b.svg — 47-bit SNVS_LP register bitfields (+0x50/+0x54), why a…

Figure 1.1b. 47-bit SNVS_LP register bitfields (+0x50/+0x54), why a low-word carry tears single reads by 131,072 s, and how 64-bit time64_t spans cleanly past 2038 to 2106.

Counter Read / Time StrategyBus Reads per CallRollover & Concurrency GuaranteeProduction Engineering Verdict
Single LPSRTCMR then LPSRTCLR read2 MMIO readsTears by +/-131,072 s (36.4 h) on low-word carryBroken: corrupts log retention every 1.5 days
Consecutive full-pair loop (retries = 6)4 (+2 on carry)Proves zero carry across snapshot; bounded on bus faultMainline rtc-snvs.c standard
Deprecated devm_rtc_device_register()Publishes earlyExposes /dev/rtc0 before range_max / state readyBroken: cold-boot udev / hctosys race
clock_gettime(CLOCK_REALTIME) in apps0 MMIO readsReads VDSO RAM clock seeded once at boot by hctosysBest for high-rate user-space timestamps

Study snvs_rtc_probe_snippet.c below. Notice how ksa_snvs_ops is static const (placed in .rodata so stray pointer writes cannot hijack function pointers), snvs_read_rtc_47bit() bounds its retry loop at 6 iterations, and ksa_snvs_probe() configures ops and range_max = U32_MAX before calling devm_rtc_register_device(rtc).

learner@ksa: ~/gl-e06/m01-l01
learner@ksa:~/gl-e06/m01-l01$ bat -H 17 -H 22 -H 24 -H 41 -H 48 snvs_rtc_probe_snippet.c File: snvs_rtc_probe_snippet.c    /* Authentic Linux 6.12 ARMv7 kernel driver pattern (drivers/rtc/rtc-snvs.c) */    #include <linux/module.h>    #include <linux/of.h>    #include <linux/platform_device.h>    #include <linux/regmap.h>    #include <linux/rtc.h>        #define SNVS_LPSRTCMR  0x50U    #define SNVS_LPSRTCLR  0x54U        static u64 snvs_read_rtc_47bit(struct regmap *map, u32 offset)    {        u32 msb, lsb, msb2, lsb2;        int retries = 6;            /* Dual-read loop guards against carry ripple between CLR and CMR */      do {            regmap_read(map, offset + SNVS_LPSRTCMR, &msb);            regmap_read(map, offset + SNVS_LPSRTCLR, &lsb);            regmap_read(map, offset + SNVS_LPSRTCMR, &msb2);            regmap_read(map, offset + SNVS_LPSRTCLR, &lsb2);      } while ((msb != msb2 || lsb != lsb2) && --retries > 0);          return (((u64)(msb & 0x7FFFU) << 32) | lsb) >> 15;    }        static int ksa_snvs_read_time(struct device *dev, struct rtc_time *tm)    {        struct snvs_rtc_data *data = dev_get_drvdata(dev);        time64_t secs = (time64_t)snvs_read_rtc_47bit(data->regmap, data->offset);        rtc_time64_to_tm(secs, tm);        return 0;    }        static const struct rtc_class_ops ksa_snvs_ops = {        .read_time = ksa_snvs_read_time,    };        static int ksa_snvs_probe(struct platform_device *pdev)    {      struct rtc_device *rtc = devm_rtc_allocate_device(&pdev->dev);        if (IS_ERR(rtc))            return PTR_ERR(rtc);            rtc->ops = &ksa_snvs_ops;        rtc->range_min = 0;        rtc->range_max = U32_MAX; /* hardware 32-bit seconds window (47b >> 15) */      return devm_rtc_register_device(rtc);    }
  1. Sample both 32-bit halves twice; any 32.768 kHz carry landing between reads forces (msb, lsb) != (msb2, lsb2).
  2. Cap retries at 6 so a faulted IPG/syscon bus degrades cleanly rather than deadlocking under rtc->ops_lock.
  3. Mask [14:0] (0x7FFFU), shift into a 64-bit word, and shift >> 15 to divide by 32,768 without division.
  4. Allocate struct rtc_device in memory without creating /dev/rtc0 or firing a udev event yet.
  5. Publish /dev/rtc0 last after ops and U32_MAX hardware range bounds are completely initialized.
rtc(4) at a glance — GL-E06
rtc(4)                      GL-E06 Quick Reference                      rtc(4) NAME       rtc - real-time clock character device UAPI (/dev/rtc0) SYNOPSIS       #include <linux/rtc.h>       int ioctl(int fd, RTC_RD_TIME, struct rtc_time *tm);       int ioctl(int fd, RTC_SET_TIME, const struct rtc_time *tm); DESCRIPTION       Provides user space and hwclock(8) uniform access to hardware RTCs       backed by kernel rtc_class_ops. On Linux 6.12, drivers register via       devm_rtc_allocate_device() + devm_rtc_register_device(). FLAGS       RTC_RD_TIME              Read broken-down UTC calendar time (tm_year + 1900, tm_mon              0..11).        RTC_ALM_SET              Program alarm wake time when .set_alarm and IRQ are wired. ERRORS       EINVAL Invalid calendar fields validated by rtc_valid_tm().        EBUSY  Another process already holds exclusive /dev/rtc0 open(). Kernel Systems Academy                    Lesson 1.1                    rtc(4) GL-E06 quick reference · full manual page: man 4 rtc 

Proving Dual-Read Rollover Rejection and Post-2038 Epoch Math in ISO C11

In snvs_rtc_verify.c, we replay a deterministic three-snapshot register sequence straddling a low-word carry (0x357C_FFFFFFFF -> 0x357D_00000000 -> 0x357D_00000000) to verify snvs_dual_read() on the host before touching target silicon. First, snvs_dual_read() rejects the mismatched boundary pair (retries == 1) and accepts the stable second pair (1,794,768,896 s). Second, converting 2,208,988,800 (2040-01-01T00:00:00Z) via gmtime_r() verifies 64-bit post-2038 calendar arithmetic (tm_year + 1900 == 2040, tm_mon + 1 == 1).

learner@ksa: ~/gl-e06/m01-l01
learner@ksa:~/gl-e06/m01-l01$ bat -H 10 -H 16 -H 35 snvs_rtc_verify.c File: snvs_rtc_verify.c    #define _POSIX_C_SOURCE 200809L    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <time.h>    #include <unistd.h>        static uint64_t snvs_dual_read(const uint32_t *cmr, const uint32_t *clr, size_t n, size_t *retries)  {        *retries = 0U;        for (size_t i = 0; i + 1U < n; ++i) {            uint64_t a = (((uint64_t)(cmr[i] & 0x7FFFU)) << 32) | clr[i];            uint64_t b = (((uint64_t)(cmr[i + 1U] & 0x7FFFU)) << 32) | clr[i + 1U];            if (a == b)              return b >> 15;            (*retries)++;        }        return 0ULL;    }        int main(void)    {        /* 1794768896 << 15 = 0x0000357D_00000000 (cmr=0x357D, clr=0). Torn read sees cmr=0x357C, clr=0xFFFFFFFF. */        const uint32_t cmr_seq[3] = {0x357CU, 0x357DU, 0x357DU};        const uint32_t clr_seq[3] = {0xFFFFFFFFU, 0x00000000U, 0x00000000U};        uint64_t torn = ((((uint64_t)(cmr_seq[0] & 0x7FFFU)) << 32) | clr_seq[0]) >> 15;        size_t retries = 0U;        uint64_t clean = snvs_dual_read(cmr_seq, clr_seq, 3U, &retries);            /* Post-Y2038 epoch test: 2040-01-01T00:00:00Z = 2208988800 */        time_t y2040 = (time_t)2208988800LL;        struct tm tm_val;        if (!gmtime_r(&y2040, &tm_val))            return EXIT_FAILURE;            int fd = open("/tmp/ksa_e06_rtc_epoch", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);        if (fd < 0)            return EXIT_FAILURE;        char buf[64];        int len = snprintf(buf, sizeof(buf), "%llu\n", (unsigned long long)clean);        if (write(fd, buf, (size_t)len) != len)            return EXIT_FAILURE;        close(fd);        unlink("/tmp/ksa_e06_rtc_epoch");            printf("torn=%llu clean=%llu delta_s=%lld retries=%zu y2040=%d-%02d-%02d\n",               (unsigned long long)torn, (unsigned long long)clean,               (long long)(clean - torn), retries,               tm_val.tm_year + 1900, tm_val.tm_mon + 1, tm_val.tm_mday);        return EXIT_SUCCESS;    }
  1. Consecutive matching reads discard the pre-carry snapshot 0x357C_FFFFFFFF after exactly 1 retry.
  2. Shifting the 47-bit 32.768 kHz count right by 15 recovers whole seconds without floating-point or division helpers.

Executing the SNVS Rollover Verifier and Auditing Syscalls

Compile and execute snvs_rtc_verify.c below. Predict retries (1) and y2040 (2040-01-01) before running, and observe in strace that no RTC ioctl is invoked on the host workstation—only deterministic scratch-file I/O and user-space 64-bit integer math.

learner@ksa: ~/gl-e06/m01-l01
learner@ksa:~/gl-e06/m01-l01gcc -std=c11 -Wall -Wextra -Werror -fdiagnostics-color=always snvs_rtc_verify.c -o snvs_rtc_verifylearner@ksa:~/gl-e06/m01-l01./snvs_rtc_verifytorn=1794768895 clean=1794768896 delta_s=1 retries=1 y2040=2040-01-01learner@ksa:~/gl-e06/m01-l01echo $?0learner@ksa:~/gl-e06/m01-l01ls -A --color=alwayssnvs_rtc_verifysnvs_rtc_verify.clearner@ksa:~/gl-e06/m01-l01
strace — learner@ksa: ~/gl-e06/m01-l01
learner@ksa:~/gl-e06/m01-l01strace -e \trace=mkdir,openat,write,unlink,close ./snvs_rtc_verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3close(3)                                = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3close(3)                                = 0openat(AT_FDCWD, "/etc/localtime", O_RDONLY|O_CLOEXEC) = 3close(3)                                = 0openat(AT_FDCWD, "/tmp/ksa_e06_rtc_epoch", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "1794768896\n", 11)            = 11close(3)                                = 0unlink("/tmp/ksa_e06_rtc_epoch")        = 0write(1, "torn=1794768895 clean=1794768896"..., 70) = 70+++ exited with 0 +++

Verification Boundaries, Crystal Drift & Transition to External Buses

Separate what the host verifier proves from what requires target hardware sign-off. Running snvs_rtc_verify on x86_64 (7.0.0-42-generic) proves 47-bit compare-until-stable retry logic, >> 15 tick-to-second scaling, and 64-bit 2040 calendar conversion. Measuring real 32.768 kHz quartz frequency drift (20 ppm equals 1.73 s/day, which dual-read coherence cannot remove!), 0x020CC000 IPG bus read latency, and VDD_SNVS_IN coin-cell retention across cold power cycles requires testing /dev/rtc0 on the 32-bit ARMv7-A Cortex-A7 target under Linux 6.12 LTS. Because SNVS_LP sits inside the SoC physical map, rtc-snvs.c reached it through syscon regmap MMIO; when clocks and sensors move off-chip onto two shared PCB traces, the Linux kernel splits controller hardware from client drivers. Later: Lesson m01-l02 builds that split for I2C, starting from open-drain physics, Device Tree i2c_client instantiation, and the single-argument .probe() contract.

Common Production Pitfalls

warning: Symptom: hwclock -r intermittently fails during cold boot, or dmesg logs rtc0: failed to read time when udev or hctosys probes /dev/rtc0. Root Cause: Calling deprecated single-step devm_rtc_device_register() publishes /dev/rtc0 before the driver sets rtc->range_min, rtc->range_max, or private regmap pointers, exposing a half-initialized struct rtc_device to concurrent readers. Fix: Allocate privately with devm_rtc_allocate_device(&pdev->dev), assign rtc->ops and range_min/range_max, and publish last with devm_rtc_register_device(rtc).

warning: Symptom: Gateway log timestamps jump backward or forward by 131,072 seconds (36.4 hours) roughly once every day and a half. Root Cause: Reading SNVS_LPSRTCMR and SNVS_LPSRTCLR once per call allows an asynchronous 32.768 kHz carry out of bit 31 to land between the two regmap_read() transactions, pairing a stale upper word with a wrapped 0x00000000 lower word. Fix: Read two full (LPSRTCMR, LPSRTCLR) snapshots in a bounded retry loop until consecutive pairs match before shifting >> 15.

Practice & Retrieval

Guided Practice: Tracing a Torn Upper-Then-Lower Snapshot

Suppose SNVS_LP advances from 0x357C_FFFFFFFF to 0x357D_00000000 right between two regmap_read() calls, so a naive single-pass reader captures msb = 0x357C and lsb = 0x00000000. Compute (((u64)0x357C << 32) | 0) >> 15 (13,692 * 131,072 = 1,794,637,824 s) and compare it against the true post-carry second 1,794,768,896 s (delta = -131,072 s), then verify what rtc_time64_to_tm() stores in tm_year (140) and tm_mon (0) for 2040-01-01T00:00:00Z.

Independent Practice: Implementing Range-Guarded set_time() Conversion

Extend snvs_rtc_verify.c in a scratch file snvs_set_verify.c with int snvs_encode_secs(int64_t secs, uint32_t *cmr, uint32_t *clr) that rejects negative timestamps or values above UINT32_MAX (4,294,967,295 s, 2106-02-07T06:28:15Z) with -ERANGE instead of silently truncating high bits, shifts valid uint64_t seconds left by 15, and splits [46:32] into *cmr and [31:0] into *clr.

quiz · 1 of 3

Why does Linux 6.12 separate devm_rtc_allocate_device() from devm_rtc_register_device() instead of registering in a single call?

quiz · 2 of 3

Why must snvs_rtc read SNVS_LPSRTCMR and SNVS_LPSRTCLR in a bounded loop until two consecutive pairs match?

quiz · 3 of 3

Why does rtc-snvs declare static const struct rtc_class_ops ksa_snvs_ops with const qualification?

Key takeaways

  • Always-on wall time on i.MX6ULL lives in the coin-cell-backed SNVS_LP island (0x020CC000), clocked at 32.768 kHz (2^15 Hz) so >> 15 yields whole seconds with zero division instructions.
  • The Linux kernel RTC class (struct rtc_device + const struct rtc_class_ops) unifies on-chip and external clocks behind /dev/rtcN and /sys/class/rtc/rtcN/.
  • Always call devm_rtc_allocate_device(), configure rtc->ops and range_min/range_max (U32_MAX), and publish last with devm_rtc_register_device().
  • Guard 47-bit SNVS_LPSRTCMR/SNVS_LPSRTCLR reads with a bounded compare-until-stable loop, and convert timestamps via 64-bit time64_t (tm_year since 1900, tm_mon in 0..11) to avoid Year-2038 overflow. Later: Lesson m01-l02 introduces the I2C bus stack and Linux 6.12 single-argument .probe().
  • Linux 6.12 drivers allocate with devm_rtc_allocate_device(), populate ops and range_min/range_max, and publish with devm_rtc_register_device().
  • snvs_rtc guards 47-bit 32.768 kHz LPSRTCMR/LPSRTCLR reads with consecutive matching snapshots before shifting >> 15 into time64_t.
  • struct rtc_time encodes tm_year relative to 1900 and tm_mon in 0..11, converted without Year-2038 overflow via rtc_time64_to_tm().
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure