Skip to main content

wasmtime/runtime/vm/instance/allocator/pooling/
index_allocator.rs

1//! Index/slot allocator policies for the pooling allocator.
2
3use super::ShardId;
4use crate::hash_map::{Entry, HashMap};
5use crate::prelude::*;
6use crate::runtime::vm::CompiledModuleId;
7use std::mem;
8use std::sync::Mutex;
9use wasmtime_environ::DefinedMemoryIndex;
10
11/// A slot index.
12#[derive(Hash, Clone, Copy, Debug, PartialEq, Eq)]
13pub struct SlotId(pub u32);
14
15impl SlotId {
16    /// The index of this slot.
17    pub fn index(self) -> usize {
18        self.0 as usize
19    }
20}
21
22/// A simple index allocator.
23///
24/// This index allocator doesn't do any module affinity or anything like that,
25/// however it is built on top of the `ModuleAffinityIndexAllocator` to save
26/// code (and code size).
27#[derive(Debug)]
28pub struct SimpleIndexAllocator(ModuleAffinityIndexAllocator);
29
30impl SimpleIndexAllocator {
31    pub fn new(capacity: u32) -> Result<Self, OutOfMemory> {
32        Ok(SimpleIndexAllocator(ModuleAffinityIndexAllocator::new(
33            capacity, 0,
34        )?))
35    }
36
37    pub fn is_empty(&self) -> bool {
38        self.0.is_empty()
39    }
40
41    pub fn alloc(&self) -> Option<SlotId> {
42        self.0.alloc(None)
43    }
44
45    /// Frees the `index` slot to be available for allocation elsewhere.
46    ///
47    /// The `bytes_resident` argument is a counter to keep track of how many
48    /// bytse are still resident in this slot, if any, for reporting later via
49    /// the [`Self::unused_bytes_resident`] method.
50    pub(crate) fn free(&self, index: SlotId, bytes_resident: usize) {
51        self.0.free(index, bytes_resident);
52    }
53
54    /// Same as [`Self::free`], but frees many slots under a single lock
55    /// acquisition.
56    pub(crate) fn free_many(&self, items: impl IntoIterator<Item = (SlotId, usize)>) {
57        self.0.free_many(items);
58    }
59
60    /// Returns the number of previously-used slots in this allocator which are
61    /// not currently in use.
62    ///
63    /// Note that this acquires a `Mutex` for synchronization at this time to
64    /// read the internal counter information.
65    pub fn unused_warm_slots(&self) -> u32 {
66        self.0.unused_warm_slots()
67    }
68
69    /// Returns the number of bytes that are resident in previously-used slots
70    /// in this allocator which are not currently in use.
71    ///
72    /// Note that this acquires a `Mutex` for synchronization at this time to
73    /// read the internal counter information.
74    pub fn unused_bytes_resident(&self) -> usize {
75        self.0.unused_bytes_resident()
76    }
77
78    #[cfg(test)]
79    pub(crate) fn testing_freelist(&self) -> Vec<SlotId> {
80        self.0.testing_freelist()
81    }
82}
83
84/// A particular defined memory within a particular module.
85#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
86pub struct MemoryInModule(pub CompiledModuleId, pub DefinedMemoryIndex);
87
88/// An index allocator that has configurable affinity between slots and modules
89/// so that slots are often reused for the same module again.
90#[derive(Debug)]
91pub struct ModuleAffinityIndexAllocator {
92    /// The slot space is partitioned into shards, each protected by its own
93    /// mutex, to avoid contention on a single lock when many threads
94    /// allocate and free slots concurrently. Each shard owns a contiguous
95    /// range of `slots_per_shard` slot indices and manages them with local
96    /// indices; translation to global `SlotId`s happens at this type's
97    /// public boundary.
98    ///
99    /// Threads have a "home" shard (the same thread-local, round-robin
100    /// assignment used for the sharded decommit queue) which they try
101    /// first for allocation, falling back to probing the other shards, so
102    /// in steady state each thread allocates and frees from its own shard
103    /// without cross-thread lock traffic. Pool exhaustion is only reported
104    /// after all shards have been consulted.
105    shards: Box<[super::CachePadded<Mutex<Inner>>]>,
106    slots_per_shard: u32,
107}
108
109#[derive(Debug)]
110struct Inner {
111    /// Maximum number of "unused warm slots" which will be allowed during
112    /// allocation.
113    ///
114    /// This is a user-configurable knob which can be used to influence the
115    /// maximum number of unused slots at any one point in time. A "warm slot"
116    /// is one that's considered having been previously allocated.
117    max_unused_warm_slots: u32,
118
119    /// Current count of "warm slots", or those that were previously allocated
120    /// which are now no longer in use.
121    ///
122    /// This is the size of the `warm` list.
123    unused_warm_slots: u32,
124
125    /// A linked list (via indices) which enumerates all "warm and unused"
126    /// slots, or those which have previously been allocated and then free'd.
127    warm: List,
128
129    /// Last slot that was allocated for the first time ever.
130    ///
131    /// This is initially 0 and is incremented during `pick_cold`. If this
132    /// matches `max_cold`, there are no more cold slots left.
133    last_cold: u32,
134
135    /// The state of any given slot.
136    ///
137    /// Records indices in the above list (empty) or two lists (with affinity),
138    /// and these indices are kept up-to-date to allow fast removal.
139    slot_state: Vec<SlotState>,
140
141    /// Affine slot management which tracks which slots are free and were last
142    /// used with the specified `CompiledModuleId`.
143    ///
144    /// The `List` here is appended to during deallocation and removal happens
145    /// from the tail during allocation.
146    module_affine: HashMap<MemoryInModule, List>,
147
148    /// Cache for the sum of the `bytes_resident` of all `UnusedWarm` slots.
149    unused_bytes_resident: usize,
150}
151
152/// A helper "linked list" data structure which is based on indices.
153#[derive(Default, Debug)]
154struct List {
155    head: Option<SlotId>,
156    tail: Option<SlotId>,
157}
158
159/// A helper data structure for an intrusive linked list, coupled with the
160/// `List` type.
161#[derive(Default, Debug, Copy, Clone)]
162struct Link {
163    prev: Option<SlotId>,
164    next: Option<SlotId>,
165}
166
167#[derive(Clone, Debug)]
168enum SlotState {
169    /// This slot is currently in use and is affine to the specified module's memory.
170    Used(Option<MemoryInModule>),
171
172    /// This slot is not currently used, and has never been used.
173    UnusedCold,
174
175    /// This slot is not currently used, but was previously allocated.
176    ///
177    /// The payload here is metadata about the lists that this slot is contained
178    /// within.
179    UnusedWarm(Unused),
180}
181
182impl SlotState {
183    fn unwrap_unused(&mut self) -> &mut Unused {
184        match self {
185            SlotState::UnusedWarm(u) => u,
186            _ => unreachable!(),
187        }
188    }
189}
190
191#[derive(Default, Copy, Clone, Debug)]
192struct Unused {
193    /// Which module this slot was historically affine to, if any.
194    affinity: Option<MemoryInModule>,
195
196    /// Number of bytes that are part of `UnusedWarm` slots and are currently
197    /// kept resident (vs paged out).
198    bytes_resident: usize,
199
200    /// Metadata about the linked list for all slots affine to `affinity`.
201    affine_list_link: Link,
202
203    /// Metadata within the `warm` list of the main allocator.
204    unused_list_link: Link,
205}
206
207enum AllocMode {
208    ForceAffineAndClear,
209    AnySlot,
210    AnyWarm,
211}
212
213/// The division of an allocator's slot space and unused-warm-slot budget
214/// into shards.
215#[derive(Debug, PartialEq, Eq)]
216struct ShardLayout {
217    /// Number of slots in each shard except possibly the last, which may be
218    /// smaller when `requested_shards` doesn't evenly divide the capacity.
219    slots_per_shard: u32,
220    /// Per-shard `(capacity, max_unused_warm_slots)`.
221    shards: Box<[(u32, u32)]>,
222}
223
224impl ShardLayout {
225    fn new(
226        capacity: u32,
227        max_unused_warm_slots: u32,
228        requested_shards: u32,
229    ) -> Result<ShardLayout, OutOfMemory> {
230        // N.B. we limit the pool sharding (via `default_shard_count`, whose
231        // cap `requested_shards` reflects) regardless of CPU count to
232        // balance reduced lock-contention with the downsides of slot
233        // sharding. In particular, on many-core systems, scaling with the
234        // number of cores can lead to:
235        // - very small shards, increasing the likelihood of running out of
236        //   slots in a shard and falling off the fast path.
237        // - warm-slot budget dilution, where `max_unused_warm_slots` is low
238        //   enough that many shards don't get warm slots at all.
239        // - affinity dilution, where some threads may have slots with the
240        //   right instance type affinity available, but the thread handling
241        //   the request doesn't, so the slower instantiation path has to be
242        //   taken.
243        //
244        // Additionally, we don't shard at all for small pools, as the
245        // downsides of sharding are too pronounced.
246        let nshards = if capacity >= 128 {
247            requested_shards.max(1)
248        } else {
249            1
250        };
251        let slots_per_shard = capacity.div_ceil(nshards).max(1);
252        let nshards = capacity.div_ceil(slots_per_shard).max(1);
253
254        let shards = (0..nshards)
255            .map(|i| {
256                let base = i * slots_per_shard;
257                let shard_capacity = capacity.saturating_sub(base).min(slots_per_shard);
258                // Distribute the unused-warm budget across shards,
259                // spreading the remainder over the leading shards.
260                let shard_warm = max_unused_warm_slots / nshards
261                    + u32::from(i < max_unused_warm_slots % nshards);
262                (shard_capacity, shard_warm)
263            })
264            .try_collect()?;
265
266        Ok(ShardLayout {
267            slots_per_shard,
268            shards,
269        })
270    }
271}
272
273impl ModuleAffinityIndexAllocator {
274    /// Create the default state for this strategy.
275    pub fn new(capacity: u32, max_unused_warm_slots: u32) -> Result<Self, OutOfMemory> {
276        Self::new_with_shard_count(
277            capacity,
278            max_unused_warm_slots,
279            super::default_shard_count(),
280        )
281    }
282
283    /// Same as [`Self::new`], but with an explicit shard count (which is
284    /// capped as described in [`ShardLayout::new`]).
285    fn new_with_shard_count(
286        capacity: u32,
287        max_unused_warm_slots: u32,
288        requested_shards: u32,
289    ) -> Result<Self, OutOfMemory> {
290        let layout = ShardLayout::new(capacity, max_unused_warm_slots, requested_shards)?;
291        let shards = layout
292            .shards
293            .iter()
294            .map(|&(shard_capacity, shard_warm)| {
295                super::CachePadded(Mutex::new(Inner {
296                    last_cold: 0,
297                    max_unused_warm_slots: shard_warm,
298                    unused_warm_slots: 0,
299                    module_affine: HashMap::new(),
300                    slot_state: (0..shard_capacity).map(|_| SlotState::UnusedCold).collect(),
301                    warm: List::default(),
302                    unused_bytes_resident: 0,
303                }))
304            })
305            .try_collect()?;
306
307        Ok(ModuleAffinityIndexAllocator {
308            shards,
309            slots_per_shard: layout.slots_per_shard,
310        })
311    }
312
313    /// Translate a shard-local slot index to a global `SlotId`.
314    fn global_id(&self, shard: ShardId, local: SlotId) -> SlotId {
315        SlotId(u32::try_from(shard.index()).unwrap() * self.slots_per_shard + local.0)
316    }
317
318    /// Translate a global `SlotId` to its shard and shard-local index.
319    fn shard_of(&self, global: SlotId) -> (ShardId, SlotId) {
320        let shard = ShardId::from_index((global.0 / self.slots_per_shard) as usize);
321        (shard, SlotId(global.0 % self.slots_per_shard))
322    }
323
324    /// Returns the [`Inner`] state of the given shard.
325    fn shard(&self, shard: ShardId) -> &Mutex<Inner> {
326        &self.shards[shard.index()].0
327    }
328
329    /// Enumerate all shard ids of this allocator.
330    fn shard_ids(&self) -> impl Iterator<Item = ShardId> + use<> {
331        (0..self.shards.len()).map(ShardId::from_index)
332    }
333
334    /// How many slots can this allocator allocate?
335    pub fn len(&self) -> usize {
336        self.shards
337            .iter()
338            .map(|s| s.0.lock().unwrap().slot_state.len())
339            .sum()
340    }
341
342    /// Are zero slots in use right now?
343    pub fn is_empty(&self) -> bool {
344        self.shards.iter().all(|s| {
345            !s.0.lock()
346                .unwrap()
347                .slot_state
348                .iter()
349                .any(|state| matches!(state, SlotState::Used(_)))
350        })
351    }
352
353    /// Allocate a new index from this allocator optionally using `id` as an
354    /// affinity request if the allocation strategy supports it.
355    ///
356    /// Returns `None` if no more slots are available.
357    pub fn alloc(&self, for_memory: Option<MemoryInModule>) -> Option<SlotId> {
358        // Start at this thread's home shard and probe the others only if
359        // it's fully allocated. In steady state this means each thread
360        // stays on its own shard.
361        for shard in super::shard_ids_from_home(self.shards.len()) {
362            let mut inner = self.shard(shard).lock().unwrap();
363            if let Some((local, _)) = Self::alloc_within(&mut inner, for_memory, AllocMode::AnySlot)
364            {
365                return Some(self.global_id(shard, local));
366            }
367        }
368        None
369    }
370
371    /// Attempts to allocate a guaranteed-affine slot to the module `id`
372    /// specified.
373    ///
374    /// Returns `None` if there are no slots affine to `id`. The allocation of
375    /// this slot will not record the affinity to `id`, instead simply listing
376    /// it as taken. This is intended to be used for clearing out all affine
377    /// slots to a module.
378    pub fn alloc_affine_and_clear_affinity(
379        &self,
380        module_id: CompiledModuleId,
381        memory_index: DefinedMemoryIndex,
382    ) -> Option<SlotId> {
383        // Affine slots for this module may live in any shard, so consult
384        // them all. This is a module-teardown path, not a hot path.
385        for shard in self.shard_ids() {
386            let mut inner = self.shard(shard).lock().unwrap();
387            if let Some((local, _)) = Self::alloc_within(
388                &mut inner,
389                Some(MemoryInModule(module_id, memory_index)),
390                AllocMode::ForceAffineAndClear,
391            ) {
392                return Some(self.global_id(shard, local));
393            }
394        }
395        None
396    }
397
398    /// Allocates a slot within `inner`, returning the slot along with the
399    /// number of bytes it had resident if it was previously a warm slot.
400    fn alloc_within(
401        inner: &mut Inner,
402        for_memory: Option<MemoryInModule>,
403        mode: AllocMode,
404    ) -> Option<(SlotId, usize)> {
405        // As a first-pass always attempt an affine allocation. This will
406        // succeed if any slots are considered affine to `module_id` (if it's
407        // specified). Failing that something else is attempted to be chosen.
408        let slot_id = inner.pick_affine(for_memory).or_else(|| {
409            match mode {
410                // If any slot is requested then this is a normal instantiation
411                // looking for an index. Without any affine candidates there are
412                // two options here:
413                //
414                // 1. Pick a slot amongst previously allocated slots
415                // 2. Pick a slot that's never been used before
416                //
417                // The choice here is guided by the initial configuration of
418                // `max_unused_warm_slots`. If our unused warm slots, which are
419                // likely all affine, is below this threshold then the affinity
420                // of the warm slots isn't tampered with and first a cold slot
421                // is chosen. If the cold slot allocation fails, however, a warm
422                // slot is evicted.
423                //
424                // The opposite happens when we're above our threshold for the
425                // maximum number of warm slots, meaning that a warm slot is
426                // attempted to be picked from first with a cold slot following
427                // that. Note that the warm slot allocation in this case should
428                // only fail of `max_unused_warm_slots` is 0, otherwise
429                // `pick_warm` will always succeed.
430                AllocMode::AnySlot => {
431                    if inner.unused_warm_slots < inner.max_unused_warm_slots {
432                        inner.pick_cold().or_else(|| inner.pick_warm())
433                    } else {
434                        inner.pick_warm().or_else(|| {
435                            debug_assert!(inner.max_unused_warm_slots == 0);
436                            inner.pick_cold()
437                        })
438                    }
439                }
440
441                // In this mode an affinity-based allocation is always performed
442                // as the purpose here is to clear out slots relevant to
443                // `module_id` during module teardown. This means that there's
444                // no consulting non-affine slots in this path.
445                AllocMode::ForceAffineAndClear => None,
446
447                // In this mode only warm slots are taken.
448                AllocMode::AnyWarm => inner.pick_warm(),
449            }
450        })?;
451
452        let slot = &mut inner.slot_state[slot_id.index()];
453        let (affinity, bytes_resident) = match slot {
454            SlotState::UnusedWarm(u) => (u.affinity, u.bytes_resident),
455            _ => (None, 0),
456        };
457        inner.unused_bytes_resident -= bytes_resident;
458        *slot = SlotState::Used(match mode {
459            AllocMode::ForceAffineAndClear => None,
460            AllocMode::AnySlot => for_memory,
461            AllocMode::AnyWarm => {
462                debug_assert!(for_memory.is_none());
463                affinity
464            }
465        });
466
467        Some((slot_id, bytes_resident))
468    }
469
470    pub(crate) fn free(&self, index: SlotId, bytes_resident: usize) {
471        let (shard, local) = self.shard_of(index);
472        let mut inner = self.shard(shard).lock().unwrap();
473        Self::free_locked(&mut inner, local, bytes_resident);
474    }
475
476    /// Same as [`Self::free`], but frees many slots under a single lock
477    /// acquisition per shard to reduce contention when a decommit-queue
478    /// flush returns a whole batch of slots at once.
479    pub(crate) fn free_many(&self, items: impl IntoIterator<Item = (SlotId, usize)>) {
480        let mut per_shard: smallvec::SmallVec<[smallvec::SmallVec<[(SlotId, usize); 8]>; 16]> =
481            (0..self.shards.len()).map(|_| Default::default()).collect();
482        for (index, bytes_resident) in items {
483            let (shard, local) = self.shard_of(index);
484            per_shard[shard.index()].push((local, bytes_resident));
485        }
486        for (shard, items) in per_shard.into_iter().enumerate() {
487            if items.is_empty() {
488                continue;
489            }
490            let mut inner = self.shard(ShardId::from_index(shard)).lock().unwrap();
491            for (local, bytes_resident) in items {
492                Self::free_locked(&mut inner, local, bytes_resident);
493            }
494        }
495    }
496
497    fn free_locked(inner: &mut Inner, index: SlotId, bytes_resident: usize) {
498        let module_memory = match inner.slot_state[index.index()] {
499            SlotState::Used(module_memory) => module_memory,
500            _ => unreachable!(),
501        };
502
503        // Bump the number of warm slots since this slot is now considered
504        // previously used. Afterwards append it to the linked list of all
505        // unused and warm slots.
506        inner.unused_warm_slots += 1;
507        let unused_list_link = inner
508            .warm
509            .append(index, &mut inner.slot_state, |s| &mut s.unused_list_link);
510
511        let affine_list_link = match module_memory {
512            // If this slot is affine to a particular module then append this
513            // index to the linked list for the affine module. Otherwise insert
514            // a new one-element linked list.
515            Some(module) => match inner.module_affine.entry(module) {
516                Entry::Occupied(mut e) => e
517                    .get_mut()
518                    .append(index, &mut inner.slot_state, |s| &mut s.affine_list_link),
519                Entry::Vacant(v) => {
520                    v.insert(List::new(index));
521                    Link::default()
522                }
523            },
524
525            // If this slot has no affinity then the affine link is empty.
526            None => Link::default(),
527        };
528
529        inner.unused_bytes_resident += bytes_resident;
530        inner.slot_state[index.index()] = SlotState::UnusedWarm(Unused {
531            affinity: module_memory,
532            bytes_resident,
533            affine_list_link,
534            unused_list_link,
535        });
536    }
537
538    /// Return the number of empty slots available in this allocator.
539    #[cfg(test)]
540    pub fn num_empty_slots(&self) -> usize {
541        self.shards
542            .iter()
543            .map(|s| {
544                let inner = s.0.lock().unwrap();
545                let total_slots = inner.slot_state.len();
546                (total_slots - inner.last_cold as usize) + inner.unused_warm_slots as usize
547            })
548            .sum()
549    }
550
551    /// For testing only, we want to be able to assert what is on the single
552    /// freelist, for the policies that keep just one.
553    #[cfg(test)]
554    pub(crate) fn testing_freelist(&self) -> Vec<SlotId> {
555        self.shard_ids()
556            .flat_map(|shard| {
557                let inner = self.shard(shard).lock().unwrap();
558                inner
559                    .warm
560                    .iter(&inner.slot_state, |s| &s.unused_list_link)
561                    .map(|local| self.global_id(shard, local))
562                    .collect::<Vec<_>>()
563            })
564            .collect()
565    }
566
567    /// For testing only, get the list of all modules with at least one slot
568    /// with affinity for that module.
569    #[cfg(test)]
570    pub(crate) fn testing_module_affinity_list(&self) -> Vec<MemoryInModule> {
571        let mut ret = Vec::new();
572        for s in self.shards.iter() {
573            let inner = s.0.lock().unwrap();
574            for key in inner.module_affine.keys() {
575                if !ret.contains(key) {
576                    ret.push(*key);
577                }
578            }
579        }
580        ret
581    }
582
583    /// Returns the number of previously-used slots in this allocator which are
584    /// not currently in use.
585    ///
586    /// Note that this acquires a `Mutex` for synchronization at this time to
587    /// read the internal counter information.
588    pub fn unused_warm_slots(&self) -> u32 {
589        self.shards
590            .iter()
591            .map(|s| s.0.lock().unwrap().unused_warm_slots)
592            .sum()
593    }
594
595    /// Takes every warm slot out of the free lists, returning each slot and
596    /// the number of bytes it has resident (which may be zero).
597    ///
598    /// The slots are marked used so that nothing can allocate them while
599    /// their memory is being released; the caller frees each one again
600    /// afterwards.
601    ///
602    /// Shards are locked one at a time rather than all at once, since this
603    /// is reclaiming memory rather than taking a snapshot.
604    pub(crate) fn take_resident_warm_slots(&self) -> Vec<(SlotId, usize)> {
605        let mut taken = Vec::new();
606        for (shard_index, shard) in self.shards.iter().enumerate() {
607            let mut inner = shard.0.lock().unwrap();
608            while let Some((slot, bytes_resident)) =
609                Self::alloc_within(&mut inner, None, AllocMode::AnyWarm)
610            {
611                taken.push((
612                    self.global_id(ShardId::from_index(shard_index), slot),
613                    bytes_resident,
614                ));
615            }
616        }
617        taken
618    }
619
620    /// Returns the number of bytes that are resident in previously-used slots
621    /// in this allocator which are not currently in use.
622    ///
623    /// Note that this acquires a `Mutex` for synchronization at this time to
624    /// read the internal counter information.
625    pub fn unused_bytes_resident(&self) -> usize {
626        self.shards
627            .iter()
628            .map(|s| s.0.lock().unwrap().unused_bytes_resident)
629            .sum()
630    }
631}
632
633impl Inner {
634    /// Attempts to allocate a slot already affine to `id`, returning `None` if
635    /// `id` is `None` or if there are no affine slots.
636    fn pick_affine(&mut self, for_memory: Option<MemoryInModule>) -> Option<SlotId> {
637        // Note that the `tail` is chosen here of the affine list as it's the
638        // most recently used, which for affine allocations is what we want --
639        // maximizing temporal reuse.
640        let ret = self.module_affine.get(&for_memory?)?.tail?;
641        self.remove(ret);
642        Some(ret)
643    }
644
645    fn pick_warm(&mut self) -> Option<SlotId> {
646        // Insertions into the `unused` list happen at the `tail`, so the
647        // least-recently-used item will be at the head. That's our goal here,
648        // pick the least-recently-used slot since something "warm" is being
649        // evicted anyway.
650        let head = self.warm.head?;
651        self.remove(head);
652        Some(head)
653    }
654
655    fn remove(&mut self, slot: SlotId) {
656        // Decrement the size of the warm list, and additionally remove it from
657        // the `warm` linked list.
658        self.unused_warm_slots -= 1;
659        self.warm
660            .remove(slot, &mut self.slot_state, |u| &mut u.unused_list_link);
661
662        // If this slot is affine to a module then additionally remove it from
663        // that module's affinity linked list. Note that if the module's affine
664        // list is empty then the module's entry in the map is completely
665        // removed as well.
666        let module = self.slot_state[slot.index()].unwrap_unused().affinity;
667        if let Some(module) = module {
668            let mut list = match self.module_affine.entry(module) {
669                Entry::Occupied(e) => e,
670                Entry::Vacant(_) => unreachable!(),
671            };
672            list.get_mut()
673                .remove(slot, &mut self.slot_state, |u| &mut u.affine_list_link);
674
675            if list.get_mut().head.is_none() {
676                list.remove();
677            }
678        }
679    }
680
681    fn pick_cold(&mut self) -> Option<SlotId> {
682        if (self.last_cold as usize) == self.slot_state.len() {
683            None
684        } else {
685            let ret = Some(SlotId(self.last_cold));
686            self.last_cold += 1;
687            ret
688        }
689    }
690}
691
692impl List {
693    /// Creates a new one-element list pointing at `id`.
694    fn new(id: SlotId) -> List {
695        List {
696            head: Some(id),
697            tail: Some(id),
698        }
699    }
700
701    /// Appends the `id` to this list whose links are determined by `link`.
702    fn append(
703        &mut self,
704        id: SlotId,
705        states: &mut [SlotState],
706        link: fn(&mut Unused) -> &mut Link,
707    ) -> Link {
708        // This `id` is the new tail...
709        let tail = mem::replace(&mut self.tail, Some(id));
710
711        // If the tail was present, then update its `next` field to ourselves as
712        // we've been appended, otherwise update the `head` since the list was
713        // previously empty.
714        match tail {
715            Some(tail) => link(states[tail.index()].unwrap_unused()).next = Some(id),
716            None => self.head = Some(id),
717        }
718        Link {
719            prev: tail,
720            next: None,
721        }
722    }
723
724    /// Removes `id` from this list whose links are determined by `link`.
725    fn remove(
726        &mut self,
727        id: SlotId,
728        slot_state: &mut [SlotState],
729        link: fn(&mut Unused) -> &mut Link,
730    ) -> Unused {
731        let mut state = *slot_state[id.index()].unwrap_unused();
732        let next = link(&mut state).next;
733        let prev = link(&mut state).prev;
734
735        // If a `next` node is present for this link, then its previous was our
736        // own previous now. Otherwise we are the tail so the new tail is our
737        // previous.
738        match next {
739            Some(next) => link(slot_state[next.index()].unwrap_unused()).prev = prev,
740            None => self.tail = prev,
741        }
742
743        // Same as the `next` node, except everything is in reverse.
744        match prev {
745            Some(prev) => link(slot_state[prev.index()].unwrap_unused()).next = next,
746            None => self.head = next,
747        }
748        state
749    }
750
751    #[cfg(test)]
752    fn iter<'a>(
753        &'a self,
754        states: &'a [SlotState],
755        link: fn(&Unused) -> &Link,
756    ) -> impl Iterator<Item = SlotId> + 'a {
757        let mut cur = self.head;
758        let mut prev = None;
759        std::iter::from_fn(move || {
760            if cur.is_none() {
761                assert_eq!(prev, self.tail);
762            }
763            let ret = cur?;
764            match &states[ret.index()] {
765                SlotState::UnusedWarm(u) => {
766                    assert_eq!(link(u).prev, prev);
767                    prev = Some(ret);
768                    cur = link(u).next
769                }
770                _ => unreachable!(),
771            }
772            Some(ret)
773        })
774    }
775}
776
777#[cfg(test)]
778mod test {
779    use super::*;
780    use rand::RngExt;
781    use wasmtime_environ::EntityRef;
782
783    #[test]
784    fn test_next_available_allocation_strategy() {
785        for size in 0..20 {
786            let state = ModuleAffinityIndexAllocator::new(size, 0).unwrap();
787            assert_eq!(state.num_empty_slots(), usize::try_from(size).unwrap());
788            for i in 0..size {
789                assert_eq!(state.num_empty_slots(), usize::try_from(size - i).unwrap());
790                assert_eq!(state.alloc(None).unwrap().index(), i as usize);
791            }
792            assert!(state.alloc(None).is_none());
793        }
794    }
795
796    /// Taking slots out to release their memory must not cost them their
797    /// affinity: `free` reads the module back out of the `Used` payload to
798    /// re-file the slot on its module's affine list.
799    #[test]
800    fn take_resident_warm_slots_keeps_affinity() {
801        let id = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
802        let state = ModuleAffinityIndexAllocator::new(4, 4).unwrap();
803
804        let index = state.alloc(Some(id)).unwrap();
805        state.free(index, 4096);
806        assert_eq!(state.unused_bytes_resident(), 4096);
807
808        let taken = state.take_resident_warm_slots();
809        assert_eq!(taken, vec![(index, 4096)]);
810        // While taken, the slot is neither warm nor counted as resident.
811        assert_eq!(state.unused_bytes_resident(), 0);
812        assert_eq!(state.unused_warm_slots(), 0);
813
814        state.free(index, 0);
815        assert_eq!(state.unused_bytes_resident(), 0);
816        assert_eq!(state.unused_warm_slots(), 1);
817        assert!(state.testing_module_affinity_list().contains(&id));
818        // And the affinity is real: the same module gets the same slot back.
819        assert_eq!(state.alloc(Some(id)).unwrap(), index);
820    }
821
822    #[test]
823    fn test_affinity_allocation_strategy() {
824        let id1 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
825        let id2 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
826        let state = ModuleAffinityIndexAllocator::new(100, 100).unwrap();
827
828        let index1 = state.alloc(Some(id1)).unwrap();
829        assert_eq!(index1.index(), 0);
830        let index2 = state.alloc(Some(id2)).unwrap();
831        assert_eq!(index2.index(), 1);
832        assert_ne!(index1, index2);
833
834        state.free(index1, 0);
835        assert_eq!(state.num_empty_slots(), 99);
836
837        // Allocate to the same `index1` slot again.
838        let index3 = state.alloc(Some(id1)).unwrap();
839        assert_eq!(index3, index1);
840        state.free(index3, 0);
841
842        state.free(index2, 0);
843
844        // Both id1 and id2 should have some slots with affinity.
845        let affinity_modules = state.testing_module_affinity_list();
846        assert_eq!(2, affinity_modules.len());
847        assert!(affinity_modules.contains(&id1));
848        assert!(affinity_modules.contains(&id2));
849
850        // Now there is 1 free instance for id2 and 1 free instance
851        // for id1, and 98 empty. Allocate 100 for id2. The first
852        // should be equal to the one we know was previously used for
853        // id2. The next 99 are arbitrary.
854        assert_eq!(state.num_empty_slots(), 100);
855        let mut indices = vec![];
856        for _ in 0..100 {
857            indices.push(state.alloc(Some(id2)).unwrap());
858        }
859        assert!(state.alloc(None).is_none());
860        assert_eq!(indices[0], index2);
861        assert_eq!(state.num_empty_slots(), 0);
862
863        for i in indices {
864            state.free(i, 0);
865        }
866
867        // Now there should be no slots left with affinity for id1.
868        let affinity_modules = state.testing_module_affinity_list();
869        assert_eq!(1, affinity_modules.len());
870        assert!(affinity_modules.contains(&id2));
871
872        // Allocate an index we know previously had an instance but
873        // now does not (list ran empty).
874        let index = state.alloc(Some(id1)).unwrap();
875        state.free(index, 0);
876    }
877
878    #[test]
879    fn clear_affine() {
880        let id = CompiledModuleId::new();
881        let memory_index = DefinedMemoryIndex::new(0);
882
883        for max_unused_warm_slots in [0, 1, 2] {
884            let state = ModuleAffinityIndexAllocator::new(100, max_unused_warm_slots).unwrap();
885
886            let index1 = state.alloc(Some(MemoryInModule(id, memory_index))).unwrap();
887            let index2 = state.alloc(Some(MemoryInModule(id, memory_index))).unwrap();
888            state.free(index2, 0);
889            state.free(index1, 0);
890            assert!(
891                state
892                    .alloc_affine_and_clear_affinity(id, memory_index)
893                    .is_some()
894            );
895            assert!(
896                state
897                    .alloc_affine_and_clear_affinity(id, memory_index)
898                    .is_some()
899            );
900            assert_eq!(
901                state.alloc_affine_and_clear_affinity(id, memory_index),
902                None
903            );
904        }
905    }
906
907    #[test]
908    fn test_affinity_allocation_strategy_random() {
909        let mut rng = rand::rng();
910
911        let ids = std::iter::repeat_with(|| {
912            MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0))
913        })
914        .take(10)
915        .collect::<Vec<_>>();
916        // Pin the allocator to a single shard: with multiple shards a
917        // thread's alloc probing finds any free slot in its home shard
918        // before consulting the shard holding the affine slot, making the
919        // hit-rate statistics below depend on the host's CPU count.
920        // Sharded allocation is covered by the proptests at the bottom of
921        // this module.
922        let state = ModuleAffinityIndexAllocator::new_with_shard_count(1000, 1000, 1).unwrap();
923        let mut allocated: Vec<SlotId> = vec![];
924        let mut last_id = vec![None; 1000];
925
926        let mut hits = 0;
927        let amt = if cfg!(miri) { 100 } else { 100_000 };
928        for _ in 0..amt {
929            loop {
930                if !allocated.is_empty() && rng.random_bool(0.5) {
931                    let i = rng.random_range(0..allocated.len());
932                    let to_free_idx = allocated.swap_remove(i);
933                    state.free(to_free_idx, 0);
934                } else {
935                    let id = ids[rng.random_range(0..ids.len())];
936                    let index = match state.alloc(Some(id)) {
937                        Some(id) => id,
938                        None => continue,
939                    };
940                    if last_id[index.index()] == Some(id) {
941                        hits += 1;
942                    }
943                    last_id[index.index()] = Some(id);
944                    allocated.push(index);
945                }
946                break;
947            }
948        }
949
950        // 10% reuse would be random chance (because we have 10 module
951        // IDs). Check for at least double that to ensure some sort of
952        // affinity is occurring.
953        assert!(
954            hits > (amt / 5),
955            "expected at least 20000 (20%) ID-reuses but got {hits}"
956        );
957    }
958
959    #[test]
960    fn test_affinity_threshold() {
961        let id1 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
962        let id2 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
963        let id3 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
964        let state = ModuleAffinityIndexAllocator::new(10, 2).unwrap();
965
966        // Set some slot affinities
967        assert_eq!(state.alloc(Some(id1)), Some(SlotId(0)));
968        state.free(SlotId(0), 0);
969        assert_eq!(state.alloc(Some(id2)), Some(SlotId(1)));
970        state.free(SlotId(1), 0);
971
972        // Only 2 slots are allowed to be unused and warm, so we're at our
973        // threshold, meaning one must now be evicted.
974        assert_eq!(state.alloc(Some(id3)), Some(SlotId(0)));
975        state.free(SlotId(0), 0);
976
977        // pickup `id2` again, it should be affine.
978        assert_eq!(state.alloc(Some(id2)), Some(SlotId(1)));
979
980        // with only one warm slot available allocation for `id1` should pick a
981        // fresh slot
982        assert_eq!(state.alloc(Some(id1)), Some(SlotId(2)));
983
984        state.free(SlotId(1), 0);
985        state.free(SlotId(2), 0);
986
987        // ensure everything stays affine
988        assert_eq!(state.alloc(Some(id1)), Some(SlotId(2)));
989        assert_eq!(state.alloc(Some(id2)), Some(SlotId(1)));
990        assert_eq!(state.alloc(Some(id3)), Some(SlotId(0)));
991
992        state.free(SlotId(1), 0);
993        state.free(SlotId(2), 0);
994        state.free(SlotId(0), 0);
995
996        // LRU is 1, so that should be picked
997        assert_eq!(
998            state.alloc(Some(MemoryInModule(
999                CompiledModuleId::new(),
1000                DefinedMemoryIndex::new(0)
1001            ))),
1002            Some(SlotId(1))
1003        );
1004
1005        // Pick another LRU entry, this time 2
1006        assert_eq!(
1007            state.alloc(Some(MemoryInModule(
1008                CompiledModuleId::new(),
1009                DefinedMemoryIndex::new(0)
1010            ))),
1011            Some(SlotId(2))
1012        );
1013
1014        // This should preserve slot `0` and pick up something new
1015        assert_eq!(
1016            state.alloc(Some(MemoryInModule(
1017                CompiledModuleId::new(),
1018                DefinedMemoryIndex::new(0)
1019            ))),
1020            Some(SlotId(3))
1021        );
1022
1023        state.free(SlotId(1), 0);
1024        state.free(SlotId(2), 0);
1025        state.free(SlotId(3), 0);
1026
1027        // for good measure make sure id3 is still affine
1028        assert_eq!(state.alloc(Some(id3)), Some(SlotId(0)));
1029    }
1030
1031    #[test]
1032    fn test_freelist() {
1033        let allocator = SimpleIndexAllocator::new(10).unwrap();
1034        assert_eq!(allocator.testing_freelist(), []);
1035        let a = allocator.alloc().unwrap();
1036        assert_eq!(allocator.testing_freelist(), []);
1037        allocator.free(a, 0);
1038        assert_eq!(allocator.testing_freelist(), [a]);
1039        assert_eq!(allocator.alloc(), Some(a));
1040        assert_eq!(allocator.testing_freelist(), []);
1041        let b = allocator.alloc().unwrap();
1042        assert_eq!(allocator.testing_freelist(), []);
1043        allocator.free(b, 0);
1044        assert_eq!(allocator.testing_freelist(), [b]);
1045        allocator.free(a, 0);
1046        assert_eq!(allocator.testing_freelist(), [b, a]);
1047    }
1048
1049    #[test]
1050    // proptest reads the current directory for its persistence file, which
1051    // miri doesn't support with isolation enabled.
1052    #[cfg_attr(miri, ignore)]
1053    fn shard_layout_is_exhaustive_and_exact() {
1054        use proptest::prelude::*;
1055
1056        proptest!(|(
1057            capacity in 0u32..100_000,
1058            max_unused_warm_slots in 0u32..10_000,
1059            requested_shards in 1u32..64,
1060        )| {
1061            let layout = ShardLayout::new(capacity, max_unused_warm_slots, requested_shards)
1062                .unwrap();
1063
1064            // Shard capacities partition the whole slot space, and the
1065            // warm-slot budgets sum to the configured total, no matter how
1066            // unevenly the capacity divides.
1067            prop_assert_eq!(
1068                layout.shards.iter().map(|(c, _)| *c).sum::<u32>(),
1069                capacity
1070            );
1071            prop_assert_eq!(
1072                layout.shards.iter().map(|(_, w)| *w).sum::<u32>(),
1073                max_unused_warm_slots
1074            );
1075
1076            // Every shard except possibly the last is exactly
1077            // `slots_per_shard` large, which the global<->local `SlotId`
1078            // translation relies on.
1079            let (last, rest) = layout.shards.split_last().unwrap();
1080            for (c, _) in rest {
1081                prop_assert_eq!(*c, layout.slots_per_shard);
1082            }
1083            prop_assert!(last.0 <= layout.slots_per_shard);
1084
1085            // The requested shard count is an upper bound, and small pools
1086            // are never sharded.
1087            prop_assert!(layout.shards.len() <= requested_shards as usize);
1088            if capacity < 128 {
1089                prop_assert_eq!(layout.shards.len(), 1);
1090            }
1091        });
1092    }
1093
1094    #[test]
1095    // proptest reads the current directory for its persistence file, which
1096    // miri doesn't support with isolation enabled.
1097    #[cfg_attr(miri, ignore)]
1098    fn sharded_alloc_is_exhaustive_and_unique() {
1099        use proptest::prelude::*;
1100
1101        proptest!(|(
1102            capacity in 0u32..2048,
1103            max_unused_warm_slots in 0u32..100,
1104            requested_shards in 1u32..64,
1105        )| {
1106            let allocator = ModuleAffinityIndexAllocator::new_with_shard_count(
1107                capacity,
1108                max_unused_warm_slots,
1109                requested_shards,
1110            )
1111            .unwrap();
1112
1113            // Regardless of shard layout, we can allocate exactly
1114            // `capacity` slots, all distinct and in-bounds, ...
1115            let mut ids = Vec::new();
1116            let mut seen = std::collections::HashSet::new();
1117            for _ in 0..capacity {
1118                let id = allocator.alloc(None).unwrap();
1119                prop_assert!(id.0 < capacity);
1120                prop_assert!(seen.insert(id.0));
1121                ids.push(id);
1122            }
1123            // ... after which the pool reports exhaustion, ...
1124            prop_assert!(allocator.alloc(None).is_none());
1125
1126            // ... and freeing everything makes it all allocatable again.
1127            allocator.free_many(ids.into_iter().map(|id| (id, 0)));
1128            for _ in 0..capacity {
1129                prop_assert!(allocator.alloc(None).is_some());
1130            }
1131            prop_assert!(allocator.alloc(None).is_none());
1132        });
1133    }
1134}