gokm/kernel
import "gokm/kernel"
Package kernel is a tiny set of bindings to Linux kernel facilities for Go code compiled with TinyGo into a kernel module. The C side lives in shim.c.
Index#
func AllocBytes(n int) []bytefunc Atomic() boolfunc CatchPanic[T ~int | ~int32 | ~int64](rc *T)func FailLoad(err error)func FreeBytes(b []byte)func LiveHandles() intfunc MakeBytes(n int) ([]byte, error)func MonotonicNanos() int64func OnExit(fn func())func Print(s string)func ToErrno(err error) int- type Errno
- type Handle
- type SpinLock
Functions#
func AllocBytes#
func AllocBytes(n int) []byte
AllocBytes allocates a zeroed n-byte buffer outside the Go heap. It returns nil if n <= 0 or the kernel is out of memory.
The buffer must only hold plain data, never Go pointers: the GC doesn’t scan it, so objects referenced only from inside it would be collected. Release it with FreeBytes. Don’t use the slice (or any slice of it) afterwards.
func Atomic#
func Atomic() bool
Atomic reports whether the calling code runs in atomic context (softirq, preemption disabled, a SpinLock held): there it must not block (no sync.Mutex, channels, time.Sleep, blocking kernel calls), and allocation can fail with an “out of memory” panic when the heap is full.
func CatchPanic#
func CatchPanic[T ~int | ~int32 | ~int64](rc *T)
CatchPanic turns a panic in the current function into an error result instead of a kernel BUG(). Use it directly with defer in functions the kernel calls:
func handler() (rc int) {
defer kernel.CatchPanic(&rc)
...
}
On panic it logs the panic value and sets *rc to -EIO (rc may be nil for functions without a result). Framework packages already do this around every callback into user code.
Taking &rc makes TinyGo allocate rc on the heap at every call. On hot paths, set the result first and pass nil, as a recovered panic returns the current value of rc:
func handler() (rc int) {
rc = -int(kernel.EIO)
defer kernel.CatchPanic[int](nil)
...
}
func FailLoad#
func FailLoad(err error)
FailLoad makes module loading fail with err once main returns (insmod reports the error). Undo anything main registered before failing: hooks registered with OnExit don’t run when loading fails. A nil err cancels a previous FailLoad.
func FreeBytes#
func FreeBytes(b []byte)
FreeBytes releases a buffer returned by AllocBytes. b must be the slice AllocBytes returned (or a reslice starting at the same address). Passing nil is a no-op.
func LiveHandles#
func LiveHandles() int
LiveHandles returns the number of handles not yet deleted (useful for leak checks at module exit).
func MakeBytes#
func MakeBytes(n int) ([]byte, error)
MakeBytes returns a zeroed, garbage-collected []byte of length n, or ENOMEM if the Go heap can’t hold it (after collecting garbage and growing up to heap_max). Unlike make, it never fails fatally.
func MonotonicNanos#
func MonotonicNanos() int64
MonotonicNanos returns ktime_get_ns().
func OnExit#
func OnExit(fn func())
OnExit registers fn to be called when the module is unloaded (rmmod). Several functions can be registered; they run in reverse order (like defer). Framework packages (gokm/fs, gokm/netdev, …) use this to unregister what’s still registered, so a hook registered after fs.Register runs before the filesystem is unregistered.
func Print#
func Print(s string)
Print writes s to the kernel log (printk, KERN_INFO). A trailing newline is not needed; each call produces one log line.
func ToErrno#
func ToErrno(err error) int
ToErrno converts err into a negative errno for returning to the kernel: nil is 0, an Errno (possibly wrapped, via Unwrap) is -errno, and any other error is -EIO.
Types#
type Errno#
type Errno int
Errno is a kernel error number (positive, like EINVAL). It implements error, so Go code can return it, and ToErrno converts any error back into the negative errno kernel callbacks return.
const (
EPERM Errno = 1
ENOENT Errno = 2
EINTR Errno = 4
EIO Errno = 5
ENXIO Errno = 6
E2BIG Errno = 7
EBADF Errno = 9
EAGAIN Errno = 11
ENOMEM Errno = 12
EACCES Errno = 13
EFAULT Errno = 14
EBUSY Errno = 16
EEXIST Errno = 17
EXDEV Errno = 18
ENODEV Errno = 19
ENOTDIR Errno = 20
EISDIR Errno = 21
EINVAL Errno = 22
ENFILE Errno = 23
EMFILE Errno = 24
ENOTTY Errno = 25
EFBIG Errno = 27
ENOSPC Errno = 28
ESPIPE Errno = 29
EROFS Errno = 30
EMLINK Errno = 31
ERANGE Errno = 34
ENAMETOOLONG Errno = 36
ENOSYS Errno = 38
ENOTEMPTY Errno = 39
ENODATA Errno = 61
EOVERFLOW Errno = 75
EOPNOTSUPP Errno = 95
EADDRNOTAVAIL Errno = 99
ETIMEDOUT Errno = 110
)
func (Errno) Error#
func (e Errno) Error() string
type Handle#
type Handle uintptr
Handle is an integer that refers to a Go value, for storing in kernel memory: private-data fields such as sb->s_fs_info, inode->i_private or file->private_data.
The garbage collector doesn’t scan kernel memory, so a Go pointer stored there would not keep its object alive, and the GC could free it while the kernel still uses it. A Handle keeps the value alive (it’s referenced from a table of GC roots) until Delete is called.
It works like cgo.Handle:
h := kernel.NewHandle(state) // store uintptr(h) in kernel memory
s := kernel.Handle(p).Value().(*State)
kernel.Handle(p).Delete() // when the kernel object goes away
Handles are never 0, so 0 can mean “no handle”. Value is lock-free, so it can be used in any context (including atomic ones); NewHandle and Delete take a mutex.
func NewHandle#
func NewHandle(v any) Handle
NewHandle returns a new handle for v.
func (Handle) Delete#
func (h Handle) Delete()
Delete releases h, letting the value be garbage collected once nothing else references it. Deleting an invalid handle panics.
func (Handle) Valid#
func (h Handle) Valid() bool
Valid reports whether h refers to a value.
func (Handle) Value#
func (h Handle) Value() any
Value returns the value h refers to. It panics if h is invalid or deleted.
type SpinLock#
type SpinLock struct {
// contains filtered or unexported fields
}
SpinLock is a mutual-exclusion lock usable from any context, including atomic ones (e.g. a netdev Driver with AtomicTransmit). It disables softirqs on the local CPU while held, so code holding it is in atomic context: keep critical sections short and never block in them.
Process-context-only code should use sync.Mutex instead.
func (*SpinLock) Lock#
func (l *SpinLock) Lock()
Lock acquires the lock, spinning while another CPU holds it.
func (*SpinLock) TryLock#
func (l *SpinLock) TryLock() bool
TryLock acquires the lock if it’s free.
func (*SpinLock) Unlock#
func (l *SpinLock) Unlock()
Unlock releases the lock.