#[cfg(feature = "metrics")]
use crate::program_cache::metrics::LoadProgramMetrics;
use {
crate::{
invoke_context::{BuiltinFunctionRegisterer, InvokeContext},
program_cache::{
DELAY_VISIBILITY_SLOT_OFFSET, env::ProgramRuntimeEnvironment,
metrics::ProgramStatistics, owner::ProgramCacheEntryOwner,
},
},
solana_clock::Slot,
solana_pubkey::Pubkey,
solana_sbpf::{elf::Executable, program::BuiltinProgram, verifier::RequisiteVerifier},
solana_svm_type_overrides::sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
};
#[derive(Default)]
pub enum ProgramCacheEntryType {
FailedVerification(ProgramRuntimeEnvironment),
#[default]
Closed,
DelayVisibility,
Unloaded(ProgramRuntimeEnvironment),
Loaded(Executable<InvokeContext<'static, 'static>>),
Builtin(BuiltinProgram<InvokeContext<'static, 'static>>),
}
impl std::fmt::Debug for ProgramCacheEntryType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct(match self {
ProgramCacheEntryType::FailedVerification(_) => {
"ProgramCacheEntryType::FailedVerification"
}
ProgramCacheEntryType::Closed => "ProgramCacheEntryType::Closed",
ProgramCacheEntryType::DelayVisibility => "ProgramCacheEntryType::DelayVisibility",
ProgramCacheEntryType::Unloaded(_) => "ProgramCacheEntryType::Unloaded",
ProgramCacheEntryType::Loaded(_) => "ProgramCacheEntryType::Loaded",
ProgramCacheEntryType::Builtin(_) => "ProgramCacheEntryType::Builtin",
})
.finish()
}
}
impl ProgramCacheEntryType {
pub fn get_environment(&self) -> Option<&ProgramRuntimeEnvironment> {
match self {
ProgramCacheEntryType::Loaded(program) => {
Some(ProgramRuntimeEnvironment::from_ref(program.get_loader()))
}
ProgramCacheEntryType::FailedVerification(env)
| ProgramCacheEntryType::Unloaded(env) => Some(env),
_ => None,
}
}
}
#[derive(Default)]
pub struct ProgramCacheEntry {
pub program: ProgramCacheEntryType,
pub account_owner: ProgramCacheEntryOwner,
pub deployment_slot: Slot,
pub stats: Arc<ProgramStatistics>,
pub latest_access_slot: AtomicU64,
}
impl std::fmt::Debug for ProgramCacheEntry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProgramCacheEntry")
.field("slot", &self.deployment_slot)
.field(
"env",
&self
.program
.get_environment()
.map(|env| Arc::as_ptr(env))
.unwrap_or(std::ptr::null()),
)
.field("type", &self.program)
.finish()
}
}
#[cfg(feature = "dev-context-only-utils")]
impl PartialEq for ProgramCacheEntry {
fn eq(&self, other: &Self) -> bool {
self.deployment_slot == other.deployment_slot
&& self.account_owner == other.account_owner
&& std::mem::discriminant(&self.program) == std::mem::discriminant(&other.program)
}
}
impl ProgramCacheEntry {
pub fn load(
loader_key: &Pubkey,
program_runtime_environment: ProgramRuntimeEnvironment,
deployment_slot: Slot,
elf_bytes: &[u8],
#[cfg(feature = "metrics")] metrics: &mut LoadProgramMetrics,
) -> Result<Self, Box<dyn std::error::Error>> {
let entry_stats = ProgramStatistics::default();
#[cfg(feature = "metrics")]
let load_elf_time = solana_svm_measure::measure::Measure::start("load_elf_time");
let executable = Executable::load(elf_bytes, Arc::clone(&*program_runtime_environment))?;
#[cfg(feature = "metrics")]
{
metrics.load_elf_us = load_elf_time.end_as_us();
}
#[cfg(feature = "metrics")]
let verify_code_time = solana_svm_measure::measure::Measure::start("verify_code_time");
executable.verify::<RequisiteVerifier>()?;
#[cfg(feature = "metrics")]
{
metrics.verify_code_us = verify_code_time.end_as_us();
}
#[cfg(all(not(target_os = "windows"), target_arch = "x86_64"))]
{
let jit_compile_time = solana_svm_measure::measure::Measure::start("jit_compile_time");
executable.jit_compile()?;
let jit_compile_time = jit_compile_time.end_as_us();
entry_stats.jit_compiled(jit_compile_time);
#[cfg(feature = "metrics")]
{
metrics.jit_compile_us = jit_compile_time;
}
}
Ok(Self {
deployment_slot,
account_owner: ProgramCacheEntryOwner::try_from(loader_key).unwrap(),
program: ProgramCacheEntryType::Loaded(executable),
stats: entry_stats.into(),
latest_access_slot: AtomicU64::new(0),
})
}
pub fn new_unloaded(
deployment_slot: Slot,
account_owner: ProgramCacheEntryOwner,
program_runtime_environment: ProgramRuntimeEnvironment,
) -> Self {
Self {
program: ProgramCacheEntryType::Unloaded(program_runtime_environment),
account_owner,
deployment_slot,
stats: Arc::default(),
latest_access_slot: AtomicU64::new(deployment_slot),
}
}
pub fn to_unloaded(&self) -> Option<Self> {
let environment = ProgramRuntimeEnvironment::clone(self.program.get_environment()?);
Some(Self {
program: ProgramCacheEntryType::Unloaded(environment),
account_owner: self.account_owner,
deployment_slot: self.deployment_slot,
stats: Arc::clone(&self.stats),
latest_access_slot: AtomicU64::new(self.latest_access_slot.load(Ordering::Relaxed)),
})
}
pub fn new_builtin(register_fn: BuiltinFunctionRegisterer) -> Self {
let mut program = BuiltinProgram::new_builtin();
register_fn(&mut program, "entrypoint").unwrap();
Self {
deployment_slot: 0, account_owner: ProgramCacheEntryOwner::NativeLoader,
program: ProgramCacheEntryType::Builtin(program),
stats: Arc::default(),
latest_access_slot: AtomicU64::new(0),
}
}
pub fn new_failed_verification_tombstone(
deployment_slot: Slot,
account_owner: ProgramCacheEntryOwner,
program_runtime_environment: ProgramRuntimeEnvironment,
) -> Self {
Self {
program: ProgramCacheEntryType::FailedVerification(program_runtime_environment),
account_owner,
deployment_slot,
stats: Arc::default(),
latest_access_slot: AtomicU64::new(0),
}
}
pub fn new_closed_tombstone(
deployment_slot: Slot,
account_owner: ProgramCacheEntryOwner,
) -> Self {
Self {
program: ProgramCacheEntryType::Closed,
account_owner,
deployment_slot,
stats: Arc::default(),
latest_access_slot: AtomicU64::new(0),
}
}
pub fn new_delay_visibility_tombstone(
deployment_slot: Slot,
account_owner: ProgramCacheEntryOwner,
stats: Arc<ProgramStatistics>,
) -> Self {
Self {
program: ProgramCacheEntryType::DelayVisibility,
account_owner,
deployment_slot,
stats,
latest_access_slot: AtomicU64::new(0),
}
}
pub fn is_tombstone(&self) -> bool {
matches!(
self.program,
ProgramCacheEntryType::FailedVerification(_)
| ProgramCacheEntryType::Closed
| ProgramCacheEntryType::DelayVisibility
)
}
pub(crate) fn is_implicit_delay_visibility_tombstone(&self, slot: Slot) -> bool {
slot >= self.deployment_slot && slot < self.effective_slot()
}
pub fn is_unloaded(&self) -> bool {
matches!(self.program, ProgramCacheEntryType::Unloaded(_))
}
pub fn effective_slot(&self) -> Slot {
match self.program {
ProgramCacheEntryType::Closed
| ProgramCacheEntryType::DelayVisibility
| ProgramCacheEntryType::FailedVerification(_)
| ProgramCacheEntryType::Builtin(_) => self.deployment_slot,
ProgramCacheEntryType::Unloaded(_) | ProgramCacheEntryType::Loaded(_) => self
.deployment_slot
.saturating_add(DELAY_VISIBILITY_SLOT_OFFSET),
}
}
pub fn update_access_slot(&self, slot: Slot) {
let _ = self.latest_access_slot.fetch_max(slot, Ordering::Relaxed);
}
pub fn retention_score(&self) -> u64 {
let last_access = self.latest_access_slot.load(Ordering::Relaxed);
let recovery_cost = self.stats.compilation_time_ema.load(Ordering::Relaxed);
let frequency = self.stats.uses.load(Ordering::Relaxed);
retention_score(last_access, recovery_cost, frequency)
}
}
pub(crate) const fn retention_score(last_access: u64, recovery_cost: u64, frequency: u64) -> u64 {
let weight = (recovery_cost as u128).wrapping_mul(frequency as u128);
let weight_log = u128::BITS.wrapping_sub(weight.leading_zeros());
last_access.saturating_add(weight_log as u64)
}
#[cfg(test)]
pub(crate) fn new_loaded_entry(env: ProgramRuntimeEnvironment) -> ProgramCacheEntryType {
use std::{fs::File, io::Read};
let mut elf = Vec::new();
File::open("../programs/bpf_loader/test_elfs/out/noop_aligned.so")
.unwrap()
.read_to_end(&mut elf)
.unwrap();
let executable = Executable::load(&elf, Arc::clone(&*env)).unwrap();
ProgramCacheEntryType::Loaded(executable)
}
#[cfg(test)]
pub(crate) fn new_test_entry_with_usage(
deployment_slot: Slot,
stats: ProgramStatistics,
) -> Arc<ProgramCacheEntry> {
use crate::program_cache::env::get_mock_program_runtime_environment;
Arc::new(ProgramCacheEntry {
program: new_loaded_entry(get_mock_program_runtime_environment()),
account_owner: ProgramCacheEntryOwner::LoaderV2,
deployment_slot,
stats: Arc::new(stats),
latest_access_slot: AtomicU64::new(deployment_slot),
})
}
#[cfg(test)]
mod tests {
use {
super::new_test_entry_with_usage,
crate::program_cache::metrics::ProgramStatistics,
std::sync::atomic::{AtomicU64, Ordering},
};
#[test]
fn test_retention_score_decay_horizon() {
let stats = ProgramStatistics {
uses: AtomicU64::new(u64::MAX),
compilation_time_ema: AtomicU64::new(u64::MAX),
..Default::default()
};
let program = new_test_entry_with_usage(0, stats);
program.update_access_slot(1);
assert!(
dbg!(program.retention_score()) <= 129,
"retention score should remain within sensible boundaries even for very frequently \
used entries."
);
}
#[test]
fn test_retention_score_frequency_preference() {
let stats = ProgramStatistics {
uses: AtomicU64::new(16),
compilation_time_ema: AtomicU64::new(1),
..Default::default()
};
let program = new_test_entry_with_usage(10, stats);
program.update_access_slot(15);
let less_used_retention_score = program.retention_score();
program.stats.uses.fetch_max(1024, Ordering::Relaxed);
let more_used_retention_score = program.retention_score();
assert!(
less_used_retention_score > 15,
"frequency should count for entry retention score"
);
assert!(
dbg!(more_used_retention_score) > dbg!(less_used_retention_score),
"retention score should prefer evicting less used entry over the more used one if \
possible"
);
}
#[test]
fn test_retention_score_recovery_time_preference() {
let stats = ProgramStatistics {
uses: AtomicU64::new(1),
compilation_time_ema: AtomicU64::new(1000),
..Default::default()
};
let program = new_test_entry_with_usage(10, stats);
program.update_access_slot(15);
let cheaper_to_compile_score = program.retention_score();
program
.stats
.compilation_time_ema
.fetch_max(2000, Ordering::Relaxed);
let more_expensive_to_compile_score = program.retention_score();
assert!(
cheaper_to_compile_score > 15,
"compile time should count for entry retention score"
);
assert!(
dbg!(more_expensive_to_compile_score) > dbg!(cheaper_to_compile_score),
"retention score should prefer evicting cheaper-to-compile entries"
);
}
#[test]
fn test_retention_weight_metric_does_not_outweight_smaller_metric() {
let stats = ProgramStatistics {
uses: AtomicU64::new(100_000_000),
compilation_time_ema: AtomicU64::new(1000),
..Default::default()
};
let program = new_test_entry_with_usage(10, stats);
program.update_access_slot(15);
let previous_score = program.retention_score();
program
.stats
.compilation_time_ema
.fetch_max(2000, Ordering::Relaxed);
let new_score = program.retention_score();
assert!(
dbg!(previous_score) != dbg!(new_score),
"retention weight components shouldn't overshadow the other due to scale differences"
);
}
}