40 lines
1.7 KiB
C#
40 lines
1.7 KiB
C#
using System.Runtime.InteropServices;
|
|
|
|
namespace CanCommon;
|
|
|
|
/// <summary>
|
|
/// Best-effort real-time scheduling for the calling thread (Linux only).
|
|
/// Putting the tx/rx thread on SCHED_FIFO stops the kernel from preempting it
|
|
/// between frames, which is what lets the CAN controller's tx FIFO stay full
|
|
/// and the bus stay saturated. Needs CAP_SYS_NICE (run under sudo or
|
|
/// <c>setcap cap_sys_nice+ep</c>); if that is missing we degrade gracefully.
|
|
/// </summary>
|
|
public static class RealtimeScheduler
|
|
{
|
|
private const int SCHED_FIFO = 1;
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct SchedParam { public int sched_priority; }
|
|
|
|
// glibc pthread_setschedparam returns the errno directly (0 == success);
|
|
// it does NOT set the global errno, so we read the return value.
|
|
[DllImport("libc")] private static extern nuint pthread_self();
|
|
[DllImport("libc")] private static extern int pthread_setschedparam(nuint thread, int policy, ref SchedParam param);
|
|
|
|
/// <summary>
|
|
/// Try to put the CURRENT thread on SCHED_FIFO at <paramref name="priority"/>.
|
|
/// Must be called from the thread you want to elevate.
|
|
/// </summary>
|
|
/// <returns><c>null</c> on success, otherwise a human-readable reason it failed.</returns>
|
|
public static string? TryEngage(int priority)
|
|
{
|
|
if (!OperatingSystem.IsLinux()) return "not Linux";
|
|
var p = new SchedParam { sched_priority = priority };
|
|
int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, ref p);
|
|
if (rc == 0) return null;
|
|
return rc == 1 /*EPERM*/
|
|
? "EPERM — need CAP_SYS_NICE (run under sudo or `setcap cap_sys_nice+ep <binary>`)"
|
|
: $"errno {rc}";
|
|
}
|
|
}
|