From 4e5daa453fc6fec88664a199bea77c48a609fe78 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 3 May 2026 21:16:58 -0700 Subject: [PATCH] frontend: chunk iSCSI R2T writes by MaxBurst --- .../frontend/iscsi/client_support_test.go | 21 ++- seaweed-block/core/frontend/iscsi/session.go | 140 +++++++++--------- .../frontend/iscsi/session_limits_test.go | 21 ++- .../frontend/iscsi/t2_large_write_test.go | 62 ++++++++ 4 files changed, 168 insertions(+), 76 deletions(-) diff --git a/seaweed-block/core/frontend/iscsi/client_support_test.go b/seaweed-block/core/frontend/iscsi/client_support_test.go index f95733aa64..f8371ab922 100644 --- a/seaweed-block/core/frontend/iscsi/client_support_test.go +++ b/seaweed-block/core/frontend/iscsi/client_support_test.go @@ -130,6 +130,17 @@ func (c *testClient) scsiCmd(t *testing.T, cdb [16]byte, immediate []byte, expec // len(solicited). Used by the ckpt 10 large-write tests to // drive the R2T → Data-Out path. func (c *testClient) scsiCmdFull(t *testing.T, cdb [16]byte, immediate, solicited []byte, expectedDataIn int) (status uint8, dataIn []byte) { + t.Helper() + status, dataIn, _ = c.scsiCmdFullWithR2TTrace(t, cdb, immediate, solicited, expectedDataIn) + return status, dataIn +} + +type r2tTrace struct { + Offset uint32 + Desired uint32 +} + +func (c *testClient) scsiCmdFullWithR2TTrace(t *testing.T, cdb [16]byte, immediate, solicited []byte, expectedDataIn int) (status uint8, dataIn []byte, traces []r2tTrace) { t.Helper() totalWrite := len(immediate) + len(solicited) @@ -164,7 +175,6 @@ func (c *testClient) scsiCmdFull(t *testing.T, cdb [16]byte, immediate, solicite // the one with S-bit. var collected bytes.Buffer solicitedOffset := len(immediate) // where in the logical write stream Data-Out starts - var dataSN uint32 for { resp, err := iscsi.ReadPDU(c.conn) if err != nil { @@ -177,6 +187,7 @@ func (c *testClient) scsiCmdFull(t *testing.T, cdb [16]byte, immediate, solicite } offset := resp.BufferOffset() desired := resp.DesiredDataLength() + traces = append(traces, r2tTrace{Offset: offset, Desired: desired}) if int(offset)-solicitedOffset < 0 || int(offset)+int(desired)-solicitedOffset > len(solicited) { t.Fatalf("R2T range (offset=%d desired=%d) outside solicited payload [%d, %d)", offset, desired, solicitedOffset, solicitedOffset+len(solicited)) @@ -191,8 +202,8 @@ func (c *testClient) scsiCmdFull(t *testing.T, cdb [16]byte, immediate, solicite out.SetLUN(0) out.SetInitiatorTaskTag(itt) out.SetTargetTransferTag(resp.TargetTransferTag()) - out.SetDataSN(dataSN) - dataSN++ + // DataSN is scoped to the current R2T data sequence. + out.SetDataSN(0) out.SetBufferOffset(offset) out.SetExpStatSN(c.statSN + 1) out.DataSegment = chunk @@ -202,10 +213,10 @@ func (c *testClient) scsiCmdFull(t *testing.T, cdb [16]byte, immediate, solicite case iscsi.OpSCSIDataIn: collected.Write(resp.DataSegment) if resp.OpSpecific1()&iscsi.FlagS != 0 { - return resp.SCSIStatusByte(), collected.Bytes() + return resp.SCSIStatusByte(), collected.Bytes(), traces } case iscsi.OpSCSIResp: - return resp.SCSIStatusByte(), collected.Bytes() + return resp.SCSIStatusByte(), collected.Bytes(), traces default: t.Fatalf("unexpected resp opcode: %s", iscsi.OpcodeName(resp.Opcode())) } diff --git a/seaweed-block/core/frontend/iscsi/session.go b/seaweed-block/core/frontend/iscsi/session.go index 8dc2ab0a33..8d0d3c591c 100644 --- a/seaweed-block/core/frontend/iscsi/session.go +++ b/seaweed-block/core/frontend/iscsi/session.go @@ -327,10 +327,10 @@ func cdbExpectedWriteBytes(cdb [16]byte, blockSize uint32) (uint64, bool) { } func (s *Session) validateWriteTransferLimits(req *PDU, edtl uint32) (SCSIResult, bool) { - if maxBurst := s.negResult.MaxBurstLength; maxBurst > 0 && uint64(edtl) > uint64(maxBurst) { + if uint64(edtl) > uint64(MaxDataSegmentLength) { return illegalRequest( ASCInvalidFieldInCDB, 0x00, - "EDTL exceeds negotiated MaxBurstLength"), false + "EDTL exceeds target write buffer limit"), false } if firstBurst := s.negResult.FirstBurstLength; firstBurst > 0 && uint64(len(req.DataSegment)) > uint64(firstBurst) { @@ -345,10 +345,9 @@ func (s *Session) validateWriteTransferLimits(req *PDU, edtl uint32) (SCSIResult // data (carried in the SCSI-Cmd) + any Data-Out PDUs solicited // via R2T. Returns the full edtl-sized buffer on success. // -// T2 scope: single R2T for all remaining bytes. V2 supports -// MaxBurstLength-chunked multi-R2T; we'll port that chunking -// only if an OS initiator actually exposes the need — per the -// assignment §4.3 rule "port the smallest required R2T path". +// Large writes are collected as one or more R2T data sequences. +// Each R2T's DesiredDataLength is capped by the negotiated +// MaxBurstLength; the total WRITE EDTL may be larger. func (s *Session) collectWriteData(req *PDU, edtl uint32) ([]byte, error) { buf := make([]byte, edtl) var received uint32 @@ -365,77 +364,80 @@ func (s *Session) collectWriteData(req *PDU, edtl uint32) ([]byte, error) { return buf, nil } - // Solicit the remainder with one R2T. TargetTransferTag is - // arbitrary per-target scope; 1 is fine while a session only - // has one outstanding write at a time (T2 minimal session). - const ttt uint32 = 1 - r2t := &PDU{} - r2t.SetOpcode(OpR2T) - r2t.SetOpSpecific1(FlagF) - r2t.SetLUN(req.LUN()) - r2t.SetInitiatorTaskTag(req.InitiatorTaskTag()) - r2t.SetTargetTransferTag(ttt) - // StatSN on R2T is a snapshot of the current StatSN (no - // increment — R2T doesn't carry status). - r2t.SetStatSN(s.statSN) - r2t.SetExpCmdSN(req.CmdSN() + 1) - r2t.SetMaxCmdSN(req.CmdSN() + 32) - r2t.SetR2TSN(0) - r2t.SetBufferOffset(received) - r2t.SetDesiredDataLength(edtl - received) - if err := WritePDU(s.conn, r2t); err != nil { - return nil, fmt.Errorf("send R2T: %w", err) + maxBurst := uint32(s.negResult.MaxBurstLength) + if maxBurst == 0 { + maxBurst = edtl } - // Read Data-Out PDU(s) until we have edtl bytes. V2 enforces - // DataSN + BufferOffset ordering (DataPDUInOrder / - // DataSequenceInOrder both default Yes); we do the same. - var nextDataSN uint32 + var r2tsn uint32 for received < edtl { - pdu, err := ReadPDU(s.conn) - if err != nil { - return nil, fmt.Errorf("read Data-Out: %w", err) + remaining := edtl - received + desired := remaining + if desired > maxBurst { + desired = maxBurst } - if pdu.Opcode() != OpSCSIDataOut { - return nil, fmt.Errorf("expected Data-Out, got %s", OpcodeName(pdu.Opcode())) - } - if pdu.TargetTransferTag() != ttt { - // R2T-solicited Data-Out MUST echo the target's TTT - // from the R2T. 0xFFFFFFFF signals unsolicited - // Data-Out, which we disable via InitialR2T=Yes — - // accepting it here would silently weaken the - // negotiated "solicited-only" discipline (architect - // review 2026-04-21 ckpt 10 Medium finding). - return nil, fmt.Errorf("Data-Out TTT=0x%08x does not echo R2T TTT=0x%08x", - pdu.TargetTransferTag(), ttt) - } - if pdu.DataSN() != nextDataSN { - return nil, fmt.Errorf("Data-Out DataSN=%d, expected %d", - pdu.DataSN(), nextDataSN) - } - nextDataSN++ + burstEnd := received + desired + ttt := uint32(1) + r2tsn - offset := pdu.BufferOffset() - if offset != received { - return nil, fmt.Errorf("Data-Out BufferOffset=%d does not match received=%d", - offset, received) + r2t := &PDU{} + r2t.SetOpcode(OpR2T) + r2t.SetOpSpecific1(FlagF) + r2t.SetLUN(req.LUN()) + r2t.SetInitiatorTaskTag(req.InitiatorTaskTag()) + r2t.SetTargetTransferTag(ttt) + // StatSN on R2T is a snapshot of the current StatSN (no + // increment — R2T doesn't carry status). + r2t.SetStatSN(s.statSN) + r2t.SetExpCmdSN(req.CmdSN() + 1) + r2t.SetMaxCmdSN(req.CmdSN() + 32) + r2t.SetR2TSN(r2tsn) + r2t.SetBufferOffset(received) + r2t.SetDesiredDataLength(desired) + if err := WritePDU(s.conn, r2t); err != nil { + return nil, fmt.Errorf("send R2T: %w", err) } - data := pdu.DataSegment - end := offset + uint32(len(data)) - if end > edtl { - return nil, fmt.Errorf("Data-Out extends past EDTL: end=%d edtl=%d", - end, edtl) - } - copy(buf[offset:], data) - received = end - // F-bit on Data-Out marks the last PDU of the sequence. - // We accept it as a hint but trust received == edtl as - // the authoritative termination condition. - if pdu.OpSpecific1()&FlagF != 0 && received != edtl { - return nil, fmt.Errorf("Data-Out F-bit with received=%d < edtl=%d", - received, edtl) + // DataSN is scoped to the current R2T data sequence. + var nextDataSN uint32 + for received < burstEnd { + pdu, err := ReadPDU(s.conn) + if err != nil { + return nil, fmt.Errorf("read Data-Out: %w", err) + } + if pdu.Opcode() != OpSCSIDataOut { + return nil, fmt.Errorf("expected Data-Out, got %s", OpcodeName(pdu.Opcode())) + } + if pdu.TargetTransferTag() != ttt { + // R2T-solicited Data-Out MUST echo the target's TTT. + return nil, fmt.Errorf("Data-Out TTT=0x%08x does not echo R2T TTT=0x%08x", + pdu.TargetTransferTag(), ttt) + } + if pdu.DataSN() != nextDataSN { + return nil, fmt.Errorf("Data-Out DataSN=%d, expected %d", + pdu.DataSN(), nextDataSN) + } + nextDataSN++ + + offset := pdu.BufferOffset() + if offset != received { + return nil, fmt.Errorf("Data-Out BufferOffset=%d does not match received=%d", + offset, received) + } + data := pdu.DataSegment + end := offset + uint32(len(data)) + if end > burstEnd { + return nil, fmt.Errorf("Data-Out extends past R2T burst: end=%d burstEnd=%d", + end, burstEnd) + } + copy(buf[offset:], data) + received = end + + if pdu.OpSpecific1()&FlagF != 0 && received != burstEnd { + return nil, fmt.Errorf("Data-Out F-bit with received=%d < burstEnd=%d", + received, burstEnd) + } } + r2tsn++ } return buf, nil } diff --git a/seaweed-block/core/frontend/iscsi/session_limits_test.go b/seaweed-block/core/frontend/iscsi/session_limits_test.go index cb5b47c090..056a637f84 100644 --- a/seaweed-block/core/frontend/iscsi/session_limits_test.go +++ b/seaweed-block/core/frontend/iscsi/session_limits_test.go @@ -20,7 +20,7 @@ func TestCDBExpectedWriteBytes_Write16UsesUint64(t *testing.T) { } } -func TestSessionValidateWriteTransferLimitsRejectsOversizedEDTL(t *testing.T) { +func TestSessionValidateWriteTransferLimitsAcceptsEDTLAboveMaxBurst(t *testing.T) { s := &Session{ negResult: LoginResult{ MaxBurstLength: 64 * 1024, @@ -31,8 +31,25 @@ func TestSessionValidateWriteTransferLimitsRejectsOversizedEDTL(t *testing.T) { req.DataSegment = make([]byte, 4*1024) result, ok := s.validateWriteTransferLimits(req, 128*1024) + if !ok { + t.Fatalf("EDTL above MaxBurst should be chunked via R2T, got status=0x%02x asc=0x%02x", + result.Status, result.ASC) + } +} + +func TestSessionValidateWriteTransferLimitsRejectsTargetBufferLimit(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, MaxDataSegmentLength+1) if ok { - t.Fatal("oversized EDTL accepted") + t.Fatal("write above target buffer limit accepted") } if result.Status != StatusCheckCondition || result.ASC != ASCInvalidFieldInCDB { t.Fatalf("unexpected result: status=0x%02x asc=0x%02x", result.Status, result.ASC) diff --git a/seaweed-block/core/frontend/iscsi/t2_large_write_test.go b/seaweed-block/core/frontend/iscsi/t2_large_write_test.go index 75f11f67c8..4da317da26 100644 --- a/seaweed-block/core/frontend/iscsi/t2_large_write_test.go +++ b/seaweed-block/core/frontend/iscsi/t2_large_write_test.go @@ -110,6 +110,68 @@ func TestT2Route_ISCSI_LargeWrite_R2TPath_Component(t *testing.T) { } } +// TestT2Route_ISCSI_LargeWrite_ChunksR2TByMaxBurst: +// Linux initiators issue filesystem writes larger than one +// negotiated MaxBurstLength. The target must chunk the transfer +// across multiple R2Ts instead of rejecting the command or +// emitting one oversized R2T for the whole EDTL. +func TestT2Route_ISCSI_LargeWrite_ChunksR2TByMaxBurst(t *testing.T) { + const blocks = 1024 // 512 KiB at the default 512-byte SCSI block size. + const maxBurst = 64 * 1024 + const blockSize = uint32(iscsi.DefaultBlockSize) + const totalBytes = int(blockSize) * blocks + + rec := testback.NewRecordingBackend(frontend.Identity{ + VolumeID: "v1", ReplicaID: "r1", Epoch: 5, EndpointVersion: 3, + }) + prov := testback.NewStaticProvider(rec) + neg := iscsi.DefaultNegotiableConfig() + neg.MaxBurstLength = maxBurst + neg.FirstBurstLength = maxBurst + tg := iscsi.NewTarget(iscsi.TargetConfig{ + Listen: "127.0.0.1:0", + IQN: "iqn.2026-04.example.v3:v1", + VolumeID: "v1", + Provider: prov, + Negotiation: neg, + }) + addr, err := tg.Start() + if err != nil { + t.Fatalf("target Start: %v", err) + } + defer tg.Close() + + cli := dialAndLogin(t, addr) + defer cli.logout(t) + + payload := make([]byte, totalBytes) + for i := range payload { + payload[i] = byte((i * 17) % 251) + } + + status, _, traces := cli.scsiCmdFullWithR2TTrace(t, writeCDB10(0, uint16(blocks)), nil, payload, 0) + expectGood(t, status, "large WRITE(10) chunked by MaxBurst") + if len(traces) < 2 { + t.Fatalf("R2T count=%d want multiple chunks", len(traces)) + } + for i, tr := range traces { + if tr.Desired > maxBurst { + t.Fatalf("R2T[%d] DesiredDataLength=%d exceeds MaxBurstLength=%d", i, tr.Desired, maxBurst) + } + } + + if rec.WriteCount() != 1 { + t.Fatalf("backend Write invoked %d times, want 1", rec.WriteCount()) + } + w := rec.WriteAt(0) + if len(w.Data) != totalBytes { + t.Fatalf("backend Write len=%d want %d", len(w.Data), totalBytes) + } + if !bytes.Equal(w.Data, payload) { + t.Fatal("chunked R2T write payload mismatch") + } +} + // TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T: // stale-lineage invariant holds even when the write goes // through the R2T path. The target MUST collect the full