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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#![allow(dead_code)]
#[macro_use]
extern crate bitflags;
extern crate errno;
extern crate libc;
extern crate num;
mod ffi;
mod topology_object;
mod bitmap;
mod support;
pub use ffi::{ObjectType, TypeDepthError, TopologyFlag};
pub use bitmap::{CpuSet, NodeSet};
pub use support::{TopologySupport, TopologyDiscoverySupport, TopologyCpuBindSupport,
TopologyMemBindSupport};
use num::{ToPrimitive, FromPrimitive};
use errno::errno;
use libc::{pthread_t, pid_t};
pub use topology_object::{TopologyObject, TopologyObjectMemory};
pub struct Topology {
topo: *mut ffi::HwlocTopology,
support: *const TopologySupport,
}
unsafe impl Send for Topology {}
unsafe impl Sync for Topology {}
impl Topology {
pub fn new() -> Topology {
let mut topo: *mut ffi::HwlocTopology = std::ptr::null_mut();
unsafe {
ffi::hwloc_topology_init(&mut topo);
ffi::hwloc_topology_load(topo);
}
let support = unsafe { ffi::hwloc_topology_get_support(topo) };
Topology {
topo: topo,
support: support,
}
}
pub fn with_flags(flags: Vec<TopologyFlag>) -> Topology {
let mut topo: *mut ffi::HwlocTopology = std::ptr::null_mut();
let final_flag = flags.iter()
.map(|f| f.to_u64().unwrap())
.fold(0, |out, current| out | current);
unsafe {
ffi::hwloc_topology_init(&mut topo);
ffi::hwloc_topology_set_flags(topo, final_flag);
ffi::hwloc_topology_load(topo);
}
let support = unsafe { ffi::hwloc_topology_get_support(topo) };
Topology {
topo: topo,
support: support,
}
}
pub fn support(&self) -> &TopologySupport {
unsafe { &*self.support }
}
pub fn flags(&self) -> Vec<TopologyFlag> {
let stored_flags = unsafe { ffi::hwloc_topology_get_flags(self.topo) };
(0..64)
.map(|x| (1 << x) & stored_flags)
.filter(|&x| x > 0)
.map(|x| TopologyFlag::from_u64(x).unwrap())
.collect::<Vec<TopologyFlag>>()
}
pub fn depth(&self) -> u32 {
unsafe { ffi::hwloc_topology_get_depth(self.topo) }
}
pub fn depth_for_type(&self, object_type: &ObjectType) -> Result<u32, TypeDepthError> {
let result = unsafe { ffi::hwloc_get_type_depth(self.topo, object_type.clone()) };
match result {
result if result >= 0 => Ok(result as u32),
-1 => Err(TypeDepthError::TypeDepthUnknown),
-2 => Err(TypeDepthError::TypeDepthMultiple),
-3 => Err(TypeDepthError::TypeDepthBridge),
-4 => Err(TypeDepthError::TypeDepthPCIDevice),
-5 => Err(TypeDepthError::TypeDepthOSDevice),
_ => Err(TypeDepthError::UnkownTypeDepthError),
}
}
pub fn depth_or_below_for_type(&self, object_type: &ObjectType) -> Result<u32, TypeDepthError> {
match self.depth_for_type(object_type) {
Ok(d) => Ok(d),
Err(TypeDepthError::TypeDepthUnknown) => {
let pu_depth = self.depth_for_type(&ObjectType::PU).unwrap();
for i in (0..pu_depth).rev() {
if self.type_at_depth(i) < *object_type {
return Ok(i + 1);
}
}
Err(TypeDepthError::TypeDepthUnknown)
}
Err(e) => Err(e),
}
}
pub fn depth_or_above_for_type(&self, object_type: &ObjectType) -> Result<u32, TypeDepthError> {
match self.depth_for_type(object_type) {
Ok(d) => Ok(d),
Err(TypeDepthError::TypeDepthUnknown) => {
let pu_depth = self.depth_for_type(&ObjectType::PU).unwrap();
for i in 0..pu_depth {
if self.type_at_depth(i) > *object_type {
return Ok(i - 1);
}
}
Err(TypeDepthError::TypeDepthUnknown)
}
Err(e) => Err(e),
}
}
pub fn type_at_depth(&self, depth: u32) -> ObjectType {
if depth > self.depth() - 1 {
panic!("The provided depth {} is out of bounds.", depth);
}
unsafe { ffi::hwloc_get_depth_type(self.topo, depth) }
}
pub fn size_at_depth(&self, depth: u32) -> u32 {
if depth > self.depth() - 1 {
panic!("The provided depth {} is out of bounds.", depth);
}
unsafe { ffi::hwloc_get_nbobjs_by_depth(self.topo, depth) }
}
pub fn object_at_root(&self) -> &TopologyObject {
self.objects_at_depth(0).first().unwrap()
}
pub fn type_at_root(&self) -> ObjectType {
self.type_at_depth(0)
}
pub fn objects_with_type(&self,
object_type: &ObjectType)
-> Result<Vec<&TopologyObject>, TypeDepthError> {
match self.depth_for_type(object_type) {
Ok(depth) => Ok(self.objects_at_depth(depth)),
Err(TypeDepthError::TypeDepthOSDevice) => {
Ok(self.objects_at_depth(TypeDepthError::TypeDepthOSDevice as u32))
}
Err(TypeDepthError::TypeDepthPCIDevice) => {
Ok(self.objects_at_depth(TypeDepthError::TypeDepthPCIDevice as u32))
}
Err(TypeDepthError::TypeDepthBridge) => {
Ok(self.objects_at_depth(TypeDepthError::TypeDepthBridge as u32))
}
Err(e) => Err(e),
}
}
pub fn objects_at_depth(&self, depth: u32) -> Vec<&TopologyObject> {
let size = self.size_at_depth(depth);
(0..size)
.map(|idx| unsafe { &*ffi::hwloc_get_obj_by_depth(self.topo, depth, idx) })
.collect::<Vec<&TopologyObject>>()
}
pub fn set_cpubinding(&mut self, set: CpuSet, flags: CpuBindFlags) -> Result<(), CpuBindError> {
let result = unsafe {
ffi::hwloc_set_cpubind(self.topo, set.as_ptr(), flags.bits())
};
match result {
r if r < 0 => {
let e = errno();
Err(CpuBindError::Generic(e.0 as i32, format!("{}", e)))
}
_ => Ok(()),
}
}
pub fn set_cpubinding_for_pid(&mut self, pid: pid_t, set: CpuSet, flags: CpuBindFlags) -> Result<(), CpuBindError> {
let result = unsafe {
ffi::hwloc_set_proc_cpubind(self.topo, pid, set.as_ptr(), flags.bits())
};
match result {
r if r < 0 => {
let e = errno();
Err(CpuBindError::Generic(e.0 as i32, format!("{}", e)))
}
_ => Ok(()),
}
}
pub fn set_cpubinding_for_thread(&mut self, tid: pthread_t, set: CpuSet, flags: CpuBindFlags) -> Result<(), CpuBindError> {
let result = unsafe {
ffi::hwloc_set_thread_cpubind(self.topo, tid, set.as_ptr(), flags.bits())
};
match result {
r if r < 0 => {
let e = errno();
Err(CpuBindError::Generic(e.0 as i32, format!("{}", e)))
}
_ => Ok(()),
}
}
pub fn get_cpubinding_for_thread(&self, tid: pthread_t, flags: CpuBindFlags) -> Option<CpuSet> {
let raw_set = unsafe { ffi::hwloc_bitmap_alloc() };
let res = unsafe { ffi::hwloc_get_thread_cpubind(self.topo, tid, raw_set, flags.bits()) };
if res >= 0 {
Some(CpuSet::from_raw(raw_set, true))
} else {
None
}
}
pub fn get_cpubinding_for_pid(&self, pid: pid_t, flags: CpuBindFlags) -> Option<CpuSet> {
let raw_set = unsafe { ffi::hwloc_bitmap_alloc() };
let res = unsafe { ffi::hwloc_get_proc_cpubind(self.topo, pid, raw_set, flags.bits()) };
if res >= 0 {
Some(CpuSet::from_raw(raw_set, true))
} else {
None
}
}
pub fn get_cpubinding(&self, flags: CpuBindFlags) -> Option<CpuSet> {
let raw_set = unsafe { ffi::hwloc_bitmap_alloc() };
let res = unsafe { ffi::hwloc_get_cpubind(self.topo, raw_set, flags.bits()) };
if res >= 0 {
Some(CpuSet::from_raw(raw_set, true))
} else {
None
}
}
pub fn get_last_cpu_location(&self, flags: CpuBindFlags) -> Option<CpuSet> {
let raw_set = unsafe { ffi::hwloc_bitmap_alloc() };
let res = unsafe {
ffi::hwloc_get_last_cpu_location(self.topo, raw_set, flags.bits())
};
if res >= 0 {
Some(CpuSet::from_raw(raw_set, true))
} else {
None
}
}
}
impl Drop for Topology {
fn drop(&mut self) {
unsafe { ffi::hwloc_topology_destroy(self.topo) }
}
}
#[derive(Debug)]
pub enum CpuBindError {
Generic(i32, String),
}
bitflags! {
flags CpuBindFlags: i32 {
const CPUBIND_PROCESS = (1<<0),
const CPUBIND_THREAD = (1<<1),
const CPUBIND_STRICT = (1<<2),
const CPUBIND_NO_MEMBIND = (1<<3),
}
}
bitflags! {
flags MemBindPolicy: i32 {
const MEMBIND_DEFAULT = 0,
const MEMBIND_FIRSTTOUCH = 1,
const MEMBIND_BIND = 2,
const MEMBIND_INTERLEAVE = 3,
const MEMBIND_REPLICATE = 4,
const MEMBIND_NEXTTOUCH = 5,
const MEMBIND_MIXED = -1,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_set_and_get_flags() {
let topo = Topology::with_flags(vec![TopologyFlag::WholeSystem, TopologyFlag::IoBridges]);
assert_eq!(vec![TopologyFlag::WholeSystem, TopologyFlag::IoBridges],
topo.flags());
}
#[test]
fn should_get_topology_depth() {
let topo = Topology::new();
assert!(topo.depth() > 0);
}
#[test]
fn should_match_types_and_their_depth() {
let topo = Topology::new();
let pu_depth = topo.depth_for_type(&ObjectType::PU).ok().unwrap();
assert!(pu_depth > 0);
assert_eq!(ObjectType::PU, topo.type_at_depth(pu_depth));
}
#[test]
fn should_get_nbobjs_by_depth() {
let topo = Topology::new();
assert!(topo.size_at_depth(1) > 0);
}
#[test]
fn should_get_root_object() {
let topo = Topology::new();
let root_obj = topo.object_at_root();
assert_eq!(ObjectType::Machine, root_obj.object_type());
assert!(root_obj.memory().total_memory() > 0);
assert_eq!(0, root_obj.depth());
assert_eq!(0, root_obj.logical_index());
assert!(root_obj.first_child().is_some());
assert!(root_obj.last_child().is_some());
}
#[test]
#[cfg(target_os="linux")]
fn should_support_cpu_binding_on_linux() {
let topo = Topology::new();
assert!(topo.support().cpu().set_current_process());
assert!(topo.support().cpu().set_current_thread());
}
#[test]
#[cfg(target_os="macos")]
fn should_not_support_cpu_binding_on_macos() {
let topo = Topology::new();
assert_eq!(false, topo.support().cpu().set_current_process());
assert_eq!(false, topo.support().cpu().set_current_thread());
}
#[test]
fn should_produce_cpubind_bitflags() {
assert_eq!("1", format!("{:b}", CPUBIND_PROCESS.bits()));
assert_eq!("10", format!("{:b}", CPUBIND_THREAD.bits()));
assert_eq!("100", format!("{:b}", CPUBIND_STRICT.bits()));
assert_eq!("101", format!("{:b}", (CPUBIND_STRICT | CPUBIND_PROCESS).bits()));
}
}