libe3 0.6.1
C++ library for E3AP RAN vendor integration
Loading...
Searching...
No Matches
latrec.h
Go to the documentation of this file.
1/**
2 * @file latrec.h
3 * @brief Lock-free per-thread latency stamp recorder (header-only, C99).
4 *
5 * One mmap-backed ring per writer thread, single producer, no locks: a stamp
6 * is one CLOCK_MONOTONIC read and four stores, with no syscall, allocation or
7 * formatting. Records are 32 bytes (seq:48 | cpu:8 | stage:8, t_ns, aux,
8 * aux2); seq is assigned once at the producer and joins the stages offline,
9 * aux/aux2 carry the per-stage payloads listed in the stage catalog below.
10 *
11 * CLOCK_MONOTONIC shares an origin across processes, so RAN, dApp and xApp
12 * stamps join without calibration.
13 *
14 * t_ns is stored last, with release ordering: a reader that acquire-loads a
15 * nonzero t_ns also observes that record's sc, aux and aux2. That makes one
16 * record self-consistent; it does not stop the slot being reused, so a reader
17 * of a ring that has wrapped may pair one write's t_ns with the next write's
18 * payload. A live reader must therefore keep up, or detect the wrap from
19 * rec_count and the single descent in t_ns.
20 *
21 * Gated once, at compile time, by LIBE3_ENABLE_LATREC: off by default, so a
22 * normal build carries none of this, not even a disabled-ring branch. With it
23 * on, tracing runs -- there is no second per-run opt-in. See the bottom of
24 * this file, and docs/utilities/latrec.md for where the rings are written.
25 *
26 * File layout: a 4 KiB latrec_hdr followed by `entries` 32-byte records. v1
27 * field offsets are frozen and v2 fields appended inside the header pad, so a
28 * v1 reader parses a v2 file. Readers detect a byte-swapped LATREC_MAGIC.
29 * 64-bit hosts only: a 32-bit host can tear the t_ns store.
30 *
31 * Installed as <libe3/latrec.h>, so a component that links libe3 includes it
32 * from there. Components that do not link libe3 mirror the layout instead, and
33 * the stage catalog below carries their ids too, so it stays the one place a
34 * new id is checked for collisions.
35 *
36 * @see [docs/utilities/latrec.md](../../docs/utilities/latrec.md) for the full guide: the clock
37 * model, ring naming/sizing, the stage catalog table, and the
38 * capture-to-CSV workflow.
39 * @see [docs/control-loops/path-a-e3-loop.md](../../docs/control-loops/path-a-e3-loop.md) and
40 * [docs/control-loops/path-b-e2-e3-loop.md](../../docs/control-loops/path-b-e2-e3-loop.md) for the loop boxes
41 * the stage catalog names.
42 *
43 * SPDX-FileCopyrightText: Copyright (c) 2026 Northeastern University
44 * SPDX-License-Identifier: Apache-2.0
45 */
46#ifndef LIBE3_LATREC_H
47#define LIBE3_LATREC_H
48
49/* clock_gettime() needs a feature-test macro under a strict -std=. Act only
50 * when the TU selected none, and use _GNU_SOURCE: _POSIX_C_SOURCE would
51 * suppress the _DEFAULT_SOURCE a -std=gnu* build otherwise gets, dropping the
52 * BSD/SVID declarations from a TU that includes this header first. Effective
53 * only before the first system header; the #error below catches the rest. */
54#if !defined(_GNU_SOURCE) && !defined(_POSIX_C_SOURCE) && \
55 !defined(_DEFAULT_SOURCE) && !defined(_XOPEN_SOURCE)
56/** Selects the GNU feature set, defined only when the including file chose none. */
57#define _GNU_SOURCE 1
58#endif
59
60#include <fcntl.h>
61#include <stdint.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <sys/mman.h>
66#include <sys/stat.h>
67#include <time.h>
68#include <unistd.h>
69
70#if !defined(CLOCK_MONOTONIC)
71#error "latrec.h: CLOCK_MONOTONIC undeclared - build with a POSIX-enabled dialect (-std=gnu11 / -std=gnu++17) or define _POSIX_C_SOURCE >= 199309L before any system header."
72#endif
73
74#ifdef __cplusplus
75extern "C" {
76#endif
77
78/* ---- portability shims ---------------------------------------------------- */
79
80/** @def LATREC_STORE_RELEASE
81 * Store with release ordering, so earlier stores are visible first.
82 * @param p location to store to
83 * @param v value to store */
84/** @def LATREC_LOAD_ACQUIRE
85 * Load with acquire ordering.
86 * @param p location to read */
87/** @def LATREC_PREFETCH_W
88 * Hint that the cache line at @p p is about to be written.
89 * @param p address of the line */
90/** @def LATREC_UNLIKELY
91 * Branch hint: @p x is expected to be false.
92 * @param x condition */
93#if defined(__GNUC__) || defined(__clang__)
94#define LATREC_STORE_RELEASE(p, v) __atomic_store_n((p), (v), __ATOMIC_RELEASE)
95#define LATREC_LOAD_ACQUIRE(p) __atomic_load_n((p), __ATOMIC_ACQUIRE)
96#define LATREC_PREFETCH_W(p) __builtin_prefetch((p), 1, 0)
97#define LATREC_UNLIKELY(x) __builtin_expect(!!(x), 0)
98#else
99/* Fallback without the builtins: correct on TSO hosts only. */
100#define LATREC_STORE_RELEASE(p, v) do { *(p) = (v); } while (0)
101#define LATREC_LOAD_ACQUIRE(p) (*(p))
102#define LATREC_PREFETCH_W(p) ((void)(p))
103#define LATREC_UNLIKELY(x) (x)
104#endif
105
106/** @def LATREC_HAVE_GETCPU
107 * 1 where sched_getcpu() is available (Linux), else 0. */
108#if defined(__linux__)
109#define LATREC_HAVE_GETCPU 1
110/* glibc exports the symbol unconditionally; only the declaration is gated
111 * behind _GNU_SOURCE, which a TU may have locked in before including us. The
112 * C++ spelling has to carry noexcept to match glibc's __THROW, otherwise a
113 * <sched.h> included after this header is a conflicting redeclaration. */
114#if defined(__cplusplus)
115extern int sched_getcpu(void) noexcept;
116#else
117extern int sched_getcpu(void);
118#endif
119#else
120#define LATREC_HAVE_GETCPU 0
121#endif
122
123/** Read the cpu id in the stamp only where sched_getcpu() resolves in user
124 * space (x86-64 glibc goes through rseq). Elsewhere it can be a getcpu
125 * syscall, so the stamp uses the id cached by latrec_refresh_cpu(). */
126#if LATREC_HAVE_GETCPU && (defined(__x86_64__) || defined(__i386__))
127#define LATREC_CPUID_ON_STAMP 1
128#else
129#define LATREC_CPUID_ON_STAMP 0
130#endif
131
132/** Pastes two tokens; use LATREC_CAT so that both are expanded first.
133 * @param a first token
134 * @param b second token */
135#define LATREC_CAT_(a, b) a##b
136/** Pastes two tokens after expanding them.
137 * @param a first token
138 * @param b second token */
139#define LATREC_CAT(a, b) LATREC_CAT_(a, b)
140/** Compile-time assertion for C and C++.
141 * @param c condition that has to hold
142 * @param m message shown when it does not (the pre-C11 fallback drops it) */
143#if defined(__cplusplus)
144#define LATREC_STATIC_ASSERT(c, m) static_assert(c, m)
145#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
146#define LATREC_STATIC_ASSERT(c, m) _Static_assert(c, m)
147#else
148#define LATREC_STATIC_ASSERT(c, m) \
149 typedef char LATREC_CAT(latrec_static_assert_, __LINE__)[(c) ? 1 : -1]
150#endif
151
152/* ---- stage catalog ------------------------------------------------------- */
153/*
154 * One identifier per *operation* on the E3AP / E3SM / E2SM-DAPP path -- not
155 * one per (operation, component) pair. Several components implement the same
156 * operation: an indication is encoded by whichever Service Model produced it,
157 * and E3AP framing is the same libe3 call whether the RAN or the dApp made it.
158 * They share the identifier. Which component wrote a given record comes from
159 * its ring name (<role>.<tid>.latrec), and which concrete message it carried
160 * from the aux payloads, so a component prefix on the stage id would only
161 * duplicate what the reader already knows.
162 *
163 * Identifiers name the boxes of the two documented loops:
164 * docs/control-loops/path-a-e3-loop.md the E3-only loop (RAN <-> dApp), boxes A1..A20
165 * docs/control-loops/path-b-e2-e3-loop.md the E2-E3 loop (dApp <-> xApp), boxes B1..B15
166 * Each comment below cites the box(es) it bounds. Boxes that hand off inside
167 * one function on one thread share a single boundary stamp rather than
168 * carrying a separate exit and entry.
169 *
170 * Stable IDs: from this baseline on, never renumber, only append.
171 */
172enum {
173 /* --- Source side: recording and processing what a Service Model reports.
174 * A1 (E3 data recording) and A2 (Processing). Stamped by whichever
175 * component is the data source -- an OAI PHY thread, an OCUDU jbpf hook
176 * feeding its E3 controller, a cuBB L1 data-lake reader, or the Simple SM
177 * shipped in examples/sm_simple. seq = the source's own record counter;
178 * aux = a source-defined slot/frame key (e.g. sfn<<16|slot). */
179 LATREC_RECORD_BEGIN = 0x10, /* A1 entry: raw input capture begins */
180 LATREC_PROCESS_BEGIN = 0x11, /* A1 exit / A2 entry: input in hand,
181 SM-side processing begins */
182
183 /* --- E3SM codec. A3 and A12 (encode), A9 and A18 (decode). The same
184 * Service Model codec on either leg and in either role; aux2 = PduType,
185 * which is what separates an indication from a control or a report.
186 * ENCODE_E3SM_BEGIN doubles as A2's exit. */
187 LATREC_ENCODE_E3SM_BEGIN = 0x18, /* A2 exit / A3 (or A12) entry */
188 LATREC_ENCODE_E3SM_DONE = 0x19, /* A3 (or A12) exit; aux = encoded bytes.
189 Hands to EMIT_ENTER */
190 LATREC_DECODE_E3SM_BEGIN = 0x1A, /* A9 (or A18) entry; aux = payload bytes */
191 LATREC_DECODE_E3SM_DONE = 0x1B, /* A9 (or A18) exit; aux = a decoded count
192 the SM cares about (PRBs, slots, ...) */
193
194 /* --- E3AP codec, queue and transport: libe3 itself. A4..A8 on the
195 * forward leg, A13..A17 on the return leg, B10..B13 on the policy leg --
196 * the same five outbound and three inbound stamps each time.
197 * seq = Pdu::enqueue_seq outbound (allocated at EMIT_ENTER so this record
198 * and the rest of the leg share one key), allocated at RECV inbound. */
199 LATREC_EMIT_ENTER = 0x20, /* A4 entry: the producer's thread crosses
200 into libe3. aux = the producer's own
201 trace seq (whatever it last passed to
202 latrec_ctx_set(), 0 if none), which is
203 what joins the producer's stages to
204 this leg; aux2 = RAN function id.
205 EMIT_ENTER->ENQUEUE is Pdu construction */
206 LATREC_ENQUEUE = 0x21, /* A4 first half exit / A5 entry;
207 aux2 = PduType */
208 LATREC_DEQUEUE = 0x22, /* A5 exit / A4 second half entry, on the
209 publisher thread; aux2 = PduType */
210 LATREC_ENCODE_E3AP_DONE = 0x23, /* A4 exit / A6 entry; aux = wire bytes */
211 LATREC_SEND_DONE = 0x24, /* A6 exit: the connector's send() returned;
212 aux = message_id. NOT the wire: a ZMQ PUB
213 send only copies into ZMQ's queue and the
214 socket write happens later on ZMQ's own
215 io thread, so ENCODE_E3AP_DONE->SEND_DONE
216 excludes that hop for ZMQ but includes it
217 for the POSIX connectors */
218 LATREC_RECV = 0x25, /* A7 / A8 entry; aux = wire bytes read */
219 LATREC_DECODE_E3AP_DONE = 0x26, /* A8 exit; aux = message_id,
220 aux2 = PduType */
221 LATREC_DELIVER_BEGIN = 0x27, /* libe3's inbound filter passed; about to
222 invoke the application. A9's entry seen
223 from the library side. A message the
224 dApp-id filter rejects gets neither this
225 nor DELIVER_DONE: see
226 LATREC_DROP_FILTERED */
227 LATREC_DELIVER_DONE = 0x28, /* the application handler returned;
228 aux2 = PduType */
229 LATREC_REPORT_QUEUED = 0x29, /* A19b entry: report handed to the report
230 worker */
231 LATREC_REPORT_DONE = 0x2A, /* A19b exit */
232 LATREC_SESSION_QUEUED = 0x2B, /* the batching seam a language binding
233 drains, inside A9 / B13; aux = kind */
234 LATREC_SESSION_POLLED = 0x2C, /* handed to the binding; aux = position in
235 batch, aux2 = batch size */
236
237 LATREC_DROP = 0x2F, /* a PDU went no further; aux2 = reason
238 (LATREC_DROP_*). An outcome marker, not
239 a box boundary */
240
241 /* --- Bootstrap: the setup and subscription handshakes, and Service Model
242 * lifecycle. These precede the measured loop rather than sitting on it, so
243 * they are bracketed per handshake instead of per box. Either role stamps
244 * the same pair -- the ring tells you which side you are looking at.
245 * seq = the request's message id. */
246 LATREC_SETUP_BEGIN = 0x30, /* setup request sent (initiator) or
247 reached the handler (responder) */
248 LATREC_SETUP_DONE = 0x31, /* setup response written, or the session
249 is ready to carry traffic; aux2 = 1
250 accepted, 0 rejected. A setup that never
251 decoded into a request is rejected with
252 no SETUP_BEGIN to pair with */
253 LATREC_SUB_BEGIN = 0x32, /* subscription request sent or received */
254 LATREC_SUB_DONE = 0x33, /* subscription response queued or
255 confirmed; aux2 = 1 accepted,
256 0 rejected; aux = granted id */
257 LATREC_SM_START = 0x34, /* first subscription: SM worker up */
258 LATREC_SM_STOP = 0x35, /* last unsubscribe: worker joined;
259 aux2 = batches emitted */
260 LATREC_SM_STATUS_BEGIN = 0x36, /* peer connect/disconnect handler entered;
261 aux = RAN function id */
262 LATREC_SM_STATUS_DONE = 0x37, /* handler returned, cadences recomputed
263 and any RIC update sent */
264
265 /* --- Receiving application, dApp side: A10 (Process), A11 (Create control
266 * or report), and B15 (Apply policy). Bespoke application logic rather
267 * than a library call, so these unify across dApp implementations (the
268 * Python framework and the C++ e3_manager dApps) but never across roles.
269 * seq = the key of the message being handled. */
270 LATREC_PROCESS_DONE = 0x40, /* A10 exit: the dApp reached a decision.
271 A10's entry is DECODE_E3SM_DONE */
272 LATREC_CREATE_OUTPUT = 0x41, /* A11: control or report built and queued;
273 aux = bytes. Hands to ENCODE_E3SM_BEGIN */
274 LATREC_APPLY_POLICY_DONE = 0x42, /* B15 exit: an xApp policy applied in the
275 dApp. B15's entry is DECODE_E3SM_DONE */
276 LATREC_ADMITTED = 0x43, /* the handler decided whether to do the
277 work at all; aux2 = outcome
278 (LATREC_OUT_*). An outcome marker */
279
280 /* --- Receiving application, RAN side: A19a (Apply control). The MAC's own
281 * slot-internal scheduler timing is not an E3 operation and is not in this
282 * catalog. seq = the E3 message id of the control being applied. */
283 LATREC_APPLY_CONTROL_DONE = 0x48, /* A19a: mask or policy installed in the
284 MAC; aux = ok. Takes the scheduler
285 lock, so this couples the control
286 thread to the slot-deadline thread */
287 LATREC_LIVE_ON_AIR = 0x49, /* A19a terminal: the first scheduler tick
288 that put this install (or its clear)
289 on air. aux = sfn<<16|slot,
290 aux2 = installs coalesced into this
291 tick (>1 means the ones behind the
292 keyed install rode along). Stamped on
293 the MAC thread but keyed on the control
294 that installed the mask. A clear with
295 no control behind it carries seq 0 */
296
297 /* --- Acknowledgment tail. Either direction: the receiver emits the
298 * ControlResponse that answers a control, the sender observes it.
299 * seq = the answered control's message id. */
300 LATREC_ACK_SENT = 0x4A, /* aux = response code, aux2 = reject
301 reason, 0 when accepted */
303
304 /* --- E2-E3 bridge: A20 (a dApp report going up toward E2) and B9 (an xApp
305 * control coming down toward E3). One pair for both directions;
306 * aux2 = 0 report-up, 1 control-down. seq = a bridge-local counter, since
307 * the E2 envelope carries no id the bridge could propagate. */
308 LATREC_BRIDGE_IN = 0x50, /* message reached the bridge; aux = bytes */
309 LATREC_BRIDGE_OUT = 0x51, /* forwarded on; aux = peers or
310 subscriptions it went to */
311
312 /* --- E2AP codec and SCTP transport. B1 and B6 (encode and send), B2 and
313 * B7 (decode). The same codec whether the xApp side or the E2 agent calls
314 * it, on either flow; aux2 = PDU type. seq = the stamping process's own
315 * counter: no id crosses the RIC, so the legs pair by time, not by seq. */
316 LATREC_ENCODE_E2AP_BEGIN = 0x58, /* aux = payload bytes */
317 LATREC_ENCODE_E2AP_DONE = 0x59, /* SCTP send returned; aux = wire bytes */
318 LATREC_DECODE_E2AP_BEGIN = 0x5A, /* aux = wire bytes received */
319 LATREC_DECODE_E2AP_DONE = 0x5B, /* aux2 = PDU type */
320
321 /* --- E2SM (including E2SM-DAPP) codec, and the xApp's own decision. B3
322 * and B8 (decode), B5 (encode), B4 (xApp processing). The codec pairs are
323 * shared by every framework that speaks E2SM -- the E2 agent's own SM
324 * handling and any xApp framework, Python or otherwise. XAPP_PROCESS_DONE
325 * stays separate from the codecs: it is application logic, not a library
326 * call. seq = the request id the stamping side keys on. */
327 LATREC_DECODE_E2SM_BEGIN = 0x60, /* B3 / B8 entry; the E2AP layer hands the
328 inner payload over; aux = bytes */
329 LATREC_DECODE_E2SM_DONE = 0x61, /* B3 / B8 exit; also B4's entry */
330 LATREC_XAPP_PROCESS_DONE = 0x62, /* B4 exit: the xApp returned a decision.
331 Also B5's entry */
332 LATREC_ENCODE_E2SM_BEGIN = 0x63, /* B5 (or B1) entry, where no xApp
333 decision precedes it */
334 LATREC_ENCODE_E2SM_DONE = 0x64, /* B5 / B1 exit; aux = bytes. Hands to
335 ENCODE_E2AP_BEGIN */
336
337 /* --- Off-path records. Not boxes: these answer "how loaded was the
338 * process" and "why did this row end early", so the one-stamp-per-box
339 * rule does not apply to them. */
340 LATREC_WAIT_ENTER = 0x70, /* a worker went back to its wait carrying
341 the item it just handled. WAIT_ENTER ->
342 the next row's RECORD_BEGIN is time
343 blocked; stamped once per item, so a
344 periodic wait that times out and loops
345 does not restamp it */
346 LATREC_SKIPPED = 0x71, /* a fetched item produced no indication;
347 aux2 = reason (LATREC_SKIP_*) */
348 LATREC_CONTEXT = 0x72 /* slow lane, ~1 Hz on its own ring:
349 aux = involuntary context switches
350 since the last tick, aux2 = current CPU
351 frequency in kHz (0 if unavailable).
352 seq = 0: no per-message key */
353};
354
355/* D5 admission outcomes (aux2) */
356enum {
361};
362
363/* LATREC_SKIPPED reasons (aux2). A telemetry SM drops a fetched publish for
364 * reasons libe3 never sees, so they are numbered separately from
365 * LATREC_DROP_*. The last two are reachable only on the sensing path. */
366enum {
367 LATREC_SKIP_NO_SUBSCRIBERS = 1, /* fetched, then the last dApp went away */
368 LATREC_SKIP_ENCODE = 2, /* indication encode failed */
369 LATREC_SKIP_COALESCED = 3, /* superseded by a newer publish inside the
370 * same emission period (periodic mode) */
371 LATREC_SKIP_NO_SHM = 4, /* /e3_l2_sensing unavailable, so the
372 * indication has no ring entry to name */
373 LATREC_SKIP_RANGES_LOST = 5 /* the publish's seqlock slot was recycled
374 * by newer writes before it was read out */
375};
376
377/* LATREC_DROP reasons (aux2) */
378enum {
387 /* A push rejected because shutdown() had already been called on that
388 * queue, distinct from LATREC_DROP_QUEUE_PUSH/REPORT_QUEUE (the ring was
389 * actually full). E3Interface::stop() shuts response_queue_/report_queue_
390 * down before joining a registered ServiceModel's own producer thread
391 * (which it does not own directly -- that happens later, via
392 * SmRegistry::clear()), so a handful of these during teardown is expected
393 * and does not indicate undersized capacity. */
395};
396
397#define LATREC_MAGIC 0x31524C41u /**< Magic number at the start of a ring file ("ALR1") */
398#define LATREC_VERSION 2u /**< Ring file layout version */
399#define LATREC_HDR_LEN 4096 /**< Bytes of file header, before the records */
400
401/** Measured timestamp cost above which latrec_open warns. A vDSO read is tens
402 * of ns; a syscall fallback is several hundred. */
403#define LATREC_CLOCK_SLOW_NS 100u
404
405/** One record of a ring, 32 bytes. */
406typedef struct {
407 uint64_t sc; /**< seq:48 (low) | cpu:8 | stage:8 (high byte) */
408 uint64_t t_ns; /**< CLOCK_MONOTONIC; released last: nonzero == valid record */
409 uint64_t aux; /**< Stage-specific value */
410 uint64_t aux2; /**< Second stage-specific value */
411} latrec_rec;
412
413/** File header of a ring. v1 layout through name[]; v2 appends inside the pad.
414 * v1 field offsets are frozen. */
415typedef struct {
416 uint32_t magic; /**< LATREC_MAGIC */
417 uint32_t version; /**< LATREC_VERSION of the writer */
418 uint64_t entries; /**< ring capacity (power of two) */
419 uint64_t rec_count; /**< final index; refreshed by latrec_heartbeat */
420 uint64_t t0_mono_ns; /**< paired clocks at open: mono<->wall mapping */
421 uint64_t t0_real_ns; /**< realtime clock at open, paired with t0_mono_ns */
422 char name[64]; /**< ring name, "process.thread" */
423 /* --- v2 --- */
424 uint32_t rec_size; /**< sizeof(latrec_rec), for reader validation */
425 uint32_t clock_ns_per_call; /**< measured timestamp cost (0 = not measured) */
426 uint64_t t1_mono_ns; /**< paired clocks refreshed by heartbeat/close */
427 uint64_t t1_real_ns; /**< realtime clock of the last refresh, paired with t1_mono_ns */
428 uint8_t pad[LATREC_HDR_LEN - 4 * 4 - 8 * 6 - 64]; /**< reserved, fills the header to LATREC_HDR_LEN */
429} latrec_hdr;
430
431LATREC_STATIC_ASSERT(sizeof(latrec_rec) == 32, "latrec_rec must stay 32 bytes");
432LATREC_STATIC_ASSERT(sizeof(latrec_hdr) == LATREC_HDR_LEN, "latrec_hdr must be 4 KiB");
433
434/** A ring in memory: the writer's view of one mapped file. */
435typedef struct {
436 latrec_rec* recs; /**< first record, just after the header */
437 uint64_t idx; /**< index of the next record to write */
438 uint64_t mask; /**< capacity minus one, to wrap idx */
439 void* map; /**< the mapped file */
440 size_t map_len; /**< length of the mapping in bytes */
441 int enabled; /**< nonzero while the ring is open */
442 uint32_t cpu; /**< cpu id used by the stamp when LATREC_CPUID_ON_STAMP
443 * is 0; set by latrec_refresh_cpu() */
444 uint64_t ctx_seq; /**< seq for code too deep to be passed one; see
445 * latrec_ctx_set() */
446} latrec_t;
447
448/** Current CLOCK_MONOTONIC reading.
449 * @return nanoseconds on the monotonic clock */
450static inline uint64_t latrec_now_ns(void)
451{
452 struct timespec ts;
453 clock_gettime(CLOCK_MONOTONIC, &ts);
454 return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
455}
456
457/** Current CLOCK_REALTIME reading.
458 * @return nanoseconds since the Unix epoch */
459static inline uint64_t latrec_real_ns(void)
460{
461 struct timespec ts;
462 clock_gettime(CLOCK_REALTIME, &ts);
463 return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
464}
465
466/** Re-read the cpu id into the ring. Call off the hot path: sched_getcpu() is
467 * a syscall on targets where LATREC_CPUID_ON_STAMP is 0.
468 * @param r ring whose cached cpu id is refreshed */
469static inline void latrec_refresh_cpu(latrec_t* r)
470{
471#if LATREC_HAVE_GETCPU
472 const int cpu = sched_getcpu();
473 if (cpu >= 0) r->cpu = (uint32_t)cpu;
474#else
475 (void)r;
476#endif
477}
478
479/** Mean cost of one latrec_now_ns() over 1000 calls, about 30 us in total.
480 * Called once per ring at open and recorded in the header.
481 * @return mean nanoseconds per call, 0 when the measurement is unusable */
482static inline uint32_t latrec_measure_clock_ns(void)
483{
484 enum { ITERS = 1000 };
485 uint64_t sink = 0;
486 const uint64_t t0 = latrec_now_ns();
487 for (int i = 0; i < ITERS; i++) sink += latrec_now_ns();
488 const uint64_t t1 = latrec_now_ns();
489 if (sink == 0 || t1 <= t0) return 0;
490 return (uint32_t)((t1 - t0) / (uint64_t)ITERS);
491}
492
493/** Where rings go when the caller does not name a directory. A build-time
494 * setting, like the recorder itself: -DLATREC_DEFAULT_DIR=... at configure
495 * time. Runtime placement is chosen with latrec_open_in(), or process-wide
496 * with latrec_set_output_dir(). */
497#ifndef LATREC_DEFAULT_DIR
498#define LATREC_DEFAULT_DIR "/tmp/latrec"
499#endif
500
501/** Open a ring under `dir`. name ("process.thread") becomes
502 * `<dir>/<name>.latrec` and must be unique per writer thread across every
503 * process sharing the directory: the file is opened O_TRUNC, so a collision
504 * discards the other writer's ring. entries_log2 sets the capacity (22 = 4 M
505 * records = 128 MiB). `dir` is created if missing (one level only).
506 *
507 * There is no "tracing disabled" return: in a build with LIBE3_ENABLE_LATREC
508 * the recorder records. Whether it exists at all is the build's decision.
509 * @param r ring to initialise
510 * @param dir directory for the file, NULL or empty for LATREC_DEFAULT_DIR
511 * @param name ring name, "process.thread"
512 * @param entries_log2 capacity as a power of two
513 * @return 1 on success, -1 on error */
514static inline int latrec_open_in(latrec_t* r, const char* dir, const char* name,
515 unsigned entries_log2)
516{
517 memset(r, 0, sizeof(*r));
518 if (!dir || !*dir) dir = LATREC_DEFAULT_DIR;
519 mkdir(dir, 0755); /* EEXIST is the normal case; ignore */
520
521 const uint64_t entries = 1ull << entries_log2;
522 const size_t len = LATREC_HDR_LEN + (size_t)entries * sizeof(latrec_rec);
523
524 /* Built under a temporary name and renamed once the header is written:
525 * rename() is atomic, so a <name>.latrec always carries a valid header. */
526 char path[512], tmp[520];
527 snprintf(path, sizeof(path), "%s/%s.latrec", dir, name);
528 snprintf(tmp, sizeof(tmp), "%s.part", path);
529 int fd = open(tmp, O_CREAT | O_RDWR | O_TRUNC, 0644);
530 if (fd < 0) return -1;
531 if (ftruncate(fd, (off_t)len) != 0) { close(fd); unlink(tmp); return -1; }
532 void* map = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
533 close(fd); /* mapping keeps the file */
534 if (map == MAP_FAILED) { unlink(tmp); return -1; }
535 memset(map, 0, len); /* pre-fault every page */
536
537 const uint32_t clock_ns = latrec_measure_clock_ns();
538
539 latrec_hdr* h = (latrec_hdr*)map;
540 h->magic = LATREC_MAGIC;
542 h->entries = entries;
543 h->rec_size = (uint32_t)sizeof(latrec_rec);
544 h->clock_ns_per_call = clock_ns;
547 h->t1_mono_ns = h->t0_mono_ns;
548 h->t1_real_ns = h->t0_real_ns;
549 snprintf(h->name, sizeof(h->name), "%s", name);
550 if (rename(tmp, path) != 0) { munmap(map, len); unlink(tmp); return -1; }
551
552 r->recs = (latrec_rec*)((uint8_t*)map + LATREC_HDR_LEN);
553 r->mask = entries - 1;
554 r->map = map;
555 r->map_len = len;
556 r->enabled = 1;
558
559 if (clock_ns > LATREC_CLOCK_SLOW_NS) {
560 fprintf(stderr,
561 "[latrec] WARNING %s: CLOCK_MONOTONIC costs %u ns/call; the vDSO "
562 "is unavailable (check the clocksource)\n", name, clock_ns);
563 }
564 return 1;
565}
566
567/** Open a ring under the compiled-in default directory.
568 * @param r ring to initialise
569 * @param name ring name, see latrec_open_in()
570 * @param entries_log2 capacity as a power of two
571 * @return 1 on success, -1 on error */
572static inline int latrec_open(latrec_t* r, const char* name, unsigned entries_log2)
573{
575}
576
577/** Stamp carrying a timestamp the caller already took, for the case where the
578 * moment being recorded is not the moment the stamp can be issued: handing an
579 * item to another thread is only known to have *succeeded* after the handoff,
580 * by which time the consumer may already have run and stamped its own stage.
581 * Reading the clock before the handoff and passing it here keeps the interval
582 * meaningful; issuing a fresh stamp afterwards can order the producer's record
583 * after the consumer's.
584 *
585 * t_ns must be a CLOCK_MONOTONIC reading from latrec_now_ns(). Zero is treated
586 * as "not taken" and replaced with the current time, since zero is also how an
587 * unwritten slot reads.
588 * @param r ring to stamp
589 * @param seq sequence number of the message, only the low 48 bits are kept
590 * @param stage stage id from the catalog
591 * @param aux stage-specific value
592 * @param aux2 second stage-specific value
593 * @param t_ns CLOCK_MONOTONIC reading taken earlier */
594static inline void latrec_stamp_at(latrec_t* r, uint64_t seq, uint8_t stage,
595 uint64_t aux, uint64_t aux2, uint64_t t_ns)
596{
597 if (LATREC_UNLIKELY(!r->enabled)) return;
598 const uint64_t i = r->idx++;
599 latrec_rec* rec = &r->recs[i & r->mask];
600#if LATREC_CPUID_ON_STAMP
601 const uint64_t cpu = (uint64_t)(unsigned)sched_getcpu();
602#else
603 const uint64_t cpu = (uint64_t)r->cpu;
604#endif
605 rec->sc = (seq & 0x0000FFFFFFFFFFFFull)
606 | ((cpu & 0xFFull) << 48)
607 | ((uint64_t)stage << 56);
608 rec->aux = aux;
609 rec->aux2 = aux2;
610 /* Last store, released: makes the record observable as valid only once
611 * sc/aux/aux2 are visible. */
612 LATREC_STORE_RELEASE(&rec->t_ns, t_ns ? t_ns : latrec_now_ns());
613 /* Take the next record's line for write while the caller runs. */
614 LATREC_PREFETCH_W(&r->recs[(i + 1) & r->mask]);
615}
616
617/** Hot path: one clock read and four stores. Single writer per ring.
618 *
619 * The disabled-ring check is repeated here deliberately. latrec_now_ns() is an
620 * argument, so it would be evaluated before the call even on a thread with no
621 * ring, putting a clock read on a path whose whole point is to be free --
622 * tests/bench_latrec.cpp holds that path to a 10 ns ceiling and catches it.
623 * @param r ring to stamp
624 * @param seq sequence number of the message, only the low 48 bits are kept
625 * @param stage stage id from the catalog
626 * @param aux stage-specific value
627 * @param aux2 second stage-specific value */
628static inline void latrec_stamp(latrec_t* r, uint64_t seq, uint8_t stage,
629 uint64_t aux, uint64_t aux2)
630{
631 if (LATREC_UNLIKELY(!r->enabled)) return;
632 latrec_stamp_at(r, seq, stage, aux, aux2, latrec_now_ns());
633}
634
635/** Refresh rec_count and the closing clock pair without closing the ring. Call
636 * periodically so a ring that is never closed still carries both.
637 * @param r ring to refresh */
638static inline void latrec_heartbeat(latrec_t* r)
639{
640 if (!r->enabled) return;
641 latrec_hdr* h = (latrec_hdr*)r->map;
642 h->rec_count = r->idx;
645}
646
647/** Record the final counts and clock pair, flush and unmap the ring, and
648 * disable it. Does nothing on a ring that is not open.
649 * @param r ring to close */
650static inline void latrec_close(latrec_t* r)
651{
652 if (!r->enabled) return;
654 msync(r->map, r->map_len, MS_SYNC);
655 munmap(r->map, r->map_len);
656 r->enabled = 0;
657}
658
659/* ---- per-thread rings (backed by latrec.c) -------------------------------- */
660
661/* @see docs/utilities/latrec.md for why this is a build-time
662 * option, and for what a consumer of an installed libe3 has to match. */
663#ifdef LIBE3_ENABLE_LATREC
664
665/** Ring of the calling thread. Never NULL: it refers to a disabled ring until
666 * the thread calls latrec_tls_open(), so a stamp before that is discarded. */
667extern __thread latrec_t* latrec_tls;
668
669/** Directory the per-thread rings are written to, for the whole process. Call
670 * before the first latrec_tls_open*(); rings already open are unaffected.
671 * NULL or empty restores LATREC_DEFAULT_DIR. This chooses *where*, never
672 * *whether*: with LIBE3_ENABLE_LATREC on, the recorder records regardless.
673 * Two processes that should not share rings (concurrent tests, one benchmark
674 * per directory) each set their own.
675 * @param dir directory for the rings, NULL or empty for LATREC_DEFAULT_DIR */
676void latrec_set_output_dir(const char* dir);
677
678/** Opens the calling thread's ring as `<role>.<tid>`, or `<program>.<tid>` when
679 * role is NULL or empty; idempotent. Capacity comes from
680 * LATREC_ENTRIES_LOG2_<ROLE> (role uppercased, non-alphanumerics as '_'),
681 * else LATREC_ENTRIES_LOG2, else the compiled-in default. The open
682 * pre-faults the whole mapping, which takes tens of ms; the stamp path does
683 * not call it.
684 * @param role ring name prefix, NULL or empty for the program name
685 * @return the calling thread's ring, a disabled one if the open failed */
686latrec_t* latrec_tls_open_as(const char* role);
687/** Same as latrec_tls_open_as() with no role.
688 * @return the calling thread's ring, a disabled one if the open failed */
690
691/** Next value of the process-wide sequence counter (starts at 1).
692 * @return the next sequence number */
693uint64_t latrec_seq_next(void);
694
695/** Stamp into the calling thread's ring, carrying a timestamp taken earlier.
696 * See latrec_stamp_at for when that is the correct thing to do.
697 * @param seq sequence number of the message
698 * @param stage stage id from the catalog
699 * @param aux stage-specific value
700 * @param aux2 second stage-specific value
701 * @param t_ns reading from latrec_tnow() */
702static inline void latrec_tstamp_at(uint64_t seq, uint8_t stage, uint64_t aux,
703 uint64_t aux2, uint64_t t_ns)
704{
705 latrec_stamp_at(latrec_tls, seq, stage, aux, aux2, t_ns);
706}
707
708/** Take a timestamp for a later latrec_tstamp_at(). Pairing these two, rather
709 * than calling latrec_now_ns() directly, keeps the clock read out of a build
710 * with the recorder compiled out: this is the point where the pair collapses
711 * to nothing.
712 * @return a CLOCK_MONOTONIC reading, 0 when the recorder is compiled out */
713static inline uint64_t latrec_tnow(void) { return latrec_now_ns(); }
714
715/** Stamp into the calling thread's ring.
716 * @param seq sequence number of the message
717 * @param stage stage id from the catalog
718 * @param aux stage-specific value
719 * @param aux2 second stage-specific value */
720static inline void latrec_tstamp(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2)
721{
722 latrec_stamp(latrec_tls, seq, stage, aux, aux2);
723}
724
725/** Publishes the seq of the message this thread is carrying, for code whose
726 * signature cannot receive it: the connector is handed a byte buffer, not a
727 * Pdu, libe3's emit entry points are handed neither, and an application's
728 * indication or control handler is handed the message alone. Caller and callee
729 * run on the same thread. latrec_ctx() reads back 0 from a thread with no ring.
730 *
731 * The value is sticky until overwritten, so a producer that wants its records
732 * joined to libe3's outbound leg (via LATREC_EMIT_ENTER's aux) sets it once
733 * per message, immediately before emitting. Readers must tolerate a stale or
734 * zero value rather than treating it as authoritative.
735 *
736 * Both directions use it. Outbound, the producer sets it and libe3 reads it
737 * into LATREC_EMIT_ENTER's aux. Inbound, libe3 sets it before invoking the
738 * application handler, so the handler's own stages can key on the same seq as
739 * the DELIVER_BEGIN/DELIVER_DONE pair around them; a dApp reads it with
740 * latrec_ctx() on entry rather than being passed it.
741 * @param seq sequence number of the message this thread is carrying */
742static inline void latrec_ctx_set(uint64_t seq)
743{
744 /* Threads without a ring share one disabled ring, so an unconditional
745 * store here would be a write race between them. */
746 latrec_t* r = latrec_tls;
747 if (r->enabled) r->ctx_seq = seq;
748}
749/** The seq published by latrec_ctx_set() on this thread.
750 * @return the published seq, 0 from a thread with no ring */
751static inline uint64_t latrec_ctx(void) { return latrec_tls->ctx_seq; }
752
753#else /* !LIBE3_ENABLE_LATREC */
754
755/* True no-op stubs, not just a disabled ring: every instrumented call site
756 * collapses to nothing here, with no dependency on latrec.c (excluded from
757 * the build in this configuration) and no linker symbol to resolve. */
758static inline void latrec_set_output_dir(const char* dir) { (void)dir; }
759static inline latrec_t* latrec_tls_open_as(const char* role) { (void)role; return NULL; }
760static inline latrec_t* latrec_tls_open(void) { return NULL; }
761static inline uint64_t latrec_seq_next(void) { return 0; }
762static inline void latrec_tstamp(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2)
763{
764 (void)seq; (void)stage; (void)aux; (void)aux2;
765}
766static inline void latrec_tstamp_at(uint64_t seq, uint8_t stage, uint64_t aux,
767 uint64_t aux2, uint64_t t_ns)
768{
769 (void)seq; (void)stage; (void)aux; (void)aux2; (void)t_ns;
770}
771/* No clock read at all here: the whole pair is compiled out. */
772static inline uint64_t latrec_tnow(void) { return 0; }
773static inline void latrec_ctx_set(uint64_t seq) { (void)seq; }
774static inline uint64_t latrec_ctx(void) { return 0; }
775
776#endif /* LIBE3_ENABLE_LATREC */
777
778#ifdef __cplusplus
779}
780#endif
781
782#endif /* LIBE3_LATREC_H */
static unsigned entries_log2(const char *role)
Definition latrec.c:91
@ LATREC_OUT_PROCESSED
Definition latrec.h:357
@ LATREC_OUT_SHED_AGE
Definition latrec.h:358
@ LATREC_OUT_SHED_LAG
Definition latrec.h:359
@ LATREC_OUT_NO_RANGE
Definition latrec.h:360
latrec_t * latrec_tls_open(void)
Definition latrec.c:162
static void latrec_tstamp(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2)
Definition latrec.h:720
@ LATREC_SKIP_RANGES_LOST
Definition latrec.h:373
@ LATREC_SKIP_COALESCED
Definition latrec.h:369
@ LATREC_SKIP_NO_SUBSCRIBERS
Definition latrec.h:367
@ LATREC_SKIP_ENCODE
Definition latrec.h:368
@ LATREC_SKIP_NO_SHM
Definition latrec.h:371
static uint64_t latrec_tnow(void)
Definition latrec.h:713
static void latrec_ctx_set(uint64_t seq)
Definition latrec.h:742
void latrec_set_output_dir(const char *dir)
Definition latrec.c:114
static int latrec_open_in(latrec_t *r, const char *dir, const char *name, unsigned entries_log2)
Definition latrec.h:514
#define LATREC_STATIC_ASSERT(c, m)
Definition latrec.h:148
#define LATREC_VERSION
Definition latrec.h:398
static void latrec_heartbeat(latrec_t *r)
Definition latrec.h:638
static void latrec_tstamp_at(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2, uint64_t t_ns)
Definition latrec.h:702
static uint32_t latrec_measure_clock_ns(void)
Definition latrec.h:482
static uint64_t latrec_now_ns(void)
Definition latrec.h:450
static uint64_t latrec_ctx(void)
Definition latrec.h:751
static void latrec_close(latrec_t *r)
Definition latrec.h:650
@ LATREC_DROP_SHUTDOWN
Definition latrec.h:394
@ LATREC_DROP_FILTERED
Definition latrec.h:386
@ LATREC_DROP_DECODE
Definition latrec.h:382
@ LATREC_DROP_SESSION_QUEUE
Definition latrec.h:385
@ LATREC_DROP_ENCODE
Definition latrec.h:380
@ LATREC_DROP_REPORT_QUEUE
Definition latrec.h:383
@ LATREC_DROP_QUEUE_PUSH
Definition latrec.h:379
@ LATREC_DROP_SEND
Definition latrec.h:381
@ LATREC_DROP_NO_HANDLER
Definition latrec.h:384
#define LATREC_STORE_RELEASE(p, v)
Definition latrec.h:100
@ LATREC_SUB_BEGIN
Definition latrec.h:253
@ LATREC_EMIT_ENTER
Definition latrec.h:199
@ LATREC_DECODE_E2SM_BEGIN
Definition latrec.h:327
@ LATREC_DECODE_E2AP_BEGIN
Definition latrec.h:318
@ LATREC_DEQUEUE
Definition latrec.h:208
@ LATREC_ACK_RECV
Definition latrec.h:302
@ LATREC_PROCESS_BEGIN
Definition latrec.h:180
@ LATREC_SETUP_BEGIN
Definition latrec.h:246
@ LATREC_SESSION_POLLED
Definition latrec.h:234
@ LATREC_SKIPPED
Definition latrec.h:346
@ LATREC_CONTEXT
Definition latrec.h:348
@ LATREC_ENCODE_E3SM_DONE
Definition latrec.h:188
@ LATREC_SM_START
Definition latrec.h:257
@ LATREC_ENCODE_E2AP_BEGIN
Definition latrec.h:316
@ LATREC_DECODE_E2SM_DONE
Definition latrec.h:329
@ LATREC_DECODE_E3SM_DONE
Definition latrec.h:191
@ LATREC_DECODE_E2AP_DONE
Definition latrec.h:319
@ LATREC_RECORD_BEGIN
Definition latrec.h:179
@ LATREC_ENCODE_E3AP_DONE
Definition latrec.h:210
@ LATREC_CREATE_OUTPUT
Definition latrec.h:272
@ LATREC_RECV
Definition latrec.h:218
@ LATREC_DECODE_E3AP_DONE
Definition latrec.h:219
@ LATREC_DECODE_E3SM_BEGIN
Definition latrec.h:190
@ LATREC_REPORT_QUEUED
Definition latrec.h:229
@ LATREC_ENCODE_E3SM_BEGIN
Definition latrec.h:187
@ LATREC_DELIVER_BEGIN
Definition latrec.h:221
@ LATREC_BRIDGE_IN
Definition latrec.h:308
@ LATREC_SETUP_DONE
Definition latrec.h:248
@ LATREC_ADMITTED
Definition latrec.h:276
@ LATREC_APPLY_CONTROL_DONE
Definition latrec.h:283
@ LATREC_PROCESS_DONE
Definition latrec.h:270
@ LATREC_SEND_DONE
Definition latrec.h:211
@ LATREC_WAIT_ENTER
Definition latrec.h:340
@ LATREC_ENCODE_E2SM_DONE
Definition latrec.h:334
@ LATREC_SM_STATUS_DONE
Definition latrec.h:262
@ LATREC_SUB_DONE
Definition latrec.h:254
@ LATREC_SESSION_QUEUED
Definition latrec.h:232
@ LATREC_ACK_SENT
Definition latrec.h:300
@ LATREC_SM_STOP
Definition latrec.h:258
@ LATREC_XAPP_PROCESS_DONE
Definition latrec.h:330
@ LATREC_REPORT_DONE
Definition latrec.h:231
@ LATREC_APPLY_POLICY_DONE
Definition latrec.h:274
@ LATREC_LIVE_ON_AIR
Definition latrec.h:287
@ LATREC_ENCODE_E2AP_DONE
Definition latrec.h:317
@ LATREC_BRIDGE_OUT
Definition latrec.h:309
@ LATREC_ENQUEUE
Definition latrec.h:206
@ LATREC_SM_STATUS_BEGIN
Definition latrec.h:260
@ LATREC_DELIVER_DONE
Definition latrec.h:227
@ LATREC_DROP
Definition latrec.h:237
@ LATREC_ENCODE_E2SM_BEGIN
Definition latrec.h:332
uint64_t latrec_seq_next(void)
Definition latrec.c:164
latrec_t * latrec_tls_open_as(const char *role)
Definition latrec.c:122
#define LATREC_DEFAULT_DIR
Definition latrec.h:498
static void latrec_refresh_cpu(latrec_t *r)
Definition latrec.h:469
#define LATREC_UNLIKELY(x)
Definition latrec.h:103
#define LATREC_HDR_LEN
Definition latrec.h:399
static uint64_t latrec_real_ns(void)
Definition latrec.h:459
#define LATREC_PREFETCH_W(p)
Definition latrec.h:102
static int latrec_open(latrec_t *r, const char *name, unsigned entries_log2)
Definition latrec.h:572
static void latrec_stamp(latrec_t *r, uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2)
Definition latrec.h:628
#define LATREC_CLOCK_SLOW_NS
Definition latrec.h:403
#define LATREC_MAGIC
Definition latrec.h:397
__thread latrec_t * latrec_tls
Definition latrec.c:45
static void latrec_stamp_at(latrec_t *r, uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2, uint64_t t_ns)
Definition latrec.h:594
uint32_t magic
Definition latrec.h:416
uint64_t t1_mono_ns
Definition latrec.h:426
uint32_t rec_size
Definition latrec.h:424
uint8_t pad[4096 - 4 *4 - 8 *6 - 64]
Definition latrec.h:428
uint64_t entries
Definition latrec.h:418
uint64_t rec_count
Definition latrec.h:419
char name[64]
Definition latrec.h:422
uint64_t t0_real_ns
Definition latrec.h:421
uint64_t t1_real_ns
Definition latrec.h:427
uint32_t clock_ns_per_call
Definition latrec.h:425
uint32_t version
Definition latrec.h:417
uint64_t t0_mono_ns
Definition latrec.h:420
uint64_t aux2
Definition latrec.h:410
uint64_t aux
Definition latrec.h:409
uint64_t sc
Definition latrec.h:407
uint64_t t_ns
Definition latrec.h:408
uint64_t mask
Definition latrec.h:438
uint64_t ctx_seq
Definition latrec.h:444
size_t map_len
Definition latrec.h:440
int enabled
Definition latrec.h:441
uint64_t idx
Definition latrec.h:437
uint32_t cpu
Definition latrec.h:442
latrec_rec * recs
Definition latrec.h:436
void * map
Definition latrec.h:439