diff --git a/seaweed-block/core/frontend/ublk/device_linux.go b/seaweed-block/core/frontend/ublk/device_linux.go index 16b9bce72a..0060f179f2 100644 --- a/seaweed-block/core/frontend/ublk/device_linux.go +++ b/seaweed-block/core/frontend/ublk/device_linux.go @@ -74,13 +74,9 @@ func Start(cfg Config) (*Device, error) { 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)) - } + _, statErr := os.Stat(charDevicePrefix + strconv.Itoa(cfg.DevID)) + if err := reclaimStale(d, id, statErr == nil, processAlive); err != nil { + return fail(err) } } @@ -171,14 +167,11 @@ func (d *Device) teardown(added bool) error { 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() + qs := make([]settler, len(d.queues)) + for i, q := range d.queues { + qs[i] = q } + note(settleQueues(qs, queueStopTimeout)) if d.charFD >= 0 { note(unix.Close(d.charFD)) d.charFD = -1 @@ -193,6 +186,27 @@ func (d *Device) teardown(added bool) error { return firstErr } +// queueStopTimeout bounds how long Close waits for the queue threads. +const queueStopTimeout = 10 * time.Second + +// command implements controller for reclaimStale. +func (d *Device) command(cmdOp uint32, devID uint32, buf []byte, data uint64) (int32, error) { + return d.ctrlCommand(cmdOp, devID, buf, data) +} + +// processAlive reports whether pid names a live process: signal 0 is +// delivered (or refused with EPERM: it exists), ESRCH means it is gone. +func processAlive(pid int32) (bool, error) { + switch err := unix.Kill(int(pid), 0); err { + case nil, unix.EPERM: + return true, nil + case unix.ESRCH: + return false, nil + default: + return false, fmt.Errorf("ublk: probe pid %d: %w", pid, err) + } +} + // 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) { @@ -312,6 +326,9 @@ func (q *queue) run(ctx context.Context) { } } +func (q *queue) doneCh() <-chan struct{} { return q.done } +func (q *queue) name() string { return "queue " + strconv.Itoa(q.id) } + func (q *queue) release() { if q.descs != nil { _ = unix.Munmap(q.descs) diff --git a/seaweed-block/core/frontend/ublk/lifecycle.go b/seaweed-block/core/frontend/ublk/lifecycle.go new file mode 100644 index 0000000000..47ad69fe1b --- /dev/null +++ b/seaweed-block/core/frontend/ublk/lifecycle.go @@ -0,0 +1,50 @@ +package ublk + +import ( + "fmt" + "time" +) + +// 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) +} + +// reclaimStale handles a device already present at id before this server +// creates its own. RED placeholder: removes it unconditionally. +func reclaimStale(c controller, id uint32, exists bool, alive func(pid int32) (bool, error)) error { + if !exists { + return nil + } + _, _ = c.command(uCmdStopDev, id, nil, 0) + if _, err := c.command(uCmdDelDev, id, nil, 0); err != nil { + return fmt.Errorf("ublk: delete stale device %d: %w", id, err) + } + return nil +} + +// 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 +} + +// settleQueues waits for the queues to stop. RED placeholder: releases +// every queue even when it did not stop in time. +func settleQueues(qs []settler, timeout time.Duration) error { + var firstErr error + for _, q := range qs { + select { + case <-q.doneCh(): + case <-time.After(timeout): + if firstErr == nil { + firstErr = fmt.Errorf("ublk: %s did not stop", q.name()) + } + } + q.release() + } + return firstErr +} diff --git a/seaweed-block/core/frontend/ublk/lifecycle_test.go b/seaweed-block/core/frontend/ublk/lifecycle_test.go new file mode 100644 index 0000000000..3932070d96 --- /dev/null +++ b/seaweed-block/core/frontend/ublk/lifecycle_test.go @@ -0,0 +1,110 @@ +package ublk + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" + "unsafe" +) + +// recordingController records control commands; GET_DEV_INFO fills the +// device info with srvPID (or fails with infoErr). +type recordingController struct { + cmds []uint32 + srvPID int32 + infoErr error +} + +func (c *recordingController) command(cmdOp uint32, devID uint32, buf []byte, data uint64) (int32, error) { + c.cmds = append(c.cmds, cmdOp) + if cmdOp == uCmdGetDevInfo { + if c.infoErr != nil { + return 0, c.infoErr + } + if len(buf) >= int(unsafe.Sizeof(devInfo{})) { + info := (*devInfo)(unsafe.Pointer(&buf[0])) + info.DevID, info.SrvPID = devID, c.srvPID + } + } + return 0, nil +} + +func (c *recordingController) destructive() []string { + var out []string + for _, op := range c.cmds { + switch op { + case uCmdStopDev: + out = append(out, "STOP") + case uCmdDelDev: + out = append(out, "DEL") + } + } + return out +} + +// A device found at our id is deleted only with proof that its server is +// dead; when its owner may be alive, or cannot be established, Start +// refuses and touches nothing. +func TestReclaimStale_DeletesOnlyWithProofTheOwnerIsDead(t *testing.T) { + dead := func(int32) (bool, error) { return false, nil } + live := func(int32) (bool, error) { return true, nil } + unknown := func(int32) (bool, error) { return false, errors.New("cannot signal") } + for _, tc := range []struct { + name string + exists bool + c *recordingController + alive func(int32) (bool, error) + refuse bool + wantDest string + }{ + {"no device", false, &recordingController{srvPID: 42}, dead, false, ""}, + {"owner process gone", true, &recordingController{srvPID: 42}, dead, false, "STOP,DEL"}, + {"owner alive", true, &recordingController{srvPID: 42}, live, true, ""}, + {"owner liveness unknown", true, &recordingController{srvPID: 42}, unknown, true, ""}, + {"never started (no owner pid)", true, &recordingController{srvPID: 0}, dead, true, ""}, + {"device info unreadable", true, &recordingController{infoErr: errors.New("EPERM")}, dead, true, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + err := reclaimStale(tc.c, 7, tc.exists, tc.alive) + if tc.refuse != (err != nil) { + t.Fatalf("refused=%v (err %v), want refused=%v", err != nil, err, tc.refuse) + } + if got := strings.Join(tc.c.destructive(), ","); got != tc.wantDest { + t.Fatalf("destructive commands %q, want %q", got, tc.wantDest) + } + }) + } +} + +type fakeQueue struct { + id int + done chan struct{} + released bool +} + +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) } + +// 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) + err := settleQueues([]settler{stopped, stuck, late}, 50*time.Millisecond) + if 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) + } +} diff --git a/seaweed-block/core/frontend/ublk/uring_linux.go b/seaweed-block/core/frontend/ublk/uring_linux.go index 222160a104..618c30ce5d 100644 --- a/seaweed-block/core/frontend/ublk/uring_linux.go +++ b/seaweed-block/core/frontend/ublk/uring_linux.go @@ -68,6 +68,15 @@ type uring struct { 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) { @@ -77,7 +86,7 @@ func newURing(entries uint32) (*uring, error) { if errno != 0 { return nil, fmt.Errorf("ublk: io_uring_setup: %w", errno) } - r := &uring{fd: int(fd), sqEntries: p.SqEntries} + 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 @@ -144,7 +153,7 @@ func (r *uring) submitAndWait(minComplete uint32) error { flags = enterGetEvents } for { - _, _, errno := unix.Syscall6(unix.SYS_IO_URING_ENTER, uintptr(r.fd), uintptr(toSubmit), uintptr(minComplete), flags, 0, 0) + _, errno := r.enter(r.fd, toSubmit, minComplete, flags) switch errno { case 0: return nil diff --git a/seaweed-block/core/frontend/ublk/uring_linux_test.go b/seaweed-block/core/frontend/ublk/uring_linux_test.go index 0107bda3e9..49e30a9a1d 100644 --- a/seaweed-block/core/frontend/ublk/uring_linux_test.go +++ b/seaweed-block/core/frontend/ublk/uring_linux_test.go @@ -58,3 +58,46 @@ func TestURing_NopRoundTrip(t *testing.T) { } } } + +// A short submission (the kernel consumed fewer SQEs than offered) must +// not lose the rest: every prepared SQE is submitted before waiting, or +// the call fails. 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, 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) + } + defer r.close() + calls := 0 + r.enter = func(fd int, toSubmit, minComplete uint32, flags uintptr) (int, unix.Errno) { + calls++ + 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) + } + } + if err := r.submitAndWait(4); 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) + } + + // No progress at all is an error, never a silent success. + 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) + } + if err := r.submitAndWait(0); err == nil { + t.Fatal("a submission the kernel never consumed was reported as submitted") + } +}