using System.Runtime.InteropServices;
namespace CanCommon;
///
/// Batched transmit of one fixed frame via a single sendmmsg(2) syscall.
///
/// The per-frame write() path costs one syscall per frame; at ~8-9 k
/// frames/s that syscall overhead is what leaves small idle gaps on the bus.
/// Pushing N frames per syscall keeps the controller's tx FIFO full so the bus
/// stays closer to 100%.
///
/// All N messages point at the SAME 16-byte frame + the SAME iovec, so the only
/// per-batch cost is the mmsghdr array. Native buffers are allocated once and
/// reused for every ; nothing is allocated on the hot path.
///
public sealed class CanTxBatch : IDisposable
{
// struct mmsghdr { struct msghdr msg_hdr; unsigned int msg_len; } on 64-bit:
// msghdr is 56 bytes, + 4 (msg_len) + 4 pad = 64. Fields we set live in msghdr:
// msg_iov at offset 16 (pointer)
// msg_iovlen at offset 24 (size_t)
private const int MmsghdrSize = 64;
private const int OffMsgIov = 16;
private const int OffMsgIovlen = 24;
[DllImport("libc", SetLastError = true)]
private static extern int sendmmsg(int fd, nint msgvec, uint vlen, int flags);
private readonly int _fd;
private readonly int _count;
private nint _frame; // 16-byte can_frame
private nint _iov; // one struct iovec pointing at _frame
private nint _mmsg; // _count contiguous struct mmsghdr
public int Count => _count;
public int LastErrno { get; private set; }
internal CanTxBatch(int fd, byte[] frame16, int count)
{
if (fd < 0) throw new ArgumentException("channel not open", nameof(fd));
if (count < 1) throw new ArgumentOutOfRangeException(nameof(count));
if (frame16.Length < CanFrame.Size) throw new ArgumentException("frame too small", nameof(frame16));
_fd = fd;
_count = count;
_frame = Marshal.AllocHGlobal(CanFrame.Size);
Marshal.Copy(frame16, 0, _frame, CanFrame.Size);
// struct iovec { void *iov_base; size_t iov_len; }
_iov = Marshal.AllocHGlobal(nint.Size * 2);
Marshal.WriteIntPtr(_iov, 0, _frame);
Marshal.WriteIntPtr(_iov, nint.Size, CanFrame.Size);
_mmsg = Marshal.AllocHGlobal(MmsghdrSize * count);
for (long b = 0; b < (long)MmsghdrSize * count; b++)
Marshal.WriteByte(_mmsg, (int)b, 0); // zero name/control/flags/len
for (int k = 0; k < count; k++)
{
nint h = _mmsg + k * MmsghdrSize;
Marshal.WriteIntPtr(h, OffMsgIov, _iov); // msg_iov -> shared iovec
Marshal.WriteIntPtr(h, OffMsgIovlen, 1); // msg_iovlen = 1
}
}
///
/// Send the whole batch in one syscall.
/// Returns the number of frames the kernel accepted (0..Count), or -1 on
/// error with set (e.g. 100 ENETDOWN).
///
public int Send()
{
int ret = sendmmsg(_fd, _mmsg, (uint)_count, 0);
if (ret >= 0) { LastErrno = 0; return ret; }
LastErrno = Marshal.GetLastPInvokeError();
return -1;
}
public void Dispose()
{
if (_mmsg != 0) { Marshal.FreeHGlobal(_mmsg); _mmsg = 0; }
if (_iov != 0) { Marshal.FreeHGlobal(_iov); _iov = 0; }
if (_frame != 0) { Marshal.FreeHGlobal(_frame); _frame = 0; }
}
}