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
use crate::device::*;
use lazy_static::lazy_static;
use std::collections::hash_map::HashMap;
use std::collections::VecDeque;
use std::sync::{Arc, RwLock};
pub trait Cache {
fn contains(key: u64) -> bool;
fn get(key: u64) -> Arc<DeviceFnMut>;
fn insert(key: u64, device_fn_mut: Arc<DeviceFnMut>);
}
lazy_static! {
static ref GLOBAL_KERNEL_CACHE: RwLock<HashMap<u64, Arc<DeviceFnMut>>> = RwLock::new(HashMap::new());
static ref GLOBAL_KERNEL_CACHE_LRU: RwLock<VecDeque<u64>> = RwLock::new(VecDeque::new());
static ref GLOBAL_KERNEL_CACHE_CAPACITY: RwLock<usize> = RwLock::new(0);
}
fn maybe_initialize_global_kernel_cache() {
if *GLOBAL_KERNEL_CACHE_CAPACITY.read().unwrap() == 0 {
*GLOBAL_KERNEL_CACHE_CAPACITY.write().unwrap() = 32;
}
}
pub struct GlobalCache;
impl GlobalCache {
pub fn reserve(additional: usize) {
*GLOBAL_KERNEL_CACHE_CAPACITY.write().unwrap() += additional;
}
}
impl Cache for GlobalCache {
fn contains(key: u64) -> bool {
maybe_initialize_global_kernel_cache();
GLOBAL_KERNEL_CACHE.read().unwrap().contains_key(&key)
}
fn get(key: u64) -> Arc<DeviceFnMut> {
maybe_initialize_global_kernel_cache();
let key_location_in_lru = GLOBAL_KERNEL_CACHE_LRU
.read()
.unwrap()
.iter()
.position(|&x| x == key)
.unwrap();
GLOBAL_KERNEL_CACHE_LRU
.write()
.unwrap()
.swap(0, key_location_in_lru);
GLOBAL_KERNEL_CACHE
.read()
.unwrap()
.get(&key)
.map(|v| Arc::clone(v))
.unwrap()
}
fn insert(key: u64, device_fn_mut: Arc<DeviceFnMut>) {
maybe_initialize_global_kernel_cache();
if GLOBAL_KERNEL_CACHE.read().unwrap().len()
== *GLOBAL_KERNEL_CACHE_CAPACITY.read().unwrap()
{
let lru_location_in_cache = (*GLOBAL_KERNEL_CACHE_LRU.read().unwrap())
.back()
.unwrap()
.clone();
GLOBAL_KERNEL_CACHE
.write()
.unwrap()
.remove(&lru_location_in_cache);
GLOBAL_KERNEL_CACHE_LRU.write().unwrap().pop_back();
GLOBAL_KERNEL_CACHE_LRU.write().unwrap().push_front(key);
} else {
GLOBAL_KERNEL_CACHE_LRU.write().unwrap().push_front(key);
}
GLOBAL_KERNEL_CACHE
.write()
.unwrap()
.insert(key, device_fn_mut);
}
}