using System.Runtime.InteropServices;
namespace CanCommon;
///
/// 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
/// setcap cap_sys_nice+ep); if that is missing we degrade gracefully.
///
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);
///
/// Try to put the CURRENT thread on SCHED_FIFO at .
/// Must be called from the thread you want to elevate.
///
/// null on success, otherwise a human-readable reason it failed.
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 `)"
: $"errno {rc}";
}
}