Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 37 additions & 9 deletions btf.lua
Original file line number Diff line number Diff line change
Expand Up @@ -98,21 +98,30 @@ function types:integer(name, size, bits)
end

---
-- A function and the prototype under it. Parameters are named, as the kernel's BTF checker
-- expects of a prototype that names any of them.
-- @function luaebpf.btf.types:func
-- @tparam string name
-- @tparam integer linkage one of `btf.linkage`
-- A function prototype. Parameters are named, as the kernel's BTF checker expects of a prototype
-- that names any of them.
-- @function luaebpf.btf.types:proto
-- @tparam table signature `{result, params}`, the result's type id and a type id per parameter
-- @treturn integer the `FUNC` type id
function types:func(name, linkage, signature)
-- @treturn integer the `FUNC_PROTO` type id
function types:proto(signature)
local params = {}
for i, id in ipairs(signature.params) do
table.insert(params, string.pack(self.order .. "I4I4", self:string("a" .. i), id))
end
local proto = self:add(string.pack(self.order .. "I4I4I4", 0, typeinfo(KIND_FUNC_PROTO, #params), signature.result)
return self:add(string.pack(self.order .. "I4I4I4", 0, typeinfo(KIND_FUNC_PROTO, #params), signature.result)
.. table.concat(params))
return self:add(string.pack(self.order .. "I4I4I4", self:string(name), typeinfo(KIND_FUNC, linkage), proto))
end

---
-- A function and the prototype under it.
-- @function luaebpf.btf.types:func
-- @tparam string name
-- @tparam integer linkage one of `btf.linkage`
-- @tparam table signature `{result, params}`, the result's type id and a type id per parameter
-- @treturn integer the `FUNC` type id
function types:func(name, linkage, signature)
return self:add(string.pack(self.order .. "I4I4I4", self:string(name), typeinfo(KIND_FUNC, linkage),
self:proto(signature)))
end

---
Expand Down Expand Up @@ -153,6 +162,25 @@ function types:struct(name, members)
.. table.concat(fields)), size
end

---
-- A struct of `members`, each `{name, type, offset}` with `offset` a byte offset, of an explicit
-- `size`. Where `types:struct` lays its members one word apart, this takes a kernel struct's own
-- offsets and whole size, for a `.struct_ops` whose members libbpf matches to the kernel's by name.
-- @function luaebpf.btf.types:record
-- @tparam string name
-- @tparam table members
-- @tparam integer size in bytes
-- @treturn integer the `STRUCT` type id
function types:record(name, members, size)
local fields = {}
for _, member in ipairs(members) do
table.insert(fields, string.pack(self.order .. "I4I4I4", self:string(member.name), member.type,
member.offset * BYTE))
end
return self:add(string.pack(self.order .. "I4I4I4", self:string(name), typeinfo(KIND_STRUCT, #members), size)
.. table.concat(fields))
end

---
-- A variable of `id` allocated in a section.
-- @function luaebpf.btf.types:var
Expand Down
45 changes: 45 additions & 0 deletions doc/guide/08-luaebpf.md
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,51 @@ Each refusal reads `lunatik: <file>:<line>: <message>`.
| the map key -1 does not fit 'I4' | a key or a value outside its spec | a value its spec packs |
| module 'byteorder' not found | `require` of a C module | a Lua module under `/lib/modules/lua/`, or the directory `--scripts` names |

## Schedulers

A program file may declare a **scheduler** instead of a device program. A scheduler is a
`struct sched_ext_ops`, the kernel's `sched_ext` (`CONFIG_SCHED_CLASS_EXT`, Linux 6.12 and later)
registers as a unit: the functions it carries are its callbacks, each compiled to eBPF and run by
the kernel at a scheduling event, and its scalar fields configure it. `bpf.scx.scheduler` declares
one, and the object `lunatik bpf` writes carries a `.struct_ops` section rather than a program per
device hook.

This first slice is the minimal scheduler, a `name` and an `init` callback that takes no argument
and returns `0` to let it load:

```Lua
local scx = require("bpf.scx")

return scx.scheduler{
name = "minimal",
init = function() return 0 end,
}
```

```Shell
sudo lunatik bpf -o /usr/local/lib/bpf/luaebpf/minimal.bpf.o minimal.bpf.lua
sudo lunatik run minimal
```

A scheduler takes **no device**: the kernel attaches it to no interface, it registers its
`struct_ops` with `sched_ext` as a whole, and from then on it schedules every task. So `lunatik run`
takes no `--dev`, and one given a scheduler is refused, `minimal is a scheduler and takes no device`,
as a device program given no `--dev` is refused the missing one. The run registers the scheduler and
pins the link that holds it at `/sys/fs/bpf/lunatik/minimal/<name>-link`, the way it pins a device
program's link, so the scheduler stays registered once the command has exited; `lunatik stop minimal`
unregisters it and the kernel's default scheduler takes over again.

A scheduler names a kernel Lua script beside it as a device program does, `minimal.lua`, whose
runtime `lunatik run` starts before it registers the scheduler, for a callback that
[calls into it](#calls-into-a-kernel-lua-runtime); the minimal scheduler names none, so no runtime
starts and `lunatik list` does not name it.

`lunatik bpf` reads the kernel's `sched_ext_ops` from its BTF, so it compiles a scheduler only where
that BTF carries the struct, a kernel built with `CONFIG_SCHED_CLASS_EXT`: elsewhere the file is
refused, `the kernel BTF has no struct 'sched_ext_ops'`. The members the object sets, `init` and
`name` here, libbpf matches to the kernel's struct by name, at the kernel's own byte offsets and
whole size, so the object carries only those and loads on any kernel of that layout.

## How a program file becomes a program

```
Expand Down
4 changes: 2 additions & 2 deletions emit/call.lua
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@ end

local function returnvalue(f, pc, state, i)
local value = state[i]
if f.isprogram then
if f.isprogram and f.unit.verdict then
checkverdict(f, pc, value)
end
f.rettype = f.rettype | value.t
if f.drop ~= "verdict" then
f.code:alu(insn.alu.MOV, insn.reg.R0, frame.getreg(f, pc, state, i, insn.reg.R0))
if f.isprogram then
if f.isprogram and f.unit.verdict then
testverdict(f, pc, value)
end
end
Expand Down
17 changes: 11 additions & 6 deletions emit/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -265,27 +265,32 @@ end
---
-- Compiles one program: its function, and every function that function reaches.
-- @function luaebpf.emit.program
-- @tparam table program `{name, fn, default, error, drop, names, places, context, kfunc, actions}`
-- @tparam table program `{name, fn, default, error, drop, names, places, context, kfunc, actions,
-- verdict, structops}`, `verdict` false and `structops` true for a struct_ops callback, which
-- returns a plain value and takes no context argument
-- @treturn table the frames, the program's own first
-- @raise `a program takes one argument, the context`, and `<file>:<line>: <reason>` for every
-- construct the subset refuses
function emit.program(program)
local unit = {
functions = {}, order = {}, lowering = {}, names = program.names or {}, places = program.places,
default = program.default, error = program.error, drop = program.drop, context = program.context,
kfunc = program.kfunc, actions = program.actions,
kfunc = program.kfunc, actions = program.actions, verdict = program.verdict ~= false,
-- no lowering can require luaebpf.emit back; read here, after the body that may set them ran
maygoto = emit.maygoto, unaligned = emit.unaligned, bigendian = emit.bigendian,
-- read here, at each compile, so from the directory luaebpf.proto.scripts named for it
maxstack = proto.script("linux.bpf").max.STACK,
subprogram = subprogram,
}
local read = proto.read(program.fn)
if read.numparams > 1 then
error(string.format("%s:%d: a program takes one argument, the context",
(read.source:gsub("^@", "")), read.linedefined), 0)
local params = program.structops and {} or {CTX}
if read.numparams > #params then
error(string.format("%s:%d: %s",
(read.source:gsub("^@", "")), read.linedefined,
program.structops and "a scheduler callback takes no argument yet"
or "a program takes one argument, the context"), 0)
end
compile(unit, program.fn, read, program.name, {CTX}, true)
compile(unit, program.fn, read, program.name, params, true)
return unit.order
end

Expand Down
6 changes: 4 additions & 2 deletions init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ local function fromlib(name)
end
package.preload["bpf.vmlinux"] = fromlib

local maps = require("luaebpf.maps")
local programs = require("luaebpf.programs")
local maps = require("luaebpf.maps")
local structops = require("luaebpf.structops")
local programs = require("luaebpf.programs")
local proto = require("luaebpf.proto")
local emit = require("luaebpf.emit")
local writer = require("luaebpf.writer")
Expand Down Expand Up @@ -107,6 +108,7 @@ function luaebpf.compile(path, btffile, scripts)
local chunk = proto.load(path)
programs.reset()
maps.reset()
structops.reset()
vmlinux.open(btffile)
proto.scripts(scripts)
local host, cpath, kept = package.path, package.cpath, modnames()
Expand Down
66 changes: 66 additions & 0 deletions lib/bpf/scx.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
--
-- SPDX-FileCopyrightText: (c) 2026 Ashwani Kumar Kamal <ashwanikamal.im421@gmail.com>
-- SPDX-License-Identifier: MIT OR GPL-2.0-only
--

---
-- Declares a sched_ext scheduler in a program file.
--
-- A scheduler is a `struct sched_ext_ops` the kernel registers as a unit: the functions it carries
-- are its callbacks, each compiled to eBPF and run by the kernel at a scheduling event, and its
-- scalar fields configure it. `scheduler` takes those as a table and hands the callbacks to the
-- compiler; the object it writes carries a `.struct_ops` section libbpf makes a struct_ops map of,
-- which `lunatik run`, with no device, loads and registers with sched_ext through
-- `bpf_map__attach_struct_ops`, pinning the link that holds the scheduler until `lunatik stop`
-- unregisters it. libbpf matches each member the object sets to the kernel's `sched_ext_ops` by
-- name, so the object carries only the members the scheduler names, at the kernel's own byte
-- offsets and whole size.
--
-- This first slice takes `name`, the scheduler's name, and `init`, a callback of no arguments that
-- returns `0` to let the scheduler load. The scheduler loads on a kernel built with
-- `CONFIG_SCHED_CLASS_EXT` (6.12 and later).
-- @module bpf.scx
-- @usage
-- local scx = require("bpf.scx")
--
-- return scx.scheduler{
-- name = "minimal",
-- init = function() return 0 end,
-- }

local programs = require("luaebpf.programs")
local structops = require("luaebpf.structops")
local vmlinux = require("bpf.vmlinux")

-- the ops struct the kernel registers; its members' offsets and whole size shift between releases,
-- so the compiler reads them from the target kernel's BTF rather than carrying one release's numbers
local STRUCT <const> = "sched_ext_ops"

local scx = {}

---
-- Declares a scheduler.
-- @function bpf.scx.scheduler
-- @tparam table opts `name`, the scheduler's name, cut to the bytes `sched_ext_ops.name` holds;
-- `init`, a callback of no arguments returning an `s32`, `0` where the scheduler is to load; and
-- `license`, the license the object declares, `Dual MIT/GPL` where it names none
-- @treturn table the declared `init` program
-- @raise `scx.scheduler takes a Lua function`, or `<file>:<line>: a scheduler callback takes no
-- argument yet`, `the kernel BTF has no struct 'sched_ext_ops'` on a kernel without sched_ext, or
-- `a scheduler is declared twice`
function scx.scheduler(opts)
local ops = vmlinux.members(STRUCT)
local init = assert(ops.members.init, "the kernel's sched_ext_ops has no init member")
local field = assert(ops.members.name, "the kernel's sched_ext_ops has no name member")
local program = programs.declare("scx.scheduler", opts.init, {section = "struct_ops/init",
verdict = false, structops = true, license = opts.license})
local name = (opts.name or "scx"):sub(1, field.size - 1)
assert(structops.declare{name = name:gsub("[^%w_]", "_"), struct = STRUCT, size = ops.size, members = {
{name = "init", offset = init.offset, program = program, proto = {params = {}}},
{name = "name", offset = field.offset, bytes = name .. ("\0"):rep(field.size - #name)},
}}, "a scheduler is declared twice")
return program
end

return scx

56 changes: 56 additions & 0 deletions lib/bpf/vmlinux.lua
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ local TYPESIZE <const> = 12
local MEMBER <const> = 12
local BYTE <const> = 8
local WIDEST <const> = 8 -- bytes of the widest load
local POINTER <const> = 8 -- a pointer is a word on the 64-bit kernels struct_ops runs on
local NESTING <const> = 16 -- qualifiers a member's type may be wrapped in, so a cycle ends

-- uapi/linux/btf.h, BTF_KIND_*
local INT <const> = 1
local PTR <const> = 2
local ARRAY <const> = 3
local STRUCT <const> = 4
local UNION <const> = 5
Expand Down Expand Up @@ -275,5 +277,59 @@ function vmlinux.layout(what)
return {size = size, fields = fields, bitfields = bitfields}
end

-- the byte size of a member's type: a pointer a word, an array its element's size times its count,
-- an integer, struct, union or enum the size its record carries, read through the qualifiers a
-- declaration may wrap it in
local function memsize(self, id)
for _ = 1, NESTING do
local at = self.offsets[id]
if at == nil then
return nil
end
local _, info, size = string.unpack(self.order .. "I4I4I4", self.bytes, at)
local kind = (info >> 24) & 0x1f
if kind == PTR then
return POINTER
elseif kind == ARRAY then
local elem, _, nelems = string.unpack(self.order .. "I4I4I4", self.bytes, at + TYPESIZE)
local esize = memsize(self, elem)
return esize and esize * nelems
elseif qualifiers[kind] then
id = size
else
return size
end
end
return nil
end

---
-- The byte offset and size of every member of a kernel struct, by name, and the struct's whole
-- size. Where `layout` reports only the integer members a `struct` codec reads, this reports every
-- member -- a function pointer and an array among them -- for a `.struct_ops` the compiler lays out
-- at the kernel's own offsets, which shift between releases.
-- @function bpf.vmlinux.members
-- @tparam string what the struct's name, as `bpftool btf dump` prints it
-- @treturn table `{size = bytes, members = {<name> = {offset = bytes, size = bytes}, ...}}`
-- @raise `<path>: <reason>`, when the BTF file cannot be read, and `the kernel BTF has no struct
-- '<what>'`
function vmlinux.members(what)
local self = reader()
local id = self.structs[what]
if id == nil then
error(("the kernel BTF has no struct '%s'"):format(what), 0)
end
local at = self.offsets[id]
local _, info, size = string.unpack(self.order .. "I4I4I4", self.bytes, at)
local vlen, kflag = info & 0xffff, info >> 31
local found = {}
for i = 0, vlen - 1 do
local nameoff, typeid, offset = string.unpack(self.order .. "I4I4I4", self.bytes, at + TYPESIZE + i * MEMBER)
local bit = kflag == 1 and offset & 0xffffff or offset
found[name(self, nameoff)] = {offset = bit // BYTE, size = memsize(self, typeid)}
end
return {size = size, members = found}
end

return vmlinux

Loading
Loading