ublk: kernel ublk server (io_uring command queues) and provider target

- uapi.go: the ublk_cmd.h ABI (ctrl/dev-info/io-desc/io-cmd/params
  structs, ioctl-encoded command numbers), checked byte for byte by
  uapi_test.go against the kernel header.
- uring_linux.go: a minimal io_uring (SQE128 for URING_CMD), NOP-tested.
- device_linux.go: ADD_DEV (UBLK_F_CMD_IOCTL_ENCODE), SET_PARAMS (basic:
  block size, volatile cache + FUA so the block layer sends FLUSH/FUA),
  per-queue descriptor mmap and FETCH for every tag, START_DEV; each
  queue is served on one locked OS thread (ublk binds a queue to the task
  that fetched it) through the request dispatch. Close: STOP_DEV, wait
  for the queues, DEL_DEV. A device left at the same id by a dead server
  is deleted first; without UBLK_F_USER_RECOVERY a server crash fails
  I/O (documented fail-closed limit).
- target.go: TargetConfig/Target opening the volume backend from a
  frontend.Provider on first I/O, like the NVMe-RDMA target.
- device_unsupported.go: Start refuses off Linux.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-15 14:08:39 -08:00
1 parent 9daf0c63e0
commit 8ecbc96f8b
9 files changed
+1064

No files matched your search

@@ -0,0 +1,64 @@
package ublk
import (
"errors"
"fmt"
"math/bits"
)
// Config describes one ublk device.
type Config struct {
Backend Backend
// Size is the device size in bytes, a multiple of BlockSize.
Size uint64
// BlockSize is the logical block size: a power of two, 512..4096.
BlockSize uint32
// DevID selects /dev/ublkbN; negative lets the kernel choose.
DevID int
// Queues is the number of hardware queues (one server thread each).
Queues int
// QueueDepth is the number of in-flight requests per queue.
QueueDepth int
// MaxIOBytes is the largest single request, a multiple of 4096.
MaxIOBytes uint32
}
// Defaults for the optional Config fields.
const (
DefaultQueues = 1
DefaultQueueDepth = 64
DefaultMaxIOBytes = 512 << 10
)
func (c *Config) applyDefaults() {
if c.Queues == 0 {
c.Queues = DefaultQueues
}
if c.QueueDepth == 0 {
c.QueueDepth = DefaultQueueDepth
}
if c.MaxIOBytes == 0 {
c.MaxIOBytes = DefaultMaxIOBytes
}
}
func (c *Config) validate() error {
c.applyDefaults()
switch {
case c.Backend == nil:
return errors.New("ublk: backend required")
case c.BlockSize < 512 || c.BlockSize > 4096 || bits.OnesCount32(c.BlockSize) != 1:
return fmt.Errorf("ublk: block size %d must be a power of two in 512..4096", c.BlockSize)
case c.Size == 0 || c.Size%uint64(c.BlockSize) != 0:
return fmt.Errorf("ublk: size %d must be a non-zero multiple of the block size %d", c.Size, c.BlockSize)
case c.Queues < 1 || c.Queues > 64:
return fmt.Errorf("ublk: %d queues, want 1..64", c.Queues)
case c.QueueDepth < 1 || c.QueueDepth > maxQueueDepth:
return fmt.Errorf("ublk: queue depth %d, want 1..%d", c.QueueDepth, maxQueueDepth)
case c.MaxIOBytes < 4096 || c.MaxIOBytes%4096 != 0 || c.MaxIOBytes > maxIOBufBytesLimit:
return fmt.Errorf("ublk: max IO %d bytes, want a multiple of 4096 up to %d", c.MaxIOBytes, maxIOBufBytesLimit)
case c.DevID > 1<<20:
return fmt.Errorf("ublk: device id %d out of range", c.DevID)
}
return nil
}
@@ -0,0 +1,319 @@
//go:build linux
package ublk
import (
"context"
"errors"
"fmt"
"math/bits"
"os"
"runtime"
"strconv"
"sync"
"time"
"unsafe"
"golang.org/x/sys/unix"
)
// Implemented reports whether this platform has the ublk server.
func Implemented() bool { return true }
// Device is a running ublk device: /dev/ublkbN served from a Backend.
type Device struct {
devID uint32
path string
ctrlFD int
ctrl *uring
charFD int
queues []*queue
cancel context.CancelFunc
closeOnce sync.Once
closeErr error
}
type queue struct {
id int
depth int
ioBytes int
descs []byte // mmap'd descriptor array (read-only)
bufs []byte // anonymous mmap: depth buffers of ioBytes each
h handler
charFD int
fetched chan error // nil once every tag has been fetched
done chan struct{} // closed when the queue thread exits
err error
}
// Start creates /dev/ublkbN (N = cfg.DevID, or the kernel's choice when
// DevID < 0) backed by cfg.Backend and serves it until Close. A device
// left at the same id by a dead server is stopped and deleted first.
func Start(cfg Config) (*Device, error) {
if err := cfg.validate(); err != nil {
return nil, err
}
ctrlFD, err := unix.Open(ctrlDevicePath, unix.O_RDWR|unix.O_CLOEXEC, 0)
if err != nil {
return nil, fmt.Errorf("ublk: open %s (ublk_drv loaded, root?): %w", ctrlDevicePath, err)
}
ctrl, err := newURing(8)
if err != nil {
_ = unix.Close(ctrlFD)
return nil, err
}
d := &Device{ctrlFD: ctrlFD, ctrl: ctrl, charFD: -1}
fail := func(err error) (*Device, error) {
d.teardown(false)
return nil, err
}
id := devIDAuto
if cfg.DevID >= 0 {
id = uint32(cfg.DevID)
if _, err := os.Stat(charDevicePrefix + strconv.Itoa(cfg.DevID)); err == nil {
// A server that died left its device behind: it fails I/O
// (no user recovery); remove it before creating ours.
_, _ = d.ctrlCommand(uCmdStopDev, id, nil, 0)
if _, err := d.ctrlCommand(uCmdDelDev, id, nil, 0); err != nil {
return fail(fmt.Errorf("ublk: delete stale device %d: %w", id, err))
}
}
}
info := devInfo{
NrHWQueues: uint16(cfg.Queues),
QueueDepth: uint16(cfg.QueueDepth),
MaxIOBufBytes: cfg.MaxIOBytes,
DevID: id,
Flags: flagCmdIoctlEncode,
}
if _, err := d.ctrlCommand(uCmdAddDev, id, bytesOf(&info), 0); err != nil {
return fail(fmt.Errorf("ublk: add device: %w", err))
}
d.devID = info.DevID
d.path = blockDevicePrefix + strconv.FormatUint(uint64(d.devID), 10)
shift := uint8(bits.TrailingZeros32(cfg.BlockSize))
p := params{
Len: uint32(unsafe.Sizeof(params{})),
Types: paramTypeBasic,
Basic: paramBasic{
Attrs: attrVolatileCache | attrFUA,
LogicalBSShift: shift,
PhysicalBSShift: shift,
IOMinShift: shift,
IOOptShift: shift,
MaxSectors: cfg.MaxIOBytes >> sectorShift,
DevSectors: cfg.Size >> sectorShift,
},
}
if _, err := d.ctrlCommand(uCmdSetParams, d.devID, bytesOf(&p), 0); err != nil {
return fail(fmt.Errorf("ublk: set params: %w", err))
}
charPath := charDevicePrefix + strconv.FormatUint(uint64(d.devID), 10)
if d.charFD, err = openWhenPresent(charPath, 5*time.Second); err != nil {
return fail(err)
}
ctx, cancel := context.WithCancel(context.Background())
d.cancel = cancel
h := handler{backend: cfg.Backend, size: cfg.Size}
for q := 0; q < cfg.Queues; q++ {
qu, err := newQueue(q, cfg, d.charFD, h)
if err != nil {
return fail(err)
}
d.queues = append(d.queues, qu)
go qu.run(ctx)
if err := <-qu.fetched; err != nil {
return fail(fmt.Errorf("ublk: queue %d: %w", q, err))
}
}
// Every tag of every queue has a FETCH outstanding: the device can go
// live. START_DEV names this server process.
if _, err := d.ctrlCommand(uCmdStartDev, d.devID, nil, uint64(os.Getpid())); err != nil {
return fail(fmt.Errorf("ublk: start device: %w", err))
}
return d, nil
}
// Path is the block device, /dev/ublkbN.
func (d *Device) Path() string { return d.path }
// Close stops the device (outstanding fetches abort), waits for the queue
// threads, and deletes the device.
func (d *Device) Close() error {
d.closeOnce.Do(func() { d.closeErr = d.teardown(true) })
return d.closeErr
}
func (d *Device) teardown(added bool) error {
var firstErr error
note := func(err error) {
if err != nil && firstErr == nil {
firstErr = err
}
}
if d.path != "" {
if _, err := d.ctrlCommand(uCmdStopDev, d.devID, nil, 0); err != nil && added {
note(fmt.Errorf("ublk: stop device: %w", err))
}
}
if d.cancel != nil {
d.cancel()
}
for _, q := range d.queues {
select {
case <-q.done:
case <-time.After(10 * time.Second):
note(fmt.Errorf("ublk: queue %d did not stop", q.id))
}
q.release()
}
if d.charFD >= 0 {
note(unix.Close(d.charFD))
d.charFD = -1
}
if d.path != "" {
if _, err := d.ctrlCommand(uCmdDelDev, d.devID, nil, 0); err != nil {
note(fmt.Errorf("ublk: delete device: %w", err))
}
}
note(d.ctrl.close())
note(unix.Close(d.ctrlFD))
return firstErr
}
// ctrlCommand runs one control command on /dev/ublk-control and returns
// the CQE result. buf (may be nil) is the command's in/out buffer.
func (d *Device) ctrlCommand(cmdOp uint32, devID uint32, buf []byte, data uint64) (int32, error) {
c := ctrlCmd{DevID: devID, QueueID: queueIDNone, Data: data}
if len(buf) > 0 {
c.Addr = uint64(uintptr(unsafe.Pointer(&buf[0])))
c.Len = uint16(len(buf))
}
if err := d.ctrl.prepare(opURingCmd, d.ctrlFD, cmdOp, bytesOf(&c), uint64(cmdOp)); err != nil {
return 0, err
}
if err := d.ctrl.submitAndWait(1); err != nil {
return 0, err
}
cq := d.ctrl.reap(nil)
runtime.KeepAlive(buf)
if len(cq) != 1 {
return 0, fmt.Errorf("ublk: control command %#x: %d completions", cmdOp, len(cq))
}
if cq[0].Res < 0 {
return cq[0].Res, unix.Errno(-cq[0].Res)
}
return cq[0].Res, nil
}
func openWhenPresent(path string, timeout time.Duration) (int, error) {
deadline := time.Now().Add(timeout)
for {
fd, err := unix.Open(path, unix.O_RDWR|unix.O_CLOEXEC, 0)
if err == nil {
return fd, nil
}
if !errors.Is(err, unix.ENOENT) || time.Now().After(deadline) {
return -1, fmt.Errorf("ublk: open %s: %w", path, err)
}
time.Sleep(10 * time.Millisecond)
}
}
func newQueue(id int, cfg Config, charFD int, h handler) (*queue, error) {
page := os.Getpagesize()
descLen := (cfg.QueueDepth*ioDescSize + page - 1) / page * page
descs, err := unix.Mmap(charFD, queueDescOffset(id), descLen, unix.PROT_READ, unix.MAP_SHARED|unix.MAP_POPULATE)
if err != nil {
return nil, fmt.Errorf("ublk: mmap queue %d descriptors: %w", id, err)
}
bufs, err := unix.Mmap(-1, 0, cfg.QueueDepth*int(cfg.MaxIOBytes), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_PRIVATE|unix.MAP_ANONYMOUS)
if err != nil {
_ = unix.Munmap(descs)
return nil, fmt.Errorf("ublk: map queue %d buffers: %w", id, err)
}
return &queue{
id: id, depth: cfg.QueueDepth, ioBytes: int(cfg.MaxIOBytes),
descs: descs, bufs: bufs, h: h, charFD: charFD,
fetched: make(chan error, 1), done: make(chan struct{}),
}, nil
}
func (q *queue) buf(tag int) []byte { return q.bufs[tag*q.ioBytes : (tag+1)*q.ioBytes] }
func (q *queue) desc(tag int) ioDesc {
return *(*ioDesc)(unsafe.Pointer(&q.descs[tag*ioDescSize]))
}
func (q *queue) ioCommand(r *uring, cmdOp uint32, tag int, result int32) error {
c := ioCmd{QID: uint16(q.id), Tag: uint16(tag), Result: result, Addr: uint64(uintptr(unsafe.Pointer(&q.buf(tag)[0])))}
return r.prepare(opURingCmd, q.charFD, cmdOp, bytesOf(&c), uint64(tag))
}
// run is the queue's server thread. ublk binds a queue to the task that
// issued its FETCH commands, so the ring lives and is driven on one
// locked OS thread.
func (q *queue) run(ctx context.Context) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(q.done)
r, err := newURing(uint32(q.depth))
if err == nil {
for tag := 0; tag < q.depth && err == nil; tag++ {
err = q.ioCommand(r, uIOFetchReq, tag, 0)
}
if err == nil {
err = r.submitAndWait(0)
}
}
q.fetched <- err
if err != nil {
if r != nil {
_ = r.close()
}
q.err = err
return
}
defer r.close()
live := q.depth // tags with a fetch outstanding
var cq []cqe
for live > 0 {
if err := r.submitAndWait(1); err != nil {
q.err = err
return
}
cq = r.reap(cq[:0])
for _, c := range cq {
tag := int(c.UserData)
if c.Res != ioResOK { // ABORT (-ENODEV) or a failure: no re-fetch
live--
continue
}
result := q.h.handle(ctx, q.desc(tag).request(), q.buf(tag))
if err := q.ioCommand(r, uIOCommitAndFetchReq, tag, result); err != nil {
q.err = err
return
}
}
}
}
func (q *queue) release() {
if q.descs != nil {
_ = unix.Munmap(q.descs)
q.descs = nil
}
if q.bufs != nil {
_ = unix.Munmap(q.bufs)
q.bufs = nil
}
}
@@ -0,0 +1,25 @@
//go:build !linux
package ublk
import "errors"
// Implemented reports whether this platform has the ublk server.
func Implemented() bool { return false }
// Device is unavailable off Linux.
type Device struct{}
// Start always fails off Linux: ublk is a Linux kernel driver.
func Start(cfg Config) (*Device, error) {
if err := cfg.validate(); err != nil {
return nil, err
}
return nil, errors.New("ublk: requires Linux (ublk_drv)")
}
// Path is empty off Linux.
func (d *Device) Path() string { return "" }
// Close is a no-op off Linux.
func (d *Device) Close() error { return nil }
+121
View File
@@ -0,0 +1,121 @@
package ublk
import (
"context"
"errors"
"fmt"
"sync"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// TargetConfig wires a ublk device to a volume through a Provider.
type TargetConfig struct {
VolumeID string
Provider frontend.Provider
DevID int
BlockSize uint32
VolumeSize uint64
Queues int
QueueDepth int
}
// Target serves one volume as /dev/ublkbN. The backend is opened from
// the Provider on first I/O, as the NVMe-RDMA target does.
type Target struct {
cfg TargetConfig
mu sync.Mutex
device *Device
}
// NewTarget returns an unstarted target.
func NewTarget(cfg TargetConfig) *Target {
if cfg.Provider == nil {
panic("ublk: NewTarget: Provider required")
}
return &Target{cfg: cfg}
}
// Start creates the device and returns its path.
func (t *Target) Start() (string, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.device != nil {
return "", errors.New("ublk: target already started")
}
d, err := Start(Config{
Backend: &providerBackend{provider: t.cfg.Provider, volumeID: t.cfg.VolumeID},
Size: t.cfg.VolumeSize,
BlockSize: t.cfg.BlockSize,
DevID: t.cfg.DevID,
Queues: t.cfg.Queues,
QueueDepth: t.cfg.QueueDepth,
})
if err != nil {
return "", err
}
t.device = d
return d.Path(), nil
}
// Close stops and deletes the device.
func (t *Target) Close() error {
if t == nil {
return nil
}
t.mu.Lock()
d := t.device
t.device = nil
t.mu.Unlock()
if d == nil {
return nil
}
return d.Close()
}
type providerBackend struct {
provider frontend.Provider
volumeID string
mu sync.Mutex
backend frontend.Backend
}
func (b *providerBackend) get(ctx context.Context) (frontend.Backend, error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.backend != nil {
return b.backend, nil
}
backend, err := b.provider.Open(ctx, b.volumeID)
if err != nil {
return nil, fmt.Errorf("ublk: open backend: %w", err)
}
b.backend = backend
return backend, nil
}
func (b *providerBackend) Read(ctx context.Context, offset int64, p []byte) (int, error) {
backend, err := b.get(ctx)
if err != nil {
return 0, err
}
return backend.Read(ctx, offset, p)
}
func (b *providerBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) {
backend, err := b.get(ctx)
if err != nil {
return 0, err
}
return backend.Write(ctx, offset, p)
}
func (b *providerBackend) Sync(ctx context.Context) error {
backend, err := b.get(ctx)
if err != nil {
return err
}
return backend.Sync(ctx)
}
@@ -0,0 +1,57 @@
package ublk
import (
"bytes"
"context"
"errors"
"syscall"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
)
type failingProvider struct{ err error }
func (p failingProvider) Open(context.Context, string) (frontend.Backend, error) { return nil, p.err }
// Through the provider glue the contract still holds: requests reach the
// opened backend, and a provider that cannot open the volume fails every
// request (never acknowledged).
func TestTarget_ProviderBackendCarriesTheContract(t *testing.T) {
rb := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})
h := handler{backend: &providerBackend{provider: testback.NewStaticProvider(rb), volumeID: "v1"}, size: testSize}
data := bytes.Repeat([]byte{7}, 4096)
if got := h.handle(context.Background(), request{op: ioOpWrite, flags: ioFlagFUA, nrSectors: 8}, data); got != 4096 {
t.Fatalf("write through the provider: %d", got)
}
if rb.WriteCount() != 1 || rb.SyncCount() != 1 {
t.Fatalf("provider backend: %d writes %d syncs", rb.WriteCount(), rb.SyncCount())
}
down := handler{backend: &providerBackend{provider: failingProvider{err: errors.New("not healthy")}, volumeID: "v1"}, size: testSize}
for _, r := range []request{{op: ioOpRead, nrSectors: 8}, {op: ioOpWrite, nrSectors: 8}, {op: ioOpFlush}} {
if got := down.handle(context.Background(), r, make([]byte, 4096)); got != -int32(syscall.EIO) {
t.Fatalf("op %d with no backend: %d, want -EIO", r.op, got)
}
}
}
func TestConfig_Validate(t *testing.T) {
ok := Config{Backend: &failingBackend{}, Size: 1 << 30, BlockSize: 4096}
if err := ok.validate(); err != nil || ok.Queues != DefaultQueues || ok.QueueDepth != DefaultQueueDepth || ok.MaxIOBytes != DefaultMaxIOBytes {
t.Fatalf("defaults: %+v %v", ok, err)
}
for name, c := range map[string]Config{
"no backend": {Size: 4096, BlockSize: 4096},
"block size": {Backend: &failingBackend{}, Size: 4096, BlockSize: 1000},
"size": {Backend: &failingBackend{}, Size: 4097, BlockSize: 4096},
"queues": {Backend: &failingBackend{}, Size: 4096, BlockSize: 4096, Queues: 65},
"queue depth": {Backend: &failingBackend{}, Size: 4096, BlockSize: 4096, QueueDepth: 4097},
"max io bytes": {Backend: &failingBackend{}, Size: 4096, BlockSize: 4096, MaxIOBytes: 1000},
} {
if err := c.validate(); err == nil {
t.Errorf("%s: accepted %+v", name, c)
}
}
}
+141
View File
@@ -0,0 +1,141 @@
package ublk
// Kernel ABI of the ublk driver (include/uapi/linux/ublk_cmd.h). The
// struct layouts and ioctl encodings are checked by uapi_test.go.
// Control commands (/dev/ublk-control), ioctl-encoded (UBLK_U_CMD_*).
const (
cmdGetDevInfo = 0x02
cmdAddDev = 0x04
cmdDelDev = 0x05
cmdStartDev = 0x06
cmdStopDev = 0x07
cmdSetParams = 0x08
ioFetchReq = 0x20
ioCommitAndRef = 0x21
)
// Device flags (UBLK_F_*).
const (
flagCmdIoctlEncode = 1 << 6
)
// Fetch/commit CQE results.
const (
ioResOK = 0
ioResAbort = -19 // -ENODEV: the queue is being torn down; no re-fetch
)
// Parameter types and basic attributes.
const (
paramTypeBasic = 1 << 0
attrVolatileCache = 1 << 2
attrFUA = 1 << 3
maxQueueDepth = 4096 // UBLK_MAX_QUEUE_DEPTH
ioDescSize = 24 // sizeof(struct ublksrv_io_desc)
cmdBufOffset = 0 // UBLKSRV_CMD_BUF_OFFSET
ctrlDevicePath = "/dev/ublk-control"
charDevicePrefix = "/dev/ublkc"
blockDevicePrefix = "/dev/ublkb"
devIDAuto = ^uint32(0)
queueIDNone = ^uint16(0)
maxIOBufBytesLimit = 1 << 25 // single IO buffer max (UBLK_IO_BUF_BITS)
)
// ctrlCmd is struct ublksrv_ctrl_cmd (32 bytes), carried in sqe->cmd.
type ctrlCmd struct {
DevID uint32
QueueID uint16
Len uint16
Addr uint64
Data uint64
DevPathLen uint16
Pad uint16
Reserved uint32
}
// devInfo is struct ublksrv_ctrl_dev_info (64 bytes).
type devInfo struct {
NrHWQueues uint16
QueueDepth uint16
State uint16
Pad0 uint16
MaxIOBufBytes uint32
DevID uint32
SrvPID int32
Pad1 uint32
Flags uint64
SrvFlags uint64
OwnerUID uint32
OwnerGID uint32
Reserved1 uint64
Reserved2 uint64
}
// ioDesc is struct ublksrv_io_desc (24 bytes), in the mmap'd descriptor
// array of /dev/ublkcN, indexed by tag.
type ioDesc struct {
OpFlags uint32
NrSectors uint32
StartSector uint64
Addr uint64
}
func (d ioDesc) request() request {
return request{op: uint8(d.OpFlags & 0xff), flags: d.OpFlags &^ 0xff, startSector: d.StartSector, nrSectors: d.NrSectors}
}
// ioCmd is struct ublksrv_io_cmd (16 bytes), carried in sqe->cmd.
type ioCmd struct {
QID uint16
Tag uint16
Result int32
Addr uint64
}
// paramBasic is struct ublk_param_basic (32 bytes).
type paramBasic struct {
Attrs uint32
LogicalBSShift uint8
PhysicalBSShift uint8
IOOptShift uint8
IOMinShift uint8
MaxSectors uint32
ChunkSectors uint32
DevSectors uint64
VirtBoundaryMask uint64
}
// params is the leading part of struct ublk_params that this server
// sets: len, types and the basic parameters (len names exactly this much).
type params struct {
Len uint32
Types uint32
Basic paramBasic
}
// iowr and ior encode a ublk command number like the kernel's _IOWR and
// _IOR('u', nr, size).
func iowr(nr, size uint32) uint32 { return 3<<30 | size<<16 | uint32('u')<<8 | nr }
func ior(nr, size uint32) uint32 { return 2<<30 | size<<16 | uint32('u')<<8 | nr }
const (
ctrlCmdSize = 32
ioCmdSize = 16
)
var (
uCmdGetDevInfo = ior(cmdGetDevInfo, ctrlCmdSize)
uCmdAddDev = iowr(cmdAddDev, ctrlCmdSize)
uCmdDelDev = iowr(cmdDelDev, ctrlCmdSize)
uCmdStartDev = iowr(cmdStartDev, ctrlCmdSize)
uCmdStopDev = iowr(cmdStopDev, ctrlCmdSize)
uCmdSetParams = iowr(cmdSetParams, ctrlCmdSize)
uIOFetchReq = iowr(ioFetchReq, ioCmdSize)
uIOCommitAndFetchReq = iowr(ioCommitAndRef, ioCmdSize)
)
// queueDescOffset is the mmap offset of queue q's descriptor array.
func queueDescOffset(q int) int64 {
return cmdBufOffset + int64(q)*maxQueueDepth*ioDescSize
}
@@ -0,0 +1,78 @@
package ublk
import (
"testing"
"unsafe"
)
// The kernel reads these structs byte for byte: their sizes and the
// command encodings must match include/uapi/linux/ublk_cmd.h exactly.
func TestUAPI_StructLayouts(t *testing.T) {
for _, tc := range []struct {
name string
got uintptr
want uintptr
}{
{"ublksrv_ctrl_cmd", unsafe.Sizeof(ctrlCmd{}), 32},
{"ublksrv_ctrl_dev_info", unsafe.Sizeof(devInfo{}), 64},
{"ublksrv_io_desc", unsafe.Sizeof(ioDesc{}), 24},
{"ublksrv_io_cmd", unsafe.Sizeof(ioCmd{}), 16},
{"ublk_param_basic", unsafe.Sizeof(paramBasic{}), 32},
{"ublk_params header+basic", unsafe.Sizeof(params{}), 40},
} {
if tc.got != tc.want {
t.Errorf("sizeof(%s) = %d, want %d", tc.name, tc.got, tc.want)
}
}
for _, tc := range []struct {
name string
got uintptr
want uintptr
}{
{"ctrl_cmd.addr", unsafe.Offsetof(ctrlCmd{}.Addr), 8},
{"ctrl_cmd.data", unsafe.Offsetof(ctrlCmd{}.Data), 16},
{"dev_info.max_io_buf_bytes", unsafe.Offsetof(devInfo{}.MaxIOBufBytes), 8},
{"dev_info.flags", unsafe.Offsetof(devInfo{}.Flags), 24},
{"io_desc.start_sector", unsafe.Offsetof(ioDesc{}.StartSector), 8},
{"io_cmd.addr", unsafe.Offsetof(ioCmd{}.Addr), 8},
{"param_basic.max_sectors", unsafe.Offsetof(paramBasic{}.MaxSectors), 8},
{"param_basic.dev_sectors", unsafe.Offsetof(paramBasic{}.DevSectors), 16},
} {
if tc.got != tc.want {
t.Errorf("offsetof(%s) = %d, want %d", tc.name, tc.got, tc.want)
}
}
}
func TestUAPI_CommandEncodings(t *testing.T) {
// _IOWR('u', nr, struct ublksrv_ctrl_cmd) and friends, computed from
// the kernel's macro definition.
for _, tc := range []struct {
name string
got, want uint32
}{
{"UBLK_U_CMD_GET_DEV_INFO", uCmdGetDevInfo, 0x80207502},
{"UBLK_U_CMD_ADD_DEV", uCmdAddDev, 0xc0207504},
{"UBLK_U_CMD_DEL_DEV", uCmdDelDev, 0xc0207505},
{"UBLK_U_CMD_START_DEV", uCmdStartDev, 0xc0207506},
{"UBLK_U_CMD_STOP_DEV", uCmdStopDev, 0xc0207507},
{"UBLK_U_CMD_SET_PARAMS", uCmdSetParams, 0xc0207508},
{"UBLK_U_IO_FETCH_REQ", uIOFetchReq, 0xc0107520},
{"UBLK_U_IO_COMMIT_AND_FETCH_REQ", uIOCommitAndFetchReq, 0xc0107521},
} {
if tc.got != tc.want {
t.Errorf("%s = %#x, want %#x", tc.name, tc.got, tc.want)
}
}
if got := queueDescOffset(2); got != 2*4096*24 {
t.Errorf("queue 2 descriptor offset %d", got)
}
}
func TestUAPI_DescriptorToRequest(t *testing.T) {
d := ioDesc{OpFlags: ioOpWrite | ioFlagFUA, NrSectors: 8, StartSector: 100}
r := d.request()
if r.op != ioOpWrite || r.flags&ioFlagFUA == 0 || r.nrSectors != 8 || r.startSector != 100 {
t.Fatalf("request %+v from %+v", r, d)
}
}
@@ -0,0 +1,199 @@
//go:build linux
package ublk
import (
"errors"
"fmt"
"sync/atomic"
"unsafe"
"golang.org/x/sys/unix"
)
// A minimal io_uring for ublk: 128-byte SQEs (IORING_SETUP_SQE128, the
// layout URING_CMD needs for an 80-byte command), 16-byte CQEs, one
// submitter. Only what the ublk server uses: NOP (tests) and URING_CMD.
const (
setupSQE128 = 1 << 10
featSingleMMap = 1 << 0
offSQRing = 0
offCQRing = 0x8000000
offSQEs = 0x10000000
enterGetEvents = 1 << 0
opNop = 0
opURingCmd = 46
sqeSize = 128
cqeSize = 16
sqeCmdOffset = 48 // sqe->cmd: 80 bytes with SQE128
sqeCmdCapacity = 80
sqeCmdOpOffset = 8
sqeUserDataOff = 32
uringParamsSize = 120
)
type sqOffsets struct {
Head, Tail, RingMask, RingEntries, Flags, Dropped, Array, Resv1 uint32
UserAddr uint64
}
type cqOffsets struct {
Head, Tail, RingMask, RingEntries, Overflow, Cqes, Flags, Resv1 uint32
UserAddr uint64
}
type uringParams struct {
SqEntries, CqEntries, Flags, SqThreadCPU, SqThreadIdle, Features, WqFd uint32
Resv [3]uint32
SqOff sqOffsets
CqOff cqOffsets
}
type cqe struct {
UserData uint64
Res int32
Flags uint32
}
type uring struct {
fd int
ringMem []byte
cqMem []byte // == ringMem with a single mmap
sqeMem []byte
sqHead, sqTail, sqMask *uint32
sqArray []uint32
cqHead, cqTail, cqMask *uint32
cqes []byte
sqEntries uint32
pending uint32 // SQEs filled but not yet submitted
}
func newURing(entries uint32) (*uring, error) {
var p uringParams
p.Flags = setupSQE128
fd, _, errno := unix.Syscall(unix.SYS_IO_URING_SETUP, uintptr(entries), uintptr(unsafe.Pointer(&p)), 0)
if errno != 0 {
return nil, fmt.Errorf("ublk: io_uring_setup: %w", errno)
}
r := &uring{fd: int(fd), sqEntries: p.SqEntries}
sqSize := int(p.SqOff.Array + p.SqEntries*4)
cqSize := int(p.CqOff.Cqes + p.CqEntries*cqeSize)
single := p.Features&featSingleMMap != 0
if single && cqSize > sqSize {
sqSize = cqSize
}
var err error
if r.ringMem, err = unix.Mmap(r.fd, offSQRing, sqSize, unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE); err != nil {
r.close()
return nil, fmt.Errorf("ublk: mmap sq ring: %w", err)
}
r.cqMem = r.ringMem
if !single {
if r.cqMem, err = unix.Mmap(r.fd, offCQRing, cqSize, unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE); err != nil {
r.close()
return nil, fmt.Errorf("ublk: mmap cq ring: %w", err)
}
}
if r.sqeMem, err = unix.Mmap(r.fd, offSQEs, int(p.SqEntries)*sqeSize, unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE); err != nil {
r.close()
return nil, fmt.Errorf("ublk: mmap sqes: %w", err)
}
u32 := func(mem []byte, off uint32) *uint32 { return (*uint32)(unsafe.Pointer(&mem[off])) }
r.sqHead, r.sqTail, r.sqMask = u32(r.ringMem, p.SqOff.Head), u32(r.ringMem, p.SqOff.Tail), u32(r.ringMem, p.SqOff.RingMask)
r.sqArray = unsafe.Slice(u32(r.ringMem, p.SqOff.Array), p.SqEntries)
r.cqHead, r.cqTail, r.cqMask = u32(r.cqMem, p.CqOff.Head), u32(r.cqMem, p.CqOff.Tail), u32(r.cqMem, p.CqOff.RingMask)
r.cqes = r.cqMem[p.CqOff.Cqes : p.CqOff.Cqes+p.CqEntries*cqeSize]
return r, nil
}
// prepare fills the next SQE: op on fd with cmdOp and an inline command
// (copied into sqe->cmd), tagged userData. It returns an error when the
// submission queue is full.
func (r *uring) prepare(op uint8, fd int, cmdOp uint32, cmd []byte, userData uint64) error {
if len(cmd) > sqeCmdCapacity {
return fmt.Errorf("ublk: command of %d bytes exceeds the SQE", len(cmd))
}
head := atomic.LoadUint32(r.sqHead)
tail := *r.sqTail + r.pending
if tail-head >= r.sqEntries {
return errors.New("ublk: submission queue full")
}
idx := tail & *r.sqMask
sqe := r.sqeMem[int(idx)*sqeSize : int(idx+1)*sqeSize]
clear(sqe)
sqe[0] = op
*(*int32)(unsafe.Pointer(&sqe[4])) = int32(fd)
*(*uint32)(unsafe.Pointer(&sqe[sqeCmdOpOffset])) = cmdOp
*(*uint64)(unsafe.Pointer(&sqe[sqeUserDataOff])) = userData
copy(sqe[sqeCmdOffset:], cmd)
r.sqArray[idx] = idx
r.pending++
return nil
}
// submitAndWait publishes the prepared SQEs and waits for at least
// minComplete completions.
func (r *uring) submitAndWait(minComplete uint32) error {
toSubmit := r.pending
atomic.StoreUint32(r.sqTail, *r.sqTail+toSubmit)
r.pending = 0
var flags uintptr
if minComplete > 0 {
flags = enterGetEvents
}
for {
_, _, errno := unix.Syscall6(unix.SYS_IO_URING_ENTER, uintptr(r.fd), uintptr(toSubmit), uintptr(minComplete), flags, 0, 0)
switch errno {
case 0:
return nil
case unix.EINTR:
toSubmit = 0 // the kernel consumed the SQEs before the interrupt
continue
default:
return fmt.Errorf("ublk: io_uring_enter: %w", errno)
}
}
}
// reap returns the available completions and releases their slots.
func (r *uring) reap(out []cqe) []cqe {
head := *r.cqHead
tail := atomic.LoadUint32(r.cqTail)
for ; head != tail; head++ {
off := int(head&*r.cqMask) * cqeSize
c := r.cqes[off : off+cqeSize]
out = append(out, cqe{
UserData: *(*uint64)(unsafe.Pointer(&c[0])),
Res: *(*int32)(unsafe.Pointer(&c[8])),
Flags: *(*uint32)(unsafe.Pointer(&c[12])),
})
}
atomic.StoreUint32(r.cqHead, head)
return out
}
func (r *uring) close() error {
if r.sqeMem != nil {
_ = unix.Munmap(r.sqeMem)
}
if r.cqMem != nil && &r.cqMem[0] != &r.ringMem[0] {
_ = unix.Munmap(r.cqMem)
}
if r.ringMem != nil {
_ = unix.Munmap(r.ringMem)
}
r.sqeMem, r.cqMem, r.ringMem = nil, nil, nil
if r.fd >= 0 {
err := unix.Close(r.fd)
r.fd = -1
return err
}
return nil
}
// bytesOf views a fixed-size struct as bytes for an inline command.
func bytesOf[T any](v *T) []byte {
return unsafe.Slice((*byte)(unsafe.Pointer(v)), unsafe.Sizeof(*v))
}
@@ -0,0 +1,60 @@
//go:build linux
package ublk
import (
"errors"
"testing"
"unsafe"
"golang.org/x/sys/unix"
)
func TestURing_ParamsLayout(t *testing.T) {
if got := unsafe.Sizeof(uringParams{}); got != uringParamsSize {
t.Fatalf("sizeof(io_uring_params) = %d, want %d", got, uringParamsSize)
}
}
// The ring itself, without ublk: NOPs round-trip through submission and
// completion with their user data, across a wrap of the queues.
func TestURing_NopRoundTrip(t *testing.T) {
r, err := newURing(4)
if errors.Is(err, unix.ENOSYS) || errors.Is(err, unix.EPERM) {
t.Skipf("io_uring unavailable here: %v", err)
}
if err != nil {
t.Fatal(err)
}
defer r.close()
var got []cqe
for round := 0; round < 3; round++ {
for i := 0; i < 4; i++ {
if err := r.prepare(opNop, -1, 0, nil, uint64(round*10+i)); err != nil {
t.Fatalf("round %d prepare %d: %v", round, i, err)
}
}
if err := r.prepare(opNop, -1, 0, nil, 99); err == nil {
t.Fatal("a fifth SQE was accepted into a 4-entry queue")
}
if err := r.submitAndWait(4); err != nil {
t.Fatal(err)
}
got = r.reap(got[:0])
if len(got) != 4 {
t.Fatalf("round %d: %d completions, want 4", round, len(got))
}
seen := map[uint64]bool{}
for _, c := range got {
if c.Res != 0 {
t.Fatalf("NOP result %d", c.Res)
}
seen[c.UserData] = true
}
for i := 0; i < 4; i++ {
if !seen[uint64(round*10+i)] {
t.Fatalf("round %d: completion for %d missing (%v)", round, round*10+i, got)
}
}
}
}