1use crate::{error::status, sys, Error, Result};
3use std::{ffi::c_void, marker::PhantomData, rc::Rc};
4
5#[derive(Clone, Copy, Debug)]
6#[repr(i32)]
7#[non_exhaustive]
8pub enum CpuQuery {
10 LogicalCount,
12 LittleCount,
14 BigCount,
16 PhysicalCount,
18 PhysicalLittleCount,
20 PhysicalBigCount,
22 L2Bytes,
24 L3Bytes,
26 Avx,
28 Fma,
30 Fma4,
32 Xop,
34 F16c,
36 Avx2,
38 AvxVnni,
40 AvxVnniInt8,
42 AvxVnniInt16,
44 AvxNeConvert,
46 Avx512,
48 Avx512Vnni,
50 Avx512Bf16,
52 Avx512Fp16,
54 ArmEdsp,
56 ArmNeon,
58 ArmVfpv4,
60 ArmFp16,
62 ArmCpuid,
64 ArmDotProduct,
66 ArmFp16Fma,
68 ArmBf16,
70 ArmI8mm,
72 ArmSve,
74 ArmSve2,
76 ArmSveBf16,
78 ArmSveI8mm,
80 ArmSveF32mm,
82}
83
84pub fn query(key: CpuQuery) -> i32 {
90 unsafe { sys::ncnn_rs_cpu_query(key as i32) }
91}
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
95pub struct ProcessorId {
96 pub group: u32,
98 pub index: u32,
100}
101
102pub fn supports_thread_affinity() -> bool {
104 unsafe { sys::ncnn_rs_os_affinity_supported() != 0 }
105}
106
107fn processors(current_thread: bool) -> Result<Vec<ProcessorId>> {
108 if !supports_thread_affinity() {
109 return Err(Error::Unsupported(
110 "exact processor identities and affinity",
111 ));
112 }
113 for _ in 0..3 {
114 let count =
115 unsafe { sys::ncnn_rs_os_processors(current_thread as i32, std::ptr::null_mut(), 0) };
116 if count == usize::MAX {
117 return Err(Error::Native(-1));
118 }
119 let mut ids = vec![0u64; count];
120 let actual = unsafe {
121 sys::ncnn_rs_os_processors(current_thread as i32, ids.as_mut_ptr(), ids.len())
122 };
123 if actual == usize::MAX {
124 return Err(Error::Native(-1));
125 }
126 if actual > ids.len() {
127 continue;
128 }
129 ids.truncate(actual);
130 return Ok(ids
131 .into_iter()
132 .map(|id| ProcessorId {
133 group: (id >> 32) as u32,
134 index: id as u32,
135 })
136 .collect());
137 }
138 Err(Error::invalid("CPU topology changed during enumeration"))
139}
140
141pub fn online_processors() -> Result<Vec<ProcessorId>> {
143 processors(false)
144}
145
146pub fn current_thread_affinity() -> Result<Vec<ProcessorId>> {
148 processors(true)
149}
150
151pub fn physical_core_count() -> Result<usize> {
153 let count = unsafe { sys::ncnn_rs_os_physical_count() };
154 if count < 0 {
155 return Err(Error::Native(count));
156 }
157 Ok(count as usize)
158}
159
160pub fn set_current_thread_affinity(processors: &[ProcessorId]) -> Result<()> {
163 if !supports_thread_affinity() {
164 return Err(Error::Unsupported("exact current-thread affinity"));
165 }
166 let ids: Vec<_> = processors
167 .iter()
168 .map(|id| ((id.group as u64) << 32) | id.index as u64)
169 .collect();
170 unsafe { status(sys::ncnn_rs_thread_affinity_set(ids.as_ptr(), ids.len())) }
171}
172
173pub struct CpuSet {
175 raw: *mut c_void,
176 _thread: PhantomData<Rc<()>>,
177}
178impl CpuSet {
179 pub fn capacity() -> usize {
181 unsafe { sys::ncnn_rs_cpuset_capacity() as usize }
182 }
183 pub fn for_powersave(mode: u8) -> Result<Self> {
185 let mask = Self::new()?;
186 unsafe {
187 status(sys::ncnn_rs_cpuset_affinity(mask.raw, mode as i32))?;
188 }
189 Ok(mask)
190 }
191 pub fn new() -> Result<Self> {
193 let raw = unsafe { sys::ncnn_rs_cpuset_create() };
194 if raw.is_null() {
195 return Err(Error::Native(-100));
196 }
197 Ok(Self {
198 raw,
199 _thread: PhantomData,
200 })
201 }
202 pub fn set(&mut self, cpu: usize, enabled: bool) -> Result<()> {
204 let cpu =
205 i32::try_from(cpu).map_err(|_| Error::invalid("CPU index exceeds native range"))?;
206 unsafe { status(sys::ncnn_rs_cpuset_update(self.raw, cpu, enabled as i32)) }
207 }
208 pub fn contains(&self, cpu: usize) -> Result<bool> {
210 let cpu =
211 i32::try_from(cpu).map_err(|_| Error::invalid("CPU index exceeds native range"))?;
212 let result = unsafe { sys::ncnn_rs_cpuset_contains(self.raw, cpu) };
213 if result < 0 {
214 return Err(Error::invalid("CPU index exceeds native mask capacity"));
215 }
216 Ok(result != 0)
217 }
218 pub fn count(&self) -> usize {
220 unsafe { sys::ncnn_rs_cpuset_count(self.raw) as usize }
221 }
222 pub unsafe fn apply(&self) -> Result<()> {
227 if !supports_thread_affinity() {
228 return Err(Error::Unsupported("exact native worker affinity"));
229 }
230 status(sys::ncnn_rs_cpuset_apply(self.raw))
231 }
232}
233impl Drop for CpuSet {
234 fn drop(&mut self) {
235 unsafe {
236 sys::ncnn_rs_cpuset_destroy(self.raw);
237 }
238 }
239}