iSCSI in Go
  • Go 99.4%
  • Shell 0.5%
  • Dockerfile 0.1%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
iscsi-go c362e7e455 The LUN field is SAM's byte array, and the codec is the only place that knows it
RFC 7143 §11.2.1.7: "The LUN field is 64 bits and should be formatted in
accordance with [SAM2]. For example, LUN[0] from [SAM2] is BHS byte 8 and so on up
to LUN[7] from [SAM2], which is BHS byte 15." It is an array of eight bytes, and
SAM's addressing methods put the unit number in LUN[1]: LUN 1 goes on the wire as
00 01 00 00 00 00 00 00, not 00 00 00 00 00 00 00 01. SetLUN wrote the number as a
big-endian integer, so LUN[1] was always zero and every command — READ, INQUIRY,
MOVE MEDIUM, all of them — addressed logical unit 0 whatever the caller asked for.

Round-tripping against our own target hid it: the target decoded with the same
mistake, so both ends agreed and nothing on the network did. The consequence on
real hardware (measured by the LTFS client against the ATTO XCORE, and recorded in
its docs/changer-mtx-2026-10-27.md) was ILLEGAL REQUEST asc 0x25 for `lun=1` —
the bridge does not say "no such LUN". Its author worked around us by pre-swizzling
in the URL layer, and every caller since has had to know that Request.LUN held a
wire layout rather than a LUN.

Now the translation happens once, in the codec:

  - PutSAMLun / ParseSAMLun convert between a number and SAM's array, choosing the
    narrowest addressing method that holds the value (peripheral device for 0..0xFF,
    flat space to 0x3FFF, extended flat space to 30 bits, then the reserved 64-bit
    form).
  - PDU.LUN/SetLUN delegate to them, so Request.LUN, target.LUN.Lun and a client's
    logical unit number are plain numbers (0, 1, 2) end to end.
  - REPORT LUNS uses the same pair on both sides: SPC lists each unit as that same
    8-byte array, so the target emits it and the tape client decodes it. An
    initiator reading the list as an integer reported unit 0 for most LUNs — a
    target exporting a drive and a medium changer looked like a target exporting one
    drive twice.

iscsi-tape -lun 1 and a target config with Lun: 1 now address the second unit for
real, on hardware as well as against our own target. Verified against a simulated
library exporting two drives and a robot on one target: INQUIRY on each LUN answers
with that unit's serial and peripheral device type, and READ ELEMENT STATUS on the
changer LUN reports the shelf while the drive LUN stays a tape.

Tests: the wire bytes are pinned, not just the round trip — a command for LUN 3
carries 00 03 00 00 00 00 00 00 in BHS[8..15] and leaves the Initiator Task Tag in
BHS[16..19] alone; LUN 0 is eight zero bytes; each addressing method round-trips and
stays inside its own width; REPORT LUNS is asserted as arrays on both the emitting
and the parsing side.
2026-11-20 14:58:19 -08:00
.pi Initial commit 2026-10-15 12:56:06 -07:00
cmd End every session with the §11.14 Logout exchange, and drain before it 2026-10-16 19:29:35 -07:00
docs FINDINGS: state the artifact status as checked, not hedged 2026-10-17 02:15:36 -07:00
internal The LUN field is SAM's byte array, and the codec is the only place that knows it 2026-11-20 14:58:19 -08:00
iscsi The LUN field is SAM's byte array, and the codec is the only place that knows it 2026-11-20 14:58:19 -08:00
reference iSCSI wrapper 2026-10-15 14:45:46 -07:00
tape The LUN field is SAM's byte array, and the codec is the only place that knows it 2026-11-20 14:58:19 -08:00
testharness iSCSI wrapper 2026-10-15 14:45:46 -07:00
go.mod iSCSI wrapper 2026-10-15 14:45:46 -07:00
PLAN.md iSCSI wrapper 2026-10-15 14:45:46 -07:00
PROGRESS.md Three depth-4 mounts: no read past the object-6 filemark, and the queue still runs 2026-10-16 23:24:38 -07:00
README.md Design the write path: EOD is the oracle, the index is the commit record 2026-10-15 22:01:57 -07:00

iscsi-go

A pure-Go iSCSI initiator (RFC 7143) that carries the SCSI tape command set over TCP, so ltfs-go can mount and read LTFS on a tape drive reached through a storage network — no kernel st/sg path, no cabling to the drive.

Stdlib only. Two public packages:

Package Role
iscsi the protocol: PDU codec, login + CHAP, session, SCSI transport, discovery
tape the SCSI tape command set (SSC) that LTFS needs, on top of iscsi
conn, err := iscsi.Dial(ctx, iscsi.Config{
	TargetAddress: "192.168.1.20:3260",
	TargetName:    "iqn.2001-04.com.example:tape1",
	InitiatorName: "iqn.2026-08.io.github.cyberax:initiator",
	CHAPUser:      "ltfs",
	CHAPSecret:    os.Getenv("ISCSI_CHAP_SECRET"),
})
if err != nil {
	return err
}
defer conn.Close()

drive := tape.New(conn, 0)
if err := drive.Reserve(ctx); err != nil {
	return err // single-writer arbitration on a shared LUN
}
if err := drive.Load(ctx); err != nil {
	return err
}

for {
	data, mark, err := drive.ReadBlock(ctx, 1<<20)
	if err != nil {
		return err
	}
	switch mark {
	case tape.MarkData:
		handle(data)
	case tape.MarkFileMark:
		continue
	case tape.MarkEOD:
		return nil
	}
}

Why these constraints

The library targets one job — carrying tape I/O to a single LTFS writer — and says so in the wire format it negotiates:

  • Single command in flight. Execute is synchronous and serialised, matching the LTFS driver model. The background reader still demultiplexes by ITT, so NOP-In, Async events, Rejects and Data-In are handled while a task is outstanding.
  • ErrorRecoveryLevel=0. No session recovery, no command retry across connections: a transport failure fails the session and the caller decides. Anything higher is a negotiation error, not a silent downgrade.
  • Digests None. Header and payload digests are proposed as None and a target that insists on CRC32C is refused with a clear error.
  • InitialR2T=Yes, ImmediateData=No. Writes always follow an explicit R2T, which is the correct flow for multi-megabyte tape blocks.
  • Sense is in-band. The SCSI Response carries the sense data; there is no automatic REQUEST SENSE round-trip that could race with the next command.
  • Unit attention is normal. Over a shared transport, resets and reservation preemptions are routine. A retryable condition on a stateful command restores tape position before retrying — otherwise the retry silently returns the next block instead of the one that was lost.

Commands

go build ./cmd/...

# list what a portal exports, then inspect one logical unit
iscsi-discover -portal 192.168.1.20:3260
iscsi-discover -portal 192.168.1.20:3260 -target iqn.2001-04.com.example:tape1 -lun 0

# read blocks off a tape (read-only by design)
iscsi-tape -portal 192.168.1.20:3260 -target iqn.2001-04.com.example:tape1 \
           -reserve -count 20 -dump ./blocks

# what is this drive, and is anyone else on it — issues nothing that moves media
iscsi-tape -portal 192.168.1.20:3260 -target iqn.2001-04.com.example:tape1 -lun 0 -status

# a portal to practise on, with a disk LUN and an emulated tape
iscsi-mock-target -listen 127.0.0.1:3260 -tape

# diagnose a real portal: which credentials it accepts, and how
iscsi-probe -portal 192.168.1.20:3260 -discover -users fedora -secrets a,b
iscsi-probe -portal 192.168.1.20:3260 -target iqn... -user fedora -matrix a,b

# send raw CDBs over a live session, and read the sense back
iscsi-probe -portal 192.168.1.20:3260 -target iqn... -lun 0 \
            -cdb '12 00 00 00 24 00 ; 34 06 00 00 00 00 00 00 00 00'

Testing

go test ./...          # hermetic: in-process target, no privileges, no network
go test -race ./...
testharness/run-e2e.sh # against istgt, a third-party target, in a container

internal/target is a userspace iSCSI target — login, CHAP, mutual CHAP, SendTargets, R2T/Data-Out, Data-In on both status paths, sense, residuals, NOP, logout — plus a tape emulation that produces the awkward cases on purpose: file marks, blank-check end of data, SILI underruns, and a unit attention that fires after the drive consumed a block.

That in-process target shares an author with the initiator, so testharness/e2e runs the same flows against istgt to catch a misreading of the RFC that both implementations hold in common. It skips unless ISCSI_E2E_PORTAL is set. See testharness/README.md.

Layout

iscsi/          protocol: pdu, text, chap, login, config, conn, scsi, sense, tmf, discovery
tape/           SCSI tape commands: cdb.go (encodings + parsers), tape.go (device)
internal/target/ in-process test target (disk + tape emulation)
internal/cli/    shared flag plumbing for the commands
cmd/            iscsi-discover, iscsi-tape, iscsi-mock-target, iscsi-probe
testharness/    istgt container + third-party interop suite
docs/           nops-and-timeouts, reconnect-and-recovery, write-path-design
reference/      RFC 7143 text and the excerpts the wire format was written against

Status and limits

Login, CHAP-MD5 (and mutual CHAP), discovery, the full SCSI data phase, in-band sense, task management, logout, and the Tier 0-3 tape commands are implemented and covered by tests that run in-process.

They are also verified against hardware: an ATTO XCORE portal exporting an HPE Ultrium 9 (LTO-9). Discovery, a Normal session with two-way CHAP, INQUIRY, READ BLOCK LIMITS, READ POSITION, MODE SENSE and PERSISTENT RESERVE IN all work end to end, and that portal taught the initiator three things no test double had insisted on — Login Requests do not consume CmdSN slots, Login Flags carry CSG and NSG as two-bit fields, and some targets prefix sense data with its own length. See PROGRESS.md.

The point of the exercise is reached: ltfs-go reads a real LTFS volume off that tape through this library, over iSCSI, with no kernel tape driver on either side. Its BlockDevice gains an iscsi:// target, so the drive is addressed the way a /dev/sgN or a file-backed image already is:

ltfs-ls -dev 'iscsi://host:3260/<target-iqn>?lun=0&initiator=…&user=…&secret=…&mutual=…&mutualsecret=…'

That path survived the thing a tape does to an iSCSI implementation: a LOCATE that runs for minutes while the target answers nothing but its own keepalive pings. What that took is written up in docs/nops-and-timeouts.md.

Not implemented, by design: digests, session recovery (ErrorRecoveryLevel>0), multiple connections per session, immediate data, unsolicited Data-Out, IPv6/RDMA transports, and multipath.