From 42c409c4d7c661ead9794c54811ce5fadf0ae8e7 Mon Sep 17 00:00:00 2001 From: Dylan Reid Date: Thu, 6 Dec 2018 22:53:39 +0000 Subject: [PATCH] sys_util: Add ability to set real time thread priority Add the minimal amount of functionality needed for audio threads that need to run with real time priority. Change-Id: I7052e0f2ba6b9179229fc4568b332952ee32f076 Signed-off-by: Dylan Reid Reviewed-on: https://chromium-review.googlesource.com/1366542 Commit-Ready: ChromeOS CL Exonerator Bot Reviewed-by: David Tolnay --- sys_util/src/lib.rs | 2 ++ sys_util/src/priority.rs | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 sys_util/src/priority.rs diff --git a/sys_util/src/lib.rs b/sys_util/src/lib.rs index 0172458e79..38fa81fc23 100644 --- a/sys_util/src/lib.rs +++ b/sys_util/src/lib.rs @@ -28,6 +28,7 @@ mod guest_memory; mod mmap; mod passwd; mod poll; +mod priority; mod seek_hole; mod shm; pub mod signal; @@ -51,6 +52,7 @@ pub use mmap::*; pub use passwd::*; pub use poll::*; pub use poll_token_derive::*; +pub use priority::*; pub use shm::*; pub use signal::*; pub use signalfd::*; diff --git a/sys_util/src/priority.rs b/sys_util/src/priority.rs new file mode 100644 index 0000000000..f65b9e02a6 --- /dev/null +++ b/sys_util/src/priority.rs @@ -0,0 +1,38 @@ +// Copyright 2018 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use {errno_result, Result}; + +/// Enables real time thread priorities in the current thread up to `limit`. +pub fn set_rt_prio_limit(limit: u64) -> Result<()> { + let rt_limit_arg = libc::rlimit { + rlim_cur: limit as libc::rlim_t, + rlim_max: limit as libc::rlim_t, + }; + // Safe because the kernel doesn't modify memory that is accessible to the process here. + let res = unsafe { libc::setrlimit(libc::RLIMIT_RTPRIO, &rt_limit_arg) }; + + if res != 0 { + errno_result() + } else { + Ok(()) + } +} + +/// Sets the current thread to be scheduled using the round robin real time class with `priority`. +pub fn set_rt_round_robin(priority: i32) -> Result<()> { + let sched_param = libc::sched_param { + sched_priority: priority, + }; + + // Safe because the kernel doesn't modify memory that is accessible to the process here. + let res = + unsafe { libc::pthread_setschedparam(libc::pthread_self(), libc::SCHED_RR, &sched_param) }; + + if res != 0 { + errno_result() + } else { + Ok(()) + } +}