1#[cfg(not(target_os = "linux"))]
28use std::alloc::System as ProcessAllocator;
29use std::alloc::{GlobalAlloc, Layout};
30use std::cell::Cell;
31use std::marker::PhantomData;
32use std::path::Path;
33use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, AtomicU64, Ordering};
34use std::sync::Mutex;
35#[cfg(target_os = "linux")]
36use tikv_jemallocator::Jemalloc as ProcessAllocator;
37
38mod capture;
39mod report;
40mod ring;
41
42pub use report::{drain_now, set_line_sink, start_logger};
43
44pub const LARGE_ALLOCATION_BYTES: usize = 64 << 20;
46pub const LABEL_BURST_BYTES: isize = 512 << 20;
48pub const FLUSH_QUANTUM_BYTES: isize = 1 << 20;
52
53const MAX_LABELS: usize = 128;
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct Label(u8);
61
62const FIXED_LABELS: [&str; 11] = [
63 "",
64 "index_build",
65 "callgraph_start",
66 "callgraph_refresh",
67 "segment_fold",
68 "meaning_fill",
69 "symbol_prewarm",
70 "remote_input_capture",
71 "frame_encode",
72 "census",
73 "tool:other",
74];
75
76static INTERNED: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
79
80impl Label {
81 pub const NONE: Label = Label(0);
83 pub const INDEX_BUILD: Label = Label(1);
85 pub const CALLGRAPH_START: Label = Label(2);
87 pub const CALLGRAPH_REFRESH: Label = Label(3);
89 pub const SEGMENT_FOLD: Label = Label(4);
91 pub const MEANING_FILL: Label = Label(5);
93 pub const SYMBOL_PREWARM: Label = Label(6);
95 pub const REMOTE_INPUT_CAPTURE: Label = Label(7);
97 pub const FRAME_ENCODE: Label = Label(8);
99 pub const CENSUS: Label = Label(9);
101 pub const TOOL_OTHER: Label = Label(10);
103
104 pub fn tool(name: &str) -> Label {
106 let valid = !name.is_empty()
107 && name.len() <= 48
108 && name
109 .bytes()
110 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'));
111 if !valid {
112 return Label::TOOL_OTHER;
113 }
114 Label::intern_with_prefix("tool:", name).unwrap_or(Label::TOOL_OTHER)
115 }
116
117 #[doc(hidden)]
120 pub fn custom(name: &str) -> Label {
121 Label::intern_with_prefix("", name).unwrap_or(Label::TOOL_OTHER)
122 }
123
124 fn intern_with_prefix(prefix: &str, name: &str) -> Option<Label> {
125 let matches = |entry: &str| entry.strip_prefix(prefix) == Some(name);
126 if let Some(index) = FIXED_LABELS.iter().position(|entry| matches(entry)) {
127 return Some(Label(index as u8));
128 }
129 let mut interned = INTERNED.lock().unwrap_or_else(|e| e.into_inner());
130 let offset = FIXED_LABELS.len();
131 if let Some(index) = interned.iter().position(|entry| matches(entry)) {
132 return Some(Label((offset + index) as u8));
133 }
134 if offset + interned.len() >= MAX_LABELS {
135 return None;
136 }
137 let leaked: &'static str = Box::leak(format!("{prefix}{name}").into_boxed_str());
138 interned.push(leaked);
139 Some(Label((offset + interned.len() - 1) as u8))
140 }
141
142 pub fn name(self) -> &'static str {
144 label_name(self.0)
145 }
146}
147
148fn label_name(id: u8) -> &'static str {
149 let id = usize::from(id);
150 if let Some(name) = FIXED_LABELS.get(id) {
151 return name;
152 }
153 INTERNED
154 .lock()
155 .unwrap_or_else(|e| e.into_inner())
156 .get(id - FIXED_LABELS.len())
157 .copied()
158 .unwrap_or("unknown")
159}
160
161#[derive(Clone, Copy)]
165pub struct RootName {
166 len: u8,
167 bytes: [u8; 47],
168}
169
170impl RootName {
171 pub const EMPTY: RootName = RootName {
172 len: 0,
173 bytes: [0; 47],
174 };
175
176 pub fn from_path(root: &Path) -> RootName {
177 let name = root
178 .file_name()
179 .map(|name| name.to_string_lossy())
180 .unwrap_or_else(|| root.to_string_lossy());
181 RootName::from_str(&name)
182 }
183
184 fn from_str(name: &str) -> RootName {
185 let mut end = name.len().min(47);
186 while !name.is_char_boundary(end) {
187 end -= 1;
188 }
189 let mut out = RootName::EMPTY;
190 out.bytes[..end].copy_from_slice(&name.as_bytes()[..end]);
191 out.len = end as u8;
192 out
193 }
194
195 pub fn as_str(&self) -> &str {
196 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("")
197 }
198}
199
200struct LabelState {
202 live: AtomicIsize,
204 census_peak: AtomicIsize,
206 burst_peak: AtomicIsize,
208 active: AtomicU32,
211 crossed: AtomicBool,
214 crossed_at_ns: AtomicU64,
216}
217
218impl LabelState {
219 const fn new() -> Self {
220 Self {
221 live: AtomicIsize::new(0),
222 census_peak: AtomicIsize::new(0),
223 burst_peak: AtomicIsize::new(0),
224 active: AtomicU32::new(0),
225 crossed: AtomicBool::new(false),
226 crossed_at_ns: AtomicU64::new(0),
227 }
228 }
229}
230
231static LABELS: [LabelState; MAX_LABELS] = [const { LabelState::new() }; MAX_LABELS];
232
233struct ThreadState {
237 label: Cell<u8>,
239 pending_label: Cell<u8>,
242 pending: Cell<isize>,
244 busy: Cell<bool>,
247 root: Cell<RootName>,
248}
249
250thread_local! {
251 static THREAD: ThreadState = const {
252 ThreadState {
253 label: Cell::new(0),
254 pending_label: Cell::new(0),
255 pending: Cell::new(0),
256 busy: Cell::new(false),
257 root: Cell::new(RootName::EMPTY),
258 }
259 };
260}
261
262pub struct TracingAllocator;
265
266unsafe impl GlobalAlloc for TracingAllocator {
267 #[inline]
268 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
269 let ptr = unsafe { ProcessAllocator.alloc(layout) };
270 if !ptr.is_null() {
271 on_alloc(layout.size());
272 }
273 ptr
274 }
275
276 #[inline]
277 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
278 let ptr = unsafe { ProcessAllocator.alloc_zeroed(layout) };
279 if !ptr.is_null() {
280 on_alloc(layout.size());
281 }
282 ptr
283 }
284
285 #[inline]
286 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
287 unsafe { ProcessAllocator.dealloc(ptr, layout) };
288 account(-(layout.size() as isize));
289 }
290
291 #[inline]
292 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
293 let next = unsafe { ProcessAllocator.realloc(ptr, layout, new_size) };
294 if !next.is_null() {
295 if new_size >= LARGE_ALLOCATION_BYTES {
296 record_large(EventKind::Realloc, new_size, layout.size());
297 }
298 account(new_size as isize - layout.size() as isize);
299 }
300 next
301 }
302}
303
304#[inline(always)]
305fn on_alloc(size: usize) {
306 if size >= LARGE_ALLOCATION_BYTES {
307 record_large(EventKind::Alloc, size, 0);
308 }
309 account(size as isize);
310}
311
312#[inline(always)]
314fn account(delta: isize) {
315 THREAD.with(|thread| {
316 let label = thread.label.get();
317 if label != thread.pending_label.get() {
318 switch_pending(thread, label, delta);
319 return;
320 }
321 if label == 0 {
322 return;
323 }
324 let pending = thread.pending.get() + delta;
325 if pending >= FLUSH_QUANTUM_BYTES || pending <= -FLUSH_QUANTUM_BYTES {
326 thread.pending.set(0);
327 flush(thread, label, pending);
328 } else {
329 thread.pending.set(pending);
330 }
331 });
332}
333
334#[cold]
337fn switch_pending(thread: &ThreadState, label: u8, delta: isize) {
338 let old = thread.pending_label.get();
339 let owed = thread.pending.replace(0);
340 if old != 0 && owed != 0 {
341 flush(thread, old, owed);
342 }
343 thread.pending_label.set(label);
344 if label == 0 {
345 return;
346 }
347 if delta >= FLUSH_QUANTUM_BYTES || delta <= -FLUSH_QUANTUM_BYTES {
348 flush(thread, label, delta);
349 } else {
350 thread.pending.set(delta);
351 }
352}
353
354#[cold]
357fn flush(thread: &ThreadState, label: u8, delta: isize) {
358 let state = &LABELS[usize::from(label)];
359 let live = state.live.fetch_add(delta, Ordering::Relaxed) + delta;
360 if delta > 0 {
361 state.census_peak.fetch_max(live, Ordering::Relaxed);
362 if live >= LABEL_BURST_BYTES {
363 state.burst_peak.fetch_max(live, Ordering::Relaxed);
364 if !state.crossed.load(Ordering::Relaxed)
365 && !state.crossed.swap(true, Ordering::Relaxed)
366 {
367 state.crossed_at_ns.store(monotonic_ns(), Ordering::Relaxed);
368 record_burst(thread, label, live);
369 }
370 }
371 } else if live < LABEL_BURST_BYTES / 2 && state.crossed.load(Ordering::Relaxed) {
372 end_burst(label, thread.root.get());
373 }
374}
375
376fn end_burst(label: u8, root: RootName) {
378 let state = &LABELS[usize::from(label)];
379 if !state.crossed.swap(false, Ordering::Relaxed) {
380 return;
381 }
382 let peak = state.burst_peak.swap(0, Ordering::Relaxed);
383 let started = state.crossed_at_ns.load(Ordering::Relaxed);
384 let mut event = ring::Event::new(EventKind::BurstEnded);
385 event.label = label;
386 event.root = root;
387 event.size = peak.max(0) as usize;
388 event.old_size = state.live.load(Ordering::Relaxed).max(0) as usize;
389 event.duration_ns = monotonic_ns().saturating_sub(started);
390 ring::push(&mut event);
391}
392
393#[derive(Clone, Copy, Debug, PartialEq, Eq)]
394pub(crate) enum EventKind {
395 Alloc,
396 Realloc,
397 BurstCrossed,
398 BurstEnded,
399}
400
401#[cold]
404#[inline(never)]
405fn record_large(kind: EventKind, size: usize, old_size: usize) {
406 THREAD.with(|thread| {
407 if thread.busy.replace(true) {
408 return;
409 }
410 let mut event = ring::Event::new(kind);
411 event.size = size;
412 event.old_size = old_size;
413 event.label = thread.label.get();
414 event.root = thread.root.get();
415 capture::fill(&mut event);
416 ring::push(&mut event);
417 thread.busy.set(false);
418 });
419}
420
421#[cold]
422#[inline(never)]
423fn record_burst(thread: &ThreadState, label: u8, live: isize) {
424 if thread.busy.replace(true) {
425 return;
426 }
427 let mut event = ring::Event::new(EventKind::BurstCrossed);
428 event.size = live.max(0) as usize;
429 event.label = label;
430 event.root = thread.root.get();
431 capture::fill(&mut event);
432 ring::push(&mut event);
433 thread.busy.set(false);
434}
435
436fn monotonic_ns() -> u64 {
437 static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
438 let epoch = *EPOCH.get_or_init(std::time::Instant::now);
439 u64::try_from(epoch.elapsed().as_nanos()).unwrap_or(u64::MAX)
440}
441
442#[must_use = "the label applies only while the guard lives"]
445pub struct ScopeGuard {
446 previous_label: u8,
447 previous_root: RootName,
448 label: u8,
449 owner: bool,
452 _not_send: PhantomData<*const ()>,
453}
454
455pub fn scope(label: Label, root: Option<&Path>) -> ScopeGuard {
459 let root = root.map(RootName::from_path);
460 enter(label.0, root, true)
461}
462
463fn enter(label: u8, root: Option<RootName>, owner: bool) -> ScopeGuard {
464 if owner && label != 0 {
465 LABELS[usize::from(label)]
466 .active
467 .fetch_add(1, Ordering::Relaxed);
468 }
469 THREAD.with(|thread| {
470 let previous_label = thread.label.replace(label);
471 let previous_root = thread.root.get();
472 if let Some(root) = root {
473 thread.root.set(root);
474 }
475 ScopeGuard {
476 previous_label,
477 previous_root,
478 label,
479 owner,
480 _not_send: PhantomData,
481 }
482 })
483}
484
485impl Drop for ScopeGuard {
486 fn drop(&mut self) {
487 let root = THREAD.with(|thread| {
488 let root = thread.root.get();
489 if self.owner && thread.pending_label.get() == self.label {
490 let owed = thread.pending.replace(0);
493 if self.label != 0 && owed != 0 {
494 flush(thread, self.label, owed);
495 }
496 }
497 thread.label.set(self.previous_label);
498 thread.root.set(self.previous_root);
499 root
500 });
501 if !self.owner || self.label == 0 {
502 return;
503 }
504 close_scope(self.label, root);
505 }
506}
507
508#[derive(Clone, Copy)]
510pub struct Carry {
511 label: u8,
512 root: RootName,
513}
514
515pub fn carry() -> Carry {
517 THREAD.with(|thread| Carry {
518 label: thread.label.get(),
519 root: thread.root.get(),
520 })
521}
522
523pub fn install<R: Send>(pool: &rayon::ThreadPool, op: impl FnOnce() -> R + Send) -> R {
526 pool.install(carry().wrap(op))
527}
528
529pub fn future<F: std::future::Future>(label: Label, root: Option<&Path>, inner: F) -> Labelled<F> {
533 Labelled {
534 inner,
535 carry: Carry {
536 label: label.0,
537 root: root.map_or_else(|| carry().root, RootName::from_path),
538 },
539 open: false,
540 }
541}
542
543pub struct Labelled<F> {
545 inner: F,
546 carry: Carry,
547 open: bool,
549}
550
551impl<F: std::future::Future> std::future::Future for Labelled<F> {
552 type Output = F::Output;
553
554 fn poll(
555 self: std::pin::Pin<&mut Self>,
556 cx: &mut std::task::Context<'_>,
557 ) -> std::task::Poll<F::Output> {
558 let this = unsafe { self.get_unchecked_mut() };
561 if !this.open && this.carry.label != 0 {
562 this.open = true;
563 LABELS[usize::from(this.carry.label)]
564 .active
565 .fetch_add(1, Ordering::Relaxed);
566 }
567 let _label = this.carry.enter();
568 unsafe { std::pin::Pin::new_unchecked(&mut this.inner) }.poll(cx)
570 }
571}
572
573impl<F> Drop for Labelled<F> {
574 fn drop(&mut self) {
575 if self.open {
576 close_scope(self.carry.label, self.carry.root);
577 }
578 }
579}
580
581fn close_scope(label: u8, root: RootName) {
586 let state = &LABELS[usize::from(label)];
587 if state.active.fetch_sub(1, Ordering::Relaxed) == 1 {
588 state.live.store(0, Ordering::Relaxed);
589 end_burst(label, root);
590 }
591}
592
593impl Carry {
594 pub fn enter(&self) -> ScopeGuard {
597 enter(self.label, Some(self.root), false)
598 }
599
600 pub fn wrap<R>(self, work: impl FnOnce() -> R) -> impl FnOnce() -> R {
602 move || {
603 let _label = self.enter();
604 work()
605 }
606 }
607
608 pub fn each<T, R>(self, work: impl Fn(T) -> R) -> impl Fn(T) -> R {
611 move |item| {
612 let _label = self.enter();
613 work(item)
614 }
615 }
616
617 pub fn label(&self) -> Label {
618 Label(self.label)
619 }
620}
621
622#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq)]
624pub struct LabelPeak {
625 pub label: &'static str,
626 pub peak_bytes: u64,
628 pub live_bytes: u64,
630}
631
632pub fn take_census_peaks(limit: usize) -> Vec<LabelPeak> {
639 if !report::logger_started() {
640 return Vec::new();
641 }
642 collect_census_peaks(limit)
643}
644
645fn collect_census_peaks(limit: usize) -> Vec<LabelPeak> {
646 let mut peaks = Vec::new();
647 for (id, state) in LABELS.iter().enumerate().skip(1) {
648 let live = state.live.load(Ordering::Relaxed).max(0);
649 let peak = state.census_peak.swap(live, Ordering::Relaxed).max(live);
650 if peak > 0 {
651 peaks.push((id as u8, peak as u64, live as u64));
652 }
653 }
654 peaks.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
655 peaks.truncate(limit);
656 peaks
657 .into_iter()
658 .map(|(id, peak_bytes, live_bytes)| LabelPeak {
659 label: label_name(id),
660 peak_bytes,
661 live_bytes,
662 })
663 .collect()
664}
665
666#[doc(hidden)]
669pub fn live_bytes(label: Label) -> isize {
670 let pending = THREAD.with(|thread| {
671 if thread.pending_label.get() == label.0 {
672 thread.pending.get()
673 } else {
674 0
675 }
676 });
677 LABELS[usize::from(label.0)].live.load(Ordering::Relaxed) + pending
678}
679
680#[cfg(test)]
681mod tests;