diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 7aae550d54..0fbb1a4a44 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -103,7 +103,8 @@ type DurableProvider struct { view frontend.ProjectionView mu sync.Mutex - volumes map[string]*volHandle // keyed by volumeID + volumes map[string]*volHandle // keyed by volumeID + opening map[string]*sync.Mutex // keyed by volumeID; serializes open/create closed bool } @@ -140,6 +141,7 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura cfg: cfg, view: view, volumes: map[string]*volHandle{}, + opening: map[string]*sync.Mutex{}, }, nil } @@ -165,6 +167,29 @@ func (p *DurableProvider) Open(ctx context.Context, volumeID string) (frontend.B return nil, err } + h, err := p.ensureHandle(volumeID) + if err != nil { + return nil, err + } + // Latch the backend's Identity to the now-Healthy projection. If + // the backend was constructed via EnsureStorage pre-assignment, its + // captured Identity has Epoch=0 even though VolumeID/ReplicaID came + // from CLI config at construction. SetIdentity transitions Epoch=0 + // to the live projection's Epoch/EV; subsequent drift still fails + // closed. + proj := p.view.Projection() + log.Printf("durable: dp.Open latching identity from projection volume=%s replica=%s epoch=%d ev=%d (post-waitHealthy)", + proj.VolumeID, proj.ReplicaID, proj.Epoch, proj.EndpointVersion) + h.backend.SetIdentity(frontend.Identity{ + VolumeID: proj.VolumeID, + ReplicaID: proj.ReplicaID, + Epoch: proj.Epoch, + EndpointVersion: proj.EndpointVersion, + }) + return h.backend, nil +} + +func (p *DurableProvider) ensureHandle(volumeID string) (*volHandle, error) { p.mu.Lock() if p.closed { p.mu.Unlock() @@ -172,22 +197,26 @@ func (p *DurableProvider) Open(ctx context.Context, volumeID string) (frontend.B } if h, ok := p.volumes[volumeID]; ok { p.mu.Unlock() - // G5-5: latch the backend's Identity to the now-Healthy - // projection. If the backend was constructed via EnsureStorage - // pre-assignment, its captured Identity has Epoch=0 even though - // VolumeID/ReplicaID came from CLI config at construction. - // SetIdentity transitions Epoch=0 โ†’ live projection's Epoch/EV; - // subsequent drift still fails closed. - proj := p.view.Projection() - log.Printf("durable: dp.Open latching identity from projection volume=%s replica=%s epoch=%d ev=%d (post-waitHealthy)", - proj.VolumeID, proj.ReplicaID, proj.Epoch, proj.EndpointVersion) - h.backend.SetIdentity(frontend.Identity{ - VolumeID: proj.VolumeID, - ReplicaID: proj.ReplicaID, - Epoch: proj.Epoch, - EndpointVersion: proj.EndpointVersion, - }) - return h.backend, nil + return h, nil + } + openMu := p.opening[volumeID] + if openMu == nil { + openMu = &sync.Mutex{} + p.opening[volumeID] = openMu + } + p.mu.Unlock() + + openMu.Lock() + defer openMu.Unlock() + + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return nil, fmt.Errorf("durable: provider closed") + } + if h, ok := p.volumes[volumeID]; ok { + p.mu.Unlock() + return h, nil } p.mu.Unlock() @@ -196,16 +225,18 @@ func (p *DurableProvider) Open(ctx context.Context, volumeID string) (frontend.B return nil, err } - // Check-then-insert: another goroutine may have raced us. p.mu.Lock() defer p.mu.Unlock() - if existing, ok := p.volumes[volumeID]; ok { - // Race: close the handle we just opened; return the winner. + if p.closed { _ = h.storage.Close() - return existing.backend, nil + return nil, fmt.Errorf("durable: provider closed") + } + if existing, ok := p.volumes[volumeID]; ok { + _ = h.storage.Close() + return existing, nil } p.volumes[volumeID] = h - return h.backend, nil + return h, nil } // EnsureStorage opens (or creates) the on-disk LogicalStorage for @@ -225,28 +256,10 @@ func (p *DurableProvider) Open(ctx context.Context, volumeID string) (frontend.B // The returned handle is borrowed โ€” caller MUST NOT call Close on // it (BUG-005 discipline: Provider owns storage lifecycle). func (p *DurableProvider) EnsureStorage(volumeID string) (storage.LogicalStorage, error) { - p.mu.Lock() - if p.closed { - p.mu.Unlock() - return nil, fmt.Errorf("durable: provider closed") - } - if h, ok := p.volumes[volumeID]; ok { - p.mu.Unlock() - return h.storage, nil - } - p.mu.Unlock() - - h, err := p.openOrCreate(volumeID) + h, err := p.ensureHandle(volumeID) if err != nil { return nil, err } - p.mu.Lock() - defer p.mu.Unlock() - if existing, ok := p.volumes[volumeID]; ok { - _ = h.storage.Close() - return existing.storage, nil - } - p.volumes[volumeID] = h return h.storage, nil } diff --git a/seaweed-block/core/frontend/durable/provider_test.go b/seaweed-block/core/frontend/durable/provider_test.go index f6bd56d871..a07e487878 100644 --- a/seaweed-block/core/frontend/durable/provider_test.go +++ b/seaweed-block/core/frontend/durable/provider_test.go @@ -9,6 +9,7 @@ import ( "errors" "os" "path/filepath" + "sync" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -234,3 +235,41 @@ func TestT3b_DurableProvider_Open_Caches(t *testing.T) { }) } } + +func TestDurableProvider_EnsureStorage_ConcurrentSameVolumeReturnsSingleHandle(t *testing.T) { + for _, impl := range implMatrix() { + impl := impl + t.Run(string(impl), func(t *testing.T) { + p, _, _ := newProvider(t, impl) + + const goroutines = 16 + var wg sync.WaitGroup + wg.Add(goroutines) + storages := make([]any, goroutines) + errs := make([]error, goroutines) + for i := 0; i < goroutines; i++ { + i := i + go func() { + defer wg.Done() + storages[i], errs[i] = p.EnsureStorage("v1") + }() + } + wg.Wait() + + for i, err := range errs { + if err != nil { + t.Fatalf("EnsureStorage[%d]: %v", i, err) + } + } + first := storages[0] + if first == nil { + t.Fatal("EnsureStorage[0] returned nil storage") + } + for i, got := range storages[1:] { + if got != first { + t.Fatalf("EnsureStorage[%d] returned different storage handle", i+1) + } + } + }) + } +} diff --git a/seaweed-block/core/frontend/iscsi/scsi.go b/seaweed-block/core/frontend/iscsi/scsi.go index eefa8a816a..5f53482c73 100644 --- a/seaweed-block/core/frontend/iscsi/scsi.go +++ b/seaweed-block/core/frontend/iscsi/scsi.go @@ -96,12 +96,12 @@ func (r SCSIResult) AsError() *SCSIError { // (if any) are an initiator / protocol concern, not this // layer's. type SCSIHandler struct { - backend frontend.Backend - blockSize uint32 - volumeSize uint64 // bytes - vendorID string // 8 bytes - productID string // 16 bytes - serialNo string + backend frontend.Backend + blockSize uint32 + volumeSize uint64 // bytes + vendorID string // 8 bytes + productID string // 16 bytes + serialNo string } // HandlerConfig configures an SCSIHandler. Zero values pick @@ -249,7 +249,7 @@ func (h *SCSIHandler) doRead(ctx context.Context, lba uint64, transferLen uint32 return SCSIResult{Status: StatusGood} } totalBlocks := h.volumeSize / uint64(h.blockSize) - if lba >= totalBlocks || lba+uint64(transferLen) > totalBlocks { + if lba >= totalBlocks || uint64(transferLen) > totalBlocks-lba { return illegalRequest(ASCLBAOutOfRange, 0x00, "read LBA out of range") } byteLen := int(transferLen) * int(h.blockSize) @@ -271,7 +271,7 @@ func (h *SCSIHandler) doWrite(ctx context.Context, lba uint64, transferLen uint3 return SCSIResult{Status: StatusGood} } totalBlocks := h.volumeSize / uint64(h.blockSize) - if lba >= totalBlocks || lba+uint64(transferLen) > totalBlocks { + if lba >= totalBlocks || uint64(transferLen) > totalBlocks-lba { log.Printf("iscsi: SCSI WRITE rejected (LBA out of range): lba=%d transferLen=%d totalBlocks=%d", lba, transferLen, totalBlocks) return illegalRequest(ASCLBAOutOfRange, 0x00, "write LBA out of range") @@ -684,9 +684,9 @@ func illegalRequest(asc, ascq uint8, reason string) SCSIResult { // (SPC-5 ยง4.5.3). Used by REQUEST SENSE. func buildSenseData(key, asc, ascq uint8) []byte { d := make([]byte, 18) - d[0] = 0x70 // Current, fixed format - d[2] = key & 0x0f // Sense key - d[7] = 10 // Additional length + d[0] = 0x70 // Current, fixed format + d[2] = key & 0x0f // Sense key + d[7] = 10 // Additional length d[12] = asc d[13] = ascq return d diff --git a/seaweed-block/core/frontend/iscsi/scsi_batch10_5_test.go b/seaweed-block/core/frontend/iscsi/scsi_batch10_5_test.go index dd26c24ec7..5c9c548a8a 100644 --- a/seaweed-block/core/frontend/iscsi/scsi_batch10_5_test.go +++ b/seaweed-block/core/frontend/iscsi/scsi_batch10_5_test.go @@ -11,6 +11,7 @@ import ( "bytes" "context" "encoding/binary" + "math" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -368,6 +369,19 @@ func TestT2Batch10_5_Write16_LBAOutOfRange_Rejected(t *testing.T) { } } +func TestT2Batch10_5_Write16_LBAOverflow_Rejected(t *testing.T) { + h := newHandlerForTest(t) + r := h.HandleCommand(context.Background(), + write16CDB(math.MaxUint64, 1), + make([]byte, iscsi.DefaultBlockSize)) + if r.Status == iscsi.StatusGood { + t.Fatal("WRITE(16) overflowing LBA range: Good (must fail)") + } + if r.ASC != iscsi.ASCLBAOutOfRange { + t.Fatalf("ASC=0x%02x want LBAOutOfRange", r.ASC) + } +} + func TestT2Batch10_5_Read16_LBAOutOfRange_Rejected(t *testing.T) { h := newHandlerForTest(t) r := h.HandleCommand(context.Background(), @@ -380,6 +394,18 @@ func TestT2Batch10_5_Read16_LBAOutOfRange_Rejected(t *testing.T) { } } +func TestT2Batch10_5_Read16_LBAOverflow_Rejected(t *testing.T) { + h := newHandlerForTest(t) + r := h.HandleCommand(context.Background(), + read16CDB(math.MaxUint64, 1), nil) + if r.Status == iscsi.StatusGood { + t.Fatal("READ(16) overflowing LBA range: Good (must fail)") + } + if r.ASC != iscsi.ASCLBAOutOfRange { + t.Fatalf("ASC=0x%02x want LBAOutOfRange", r.ASC) + } +} + // ReadCapacity10 should still work alongside the new (16) variant. // Regression guard that the ckpt 2 code path wasn't broken by the // dispatch changes. diff --git a/seaweed-block/core/frontend/iscsi/session.go b/seaweed-block/core/frontend/iscsi/session.go index 1b4e341b4c..8dc2ab0a33 100644 --- a/seaweed-block/core/frontend/iscsi/session.go +++ b/seaweed-block/core/frontend/iscsi/session.go @@ -74,9 +74,9 @@ type Session struct { // only. provider + volumeID + hcfg are captured at session // construction; the session calls provider.Open() after // login succeeds and builds the SCSIHandler then. - provider frontend.Provider - volumeID string - hcfg HandlerConfig + provider frontend.Provider + volumeID string + hcfg HandlerConfig // backend holds the opened backend so serve() can Close it // on exit. nil for Discovery sessions. backend frontend.Backend @@ -275,12 +275,15 @@ func (s *Session) handleSCSICmd(ctx context.Context, req *PDU) error { // using an opcode we don't recognize here fall through // to the handler (which rejects Invalid Opcode). if expected, ok := cdbExpectedWriteBytes(cdb, s.handler.BlockSize()); ok { - if edtl != expected { + if uint64(edtl) != expected { return s.sendSCSIResponse(req, illegalRequest( ASCInvalidFieldInCDB, 0x00, "EDTL does not match CDB transfer length")) } } + if result, ok := s.validateWriteTransferLimits(req, edtl); !ok { + return s.sendSCSIResponse(req, result) + } collected, err := s.collectWriteData(req, edtl) if err != nil { return err @@ -309,20 +312,35 @@ func (s *Session) handleSCSICmd(ctx context.Context, req *PDU) error { // because handleSCSICmd doesn't need to build a SCSIResult โ€” it // just needs to bound the pre-allocation. Expand as new write // opcodes are added to scsi.go. -func cdbExpectedWriteBytes(cdb [16]byte, blockSize uint32) (uint32, bool) { +func cdbExpectedWriteBytes(cdb [16]byte, blockSize uint32) (uint64, bool) { switch cdb[0] { case ScsiWrite10: transferLen := uint32(cdb[7])<<8 | uint32(cdb[8]) - return transferLen * blockSize, true + return uint64(transferLen) * uint64(blockSize), true case ScsiWrite16: // 32-bit transferLen in CDB bytes 10-13 (Batch 10.5). transferLen := uint32(cdb[10])<<24 | uint32(cdb[11])<<16 | uint32(cdb[12])<<8 | uint32(cdb[13]) - return transferLen * blockSize, true + return uint64(transferLen) * uint64(blockSize), true } return 0, false } +func (s *Session) validateWriteTransferLimits(req *PDU, edtl uint32) (SCSIResult, bool) { + if maxBurst := s.negResult.MaxBurstLength; maxBurst > 0 && uint64(edtl) > uint64(maxBurst) { + return illegalRequest( + ASCInvalidFieldInCDB, 0x00, + "EDTL exceeds negotiated MaxBurstLength"), false + } + if firstBurst := s.negResult.FirstBurstLength; firstBurst > 0 && + uint64(len(req.DataSegment)) > uint64(firstBurst) { + return illegalRequest( + ASCInvalidFieldInCDB, 0x00, + "immediate data exceeds negotiated FirstBurstLength"), false + } + return SCSIResult{Status: StatusGood}, true +} + // collectWriteData assembles the write payload from immediate // data (carried in the SCSI-Cmd) + any Data-Out PDUs solicited // via R2T. Returns the full edtl-sized buffer on success. diff --git a/seaweed-block/core/frontend/iscsi/session_limits_test.go b/seaweed-block/core/frontend/iscsi/session_limits_test.go new file mode 100644 index 0000000000..cb5b47c090 --- /dev/null +++ b/seaweed-block/core/frontend/iscsi/session_limits_test.go @@ -0,0 +1,74 @@ +package iscsi + +import "testing" + +func TestCDBExpectedWriteBytes_Write16UsesUint64(t *testing.T) { + var cdb [16]byte + cdb[0] = ScsiWrite16 + cdb[10], cdb[11], cdb[12], cdb[13] = 0xff, 0xff, 0xff, 0xff + + got, ok := cdbExpectedWriteBytes(cdb, DefaultBlockSize) + if !ok { + t.Fatal("WRITE(16) expected-byte calculation not recognized") + } + want := uint64(0xffffffff) * uint64(DefaultBlockSize) + if got != want { + t.Fatalf("expected bytes=%d want %d", got, want) + } + if got <= uint64(^uint32(0)) { + t.Fatalf("expected bytes=%d should exceed uint32 max", got) + } +} + +func TestSessionValidateWriteTransferLimitsRejectsOversizedEDTL(t *testing.T) { + s := &Session{ + negResult: LoginResult{ + MaxBurstLength: 64 * 1024, + FirstBurstLength: 16 * 1024, + }, + } + req := &PDU{} + req.DataSegment = make([]byte, 4*1024) + + result, ok := s.validateWriteTransferLimits(req, 128*1024) + if ok { + t.Fatal("oversized EDTL accepted") + } + if result.Status != StatusCheckCondition || result.ASC != ASCInvalidFieldInCDB { + t.Fatalf("unexpected result: status=0x%02x asc=0x%02x", result.Status, result.ASC) + } +} + +func TestSessionValidateWriteTransferLimitsRejectsOversizedImmediateData(t *testing.T) { + s := &Session{ + negResult: LoginResult{ + MaxBurstLength: 64 * 1024, + FirstBurstLength: 4 * 1024, + }, + } + req := &PDU{} + req.DataSegment = make([]byte, 8*1024) + + result, ok := s.validateWriteTransferLimits(req, 8*1024) + if ok { + t.Fatal("oversized immediate data accepted") + } + if result.Status != StatusCheckCondition || result.ASC != ASCInvalidFieldInCDB { + t.Fatalf("unexpected result: status=0x%02x asc=0x%02x", result.Status, result.ASC) + } +} + +func TestSessionValidateWriteTransferLimitsAcceptsNegotiatedWrite(t *testing.T) { + s := &Session{ + negResult: LoginResult{ + MaxBurstLength: 64 * 1024, + FirstBurstLength: 16 * 1024, + }, + } + req := &PDU{} + req.DataSegment = make([]byte, 8*1024) + + if result, ok := s.validateWriteTransferLimits(req, 32*1024); !ok { + t.Fatalf("valid write rejected: status=0x%02x asc=0x%02x", result.Status, result.ASC) + } +}