| 1 | |
| 2 |
|
| 3 | |
| 4 | |
| 5 | |
| 6 |
|
| 7 | use crate::{bindings, device::Device, error::Result, prelude::ENODEV};
|
| 8 |
|
| 9 | |
| 10 | #[inline]
|
| 11 | pub fn nr_cpu_ids() -> u32 {
|
| 12 | #[cfg(any(NR_CPUS_1, CONFIG_FORCE_NR_CPUS))]
|
| 13 | {
|
| 14 | bindings::NR_CPUS
|
| 15 | }
|
| 16 |
|
| 17 | #[cfg(not(any(NR_CPUS_1, CONFIG_FORCE_NR_CPUS)))]
|
| 18 | |
| 19 | unsafe {
|
| 20 | bindings::nr_cpu_ids
|
| 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 | #[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
| 47 | pub struct CpuId(u32);
|
| 48 |
|
| 49 | impl CpuId {
|
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | #[inline]
|
| 56 | pub unsafe fn from_i32_unchecked(id: i32) -> Self {
|
| 57 | debug_assert!(id >= 0);
|
| 58 | debug_assert!((id as u32) < nr_cpu_ids());
|
| 59 |
|
| 60 | |
| 61 | Self(id as u32)
|
| 62 | }
|
| 63 |
|
| 64 | |
| 65 | pub fn from_i32(id: i32) -> Option<Self> {
|
| 66 | if id < 0 || id as u32 >= nr_cpu_ids() {
|
| 67 | None
|
| 68 | } else {
|
| 69 | |
| 70 | Some(Self(id as u32))
|
| 71 | }
|
| 72 | }
|
| 73 |
|
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | #[inline]
|
| 80 | pub unsafe fn from_u32_unchecked(id: u32) -> Self {
|
| 81 | debug_assert!(id < nr_cpu_ids());
|
| 82 |
|
| 83 | |
| 84 | debug_assert!(id <= i32::MAX as u32);
|
| 85 |
|
| 86 | |
| 87 | Self(id)
|
| 88 | }
|
| 89 |
|
| 90 | |
| 91 | pub fn from_u32(id: u32) -> Option<Self> {
|
| 92 | if id >= nr_cpu_ids() {
|
| 93 | None
|
| 94 | } else {
|
| 95 | |
| 96 | Some(Self(id))
|
| 97 | }
|
| 98 | }
|
| 99 |
|
| 100 | |
| 101 | #[inline]
|
| 102 | pub fn as_u32(&self) -> u32 {
|
| 103 | self.0
|
| 104 | }
|
| 105 |
|
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | #[inline]
|
| 113 | pub fn current() -> Self {
|
| 114 | |
| 115 | unsafe { Self::from_u32_unchecked(bindings::raw_smp_processor_id()) }
|
| 116 | }
|
| 117 | }
|
| 118 |
|
| 119 | impl From<CpuId> for u32 {
|
| 120 | fn from(id: CpuId) -> Self {
|
| 121 | id.as_u32()
|
| 122 | }
|
| 123 | }
|
| 124 |
|
| 125 | impl From<CpuId> for i32 {
|
| 126 | fn from(id: CpuId) -> Self {
|
| 127 | id.as_u32() as i32
|
| 128 | }
|
| 129 | }
|
| 130 |
|
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | pub unsafe fn from_cpu(cpu: CpuId) -> Result<&'static Device> {
|
| 143 | |
| 144 | let ptr = unsafe { bindings::get_cpu_device(u32::from(cpu)) };
|
| 145 | if ptr.is_null() {
|
| 146 | return Err(ENODEV);
|
| 147 | }
|
| 148 |
|
| 149 | |
| 150 | |
| 151 | Ok(unsafe { Device::from_raw(ptr) })
|
| 152 | }
|