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
use crate::error::{ErrorKind, Result};
use crate::runtime::linux_wrapper::CpuSet;
use std::default::Default;
use std::fs::File;
use std::io::Error as IoError;
use std::io::Read;
use std::path::Path;
#[derive(Clone)]
pub struct CpuAffinity {
affinity_list: Vec<u16>,
}
impl CpuAffinity {
pub fn from_slice(affinity_list: &[u16]) -> Self {
Self {
affinity_list: Vec::from(affinity_list),
}
}
pub fn from_file(path: &Path) -> Result<Self> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let affinity_list = contents
.lines()
.filter(|line| !line.starts_with('#'))
.take(1)
.flat_map(|line| line.split_whitespace())
.filter_map(|item| item.parse::<u16>().ok())
.collect();
Ok(Self { affinity_list })
}
pub fn thread_to_cpu(&self, tid: u16) -> Option<u16> {
let index: usize = tid.into();
self.affinity_list.get(index).map(|&tid| tid)
}
pub fn set_affinity(&self, tid: u16) -> Result<()> {
let core_id = self
.thread_to_cpu(tid)
.ok_or_else(|| ErrorKind::InvalidArgument("Thread ID is out-of-bounds".to_string()))?;
let mut cpu_set = CpuSet::new();
cpu_set.add(core_id);
unsafe {
if libc::sched_setaffinity(
0,
cpu_set.bytes(),
cpu_set.as_slice().as_ptr() as *const libc::cpu_set_t,
) == -1
{
Err(ErrorKind::Io(IoError::last_os_error()))?
}
}
Ok(())
}
pub fn len(&self) -> usize {
self.affinity_list.len()
}
pub fn get_cpu() -> Result<u16> {
unsafe {
match libc::sched_getcpu() {
-1 => Err(ErrorKind::Io(IoError::last_os_error()))?,
cpu_id => Ok(cpu_id as u16),
}
}
}
}
impl Default for CpuAffinity {
fn default() -> Self {
let mut cpu_set = CpuSet::new();
unsafe {
if libc::sched_getaffinity(
0,
cpu_set.bytes(),
cpu_set.as_mut_slice().as_mut_ptr() as *mut libc::cpu_set_t,
) == -1
{
Err(ErrorKind::Io(IoError::last_os_error()))
.expect("Couldn't get the list of available CPU affinities from the OS")
}
}
let affinity_list: Vec<_> = (0..cpu_set.max_id())
.filter(|&cpu_id| cpu_set.is_set(cpu_id))
.collect();
Self { affinity_list }
}
}