-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
in_mem_accounts_index.rs
1955 lines (1813 loc) · 77.4 KB
/
in_mem_accounts_index.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::{
accounts_index::{
AccountMapEntry, AccountMapEntryInner, AccountMapEntryMeta, IndexValue,
PreAllocatedAccountMapEntry, RefCount, SlotList, SlotSlice, UpsertReclaim, ZeroLamport,
},
bucket_map_holder::{Age, BucketMapHolder},
bucket_map_holder_stats::BucketMapHolderStats,
waitable_condvar::WaitableCondvar,
},
rand::{thread_rng, Rng},
solana_bucket_map::bucket_api::BucketApi,
solana_measure::measure::Measure,
solana_sdk::{clock::Slot, pubkey::Pubkey},
std::{
collections::{
hash_map::{Entry, VacantEntry},
HashMap,
},
fmt::Debug,
ops::{Bound, RangeBounds, RangeInclusive},
sync::{
atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering},
Arc, Mutex, RwLock, RwLockWriteGuard,
},
},
};
type K = Pubkey;
type CacheRangesHeld = RwLock<Vec<RangeInclusive<Pubkey>>>;
type InMemMap<T> = HashMap<Pubkey, AccountMapEntry<T>>;
#[derive(Debug)]
pub struct PossibleEvictions<T: IndexValue> {
/// vec per age in the future, up to size 'ages_to_stay_in_cache'
possible_evictions: Vec<FlushScanResult<T>>,
/// next index to use into 'possible_evictions'
/// if 'index' >= 'possible_evictions.len()', then there are no available entries
index: usize,
}
impl<T: IndexValue> PossibleEvictions<T> {
fn new(max_ages: Age) -> Self {
Self {
possible_evictions: (0..max_ages).map(|_| FlushScanResult::default()).collect(),
index: max_ages as usize, // initially no data
}
}
/// remove the possible evictions. This is required because we need ownership of the Arc strong counts to transfer to caller so entries can be removed from the accounts index
fn get_possible_evictions(&mut self) -> Option<FlushScanResult<T>> {
self.possible_evictions.get_mut(self.index).map(|result| {
self.index += 1;
// remove the list from 'possible_evictions'
std::mem::take(result)
})
}
/// clear existing data and prepare to add 'entries' more ages of data
fn reset(&mut self, entries: Age) {
self.possible_evictions.iter_mut().for_each(|entry| {
entry.evictions_random.clear();
entry.evictions_age_possible.clear();
});
let entries = entries as usize;
assert!(
entries <= self.possible_evictions.len(),
"entries: {}, len: {}",
entries,
self.possible_evictions.len()
);
self.index = self.possible_evictions.len() - entries;
}
/// insert 'entry' at 'relative_age' in the future into 'possible_evictions'
fn insert(&mut self, relative_age: Age, key: Pubkey, entry: AccountMapEntry<T>, random: bool) {
let index = self.index + (relative_age as usize);
let list = &mut self.possible_evictions[index];
if random {
&mut list.evictions_random
} else {
&mut list.evictions_age_possible
}
.push((key, entry));
}
}
// one instance of this represents one bin of the accounts index.
pub struct InMemAccountsIndex<T: IndexValue> {
last_age_flushed: AtomicU8,
// backing store
map_internal: RwLock<InMemMap<T>>,
storage: Arc<BucketMapHolder<T>>,
bin: usize,
bucket: Option<Arc<BucketApi<(Slot, T)>>>,
// pubkey ranges that this bin must hold in the cache while the range is present in this vec
pub(crate) cache_ranges_held: CacheRangesHeld,
// incremented each time stop_evictions is changed
stop_evictions_changes: AtomicU64,
// true while ranges are being manipulated. Used to keep an async flush from removing things while a range is being held.
stop_evictions: AtomicU64,
// set to true while this bin is being actively flushed
flushing_active: AtomicBool,
/// info to streamline initial index generation
startup_info: Mutex<StartupInfo<T>>,
/// possible evictions for next few slots coming up
possible_evictions: RwLock<PossibleEvictions<T>>,
/// when age % ages_to_stay_in_cache == 'age_to_flush_bin_offset', then calculate the next 'ages_to_stay_in_cache' 'possible_evictions'
/// this causes us to scan the entire in-mem hash map every 1/'ages_to_stay_in_cache' instead of each age
age_to_flush_bin_mod: Age,
}
impl<T: IndexValue> Debug for InMemAccountsIndex<T> {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}
pub enum InsertNewEntryResults {
DidNotExist,
ExistedNewEntryZeroLamports,
ExistedNewEntryNonZeroLamports,
}
#[derive(Default, Debug)]
struct StartupInfo<T: IndexValue> {
/// entries to add next time we are flushing to disk
insert: Vec<(Slot, Pubkey, T)>,
/// pubkeys that were found to have duplicate index entries
duplicates: Vec<(Slot, Pubkey)>,
}
#[derive(Default, Debug)]
/// result from scanning in-mem index during flush
struct FlushScanResult<T> {
/// pubkeys whose age indicates they may be evicted now, pending further checks.
evictions_age_possible: Vec<(Pubkey, AccountMapEntry<T>)>,
/// pubkeys chosen to evict based on random eviction
evictions_random: Vec<(Pubkey, AccountMapEntry<T>)>,
}
impl<T: IndexValue> InMemAccountsIndex<T> {
pub fn new(storage: &Arc<BucketMapHolder<T>>, bin: usize) -> Self {
let ages_to_stay_in_cache = storage.ages_to_stay_in_cache;
Self {
map_internal: RwLock::default(),
storage: Arc::clone(storage),
bin,
bucket: storage
.disk
.as_ref()
.map(|disk| disk.get_bucket_from_index(bin))
.map(Arc::clone),
cache_ranges_held: CacheRangesHeld::default(),
stop_evictions_changes: AtomicU64::default(),
stop_evictions: AtomicU64::default(),
flushing_active: AtomicBool::default(),
// initialize this to max, to make it clear we have not flushed at age 0, the starting age
last_age_flushed: AtomicU8::new(Age::MAX),
startup_info: Mutex::default(),
possible_evictions: RwLock::new(PossibleEvictions::new(ages_to_stay_in_cache)),
// Spread out the scanning across all ages within the window.
// This causes us to scan 1/N of the bins each 'Age'
age_to_flush_bin_mod: thread_rng().gen_range(0, ages_to_stay_in_cache),
}
}
/// # ages to scan ahead
fn ages_to_scan_ahead(&self, current_age: Age) -> Age {
let ages_to_stay_in_cache = self.storage.ages_to_stay_in_cache;
if (self.age_to_flush_bin_mod == current_age % ages_to_stay_in_cache)
&& !self.storage.get_startup()
{
// scan ahead multiple ages
ages_to_stay_in_cache
} else {
1 // just current age
}
}
/// true if this bucket needs to call flush for the current age
/// we need to scan each bucket once per value of age
fn get_should_age(&self, age: Age) -> bool {
let last_age_flushed = self.last_age_flushed();
last_age_flushed != age
}
/// called after flush scans this bucket at the current age
fn set_has_aged(&self, age: Age, can_advance_age: bool) {
self.last_age_flushed.store(age, Ordering::Release);
self.storage.bucket_flushed_at_current_age(can_advance_age);
}
fn last_age_flushed(&self) -> Age {
self.last_age_flushed.load(Ordering::Acquire)
}
/// Release entire in-mem hashmap to free all memory associated with it.
/// Idea is that during startup we needed a larger map than we need during runtime.
/// When using disk-buckets, in-mem index grows over time with dynamic use and then shrinks, in theory back to 0.
pub fn shrink_to_fit(&self) {
// shrink_to_fit could be quite expensive on large map sizes, which 'no disk buckets' could produce, so avoid shrinking in case we end up here
if self.storage.is_disk_index_enabled() {
self.map_internal.write().unwrap().shrink_to_fit();
}
}
pub fn items<R>(&self, range: &R) -> Vec<(K, AccountMapEntry<T>)>
where
R: RangeBounds<Pubkey> + std::fmt::Debug,
{
let m = Measure::start("items");
self.hold_range_in_memory(range, true);
let map = self.map_internal.read().unwrap();
let mut result = Vec::with_capacity(map.len());
map.iter().for_each(|(k, v)| {
if range.contains(k) {
result.push((*k, Arc::clone(v)));
}
});
drop(map);
self.hold_range_in_memory(range, false);
Self::update_stat(&self.stats().items, 1);
Self::update_time_stat(&self.stats().items_us, m);
result
}
// only called in debug code paths
pub fn keys(&self) -> Vec<Pubkey> {
Self::update_stat(&self.stats().keys, 1);
// easiest implementation is to load evrything from disk into cache and return the keys
let evictions_guard = EvictionsGuard::lock(self);
self.put_range_in_cache(&None::<&RangeInclusive<Pubkey>>, &evictions_guard);
let keys = self.map_internal.read().unwrap().keys().cloned().collect();
keys
}
fn load_from_disk(&self, pubkey: &Pubkey) -> Option<(SlotList<T>, RefCount)> {
self.bucket.as_ref().and_then(|disk| {
let m = Measure::start("load_disk_found_count");
let entry_disk = disk.read_value(pubkey);
match &entry_disk {
Some(_) => {
Self::update_time_stat(&self.stats().load_disk_found_us, m);
Self::update_stat(&self.stats().load_disk_found_count, 1);
}
None => {
Self::update_time_stat(&self.stats().load_disk_missing_us, m);
Self::update_stat(&self.stats().load_disk_missing_count, 1);
}
}
entry_disk
})
}
fn load_account_entry_from_disk(&self, pubkey: &Pubkey) -> Option<AccountMapEntry<T>> {
let entry_disk = self.load_from_disk(pubkey)?; // returns None if not on disk
Some(self.disk_to_cache_entry(entry_disk.0, entry_disk.1))
}
/// lookup 'pubkey' by only looking in memory. Does not look on disk.
/// callback is called whether pubkey is found or not
fn get_only_in_mem<RT>(
&self,
pubkey: &K,
callback: impl for<'a> FnOnce(Option<&'a AccountMapEntry<T>>) -> RT,
) -> RT {
let mut found = true;
let mut m = Measure::start("get");
let result = {
let map = self.map_internal.read().unwrap();
let result = map.get(pubkey);
m.stop();
callback(if let Some(entry) = result {
entry.set_age(self.storage.future_age_to_flush());
Some(entry)
} else {
drop(map);
found = false;
None
})
};
let stats = self.stats();
let (count, time) = if found {
(&stats.gets_from_mem, &stats.get_mem_us)
} else {
(&stats.gets_missing, &stats.get_missing_us)
};
Self::update_stat(time, m.as_us());
Self::update_stat(count, 1);
result
}
/// lookup 'pubkey' in index (in mem or on disk)
pub fn get(&self, pubkey: &K) -> Option<AccountMapEntry<T>> {
self.get_internal(pubkey, |entry| (true, entry.map(Arc::clone)))
}
/// lookup 'pubkey' in index (in_mem or disk).
/// call 'callback' whether found or not
pub(crate) fn get_internal<RT>(
&self,
pubkey: &K,
// return true if item should be added to in_mem cache
callback: impl for<'a> FnOnce(Option<&AccountMapEntry<T>>) -> (bool, RT),
) -> RT {
self.get_only_in_mem(pubkey, |entry| {
if let Some(entry) = entry {
entry.set_age(self.storage.future_age_to_flush());
callback(Some(entry)).1
} else {
// not in cache, look on disk
let stats = &self.stats();
let disk_entry = self.load_account_entry_from_disk(pubkey);
if disk_entry.is_none() {
return callback(None).1;
}
let disk_entry = disk_entry.unwrap();
let mut map = self.map_internal.write().unwrap();
let entry = map.entry(*pubkey);
match entry {
Entry::Occupied(occupied) => callback(Some(occupied.get())).1,
Entry::Vacant(vacant) => {
let (add_to_cache, rt) = callback(Some(&disk_entry));
if add_to_cache {
stats.inc_mem_count(self.bin);
vacant.insert(disk_entry);
}
rt
}
}
}
})
}
fn remove_if_slot_list_empty_value(&self, slot_list: SlotSlice<T>) -> bool {
if slot_list.is_empty() {
self.stats().inc_delete();
true
} else {
false
}
}
fn delete_disk_key(&self, pubkey: &Pubkey) {
if let Some(disk) = self.bucket.as_ref() {
disk.delete_key(pubkey)
}
}
fn remove_if_slot_list_empty_entry(&self, entry: Entry<K, AccountMapEntry<T>>) -> bool {
match entry {
Entry::Occupied(occupied) => {
let result =
self.remove_if_slot_list_empty_value(&occupied.get().slot_list.read().unwrap());
if result {
// note there is a potential race here that has existed.
// if someone else holds the arc,
// then they think the item is still in the index and can make modifications.
// We have to have a write lock to the map here, which means nobody else can get
// the arc, but someone may already have retrieved a clone of it.
// account index in_mem flushing is one such possibility
self.delete_disk_key(occupied.key());
self.stats().dec_mem_count(self.bin);
occupied.remove();
}
result
}
Entry::Vacant(vacant) => {
// not in cache, look on disk
let entry_disk = self.load_from_disk(vacant.key());
match entry_disk {
Some(entry_disk) => {
// on disk
if self.remove_if_slot_list_empty_value(&entry_disk.0) {
// not in cache, but on disk, so just delete from disk
self.delete_disk_key(vacant.key());
true
} else {
// could insert into cache here, but not required for correctness and value is unclear
false
}
}
None => false, // not in cache or on disk
}
}
}
}
// If the slot list for pubkey exists in the index and is empty, remove the index entry for pubkey and return true.
// Return false otherwise.
pub fn remove_if_slot_list_empty(&self, pubkey: Pubkey) -> bool {
let mut m = Measure::start("entry");
let mut map = self.map_internal.write().unwrap();
let entry = map.entry(pubkey);
m.stop();
let found = matches!(entry, Entry::Occupied(_));
let result = self.remove_if_slot_list_empty_entry(entry);
drop(map);
self.update_entry_stats(m, found);
result
}
pub fn slot_list_mut<RT>(
&self,
pubkey: &Pubkey,
user: impl for<'a> FnOnce(&mut RwLockWriteGuard<'a, SlotList<T>>) -> RT,
) -> Option<RT> {
self.get_internal(pubkey, |entry| {
(
true,
entry.map(|entry| {
let result = user(&mut entry.slot_list.write().unwrap());
entry.set_dirty(true);
result
}),
)
})
}
pub fn unref(&self, pubkey: &Pubkey) {
self.get_internal(pubkey, |entry| {
if let Some(entry) = entry {
entry.add_un_ref(false)
}
(true, ())
})
}
pub fn upsert(
&self,
pubkey: &Pubkey,
new_value: PreAllocatedAccountMapEntry<T>,
other_slot: Option<Slot>,
reclaims: &mut SlotList<T>,
reclaim: UpsertReclaim,
) {
let mut updated_in_mem = true;
// try to get it just from memory first using only a read lock
self.get_only_in_mem(pubkey, |entry| {
if let Some(entry) = entry {
Self::lock_and_update_slot_list(
entry,
new_value.into(),
other_slot,
reclaims,
reclaim,
);
// age is incremented by caller
} else {
let mut m = Measure::start("entry");
let mut map = self.map_internal.write().unwrap();
let entry = map.entry(*pubkey);
m.stop();
let found = matches!(entry, Entry::Occupied(_));
match entry {
Entry::Occupied(mut occupied) => {
let current = occupied.get_mut();
Self::lock_and_update_slot_list(
current,
new_value.into(),
other_slot,
reclaims,
reclaim,
);
current.set_age(self.storage.future_age_to_flush());
}
Entry::Vacant(vacant) => {
// not in cache, look on disk
updated_in_mem = false;
// desired to be this for filler accounts: self.storage.get_startup();
// but, this has proven to be far too slow at high account counts
let directly_to_disk = false;
if directly_to_disk {
// We may like this to always run, but it is unclear.
// If disk bucket needs to resize, then this call can stall for a long time.
// Right now, we know it is safe during startup.
let already_existed = self
.upsert_on_disk(vacant, new_value, other_slot, reclaims, reclaim);
if !already_existed {
self.stats().inc_insert();
}
} else {
// go to in-mem cache first
let disk_entry = self.load_account_entry_from_disk(vacant.key());
let new_value = if let Some(disk_entry) = disk_entry {
// on disk, so merge new_value with what was on disk
Self::lock_and_update_slot_list(
&disk_entry,
new_value.into(),
other_slot,
reclaims,
reclaim,
);
disk_entry
} else {
// not on disk, so insert new thing
self.stats().inc_insert();
new_value.into_account_map_entry(&self.storage)
};
assert!(new_value.dirty());
vacant.insert(new_value);
self.stats().inc_mem_count(self.bin);
}
}
}
drop(map);
self.update_entry_stats(m, found);
};
});
if updated_in_mem {
Self::update_stat(&self.stats().updates_in_mem, 1);
}
}
fn update_entry_stats(&self, stopped_measure: Measure, found: bool) {
let stats = &self.stats();
let (count, time) = if found {
(&stats.entries_from_mem, &stats.entry_mem_us)
} else {
(&stats.entries_missing, &stats.entry_missing_us)
};
Self::update_stat(time, stopped_measure.as_us());
Self::update_stat(count, 1);
}
/// Try to update an item in the slot list the given `slot` If an item for the slot
/// already exists in the list, remove the older item, add it to `reclaims`, and insert
/// the new item.
/// if 'other_slot' is some, then also remove any entries in the slot list that are at 'other_slot'
pub fn lock_and_update_slot_list(
current: &AccountMapEntryInner<T>,
new_value: (Slot, T),
other_slot: Option<Slot>,
reclaims: &mut SlotList<T>,
reclaim: UpsertReclaim,
) {
let mut slot_list = current.slot_list.write().unwrap();
let (slot, new_entry) = new_value;
let addref = Self::update_slot_list(
&mut slot_list,
slot,
new_entry,
other_slot,
reclaims,
reclaim,
);
if addref {
current.add_un_ref(true);
}
current.set_dirty(true);
}
/// modifies slot_list
/// any entry at 'slot' or slot 'other_slot' is replaced with 'account_info'.
/// or, 'account_info' is appended to the slot list if the slot did not exist previously.
/// returns true if caller should addref
/// conditions when caller should addref:
/// 'account_info' does NOT represent a cached storage (the slot is being flushed from the cache)
/// AND
/// previous slot_list entry AT 'slot' did not exist (this is the first time this account was modified in this "slot"), or was previously cached (the storage is now being flushed from the cache)
/// Note that even if entry DID exist at 'other_slot', the above conditions apply.
fn update_slot_list(
slot_list: &mut SlotList<T>,
slot: Slot,
account_info: T,
mut other_slot: Option<Slot>,
reclaims: &mut SlotList<T>,
reclaim: UpsertReclaim,
) -> bool {
let mut addref = !account_info.is_cached();
if other_slot == Some(slot) {
other_slot = None; // redundant info, so ignore
}
// There may be 0..=2 dirty accounts found (one at 'slot' and one at 'other_slot')
// that are already in the slot list. Since the first one found will be swapped with the
// new account, if a second one is found, we cannot swap again. Instead, just remove it.
let mut found_slot = false;
let mut found_other_slot = false;
(0..slot_list.len())
.into_iter()
.rev() // rev since we delete from the list in some cases
.for_each(|slot_list_index| {
let (cur_slot, cur_account_info) = &slot_list[slot_list_index];
let matched_slot = *cur_slot == slot;
if matched_slot || Some(*cur_slot) == other_slot {
// make sure neither 'slot' nor 'other_slot' are in the slot list more than once
let matched_other_slot = !matched_slot;
assert!(
!(found_slot && matched_slot || matched_other_slot && found_other_slot),
"{:?}, slot: {}, other_slot: {:?}",
slot_list,
slot,
other_slot
);
let is_cur_account_cached = cur_account_info.is_cached();
let reclaim_item = if !(found_slot || found_other_slot) {
// first time we found an entry in 'slot' or 'other_slot', so replace it in-place.
// this may be the only instance we find
std::mem::replace(&mut slot_list[slot_list_index], (slot, account_info))
} else {
// already replaced one entry, so this one has to be removed
slot_list.remove(slot_list_index)
};
match reclaim {
UpsertReclaim::PopulateReclaims => {
reclaims.push(reclaim_item);
}
UpsertReclaim::PreviousSlotEntryWasCached => {
assert!(is_cur_account_cached);
}
UpsertReclaim::IgnoreReclaims => {
// do nothing. nothing to assert. nothing to return in reclaims
}
}
if matched_slot {
found_slot = true;
if !is_cur_account_cached {
// current info at 'slot' is NOT cached, so we should NOT addref. This slot already has a ref count for this pubkey.
addref = false;
}
} else {
found_other_slot = true;
}
}
});
if !found_slot && !found_other_slot {
// if we make it here, we did not find the slot in the list
slot_list.push((slot, account_info));
}
addref
}
// convert from raw data on disk to AccountMapEntry, set to age in future
fn disk_to_cache_entry(
&self,
slot_list: SlotList<T>,
ref_count: RefCount,
) -> AccountMapEntry<T> {
Arc::new(AccountMapEntryInner::new(
slot_list,
ref_count,
AccountMapEntryMeta::new_clean(&self.storage),
))
}
pub fn len_for_stats(&self) -> usize {
self.stats().count_in_bucket(self.bin)
}
/// Queue up these insertions for when the flush thread is dealing with this bin.
/// This is very fast and requires no lookups or disk access.
pub fn startup_insert_only(&self, slot: Slot, items: impl Iterator<Item = (Pubkey, T)>) {
assert!(self.storage.get_startup());
assert!(self.bucket.is_some());
let insert = &mut self.startup_info.lock().unwrap().insert;
items
.into_iter()
.for_each(|(k, v)| insert.push((slot, k, v)));
}
pub fn insert_new_entry_if_missing_with_lock(
&self,
pubkey: Pubkey,
new_entry: PreAllocatedAccountMapEntry<T>,
) -> InsertNewEntryResults {
let mut m = Measure::start("entry");
let mut map = self.map_internal.write().unwrap();
let entry = map.entry(pubkey);
m.stop();
let new_entry_zero_lamports = new_entry.is_zero_lamport();
let (found_in_mem, already_existed) = match entry {
Entry::Occupied(occupied) => {
// in cache, so merge into cache
let (slot, account_info) = new_entry.into();
InMemAccountsIndex::lock_and_update_slot_list(
occupied.get(),
(slot, account_info),
None, // should be None because we don't expect a different slot # during index generation
&mut Vec::default(),
UpsertReclaim::PopulateReclaims, // this should be ignore?
);
(
true, /* found in mem */
true, /* already existed */
)
}
Entry::Vacant(vacant) => {
// not in cache, look on disk
let initial_insert_directly_to_disk = false;
if initial_insert_directly_to_disk {
// This is more direct, but becomes too slow with very large acct #.
// disk buckets will be improved to make them more performant. Tuning the disks may also help.
// This may become a config tuning option.
let already_existed = self.upsert_on_disk(
vacant,
new_entry,
None, // not changing slots here since it doesn't exist in the index at all
&mut Vec::default(),
UpsertReclaim::PopulateReclaims,
);
(false, already_existed)
} else {
let disk_entry = self.load_account_entry_from_disk(vacant.key());
self.stats().inc_mem_count(self.bin);
if let Some(disk_entry) = disk_entry {
let (slot, account_info) = new_entry.into();
InMemAccountsIndex::lock_and_update_slot_list(
&disk_entry,
(slot, account_info),
// None because we are inserting the first element in the slot list for this pubkey.
// There can be no 'other' slot in the list.
None,
&mut Vec::default(),
UpsertReclaim::PopulateReclaims,
);
vacant.insert(disk_entry);
(
false, /* found in mem */
true, /* already existed */
)
} else {
// not on disk, so insert new thing and we're done
let new_entry: AccountMapEntry<T> =
new_entry.into_account_map_entry(&self.storage);
assert!(new_entry.dirty());
vacant.insert(new_entry);
(false, false)
}
}
}
};
drop(map);
self.update_entry_stats(m, found_in_mem);
let stats = self.stats();
if !already_existed {
stats.inc_insert();
} else {
Self::update_stat(&stats.updates_in_mem, 1);
}
if !already_existed {
InsertNewEntryResults::DidNotExist
} else if new_entry_zero_lamports {
InsertNewEntryResults::ExistedNewEntryZeroLamports
} else {
InsertNewEntryResults::ExistedNewEntryNonZeroLamports
}
}
/// return true if item already existed in the index
fn upsert_on_disk(
&self,
vacant: VacantEntry<K, AccountMapEntry<T>>,
new_entry: PreAllocatedAccountMapEntry<T>,
other_slot: Option<Slot>,
reclaims: &mut SlotList<T>,
reclaim: UpsertReclaim,
) -> bool {
if let Some(disk) = self.bucket.as_ref() {
let mut existed = false;
let (slot, account_info) = new_entry.into();
disk.update(vacant.key(), |current| {
if let Some((slot_list, mut ref_count)) = current {
// on disk, so merge and update disk
let mut slot_list = slot_list.to_vec();
let addref = Self::update_slot_list(
&mut slot_list,
slot,
account_info,
other_slot,
reclaims,
reclaim,
);
if addref {
ref_count += 1
};
existed = true; // found on disk, so it did exist
Some((slot_list, ref_count))
} else {
// doesn't exist on disk yet, so insert it
let ref_count = if account_info.is_cached() { 0 } else { 1 };
Some((vec![(slot, account_info)], ref_count))
}
});
existed
} else {
// not using disk, so insert into mem
self.stats().inc_mem_count(self.bin);
let new_entry: AccountMapEntry<T> = new_entry.into_account_map_entry(&self.storage);
assert!(new_entry.dirty());
vacant.insert(new_entry);
false // not using disk, not in mem, so did not exist
}
}
/// Look at the currently held ranges. If 'range' is already included in what is
/// being held, then add 'range' to the currently held list AND return true
/// If 'range' is NOT already included in what is being held, then return false
/// withOUT adding 'range' to the list of what is currently held
fn add_hold_range_in_memory_if_already_held<R>(
&self,
range: &R,
evictions_guard: &EvictionsGuard,
) -> bool
where
R: RangeBounds<Pubkey>,
{
let start_holding = true;
let only_add_if_already_held = true;
self.just_set_hold_range_in_memory_internal(
range,
start_holding,
only_add_if_already_held,
evictions_guard,
)
}
fn just_set_hold_range_in_memory<R>(
&self,
range: &R,
start_holding: bool,
evictions_guard: &EvictionsGuard,
) where
R: RangeBounds<Pubkey>,
{
let only_add_if_already_held = false;
let _ = self.just_set_hold_range_in_memory_internal(
range,
start_holding,
only_add_if_already_held,
evictions_guard,
);
}
/// if 'start_holding', then caller wants to add 'range' to the list of ranges being held
/// if !'start_holding', then caller wants to remove 'range' to the list
/// if 'only_add_if_already_held', caller intends to only add 'range' to the list if the range is already held
/// returns true iff start_holding=true and the range we're asked to hold was already being held
fn just_set_hold_range_in_memory_internal<R>(
&self,
range: &R,
start_holding: bool,
only_add_if_already_held: bool,
_evictions_guard: &EvictionsGuard,
) -> bool
where
R: RangeBounds<Pubkey>,
{
assert!(!only_add_if_already_held || start_holding);
let start = match range.start_bound() {
Bound::Included(bound) | Bound::Excluded(bound) => *bound,
Bound::Unbounded => Pubkey::new(&[0; 32]),
};
let end = match range.end_bound() {
Bound::Included(bound) | Bound::Excluded(bound) => *bound,
Bound::Unbounded => Pubkey::new(&[0xff; 32]),
};
// this becomes inclusive - that is ok - we are just roughly holding a range of items.
// inclusive is bigger than exclusive so we may hold 1 extra item worst case
let inclusive_range = start..=end;
let mut ranges = self.cache_ranges_held.write().unwrap();
let mut already_held = false;
if start_holding {
if only_add_if_already_held {
for r in ranges.iter() {
if r.contains(&start) && r.contains(&end) {
already_held = true;
break;
}
}
}
if already_held || !only_add_if_already_held {
ranges.push(inclusive_range);
}
} else {
// find the matching range and delete it since we don't want to hold it anymore
// search backwards, assuming LIFO ordering
for (i, r) in ranges.iter().enumerate().rev() {
if let (Bound::Included(start_found), Bound::Included(end_found)) =
(r.start_bound(), r.end_bound())
{
if start_found == &start && end_found == &end {
// found a match. There may be dups, that's ok, we expect another call to remove the dup.
ranges.remove(i);
break;
}
}
}
}
already_held
}
/// if 'start_holding'=true, then:
/// at the end of this function, cache_ranges_held will be updated to contain 'range'
/// and all pubkeys in that range will be in the in-mem cache
/// if 'start_holding'=false, then:
/// 'range' will be removed from cache_ranges_held
/// and all pubkeys will be eligible for being removed from in-mem cache in the bg if no other range is holding them
/// Any in-process flush will be aborted when it gets to evicting items from in-mem.
pub fn hold_range_in_memory<R>(&self, range: &R, start_holding: bool)
where
R: RangeBounds<Pubkey> + Debug,
{
let evictions_guard = EvictionsGuard::lock(self);
if !start_holding || !self.add_hold_range_in_memory_if_already_held(range, &evictions_guard)
{
if start_holding {
// put everything in the cache and it will be held there
self.put_range_in_cache(&Some(range), &evictions_guard);
}
// do this AFTER items have been put in cache - that way anyone who finds this range can know that the items are already in the cache
self.just_set_hold_range_in_memory(range, start_holding, &evictions_guard);
}
}
fn put_range_in_cache<R>(&self, range: &Option<&R>, _evictions_guard: &EvictionsGuard)
where
R: RangeBounds<Pubkey>,
{
assert!(self.get_stop_evictions()); // caller should be controlling the lifetime of how long this needs to be present
let m = Measure::start("range");
let mut added_to_mem = 0;
// load from disk
if let Some(disk) = self.bucket.as_ref() {
let mut map = self.map_internal.write().unwrap();
let items = disk.items_in_range(range); // map's lock has to be held while we are getting items from disk
let future_age = self.storage.future_age_to_flush();
for item in items {
let entry = map.entry(item.pubkey);
match entry {
Entry::Occupied(occupied) => {
// item already in cache, bump age to future. This helps the current age flush to succeed.
occupied.get().set_age(future_age);
}
Entry::Vacant(vacant) => {
vacant.insert(self.disk_to_cache_entry(item.slot_list, item.ref_count));
added_to_mem += 1;
}
}
}
}
self.stats().add_mem_count(self.bin, added_to_mem);
Self::update_time_stat(&self.stats().get_range_us, m);
}
/// returns true if there are active requests to stop evictions
fn get_stop_evictions(&self) -> bool {
self.stop_evictions.load(Ordering::Acquire) > 0
}
/// return count of calls to 'start_stop_evictions', indicating changes could have been made to eviction strategy
fn get_stop_evictions_changes(&self) -> u64 {
self.stop_evictions_changes.load(Ordering::Acquire)
}
pub(crate) fn flush(&self, can_advance_age: bool) {
if let Some(flush_guard) = FlushGuard::lock(&self.flushing_active) {
self.flush_internal(&flush_guard, can_advance_age)
}
}
/// returns true if a dice roll indicates this call should result in a random eviction.
/// This causes non-determinism in cache contents per validator.
fn random_chance_of_eviction() -> bool {
// random eviction
const N: usize = 1000;
// 1/N chance of eviction
thread_rng().gen_range(0, N) == 0
}
/// assumes 1 entry in the slot list. Ignores overhead of the HashMap and such
fn approx_size_of_one_entry() -> usize {
std::mem::size_of::<T>()
+ std::mem::size_of::<Pubkey>()
+ std::mem::size_of::<AccountMapEntry<T>>()
}