|
| 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 | +} |
0 commit comments