Skip to content

Commit 3ce79cd

Browse files
committed
cpumask: add a function like for_each_online_cpu
This commit add a function return a struct implementing Iterator trait. Thus, this struct can be used as an iterator that returns an online cpu index each time. Signed-off-by: Li Hongyu <[email protected]>
1 parent df9024b commit 3ce79cd

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

rust/kernel/cpumask.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Cpumask variables and related functions.
4+
//!
5+
//! C header: [`include/linux/cpumask.h`](../../../../include/linux/cpumask.h).
6+
7+
use crate::bindings;
8+
use core::iter::Iterator;
9+
10+
/// An online CPU index iterator.
11+
///
12+
/// This iterator has a similar abilitiy to the kernel's macro `for_each_online_cpu`.
13+
pub struct OnlineCpusIndexIter {
14+
index: i32,
15+
}
16+
17+
impl Iterator for OnlineCpusIndexIter {
18+
type Item = u32;
19+
20+
fn next(&mut self) -> Option<u32> {
21+
let next_cpu_id =
22+
unsafe { bindings::cpumask_next(self.index, &bindings::__cpu_online_mask) };
23+
// When [`bindings::cpumask_next`] can not find further CPUs set in the
24+
// [`bindings::__cpu_online_mask`], it returns a value >= [`bindings::nr_cpu_ids`].
25+
if next_cpu_id >= unsafe { bindings::nr_cpu_ids } {
26+
return None;
27+
}
28+
self.index = next_cpu_id as i32;
29+
Some(next_cpu_id)
30+
}
31+
}
32+
33+
/// Returns a [`OnlineCpusIndexIter`] that gives the online CPU indexes.
34+
///
35+
/// # Examples
36+
///
37+
/// ```
38+
/// # use kernel::prelude::*;
39+
/// # use kernel::cpumask::online_cpus;
40+
///
41+
/// fn example() {
42+
/// // This prints all the online cpu indexes.
43+
/// for cpu in online_cpus(){
44+
/// pr_info!("{}\n", cpu);
45+
/// }
46+
/// }
47+
/// ```
48+
pub fn online_cpus() -> OnlineCpusIndexIter {
49+
// Inital index is set to -1. Since [`bindings::cpumask_next`] return the next set bit in a
50+
// [`bindings::__cpu_online_mask`], the CPU index should begins from 0.
51+
OnlineCpusIndexIter { index: -1 }
52+
}

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ pub mod platform;
9494
mod types;
9595
pub mod user_ptr;
9696

97+
pub mod cpumask;
9798
#[doc(hidden)]
9899
pub use build_error::build_error;
99100

0 commit comments

Comments
 (0)