Skip to main content

traces/
kernel.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4use anyhow::Result;
5use fuchsia_async::{Interval, MonotonicDuration};
6use fuchsia_trace::{category_enabled, counter};
7use fuchsia_trace_observer::TraceObserver;
8use futures::{StreamExt, select};
9use log::debug;
10use stalls::StallProvider;
11use stalls::refaults::RefaultProvider;
12use std::ffi::CStr;
13const CATEGORY_MEMORY_KERNEL: &'static CStr = c"memory:kernel";
14use futures::future::FutureExt;
15
16// Continuously monitors the 'memory:kernel' trace category on a dedicated thread.
17// Once enabled, it periodically records memory statistics until the category is disabled.
18// This function runs indefinitely
19pub async fn serve_forever(
20    kernel_stats: impl fidl_fuchsia_kernel::StatsProxyInterface + Send + 'static,
21    stall_provider: impl StallProvider + Send + 'static,
22    page_refault_tracker: impl RefaultProvider + Send + 'static,
23) {
24    let (tx, rx) = futures::channel::oneshot::channel::<()>();
25    std::thread::Builder::new()
26        .name("memory:tracing".to_string())
27        .spawn(move || {
28            let mut executor = fuchsia_async::LocalExecutor::default();
29            executor.run_singlethreaded(serve_forever_loop(
30                kernel_stats,
31                stall_provider,
32                page_refault_tracker,
33            ));
34            // The task failed, send a message.
35            let _ = tx.send(());
36        })
37        .expect("failed to spawn memory:tracing thread");
38    let _ = rx.await;
39}
40
41// Internal loop, kept public for testing in
42// //src/performance/memory/attribution/monitor/tests/traces.
43pub async fn serve_forever_loop(
44    kernel_stats: impl fidl_fuchsia_kernel::StatsProxyInterface,
45    stall_provider: impl StallProvider,
46    page_refault_tracker: impl RefaultProvider,
47) {
48    fuchsia_trace_provider::trace_provider_create_with_fdio();
49    fuchsia_trace_provider::trace_provider_wait_for_init();
50    debug!("Start serving traces");
51    let trace_observer = TraceObserver::new();
52    loop {
53        let delay_in_secs = 1;
54        let mut interval = Interval::new(MonotonicDuration::from_seconds(1));
55        while category_enabled(CATEGORY_MEMORY_KERNEL) {
56            if let Err(err) = publish_one_sample(
57                &kernel_stats,
58                stall_provider.clone(),
59                page_refault_tracker.clone(),
60            )
61            .await
62            {
63                log::warn!("Failed to trace on category {:?} : {:?}", CATEGORY_MEMORY_KERNEL, err);
64            }
65            debug!("Wait for {} second(s)", delay_in_secs);
66            select! {
67                _ = interval.next() => (),
68                _ = trace_observer.on_state_changed().fuse() => (),
69            };
70        }
71        debug!("Trace category {:?} not active. Waiting.", CATEGORY_MEMORY_KERNEL);
72        let _ = trace_observer.on_state_changed().await;
73        debug!("Trace event detected");
74    }
75}
76
77async fn publish_one_sample(
78    kernel_stats: &impl fidl_fuchsia_kernel::StatsProxyInterface,
79    stall_provider: impl StallProvider,
80    page_refault_tracker: impl RefaultProvider,
81) -> Result<()> {
82    debug!("Publish trace records for category {:?}", CATEGORY_MEMORY_KERNEL);
83    let mem_stats = kernel_stats.get_memory_stats().await?;
84    // Statistics are split into two records to comply with the 15-argument limit.
85    counter!(CATEGORY_MEMORY_KERNEL, c"kmem_stats_a",0,
86        "total_bytes"=>mem_stats.total_bytes.unwrap_or_default(),
87        "free_bytes"=>mem_stats.free_bytes.unwrap_or_default(),
88        "free_loaned_bytes"=>mem_stats.free_loaned_bytes.unwrap_or_default(),
89        "wired_bytes"=>mem_stats.wired_bytes.unwrap_or_default(),
90        "total_heap_bytes"=>mem_stats.total_heap_bytes.unwrap_or_default(),
91        "free_heap_bytes"=>mem_stats.free_heap_bytes.unwrap_or_default(),
92        "vmo_bytes"=>mem_stats.vmo_bytes.unwrap_or_default(),
93        "mmu_overhead_bytes"=>mem_stats.mmu_overhead_bytes.unwrap_or_default(),
94        "ipc_bytes"=>mem_stats.ipc_bytes.unwrap_or_default(),
95        "cache_bytes"=>mem_stats.cache_bytes.unwrap_or_default(),
96        "slab_bytes"=>mem_stats.slab_bytes.unwrap_or_default(),
97        "zram_bytes"=>mem_stats.zram_bytes.unwrap_or_default(),
98        "other_bytes"=>mem_stats.other_bytes.unwrap_or_default()
99    );
100    counter!(CATEGORY_MEMORY_KERNEL, c"kmem_stats_b", 0,
101        "vmo_reclaim_total_bytes"=>mem_stats.vmo_reclaim_total_bytes.unwrap_or_default(),
102        "vmo_reclaim_newest_bytes"=>mem_stats.vmo_reclaim_newest_bytes.unwrap_or_default(),
103        "vmo_reclaim_oldest_bytes"=>mem_stats.vmo_reclaim_oldest_bytes.unwrap_or_default(),
104        "vmo_reclaim_disabled_bytes"=>mem_stats.vmo_reclaim_disabled_bytes.unwrap_or_default(),
105        "vmo_discardable_locked_bytes"=>mem_stats.vmo_discardable_locked_bytes.unwrap_or_default(),
106        "vmo_discardable_unlocked_bytes"=>mem_stats.vmo_discardable_unlocked_bytes.unwrap_or_default()
107    );
108    let cmp_stats = kernel_stats.get_memory_stats_compression().await?;
109    counter!(CATEGORY_MEMORY_KERNEL, c"kmem_stats_compression", 0,
110        "uncompressed_storage_bytes"=>cmp_stats.uncompressed_storage_bytes.unwrap_or_default(),
111        "compressed_storage_bytes"=>cmp_stats.compressed_storage_bytes.unwrap_or_default(),
112        "compressed_fragmentation_bytes"=>cmp_stats.compressed_fragmentation_bytes.unwrap_or_default(),
113        "compression_time"=>cmp_stats.compression_time.unwrap_or_default(),
114        "decompression_time"=>cmp_stats.decompression_time.unwrap_or_default(),
115        "total_page_compression_attempts"=>cmp_stats.total_page_compression_attempts.unwrap_or_default(),
116        "failed_page_compression_attempts"=>cmp_stats.failed_page_compression_attempts.unwrap_or_default(),
117        "total_page_decompressions"=>cmp_stats.total_page_decompressions.unwrap_or_default(),
118        "compressed_page_evictions"=>cmp_stats.compressed_page_evictions.unwrap_or_default(),
119        "eager_page_compressions"=>cmp_stats.eager_page_compressions.unwrap_or_default(),
120        "memory_pressure_page_compressions"=>cmp_stats.memory_pressure_page_compressions.unwrap_or_default(),
121        "critical_memory_page_compressions"=>cmp_stats.critical_memory_page_compressions.unwrap_or_default()
122    );
123
124    if let Some(pd) = cmp_stats.pages_decompressed_within_log_time {
125        counter!(
126            CATEGORY_MEMORY_KERNEL,
127            c"kmem_stats_compression_time",0,
128            "pages_decompressed_unit_ns"=>cmp_stats.pages_decompressed_unit_ns.unwrap_or_default(),
129            "pages_decompressed_within_log_time[0]"=>pd[0],
130            "pages_decompressed_within_log_time[1]"=>pd[1],
131            "pages_decompressed_within_log_time[2]"=>pd[2],
132            "pages_decompressed_within_log_time[3]"=>pd[3],
133            "pages_decompressed_within_log_time[4]"=>pd[4],
134            "pages_decompressed_within_log_time[5]"=>pd[5],
135            "pages_decompressed_within_log_time[6]"=>pd[6],
136            "pages_decompressed_within_log_time[7]"=>pd[7]
137        );
138    }
139
140    let stall_info = stall_provider.get_stall_info()?;
141    counter!(
142        CATEGORY_MEMORY_KERNEL,
143        c"memory_stall",0,
144        "stall_time_some_ns"=>u64::try_from(stall_info.some.as_nanos())?,
145        "stall_time_full_ns"=>u64::try_from(stall_info.full.as_nanos())?,
146        "page_refaults"=>page_refault_tracker.get_count()
147    );
148
149    Ok(())
150}