forked from solana-labs/solana
-
Notifications
You must be signed in to change notification settings - Fork 331
/
Copy pathloaded_programs.rs
2789 lines (2524 loc) · 111 KB
/
loaded_programs.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use {
crate::{
invoke_context::{BuiltinFunctionWithContext, InvokeContext},
timings::ExecuteDetailsTimings,
},
log::{debug, error, log_enabled, trace},
percentage::PercentageInteger,
solana_measure::measure::Measure,
solana_rbpf::{
elf::Executable,
program::{BuiltinProgram, FunctionRegistry},
verifier::RequisiteVerifier,
vm::Config,
},
solana_sdk::{
bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable,
clock::{Epoch, Slot},
loader_v4, native_loader,
pubkey::Pubkey,
saturating_add_assign,
},
solana_type_overrides::{
rand::{thread_rng, Rng},
sync::{
atomic::{AtomicU64, Ordering},
Arc, Condvar, Mutex, RwLock,
},
thread,
},
std::{
collections::{hash_map::Entry, HashMap},
fmt::{Debug, Formatter},
sync::Weak,
},
};
pub type ProgramRuntimeEnvironment = Arc<BuiltinProgram<InvokeContext<'static>>>;
pub const MAX_LOADED_ENTRY_COUNT: usize = 256;
pub const DELAY_VISIBILITY_SLOT_OFFSET: Slot = 1;
/// Relationship between two fork IDs
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum BlockRelation {
/// The slot is on the same fork and is an ancestor of the other slot
Ancestor,
/// The two slots are equal and are on the same fork
Equal,
/// The slot is on the same fork and is a descendant of the other slot
Descendant,
/// The slots are on two different forks and may have had a common ancestor at some point
Unrelated,
/// Either one or both of the slots are either older than the latest root, or are in future
Unknown,
}
/// Maps relationship between two slots.
pub trait ForkGraph {
/// Returns the BlockRelation of A to B
fn relationship(&self, a: Slot, b: Slot) -> BlockRelation;
/// Returns the epoch of the given slot
fn slot_epoch(&self, _slot: Slot) -> Option<Epoch> {
Some(0)
}
}
/// The owner of a programs accounts, thus the loader of a program
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub enum ProgramCacheEntryOwner {
#[default]
NativeLoader,
LoaderV1,
LoaderV2,
LoaderV3,
LoaderV4,
}
impl TryFrom<&Pubkey> for ProgramCacheEntryOwner {
type Error = ();
fn try_from(loader_key: &Pubkey) -> Result<Self, ()> {
if native_loader::check_id(loader_key) {
Ok(ProgramCacheEntryOwner::NativeLoader)
} else if bpf_loader_deprecated::check_id(loader_key) {
Ok(ProgramCacheEntryOwner::LoaderV1)
} else if bpf_loader::check_id(loader_key) {
Ok(ProgramCacheEntryOwner::LoaderV2)
} else if bpf_loader_upgradeable::check_id(loader_key) {
Ok(ProgramCacheEntryOwner::LoaderV3)
} else if loader_v4::check_id(loader_key) {
Ok(ProgramCacheEntryOwner::LoaderV4)
} else {
Err(())
}
}
}
impl From<ProgramCacheEntryOwner> for Pubkey {
fn from(program_cache_entry_owner: ProgramCacheEntryOwner) -> Self {
match program_cache_entry_owner {
ProgramCacheEntryOwner::NativeLoader => native_loader::id(),
ProgramCacheEntryOwner::LoaderV1 => bpf_loader_deprecated::id(),
ProgramCacheEntryOwner::LoaderV2 => bpf_loader::id(),
ProgramCacheEntryOwner::LoaderV3 => bpf_loader_upgradeable::id(),
ProgramCacheEntryOwner::LoaderV4 => loader_v4::id(),
}
}
}
/*
The possible ProgramCacheEntryType transitions:
DelayVisibility is special in that it is never stored in the cache.
It is only returned by ProgramCacheForTxBatch::find() when a Loaded entry
is encountered which is not effective yet.
Builtin re/deployment:
- Empty => Builtin in TransactionBatchProcessor::add_builtin
- Builtin => Builtin in TransactionBatchProcessor::add_builtin
Un/re/deployment (with delay and cooldown):
- Empty / Closed => Loaded in UpgradeableLoaderInstruction::DeployWithMaxDataLen
- Loaded / FailedVerification => Loaded in UpgradeableLoaderInstruction::Upgrade
- Loaded / FailedVerification => Closed in UpgradeableLoaderInstruction::Close
Eviction and unloading (in the same slot):
- Unloaded => Loaded in ProgramCache::assign_program
- Loaded => Unloaded in ProgramCache::unload_program_entry
At epoch boundary (when feature set and environment changes):
- Loaded => FailedVerification in Bank::_new_from_parent
- FailedVerification => Loaded in Bank::_new_from_parent
Through pruning (when on orphan fork or overshadowed on the rooted fork):
- Closed / Unloaded / Loaded / Builtin => Empty in ProgramCache::prune
*/
/// Actual payload of [ProgramCacheEntry].
#[derive(Default)]
pub enum ProgramCacheEntryType {
/// Tombstone for programs which currently do not pass the verifier but could if the feature set changed.
FailedVerification(ProgramRuntimeEnvironment),
/// Tombstone for programs that were either explicitly closed or never deployed.
///
/// It's also used for accounts belonging to program loaders, that don't actually contain program code (e.g. buffer accounts for LoaderV3 programs).
#[default]
Closed,
/// Tombstone for programs which have recently been modified but the new version is not visible yet.
DelayVisibility,
/// Successfully verified but not currently compiled.
///
/// It continues to track usage statistics even when the compiled executable of the program is evicted from memory.
Unloaded(ProgramRuntimeEnvironment),
/// Verified and compiled program
Loaded(Executable<InvokeContext<'static>>),
/// A built-in program which is not stored on-chain but backed into and distributed with the validator
Builtin(BuiltinProgram<InvokeContext<'static>>),
}
impl Debug for ProgramCacheEntryType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ProgramCacheEntryType::FailedVerification(_) => {
write!(f, "ProgramCacheEntryType::FailedVerification")
}
ProgramCacheEntryType::Closed => write!(f, "ProgramCacheEntryType::Closed"),
ProgramCacheEntryType::DelayVisibility => {
write!(f, "ProgramCacheEntryType::DelayVisibility")
}
ProgramCacheEntryType::Unloaded(_) => write!(f, "ProgramCacheEntryType::Unloaded"),
ProgramCacheEntryType::Loaded(_) => write!(f, "ProgramCacheEntryType::Loaded"),
ProgramCacheEntryType::Builtin(_) => write!(f, "ProgramCacheEntryType::Builtin"),
}
}
}
impl ProgramCacheEntryType {
/// Returns a reference to its environment if it has one
pub fn get_environment(&self) -> Option<&ProgramRuntimeEnvironment> {
match self {
ProgramCacheEntryType::Loaded(program) => Some(program.get_loader()),
ProgramCacheEntryType::FailedVerification(env)
| ProgramCacheEntryType::Unloaded(env) => Some(env),
_ => None,
}
}
}
/// Holds a program version at a specific address and on a specific slot / fork.
///
/// It contains the actual program in [ProgramCacheEntryType] and a bunch of meta-data.
#[derive(Debug, Default)]
pub struct ProgramCacheEntry {
/// The program of this entry
pub program: ProgramCacheEntryType,
/// The loader of this entry
pub account_owner: ProgramCacheEntryOwner,
/// Size of account that stores the program and program data
pub account_size: usize,
/// Slot in which the program was (re)deployed
pub deployment_slot: Slot,
/// Slot in which this entry will become active (can be in the future)
pub effective_slot: Slot,
/// How often this entry was used by a transaction
pub tx_usage_counter: AtomicU64,
/// How often this entry was used by an instruction
pub ix_usage_counter: AtomicU64,
/// Latest slot in which the entry was used
pub latest_access_slot: AtomicU64,
}
/// Global cache statistics for [ProgramCache].
#[derive(Debug, Default)]
pub struct ProgramCacheStats {
/// a program was already in the cache
pub hits: AtomicU64,
/// a program was not found and loaded instead
pub misses: AtomicU64,
/// a compiled executable was unloaded
pub evictions: HashMap<Pubkey, u64>,
/// an unloaded program was loaded again (opposite of eviction)
pub reloads: AtomicU64,
/// a program was loaded or un/re/deployed
pub insertions: AtomicU64,
/// a program was loaded but can not be extracted on its own fork anymore
pub lost_insertions: AtomicU64,
/// a program which was already in the cache was reloaded by mistake
pub replacements: AtomicU64,
/// a program was only used once before being unloaded
pub one_hit_wonders: AtomicU64,
/// a program became unreachable in the fork graph because of rerooting
pub prunes_orphan: AtomicU64,
/// a program got pruned because it was not recompiled for the next epoch
pub prunes_environment: AtomicU64,
/// a program had no entries because all slot versions got pruned
pub empty_entries: AtomicU64,
/// water level of loaded entries currently cached
pub water_level: AtomicU64,
}
impl ProgramCacheStats {
pub fn reset(&mut self) {
*self = ProgramCacheStats::default();
}
pub fn log(&self) {
let hits = self.hits.load(Ordering::Relaxed);
let misses = self.misses.load(Ordering::Relaxed);
let evictions: u64 = self.evictions.values().sum();
let reloads = self.reloads.load(Ordering::Relaxed);
let insertions = self.insertions.load(Ordering::Relaxed);
let lost_insertions = self.lost_insertions.load(Ordering::Relaxed);
let replacements = self.replacements.load(Ordering::Relaxed);
let one_hit_wonders = self.one_hit_wonders.load(Ordering::Relaxed);
let prunes_orphan = self.prunes_orphan.load(Ordering::Relaxed);
let prunes_environment = self.prunes_environment.load(Ordering::Relaxed);
let empty_entries = self.empty_entries.load(Ordering::Relaxed);
let water_level = self.water_level.load(Ordering::Relaxed);
debug!(
"Loaded Programs Cache Stats -- Hits: {}, Misses: {}, Evictions: {}, Reloads: {}, Insertions: {}, Lost-Insertions: {}, Replacements: {}, One-Hit-Wonders: {}, Prunes-Orphan: {}, Prunes-Environment: {}, Empty: {}, Water-Level: {}",
hits, misses, evictions, reloads, insertions, lost_insertions, replacements, one_hit_wonders, prunes_orphan, prunes_environment, empty_entries, water_level
);
if log_enabled!(log::Level::Trace) && !self.evictions.is_empty() {
let mut evictions = self.evictions.iter().collect::<Vec<_>>();
evictions.sort_by_key(|e| e.1);
let evictions = evictions
.into_iter()
.rev()
.map(|(program_id, evictions)| {
format!(" {:<44} {}", program_id.to_string(), evictions)
})
.collect::<Vec<_>>();
let evictions = evictions.join("\n");
trace!(
"Eviction Details:\n {:<44} {}\n{}",
"Program",
"Count",
evictions
);
}
}
}
/// Time measurements for loading a single [ProgramCacheEntry].
#[derive(Debug, Default)]
pub struct LoadProgramMetrics {
/// Program address, but as text
pub program_id: String,
/// Microseconds it took to `create_program_runtime_environment`
pub register_syscalls_us: u64,
/// Microseconds it took to `Executable::<InvokeContext>::load`
pub load_elf_us: u64,
/// Microseconds it took to `executable.verify::<RequisiteVerifier>`
pub verify_code_us: u64,
/// Microseconds it took to `executable.jit_compile`
pub jit_compile_us: u64,
}
impl LoadProgramMetrics {
pub fn submit_datapoint(&self, timings: &mut ExecuteDetailsTimings) {
saturating_add_assign!(
timings.create_executor_register_syscalls_us,
self.register_syscalls_us
);
saturating_add_assign!(timings.create_executor_load_elf_us, self.load_elf_us);
saturating_add_assign!(timings.create_executor_verify_code_us, self.verify_code_us);
saturating_add_assign!(timings.create_executor_jit_compile_us, self.jit_compile_us);
datapoint_trace!(
"create_executor_trace",
("program_id", self.program_id, String),
("register_syscalls_us", self.register_syscalls_us, i64),
("load_elf_us", self.load_elf_us, i64),
("verify_code_us", self.verify_code_us, i64),
("jit_compile_us", self.jit_compile_us, i64),
);
}
}
impl PartialEq for ProgramCacheEntry {
fn eq(&self, other: &Self) -> bool {
self.effective_slot == other.effective_slot
&& self.deployment_slot == other.deployment_slot
&& self.is_tombstone() == other.is_tombstone()
}
}
impl ProgramCacheEntry {
/// Creates a new user program
pub fn new(
loader_key: &Pubkey,
program_runtime_environment: ProgramRuntimeEnvironment,
deployment_slot: Slot,
effective_slot: Slot,
elf_bytes: &[u8],
account_size: usize,
metrics: &mut LoadProgramMetrics,
) -> Result<Self, Box<dyn std::error::Error>> {
Self::new_internal(
loader_key,
program_runtime_environment,
deployment_slot,
effective_slot,
elf_bytes,
account_size,
metrics,
false, /* reloading */
)
}
/// Reloads a user program, *without* running the verifier.
///
/// # Safety
///
/// This method is unsafe since it assumes that the program has already been verified. Should
/// only be called when the program was previously verified and loaded in the cache, but was
/// unloaded due to inactivity. It should also be checked that the `program_runtime_environment`
/// hasn't changed since it was unloaded.
pub unsafe fn reload(
loader_key: &Pubkey,
program_runtime_environment: Arc<BuiltinProgram<InvokeContext<'static>>>,
deployment_slot: Slot,
effective_slot: Slot,
elf_bytes: &[u8],
account_size: usize,
metrics: &mut LoadProgramMetrics,
) -> Result<Self, Box<dyn std::error::Error>> {
Self::new_internal(
loader_key,
program_runtime_environment,
deployment_slot,
effective_slot,
elf_bytes,
account_size,
metrics,
true, /* reloading */
)
}
fn new_internal(
loader_key: &Pubkey,
program_runtime_environment: Arc<BuiltinProgram<InvokeContext<'static>>>,
deployment_slot: Slot,
effective_slot: Slot,
elf_bytes: &[u8],
account_size: usize,
metrics: &mut LoadProgramMetrics,
reloading: bool,
) -> Result<Self, Box<dyn std::error::Error>> {
let load_elf_time = Measure::start("load_elf_time");
// The following unused_mut exception is needed for architectures that do not
// support JIT compilation.
#[allow(unused_mut)]
let mut executable = Executable::load(elf_bytes, program_runtime_environment.clone())?;
metrics.load_elf_us = load_elf_time.end_as_us();
if !reloading {
let verify_code_time = Measure::start("verify_code_time");
executable.verify::<RequisiteVerifier>()?;
metrics.verify_code_us = verify_code_time.end_as_us();
}
#[cfg(all(not(target_os = "windows"), target_arch = "x86_64"))]
{
let jit_compile_time = Measure::start("jit_compile_time");
executable.jit_compile()?;
metrics.jit_compile_us = jit_compile_time.end_as_us();
}
Ok(Self {
deployment_slot,
account_owner: ProgramCacheEntryOwner::try_from(loader_key).unwrap(),
account_size,
effective_slot,
tx_usage_counter: AtomicU64::new(0),
program: ProgramCacheEntryType::Loaded(executable),
ix_usage_counter: AtomicU64::new(0),
latest_access_slot: AtomicU64::new(0),
})
}
pub fn to_unloaded(&self) -> Option<Self> {
match &self.program {
ProgramCacheEntryType::Loaded(_) => {}
ProgramCacheEntryType::FailedVerification(_)
| ProgramCacheEntryType::Closed
| ProgramCacheEntryType::DelayVisibility
| ProgramCacheEntryType::Unloaded(_)
| ProgramCacheEntryType::Builtin(_) => {
return None;
}
}
Some(Self {
program: ProgramCacheEntryType::Unloaded(self.program.get_environment()?.clone()),
account_owner: self.account_owner,
account_size: self.account_size,
deployment_slot: self.deployment_slot,
effective_slot: self.effective_slot,
tx_usage_counter: AtomicU64::new(self.tx_usage_counter.load(Ordering::Relaxed)),
ix_usage_counter: AtomicU64::new(self.ix_usage_counter.load(Ordering::Relaxed)),
latest_access_slot: AtomicU64::new(self.latest_access_slot.load(Ordering::Relaxed)),
})
}
/// Creates a new built-in program
pub fn new_builtin(
deployment_slot: Slot,
account_size: usize,
builtin_function: BuiltinFunctionWithContext,
) -> Self {
let mut function_registry = FunctionRegistry::default();
function_registry
.register_function_hashed(*b"entrypoint", builtin_function)
.unwrap();
Self {
deployment_slot,
account_owner: ProgramCacheEntryOwner::NativeLoader,
account_size,
effective_slot: deployment_slot,
tx_usage_counter: AtomicU64::new(0),
program: ProgramCacheEntryType::Builtin(BuiltinProgram::new_builtin(function_registry)),
ix_usage_counter: AtomicU64::new(0),
latest_access_slot: AtomicU64::new(0),
}
}
pub fn new_tombstone(
slot: Slot,
account_owner: ProgramCacheEntryOwner,
reason: ProgramCacheEntryType,
) -> Self {
let tombstone = Self {
program: reason,
account_owner,
account_size: 0,
deployment_slot: slot,
effective_slot: slot,
tx_usage_counter: AtomicU64::default(),
ix_usage_counter: AtomicU64::default(),
latest_access_slot: AtomicU64::new(0),
};
debug_assert!(tombstone.is_tombstone());
tombstone
}
pub fn is_tombstone(&self) -> bool {
matches!(
self.program,
ProgramCacheEntryType::FailedVerification(_)
| ProgramCacheEntryType::Closed
| ProgramCacheEntryType::DelayVisibility
)
}
fn is_implicit_delay_visibility_tombstone(&self, slot: Slot) -> bool {
!matches!(self.program, ProgramCacheEntryType::Builtin(_))
&& self.effective_slot.saturating_sub(self.deployment_slot)
== DELAY_VISIBILITY_SLOT_OFFSET
&& slot >= self.deployment_slot
&& slot < self.effective_slot
}
pub fn update_access_slot(&self, slot: Slot) {
let _ = self.latest_access_slot.fetch_max(slot, Ordering::Relaxed);
}
pub fn decayed_usage_counter(&self, now: Slot) -> u64 {
let last_access = self.latest_access_slot.load(Ordering::Relaxed);
// Shifting the u64 value for more than 63 will cause an overflow.
let decaying_for = std::cmp::min(63, now.saturating_sub(last_access));
self.tx_usage_counter.load(Ordering::Relaxed) >> decaying_for
}
pub fn account_owner(&self) -> Pubkey {
self.account_owner.into()
}
}
/// Globally shared RBPF config and syscall registry
///
/// This is only valid in an epoch range as long as no feature affecting RBPF is activated.
#[derive(Clone, Debug)]
pub struct ProgramRuntimeEnvironments {
/// For program runtime V1
pub program_runtime_v1: ProgramRuntimeEnvironment,
/// For program runtime V2
pub program_runtime_v2: ProgramRuntimeEnvironment,
}
impl Default for ProgramRuntimeEnvironments {
fn default() -> Self {
let empty_loader = Arc::new(BuiltinProgram::new_loader(
Config::default(),
FunctionRegistry::default(),
));
Self {
program_runtime_v1: empty_loader.clone(),
program_runtime_v2: empty_loader,
}
}
}
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct LoadingTaskCookie(u64);
impl LoadingTaskCookie {
fn new() -> Self {
Self(0)
}
fn update(&mut self) {
let LoadingTaskCookie(cookie) = self;
*cookie = cookie.wrapping_add(1);
}
}
/// Suspends the thread in case no cooprative loading task was assigned
#[derive(Debug, Default)]
pub struct LoadingTaskWaiter {
cookie: Mutex<LoadingTaskCookie>,
cond: Condvar,
}
impl LoadingTaskWaiter {
pub fn new() -> Self {
Self {
cookie: Mutex::new(LoadingTaskCookie::new()),
cond: Condvar::new(),
}
}
pub fn cookie(&self) -> LoadingTaskCookie {
*self.cookie.lock().unwrap()
}
pub fn notify(&self) {
let mut cookie = self.cookie.lock().unwrap();
cookie.update();
self.cond.notify_all();
}
pub fn wait(&self, cookie: LoadingTaskCookie) -> LoadingTaskCookie {
let cookie_guard = self.cookie.lock().unwrap();
*self
.cond
.wait_while(cookie_guard, |current_cookie| *current_cookie == cookie)
.unwrap()
}
}
#[derive(Debug)]
enum IndexImplementation {
/// Fork-graph aware index implementation
V1 {
/// A two level index:
///
/// - the first level is for the address at which programs are deployed
/// - the second level for the slot (and thus also fork), sorted by slot number.
entries: HashMap<Pubkey, Vec<Arc<ProgramCacheEntry>>>,
/// The entries that are getting loaded and have not yet finished loading.
///
/// The key is the program address, the value is a tuple of the slot in which the program is
/// being loaded and the thread ID doing the load.
///
/// It is possible that multiple TX batches from different slots need different versions of a
/// program. The deployment slot of a program is only known after load tho,
/// so all loads for a given program key are serialized.
loading_entries: Mutex<HashMap<Pubkey, (Slot, thread::ThreadId)>>,
},
}
/// This structure is the global cache of loaded, verified and compiled programs.
///
/// It ...
/// - is validator global and fork graph aware, so it can optimize the commonalities across banks.
/// - handles the visibility rules of un/re/deployments.
/// - stores the usage statistics and verification status of each program.
/// - is elastic and uses a probabilistic eviction stragety based on the usage statistics.
/// - also keeps the compiled executables around, but only for the most used programs.
/// - supports various kinds of tombstones to avoid loading programs which can not be loaded.
/// - cleans up entries on orphan branches when the block store is rerooted.
/// - supports the cache preparation phase before feature activations which can change cached programs.
/// - manages the environments of the programs and upcoming environments for the next epoch.
/// - allows for cooperative loading of TX batches which hit the same missing programs simultaneously.
/// - enforces that all programs used in a batch are eagerly loaded ahead of execution.
/// - is not persisted to disk or a snapshot, so it needs to cold start and warm up first.
pub struct ProgramCache<FG: ForkGraph> {
/// Index of the cached entries and cooperative loading tasks
index: IndexImplementation,
/// The slot of the last rerooting
pub latest_root_slot: Slot,
/// The epoch of the last rerooting
pub latest_root_epoch: Epoch,
/// Environments of the current epoch
pub environments: ProgramRuntimeEnvironments,
/// Anticipated replacement for `environments` at the next epoch
///
/// This is `None` during most of an epoch, and only `Some` around the boundaries (at the end and beginning of an epoch).
/// More precisely, it starts with the cache preparation phase a few hundred slots before the epoch boundary,
/// and it ends with the first rerooting after the epoch boundary.
pub upcoming_environments: Option<ProgramRuntimeEnvironments>,
/// List of loaded programs which should be recompiled before the next epoch (but don't have to).
pub programs_to_recompile: Vec<(Pubkey, Arc<ProgramCacheEntry>)>,
/// Statistics counters
pub stats: ProgramCacheStats,
/// Reference to the block store
pub fork_graph: Option<Weak<RwLock<FG>>>,
/// Coordinates TX batches waiting for others to complete their task during cooperative loading
pub loading_task_waiter: Arc<LoadingTaskWaiter>,
}
impl<FG: ForkGraph> Debug for ProgramCache<FG> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProgramCache")
.field("root slot", &self.latest_root_slot)
.field("root epoch", &self.latest_root_epoch)
.field("stats", &self.stats)
.field("index", &self.index)
.finish()
}
}
/// Local view into [ProgramCache] which was extracted for a specific TX batch.
///
/// This isolation enables the global [ProgramCache] to continue to evolve (e.g. evictions),
/// while the TX batch is guaranteed it will continue to find all the programs it requires.
/// For program management instructions this also buffers them before they are merged back into the global [ProgramCache].
#[derive(Clone, Debug, Default)]
pub struct ProgramCacheForTxBatch {
/// Pubkey is the address of a program.
/// ProgramCacheEntry is the corresponding program entry valid for the slot in which a transaction is being executed.
entries: HashMap<Pubkey, Arc<ProgramCacheEntry>>,
/// Program entries modified during the transaction batch.
modified_entries: HashMap<Pubkey, Arc<ProgramCacheEntry>>,
slot: Slot,
pub environments: ProgramRuntimeEnvironments,
/// Anticipated replacement for `environments` at the next epoch.
///
/// This is `None` during most of an epoch, and only `Some` around the boundaries (at the end and beginning of an epoch).
/// More precisely, it starts with the cache preparation phase a few hundred slots before the epoch boundary,
/// and it ends with the first rerooting after the epoch boundary.
/// Needed when a program is deployed at the last slot of an epoch, becomes effective in the next epoch.
/// So needs to be compiled with the environment for the next epoch.
pub upcoming_environments: Option<ProgramRuntimeEnvironments>,
/// The epoch of the last rerooting
pub latest_root_epoch: Epoch,
pub hit_max_limit: bool,
pub loaded_missing: bool,
pub merged_modified: bool,
}
impl ProgramCacheForTxBatch {
pub fn new(
slot: Slot,
environments: ProgramRuntimeEnvironments,
upcoming_environments: Option<ProgramRuntimeEnvironments>,
latest_root_epoch: Epoch,
) -> Self {
Self {
entries: HashMap::new(),
modified_entries: HashMap::new(),
slot,
environments,
upcoming_environments,
latest_root_epoch,
hit_max_limit: false,
loaded_missing: false,
merged_modified: false,
}
}
pub fn new_from_cache<FG: ForkGraph>(
slot: Slot,
epoch: Epoch,
cache: &ProgramCache<FG>,
) -> Self {
Self {
entries: HashMap::new(),
modified_entries: HashMap::new(),
slot,
environments: cache.get_environments_for_epoch(epoch),
upcoming_environments: cache.get_upcoming_environments_for_epoch(epoch),
latest_root_epoch: cache.latest_root_epoch,
hit_max_limit: false,
loaded_missing: false,
merged_modified: false,
}
}
/// Returns the current environments depending on the given epoch
pub fn get_environments_for_epoch(&self, epoch: Epoch) -> &ProgramRuntimeEnvironments {
if epoch != self.latest_root_epoch {
if let Some(upcoming_environments) = self.upcoming_environments.as_ref() {
return upcoming_environments;
}
}
&self.environments
}
/// Refill the cache with a single entry. It's typically called during transaction loading, and
/// transaction processing (for program management instructions).
/// It replaces the existing entry (if any) with the provided entry. The return value contains
/// `true` if an entry existed.
/// The function also returns the newly inserted value.
pub fn replenish(
&mut self,
key: Pubkey,
entry: Arc<ProgramCacheEntry>,
) -> (bool, Arc<ProgramCacheEntry>) {
(self.entries.insert(key, entry.clone()).is_some(), entry)
}
/// Store an entry in `modified_entries` for a program modified during the
/// transaction batch.
pub fn store_modified_entry(&mut self, key: Pubkey, entry: Arc<ProgramCacheEntry>) {
self.modified_entries.insert(key, entry);
}
/// Drain the program cache's modified entries, returning the owned
/// collection.
pub fn drain_modified_entries(&mut self) -> HashMap<Pubkey, Arc<ProgramCacheEntry>> {
std::mem::take(&mut self.modified_entries)
}
pub fn find(&self, key: &Pubkey) -> Option<Arc<ProgramCacheEntry>> {
// First lookup the cache of the programs modified by the current
// transaction. If not found, lookup the cache of the cache of the
// programs that are loaded for the transaction batch.
self.modified_entries
.get(key)
.or(self.entries.get(key))
.map(|entry| {
if entry.is_implicit_delay_visibility_tombstone(self.slot) {
// Found a program entry on the current fork, but it's not effective
// yet. It indicates that the program has delayed visibility. Return
// the tombstone to reflect that.
Arc::new(ProgramCacheEntry::new_tombstone(
entry.deployment_slot,
entry.account_owner,
ProgramCacheEntryType::DelayVisibility,
))
} else {
entry.clone()
}
})
}
pub fn slot(&self) -> Slot {
self.slot
}
pub fn set_slot_for_tests(&mut self, slot: Slot) {
self.slot = slot;
}
pub fn merge(&mut self, modified_entries: &HashMap<Pubkey, Arc<ProgramCacheEntry>>) {
modified_entries.iter().for_each(|(key, entry)| {
self.merged_modified = true;
self.replenish(*key, entry.clone());
})
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
pub enum ProgramCacheMatchCriteria {
DeployedOnOrAfterSlot(Slot),
Tombstone,
NoCriteria,
}
impl<FG: ForkGraph> ProgramCache<FG> {
pub fn new(root_slot: Slot, root_epoch: Epoch) -> Self {
Self {
index: IndexImplementation::V1 {
entries: HashMap::new(),
loading_entries: Mutex::new(HashMap::new()),
},
latest_root_slot: root_slot,
latest_root_epoch: root_epoch,
environments: ProgramRuntimeEnvironments::default(),
upcoming_environments: None,
programs_to_recompile: Vec::default(),
stats: ProgramCacheStats::default(),
fork_graph: None,
loading_task_waiter: Arc::new(LoadingTaskWaiter::default()),
}
}
pub fn set_fork_graph(&mut self, fork_graph: Weak<RwLock<FG>>) {
self.fork_graph = Some(fork_graph);
}
/// Returns the current environments depending on the given epoch
pub fn get_environments_for_epoch(&self, epoch: Epoch) -> ProgramRuntimeEnvironments {
if epoch != self.latest_root_epoch {
if let Some(upcoming_environments) = self.upcoming_environments.as_ref() {
return upcoming_environments.clone();
}
}
self.environments.clone()
}
/// Returns the upcoming environments depending on the given epoch
pub fn get_upcoming_environments_for_epoch(
&self,
epoch: Epoch,
) -> Option<ProgramRuntimeEnvironments> {
if epoch == self.latest_root_epoch {
return self.upcoming_environments.clone();
}
None
}
/// Insert a single entry. It's typically called during transaction loading,
/// when the cache doesn't contain the entry corresponding to program `key`.
pub fn assign_program(&mut self, key: Pubkey, entry: Arc<ProgramCacheEntry>) -> bool {
debug_assert!(!matches!(
&entry.program,
ProgramCacheEntryType::DelayVisibility
));
// This function always returns `true` during normal operation.
// Only during the cache preparation phase this can return `false`
// for entries with `upcoming_environments`.
fn is_current_env(
environments: &ProgramRuntimeEnvironments,
env_opt: Option<&ProgramRuntimeEnvironment>,
) -> bool {
env_opt
.map(|env| {
Arc::ptr_eq(env, &environments.program_runtime_v1)
|| Arc::ptr_eq(env, &environments.program_runtime_v2)
})
.unwrap_or(true)
}
match &mut self.index {
IndexImplementation::V1 { entries, .. } => {
let slot_versions = &mut entries.entry(key).or_default();
match slot_versions.binary_search_by(|at| {
at.effective_slot
.cmp(&entry.effective_slot)
.then(at.deployment_slot.cmp(&entry.deployment_slot))
.then(
// This `.then()` has no effect during normal operation.
// Only during the cache preparation phase this does allow entries
// which only differ in their environment to be interleaved in `slot_versions`.
is_current_env(&self.environments, at.program.get_environment()).cmp(
&is_current_env(
&self.environments,
entry.program.get_environment(),
),
),
)
}) {
Ok(index) => {
let existing = slot_versions.get_mut(index).unwrap();
match (&existing.program, &entry.program) {
(
ProgramCacheEntryType::Builtin(_),
ProgramCacheEntryType::Builtin(_),
)
| (
ProgramCacheEntryType::Unloaded(_),
ProgramCacheEntryType::Loaded(_),
) => {}
_ => {
// Something is wrong, I can feel it ...
error!("ProgramCache::assign_program() failed key={:?} existing={:?} entry={:?}", key, slot_versions, entry);
debug_assert!(false, "Unexpected replacement of an entry");
self.stats.replacements.fetch_add(1, Ordering::Relaxed);
return true;
}
}
// Copy over the usage counter to the new entry
entry.tx_usage_counter.fetch_add(
existing.tx_usage_counter.load(Ordering::Relaxed),
Ordering::Relaxed,
);
entry.ix_usage_counter.fetch_add(
existing.ix_usage_counter.load(Ordering::Relaxed),
Ordering::Relaxed,
);
*existing = Arc::clone(&entry);
self.stats.reloads.fetch_add(1, Ordering::Relaxed);
}
Err(index) => {
self.stats.insertions.fetch_add(1, Ordering::Relaxed);
slot_versions.insert(index, Arc::clone(&entry));
}
}
}
}
false
}
pub fn prune_by_deployment_slot(&mut self, slot: Slot) {
match &mut self.index {
IndexImplementation::V1 { entries, .. } => {
for second_level in entries.values_mut() {
second_level.retain(|entry| entry.deployment_slot != slot);
}
self.remove_programs_with_no_entries();
}
}
}
/// Before rerooting the blockstore this removes all superfluous entries
pub fn prune(&mut self, new_root_slot: Slot, new_root_epoch: Epoch) {
let Some(fork_graph) = self.fork_graph.clone() else {
error!("Program cache doesn't have fork graph.");
return;
};
let fork_graph = fork_graph.upgrade().unwrap();
let Ok(fork_graph) = fork_graph.read() else {
error!("Failed to lock fork graph for reading.");
return;
};
let mut preparation_phase_ends = false;
if self.latest_root_epoch != new_root_epoch {
self.latest_root_epoch = new_root_epoch;
if let Some(upcoming_environments) = self.upcoming_environments.take() {
preparation_phase_ends = true;
self.environments = upcoming_environments;
self.programs_to_recompile.clear();
}
}
match &mut self.index {
IndexImplementation::V1 { entries, .. } => {
for second_level in entries.values_mut() {
// Remove entries un/re/deployed on orphan forks
let mut first_ancestor_found = false;
let mut first_ancestor_env = None;
*second_level = second_level
.iter()
.rev()
.filter(|entry| {
let relation =
fork_graph.relationship(entry.deployment_slot, new_root_slot);
if entry.deployment_slot >= new_root_slot {
matches!(relation, BlockRelation::Equal | BlockRelation::Descendant)
} else if matches!(relation, BlockRelation::Ancestor)
|| entry.deployment_slot <= self.latest_root_slot
{
if !first_ancestor_found {
first_ancestor_found = true;
first_ancestor_env = entry.program.get_environment();
return true;
}
// Do not prune the entry if the runtime environment of the entry is different
// than the entry that was previously found (stored in first_ancestor_env).
// Different environment indicates that this entry might belong to an older
// epoch that had a different environment (e.g. different feature set).
// Once the root moves to the new/current epoch, the entry will get pruned.
// But, until then the entry might still be getting used by an older slot.
if let Some(entry_env) = entry.program.get_environment() {
if let Some(env) = first_ancestor_env {
if !Arc::ptr_eq(entry_env, env) {
return true;
}
}
}