mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
Merge pull request #136 from seaweedfs/blockc/ublk-frontend-m5
ublk frontend: serve a volume as /dev/ublkbN (io_uring command queues)
This commit is contained in:
commit
4e5da657f5
19 files changed
+2124
No files matched your search
@@ -26,6 +26,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/memback"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvmerdma"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/ublk"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
"github.com/seaweedfs/seaweed-block/core/recovery"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
@@ -94,6 +95,12 @@ type flags struct {
|
||||
// gates; default installs remain loopback-only.
|
||||
allowExternalNVMeBind bool
|
||||
|
||||
// ublk frontend: serve the volume as the local block device
|
||||
// /dev/ublkbN (Linux ublk_drv, root). -1 disables.
|
||||
ublkDevice int
|
||||
ublkQueues int
|
||||
ublkQueueDepth int
|
||||
|
||||
// Durable-backend flags. When --durable-root is set, the iSCSI
|
||||
// and NVMe providers use DurableProvider instead of memback.
|
||||
// --durable-impl selects smartwal, walstore, or the explicit
|
||||
@@ -174,6 +181,9 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.nvmeTransport, "nvme-transport", "tcp", "NVMe-oF transport: tcp or the explicit Linux-only standalone rdma target")
|
||||
fs.UintVar(&f.nvmeMaxH2C, "nvme-max-h2c-data-length", 0, "NVMe/TCP MaxH2CDataLength in bytes. 0 preserves the target default")
|
||||
fs.BoolVar(&f.allowExternalNVMeBind, "allow-external-nvme-bind", false, "allow NVMe to bind a non-loopback address; unauthenticated, intended only for explicit gates")
|
||||
fs.IntVar(&f.ublkDevice, "ublk-device", -1, "serve the volume as the local block device /dev/ublkbN (Linux ublk_drv, root); -1 disables. Same-host alternative to the NVMe/TCP loopback")
|
||||
fs.IntVar(&f.ublkQueues, "ublk-queues", 0, "ublk hardware queues (one server thread each); 0 = default 1. Requires --ublk-device")
|
||||
fs.IntVar(&f.ublkQueueDepth, "ublk-queue-depth", 0, "ublk in-flight requests per queue; 0 = default 64. Requires --ublk-device")
|
||||
fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)")
|
||||
fs.StringVar(&f.durableImpl, "durable-impl", "smartwal", "LogicalStorage impl: smartwal (default), walstore, opt-in parallel-walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set")
|
||||
fs.StringVar(&f.chunk.filer, "chunk-filer", "", "walstore-chunk: SeaweedFS filer gRPC address host:port")
|
||||
@@ -334,6 +344,24 @@ func parseFlags(args []string) (flags, error) {
|
||||
} else if f.nvmeMaxH2C != 0 {
|
||||
return flags{}, fmt.Errorf("--nvme-max-h2c-data-length requires --nvme-listen")
|
||||
}
|
||||
if f.ublkDevice >= 0 {
|
||||
if f.ublkQueues < 0 || f.ublkQueues > 64 {
|
||||
return flags{}, fmt.Errorf("--ublk-queues=%d, want 0..64", f.ublkQueues)
|
||||
}
|
||||
if f.ublkQueueDepth < 0 || f.ublkQueueDepth > 4096 {
|
||||
return flags{}, fmt.Errorf("--ublk-queue-depth=%d, want 0..4096", f.ublkQueueDepth)
|
||||
}
|
||||
// Like iSCSI and NVMe: the device serves only through a healthy
|
||||
// projection.
|
||||
if !f.enableT1Readiness {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: ublk enabled: t1-readiness auto-enabled")
|
||||
}
|
||||
f.enableT1Readiness = true
|
||||
} else if f.ublkDevice < -1 {
|
||||
return flags{}, fmt.Errorf("--ublk-device=%d, want -1 (off) or a device id >= 0", f.ublkDevice)
|
||||
} else if f.ublkQueues != 0 || f.ublkQueueDepth != 0 {
|
||||
return flags{}, fmt.Errorf("--ublk-queues/--ublk-queue-depth require --ublk-device")
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
@@ -479,6 +507,13 @@ type iscsiReadyLine struct {
|
||||
IQN string `json:"iqn"`
|
||||
}
|
||||
|
||||
// ublkReadyLine reports the ublk block device once it serves.
|
||||
type ublkReadyLine struct {
|
||||
Component string `json:"component"`
|
||||
Phase string `json:"phase"`
|
||||
Device string `json:"device"`
|
||||
}
|
||||
|
||||
type nvmeReadyLine struct {
|
||||
Component string `json:"component"`
|
||||
Phase string `json:"phase"`
|
||||
@@ -1128,6 +1163,61 @@ func run(f flags) int {
|
||||
}
|
||||
}
|
||||
|
||||
var ublkTarget *ublk.Target
|
||||
if f.ublkDevice >= 0 {
|
||||
blockSize := frontendBlockSize
|
||||
volumeSize := frontendVolumeSize
|
||||
if blockSize == 0 {
|
||||
blockSize = nvme.DefaultBlockSize
|
||||
}
|
||||
if volumeSize == 0 {
|
||||
volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize)
|
||||
}
|
||||
ublkTarget = ublk.NewTarget(ublk.TargetConfig{
|
||||
VolumeID: f.volumeID,
|
||||
Provider: provider,
|
||||
DevID: f.ublkDevice,
|
||||
BlockSize: blockSize,
|
||||
VolumeSize: volumeSize,
|
||||
Queues: f.ublkQueues,
|
||||
QueueDepth: f.ublkQueueDepth,
|
||||
})
|
||||
ublkPath, err := ublkTarget.Start()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: ublk device:", err)
|
||||
if nvmeTarget != nil {
|
||||
_ = nvmeTarget.Close()
|
||||
}
|
||||
if iscsiTarget != nil {
|
||||
_ = iscsiTarget.Close()
|
||||
}
|
||||
if replListen != nil {
|
||||
replListen.Stop()
|
||||
}
|
||||
if replVolume != nil {
|
||||
_ = replVolume.Close()
|
||||
}
|
||||
if durableProv != nil {
|
||||
_ = durableProv.Close()
|
||||
}
|
||||
if status != nil {
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = status.Close(shutCtx)
|
||||
shutCancel()
|
||||
}
|
||||
_ = h.Close()
|
||||
return 1
|
||||
}
|
||||
if status != nil {
|
||||
status.SetUblkStatusSource(ublkTarget)
|
||||
}
|
||||
_ = json.NewEncoder(os.Stdout).Encode(ublkReadyLine{
|
||||
Component: "blockvolume",
|
||||
Phase: "ublk-ready",
|
||||
Device: ublkPath,
|
||||
})
|
||||
}
|
||||
|
||||
shutdownCtx, stopSignals := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stopSignals()
|
||||
var leaseRequests <-chan workspaceStopRequest
|
||||
@@ -1152,6 +1242,11 @@ func run(f flags) int {
|
||||
drainErr = durableProv.Backend(f.volumeID).StopIO(leaseStop.ctx, "workspace lease fenced")
|
||||
}
|
||||
h.SetFrontendTargets(nil)
|
||||
// The ublk device drains with the other frontends: its Close (STOP_DEV,
|
||||
// queue join, DEL_DEV) is part of the drain the lease ACK waits for.
|
||||
if ublkTarget != nil {
|
||||
drainErr = errors.Join(drainErr, ublkTarget.Close())
|
||||
}
|
||||
if nvmeTarget != nil {
|
||||
if status != nil {
|
||||
status.SetNVMeListenerReady(false)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestUblkFlags(t *testing.T) {
|
||||
base := func(extra ...string) []string {
|
||||
return append(phase150RequiredBlockvolumeArgs(), extra...)
|
||||
}
|
||||
off, err := parseFlags(base())
|
||||
if err != nil || off.ublkDevice != -1 {
|
||||
t.Fatalf("default: ublk-device=%d err=%v, want -1 (off)", off.ublkDevice, err)
|
||||
}
|
||||
on, err := parseFlags(base("--ublk-device=3", "--ublk-queues=2", "--ublk-queue-depth=128"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if on.ublkDevice != 3 || on.ublkQueues != 2 || on.ublkQueueDepth != 128 {
|
||||
t.Fatalf("parsed ublk flags: device %d queues %d depth %d", on.ublkDevice, on.ublkQueues, on.ublkQueueDepth)
|
||||
}
|
||||
if !on.enableT1Readiness {
|
||||
t.Fatal("--ublk-device did not enable the readiness bridge (the device must serve only through a healthy projection)")
|
||||
}
|
||||
for name, args := range map[string][]string{
|
||||
"queues without a device": base("--ublk-queues=2"),
|
||||
"depth without a device": base("--ublk-queue-depth=8"),
|
||||
"negative device id": base("--ublk-device=-2"),
|
||||
"too many queues": base("--ublk-device=0", "--ublk-queues=65"),
|
||||
"queue depth too large": base("--ublk-device=0", "--ublk-queue-depth=4097"),
|
||||
} {
|
||||
if _, err := parseFlags(args); err == nil {
|
||||
t.Errorf("%s: parseFlags succeeded; want an error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,362 @@
|
||||
//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
|
||||
stats *counters
|
||||
|
||||
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
|
||||
// already present at the requested id is refused untouched.
|
||||
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)
|
||||
_, statErr := os.Stat(charDevicePrefix + strconv.Itoa(cfg.DevID))
|
||||
if err := refusePreExisting(id, statErr == nil); err != nil {
|
||||
return fail(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
|
||||
d.stats = &counters{}
|
||||
h := handler{backend: cfg.Backend, size: cfg.Size, stats: d.stats}
|
||||
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 }
|
||||
|
||||
// Stats returns the request counters since the device started.
|
||||
func (d *Device) Stats() Stats { return d.stats.snapshot() }
|
||||
|
||||
// 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 {
|
||||
qs := make([]settler, len(d.queues))
|
||||
for i, q := range d.queues {
|
||||
qs[i] = q
|
||||
}
|
||||
return d.teardownWith(qs, d, added)
|
||||
}
|
||||
|
||||
// command implements controller on the device's control ring.
|
||||
func (d *Device) command(cmdOp uint32, devID uint32, buf []byte, data uint64) (int32, error) {
|
||||
return d.ctrlCommand(cmdOp, devID, buf, data)
|
||||
}
|
||||
|
||||
// teardownWith stops the device through ctl, settles the queues and deletes
|
||||
// the device. It is the whole Close path; tests drive it with recorders.
|
||||
func (d *Device) teardownWith(qs []settler, ctl controller, added bool) error {
|
||||
var firstErr error
|
||||
note := func(err error) {
|
||||
if err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
if d.path != "" {
|
||||
if _, err := ctl.command(uCmdStopDev, d.devID, nil, 0); err != nil && added {
|
||||
note(fmt.Errorf("ublk: stop device: %w", err))
|
||||
}
|
||||
}
|
||||
if d.cancel != nil {
|
||||
d.cancel()
|
||||
}
|
||||
leaked, settleErr := settleQueues(qs, queueStopTimeout)
|
||||
note(settleErr)
|
||||
if d.charFD >= 0 {
|
||||
note(unix.Close(d.charFD))
|
||||
d.charFD = -1
|
||||
}
|
||||
if d.path != "" && leaked {
|
||||
// A queue's mappings are kept (it may still run), which holds the
|
||||
// char device open: DEL_DEV would wait for its release forever.
|
||||
// The device stays (it fails I/O); the error above reports it.
|
||||
note(fmt.Errorf("ublk: device %d left in place: a queue did not stop", d.devID))
|
||||
} else if d.path != "" {
|
||||
if _, err := ctl.command(uCmdDelDev, d.devID, nil, 0); err != nil {
|
||||
note(fmt.Errorf("ublk: delete device: %w", err))
|
||||
}
|
||||
}
|
||||
if d.ctrl != nil {
|
||||
note(d.ctrl.close())
|
||||
}
|
||||
if d.ctrlFD >= 0 {
|
||||
note(unix.Close(d.ctrlFD))
|
||||
}
|
||||
return firstErr
|
||||
}
|
||||
|
||||
// queueStopTimeout bounds how long Close waits for the queue threads.
|
||||
const queueStopTimeout = 10 * time.Second
|
||||
|
||||
// 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 {
|
||||
err = errors.Join(err, r.close())
|
||||
}
|
||||
q.err = err
|
||||
return
|
||||
}
|
||||
defer func() { q.err = errors.Join(q.err, r.close()) }() // before done closes
|
||||
|
||||
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 {
|
||||
still, err := q.onCQE(ctx, c, func(tag int, result int32) error {
|
||||
return q.ioCommand(r, uIOCommitAndFetchReq, tag, result)
|
||||
})
|
||||
if err != nil {
|
||||
q.err = err
|
||||
return
|
||||
}
|
||||
if !still {
|
||||
live--
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// onCQE handles one completion of a FETCH or COMMIT_AND_FETCH for a tag:
|
||||
// a new request is served and committed (the tag stays live); any other
|
||||
// result ends the tag (no re-fetch). It returns whether the tag is still
|
||||
// live and a commit failure.
|
||||
func (q *queue) onCQE(ctx context.Context, c cqe, commit func(tag int, result int32) error) (bool, error) {
|
||||
tag := int(c.UserData)
|
||||
switch {
|
||||
case c.Res == ioResAbort: // the device is stopping: no re-fetch
|
||||
return false, nil
|
||||
case c.Res != ioResOK: // anything else ends the tag and is reported
|
||||
q.err = errors.Join(q.err, fmt.Errorf("ublk: queue %d tag %d: unexpected completion result %d", q.id, tag, c.Res))
|
||||
return false, nil
|
||||
}
|
||||
result := q.h.handle(ctx, q.desc(tag).request(), q.buf(tag))
|
||||
return true, commit(tag, result)
|
||||
}
|
||||
|
||||
func (q *queue) doneCh() <-chan struct{} { return q.done }
|
||||
func (q *queue) result() error { return q.err }
|
||||
func (q *queue) name() string { return "queue " + strconv.Itoa(q.id) }
|
||||
|
||||
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,28 @@
|
||||
//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 "" }
|
||||
|
||||
// Stats is empty off Linux.
|
||||
func (d *Device) Stats() Stats { return Stats{} }
|
||||
|
||||
// Close is a no-op off Linux.
|
||||
func (d *Device) Close() error { return nil }
|
||||
@@ -0,0 +1,144 @@
|
||||
package ublk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// ublk request operations and flags (include/uapi/linux/ublk_cmd.h).
|
||||
const (
|
||||
ioOpRead = 0
|
||||
ioOpWrite = 1
|
||||
ioOpFlush = 2
|
||||
ioOpDiscard = 3
|
||||
ioOpWriteSame = 4
|
||||
ioOpWriteZeroes = 5
|
||||
|
||||
ioFlagFUA = 1 << 13
|
||||
|
||||
sectorShift = 9
|
||||
)
|
||||
|
||||
// Backend is the block contract the ublk bridge needs.
|
||||
type Backend interface {
|
||||
Read(context.Context, int64, []byte) (int, error)
|
||||
Write(context.Context, int64, []byte) (int, error)
|
||||
Sync(context.Context) error
|
||||
}
|
||||
|
||||
// request is one ublk I/O descriptor: op and flags from op_flags, the
|
||||
// range in 512-byte sectors.
|
||||
type request struct {
|
||||
op uint8
|
||||
flags uint32 // op_flags >> 8 shifted back: the raw flag bits
|
||||
startSector uint64
|
||||
nrSectors uint32
|
||||
}
|
||||
|
||||
// handler maps ublk requests onto a Backend.
|
||||
type handler struct {
|
||||
backend Backend
|
||||
size uint64 // device size in bytes
|
||||
stats *counters // nil: not counted
|
||||
}
|
||||
|
||||
// Stats are the device's request counters since it started. A request is
|
||||
// counted when it is received, before the backend call; Errors counts the
|
||||
// requests that completed with a negative result.
|
||||
type Stats struct {
|
||||
ReadRequests uint64 `json:"read_requests"`
|
||||
WriteRequests uint64 `json:"write_requests"`
|
||||
FlushRequests uint64 `json:"flush_requests"`
|
||||
FUAWrites uint64 `json:"fua_writes"`
|
||||
OtherRequests uint64 `json:"other_requests"`
|
||||
Errors uint64 `json:"errors"`
|
||||
}
|
||||
|
||||
type counters struct {
|
||||
reads, writes, flushes, fuaWrites, others, errors atomic.Uint64
|
||||
}
|
||||
|
||||
func (c *counters) snapshot() Stats {
|
||||
if c == nil {
|
||||
return Stats{}
|
||||
}
|
||||
return Stats{
|
||||
ReadRequests: c.reads.Load(), WriteRequests: c.writes.Load(), FlushRequests: c.flushes.Load(),
|
||||
FUAWrites: c.fuaWrites.Load(), OtherRequests: c.others.Load(), Errors: c.errors.Load(),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *counters) count(r request) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
switch r.op {
|
||||
case ioOpRead:
|
||||
c.reads.Add(1)
|
||||
case ioOpWrite:
|
||||
c.writes.Add(1)
|
||||
if r.flags&ioFlagFUA != 0 {
|
||||
c.fuaWrites.Add(1)
|
||||
}
|
||||
case ioOpFlush:
|
||||
c.flushes.Add(1)
|
||||
default:
|
||||
c.others.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
// handle serves one request against buf (len >= nrSectors<<9 for reads
|
||||
// and writes) and returns the ublk result: bytes transferred, 0 for a
|
||||
// flush, or a negative errno.
|
||||
func (h handler) handle(ctx context.Context, r request, buf []byte) int32 {
|
||||
h.stats.count(r)
|
||||
res := h.serve(ctx, r, buf)
|
||||
if res < 0 && h.stats != nil {
|
||||
h.stats.errors.Add(1)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func (h handler) serve(ctx context.Context, r request, buf []byte) int32 {
|
||||
switch r.op {
|
||||
case ioOpFlush:
|
||||
if err := h.backend.Sync(ctx); err != nil {
|
||||
return errno(syscall.EIO)
|
||||
}
|
||||
return 0
|
||||
case ioOpRead, ioOpWrite:
|
||||
default:
|
||||
return errno(syscall.EOPNOTSUPP)
|
||||
}
|
||||
|
||||
length := uint64(r.nrSectors) << sectorShift
|
||||
if r.startSector > h.size>>sectorShift {
|
||||
return errno(syscall.EINVAL)
|
||||
}
|
||||
offset := r.startSector << sectorShift
|
||||
if length > h.size-offset || length > uint64(len(buf)) || length > 1<<31-1 {
|
||||
return errno(syscall.EINVAL)
|
||||
}
|
||||
data := buf[:length]
|
||||
|
||||
if r.op == ioOpRead {
|
||||
n, err := h.backend.Read(ctx, int64(offset), data)
|
||||
if err != nil || n != len(data) {
|
||||
return errno(syscall.EIO)
|
||||
}
|
||||
return int32(n)
|
||||
}
|
||||
n, err := h.backend.Write(ctx, int64(offset), data)
|
||||
if err != nil || n != len(data) {
|
||||
return errno(syscall.EIO)
|
||||
}
|
||||
if r.flags&ioFlagFUA != 0 {
|
||||
if err := h.backend.Sync(ctx); err != nil {
|
||||
return errno(syscall.EIO)
|
||||
}
|
||||
}
|
||||
return int32(n)
|
||||
}
|
||||
|
||||
func errno(e syscall.Errno) int32 { return -int32(e) }
|
||||
@@ -0,0 +1,200 @@
|
||||
package ublk
|
||||
|
||||
// Frontend contract for the ublk bridge, the same contract the NBD and
|
||||
// NVMe frontends keep: reads and writes reach the backend at the right
|
||||
// offset, FLUSH and write-FUA reach Backend.Sync, every backend failure
|
||||
// is reported (never acknowledged), and an out-of-range request never
|
||||
// touches the backend.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
|
||||
)
|
||||
|
||||
const testSize = 1 << 20
|
||||
|
||||
func newTestHandler(b Backend) handler { return handler{backend: b, size: testSize} }
|
||||
|
||||
func sectors(n int) uint32 { return uint32(n >> sectorShift) }
|
||||
|
||||
func TestDispatch_WriteThenReadRoundTrip(t *testing.T) {
|
||||
rb := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})
|
||||
h := newTestHandler(rb)
|
||||
data := bytes.Repeat([]byte{0x5a}, 8192)
|
||||
if got := h.handle(context.Background(), request{op: ioOpWrite, startSector: 16, nrSectors: sectors(len(data))}, data); got != int32(len(data)) {
|
||||
t.Fatalf("write result %d, want %d", got, len(data))
|
||||
}
|
||||
if rb.WriteCount() != 1 || rb.WriteAt(0).Offset != 16<<sectorShift || !bytes.Equal(rb.WriteAt(0).Data, data) {
|
||||
t.Fatalf("backend write %+v, want offset %d and the request bytes", rb.WriteAt(0), 16<<sectorShift)
|
||||
}
|
||||
if rb.SyncCount() != 0 {
|
||||
t.Fatalf("a plain write synced %d times", rb.SyncCount())
|
||||
}
|
||||
out := make([]byte, len(data))
|
||||
if got := h.handle(context.Background(), request{op: ioOpRead, startSector: 16, nrSectors: sectors(len(out))}, out); got != int32(len(out)) {
|
||||
t.Fatalf("read result %d, want %d", got, len(out))
|
||||
}
|
||||
if !bytes.Equal(out, data) || rb.ReadAt(0).Offset != 16<<sectorShift {
|
||||
t.Fatalf("read back %x... at offset %d", out[:4], rb.ReadAt(0).Offset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatch_FlushSyncs(t *testing.T) {
|
||||
rb := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})
|
||||
h := newTestHandler(rb)
|
||||
if got := h.handle(context.Background(), request{op: ioOpFlush}, nil); got != 0 {
|
||||
t.Fatalf("flush result %d, want 0", got)
|
||||
}
|
||||
if rb.SyncCount() != 1 || rb.WriteCount() != 0 {
|
||||
t.Fatalf("flush: %d syncs %d writes, want exactly one sync", rb.SyncCount(), rb.WriteCount())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatch_WriteFUASyncsBeforeCompleting(t *testing.T) {
|
||||
rb := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})
|
||||
h := newTestHandler(rb)
|
||||
data := bytes.Repeat([]byte{1}, 4096)
|
||||
if got := h.handle(context.Background(), request{op: ioOpWrite, flags: ioFlagFUA, nrSectors: sectors(len(data))}, data); got != int32(len(data)) {
|
||||
t.Fatalf("FUA write result %d", got)
|
||||
}
|
||||
if rb.WriteCount() != 1 || rb.SyncCount() != 1 {
|
||||
t.Fatalf("FUA write: %d writes %d syncs, want 1 and 1", rb.WriteCount(), rb.SyncCount())
|
||||
}
|
||||
}
|
||||
|
||||
// failingBackend fails the selected operation.
|
||||
type failingBackend struct {
|
||||
failRead, failWrite, failSync, shortRead bool
|
||||
err error
|
||||
syncs, writes, reads int
|
||||
}
|
||||
|
||||
func (b *failingBackend) Read(_ context.Context, _ int64, p []byte) (int, error) {
|
||||
b.reads++
|
||||
if b.failRead {
|
||||
return 0, b.err
|
||||
}
|
||||
if b.shortRead {
|
||||
return len(p) - 1, nil
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (b *failingBackend) Write(_ context.Context, _ int64, p []byte) (int, error) {
|
||||
b.writes++
|
||||
if b.failWrite {
|
||||
return 0, b.err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (b *failingBackend) Sync(context.Context) error {
|
||||
b.syncs++
|
||||
if b.failSync {
|
||||
return b.err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestDispatch_BackendFailuresAreReportedNotAcknowledged(t *testing.T) {
|
||||
eio := -int32(syscall.EIO)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
b *failingBackend
|
||||
r request
|
||||
}{
|
||||
{"read error", &failingBackend{failRead: true, err: errors.New("boom")}, request{op: ioOpRead, nrSectors: 8}},
|
||||
{"short read", &failingBackend{shortRead: true}, request{op: ioOpRead, nrSectors: 8}},
|
||||
{"write error", &failingBackend{failWrite: true, err: errors.New("boom")}, request{op: ioOpWrite, nrSectors: 8}},
|
||||
{"flush error", &failingBackend{failSync: true, err: errors.New("boom")}, request{op: ioOpFlush}},
|
||||
{"FUA sync error", &failingBackend{failSync: true, err: errors.New("boom")}, request{op: ioOpWrite, flags: ioFlagFUA, nrSectors: 8}},
|
||||
{"stale primary", &failingBackend{failWrite: true, err: frontend.ErrStalePrimary}, request{op: ioOpWrite, nrSectors: 8}},
|
||||
{"backend closed", &failingBackend{failSync: true, err: frontend.ErrBackendClosed}, request{op: ioOpFlush}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newTestHandler(tc.b)
|
||||
if got := h.handle(context.Background(), tc.r, make([]byte, 4096)); got != eio {
|
||||
t.Fatalf("result %d, want -EIO (%d)", got, eio)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatch_OutOfRangeNeverTouchesTheBackend(t *testing.T) {
|
||||
einval := -int32(syscall.EINVAL)
|
||||
for _, r := range []request{
|
||||
{op: ioOpRead, startSector: testSize >> sectorShift, nrSectors: 1},
|
||||
{op: ioOpWrite, startSector: (testSize >> sectorShift) - 1, nrSectors: 2},
|
||||
{op: ioOpWrite, startSector: 1<<63 - 1, nrSectors: 8},
|
||||
} {
|
||||
b := &failingBackend{}
|
||||
if got := newTestHandler(b).handle(context.Background(), r, make([]byte, 4096)); got != einval {
|
||||
t.Fatalf("%+v: result %d, want -EINVAL", r, got)
|
||||
}
|
||||
if b.reads+b.writes+b.syncs != 0 {
|
||||
t.Fatalf("%+v reached the backend", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleNoPanic reports a panic in the handler as a test failure.
|
||||
func handleNoPanic(t *testing.T, h handler, r request, buf []byte) (res int32) {
|
||||
t.Helper()
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
t.Fatalf("handler panicked on %+v with a %d-byte buffer: %v", r, len(buf), p)
|
||||
}
|
||||
}()
|
||||
return h.handle(context.Background(), r, buf)
|
||||
}
|
||||
|
||||
func TestDispatch_BufferShorterThanRequestIsRefused(t *testing.T) {
|
||||
b := &failingBackend{}
|
||||
if got := handleNoPanic(t, newTestHandler(b), request{op: ioOpWrite, nrSectors: 16}, make([]byte, 4096)); got != -int32(syscall.EINVAL) {
|
||||
t.Fatalf("result %d, want -EINVAL for a request larger than its buffer", got)
|
||||
}
|
||||
if b.writes != 0 {
|
||||
t.Fatal("an oversized request reached the backend")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatch_UnsupportedOperations(t *testing.T) {
|
||||
for _, op := range []uint8{ioOpDiscard, ioOpWriteSame, ioOpWriteZeroes, 10, 18, 0xff} {
|
||||
b := &failingBackend{}
|
||||
if got := newTestHandler(b).handle(context.Background(), request{op: op, nrSectors: 8}, make([]byte, 4096)); got != -int32(syscall.EOPNOTSUPP) {
|
||||
t.Fatalf("op %d: result %d, want -EOPNOTSUPP", op, got)
|
||||
}
|
||||
if b.reads+b.writes+b.syncs != 0 {
|
||||
t.Fatalf("op %d reached the backend", op)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The counters the fsync gate reads: every received request is counted
|
||||
// by kind before the backend call, FUA writes separately, and failures.
|
||||
func TestDispatch_CountersCountReceivedRequests(t *testing.T) {
|
||||
c := &counters{}
|
||||
h := handler{backend: &failingBackend{failSync: true, err: errors.New("boom")}, size: testSize, stats: c}
|
||||
ctx := context.Background()
|
||||
buf := make([]byte, 4096)
|
||||
h.handle(ctx, request{op: ioOpRead, nrSectors: 8}, buf)
|
||||
h.handle(ctx, request{op: ioOpWrite, nrSectors: 8}, buf)
|
||||
h.handle(ctx, request{op: ioOpWrite, flags: ioFlagFUA, nrSectors: 8}, buf) // sync fails -> error
|
||||
h.handle(ctx, request{op: ioOpFlush}, nil) // sync fails -> error
|
||||
h.handle(ctx, request{op: ioOpFlush}, nil)
|
||||
h.handle(ctx, request{op: ioOpDiscard, nrSectors: 8}, buf) // -EOPNOTSUPP -> error
|
||||
got := c.snapshot()
|
||||
want := Stats{ReadRequests: 1, WriteRequests: 2, FUAWrites: 1, FlushRequests: 2, OtherRequests: 1, Errors: 4}
|
||||
if got != want {
|
||||
t.Fatalf("counters %+v, want %+v", got, want)
|
||||
}
|
||||
if (handler{backend: &failingBackend{}, size: testSize}).handle(ctx, request{op: ioOpFlush}, nil) != 0 {
|
||||
t.Fatal("an uncounted handler failed a flush")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Package ublk exposes a frontend.Backend as a local Linux block device
|
||||
// through the kernel ublk driver (/dev/ublkbN): io_uring command queues,
|
||||
// one server thread per hardware queue. It is a same-host alternative to
|
||||
// the NVMe/TCP loopback target.
|
||||
//
|
||||
// Request semantics match the NVMe frontend:
|
||||
// - READ and WRITE map to Backend.Read and Backend.Write;
|
||||
// - FLUSH maps to Backend.Sync;
|
||||
// - a WRITE carrying FUA is written and then synced before completing;
|
||||
// - any backend error completes the request with -EIO (fail-closed);
|
||||
// a range outside the device completes with -EINVAL without touching
|
||||
// the backend; other operations complete with -EOPNOTSUPP (the device
|
||||
// advertises no discard or write-zeroes support).
|
||||
//
|
||||
// Server crash or restart is fail-closed: the device is created without
|
||||
// UBLK_F_USER_RECOVERY, so when the server process dies the kernel aborts
|
||||
// outstanding and new I/O on /dev/ublkbN with errors; nothing is
|
||||
// acknowledged that the backend did not complete.
|
||||
//
|
||||
// A restarted server never reclaims a device left at its id: Start
|
||||
// refuses any pre-existing /dev/ublkcN with an error naming the id and
|
||||
// sends nothing to the kernel. Removing a leftover device is a separate
|
||||
// operator step, taken only after proving no server uses it: delete it
|
||||
// through the ublk control device (for example the ublksrv "ublk del -n N"
|
||||
// tool), or unload ublk_drv once no device is in use. Then start again;
|
||||
// the consumer must reopen /dev/ublkbN.
|
||||
package ublk
|
||||
@@ -0,0 +1,74 @@
|
||||
package ublk
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// refusePreExisting refuses a device id that is already present. There is
|
||||
// no automatic reclaim: deciding that another server's device is dead (a
|
||||
// device-info read plus a pid probe, then a numeric STOP/DEL) races a
|
||||
// replacement device created in between, and a pid probe from another PID
|
||||
// namespace proves nothing. Nothing is sent to the kernel here; removing a
|
||||
// leftover device is a separate operator step (see the package doc).
|
||||
func refusePreExisting(id uint32, exists bool) error {
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("ublk: device %d already exists (%s%d); refusing to start: it may belong to another server. "+
|
||||
"Remove it as a separate operator step once it is proven unused", id, charDevicePrefix, id)
|
||||
}
|
||||
|
||||
// controller runs one ublk control command (the device's control ring in
|
||||
// production; a recorder in tests).
|
||||
type controller interface {
|
||||
command(cmdOp uint32, devID uint32, buf []byte, data uint64) (int32, error)
|
||||
}
|
||||
|
||||
// settler is a queue being shut down: done closes when its thread has
|
||||
// exited, release frees the memory the kernel and the thread share.
|
||||
type settler interface {
|
||||
doneCh() <-chan struct{}
|
||||
release()
|
||||
name() string
|
||||
result() error // read only after doneCh is closed
|
||||
}
|
||||
|
||||
// settleQueues waits, until one shared deadline, for the queues to stop
|
||||
// and releases each one that did, returning the first error a stopped
|
||||
// queue's thread ended with. A queue that did not stop keeps its mappings:
|
||||
// its thread may still read descriptors or write buffers, so they are
|
||||
// leaked (fail closed) and the failure is returned.
|
||||
func settleQueues(qs []settler, timeout time.Duration) (leaked bool, err error) {
|
||||
var firstErr error
|
||||
deadline := time.NewTimer(timeout)
|
||||
defer deadline.Stop()
|
||||
expired := false
|
||||
for _, q := range qs {
|
||||
if !expired {
|
||||
select {
|
||||
case <-q.doneCh():
|
||||
q.release()
|
||||
if err := q.result(); err != nil && firstErr == nil {
|
||||
firstErr = fmt.Errorf("ublk: %s: %w", q.name(), err)
|
||||
}
|
||||
continue
|
||||
case <-deadline.C:
|
||||
expired = true
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-q.doneCh(): // stopped by now: safe to release
|
||||
q.release()
|
||||
if err := q.result(); err != nil && firstErr == nil {
|
||||
firstErr = fmt.Errorf("ublk: %s: %w", q.name(), err)
|
||||
}
|
||||
default:
|
||||
leaked = true
|
||||
if firstErr == nil {
|
||||
firstErr = fmt.Errorf("ublk: %s did not stop; its mappings are kept (leaked) while its thread may run", q.name())
|
||||
}
|
||||
}
|
||||
}
|
||||
return leaked, firstErr
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package ublk
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A device already present at our id is never reclaimed automatically:
|
||||
// Start refuses with an error naming the id (and refusePreExisting has no
|
||||
// way to send a command). An absent id is accepted.
|
||||
func TestRefusePreExisting_RefusesAnyExistingID(t *testing.T) {
|
||||
if err := refusePreExisting(7, false); err != nil {
|
||||
t.Fatalf("absent id refused: %v", err)
|
||||
}
|
||||
err := refusePreExisting(7, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "device 7") || !strings.Contains(err.Error(), "/dev/ublkc7") {
|
||||
t.Fatalf("err %v, want a refusal naming device 7", err)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeQueue struct {
|
||||
id int
|
||||
done chan struct{}
|
||||
released bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (q *fakeQueue) doneCh() <-chan struct{} { return q.done }
|
||||
func (q *fakeQueue) release() { q.released = true }
|
||||
func (q *fakeQueue) name() string { return fmt.Sprintf("queue %d", q.id) }
|
||||
func (q *fakeQueue) result() error { return q.err }
|
||||
|
||||
// A queue that did not stop keeps its mappings: its thread may still read
|
||||
// descriptors or write buffers, so they are leaked, never unmapped, and
|
||||
// the shutdown reports the failure. Stopped queues are released.
|
||||
func TestSettleQueues_NeverReleasesAQueueThatMayStillRun(t *testing.T) {
|
||||
stopped := &fakeQueue{id: 0, done: make(chan struct{})}
|
||||
close(stopped.done)
|
||||
stuck := &fakeQueue{id: 1, done: make(chan struct{})}
|
||||
late := &fakeQueue{id: 2, done: make(chan struct{})}
|
||||
close(late.done)
|
||||
leaked, err := settleQueues([]settler{stopped, stuck, late}, 50*time.Millisecond)
|
||||
if !leaked || err == nil || !strings.Contains(err.Error(), "queue 1") {
|
||||
t.Fatalf("err %v, want queue 1 reported", err)
|
||||
}
|
||||
if stuck.released {
|
||||
t.Fatal("a queue that may still run had its mappings released")
|
||||
}
|
||||
if !stopped.released || !late.released {
|
||||
t.Fatalf("stopped queues not released: %v %v", stopped.released, late.released)
|
||||
}
|
||||
}
|
||||
|
||||
// A queue thread that ended abnormally (its ring failed, or closing the
|
||||
// ring failed) reports that error through the shutdown.
|
||||
func TestSettleQueues_SurfacesAQueueThreadError(t *testing.T) {
|
||||
q := &fakeQueue{id: 3, done: make(chan struct{}), err: errors.New("io_uring_enter: EBADF")}
|
||||
close(q.done)
|
||||
leaked, err := settleQueues([]settler{q}, time.Second)
|
||||
if leaked || err == nil || !strings.Contains(err.Error(), "EBADF") {
|
||||
t.Fatalf("err %v, want the queue thread's error surfaced", err)
|
||||
}
|
||||
if !q.released {
|
||||
t.Fatal("a stopped queue was not released")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
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 targetDevice
|
||||
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
closed bool // under mu: Close was called
|
||||
}
|
||||
|
||||
// targetDevice is what Target needs from a running device.
|
||||
type targetDevice interface {
|
||||
Path() string
|
||||
Stats() Stats
|
||||
Close() error
|
||||
}
|
||||
|
||||
// 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.closed {
|
||||
return "", errors.New("ublk: target closed; a closed target never starts a device")
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// Stats returns the device's request counters (zero before Start).
|
||||
func (t *Target) Stats() Stats {
|
||||
t.mu.Lock()
|
||||
d := t.device
|
||||
t.mu.Unlock()
|
||||
if d == nil {
|
||||
return Stats{}
|
||||
}
|
||||
return d.Stats()
|
||||
}
|
||||
|
||||
// Close stops and deletes the device. It is idempotent: the device is
|
||||
// closed once, and every caller, concurrent or later, gets that result.
|
||||
func (t *Target) Close() error {
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
t.mu.Lock()
|
||||
t.closed = true // a later Start refuses; a running Start finishes first (it holds mu)
|
||||
t.mu.Unlock()
|
||||
t.closeOnce.Do(func() {
|
||||
t.mu.Lock()
|
||||
d := t.device
|
||||
t.mu.Unlock()
|
||||
if d != nil {
|
||||
t.closeErr = d.Close()
|
||||
}
|
||||
})
|
||||
return t.closeErr
|
||||
}
|
||||
|
||||
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,117 @@
|
||||
package ublk
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type fakeDevice struct {
|
||||
closes atomic.Int32
|
||||
err error
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (d *fakeDevice) Path() string { return "/dev/ublkb9" }
|
||||
func (d *fakeDevice) Stats() Stats { return Stats{} }
|
||||
func (d *fakeDevice) Close() error {
|
||||
d.closes.Add(1)
|
||||
<-d.release
|
||||
return d.err
|
||||
}
|
||||
|
||||
// Close is idempotent: concurrent and repeated callers all get the first
|
||||
// close's result (never a nil while it is pending or after it failed),
|
||||
// and the device is closed once.
|
||||
func TestTarget_CloseGivesEveryCallerTheSameResult(t *testing.T) {
|
||||
dev := &fakeDevice{err: errors.New("queue 0 did not stop"), release: make(chan struct{})}
|
||||
tg := &Target{cfg: TargetConfig{Provider: testback.NewStaticProvider(nil)}, device: dev}
|
||||
results := make(chan error, 3)
|
||||
for i := 0; i < 3; i++ {
|
||||
go func() { results <- tg.Close() }()
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
close(dev.release)
|
||||
for i := 0; i < 3; i++ {
|
||||
select {
|
||||
case err := <-results:
|
||||
if err == nil || err.Error() != dev.err.Error() {
|
||||
t.Fatalf("concurrent Close %d returned %v, want %v", i, err, dev.err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("a concurrent Close did not return")
|
||||
}
|
||||
}
|
||||
if err := tg.Close(); err == nil || err.Error() != dev.err.Error() {
|
||||
t.Fatalf("repeated Close returned %v, want %v", err, dev.err)
|
||||
}
|
||||
if n := dev.closes.Load(); n != 1 {
|
||||
t.Fatalf("device closed %d times, want once", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Close before Start must not leave a device nobody can close: a Start
|
||||
// after Close refuses before creating anything.
|
||||
func TestTarget_StartAfterCloseRefuses(t *testing.T) {
|
||||
tg := NewTarget(TargetConfig{Provider: testback.NewStaticProvider(nil), BlockSize: 4096, VolumeSize: 1 << 20, DevID: -1})
|
||||
if err := tg.Close(); err != nil {
|
||||
t.Fatalf("Close before Start: %v", err)
|
||||
}
|
||||
_, err := tg.Start()
|
||||
if err == nil || !strings.Contains(err.Error(), "closed") {
|
||||
t.Fatalf("Start after Close: %v, want a refusal because the target is closed", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//go:build linux
|
||||
|
||||
package ublk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type cmdRecorder struct{ cmds []uint32 }
|
||||
|
||||
func (c *cmdRecorder) command(cmdOp uint32, devID uint32, buf []byte, data uint64) (int32, error) {
|
||||
c.cmds = append(c.cmds, cmdOp)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (c *cmdRecorder) deleted() bool {
|
||||
for _, op := range c.cmds {
|
||||
if op == uCmdDelDev {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// The Close path deletes its device when every queue thread has exited,
|
||||
// even if one of them ended with an error (the error is reported); only a
|
||||
// queue whose thread is still running keeps its mappings and suppresses
|
||||
// DEL_DEV.
|
||||
func TestTeardown_DeletesTheDeviceUnlessAQueueIsStillRunning(t *testing.T) {
|
||||
stoppedWithErr := &fakeQueue{id: 0, done: make(chan struct{}), err: errors.New("io_uring_enter: EBADF")}
|
||||
close(stoppedWithErr.done)
|
||||
d := &Device{devID: 4, path: "/dev/ublkb4", ctrlFD: -1, charFD: -1}
|
||||
ctl := &cmdRecorder{}
|
||||
err := d.teardownWith([]settler{stoppedWithErr}, ctl, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "EBADF") {
|
||||
t.Fatalf("teardown err %v, want the queue error reported", err)
|
||||
}
|
||||
if !ctl.deleted() {
|
||||
t.Fatalf("a device whose queues all stopped was not deleted (commands %v)", ctl.cmds)
|
||||
}
|
||||
|
||||
running := &fakeQueue{id: 1, done: make(chan struct{})}
|
||||
d2 := &Device{devID: 5, path: "/dev/ublkb5", ctrlFD: -1, charFD: -1}
|
||||
ctl2 := &cmdRecorder{}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- d2.teardownWith([]settler{running}, ctl2, true) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil || ctl2.deleted() || running.released {
|
||||
t.Fatalf("running queue: err %v deleted %v released %v; want an error, no DEL_DEV, mappings kept", err, ctl2.deleted(), running.released)
|
||||
}
|
||||
case <-time.After(queueStopTimeout + 5*time.Second):
|
||||
t.Fatal("teardown did not return")
|
||||
}
|
||||
}
|
||||
|
||||
// A completion that is neither a new request nor the expected abort ends
|
||||
// the tag and is reported as the queue's error, never dropped silently.
|
||||
func TestQueue_UnexpectedCompletionIsReported(t *testing.T) {
|
||||
q := &queue{id: 0, depth: 1, ioBytes: 4096, descs: make([]byte, ioDescSize), bufs: make([]byte, 4096), h: handler{backend: &failingBackend{}, size: testSize}}
|
||||
commits := 0
|
||||
commit := func(int, int32) error { commits++; return nil }
|
||||
|
||||
still, err := q.onCQE(context.Background(), cqe{UserData: 0, Res: ioResAbort}, commit)
|
||||
if still || err != nil || q.err != nil || commits != 0 {
|
||||
t.Fatalf("abort: still=%v err=%v q.err=%v commits=%d, want the tag ended quietly", still, err, q.err, commits)
|
||||
}
|
||||
still, err = q.onCQE(context.Background(), cqe{UserData: 0, Res: -int32(syscall.EIO)}, commit)
|
||||
if still || commits != 0 {
|
||||
t.Fatalf("unexpected result: still=%v commits=%d, want the tag ended", still, commits)
|
||||
}
|
||||
if q.err == nil || !strings.Contains(q.err.Error(), "-5") {
|
||||
t.Fatalf("unexpected completion -EIO not reported (q.err %v, err %v)", q.err, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package ublk
|
||||
|
||||
import "unsafe"
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// bytesOf views a fixed-size struct as bytes (an inline command or a
|
||||
// command buffer the kernel reads or fills).
|
||||
func bytesOf[T any](v *T) []byte {
|
||||
return unsafe.Slice((*byte)(unsafe.Pointer(v)), unsafe.Sizeof(*v))
|
||||
}
|
||||
|
||||
// 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,218 @@
|
||||
//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
|
||||
|
||||
// enter is io_uring_enter (a test may wrap it): it returns how many
|
||||
// SQEs the kernel consumed.
|
||||
enter func(fd int, toSubmit, minComplete uint32, flags uintptr) (int, unix.Errno)
|
||||
}
|
||||
|
||||
func sysEnter(fd int, toSubmit, minComplete uint32, flags uintptr) (int, unix.Errno) {
|
||||
n, _, errno := unix.Syscall6(unix.SYS_IO_URING_ENTER, uintptr(fd), uintptr(toSubmit), uintptr(minComplete), flags, 0, 0)
|
||||
return int(n), errno
|
||||
}
|
||||
|
||||
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, enter: sysEnter}
|
||||
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, makes sure the kernel has
|
||||
// consumed every one of them (a short io_uring_enter leaves the rest in
|
||||
// the ring: they are offered again), then waits for at least minComplete
|
||||
// completions. A call that consumes nothing is an error: the unsubmitted
|
||||
// SQEs would otherwise be reported as submitted.
|
||||
func (r *uring) submitAndWait(minComplete uint32) error {
|
||||
atomic.StoreUint32(r.sqTail, *r.sqTail+r.pending)
|
||||
r.pending = 0
|
||||
for {
|
||||
outstanding := atomic.LoadUint32(r.sqTail) - atomic.LoadUint32(r.sqHead)
|
||||
if outstanding == 0 {
|
||||
break
|
||||
}
|
||||
n, errno := r.enter(r.fd, outstanding, 0, 0)
|
||||
switch {
|
||||
case errno == unix.EINTR:
|
||||
continue
|
||||
case errno != 0:
|
||||
return fmt.Errorf("ublk: io_uring_enter: %w", errno)
|
||||
case n == 0 && atomic.LoadUint32(r.sqTail)-atomic.LoadUint32(r.sqHead) == outstanding:
|
||||
return fmt.Errorf("ublk: io_uring_enter consumed none of %d SQEs", outstanding)
|
||||
}
|
||||
}
|
||||
if minComplete == 0 {
|
||||
return nil
|
||||
}
|
||||
for {
|
||||
_, errno := r.enter(r.fd, 0, minComplete, enterGetEvents)
|
||||
switch errno {
|
||||
case 0:
|
||||
return nil
|
||||
case unix.EINTR:
|
||||
continue
|
||||
default:
|
||||
return fmt.Errorf("ublk: io_uring_enter wait: %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
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//go:build linux
|
||||
|
||||
package ublk
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
"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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newTestRing returns a ring, or skips where io_uring is unavailable.
|
||||
func newTestRing(t *testing.T) *uring {
|
||||
t.Helper()
|
||||
r, err := newURing(8)
|
||||
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)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// submitWithin runs submitAndWait and reports false if it does not return
|
||||
// in time (lost SQEs would leave it waiting forever). A ring whose call
|
||||
// did not return is left open: its goroutine may still be using it.
|
||||
func submitWithin(r *uring, minComplete uint32, d time.Duration) (error, bool) {
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- r.submitAndWait(minComplete) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err, true
|
||||
case <-time.After(d):
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// A short submission (the kernel consumed fewer SQEs than offered) must
|
||||
// not lose the rest: every prepared SQE is submitted before waiting. The
|
||||
// wrapper lets the kernel take at most one SQE per call and returns
|
||||
// without waiting, as a short io_uring_enter does.
|
||||
func TestURing_ShortSubmissionSubmitsTheRest(t *testing.T) {
|
||||
r := newTestRing(t)
|
||||
var calls atomic.Int32
|
||||
r.enter = func(fd int, toSubmit, minComplete uint32, flags uintptr) (int, unix.Errno) {
|
||||
calls.Add(1)
|
||||
if toSubmit > 1 {
|
||||
return sysEnter(fd, 1, 0, 0) // short: one SQE taken, no wait
|
||||
}
|
||||
return sysEnter(fd, toSubmit, minComplete, flags)
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
if err := r.prepare(opNop, -1, 0, nil, uint64(i)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
err, returned := submitWithin(r, 4, 5*time.Second)
|
||||
if !returned {
|
||||
t.Fatalf("submitAndWait(4) did not return within 5s after a short submission: SQEs were lost (%d enter calls)", calls.Load())
|
||||
}
|
||||
defer r.close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := r.reap(nil); len(got) != 4 {
|
||||
t.Fatalf("%d completions after a short submission (%d enter calls), want all 4", len(got), calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A submission the kernel never consumes is an error, never a silent
|
||||
// success and never an endless retry.
|
||||
func TestURing_SubmissionWithNoProgressFails(t *testing.T) {
|
||||
r := newTestRing(t)
|
||||
r.enter = func(int, uint32, uint32, uintptr) (int, unix.Errno) { return 0, 0 }
|
||||
if err := r.prepare(opNop, -1, 0, nil, 9); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err, returned := submitWithin(r, 0, 5*time.Second)
|
||||
if !returned {
|
||||
t.Fatal("submitAndWait did not return within 5s when the kernel consumed nothing (endless retry)")
|
||||
}
|
||||
defer r.close()
|
||||
if err == nil {
|
||||
t.Fatal("a submission the kernel never consumed was reported as submitted")
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/ublk"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
)
|
||||
|
||||
@@ -45,6 +46,10 @@ import (
|
||||
// -> 200 JSON read-only NVMe target counters (when a TCP target is wired)
|
||||
// -> 404 (wrong volume or no TCP source)
|
||||
//
|
||||
// GET /status/ublk?volume=<id>
|
||||
// -> 200 JSON read-only ublk device request counters (when wired)
|
||||
// -> 404 (wrong volume or no ublk device)
|
||||
//
|
||||
// The server binds on a caller-supplied addr (":0" for tests);
|
||||
// the actual bound addr is available via Addr() after Start.
|
||||
type StatusServer struct {
|
||||
@@ -60,6 +65,7 @@ type StatusServer struct {
|
||||
peerSource peerStatusSource
|
||||
durableSource durableStatusSource
|
||||
nvmeSource nvmeStatusSource
|
||||
ublkSource ublkStatusSource
|
||||
runtimeSource runtimeRecoverySource
|
||||
frontendCaps []FrontendTransportCapability
|
||||
nvmePending bool // configured listener has not started (or is stopping)
|
||||
@@ -89,6 +95,10 @@ type nvmeStatusSource interface {
|
||||
Stats() nvme.Stats
|
||||
}
|
||||
|
||||
type ublkStatusSource interface {
|
||||
Stats() ublk.Stats
|
||||
}
|
||||
|
||||
type runtimeRecoverySource interface {
|
||||
StartRuntimeRecovery(context.Context, replication.RuntimeRecoveryRequest) error
|
||||
RuntimeRecoveryStatus(context.Context, replication.RuntimeRecoveryRequest) (replication.RuntimeRecoveryStatus, error)
|
||||
@@ -150,6 +160,12 @@ type NVMeStatus struct {
|
||||
Stats nvme.Stats `json:"stats"`
|
||||
}
|
||||
|
||||
// UblkStatus is the /status/ublk body: the ublk device's request counters.
|
||||
type UblkStatus struct {
|
||||
VolumeID string `json:"volumeID"`
|
||||
Stats ublk.Stats `json:"stats"`
|
||||
}
|
||||
|
||||
const (
|
||||
AuthorityRolePrimary = "primary"
|
||||
AuthorityRoleSuperseded = "superseded"
|
||||
@@ -255,6 +271,14 @@ func (s *StatusServer) SetDurableStatusSource(src durableStatusSource) {
|
||||
s.durableSource = src
|
||||
}
|
||||
|
||||
// SetUblkStatusSource enables /status/ublk with the ublk device's counters.
|
||||
// It may be called before or after Start.
|
||||
func (s *StatusServer) SetUblkStatusSource(src ublkStatusSource) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.ublkSource = src
|
||||
}
|
||||
|
||||
// SetNVMeStatusSource enables /status/nvme with a read-only target snapshot.
|
||||
// It may be called before or after Start.
|
||||
func (s *StatusServer) SetNVMeStatusSource(src nvmeStatusSource) {
|
||||
@@ -307,6 +331,7 @@ func (s *StatusServer) Start(addr string) (string, error) {
|
||||
mux.HandleFunc("/status/peers", s.handleStatusPeers)
|
||||
mux.HandleFunc("/status/durable", s.handleStatusDurable)
|
||||
mux.HandleFunc("/status/nvme", s.handleStatusNVMe)
|
||||
mux.HandleFunc("/status/ublk", s.handleStatusUblk)
|
||||
mux.HandleFunc("/status/frontend-capabilities", s.handleFrontendCapabilities)
|
||||
if s.recoveryEnabled {
|
||||
mux.HandleFunc("/status/recovery", s.handleStatusRecovery)
|
||||
@@ -394,6 +419,32 @@ func (s *StatusServer) handleFrontendCapabilities(w http.ResponseWriter, r *http
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StatusServer) handleStatusUblk(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) {
|
||||
http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
vol := r.URL.Query().Get("volume")
|
||||
if vol == "" {
|
||||
http.Error(w, "missing volume query param", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
p := s.statusProjection()
|
||||
if p.VolumeID != vol {
|
||||
http.Error(w, fmt.Sprintf("volume %q not served by this host (serves %q)", vol, p.VolumeID), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
src := s.ublkSource
|
||||
s.mu.Unlock()
|
||||
if src == nil {
|
||||
http.Error(w, "ublk status source unavailable", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(UblkStatus{VolumeID: p.VolumeID, Stats: src.Stats()})
|
||||
}
|
||||
|
||||
func (s *StatusServer) handleStatusNVMe(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) {
|
||||
http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden)
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/ublk"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
@@ -1133,3 +1134,46 @@ func containsString(values []string, want string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type stubUblkStatusSource struct{ stats ublk.Stats }
|
||||
|
||||
func (s stubUblkStatusSource) Stats() ublk.Stats { return s.stats }
|
||||
|
||||
func TestStatusServer_UblkStatusEndpoint(t *testing.T) {
|
||||
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
|
||||
addr, err := s.Start("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
defer func() { _ = s.Close(context.Background()) }()
|
||||
resp, err := http.Get("http://" + addr + "/status/ublk?volume=v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("without a ublk device: %d, want 404", resp.StatusCode)
|
||||
}
|
||||
s.SetUblkStatusSource(stubUblkStatusSource{stats: ublk.Stats{FlushRequests: 4002, FUAWrites: 3, WriteRequests: 9}})
|
||||
for _, tc := range []struct {
|
||||
vol string
|
||||
code int
|
||||
}{{"v2", http.StatusNotFound}, {"v1", http.StatusOK}} {
|
||||
resp, err := http.Get("http://" + addr + "/status/ublk?volume=" + tc.vol)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.StatusCode != tc.code {
|
||||
resp.Body.Close()
|
||||
t.Fatalf("volume %s: %d, want %d", tc.vol, resp.StatusCode, tc.code)
|
||||
}
|
||||
if tc.code == http.StatusOK {
|
||||
var body UblkStatus
|
||||
err := json.NewDecoder(resp.Body).Decode(&body)
|
||||
if err != nil || body.VolumeID != "v1" || body.Stats.FlushRequests != 4002 || body.Stats.FUAWrites != 3 {
|
||||
t.Fatalf("body %+v err %v", body, err)
|
||||
}
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user