• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Google Inc. All rights reserved
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files
6  * (the "Software"), to deal in the Software without restriction,
7  * including without limitation the rights to use, copy, modify, merge,
8  * publish, distribute, sublicense, and/or sell copies of the Software,
9  * and to permit persons to whom the Software is furnished to do so,
10  * subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22  */
23 
24 use alloc::boxed::Box;
25 use core::ffi::c_int;
26 use core::ffi::c_void;
27 use core::ffi::CStr;
28 use core::fmt;
29 use core::fmt::Display;
30 use core::fmt::Formatter;
31 use core::ops::Add;
32 use core::ops::Sub;
33 use core::ptr::NonNull;
34 
35 use crate::Error;
36 
37 use crate::sys::thread_create;
38 use crate::sys::thread_resume;
39 use crate::sys::thread_t;
40 use crate::sys::DEFAULT_PRIORITY;
41 use crate::sys::DPC_PRIORITY;
42 use crate::sys::HIGHEST_PRIORITY;
43 use crate::sys::HIGH_PRIORITY;
44 use crate::sys::IDLE_PRIORITY;
45 use crate::sys::LOWEST_PRIORITY;
46 use crate::sys::LOW_PRIORITY;
47 use crate::sys::NUM_PRIORITIES;
48 
49 use crate::sys::DEFAULT_STACK_SIZE;
50 
51 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
52 pub struct Priority(c_int);
53 
54 impl Priority {
55     pub const NUM: usize = NUM_PRIORITIES as _;
56 
57     pub const LOWEST: Self = Self(LOWEST_PRIORITY as _);
58     pub const HIGHEST: Self = Self(HIGHEST_PRIORITY as _);
59     pub const DPC: Self = Self(DPC_PRIORITY as _);
60     pub const IDLE: Self = Self(IDLE_PRIORITY as _);
61     pub const LOW: Self = Self(LOW_PRIORITY as _);
62     pub const DEFAULT: Self = Self(DEFAULT_PRIORITY as _);
63     pub const HIGH: Self = Self(HIGH_PRIORITY as _);
64 }
65 
66 impl Default for Priority {
default() -> Self67     fn default() -> Self {
68         Self::DEFAULT
69     }
70 }
71 
72 #[derive(Debug)]
73 pub enum PriorityError {
74     TooLow(c_int),
75     TooHigh(c_int),
76 }
77 
78 impl Display for PriorityError {
fmt(&self, f: &mut Formatter) -> fmt::Result79     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
80         match self {
81             PriorityError::TooLow(val) => write!(f, "{val} < {}", Priority::LOWEST.0),
82             PriorityError::TooHigh(val) => write!(f, "{val} > {}", Priority::HIGHEST.0),
83         }
84     }
85 }
86 
87 impl TryFrom<c_int> for Priority {
88     type Error = PriorityError;
89 
try_from(value: c_int) -> Result<Self, Self::Error>90     fn try_from(value: c_int) -> Result<Self, Self::Error> {
91         if value < Priority::LOWEST.0 {
92             Err(PriorityError::TooLow(value))
93         } else if value > Priority::HIGHEST.0 {
94             Err(PriorityError::TooHigh(value))
95         } else {
96             Ok(Priority(value))
97         }
98     }
99 }
100 
101 impl Add<c_int> for Priority {
102     type Output = Self;
103 
add(self, other: c_int) -> Self104     fn add(self, other: c_int) -> Self {
105         match self.0.checked_add(other).map(Self::try_from) {
106             None => panic!("priority overflow"),
107             Some(Err(reason)) => panic!("priority out of range: {reason}"),
108             Some(Ok(priority)) => priority,
109         }
110     }
111 }
112 
113 impl Sub<c_int> for Priority {
114     type Output = Self;
115 
sub(self, other: c_int) -> Self116     fn sub(self, other: c_int) -> Self {
117         match self.0.checked_sub(other).map(Self::try_from) {
118             None => panic!("priority overflow"),
119             Some(Err(reason)) => panic!("priority out of range: {reason}"),
120             Some(Ok(priority)) => priority,
121         }
122     }
123 }
124 
125 pub struct JoinHandle {
126     _thread: NonNull<thread_t>,
127 }
128 
129 #[derive(Debug)]
130 pub struct Builder<'a> {
131     pub name: Option<&'a CStr>,
132     pub priority: Priority,
133     pub stack_size: usize,
134 }
135 
136 impl<'a> Default for Builder<'a> {
default() -> Self137     fn default() -> Self {
138         Self::new()
139     }
140 }
141 
142 impl<'a> Builder<'a> {
new() -> Self143     pub const fn new() -> Self {
144         Self { name: None, priority: Priority::DEFAULT, stack_size: DEFAULT_STACK_SIZE as _ }
145     }
146 
name(mut self, name: &'a CStr) -> Self147     pub fn name(mut self, name: &'a CStr) -> Self {
148         self.name = Some(name);
149         self
150     }
151 
priority(mut self, priority: Priority) -> Self152     pub fn priority(mut self, priority: Priority) -> Self {
153         self.priority = priority;
154         self
155     }
156 
stack_size(mut self, stack_size: usize) -> Self157     pub fn stack_size(mut self, stack_size: usize) -> Self {
158         self.stack_size = stack_size;
159         self
160     }
161 
spawn<F>(self, f: F) -> Result<JoinHandle, i32> where F: FnOnce() -> c_int + Send + 'static,162     pub fn spawn<F>(self, f: F) -> Result<JoinHandle, i32>
163     where
164         F: FnOnce() -> c_int + Send + 'static,
165     {
166         let name = self.name.unwrap_or(c"thread");
167         // We need a pointer to f that lasts until `thread_entry_wrapper`
168         // gets called. `thread_resume` does not wait for the new
169         // thread to run. Thus, passing the address of a local
170         // wouldn't live long enough so we heap allocate instead.
171         let f = Box::new(f);
172 
173         extern "C" fn thread_entry_wrapper<F>(arg: *mut c_void) -> c_int
174         where
175             F: FnOnce() -> c_int + Send + 'static,
176         {
177             // SAFETY:
178             // We passed in a `Box<F>`.
179             // `thread_entry_wrapper` is called exactly once per thread.
180             let f = unsafe { Box::<F>::from_raw(arg as _) };
181             f()
182         }
183 
184         // SAFETY:
185         // `name` outlives the call to `thread_create` during which the
186         // string is copied into the newly created thread structure.
187         //
188         // `arg`: The lifetime of `Box<F>` lasts until the end of the
189         // call to `thread_entry_wrapper`. The trusty kernel will pass `arg`
190         // to `thread_entry_wrapper` exactly once per thread.
191         let thread = unsafe {
192             thread_create(
193                 name.as_ptr(),
194                 Some(thread_entry_wrapper::<F>),
195                 Box::<F>::into_raw(f) as *mut c_void,
196                 self.priority.0,
197                 self.stack_size,
198             )
199         };
200         let thread = NonNull::new(thread).ok_or::<i32>(Error::ERR_GENERIC.into())?;
201         // SAFETY: `thread` is non-null, so `thread_create` initialized it properly.
202         let status = unsafe { thread_resume(thread.as_ptr()) };
203         if status == Error::NO_ERROR.into() {
204             Ok(JoinHandle { _thread: thread })
205         } else {
206             Err(status)
207         }
208     }
209 }
210 
spawn<F>(f: F) -> Result<JoinHandle, i32> where F: FnOnce() -> c_int + Send + 'static,211 pub fn spawn<F>(f: F) -> Result<JoinHandle, i32>
212 where
213     F: FnOnce() -> c_int + Send + 'static,
214 {
215     Builder::new().spawn(f)
216 }
217