Post

350 Microseconds: Racing the Clock on an nRF52840

Last week I described the APP link. This is the protocol an Oculus controller uses to talk to the headset after pairing: a beacon every 2 ms, frequency hopping across 37 channels, and encrypted answers at fixed offsets. On paper it all looks clean, but getting it to work on real hardware was a different story.

To test the protocol from both ends, my Pulsar dongle can play either role. It can be the host (pretending to be the headset) or the client (pretending to be the controller). The host side was relatively easy. The client side was much harder, because there my dongle has to answer the host exactly when and how a real controller would, and it turned into a long fight with microseconds.

In this post I will go through timing, clocks, a hardware AES trick, and a few bugs that took me way too long to find.

Please note that all information presented here is the result of independent research and may contain mistakes or inconsistencies.

The Problem in One Picture

Here is the slot again:

350 Microsecond Seek Slot Deadline

A controller that isn’t attached yet answers in the seek slot, at 350 µs after the start of the beacon. At first it sounds like plenty of time. This is how it gets used up:

StepTime
The beacon itself is on air: preamble, address, header, 26-byte body, CRC (37 bytes × 4 µs)~148 µs
Radio interrupt, event dispatch to the protocol logic (what my tests assume)~30 µs
Build the answer, encrypt it, schedule the TX???
Radio TX ramp-up (with fast ramp-up enabled)40 µs
Margin so the hardware compare is set in time20 µs
Answer must be on air350 µs

So the “build and encrypt” step gets roughly 110 µs. Everything else is fixed by the radio and the firmware around it.

This is also a hard deadline. The protocol rule is “correct when sent, or not sent at all”. If the answer can’t be on air at its slot offset, it is skipped and counted, and never sent late. The host only listens for it at that offset, so a late answer is wasted air time at best.

Problem #1: AES Is Slow (in Software)

Every answer is sealed with AES-128-CCM. CCM makes two passes over the data, a CBC-MAC for the tag and CTR mode for the encryption. For a payload of len bytes, the number of AES blocks is:

1
blocks = 3 + 2·⌈len/16⌉

An attach request is 14 bytes, so that’s 5 AES blocks. Now it depends on how fast one block is.

  • Software AES on the Cortex-M4: ~120 µs per block, so ~600 µs for one attach request. This is not even close.
  • The nRF52’s AES-ECB peripheral: ~6.5 µs per block, so ~33 µs of raw AES for the attach request. With the per-block setup and the CCM bookkeeping around it, a whole seal takes roughly 60-110 µs in the firmware. It fits, but only just.

The nRF52840 also has a CCM peripheral, and most likely this is what the real controller uses (the nonce format matches its BLE mode). I did it differently. I use the plain AES-ECB peripheral as a block function and do the CCM bookkeeping (RFC 3610) in software around it. It’s a few dozen lines of Rust:

1
2
3
4
5
6
7
8
9
10
11
12
13
/// [`seal_answer`] on an AES-128 block function (`encrypt` encrypts one block in place
/// with the link key), so the firmware can use the radio's AES-ECB peripheral: software
/// AES is far too slow for the 350 µs seek answer. CCM per RFC 3610 with the nRF CCM's
/// parameters: 13-byte nonce, 1-byte AAD, 4-byte MIC. Costs `3 + 2·⌈len/16⌉` blocks.
pub fn seal_answer_with(
    encrypt: &mut impl FnMut(&mut [u8; BLOCK]),
    iv: &CcmIv,
    frame: &mut [u8],
    payload_len: usize,
) -> Result<usize, LinkError> {
    // CBC-MAC over B0, the AAD block and the zero-padded plaintext ...
    // CTR: A0 encrypts the tag, A1.. the plaintext ...
}

Because the block cipher is passed in as a closure, I can pass a software AES on the host (my laptop), and the tests check the result byte-for-byte against the RustCrypto ccm crate and a known-answer vector. On the dongle I pass the hardware peripheral instead. So it is the same code, and I only have to verify it once.

Problem #2: Ramp-up Time

The nRF52 radio doesn’t start transmitting the moment you tell it to. First it has to ramp up (the PLL settles, the PA powers on and so on), and by default that takes about 140 µs. We already have 148 µs of beacon and 30 µs of handling, so a 140 µs ramp-up would leave pretty much nothing for the encryption.

The radio has a fast ramp-up mode (MODECNF0.RU = Fast) which brings this down to 40 µs. Switching it on gave me 80 µs (100 µs less ramp-up, minus a 20 µs scheduling margin).

Another important detail is that the answer is not started by software. The firmware computes the exact TX instant ahead of time and arms a TIMER0 compare → PPI → TXEN chain. Then the hardware fires the radio at exactly the right microsecond, no matter what the CPU is doing at that moment. If the deadline is already too close to schedule, the driver refuses with late and the answer is skipped.

To keep an eye on this, the client status reports the smallest TX lead of any answer it sent, i.e. how close it came to missing the deadline. I find it very handy for spotting regressions.

Problem #3: Two Clocks That Don’t Agree

The headset and my dongle each have their own crystal. Crystals are good, but not perfect, and two of them can be a few tens of ppm off from each other. 50 ppm sounds tiny, but it means 50 µs per second, and the whole link runs on microsecond-level offsets.

The protocol handles this in a very simple way, by re-anchoring on every beacon. The client opens its receiver for a short window around the time it expects the next beacon:

  • open the RX 100 µs before the expected start (the guard);
  • keep it open for 400 µs;
  • when a beacon arrives, re-anchor the slot grid on its timestamp;
  • if the window closes empty, count a miss and move on to the next slot (and hop by Δ, so the hop sequence stays aligned).

Even 50 ppm of drift is only 0.1 µs per 2 ms slot, and since the client re-anchors on every beacon, nothing accumulates.

Translating time

The client also keeps a translation between its own clock and the host’s system time (the 48-bit µs value in every beacon). It needs this because data the controller timestamps (the IMU samples!) is expressed in the host’s time, so the headset can line it up with its own events.

The translation is just one number:

1
offset = system − local        (64-bit, wrapping)

Each accepted beacon replaces the offset with beacon.system − arrival. I deliberately don’t do any averaging here. The host sends each beacon exactly at its slot start (hardware-timed), so the timestamp in it is exact and the newest sample is always the best one. Filtering would only add lag.

Still, one bad sample must never move the time base, so each new sample has to pass two gates first:

GateRuleRejects
Monotonicsystem ≥ last_systemA stale or replayed beacon
Driftabs(Δlocal − Δsystem) ≤ (Δlocal / 1 s + 1) · 50 µsA jump bigger than a crystal can drift: 50 ppm, plus 50 µs of slack

A rejected sample is counted and ignored. The beacon itself still drives the slot timing and hopping, and only its time sample is dropped. If more than 24 slots go by without a beacon, the client declares the link lost and starts fresh. It doesn’t try to guess or keep drifting.

32 bits isn’t enough

On the dongle the radio clock is TIMER0, a 32-bit µs counter, which wraps every ~71 minutes. The link’s system time on air is 48 bits. So I extend the timer in software to 64 bits. The extension accepts readings slightly before the latest one (for example a slot start computed ahead of time) without treating them as a wrap. To catch problems with this, the loopback tests deliberately start both simulated clocks just before their wrap point.

Problem #4: When Exactly Is “Now”?

Every time in this protocol refers to the start of the packet on air, meaning the first bit of its preamble. But the nRF52 timestamps a packet at its ADDRESS event, and that event fires after the preamble and the 5-byte address are already in. At 2 Mbit/s that is 24 µs later.

My first version got this wrong in the other direction. It also subtracted the S0/LEN/S1 header bytes, which come after the ADDRESS event. That’s 36 µs instead of 24, so every RX timestamp was 12 µs early. The same was true for every measurement taken with it, including the real controller’s answer time below. Written down like this it sounds obvious, but it wasn’t obvious at all when I was staring at numbers that were “almost right”.

Problem #5: Matching the Real Controller

Being inside the window is not the same as behaving like a real controller. To check this I used the dongle as host, connected a real left controller, and measured where its endpoint answer arrives. It was about 590 µs after the beacon start (the nominal offset is 575 µs).

My emulator, with the nominal offset plus a 15 µs trim, arrived at 601 µs. The RX and TX chains add about 11 µs between “the timer fired” and “bits on air”, so I reduced the trim to 4 µs:

1
2
3
4
5
/// Added to the nominal answer offset so the emulator goes on air when a real controller
/// does: our host measured the real left controller's endpoint answer at 578 µs with RX
/// timestamps then 12 µs early, so about 590 µs after the beacon. On two dongles a trim of
/// 15 µs put this emulator's endpoint answer at 601 µs (the RX/TX chains add ~11 µs), so 4.
pub const ANSWER_TRIM_US: u32 = 4;

On my two-dongle bench (one dongle as the host, one as the emulated controller) I now measure 590 µs, which is the same as the real controller.

Problem #6: The 37% Bug

Once the timing was mostly right, the client was still missing 37% of beacons. That is more than a third, so it was clearly not just normal packet loss.

It turned out that after a TX the nRF52 radio doesn’t go back to DISABLED. Without the END→DISABLE short, it stays in TXIDLE, and in TXIDLE the radio silently ignores RXEN. So after the client sent its answer, the RX window for the next beacon was “armed” but never actually opened. Every time the timing lined up like that, the next beacon was lost.

The fix is small. If the radio is in a TX state, disable it before arming RX. With that, beacon misses dropped from 37% to 2.4%.

Testing Timing Without a Radio

A logic analyzer alone is not enough to debug this kind of thing. Most of the timing logic in Pulsar is pure: it takes timestamps as input and owns no hardware, which means it can run on my laptop.

The loopback tests put a host link on one mock radio and a client link on another, connected by a simulated air interface:

1
2
3
//! Host <-> client loopback: a `HostLink` on one mock radio, a `ClientLink` on
//! another, connected by a simulated air interface with independent clocks
//! (different start values, both wrapping, client running 40 ppm fast).

The simulator models air time ((1 + 5 + len + 3) · 4 µs), interrupt handling time, the ramp-up rules and the drift between the two clocks. In addition there are tests for tracking with drift, acquiring via the seek channels, mask changes, link loss, attaching, command round trips and re-attaching after an outage. So when something breaks, I find out in cargo test and not on a bench with two dongles and a headset.

Conclusion

To sum up, the timing on both sides of the link relies on hardware AES to fit the encryption into ~110 µs, fast ramp-up, hardware-timed TX via PPI, re-anchoring on every beacon, and careful accounting of when exactly “now” is.

With radio protocols, “almost right” is the same as broken. 590 µs works. 601 µs also works, until it doesn’t.

Next week I will look at what is actually inside those encrypted answers: buttons, sticks, capacitive touch, the IMU stream, and a JSON file hiding in the controller’s flash.

Anyway, this was a fun rabbit hole to go down.


Independent research on devices I own, for security research and interoperability. Not affiliated with or endorsed by Meta/Oculus. No vendor firmware, keys or code are published here. See the Disclaimer.

This post is licensed under CC BY 4.0 by the author.