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::{select, StreamExt};
9use log::debug;
10use stalls::StallProvider;
11use std::ffi::CStr;
12use std::sync::Arc;
13const CATEGORY_MEMORY_KERNEL: &'static CStr = c"memory:kernel";
14use futures::future::FutureExt;
15
16// Continuously monitors the 'memory:kernel' trace category.
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,
21    stall_provider: Arc<impl StallProvider>,
22) {
23    fuchsia_trace_provider::trace_provider_create_with_fdio();
24    fuchsia_trace_provider::trace_provider_wait_for_init();
25    eprintln!("Start serving traces");
26    debug!("Start serving traces");
27    let trace_observer = TraceObserver::new();
28    loop {
29        let delay_in_secs = 1;
30        let mut interval = Interval::new(MonotonicDuration::from_seconds(1));
31        while category_enabled(CATEGORY_MEMORY_KERNEL) {
32            if let Err(err) = publish_one_sample(&kernel_stats, stall_provider.clone()).await {
33                log::warn!("Failed to trace on category {:?} : {:?}", CATEGORY_MEMORY_KERNEL, err);
34            }
35            debug!("Wait for {} second(s)", delay_in_secs);
36            select! {
37                _ = interval.next() => (),
38                _ = trace_observer.on_state_changed().fuse() => (),
39            };
40        }
41        debug!("Trace category {:?} not active. Waiting.", CATEGORY_MEMORY_KERNEL);
42        let _ = trace_observer.on_state_changed().await;
43        debug!("Trace event detected");
44    }
45}
46
47async fn publish_one_sample(
48    kernel_stats: &impl fidl_fuchsia_kernel::StatsProxyInterface,
49    stall_provider: Arc<impl StallProvider>,
50) -> Result<()> {
51    debug!("Publish trace records for category {:?}", CATEGORY_MEMORY_KERNEL);
52    let mem_stats = kernel_stats.get_memory_stats().await?;
53    // Statistics are split into two records to comply with the 15-argument limit.
54    counter!(CATEGORY_MEMORY_KERNEL, c"kmem_stats_a",0,
55        "total_bytes"=>mem_stats.total_bytes.unwrap_or_default(),
56        "free_bytes"=>mem_stats.free_bytes.unwrap_or_default(),
57        "free_loaned_bytes"=>mem_stats.free_loaned_bytes.unwrap_or_default(),
58        "wired_bytes"=>mem_stats.wired_bytes.unwrap_or_default(),
59        "total_heap_bytes"=>mem_stats.total_heap_bytes.unwrap_or_default(),
60        "free_heap_bytes"=>mem_stats.free_heap_bytes.unwrap_or_default(),
61        "vmo_bytes"=>mem_stats.vmo_bytes.unwrap_or_default(),
62        "mmu_overhead_bytes"=>mem_stats.mmu_overhead_bytes.unwrap_or_default(),
63        "ipc_bytes"=>mem_stats.ipc_bytes.unwrap_or_default(),
64        "cache_bytes"=>mem_stats.cache_bytes.unwrap_or_default(),
65        "slab_bytes"=>mem_stats.slab_bytes.unwrap_or_default(),
66        "zram_bytes"=>mem_stats.zram_bytes.unwrap_or_default(),
67        "other_bytes"=>mem_stats.other_bytes.unwrap_or_default()
68    );
69    counter!(CATEGORY_MEMORY_KERNEL, c"kmem_stats_b", 0,
70        "vmo_reclaim_total_bytes"=>mem_stats.vmo_reclaim_total_bytes.unwrap_or_default(),
71        "vmo_reclaim_newest_bytes"=>mem_stats.vmo_reclaim_newest_bytes.unwrap_or_default(),
72        "vmo_reclaim_oldest_bytes"=>mem_stats.vmo_reclaim_oldest_bytes.unwrap_or_default(),
73        "vmo_reclaim_disabled_bytes"=>mem_stats.vmo_reclaim_disabled_bytes.unwrap_or_default(),
74        "vmo_discardable_locked_bytes"=>mem_stats.vmo_discardable_locked_bytes.unwrap_or_default(),
75        "vmo_discardable_unlocked_bytes"=>mem_stats.vmo_discardable_unlocked_bytes.unwrap_or_default()
76    );
77    let cmp_stats = kernel_stats.get_memory_stats_compression().await?;
78    counter!(CATEGORY_MEMORY_KERNEL, c"kmem_stats_compression", 0,
79        "uncompressed_storage_bytes"=>cmp_stats.uncompressed_storage_bytes.unwrap_or_default(),
80        "compressed_storage_bytes"=>cmp_stats.compressed_storage_bytes.unwrap_or_default(),
81        "compressed_fragmentation_bytes"=>cmp_stats.compressed_fragmentation_bytes.unwrap_or_default(),
82        "compression_time"=>cmp_stats.compression_time.unwrap_or_default(),
83        "decompression_time"=>cmp_stats.decompression_time.unwrap_or_default(),
84        "total_page_compression_attempts"=>cmp_stats.total_page_compression_attempts.unwrap_or_default(),
85        "failed_page_compression_attempts"=>cmp_stats.failed_page_compression_attempts.unwrap_or_default(),
86        "total_page_decompressions"=>cmp_stats.total_page_decompressions.unwrap_or_default(),
87        "compressed_page_evictions"=>cmp_stats.compressed_page_evictions.unwrap_or_default(),
88        "eager_page_compressions"=>cmp_stats.eager_page_compressions.unwrap_or_default(),
89        "memory_pressure_page_compressions"=>cmp_stats.memory_pressure_page_compressions.unwrap_or_default(),
90        "critical_memory_page_compressions"=>cmp_stats.critical_memory_page_compressions.unwrap_or_default()
91    );
92
93    if let Some(pd) = cmp_stats.pages_decompressed_within_log_time {
94        counter!(
95            CATEGORY_MEMORY_KERNEL,
96            c"kmem_stats_compression_time",0,
97            "pages_decompressed_unit_ns"=>cmp_stats.pages_decompressed_unit_ns.unwrap_or_default(),
98            "pages_decompressed_within_log_time[0]"=>pd[0],
99            "pages_decompressed_within_log_time[1]"=>pd[1],
100            "pages_decompressed_within_log_time[2]"=>pd[2],
101            "pages_decompressed_within_log_time[3]"=>pd[3],
102            "pages_decompressed_within_log_time[4]"=>pd[4],
103            "pages_decompressed_within_log_time[5]"=>pd[5],
104            "pages_decompressed_within_log_time[6]"=>pd[6],
105            "pages_decompressed_within_log_time[7]"=>pd[7]
106        );
107    }
108
109    let stall_info = stall_provider.get_stall_info()?;
110    counter!(
111        CATEGORY_MEMORY_KERNEL,
112        c"memory_stall",0,
113        "stall_time_some_ns"=>u64::try_from(stall_info.some.as_nanos())?,
114        "stall_time_full_ns"=>u64::try_from(stall_info.full.as_nanos())?
115    );
116
117    Ok(())
118}