/**
 ** PosixIo.java - minimal libc file I/O for the CUAS RT 16-bit scene feeder.
 **
 ** Copyright (C) 2026 Elphel, Inc.
 **
 ** -----------------------------------------------------------------------------**
 **
 **  PosixIo.java is free software: you can redistribute it and/or modify
 **  it under the terms of the GNU General Public License as published by
 **  the Free Software Foundation, either version 3 of the License, or
 **  (at your option) any later version.
 **
 **  PosixIo.java is distributed in the hope that it will be useful,
 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 **  GNU General Public License for more details.
 **
 **  You should have received a copy of the GNU General Public License
 **  along with PosixIo.java.  If not, see <http://www.gnu.org/licenses/>.
 ** -----------------------------------------------------------------------------**
 **
 */
package com.elphel.imagej.cuas.rt;

import com.sun.jna.Native;
import com.sun.jna.Pointer;

/**
 * Direct-mapped libc calls for the T2 16-bit feeder: pread() straight into the
 * pinned u16 staging buffer (no Java heap copy - the kernel's read() IS the
 * pinned write), and posix_fadvise(DONTNEED) so every run's in-loop reads stay
 * honestly cold (the production feeder is a RAM-based dual-port SATA device
 * whose frames are always new - page-cache replay would fake the I/O cost).
 * Linux/glibc only, like the JNA tile-processor backend it feeds.
 * By Claude on 07/18/2026, from Andrey's T2 design.
 */
public final class PosixIo {
	public static final int O_RDONLY = 0;
	public static final int POSIX_FADV_DONTNEED = 4;

	public static native int  open(String path, int flags);
	public static native long pread(int fd, Pointer buf, long count, long offset);
	public static native int  close(int fd);
	public static native int  posix_fadvise(int fd, long offset, long len, int advice);

	private static boolean available = false;
	static {
		try {
			Native.register(PosixIo.class, "c");
			available = true;
		} catch (Throwable t) {
			System.out.println("PosixIo: libc direct mapping unavailable ("+t.getMessage()+
					") - the 16-bit feeder will fall back to heap reads");
		}
	}
	public static boolean isAvailable() { return available; }

	private PosixIo() {}
}
