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
use crate::{CoreAllocator, CoreGroup, CoreIndex};
use hwloc2::CpuSet;
use std::fmt::{Debug, Formatter};
use std::mem::replace;
use std::ops::Range;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
#[cfg(feature = "hwloc2")]
lazy_static::lazy_static! {
    static ref ALL_CORES: Arc<Vec<Arc<Mutex<CoreIndex>>>> = {
        let topo = hwloc2::Topology::new().unwrap();
        let cpuset = topo.object_at_root().cpuset().unwrap();
        let cores = cpuset.into_iter().map(|x| x as _).map(CoreIndex::new).map(Mutex::new).map(Arc::new).collect();
        Arc::new(cores)
    };
}
#[cfg(not(feature = "hwloc2"))]
lazy_static::lazy_static! {
    static ref ALL_CORES: Arc<Vec<Arc<Mutex<CoreIndex>>>> = {
        let cpuset = 0..256;
        let cores = cpuset.into_iter().map(|x| x as _).map(CoreIndex::new).map(Mutex::new).map(Arc::new).collect();
        Arc::new(cores)
    };
}
pub struct NoAllocator;
impl CoreAllocator for NoAllocator {
    fn allocate_core(&self) -> Option<CoreGroup> {
        Some(CoreGroup::any_core())
    }
}
struct ManagedGroup {
    allocated: AtomicBool,
    group: Vec<Arc<Mutex<CoreIndex>>>,
}

pub struct GroupedAllocator {
    groups: Vec<ManagedGroup>,
}
impl GroupedAllocator {
    pub fn new() -> Self {
        Self { groups: vec![] }
    }
    pub fn add_group(&mut self, group: Vec<Arc<Mutex<CoreIndex>>>) {
        self.groups.push(ManagedGroup {
            allocated: AtomicBool::new(false),
            group,
        });
    }
    pub fn filter_group(&mut self, filter: impl Fn(&CoreIndex) -> bool) {
        let groups = replace(&mut self.groups, vec![]);
        'outer: for group in groups {
            for core in &group.group {
                if !filter(&core.lock().unwrap()) {
                    continue 'outer;
                }
            }
            self.groups.push(group);
        }
    }
}
impl CoreAllocator for GroupedAllocator {
    fn allocate_core(&self) -> Option<CoreGroup> {
        for group in self.groups.iter() {
            if group.allocated.load(Ordering::Relaxed) == true {
                let mut only = true;
                for c in &group.group {
                    if Arc::strong_count(c) > 1 {
                        only = false;
                        break;
                    }
                }
                if only {
                    group.allocated.store(false, Ordering::Relaxed);
                }
            }
            if group
                .allocated
                .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
                == Ok(false)
            {
                return Some(CoreGroup::cores(group.group.clone()));
            }
        }

        None
    }
}
impl Debug for GroupedAllocator {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let groups = self
            .groups
            .iter()
            .map(|x| CoreGroup::cores(x.group.clone()))
            .collect::<Vec<_>>();
        groups.fmt(f)
    }
}
pub struct SequentialAllocator;

impl SequentialAllocator {
    pub fn new_range(range: Range<usize>, width: usize) -> GroupedAllocator {
        let mut groups = GroupedAllocator::new();
        let mut group = vec![];
        for i in range {
            group.push(Arc::clone(&ALL_CORES.get(i).unwrap()));
            if group.len() == width {
                groups.add_group(replace(&mut group, vec![]));
            }
        }
        groups
    }
}

#[cfg(feature = "hwloc2")]
pub struct HierarchicalAllocator {
    depth: usize,
    on_cpus: Option<Vec<usize>>,
}
impl HierarchicalAllocator {
    // only for references: see also hwloc-ls
    pub const PHYSICAL_CPU: usize = 1;
    pub const L3_CACHE: usize = 2;
    pub const L2_CACHE: usize = 3;
    pub const LOGICAL_CORE: usize = 4;

    pub fn new_at_depth(depth: usize) -> Self {
        Self {
            depth,
            on_cpus: None,
        }
    }
    pub fn on_cpu(mut self, on_cpus: Vec<usize>) -> Self {
        self.on_cpus = Some(on_cpus);
        self
    }
    pub fn finish(self) -> GroupedAllocator {
        let depth = self.depth;
        let topo = hwloc2::Topology::new().unwrap();
        let mut groups = GroupedAllocator::new();
        let mut allow = CpuSet::new();
        if let Some(allow_cpu) = self.on_cpus {
            for (i, cpu) in topo
                .objects_at_depth(HierarchicalAllocator::PHYSICAL_CPU as u32)
                .iter()
                .enumerate()
            {
                if allow_cpu.iter().find(|x| **x == i).is_some() {
                    for bit in cpu.cpuset().unwrap() {
                        allow.set(bit);
                    }
                }
            }
        } else {
            allow = CpuSet::full();
        }
        if depth == Self::L3_CACHE {
            for object in topo.objects_at_depth(depth as u32).iter() {
                let mut phys = CpuSet::new();
                let mut hypers = CpuSet::new();
                for l2 in object.children() {
                    let mut cpu = l2.cpuset().unwrap().into_iter();
                    phys.set(cpu.next().unwrap());
                    hypers.set(cpu.next().unwrap());
                    assert_eq!(cpu.next(), None);
                }
                for cpu_set in [phys, hypers] {
                    let group = cpu_set
                        .into_iter()
                        .filter(|x| allow.is_set(*x))
                        .flat_map(|x| ALL_CORES.get(x as usize))
                        .map(Arc::clone)
                        .collect::<Vec<_>>();
                    if group.len() > 0 {
                        groups.add_group(group)
                    }
                }
            }
        } else {
            for object in topo.objects_at_depth(depth as u32).iter() {
                let cpu_set = object.cpuset();
                match cpu_set {
                    Some(cpu_set) => {
                        let group = cpu_set
                            .into_iter()
                            .filter(|x| allow.is_set(*x))
                            .flat_map(|x| ALL_CORES.get(x as usize))
                            .map(Arc::clone)
                            .collect::<Vec<_>>();
                        if group.len() > 0 {
                            groups.add_group(group)
                        }
                    }
                    None => {}
                }
            }
        }
        groups
    }
}