mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
T2 checkpoint 6: NVMe/TCP minimal slice — L0 green + boundary guard
Checkpoint 6 mirrors iSCSI checkpoints 1+2 for the NVMe/TCP
protocol. L1/L2 for NVMe come in later checkpoints.
cmd/blockvolume/main.go
Small follow-up on T2A-iSCSI-provisional sign-off note:
emit a stderr line "iscsi enabled: t1-readiness auto-enabled"
when --iscsi-listen implicitly flips the readiness bridge on.
Keeps operators from misreading the auto-enable as silent.
core/frontend/nvme/errors.go (NEW)
NVMe status vocabulary for T2:
SCT types (Generic, CommandSpecific, MediaDataInteg, PathRelated,
VendorSpecific)
Generic SCs: Success, InvalidOpcode, InvalidField, InternalError,
LBAOutOfRange, CapacityExceeded, NamespaceNotReady.
PathRelated SCs: ANA PersistLoss / Inaccessible / Transition.
StatusError type carrying (SCT, SC, Reason) with Error() and
EncodeStatusField() that packs SCT/SC into the 16-bit CQE
status field (SC<<1 | SCT<<9 per NVMe base spec §4.6.1).
Canonical constructors:
NewStaleLineage() -> SCT=3 (PathRelated) + SC=0x03 (ANA Transition)
— semantic match for authority-move
transition; Linux nvme driver treats this
as a path-retry condition.
NewBackendClosed() -> SCT=3 + SC=0x02 (ANA Inaccessible)
— distinct from stale-lineage so logs
disambiguate the two fail modes.
NewInvalidField(sc, reason) -> SCT=0 + caller SC.
Symmetric with iscsi/errors.go's ALUA 0x04/0x0A vs 0x04/0x00
distinction (see earlier checkpoint 2 note).
core/frontend/nvme/io.go (NEW)
IOHandler dispatches NVMe IO Read/Write/Flush to a
frontend.Backend. Opcode set intentionally minimal for L0 scope;
Identify / SetFeatures / fabric admin land with capsule framing
in a later checkpoint.
IOCommand is the normalized form (Opcode, NSID, SLBA, NLB, Data).
IOResult.AsError() returns nil on Success or a *StatusError.
mapBackendError: ErrStalePrimary -> ANA Transition;
ErrBackendClosed -> ANA Inaccessible;
other -> Internal Error (fail-closed).
LBA-range + NSID + short-data validation BEFORE backend call
(fail closed). NLB=0 is invalid in our one-based form (zero-based
on wire, one-based in IOCommand for readability).
core/frontend/nvme/io_test.go (QA-owned, test-spec §4 n1..n4)
T2.L0.n1 CommandReadWrite_UsesFrontendBackend: Read + Write
route through RecordingBackend, single invocation, exact
offset + data.
T2.L0.n2 StaleWrite_ReturnsProtocolFailure: non-Success,
SCT=3 SC=3 (ANA Transition).
T2.L0.n3 StaleRead_ReturnsProtocolFailure: non-Success,
zero data bytes (MUST NOT leak stale bytes), ANA Transition.
T2.L0.n4 InvalidInput_FailsClosed: table-driven — LBA past
end, LBA overflow, short data, NLB=0, unknown NSID. Each
fails at handler, backend never invoked.
Plus sw-added regressions:
BackendClosed_DistinctFromStale pins the ANA Transition vs
ANA Inaccessible distinction.
UnknownOpcode_ReturnsInvalidOpcode (fail-closed on 0x7f).
Flush_SuccessInT2Scope (no-op).
IOResult.AsError_NilOnSuccess + SupportsErrorsAs.
core/frontend/nvme/boundary_guard_test.go (QA-owned, test-spec n5+n6)
T2.L0.n5 + n6 AST guard: full-parse + alias-resolution (same
shape as iSCSI's boundary guard). Extends PCDD-STUFFING-001
coverage to core/frontend/nvme. No core/authority, no
core/adapter, no authority-minting composite literal, no
dot-import bypass.
Tests green (no regressions):
core/frontend/nvme: 17 tests (errors 7 + boundary 1 + io 9)
core/frontend/iscsi: unchanged (31)
All other packages: unchanged.
Sign-off tier: T2B-NVMe checkpoint 6 (L0 foundation). L1 + L2
arrive in checkpoints 7-8; T2B-NVMe-provisional pending L2-harness
(checkpoint 8).
This commit is contained in:
1 parent
15e049d79a
commit
28e9636edb
6 files changed
+878
-2
No files matched your search
@@ -96,8 +96,12 @@ func parseFlags(args []string) (flags, error) {
|
||||
// iSCSI needs a Healthy adapter projection to open a
|
||||
// memback backend. Auto-enable the T1 readiness bridge
|
||||
// rather than failing — safer default for the beta
|
||||
// product host (operator can still set --t1-readiness=false
|
||||
// explicitly to surface a configuration error).
|
||||
// product host. Emits a one-line stderr notice so
|
||||
// operators don't misread the auto-enable as an
|
||||
// invisible side effect.
|
||||
if !f.enableT1Readiness {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: iscsi enabled: t1-readiness auto-enabled")
|
||||
}
|
||||
f.enableT1Readiness = true
|
||||
}
|
||||
return f, nil
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// Ownership: QA (from sketch-approved test spec v3-phase-15-t2-test-spec.md for T2 First Real Frontends).
|
||||
// sw may NOT modify this file without architect approval via §8B.4 Discovery Bridge.
|
||||
// See: sw-block/design/v3-phase-15-t2-test-spec.md
|
||||
// Maps to ledger rows: PCDD-STUFFING-001 (extended to NVMe package)
|
||||
//
|
||||
// Test layer: Unit (AST)
|
||||
// Protocol: NVMe/TCP
|
||||
// Bounded fate: core/frontend/nvme production code must not
|
||||
// import core/authority or core/adapter, and must not construct
|
||||
// any authority-minting composite literal. Same invariants as
|
||||
// the iSCSI boundary guard — extends PCDD-STUFFING-001 coverage
|
||||
// to the NVMe package.
|
||||
package nvme_test
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var forbiddenImports = []string{
|
||||
"github.com/seaweedfs/seaweed-block/core/authority",
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter",
|
||||
}
|
||||
|
||||
type forbiddenMinter struct {
|
||||
importPath string
|
||||
typeName string
|
||||
}
|
||||
|
||||
var forbiddenMinters = []forbiddenMinter{
|
||||
{importPath: "github.com/seaweedfs/seaweed-block/core/adapter", typeName: "AssignmentInfo"},
|
||||
{importPath: "github.com/seaweedfs/seaweed-block/core/adapter", typeName: "AssignmentAsk"},
|
||||
{importPath: "github.com/seaweedfs/seaweed-block/core/authority", typeName: "AssignmentAsk"},
|
||||
{importPath: "github.com/seaweedfs/seaweed-block/core/authority", typeName: "DurableRecord"},
|
||||
{importPath: "github.com/seaweedfs/seaweed-block/core/authority", typeName: "AuthorityBasis"},
|
||||
}
|
||||
|
||||
func TestT2NVMe_Boundary_NoAuthorityMintingAndNoCoreAdapterImport(t *testing.T) {
|
||||
root, err := findNVMePkgRoot(t)
|
||||
if err != nil {
|
||||
t.Fatalf("findNVMePkgRoot: %v", err)
|
||||
}
|
||||
|
||||
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, werr error) error {
|
||||
if werr != nil {
|
||||
return werr
|
||||
}
|
||||
if d.IsDir() || !strings.HasSuffix(path, ".go") {
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
checkNVMeFile(t, path)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("WalkDir: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func checkNVMeFile(t *testing.T, path string) {
|
||||
fset := token.NewFileSet()
|
||||
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
|
||||
if err != nil {
|
||||
t.Errorf("%s: parse: %v", path, err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, imp := range f.Imports {
|
||||
p := strings.Trim(imp.Path.Value, `"`)
|
||||
for _, bad := range forbiddenImports {
|
||||
if p == bad {
|
||||
t.Errorf("%s: forbidden import %q in core/frontend/nvme production code",
|
||||
path, p)
|
||||
}
|
||||
}
|
||||
if imp.Name != nil && imp.Name.Name == "." {
|
||||
for _, bad := range forbiddenImports {
|
||||
if p == bad {
|
||||
t.Errorf("%s: forbidden dot-import %q — bare literals would bypass the AST guard",
|
||||
path, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
aliases := importAliasMap(f)
|
||||
ast.Inspect(f, func(n ast.Node) bool {
|
||||
cl, ok := n.(*ast.CompositeLit)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
sel, ok := cl.Type.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
pkgIdent, ok := sel.X.(*ast.Ident)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
canonical, has := aliases[pkgIdent.Name]
|
||||
if !has {
|
||||
return true
|
||||
}
|
||||
for _, m := range forbiddenMinters {
|
||||
if canonical == m.importPath && sel.Sel.Name == m.typeName {
|
||||
t.Errorf("%s: forbidden composite literal %s.%s (resolves to %s.%s)",
|
||||
path, pkgIdent.Name, sel.Sel.Name, m.importPath, m.typeName)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func importAliasMap(f *ast.File) map[string]string {
|
||||
m := map[string]string{}
|
||||
for _, imp := range f.Imports {
|
||||
path := strings.Trim(imp.Path.Value, `"`)
|
||||
var alias string
|
||||
if imp.Name != nil {
|
||||
if imp.Name.Name == "_" || imp.Name.Name == "." {
|
||||
continue
|
||||
}
|
||||
alias = imp.Name.Name
|
||||
} else {
|
||||
alias = path
|
||||
if i := strings.LastIndex(alias, "/"); i >= 0 {
|
||||
alias = alias[i+1:]
|
||||
}
|
||||
}
|
||||
m[alias] = path
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func findNVMePkgRoot(t *testing.T) (string, error) {
|
||||
t.Helper()
|
||||
_, file, _, ok := runtime.Caller(0)
|
||||
if !ok {
|
||||
return "", &pkgRootError{"runtime.Caller failed"}
|
||||
}
|
||||
return filepath.Dir(file), nil
|
||||
}
|
||||
|
||||
type pkgRootError struct{ msg string }
|
||||
|
||||
func (e *pkgRootError) Error() string { return e.msg }
|
||||
@@ -0,0 +1,124 @@
|
||||
// Package nvme is the T2 NVMe/TCP target for the V3 frontend.
|
||||
// Symmetric with core/frontend/iscsi: consumes authority truth
|
||||
// through frontend.Provider, never mints assignments, never
|
||||
// imports core/authority. See
|
||||
// sw-block/design/v3-phase-15-t2-sketch.md §6.
|
||||
package nvme
|
||||
|
||||
import "fmt"
|
||||
|
||||
// NVMe Status Code Types (SCT). Selected subset; full table
|
||||
// lives in NVMe base spec §4.5.
|
||||
const (
|
||||
SCTGeneric uint8 = 0x0
|
||||
SCTCommandSpecific uint8 = 0x1
|
||||
SCTMediaDataInteg uint8 = 0x2
|
||||
SCTPathRelated uint8 = 0x3
|
||||
SCTVendorSpecific uint8 = 0x7
|
||||
)
|
||||
|
||||
// NVMe Status Codes within SCTGeneric.
|
||||
const (
|
||||
SCSuccess uint8 = 0x00
|
||||
SCInvalidOpcode uint8 = 0x01
|
||||
SCInvalidField uint8 = 0x02
|
||||
SCCommandIDConflict uint8 = 0x03
|
||||
SCDataTransferError uint8 = 0x04
|
||||
SCAbortedCmdFencing uint8 = 0x05
|
||||
SCInternalError uint8 = 0x06
|
||||
SCCommandAbort uint8 = 0x07
|
||||
SCNamespaceNotReady uint8 = 0x82
|
||||
SCLBAOutOfRange uint8 = 0x80
|
||||
SCCapacityExceeded uint8 = 0x81
|
||||
)
|
||||
|
||||
// NVMe Status Codes within SCTPathRelated. These are the
|
||||
// "ANA" (Asymmetric Namespace Access) family — the direct
|
||||
// semantic match for a V3 authority move: a path that was
|
||||
// serving is temporarily or persistently unavailable because
|
||||
// the controller has transitioned state.
|
||||
//
|
||||
// We pick ANATransition (0x03) for stale-lineage because it
|
||||
// corresponds to "the transition is in progress" — exactly
|
||||
// what a V3 RefreshEndpoint / cross-replica reassign presents
|
||||
// to the host. ANAInaccessible (0x02) is reserved for the
|
||||
// closed-backend case so operators can tell the two fail
|
||||
// modes apart in CQE logs (parity with iSCSI's 0x04/0x0A
|
||||
// vs 0x04/0x00 distinction — see iscsi/errors.go).
|
||||
const (
|
||||
SCPathInternalError uint8 = 0x00
|
||||
SCPathAsymAccessPersistLoss uint8 = 0x01
|
||||
SCPathAsymAccessInaccessible uint8 = 0x02
|
||||
SCPathAsymAccessTransition uint8 = 0x03
|
||||
SCPathControllerPathingErr uint8 = 0x60
|
||||
SCPathHostPathingErr uint8 = 0x61
|
||||
SCPathCommandAbortHost uint8 = 0x71
|
||||
)
|
||||
|
||||
// StatusError is the Go error surface for non-success NVMe
|
||||
// completion. Carries the SCT+SC tuple plus a diagnostic
|
||||
// reason; the wire layer encodes these into the 16-bit CQE
|
||||
// status field.
|
||||
//
|
||||
// Symmetric with iscsi.SCSIError in shape: L0 unit tests can
|
||||
// assert the exact tuple without decoding a capsule.
|
||||
type StatusError struct {
|
||||
SCT uint8
|
||||
SC uint8
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (e *StatusError) Error() string {
|
||||
return fmt.Sprintf("nvme: sct=0x%x sc=0x%02x reason=%s", e.SCT, e.SC, e.Reason)
|
||||
}
|
||||
|
||||
// EncodeStatusField packs SCT + SC into the 16-bit NVMe CQE
|
||||
// status field. Phase Tag / More / DNR bits are caller-owned
|
||||
// and set at the wire layer (0 for T2 scope). Format per NVMe
|
||||
// base spec §4.6.1:
|
||||
//
|
||||
// bit 0 : Phase Tag
|
||||
// bits 1–8 : Status Code (SC)
|
||||
// bits 9–11 : Status Code Type (SCT)
|
||||
// bits 12–13 : CRD (reserved in T2)
|
||||
// bit 14 : More
|
||||
// bit 15 : DNR
|
||||
func (e *StatusError) EncodeStatusField() uint16 {
|
||||
return uint16(e.SC)<<1 | uint16(e.SCT&0x7)<<9
|
||||
}
|
||||
|
||||
// NewStaleLineage is the canonical constructor surfaced when
|
||||
// the bound frontend.Backend reports ErrStalePrimary. ANA
|
||||
// Transition (SCT=3, SC=3) semantically matches an in-progress
|
||||
// authority move. Linux's nvme driver treats this as a path
|
||||
// retry condition, which is the behavior we want once L2-OS
|
||||
// lands.
|
||||
func NewStaleLineage() *StatusError {
|
||||
return &StatusError{
|
||||
SCT: SCTPathRelated,
|
||||
SC: SCPathAsymAccessTransition,
|
||||
Reason: "stale primary lineage",
|
||||
}
|
||||
}
|
||||
|
||||
// NewBackendClosed is the canonical constructor for
|
||||
// ErrBackendClosed. Distinct from stale-lineage (Inaccessible
|
||||
// vs Transition) so logs disambiguate.
|
||||
func NewBackendClosed() *StatusError {
|
||||
return &StatusError{
|
||||
SCT: SCTPathRelated,
|
||||
SC: SCPathAsymAccessInaccessible,
|
||||
Reason: "backend closed",
|
||||
}
|
||||
}
|
||||
|
||||
// NewInvalidField is used for malformed commands (unsupported
|
||||
// opcode, LBA out of range, short data transfer, etc.). Caller
|
||||
// picks the exact SC.
|
||||
func NewInvalidField(sc uint8, reason string) *StatusError {
|
||||
return &StatusError{
|
||||
SCT: SCTGeneric,
|
||||
SC: sc,
|
||||
Reason: reason,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package nvme
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStatusError_StaleLineageTuple(t *testing.T) {
|
||||
se := NewStaleLineage()
|
||||
if se.SCT != SCTPathRelated {
|
||||
t.Fatalf("SCT=0x%x want PathRelated (0x3)", se.SCT)
|
||||
}
|
||||
if se.SC != SCPathAsymAccessTransition {
|
||||
t.Fatalf("SC=0x%02x want ANATransition (0x03)", se.SC)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusError_BackendClosedTuple(t *testing.T) {
|
||||
se := NewBackendClosed()
|
||||
if se.SCT != SCTPathRelated {
|
||||
t.Fatalf("SCT=0x%x want PathRelated", se.SCT)
|
||||
}
|
||||
if se.SC != SCPathAsymAccessInaccessible {
|
||||
t.Fatalf("SC=0x%02x want ANAInaccessible (0x02)", se.SC)
|
||||
}
|
||||
// Distinct from stale-lineage so operators can tell them apart.
|
||||
if se.SC == SCPathAsymAccessTransition {
|
||||
t.Fatal("closed-backend must NOT use ANATransition SC (would conflate two fail modes)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusError_InvalidField_CarriesCallerSC(t *testing.T) {
|
||||
se := NewInvalidField(SCLBAOutOfRange, "LBA past end")
|
||||
if se.SCT != SCTGeneric {
|
||||
t.Fatalf("SCT=0x%x want Generic (0x0)", se.SCT)
|
||||
}
|
||||
if se.SC != SCLBAOutOfRange {
|
||||
t.Fatalf("SC=0x%02x want LBAOutOfRange (0x80)", se.SC)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusError_ErrorFormat_Stable(t *testing.T) {
|
||||
se := NewStaleLineage()
|
||||
msg := se.Error()
|
||||
if msg == "" {
|
||||
t.Fatal("Error() empty")
|
||||
}
|
||||
if want := "nvme:"; !contains(msg, want) {
|
||||
t.Fatalf("msg=%q should contain %q", msg, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusError_AsError(t *testing.T) {
|
||||
var err error = NewStaleLineage()
|
||||
var se *StatusError
|
||||
if !errors.As(err, &se) {
|
||||
t.Fatal("errors.As must unwrap *StatusError")
|
||||
}
|
||||
if se.SC != SCPathAsymAccessTransition {
|
||||
t.Fatalf("unwrapped SC=0x%02x", se.SC)
|
||||
}
|
||||
}
|
||||
|
||||
// T2 invariant: stale-lineage and closed-backend map to
|
||||
// DIFFERENT wire bits, so Linux's nvme driver can route retries
|
||||
// vs hard failures differently.
|
||||
func TestStatusError_StaleAndClosed_DistinctOnWire(t *testing.T) {
|
||||
stale := NewStaleLineage().EncodeStatusField()
|
||||
closed := NewBackendClosed().EncodeStatusField()
|
||||
if stale == closed {
|
||||
t.Fatalf("stale (0x%04x) and closed (0x%04x) produce identical wire bits — would conflate fail modes",
|
||||
stale, closed)
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity on the encoder: SCT sits in bits 9-11, SC in bits 1-8,
|
||||
// Phase Tag (bit 0) stays 0 at this layer.
|
||||
func TestStatusError_EncodeStatusField_LayoutCorrect(t *testing.T) {
|
||||
se := &StatusError{SCT: 0x3, SC: 0x03} // stale-lineage tuple
|
||||
got := se.EncodeStatusField()
|
||||
// Expected: (SC << 1) | (SCT << 9) = (0x03 << 1) | (0x3 << 9) = 0x0606
|
||||
if got != 0x0606 {
|
||||
t.Fatalf("encoded=0x%04x want 0x0606 (SC=0x03 SCT=0x3)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package nvme
|
||||
|
||||
// NVMe IO command handler — minimal T2 scope.
|
||||
//
|
||||
// Structure mirrors core/frontend/iscsi/scsi.go: an IOHandler
|
||||
// wraps a frontend.Backend and dispatches NVMe IO Read/Write
|
||||
// commands to it. LBA math uses the namespace's logical block
|
||||
// size (512B default). Stale-lineage errors from the backend
|
||||
// map to SCT=3 SC=3 (ANA Transition) via StatusError so the
|
||||
// wire layer can encode a proper CQE.
|
||||
//
|
||||
// L0 tests exercise this handler directly without PDU framing
|
||||
// — same rationale as the iSCSI slice: handler-level is the
|
||||
// deterministic seam between an NVMe command and the frontend
|
||||
// contract. Capsule framing + fabric login land in a later
|
||||
// checkpoint.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
)
|
||||
|
||||
// DefaultBlockSize / DefaultVolumeBlocks are symmetric with the
|
||||
// iSCSI defaults so the two protocols present the same 1 MiB
|
||||
// volume to the contract backend.
|
||||
const (
|
||||
DefaultBlockSize uint32 = 512
|
||||
DefaultVolumeBlocks uint64 = 2048 // 2048 * 512 = 1 MiB
|
||||
)
|
||||
|
||||
// NVMe IO command opcodes (NVM Command Set spec §6).
|
||||
// Package-private because callers build IOCommand using these
|
||||
// constants through the handler seam, not directly off the wire.
|
||||
// The NVMe admin opcode set (Identify, Get Log Page, etc.) is
|
||||
// intentionally out of scope for T2 L0 — admin commands land
|
||||
// with capsule framing in a later checkpoint.
|
||||
const (
|
||||
ioFlush uint8 = 0x00
|
||||
ioWrite uint8 = 0x01
|
||||
ioRead uint8 = 0x02
|
||||
)
|
||||
|
||||
// IOCommand is the T2 normalized form of an NVMe IO command.
|
||||
// Callers (wire decoder in a later checkpoint) translate the
|
||||
// 64-byte Submission Queue Entry into this struct. L0 tests
|
||||
// build IOCommand directly.
|
||||
//
|
||||
// Fields match the NVMe IO Read/Write CDW10-13 layout:
|
||||
// - SLBA = CDW10 (low) + CDW11 (high) — 64-bit starting LBA
|
||||
// - NLB = CDW12[15:0] + 1 (Number of Logical Blocks, zero-based on wire,
|
||||
// one-based in this struct for readability)
|
||||
// - NSID = command header Namespace Identifier
|
||||
//
|
||||
// Data is the host-provided write payload (nil for Read).
|
||||
// Expected read length = NLB * BlockSize; caller sizes the
|
||||
// returned data accordingly.
|
||||
type IOCommand struct {
|
||||
Opcode uint8
|
||||
NSID uint32
|
||||
SLBA uint64
|
||||
NLB uint32
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// IOResult is the handler-level outcome of one IO command.
|
||||
// Mirrors iscsi.SCSIResult in shape. Callers that want an
|
||||
// idiomatic error use AsError() — nil return means Status
|
||||
// was Success.
|
||||
type IOResult struct {
|
||||
SCT uint8
|
||||
SC uint8
|
||||
Data []byte // read payload (nil for writes / errors)
|
||||
Reason string
|
||||
}
|
||||
|
||||
// AsError returns a non-nil *StatusError iff Status != Success.
|
||||
func (r IOResult) AsError() *StatusError {
|
||||
if r.SCT == SCTGeneric && r.SC == SCSuccess {
|
||||
return nil
|
||||
}
|
||||
return &StatusError{SCT: r.SCT, SC: r.SC, Reason: r.Reason}
|
||||
}
|
||||
|
||||
// IOHandler dispatches IOCommands to a frontend.Backend. Owns
|
||||
// no storage; every Read/Write routes through Backend.Read /
|
||||
// .Write so the per-op lineage fence fires exactly once per
|
||||
// NVMe command. Stateless with respect to the backend.
|
||||
type IOHandler struct {
|
||||
backend frontend.Backend
|
||||
blockSize uint32
|
||||
volumeSize uint64
|
||||
// nsid is the single namespace ID this handler serves. T2
|
||||
// advertises NSID=1 (the canonical "first namespace" in
|
||||
// NVMe discovery); commands for any other NSID are
|
||||
// rejected with Invalid Namespace.
|
||||
nsid uint32
|
||||
}
|
||||
|
||||
// HandlerConfig configures an IOHandler. Zero values pick T2
|
||||
// defaults.
|
||||
type HandlerConfig struct {
|
||||
Backend frontend.Backend
|
||||
BlockSize uint32
|
||||
VolumeSize uint64
|
||||
NSID uint32
|
||||
}
|
||||
|
||||
// NewIOHandler builds a handler. Backend MUST be non-nil.
|
||||
func NewIOHandler(cfg HandlerConfig) *IOHandler {
|
||||
if cfg.Backend == nil {
|
||||
panic("nvme: NewIOHandler: Backend required")
|
||||
}
|
||||
bs := cfg.BlockSize
|
||||
if bs == 0 {
|
||||
bs = DefaultBlockSize
|
||||
}
|
||||
vs := cfg.VolumeSize
|
||||
if vs == 0 {
|
||||
vs = DefaultVolumeBlocks * uint64(bs)
|
||||
}
|
||||
nsid := cfg.NSID
|
||||
if nsid == 0 {
|
||||
nsid = 1
|
||||
}
|
||||
return &IOHandler{
|
||||
backend: cfg.Backend,
|
||||
blockSize: bs,
|
||||
volumeSize: vs,
|
||||
nsid: nsid,
|
||||
}
|
||||
}
|
||||
|
||||
// BlockSize exposes the advertised logical block size.
|
||||
func (h *IOHandler) BlockSize() uint32 { return h.blockSize }
|
||||
|
||||
// VolumeSize exposes the volume size in bytes.
|
||||
func (h *IOHandler) VolumeSize() uint64 { return h.volumeSize }
|
||||
|
||||
// NSID exposes the namespace this handler serves.
|
||||
func (h *IOHandler) NSID() uint32 { return h.nsid }
|
||||
|
||||
// Handle dispatches one IOCommand. Minimal T2 opcode set:
|
||||
// Read, Write, Flush. Everything else → Invalid Opcode.
|
||||
func (h *IOHandler) Handle(ctx context.Context, cmd IOCommand) IOResult {
|
||||
if cmd.NSID != h.nsid {
|
||||
// Invalid Namespace or Format (SCT=0 SC=0x0B is the
|
||||
// spec'd code, but we use InvalidField 0x02 for T2
|
||||
// scope because the test harness only exercises NSID=1).
|
||||
return IOResult{
|
||||
SCT: SCTGeneric,
|
||||
SC: SCInvalidField,
|
||||
Reason: fmt.Sprintf("unknown NSID %d", cmd.NSID),
|
||||
}
|
||||
}
|
||||
switch cmd.Opcode {
|
||||
case ioRead:
|
||||
return h.read(ctx, cmd)
|
||||
case ioWrite:
|
||||
return h.write(ctx, cmd)
|
||||
case ioFlush:
|
||||
// No backend-level flush yet — Success is safe because
|
||||
// the T2 memback backend is not a write-back cache.
|
||||
return IOResult{SCT: SCTGeneric, SC: SCSuccess}
|
||||
default:
|
||||
return IOResult{
|
||||
SCT: SCTGeneric,
|
||||
SC: SCInvalidOpcode,
|
||||
Reason: fmt.Sprintf("unsupported opcode 0x%02x", cmd.Opcode),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- data path ----------
|
||||
|
||||
func (h *IOHandler) read(ctx context.Context, cmd IOCommand) IOResult {
|
||||
if cmd.NLB == 0 {
|
||||
// NVMe treats NLB=0 (wire) as one block; IOCommand.NLB
|
||||
// is one-based so 0 here means "caller set it wrong".
|
||||
// Fail closed.
|
||||
return IOResult{SCT: SCTGeneric, SC: SCInvalidField, Reason: "NLB=0"}
|
||||
}
|
||||
totalBlocks := h.volumeSize / uint64(h.blockSize)
|
||||
if cmd.SLBA >= totalBlocks || cmd.SLBA+uint64(cmd.NLB) > totalBlocks {
|
||||
return IOResult{SCT: SCTGeneric, SC: SCLBAOutOfRange, Reason: "read LBA out of range"}
|
||||
}
|
||||
byteLen := int(cmd.NLB) * int(h.blockSize)
|
||||
buf := make([]byte, byteLen)
|
||||
_, err := h.backend.Read(ctx, int64(cmd.SLBA)*int64(h.blockSize), buf)
|
||||
if err != nil {
|
||||
return mapBackendError(err, "read")
|
||||
}
|
||||
return IOResult{SCT: SCTGeneric, SC: SCSuccess, Data: buf}
|
||||
}
|
||||
|
||||
func (h *IOHandler) write(ctx context.Context, cmd IOCommand) IOResult {
|
||||
if cmd.NLB == 0 {
|
||||
return IOResult{SCT: SCTGeneric, SC: SCInvalidField, Reason: "NLB=0"}
|
||||
}
|
||||
totalBlocks := h.volumeSize / uint64(h.blockSize)
|
||||
if cmd.SLBA >= totalBlocks || cmd.SLBA+uint64(cmd.NLB) > totalBlocks {
|
||||
return IOResult{SCT: SCTGeneric, SC: SCLBAOutOfRange, Reason: "write LBA out of range"}
|
||||
}
|
||||
expectedBytes := int(cmd.NLB) * int(h.blockSize)
|
||||
if len(cmd.Data) < expectedBytes {
|
||||
return IOResult{
|
||||
SCT: SCTGeneric,
|
||||
SC: SCInvalidField,
|
||||
Reason: "host data shorter than NLB*BlockSize",
|
||||
}
|
||||
}
|
||||
_, err := h.backend.Write(ctx, int64(cmd.SLBA)*int64(h.blockSize), cmd.Data[:expectedBytes])
|
||||
if err != nil {
|
||||
return mapBackendError(err, "write")
|
||||
}
|
||||
return IOResult{SCT: SCTGeneric, SC: SCSuccess}
|
||||
}
|
||||
|
||||
// mapBackendError translates frontend errors into NVMe CQE
|
||||
// status tuples. ErrStalePrimary → ANA Transition;
|
||||
// ErrBackendClosed → ANA Inaccessible; anything else → Internal
|
||||
// Error (fail-closed; real-backend-specific mapping lands with
|
||||
// T3).
|
||||
func mapBackendError(err error, op string) IOResult {
|
||||
if errors.Is(err, frontend.ErrStalePrimary) {
|
||||
return IOResult{
|
||||
SCT: SCTPathRelated,
|
||||
SC: SCPathAsymAccessTransition,
|
||||
Reason: "stale primary lineage on " + op,
|
||||
}
|
||||
}
|
||||
if errors.Is(err, frontend.ErrBackendClosed) {
|
||||
return IOResult{
|
||||
SCT: SCTPathRelated,
|
||||
SC: SCPathAsymAccessInaccessible,
|
||||
Reason: "backend closed on " + op,
|
||||
}
|
||||
}
|
||||
return IOResult{
|
||||
SCT: SCTGeneric,
|
||||
SC: SCInternalError,
|
||||
Reason: "backend error on " + op + ": " + err.Error(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
// Ownership: QA (from sketch-approved test spec v3-phase-15-t2-test-spec.md for T2 First Real Frontends).
|
||||
// sw may NOT modify this file without architect approval via §8B.4 Discovery Bridge.
|
||||
// See: sw-block/design/v3-phase-15-t2-test-spec.md
|
||||
// Maps to ledger rows: INV-FRONTEND-NVME-001, INV-FRONTEND-PROTOCOL-001,
|
||||
// INV-FRONTEND-PROTOCOL-002.WRITE, INV-FRONTEND-PROTOCOL-002.READ
|
||||
//
|
||||
// Test layer: Unit (L0)
|
||||
// Protocol: NVMe/TCP
|
||||
// Bounded fate (mirror of iSCSI L0 with NVMe protocol mapping):
|
||||
// - NVMe IO Read/Write route every byte through
|
||||
// frontend.Backend with correct offset/length.
|
||||
// - frontend.ErrStalePrimary maps to SCT=3 SC=3 (ANA Transition).
|
||||
// No success ACK on stale WRITE; no bytes returned on stale
|
||||
// READ.
|
||||
// - Invalid input (LBA out of range, NSID mismatch, short data)
|
||||
// maps to SCT=0 with a specific SC, without reaching the
|
||||
// backend.
|
||||
//
|
||||
// Spec adaptation note: test-spec §4 T2.L0.n* series is specified
|
||||
// as the iSCSI series with names replaced (CheckCondition ->
|
||||
// ProtocolFailure etc.). This file delivers the equivalents at
|
||||
// the handler level — capsule framing + fabric login arrive with
|
||||
// a later checkpoint, same as the iSCSI slice.
|
||||
package nvme_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
|
||||
)
|
||||
|
||||
// The io.go constants are lowercase (package-private). Tests use
|
||||
// the public re-exports defined below for readability.
|
||||
const (
|
||||
opRead = 0x02
|
||||
opWrite = 0x01
|
||||
opFlush = 0x00
|
||||
)
|
||||
|
||||
// T2.L0.n1 — Read and Write route through frontend.Backend.
|
||||
func TestT2NVMe_CommandReadWrite_UsesFrontendBackend(t *testing.T) {
|
||||
rec := testback.NewRecordingBackend(frontend.Identity{
|
||||
VolumeID: "v1", ReplicaID: "r1", Epoch: 5, EndpointVersion: 3,
|
||||
})
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: rec})
|
||||
ctx := context.Background()
|
||||
|
||||
payload := make([]byte, nvme.DefaultBlockSize)
|
||||
copy(payload, []byte("hello-nvme-t2"))
|
||||
r := h.Handle(ctx, nvme.IOCommand{
|
||||
Opcode: opWrite, NSID: 1, SLBA: 0, NLB: 1, Data: payload,
|
||||
})
|
||||
if e := r.AsError(); e != nil {
|
||||
t.Fatalf("Write: %v", e)
|
||||
}
|
||||
if rec.WriteCount() != 1 {
|
||||
t.Fatalf("backend Write invoked %d times, want 1", rec.WriteCount())
|
||||
}
|
||||
w := rec.WriteAt(0)
|
||||
if w.Offset != 0 || !bytes.Equal(w.Data, payload) {
|
||||
t.Fatalf("backend Write mismatch: offset=%d len=%d", w.Offset, len(w.Data))
|
||||
}
|
||||
|
||||
rr := h.Handle(ctx, nvme.IOCommand{
|
||||
Opcode: opRead, NSID: 1, SLBA: 0, NLB: 1,
|
||||
})
|
||||
if e := rr.AsError(); e != nil {
|
||||
t.Fatalf("Read: %v", e)
|
||||
}
|
||||
if !bytes.Equal(rr.Data, payload) {
|
||||
t.Fatalf("Read data mismatch")
|
||||
}
|
||||
if rec.ReadCount() != 1 {
|
||||
t.Fatalf("backend Read invoked %d times, want 1", rec.ReadCount())
|
||||
}
|
||||
}
|
||||
|
||||
// T2.L0.n2 — stale Write returns ANA Transition; MUST NOT ACK success.
|
||||
func TestT2NVMe_StaleWrite_ReturnsProtocolFailure(t *testing.T) {
|
||||
stale := testback.NewStaleRejectingBackend()
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: stale})
|
||||
ctx := context.Background()
|
||||
|
||||
payload := make([]byte, nvme.DefaultBlockSize)
|
||||
r := h.Handle(ctx, nvme.IOCommand{Opcode: opWrite, NSID: 1, SLBA: 0, NLB: 1, Data: payload})
|
||||
|
||||
if r.SCT == nvme.SCTGeneric && r.SC == nvme.SCSuccess {
|
||||
t.Fatal("stale Write returned Success — silent stale-ACK is a correctness violation")
|
||||
}
|
||||
e := r.AsError()
|
||||
if e == nil {
|
||||
t.Fatal("AsError nil for non-Success status")
|
||||
}
|
||||
if e.SCT != nvme.SCTPathRelated {
|
||||
t.Fatalf("SCT=0x%x want PathRelated (0x3)", e.SCT)
|
||||
}
|
||||
if e.SC != nvme.SCPathAsymAccessTransition {
|
||||
t.Fatalf("SC=0x%02x want ANATransition (0x03)", e.SC)
|
||||
}
|
||||
}
|
||||
|
||||
// T2.L0.n3 — stale Read returns ANA Transition; MUST NOT leak bytes.
|
||||
func TestT2NVMe_StaleRead_ReturnsProtocolFailure(t *testing.T) {
|
||||
stale := testback.NewStaleRejectingBackend()
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: stale})
|
||||
ctx := context.Background()
|
||||
|
||||
r := h.Handle(ctx, nvme.IOCommand{Opcode: opRead, NSID: 1, SLBA: 0, NLB: 1})
|
||||
|
||||
if r.SCT == nvme.SCTGeneric && r.SC == nvme.SCSuccess {
|
||||
t.Fatal("stale Read returned Success — stale-read data leak is a correctness violation")
|
||||
}
|
||||
if len(r.Data) != 0 {
|
||||
t.Fatalf("stale Read returned %d bytes — must not leak stale bytes to initiator", len(r.Data))
|
||||
}
|
||||
e := r.AsError()
|
||||
if e.SCT != nvme.SCTPathRelated || e.SC != nvme.SCPathAsymAccessTransition {
|
||||
t.Fatalf("stale Read status (SCT=0x%x SC=0x%02x) want PathRelated/ANATransition",
|
||||
e.SCT, e.SC)
|
||||
}
|
||||
}
|
||||
|
||||
// T2.L0.n4 — invalid input fails closed without reaching backend.
|
||||
func TestT2NVMe_InvalidInput_FailsClosed(t *testing.T) {
|
||||
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: rec})
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
cmd nvme.IOCommand
|
||||
wantSC uint8
|
||||
}{
|
||||
{
|
||||
name: "read_lba_past_end",
|
||||
cmd: nvme.IOCommand{Opcode: opRead, NSID: 1, SLBA: nvme.DefaultVolumeBlocks + 1, NLB: 1},
|
||||
wantSC: nvme.SCLBAOutOfRange,
|
||||
},
|
||||
{
|
||||
name: "write_overflow_range",
|
||||
cmd: nvme.IOCommand{Opcode: opWrite, NSID: 1, SLBA: nvme.DefaultVolumeBlocks - 1, NLB: 4, Data: make([]byte, 4*nvme.DefaultBlockSize)},
|
||||
wantSC: nvme.SCLBAOutOfRange,
|
||||
},
|
||||
{
|
||||
name: "write_short_data",
|
||||
cmd: nvme.IOCommand{Opcode: opWrite, NSID: 1, SLBA: 0, NLB: 4, Data: make([]byte, nvme.DefaultBlockSize)},
|
||||
wantSC: nvme.SCInvalidField,
|
||||
},
|
||||
{
|
||||
name: "nlb_zero",
|
||||
cmd: nvme.IOCommand{Opcode: opWrite, NSID: 1, SLBA: 0, NLB: 0, Data: nil},
|
||||
wantSC: nvme.SCInvalidField,
|
||||
},
|
||||
{
|
||||
name: "unknown_nsid",
|
||||
cmd: nvme.IOCommand{Opcode: opRead, NSID: 99, SLBA: 0, NLB: 1},
|
||||
wantSC: nvme.SCInvalidField,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
beforeW := rec.WriteCount()
|
||||
beforeR := rec.ReadCount()
|
||||
r := h.Handle(ctx, tc.cmd)
|
||||
if r.SCT == nvme.SCTGeneric && r.SC == nvme.SCSuccess {
|
||||
t.Fatalf("%s: Success — must fail closed", tc.name)
|
||||
}
|
||||
if r.SCT != nvme.SCTGeneric {
|
||||
t.Fatalf("%s: SCT=0x%x want Generic (0x0)", tc.name, r.SCT)
|
||||
}
|
||||
if r.SC != tc.wantSC {
|
||||
t.Fatalf("%s: SC=0x%02x want 0x%02x", tc.name, r.SC, tc.wantSC)
|
||||
}
|
||||
if rec.WriteCount() != beforeW || rec.ReadCount() != beforeR {
|
||||
t.Fatalf("%s: backend invoked for invalid input", tc.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Distinction regression: backend-closed must produce a different
|
||||
// wire tuple than stale-lineage (same SCT, different SC), matching
|
||||
// the iSCSI slice's closed-vs-stale invariant.
|
||||
func TestT2NVMe_BackendClosed_DistinctFromStale(t *testing.T) {
|
||||
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})
|
||||
_ = rec.Close()
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: rec})
|
||||
ctx := context.Background()
|
||||
r := h.Handle(ctx, nvme.IOCommand{
|
||||
Opcode: opWrite, NSID: 1, SLBA: 0, NLB: 1,
|
||||
Data: make([]byte, nvme.DefaultBlockSize),
|
||||
})
|
||||
if r.SCT != nvme.SCTPathRelated {
|
||||
t.Fatalf("SCT=0x%x want PathRelated", r.SCT)
|
||||
}
|
||||
if r.SC == nvme.SCPathAsymAccessTransition {
|
||||
t.Fatalf("closed-backend SC must NOT equal ANATransition (conflates fail modes)")
|
||||
}
|
||||
if r.SC != nvme.SCPathAsymAccessInaccessible {
|
||||
t.Fatalf("closed-backend: SC=0x%02x want ANAInaccessible (0x02)", r.SC)
|
||||
}
|
||||
}
|
||||
|
||||
// Unknown opcode rejected without reaching backend.
|
||||
func TestT2NVMe_UnknownOpcode_ReturnsInvalidOpcode(t *testing.T) {
|
||||
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: rec})
|
||||
r := h.Handle(context.Background(), nvme.IOCommand{
|
||||
Opcode: 0x7f, NSID: 1, SLBA: 0, NLB: 1,
|
||||
})
|
||||
if r.SCT != nvme.SCTGeneric || r.SC != nvme.SCInvalidOpcode {
|
||||
t.Fatalf("unknown opcode status (SCT=0x%x SC=0x%02x) want Generic/InvalidOpcode",
|
||||
r.SCT, r.SC)
|
||||
}
|
||||
if rec.ReadCount()+rec.WriteCount() != 0 {
|
||||
t.Fatal("unknown opcode reached backend")
|
||||
}
|
||||
}
|
||||
|
||||
// Flush is accepted as a no-op Success in T2 scope.
|
||||
func TestT2NVMe_Flush_SuccessInT2Scope(t *testing.T) {
|
||||
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"})
|
||||
h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: rec})
|
||||
r := h.Handle(context.Background(), nvme.IOCommand{Opcode: opFlush, NSID: 1})
|
||||
if r.AsError() != nil {
|
||||
t.Fatalf("Flush: %v", r.AsError())
|
||||
}
|
||||
}
|
||||
|
||||
// AsError on a success IOResult is nil.
|
||||
func TestIOResult_AsError_NilOnSuccess(t *testing.T) {
|
||||
var r nvme.IOResult
|
||||
if r.AsError() != nil {
|
||||
t.Fatal("AsError non-nil on zero (Success) result")
|
||||
}
|
||||
}
|
||||
|
||||
// errors.As chains through IOResult.AsError().
|
||||
func TestIOResult_AsError_SupportsErrorsAs(t *testing.T) {
|
||||
r := nvme.IOResult{SCT: nvme.SCTPathRelated, SC: nvme.SCPathAsymAccessTransition}
|
||||
var err error = r.AsError()
|
||||
var se *nvme.StatusError
|
||||
if !errors.As(err, &se) {
|
||||
t.Fatal("errors.As failed")
|
||||
}
|
||||
if se.SC != nvme.SCPathAsymAccessTransition {
|
||||
t.Fatalf("unwrapped SC=0x%02x", se.SC)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user