Debian Codegraph @

third_party/rust/audio_thread_priority/src/rt_linux.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 /* Widely copied from dbus-rs/dbus/examples/rtkit.rs */
6
7 extern crate dbus;
8 extern crate libc;
9
10 use std::cmp;
11 use std::convert::TryInto;
12 use std::error::Error;
13 use std::io::Error as OSError;
14
15 use dbus::{BusType, Connection, Message, MessageItem, Props};
16
17 use crate::AudioThreadPriorityError;
18
19 const DBUS_SOCKET_TIMEOUT: i32 = 10_000;
20 const RT_PRIO_DEFAULT: u32 = 10;
21 // This is different from libc::pid_t, which is 32 bits, and is defined in sys/types.h.
22 #[allow(non_camel_case_types)]
23 type kernel_pid_t = libc::c_long;
24
25 impl From<dbus::Error> for AudioThreadPriorityError {
26 fn from(error: dbus::Error) -> Self {
27 AudioThreadPriorityError::new(&format!(
28 "{}:{}",
29 error.name().unwrap_or("?"),
30 error.message().unwrap_or("?")
31 ))
32 }
33 }
34
35 impl From<Box<dyn Error>> for AudioThreadPriorityError {
36 fn from(error: Box<dyn Error>) -> Self {
37 AudioThreadPriorityError::new(&error.to_string())
38 }
39 }
40
41 #[repr(C)]
42 #[derive(Clone, Copy)]
43 pub struct RtPriorityThreadInfoInternal {
44 /// System-wise thread id, use to promote the thread via dbus.
45 thread_id: kernel_pid_t,
46 /// Process-local thread id, used to restore scheduler characteristics. This information is not
47 /// useful in another process, but is useful tied to the `thread_id`, when back into the first
48 /// process.
49 pthread_id: libc::pthread_t,
50 /// The PID of the process containing `thread_id` below.
51 pid: libc::pid_t,
52 /// ...
53 policy: libc::c_int,
54 }
55
56 impl RtPriorityThreadInfoInternal {
57 /// Serialize a RtPriorityThreadInfoInternal to a byte buffer.
58 pub fn serialize(&self) -> [u8; std::mem::size_of::<Self>()] {
59 unsafe { std::mem::transmute::<Self, [u8; std::mem::size_of::<Self>()]>(*self) }
60 }
61 /// Get an RtPriorityThreadInfoInternal from a byte buffer.
62 pub fn deserialize(bytes: [u8; std::mem::size_of::<Self>()]) -> Self {
63 unsafe { std::mem::transmute::<[u8; std::mem::size_of::<Self>()], Self>(bytes) }
64 }
65 }
66
67 impl PartialEq for RtPriorityThreadInfoInternal {
68 fn eq(&self, other: &Self) -> bool {
69 self.thread_id == other.thread_id && self.pthread_id == other.pthread_id
70 }
71 }
72
73 /*#[derive(Debug)]*/
74 pub struct RtPriorityHandleInternal {
75 thread_info: RtPriorityThreadInfoInternal,
76 }
77
78 fn item_as_i64(i: MessageItem) -> Result<i64, AudioThreadPriorityError> {
79 match i {
80 MessageItem::Int32(i) => Ok(i as i64),
81 MessageItem::Int64(i) => Ok(i),
82 _ => Err(AudioThreadPriorityError::new(&format!(
83 "Property is not integer ({:?})",
84 i
85 ))),
86 }
87 }
88
89 fn rtkit_set_realtime(thread: u64, pid: u64, prio: u32) -> Result<(), Box<dyn Error>> {
90 let m = if unsafe { libc::getpid() as u64 } == pid {
91 let mut m = Message::new_method_call(
92 "org.freedesktop.RealtimeKit1",
93 "/org/freedesktop/RealtimeKit1",
94 "org.freedesktop.RealtimeKit1",
95 "MakeThreadRealtime",
96 )?;
97 m.append_items(&[thread.into(), prio.into()]);
98 m
99 } else {
100 let mut m = Message::new_method_call(
101 "org.freedesktop.RealtimeKit1",
102 "/org/freedesktop/RealtimeKit1",
103 "org.freedesktop.RealtimeKit1",
104 "MakeThreadRealtimeWithPID",
105 )?;
106 m.append_items(&[pid.into(), thread.into(), prio.into()]);
107 m
108 };
109 let c = Connection::get_private(BusType::System)?;
110 c.send_with_reply_and_block(m, DBUS_SOCKET_TIMEOUT)?;
111 Ok(())
112 }
113
114 /// Returns the maximum priority, maximum real-time time slice, and the current real-time time
115 /// slice for this process.
116 fn get_limits() -> Result<(i64, u64, libc::rlimit), AudioThreadPriorityError> {
117 let c = Connection::get_private(BusType::System)?;
118
119 let p = Props::new(
120 &c,
121 "org.freedesktop.RealtimeKit1",
122 "/org/freedesktop/RealtimeKit1",
123 "org.freedesktop.RealtimeKit1",
124 DBUS_SOCKET_TIMEOUT,
125 );
126 let mut current_limit = libc::rlimit {
127 rlim_cur: 0,
128 rlim_max: 0,
129 };
130
131 let max_prio = item_as_i64(p.get("MaxRealtimePriority")?)?;
132 if max_prio < 0 {
133 return Err(AudioThreadPriorityError::new(
134 "invalid negative MaxRealtimePriority",
135 ));
136 }
137
138 let max_rttime = item_as_i64(p.get("RTTimeUSecMax")?)?;
139 if max_rttime < 0 {
140 return Err(AudioThreadPriorityError::new(
141 "invalid negative RTTimeUSecMax",
142 ));
143 }
144
145 if unsafe { libc::getrlimit(libc::RLIMIT_RTTIME, &mut current_limit) } < 0 {
146 return Err(AudioThreadPriorityError::new_with_inner(
147 "getrlimit",
148 Box::new(OSError::last_os_error()),
149 ));
150 }
151
152 Ok((max_prio, (max_rttime as u64), current_limit))
153 }
154
155 fn set_limits(request: u64, max: u64) -> Result<(), AudioThreadPriorityError> {
156 // Set a soft limit to the limit requested, to be able to handle going over the limit using
157 // SIGXCPU. Set the hard limit to the maximum slice to prevent getting SIGKILL.
158 #[allow(clippy::useless_conversion)]
159 let new_limit = libc::rlimit {
160 rlim_cur: request
161 .try_into()
162 .map_err(|_| AudioThreadPriorityError::new("setrlimit"))?,
163 rlim_max: max
164 .try_into()
165 .map_err(|_| AudioThreadPriorityError::new("setrlimit"))?,
166 };
167 if unsafe { libc::setrlimit(libc::RLIMIT_RTTIME, &new_limit) } < 0 {
168 return Err(AudioThreadPriorityError::new_with_inner(
169 "setrlimit",
170 Box::new(OSError::last_os_error()),
171 ));
172 }
173
174 Ok(())
175 }
176
177 pub fn promote_current_thread_to_real_time_internal(
178 audio_buffer_frames: u32,
179 audio_samplerate_hz: u32,
180 ) -> Result<RtPriorityHandleInternal, AudioThreadPriorityError> {
181 let thread_info = get_current_thread_info_internal()?;
182 promote_thread_to_real_time_internal(thread_info, audio_buffer_frames, audio_samplerate_hz)
183 }
184
185 pub fn demote_current_thread_from_real_time_internal(
186 rt_priority_handle: RtPriorityHandleInternal,
187 ) -> Result<(), AudioThreadPriorityError> {
188 assert!(unsafe { libc::pthread_self() } == rt_priority_handle.thread_info.pthread_id);
189
190 let param = unsafe { std::mem::zeroed::<libc::sched_param>() };
191
192 if unsafe {
193 libc::pthread_setschedparam(
194 rt_priority_handle.thread_info.pthread_id,
195 rt_priority_handle.thread_info.policy,
196 &param,
197 )
198 } < 0
199 {
200 return Err(AudioThreadPriorityError::new_with_inner(
201 "could not demote thread",
202 Box::new(OSError::last_os_error()),
203 ));
204 }
205 Ok(())
206 }
207
208 /// This can be called by sandboxed code, it only restores priority to what they were.
209 pub fn demote_thread_from_real_time_internal(
210 thread_info: RtPriorityThreadInfoInternal,
211 ) -> Result<(), AudioThreadPriorityError> {
212 let param = unsafe { std::mem::zeroed::<libc::sched_param>() };
213
214 // https://github.com/rust-lang/libc/issues/1511
215 const SCHED_RESET_ON_FORK: libc::c_int = 0x40000000;
216
217 if unsafe {
218 libc::pthread_setschedparam(
219 thread_info.pthread_id,
220 libc::SCHED_OTHER | SCHED_RESET_ON_FORK,
221 &param,
222 )
223 } < 0
224 {
225 return Err(AudioThreadPriorityError::new_with_inner(
226 "could not demote thread",
227 Box::new(OSError::last_os_error()),
228 ));
229 }
230 Ok(())
231 }
232
233 /// Get the current thread information, as an opaque struct, that can be serialized and sent
234 /// accross processes. This is enough to capture the current state of the scheduling policy, and
235 /// an identifier to have another thread promoted to real-time.
236 pub fn get_current_thread_info_internal(
237 ) -> Result<RtPriorityThreadInfoInternal, AudioThreadPriorityError> {
238 let thread_id = unsafe { libc::syscall(libc::SYS_gettid) };
239 let pthread_id = unsafe { libc::pthread_self() };
240 let mut param = unsafe { std::mem::zeroed::<libc::sched_param>() };
241 let mut policy = 0;
242
243 if unsafe { libc::pthread_getschedparam(pthread_id, &mut policy, &mut param) } < 0 {
244 return Err(AudioThreadPriorityError::new_with_inner(
245 "pthread_getschedparam",
246 Box::new(OSError::last_os_error()),
247 ));
248 }
249
250 let pid = unsafe { libc::getpid() };
251
252 Ok(RtPriorityThreadInfoInternal {
253 pid,
254 thread_id,
255 pthread_id,
256 policy,
257 })
258 }
259
260 /// This set the RLIMIT_RTTIME resource to something other than "unlimited". It's necessary for the
261 /// rtkit request to succeed, and needs to hapen in the child. We can't get the real limit here,
262 /// because we don't have access to DBUS, so it is hardcoded to 200ms, which is the default in the
263 /// rtkit package.
264 pub fn set_real_time_hard_limit_internal(
265 audio_buffer_frames: u32,
266 audio_samplerate_hz: u32,
267 ) -> Result<(), AudioThreadPriorityError> {
268 let buffer_frames = if audio_buffer_frames > 0 {
269 audio_buffer_frames
270 } else {
271 // 50ms slice. This "ought to be enough for anybody".
272 audio_samplerate_hz / 20
273 };
274 let budget_us = buffer_frames as u64 * 1_000_000 / audio_samplerate_hz as u64;
275
276 // It's only necessary to set RLIMIT_RTTIME to something when in the child, skip it if it's a
277 // remoting call.
278 let (_, max_rttime, _) = get_limits()?;
279
280 // Only take what we need, or cap at the system limit, no further.
281 let rttime_request = cmp::min(budget_us, max_rttime);
282 set_limits(rttime_request, max_rttime)?;
283
284 Ok(())
285 }
286
287 /// Promote a thread (possibly in another process) identified by its tid, to real-time.
288 pub fn promote_thread_to_real_time_internal(
289 thread_info: RtPriorityThreadInfoInternal,
290 audio_buffer_frames: u32,
291 audio_samplerate_hz: u32,
292 ) -> Result<RtPriorityHandleInternal, AudioThreadPriorityError> {
293 let RtPriorityThreadInfoInternal { pid, thread_id, .. } = thread_info;
294
295 let handle = RtPriorityHandleInternal { thread_info };
296
297 set_real_time_hard_limit_internal(audio_buffer_frames, audio_samplerate_hz)?;
298
299 let r = rtkit_set_realtime(thread_id as u64, pid as u64, RT_PRIO_DEFAULT);
300
301 match r {
302 Ok(_) => Ok(handle),
303 Err(e) => {
304 let (_, _, limits) = get_limits()?;
305 if limits.rlim_cur != libc::RLIM_INFINITY
306 && unsafe { libc::setrlimit(libc::RLIMIT_RTTIME, &limits) } < 0
307 {
308 return Err(AudioThreadPriorityError::new_with_inner(
309 "setrlimit",
310 Box::new(OSError::last_os_error()),
311 ));
312 }
313 Err(AudioThreadPriorityError::new_with_inner(
314 "Thread promotion error",
315 e,
316 ))
317 }
318 }
319 }