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
use super::PoolingAllocationStrategy;
use crate::CompiledModuleId;
use rand::Rng;
use std::collections::HashMap;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SlotId(pub usize);
impl SlotId {
pub fn index(self) -> usize {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GlobalFreeListIndex(usize);
impl GlobalFreeListIndex {
fn index(self) -> usize {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PerModuleFreeListIndex(usize);
impl PerModuleFreeListIndex {
fn index(self) -> usize {
self.0
}
}
#[derive(Clone, Debug)]
pub(crate) enum PoolingAllocationState {
NextAvailable(Vec<SlotId>),
Random(Vec<SlotId>),
ReuseAffinity {
free_list: Vec<SlotId>,
per_module: HashMap<CompiledModuleId, Vec<SlotId>>,
slot_state: Vec<SlotState>,
},
}
#[derive(Clone, Debug)]
pub(crate) enum SlotState {
Taken(Option<CompiledModuleId>),
Free(FreeSlotState),
}
impl SlotState {
fn unwrap_free(&self) -> &FreeSlotState {
match self {
&Self::Free(ref free) => free,
_ => panic!("Slot not free"),
}
}
fn unwrap_free_mut(&mut self) -> &mut FreeSlotState {
match self {
&mut Self::Free(ref mut free) => free,
_ => panic!("Slot not free"),
}
}
fn unwrap_module_id(&self) -> Option<CompiledModuleId> {
match self {
&Self::Taken(module_id) => module_id,
_ => panic!("Slot not in Taken state"),
}
}
}
#[derive(Clone, Debug)]
pub(crate) enum FreeSlotState {
NoAffinity {
free_list_index: GlobalFreeListIndex,
},
Affinity {
module: CompiledModuleId,
free_list_index: GlobalFreeListIndex,
per_module_index: PerModuleFreeListIndex,
},
}
impl FreeSlotState {
fn free_list_index(&self) -> GlobalFreeListIndex {
match self {
&Self::NoAffinity { free_list_index }
| &Self::Affinity {
free_list_index, ..
} => free_list_index,
}
}
fn update_free_list_index(&mut self, index: GlobalFreeListIndex) {
match self {
&mut Self::NoAffinity {
ref mut free_list_index,
}
| &mut Self::Affinity {
ref mut free_list_index,
..
} => {
*free_list_index = index;
}
}
}
fn per_module_index(&self) -> PerModuleFreeListIndex {
match self {
&Self::Affinity {
per_module_index, ..
} => per_module_index,
_ => panic!("per_module_index on slot with no affinity"),
}
}
fn update_per_module_index(&mut self, index: PerModuleFreeListIndex) {
match self {
&mut Self::Affinity {
ref mut per_module_index,
..
} => {
*per_module_index = index;
}
_ => panic!("per_module_index on slot with no affinity"),
}
}
}
fn remove_global_free_list_item(
slot_state: &mut Vec<SlotState>,
free_list: &mut Vec<SlotId>,
index: SlotId,
) {
let free_list_index = slot_state[index.index()].unwrap_free().free_list_index();
assert_eq!(index, free_list.swap_remove(free_list_index.index()));
if free_list_index.index() < free_list.len() {
let replaced = free_list[free_list_index.index()];
slot_state[replaced.index()]
.unwrap_free_mut()
.update_free_list_index(free_list_index);
}
}
fn remove_module_free_list_item(
slot_state: &mut Vec<SlotState>,
per_module: &mut HashMap<CompiledModuleId, Vec<SlotId>>,
id: CompiledModuleId,
index: SlotId,
) {
debug_assert!(
per_module.contains_key(&id),
"per_module list for given module should not be empty"
);
let per_module_list = per_module.get_mut(&id).unwrap();
debug_assert!(!per_module_list.is_empty());
let per_module_index = slot_state[index.index()].unwrap_free().per_module_index();
assert_eq!(index, per_module_list.swap_remove(per_module_index.index()));
if per_module_index.index() < per_module_list.len() {
let replaced = per_module_list[per_module_index.index()];
slot_state[replaced.index()]
.unwrap_free_mut()
.update_per_module_index(per_module_index);
}
if per_module_list.is_empty() {
per_module.remove(&id);
}
}
impl PoolingAllocationState {
pub(crate) fn new(strategy: PoolingAllocationStrategy, max_instances: usize) -> Self {
let ids = (0..max_instances).map(|i| SlotId(i)).collect::<Vec<_>>();
match strategy {
PoolingAllocationStrategy::NextAvailable => PoolingAllocationState::NextAvailable(ids),
PoolingAllocationStrategy::Random => PoolingAllocationState::Random(ids),
PoolingAllocationStrategy::ReuseAffinity => PoolingAllocationState::ReuseAffinity {
free_list: ids,
per_module: HashMap::new(),
slot_state: (0..max_instances)
.map(|i| {
SlotState::Free(FreeSlotState::NoAffinity {
free_list_index: GlobalFreeListIndex(i),
})
})
.collect(),
},
}
}
pub(crate) fn is_empty(&self) -> bool {
match self {
&PoolingAllocationState::NextAvailable(ref free_list)
| &PoolingAllocationState::Random(ref free_list) => free_list.is_empty(),
&PoolingAllocationState::ReuseAffinity { ref free_list, .. } => free_list.is_empty(),
}
}
pub(crate) fn alloc(&mut self, id: Option<CompiledModuleId>) -> SlotId {
match self {
&mut PoolingAllocationState::NextAvailable(ref mut free_list) => {
debug_assert!(free_list.len() > 0);
free_list.pop().unwrap()
}
&mut PoolingAllocationState::Random(ref mut free_list) => {
debug_assert!(free_list.len() > 0);
let id = rand::thread_rng().gen_range(0..free_list.len());
free_list.swap_remove(id)
}
&mut PoolingAllocationState::ReuseAffinity {
ref mut free_list,
ref mut per_module,
ref mut slot_state,
..
} => {
if let Some(this_module) = id.and_then(|id| per_module.get_mut(&id)) {
assert!(!this_module.is_empty());
let slot_id = this_module.pop().expect("List should never be empty");
if this_module.is_empty() {
per_module.remove(&id.unwrap());
}
remove_global_free_list_item(slot_state, free_list, slot_id);
slot_state[slot_id.index()] = SlotState::Taken(id);
slot_id
} else {
let free_list_index = rand::thread_rng().gen_range(0..free_list.len());
let slot_id = free_list[free_list_index];
remove_global_free_list_item(slot_state, free_list, slot_id);
if let &SlotState::Free(FreeSlotState::Affinity { module, .. }) =
&slot_state[slot_id.index()]
{
remove_module_free_list_item(slot_state, per_module, module, slot_id);
}
slot_state[slot_id.index()] = SlotState::Taken(id);
slot_id
}
}
}
}
pub(crate) fn free(&mut self, index: SlotId) {
match self {
&mut PoolingAllocationState::NextAvailable(ref mut free_list)
| &mut PoolingAllocationState::Random(ref mut free_list) => {
free_list.push(index);
}
&mut PoolingAllocationState::ReuseAffinity {
ref mut per_module,
ref mut free_list,
ref mut slot_state,
} => {
let module_id = slot_state[index.index()].unwrap_module_id();
let free_list_index = GlobalFreeListIndex(free_list.len());
free_list.push(index);
if let Some(id) = module_id {
let per_module_list = per_module
.entry(id)
.or_insert_with(|| Vec::with_capacity(1));
let per_module_index = PerModuleFreeListIndex(per_module_list.len());
per_module_list.push(index);
slot_state[index.index()] = SlotState::Free(FreeSlotState::Affinity {
module: id,
free_list_index,
per_module_index,
});
} else {
slot_state[index.index()] =
SlotState::Free(FreeSlotState::NoAffinity { free_list_index });
}
}
}
}
#[cfg(test)]
pub(crate) fn testing_freelist(&self) -> &[SlotId] {
match self {
&PoolingAllocationState::NextAvailable(ref free_list)
| &PoolingAllocationState::Random(ref free_list) => &free_list[..],
_ => panic!("Wrong kind of state"),
}
}
#[cfg(test)]
pub(crate) fn testing_module_affinity_list(&self) -> Vec<CompiledModuleId> {
match self {
&PoolingAllocationState::NextAvailable(..) | &PoolingAllocationState::Random(..) => {
panic!("Wrong kind of state")
}
&PoolingAllocationState::ReuseAffinity { ref per_module, .. } => {
let mut ret = vec![];
for (module, list) in per_module {
assert!(!list.is_empty());
ret.push(*module);
}
ret
}
}
}
}
#[cfg(test)]
mod test {
use super::{PoolingAllocationState, SlotId};
use crate::CompiledModuleIdAllocator;
use crate::PoolingAllocationStrategy;
#[test]
fn test_next_available_allocation_strategy() {
let strat = PoolingAllocationStrategy::NextAvailable;
let mut state = PoolingAllocationState::new(strat, 10);
assert_eq!(state.alloc(None).index(), 9);
let mut state = PoolingAllocationState::new(strat, 5);
assert_eq!(state.alloc(None).index(), 4);
let mut state = PoolingAllocationState::new(strat, 1);
assert_eq!(state.alloc(None).index(), 0);
}
#[test]
fn test_random_allocation_strategy() {
let strat = PoolingAllocationStrategy::Random;
let mut state = PoolingAllocationState::new(strat, 100);
assert!(state.alloc(None).index() < 100);
let mut state = PoolingAllocationState::new(strat, 1);
assert_eq!(state.alloc(None).index(), 0);
}
#[test]
fn test_affinity_allocation_strategy() {
let strat = PoolingAllocationStrategy::ReuseAffinity;
let id_alloc = CompiledModuleIdAllocator::new();
let id1 = id_alloc.alloc();
let id2 = id_alloc.alloc();
let mut state = PoolingAllocationState::new(strat, 100);
let index1 = state.alloc(Some(id1));
assert!(index1.index() < 100);
let index2 = state.alloc(Some(id2));
assert!(index2.index() < 100);
assert_ne!(index1, index2);
state.free(index1);
let index3 = state.alloc(Some(id1));
assert_eq!(index3, index1);
state.free(index3);
state.free(index2);
let affinity_modules = state.testing_module_affinity_list();
assert_eq!(2, affinity_modules.len());
assert!(affinity_modules.contains(&id1));
assert!(affinity_modules.contains(&id2));
let mut indices = vec![];
for _ in 0..100 {
assert!(!state.is_empty());
indices.push(state.alloc(Some(id2)));
}
assert!(state.is_empty());
assert_eq!(indices[0], index2);
for i in indices {
state.free(i);
}
let affinity_modules = state.testing_module_affinity_list();
assert_eq!(1, affinity_modules.len());
assert!(affinity_modules.contains(&id2));
let index = state.alloc(Some(id1));
state.free(index);
}
#[test]
fn test_affinity_allocation_strategy_random() {
use rand::Rng;
let mut rng = rand::thread_rng();
let strat = PoolingAllocationStrategy::ReuseAffinity;
let id_alloc = CompiledModuleIdAllocator::new();
let ids = std::iter::repeat_with(|| id_alloc.alloc())
.take(10)
.collect::<Vec<_>>();
let mut state = PoolingAllocationState::new(strat, 1000);
let mut allocated: Vec<SlotId> = vec![];
let mut last_id = vec![None; 1000];
let mut hits = 0;
for _ in 0..100_000 {
if !allocated.is_empty() && (state.is_empty() || rng.gen_bool(0.5)) {
let i = rng.gen_range(0..allocated.len());
let to_free_idx = allocated.swap_remove(i);
state.free(to_free_idx);
} else {
assert!(!state.is_empty());
let id = ids[rng.gen_range(0..ids.len())];
let index = state.alloc(Some(id));
if last_id[index.index()] == Some(id) {
hits += 1;
}
last_id[index.index()] = Some(id);
allocated.push(index);
}
}
assert!(
hits > 20000,
"expected at least 20000 (20%) ID-reuses but got {}",
hits
);
}
}