From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 3D9521FF0B3 for ; Thu, 26 Nov 2026 16:10:16 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id B48D5216F8; Thu, 26 Nov 2026 16:10:13 +0100 (CET) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=neatech-ar.20260707.gappssmtp.com; s=20260707; t=1795705801; x=1796310601; darn=lists.proxmox.com; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=MQ1fEm5ichG4wJDhMH9QpMjU2/sP25mXzbVwRfENZK8=; b=AJvTCw+fKkD8rKul8eUAOnA3SGYmzeTInQnk5vEx10UYwiRrN0MJ2KKl6zG7aYLjVy pAsZzjlhQB424zaYz27Jngwvxiij9E0ZiHGfy8EEaNFVPo7/AlkYXOM/srjuzrBg5BgQ 1nsxCVXwrxIZtb/Pj1YCZ3Du5GTDJHjsmbYWxOjoujQJvtyfwTjnfWw3M+O1Ns9VHQZY vjZaEFC8DY7pd5kyrtHe0Dj8MQM3WGwgc5UjJ4AzaCoDN8iiWR8dRkMZps3Q+033aO6z abQlnflj46oYVSafTd8NgUt5nmvwdT+sRFFBVx38n3L8Fe1T4yMq0ROw777YGtJi+GVh 9KdQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795705801; x=1796310601; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=MQ1fEm5ichG4wJDhMH9QpMjU2/sP25mXzbVwRfENZK8=; b=hqmBYMXdJyO0v1ZEzr2LdLtbM5vr+C2t3iw/5p5/XPOJ2TfyDBaybb83GNtdI09lpA KOCYvCbpla0f6XnPOJzO0vSbTjMoUHr2xDN7u3iDXAaUEUB6cyBWXDSynkg3KBSH8XVo z163p5sr39ZYLDZs2FmJwby4k5pdoo6h3q29MMXG53tKijCGKjtPQYYhL3CziR2CynBN FmBjIGPFweqbA9aWWPVgTGYoqY9M5yJVg6fLrWdAd6fPe5iKUJBbc8eZThMKhg8ry4pd 2fCr/hiYUR8NGaEBsT2eDLC8SMwa2VnoKv/WmnbgSpGd7qA6Bdn+eZnJqVinsEsldhGF zclg== X-Gm-Message-State: APuU4Z9XbJLfeSVMxjZsBPi8PFiajRBTmOh7rTS6TDYP5yjQiuxeSSX5 GDzolzaeCmfKkgUutC8rtNlhSB07KcMiBg51PTwtaQUfJTq6w2e5+TJjYCWVOXDgOgr/5ougaaL r58U0dUU= X-Gm-Gg: AZFdTZdUCdCnLSdf3nsCJ7zA+S6nS0s/ya/hxaBXKIymyLdCtk/Rh+igoUckYaA5tit tDWj+7L7/7h5FOEh6p80zZ6WKXTHDrelmSiXmbyIdeC2MgaAWf1DIUC3IpR2CtvHjKqMepQnRz7 CxTjaNiosIHmWqPfkIkHIRPzeWf2byA+YDqLURdvDCSXPV7Kc81OhDb3XDwDLRSpq1NVPw4FPyD 8xP57LZlK5FLCDZbQa/LFrA3bf4uFh76EytFVMvdX8iWVhTG9mgBRQGP+/20KHZ4uXiT/9rbg0Y Dg8Z1pbsOpDRgfXftCg8U1k6KwKt2MC6JFA98CHiAXYr3qnzP6NLWyWnHgyUoHQ3Mt+vl3P01XV zxRObBynrQ7jHPMEN9q86lwcL1B649XbDMPT3TXRN26GyB/oZRmsLgnsx3yqaAl2sYaXyWkm0rB 8swmaCcl7oetDJmTuMeo3mu567KbPlROeg9lKBJDH+EfwenNZvtv7h8ffusm3Z0gXmQQ+PAbKJg RscP+iR2JbFWF6BAu8b2ZOpOMgXwPB9VHY5ViYiKuf6JDsPfRoDHEfTBU91F413HPL0sAb48PEi 3HgFzTScYpB8mBoGh987WsevW9w++/MpXvH4zmQ1hzj/imL/wSikz5BidxRa0MPJsX+1AVdgVBI +KywpFBGWsOWnFmudoxXJLnx4VJnydg== X-Received: by 2002:a05:6102:14cf:10b0:7c3:91f5:26d4 with SMTP id ada2fe7eead31-7d7393b9c85mr14386033137.3.1795705800288; Thu, 26 Nov 2026 07:10:00 -0800 (PST) From: Joaquin Varela To: pve-devel@lists.proxmox.com Subject: [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning Date: Thu, 26 Nov 2026 12:09:42 -0300 Message-ID: <20261126150956.310593-2-joaquinvarela@neatech.ar> X-Mailer: git-send-email 2.54.0.windows.1 In-Reply-To: <20261126150956.310593-1-joaquinvarela@neatech.ar> References: <20261126150956.310593-1-joaquinvarela@neatech.ar> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.167 Adjusted score from AWL reputation of From: address DKIM_SIGNED 0.1 Message has a DKIM or DK signature, not necessarily valid DKIM_VALID -0.1 Message has at least one valid DKIM or DK signature DMARC_PASS -0.1 DMARC pass policy POISEN_SPAM_PILL 0.1 Meta: its spam POISEN_SPAM_PILL_1 0.1 random spam to be learned in bayes POISEN_SPAM_PILL_3 0.1 random spam to be learned in bayes RCVD_IN_DNSWL_NONE -0.0001 Sender listed at https://www.dnswl.org/, no trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: CZY24724KNZJOW76WRUY7INA35HVUNCC X-Message-ID-Hash: CZY24724KNZJOW76WRUY7INA35HVUNCC X-MailFrom: joaquinvarela@neatech.ar X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: Add the first part of the 'zfsnvme' storage plugin: ZFS zvols on a remote Linux target, exported with the kernel nvmet driver over NVMe/TCP and managed over SSH like ZFS over iSCSI. This part reads the target state with one 'zfs get' and one 'find' over configfs, parses it and plans the changes as quoted commands. Parsing and planning are local and pure. A value that is read from the target or passed in by a caller is untainted by the capture of the regex that validates it, as pvedaemon runs with -T. The patch also holds the SSH runner that every target call goes through. A later patch of this series registers the plugin. Signed-off-by: Joaquin Varela --- src/PVE/Storage/ZFSNVMePlugin.pm | 1007 ++++++++++++++++++++++++++++++ 1 file changed, 1007 insertions(+) create mode 100644 src/PVE/Storage/ZFSNVMePlugin.pm diff --git a/src/PVE/Storage/ZFSNVMePlugin.pm b/src/PVE/Storage/ZFSNVMePlugin.pm new file mode 100644 index 00000000..270d559c --- /dev/null +++ b/src/PVE/Storage/ZFSNVMePlugin.pm @@ -0,0 +1,1007 @@ +package PVE::Storage::ZFSNVMePlugin; + +use v5.36; + +use Compress::Zlib qw(crc32); +use Digest::SHA qw(sha256_hex); +use Errno qw(ENOENT); +use Fcntl qw(O_NOFOLLOW O_RDONLY O_RDWR S_ISCHR); +use File::Path qw(make_path); +use List::Util qw(max); +use MIME::Base64 qw(decode_base64); +use POSIX qw(SIG_BLOCK SIG_SETMASK SIGHUP SIGINT SIGQUIT SIGTERM sigprocmask); +use Socket qw(AF_INET6 inet_ntop inet_pton); +use Time::HiRes; + +use PVE::Cluster; +use PVE::File; +use PVE::JSONSchema; +use PVE::Network; +use PVE::RESTEnvironment qw(log_warn); +use PVE::RPCEnvironment; +use PVE::SysFSTools; +use PVE::Tools qw(file_read_firstline file_set_contents run_command trim); + +use base qw(PVE::Storage::Plugin); + +# ZFS zvols on a remote Linux target, exported through the kernel NVMe target (nvmet, configured +# through configfs) over NVMe/TCP and consumed with native NVMe multipath. The ZFS dataset is the +# source of truth for a namespace (owner NQN, NSID and UUID are ZFS user properties), everything +# else on the target is derived state that is rebuilt after a restart. +# +# Parsing, validation and planning happen locally. Target calls are quoted commands over SSH, +# sometimes joined with `&&`, with `>` writes into configfs and one `dd | tee` pipe for a key, +# because configfs needs its writes in order. A pmxcfs domain lock per target serializes the +# changes in the cluster. + +# LogLevel=ERROR keeps a login banner out of the first stderr line, the error text of a failed call. +my @ssh_cmd = ( + '/usr/bin/ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'LogLevel=ERROR', +); +my $id_rsa_path = '/etc/pve/priv/zfs'; +my $secret_dir = '/etc/pve/priv/storage'; +my $max_paths = 16; +my $max_hosts = 64; +my $slow_path_backoff = 60; + +my $nvmet_root = '/sys/kernel/config/nvmet'; +my $nvmet_model = 'Proxmox ZFS NVMe'; +my $nvmet_marker = 'ZFSNVME-CONFIGFS'; +my $nvmet_max_nsid = 0xfffffffe; +my $nvmet_max_command = 65536; +my $nvmet_lock_wait = 30; +my $nvmet_last_nsid = 'proxmox:nvme-last-nsid'; + +my @nvmet_zfs_props = + ('type', 'proxmox:nvme-subsys', 'proxmox:nvme-nsid', 'proxmox:nvme-uuid', $nvmet_last_nsid); +my %nvmet_zfs_keys = ( + type => 'type', + 'proxmox:nvme-subsys' => 'nqn', + 'proxmox:nvme-nsid' => 'nsid', + 'proxmox:nvme-uuid' => 'uuid', + $nvmet_last_nsid => 'last_nsid', +); +my @nvmet_cfs_attrs = qw( + enable device_path device_uuid buffered_io + attr_model attr_serial attr_allow_any_host + addr_trtype addr_adrfam addr_traddr addr_trsvcid +); +# The commands that _nvmet_render accepts as the first word of a step. Also run on the target are +# find, which the configfs read starts through env to set its locale, the printf, grep and sha256sum +# that find runs, and the dd and tee of a key write. +my %nvmet_commands = map { $_ => 1 } qw( + cat chmod env grep ln mkdir modprobe mount printf rm rmdir test zfs +); + +my $RE_NQN = qr{ + \A + nqn \. + [A-Za-z0-9] [A-Za-z0-9.-]* + : + [A-Za-z0-9] [A-Za-z0-9._:-]* + \z +}nxx; +my $RE_HOST_IFACE = qr{\A [A-Za-z0-9_.-]+ \z}nxx; +my $RE_DHCHAP_KEY = qr{ + \A (? DHHC-1 : (? 0[0-3]) : (? [A-Za-z0-9+/]+ ={0,2}) :) \z +}nxx; +my $RE_TASK_INTERRUPT = qr{ + \A (?: (?: command \x20 ' .* ' \x20 failed: \x20 )? received \x20 interrupt + | interrupted \x20 by \x20 unexpected \x20 signal ) \n \z +}nsxx; +my $RE_COMMAND_TIMEOUT = qr{ + \A (?: command \x20 ' .* ' \x20 failed: \x20 )? got \x20 timeout \n \z +}nsxx; +my $RE_COMMAND_EXIT = + qr{\A command \x20 ' .* ' \x20 failed: \x20 exit \x20 code \x20 (? [0-9]+) \n \z}nsxx; +my $RE_FABRICS_VALUE = qr{\A [^\s,\x00]+ \z}nxx; +my $RE_FABRICS_RESULT = qr{\A instance=(? [0-9]+) ,cntlid= [0-9]+ \n \z}nxx; +my $RE_CONFIG_INT = qr{\A -?[0-9]+ \z}nxx; +my $RE_NVME_CONTROLLER = qr{\A nvme [0-9]+ \z}nxx; +my $RE_NVME_SUBSYSTEM = qr{\A nvme-subsys [0-9]+ \z}nxx; +my $RE_NVME_NAMESPACE = qr{\A (? nvme [0-9]+ n [0-9]+) \z}nxx; +my $RE_TRADDR = qr{(?: \A | ,) traddr=(?[^,]+)}nxx; +my $RE_TRSVCID = qr{(?: \A | ,) trsvcid=(?[^,]+)}nxx; +my $RE_HOST_IFACE_ADDRESS = qr{(?: \A | ,) host_iface=(?[^,]+)}nxx; +# no ':' like ZFSPlugin, and anchor with \z as $ also accepts a trailing newline +my $RE_ZVOL_SUFFIX = qr{[a-zA-Z0-9_.-]+}nxx; +my $RE_ZVOL_OWNER = qr{\A (?:vm|base|subvol|basevol)- (?\d+) - $RE_ZVOL_SUFFIX \z}nxx; +my $RE_VOLNAME = qr{ + \A + (?: (? (?:base|basevol)- (?\d+) - $RE_ZVOL_SUFFIX) /)? + (? (?base|basevol|vm|subvol)- (?\d+) - $RE_ZVOL_SUFFIX) + \z +}nxx; +my $RE_BASE_SNAPSHOT = qr{\A (? [a-zA-Z0-9_.-]+) \@__base__ \z}nxx; +my $RE_UNSIGNED_INTEGER = qr{^ (?\d+) $}nxx; + +# The named captures untaint the values that were read and those that callers pass, as the daemons +# run with -T. +my $RE_NVMET_UUID = qr{ + \A (? [0-9a-fA-F]{8} (?: - [0-9a-fA-F]{4}){3} - [0-9a-fA-F]{12}) \z +}nxx; +my $RE_NVMET_NSID = qr{\A (? [1-9] [0-9]*) \z}nxx; +my $RE_NVMET_POOL = qr{\A [A-Za-z0-9] [A-Za-z0-9_.:/-]* \z}nxx; +my $RE_NVMET_DATASET_NAME = qr{\A (? [A-Za-z0-9] [A-Za-z0-9_.:-]*) \z}nxx; +my $RE_NVMET_SNAPSHOT = qr{\A (? [A-Za-z0-9_.:-]+) \z}nxx; +# as the pve-storage-id format checks it +my $RE_STORAGE_ID = qr{\A (? [a-z] [a-z0-9_.-]* [a-z0-9]) \z}nxxi; +my $RE_NVMET_TEMPLATE_ZVOL = qr{/ (? vm | base) - (? [^/]+) \z}nxx; +my $RE_NVMET_INHERITED = qr{\A inherited \x20 from \x20 (? .+) \z}nxx; +my $RE_NVMET_ABANDONED = qr{ + (?: \A received \x20 interrupt | ; \x20 the \x20 target \x20 state \x20 is \x20 unknown) \n \z +}nxx; + +# attribute names anchor the split, so an NQN containing ':' is never ambiguous +my $cfs_root = quotemeta($nvmet_root); +my $RE_CFS_TOP = qr{\A D \x20 $cfs_root (?: / (? hosts | ports | subsystems))? \z}nxx; +my $RE_CFS_SUBSYS_DIR = qr{\A D \x20 $cfs_root /subsystems/ (? [^/]+) \z}nxx; +my $RE_CFS_SUBSYS_GROUP = qr{ + \A D \x20 $cfs_root /subsystems/ [^/]+ / (?: namespaces | allowed_hosts) \z +}nxx; +my $RE_CFS_NS_DIR = qr{ + \A D \x20 $cfs_root /subsystems/ (? [^/]+) /namespaces/ (? [0-9]+) \z +}nxx; +my $RE_CFS_PORT_DIR = qr{\A D \x20 $cfs_root /ports/ (? [0-9]+) \z}nxx; +my $RE_CFS_PORT_GROUP = qr{\A D \x20 $cfs_root /ports/ [0-9]+ /subsystems \z}nxx; +my $RE_CFS_HOST_DIR = qr{\A D \x20 $cfs_root /hosts/ (? [^/]+) \z}nxx; +my $RE_CFS_PORT_LINK = qr{ + \A L \x20 $cfs_root /ports/ (? [0-9]+) /subsystems/ (? [^/]+) \z +}nxx; +my $RE_CFS_ACL_LINK = qr{ + \A L \x20 $cfs_root /subsystems/ (? [^/]+) /allowed_hosts/ (? [^/]+) \z +}nxx; +my $RE_CFS_OTHER_ENTRY = qr{\A [DL] \x20 $cfs_root /}nxx; +my $RE_CFS_NS_ATTR = qr{ + \A $cfs_root /subsystems/ (? [^/]+) /namespaces/ (? [0-9]+) + / (? enable | device_path | device_uuid | buffered_io) : (? .*) \z +}nxx; +my $RE_CFS_SUBSYS_ATTR = qr{ + \A $cfs_root /subsystems/ (? [^/]+) + / (? attr_model | attr_serial | attr_allow_any_host) : (? .*) \z +}nxx; +my $RE_CFS_PORT_ATTR = qr{ + \A $cfs_root /ports/ (? [0-9]+) + / (? addr_trtype | addr_adrfam | addr_traddr | addr_trsvcid) : (? .*) \z +}nxx; +my $RE_CFS_KEY_DIGEST = qr{ + \A (? [0-9a-f]{64}) \x20 [\x20*] $cfs_root /hosts/ (? [^/]+) /dhchap_key \z +}nxx; +my $RE_CFS_OTHER_ATTR = qr{\A $cfs_root /}nxx; + +sub verify_nvme_nqn($value, $noerr = undef) { + + if ( + length($value) > 223 + || $value !~ $RE_NQN + ) { + return undef if $noerr; + die "value is not a valid NVMe qualified name\n"; + } + + return $value; +} + +sub parse_nvme_host_nqns($value, $noerr = undef) { + my $result = []; + my $seen = {}; + + for my $hostnqn (split(/,/, $value // '')) { + $hostnqn = trim($hostnqn); + if (!verify_nvme_nqn($hostnqn, 1) || $seen->{$hostnqn}++) { + return undef if $noerr; + die "invalid or duplicate NVMe host NQN '$hostnqn'\n"; + } + push $result->@*, $hostnqn; + if (scalar($result->@*) > $max_hosts) { + return undef if $noerr; + die "at most $max_hosts NVMe host NQNs are supported\n"; + } + } + + if (!$result->@*) { + return undef if $noerr; + die "at least one NVMe host NQN is required\n"; + } + + return $result; +} + +my sub nvmet_server($scfg) { + return $scfg->{server}; +} + +my sub nvmet_ssh_key($scfg) { + return "$id_rsa_path/" . nvmet_server($scfg) . '_id_rsa'; +} + +my sub nvmet_lock_id($scfg) { + my $server = nvmet_server($scfg) // ''; + return 'zfsnvme-' . ($server =~ s/[^A-Za-z0-9.-]/_/gr); +} + +my sub secret_path($storeid) { + die "invalid storage ID\n" if !defined($storeid) || $storeid !~ $RE_STORAGE_ID; + return "$secret_dir/$+{storeid}.nvme-dhchap"; +} + +my sub nvmet_nqn($scfg) { + my $nqn = $scfg->{subsysnqn}; + die "invalid NVMe subsystem NQN\n" if !defined($nqn) || !verify_nvme_nqn($nqn, 1); + return $nqn; +} + +my sub nvmet_pool($scfg) { + my $pool = $scfg->{pool}; + die "invalid ZFS pool name\n" if !defined($pool) || $pool !~ $RE_NVMET_POOL; + return $pool; +} + +my sub nvmet_dataset($scfg, $name) { + die "invalid ZFS volume name\n" if !defined($name) || $name !~ $RE_NVMET_DATASET_NAME; + my $volume = $+{name}; + return nvmet_pool($scfg) . "/$volume"; +} + +# zfs destroy reads '%' and ',' in a snapshot name as a range and a list. +my sub nvmet_snapshot($scfg, $name, $snap) { + die "invalid snapshot name\n" if !defined($snap) || $snap !~ $RE_NVMET_SNAPSHOT; + my $tag = $+{snap}; + return nvmet_dataset($scfg, $name) . "\@$tag"; +} + +# These return the captured text, or undef if the value is not valid. +my sub nvmet_nsid($value) { + return undef if !defined($value) || $value !~ $RE_NVMET_NSID; + my $nsid = $+{nsid}; + return $nsid <= $nvmet_max_nsid ? $nsid : undef; +} + +my sub nvmet_uuid($value) { + return defined($value) && $value =~ $RE_NVMET_UUID ? $+{uuid} : undef; +} + +my sub nvmet_canonical_address($address) { + return $address if !defined($address) || index($address, ':') < 0; + my $packed = inet_pton(AF_INET6, $address) // return $address; + return inet_ntop(AF_INET6, $packed); +} + +# Target-provided names only appear in messages when they are well-formed. +my sub nvmet_label($name) { + return $name =~ $RE_NQN ? " '$name'" : ''; +} + +my sub nvmet_template_twin($name) { + return '' if $name !~ $RE_NVMET_TEMPLATE_ZVOL; + my $twin = ($+{type} eq 'vm' ? 'base' : 'vm') . "-$+{suffix}"; + return substr($name, 0, $-[0]) . "/$twin"; +} + +# ZFS waits for transaction groups, which a busy pool can take minutes to sync +my sub nvmet_long_timeout() { + return PVE::RPCEnvironment->is_worker() ? 60 * 60 : 60; +} + +# A step is an argv array, a configfs write (hash with write and value) or a key write (hash with +# key) fed from stdin. A unit is a list of steps that must stay in one call. + +my sub nvmet_subsys_path($nqn) { + return "$nvmet_root/subsystems/$nqn"; +} + +my sub nvmet_ns_path($nqn, $nsid) { + return "$nvmet_root/subsystems/$nqn/namespaces/$nsid"; +} + +my sub nvmet_port_path($id) { + return "$nvmet_root/ports/$id"; +} + +my sub nvmet_host_path($hostnqn) { + return "$nvmet_root/hosts/$hostnqn"; +} + +my sub nvmet_write($path, $value) { + return { write => $path, value => $value }; +} + +my sub nvmet_namespaces($cfs, $nqn) { + my $subsys = $cfs->{subsystems}->{$nqn}; + return ($subsys ? $subsys->{namespaces} : undef) // {}; +} + +my sub nvmet_port_linked($cfs, $id, $nqn) { + my $port = $cfs->{ports}->{$id}; + return $port && ($port->{links} // {})->{$nqn}; +} + +# The first subsystem, by NQN, that allows each host +my sub nvmet_linked_hosts($cfs) { + my %linked; + for my $nqn (sort keys $cfs->{subsystems}->%*) { + $linked{$_} //= $nqn for keys(($cfs->{subsystems}->{$nqn}->{acl} // {})->%*); + } + return \%linked; +} + +# Creation stopped after the model write and before the serial: nobody else writes our model and +# nothing is exported, so completing it is safe. A default model may belong to another tool. +my sub nvmet_unfinished_subsystem($cfs, $nqn) { + my $subsys = $cfs->{subsystems}->{$nqn}; + return 0 if !$subsys; + return + $subsys->{attr_model} eq $nvmet_model + && !($subsys->{namespaces} // {})->%* + && !($subsys->{acl} // {})->%* + && !grep { nvmet_port_linked($cfs, $_, $nqn) } keys $cfs->{ports}->%*; +} + +# Same write order as the kernel requires: the device before enabling it. +my sub nvmet_build_unit($nqn, $nsid, $uuid, $dev) { + my $ns = nvmet_ns_path($nqn, $nsid); + return [ + ['test', '-b', $dev], + ['mkdir', $ns], + nvmet_write("$ns/device_path", $dev), + nvmet_write("$ns/device_uuid", $uuid), + nvmet_write("$ns/buffered_io", 0), + nvmet_write("$ns/enable", 1), + ]; +} + +my sub nvmet_enable_unit($nqn, $nsid, $dev) { + return [['test', '-b', $dev], nvmet_write(nvmet_ns_path($nqn, $nsid) . '/enable', 1)]; +} + +my sub nvmet_unexport_unit($nqn, $nsid, $enabled) { + my $ns = nvmet_ns_path($nqn, $nsid); + return [($enabled ? (nvmet_write("$ns/enable", 0)) : ()), ['rmdir', $ns]]; +} + +my sub nvmet_identity($nqn, $nsid, $uuid) { + return ("proxmox:nvme-subsys=$nqn", "proxmox:nvme-nsid=$nsid", "proxmox:nvme-uuid=$uuid"); +} + +my sub nvmet_zfs_inventory_step($pool) { + return [ + 'zfs', + 'get', + '-H', + '-p', + '-d', + '1', + '-t', + 'filesystem,volume', + '-o', + 'name,property,value,source', + join(',', @nvmet_zfs_props), + $pool, + ]; +} + +# Keys are never read back, only their sha256. Only the kernel's own groups of unused objects are +# skipped, so an object of another tool with one of their names is still listed. +my sub nvmet_configfs_step($hostnqns) { + my @names = map { ('-o', '-name', $_) } @nvmet_cfs_attrs; + shift @names; + my @keys = map { ('-o', '-path', nvmet_host_path($_) . '/dhchap_key') } $hostnqns->@*; + shift @keys; + return [ + 'env', + 'LC_ALL=C', + 'find', + $nvmet_root, + '(', + '-path', + "$nvmet_root/subsystems/*/passthru", + '-o', + '-path', + "$nvmet_root/ports/*/ana_groups", + '-o', + '-path', + "$nvmet_root/ports/*/referrals", + ')', + '-type', + 'd', + '-prune', + '-o', + '-type', + 'd', + '-exec', + 'printf', + 'D %s\n', + '{}', + '+', + '-o', + '-type', + 'l', + '-exec', + 'printf', + 'L %s\n', + '{}', + '+', + '-o', + '-type', + 'f', + '(', + @names, + ')', + '-exec', + 'grep', + '', + '/dev/null', + '{}', + '+', + (@keys ? ('-o', '-type', 'f', '(', @keys, ')', '-exec', 'sha256sum', '{}', '+') : ()), + ]; +} + +my sub nvmet_state_steps($pool, $hostnqns, $modprobe) { + return [ + ($modprobe ? (['modprobe', 'nvmet_tcp']) : ()), + nvmet_zfs_inventory_step($pool), + ['printf', '%s\n', $nvmet_marker], + nvmet_configfs_step($hostnqns), + ]; +} + +my sub nvmet_valid_word($word) { + return defined($word) && !ref($word) && $word !~ /[\0\r\n]/; +} + +my sub nvmet_valid_path($path) { + return nvmet_valid_word($path) && $path =~ m{\A/}; +} + +my sub nvmet_quote($word) { + return PVE::Tools::shellquote($word); +} + +# Renders steps into one POSIX shell command line: commands joined with `&&`, `>` for configfs +# writes and one `dd | tee` pipe for a key. No loops, variables or substitutions, every word is +# quoted and every operand comes from validated configuration. +sub _nvmet_render($steps) { + my $invalid = "internal error: invalid NVMe target step\n"; + die $invalid if ref($steps) ne 'ARRAY' || !$steps->@*; + + my $keys = 0; + my @commands; + for my $step ($steps->@*) { + if (ref($step) eq 'ARRAY') { + die $invalid if !$step->@* || grep { !nvmet_valid_word($_) } $step->@*; + die $invalid if !$nvmet_commands{ $step->[0] }; + push @commands, join(' ', map { nvmet_quote($_) } $step->@*); + } elsif (ref($step) eq 'HASH' && exists($step->{write})) { + die $invalid + if keys($step->%*) != 2 + || !nvmet_valid_path($step->{write}) + || !nvmet_valid_word($step->{value}); + push @commands, + q{printf '%s\n' } + . nvmet_quote($step->{value}) . ' > ' + . nvmet_quote($step->{write}); + } elsif (ref($step) eq 'HASH' && exists($step->{key})) { + my $paths = $step->{key}; + die $invalid + if keys($step->%*) != 1 + || ref($paths) ne 'ARRAY' + || !$paths->@* + || grep { !nvmet_valid_path($_) } $paths->@*; + $keys++; + die $invalid if $keys > 1; + # configfs needs the whole key in one write(2). dd collects its + # input into one output block: GNU dd without bs=, busybox dd only + # when ibs and obs differ. tee writes it to every host object. + push @commands, + 'dd ibs=4096 obs=8192 2>/dev/null | tee ' + . join(' ', map { nvmet_quote($_) } $paths->@*) + . ' >/dev/null'; + } else { + die $invalid; + } + } + return join(' && ', @commands); +} + +# Packs whole units into calls of at most $max bytes of rendered command, the +# single argument sshd runs, below its limit. A rendered command is ASCII +# (every operand is validated), so its length is its size in bytes. +sub _nvmet_chunk($units, $max = $nvmet_max_command) { + my (@chunks, @current); + for my $unit ($units->@*) { + my @next = (@current, $unit->@*); + if (length(_nvmet_render(\@next)) > $max) { + die "internal error: NVMe target command too long\n" + if !@current || length(_nvmet_render($unit)) > $max; + push @chunks, [@current]; + @next = $unit->@*; + } + @current = @next; + } + push @chunks, [@current] if @current; + return \@chunks; +} + +# Never propagate the context that run_command adds to the task marker, it quotes the command line. +my sub rethrow_task_interrupt($error) { + die "received interrupt\n" if $error =~ $RE_TASK_INTERRUPT; +} + +# The only code that runs anything on the target. Returns a hash with rc (-1 when ssh did not run +# to its end), out (the lines) and err (the text). It never dies on a failing command, but a +# stopped task dies with the task marker. %opts are op (label, required), timeout and input +# (stdin, for keys). +sub _nvmet_run($scfg, $steps, %opts) { + die "internal error: NVMe target call without label\n" if !defined($opts{op}); + my $command = _nvmet_render($steps); + die "internal error: NVMe target command too long\n" if length($command) > $nvmet_max_command; + # Not build_ssh_command: it quotes every remote word, and $command is one finished script. The + # extra quoting layer would grow it beyond what _nvmet_chunk measures against its size budget. + my $cmd = + [@ssh_cmd, '-i', nvmet_ssh_key($scfg), '--', 'root@' . nvmet_server($scfg), $command]; + my (@out, $err); + my $rc = 0; + # Not noerr, as run_command would then swallow the interrupt of a stopped task too. + eval { + run_command( + $cmd, + timeout => $opts{timeout} // 15, + outfunc => sub($line) { push @out, $line }, + errfunc => sub($line) { $err = $line if !defined($err) && $line ne '' }, + (defined($opts{input}) ? (input => $opts{input}) : ()), + ); + }; + if (my $error = $@) { + rethrow_task_interrupt($error); + return { rc => -1, out => [], err => 'timeout' } if $error =~ $RE_COMMAND_TIMEOUT; + return { rc => -1, out => [], err => 'ssh failed' } if $error !~ $RE_COMMAND_EXIT; + $rc = $+{code}; + } + return { rc => $rc, out => \@out, err => $err // ($rc ? "exit code $rc" : '') }; +} + +# _now, _sleep and the other local I/O subs are package subs so that tests can mock them +sub _now() { + return Time::HiRes::clock_gettime(Time::HiRes::CLOCK_MONOTONIC()); +} + +sub _sleep($seconds) { + Time::HiRes::sleep($seconds); + return; +} + +sub _nvmet_split_state($text) { + my @parts = split /^\Q$nvmet_marker\E\n/m, $text, -1; + die "malformed NVMe target state\n" if @parts != 2; + return @parts; +} + +sub _nvmet_property_value($value, $source) { + die "malformed ZFS property value\n" + if !defined($value) + || !defined($source) + || $value eq '' + || $source eq '' + || $value =~ /[\r\n\t]/ + || $source =~ /[\r\n\t]/; + return $value if $source eq 'local' || $source eq 'received'; + return '-' if $value eq '-' && $source eq '-'; + if ($source =~ $RE_NVMET_INHERITED) { + die "invalid ZFS pool name\n" if $+{source} !~ $RE_NVMET_POOL; + return '-'; + } + die "invalid ZFS property source\n"; +} + +# The inventory must be complete or the read fails. Children with names PVE never uses (for example +# with a space) stay datasets but never count as owned. +sub _nvmet_parse_zfs_inventory($text, $pool) { + die "invalid ZFS pool name\n" if $pool !~ $RE_NVMET_POOL; + + my (%rows, %foreign); + for my $line (split /\n/, $text) { + my @fields = split /\t/, $line, -1; + die "malformed ZFS inventory row\n" if @fields != 4 || $line =~ /\r/; + my ($dataset, $property, $value, $source) = @fields; + if ($dataset ne $pool) { + die "ZFS dataset is outside configured pool\n" if index($dataset, "$pool/") != 0; + my $child = substr($dataset, length($pool) + 1); + die "ZFS dataset is outside configured pool\n" + if $child eq '' || index($child, '/') >= 0; + $foreign{$dataset} = 1 if $child !~ $RE_NVMET_DATASET_NAME; + } + my $on = $foreign{$dataset} ? '' : " on '$dataset'"; + my $key = $nvmet_zfs_keys{$property} // die "unexpected ZFS property$on\n"; + die "duplicate ZFS property '$property'$on\n" if exists($rows{$dataset}->{$key}); + if ($key eq 'type') { + die "invalid ZFS dataset type$on\n" + if ($value ne 'filesystem' && $value ne 'volume') || $source ne '-'; + $rows{$dataset}->{type} = $value; + } else { + $rows{$dataset}->{$key} = _nvmet_property_value($value, $source); + } + } + die "ZFS dataset inventory is missing the configured pool\n" if !$rows{$pool}; + + my (%types, %volumes); + for my $dataset (keys %rows) { + my $row = $rows{$dataset}; + die "incomplete ZFS properties" . ($foreign{$dataset} ? '' : " on '$dataset'") . "\n" + if keys($row->%*) != scalar(@nvmet_zfs_props); + $types{$dataset} = $row->{type}; + next if $row->{type} ne 'volume'; + # nvmet shows device_uuid and udev names the by-id link in lower case + $volumes{$dataset} = + $foreign{$dataset} + ? { nqn => '-', nsid => '-', uuid => '-' } + : { nqn => $row->{nqn}, nsid => $row->{nsid}, uuid => lc($row->{uuid}) }; + } + my $last_nsid = $rows{$pool}->{last_nsid}; + return { + types => \%types, + volumes => \%volumes, + last_nsid => nvmet_nsid($last_nsid) // 0, + }; +} + +# every object must be complete, unknown objects of newer kernels are ignored +sub _nvmet_parse_configfs($text) { + my $state = { subsystems => {}, ports => {}, hosts => {} }; + my (%top, %dir); + + my $subsystem = sub($nqn) { + return $state->{subsystems}->{$nqn} //= { acl => {}, namespaces => {} }; + }; + my $namespace = sub($nqn, $nsid) { + return $subsystem->($nqn)->{namespaces}->{$nsid} //= {}; + }; + my $port = sub($id) { return $state->{ports}->{$id} //= { links => {} } }; + my $host = sub($hostnqn) { return $state->{hosts}->{$hostnqn} //= { key_sha256 => undef } }; + my $set = sub($object, $attr, $value) { + die "duplicate NVMe target configfs attribute\n" if exists($object->{$attr}); + $object->{$attr} = $value; + }; + + for my $line (split /\n/, $text) { + if ($line =~ $RE_CFS_TOP) { + $top{ $+{top} // 'root' } = 1; + } elsif ($line =~ $RE_CFS_SUBSYS_DIR) { + my $nqn = $+{nqn}; + $subsystem->($nqn); + $dir{"subsystem $nqn"} = 1; + } elsif ($line =~ $RE_CFS_SUBSYS_GROUP || $line =~ $RE_CFS_PORT_GROUP) { + # default groups, always present with their parent + } elsif ($line =~ $RE_CFS_NS_DIR) { + my ($nqn, $nsid) = @+{qw(nqn nsid)}; + $namespace->($nqn, $nsid); + $dir{"namespace $nqn/$nsid"} = 1; + } elsif ($line =~ $RE_CFS_PORT_DIR) { + my $id = $+{port}; + $port->($id); + $dir{"port $id"} = 1; + } elsif ($line =~ $RE_CFS_HOST_DIR) { + my $hostnqn = $+{host}; + $host->($hostnqn); + $dir{"host $hostnqn"} = 1; + } elsif ($line =~ $RE_CFS_PORT_LINK) { + my ($id, $nqn) = @+{qw(port nqn)}; + $port->($id)->{links}->{$nqn} = 1; + } elsif ($line =~ $RE_CFS_ACL_LINK) { + my ($nqn, $hostnqn) = @+{qw(nqn host)}; + $subsystem->($nqn)->{acl}->{$hostnqn} = 1; + } elsif ($line =~ $RE_CFS_OTHER_ENTRY) { + # objects of a shape the plugin does not use + } elsif ($line =~ $RE_CFS_NS_ATTR) { + my ($nqn, $nsid, $attr, $value) = @+{qw(nqn nsid attr value)}; + $set->($namespace->($nqn, $nsid), $attr, $value); + } elsif ($line =~ $RE_CFS_SUBSYS_ATTR) { + my ($nqn, $attr, $value) = @+{qw(nqn attr value)}; + $set->($subsystem->($nqn), $attr, $value); + } elsif ($line =~ $RE_CFS_PORT_ATTR) { + my ($id, $attr, $value) = @+{qw(port attr value)}; + $set->($port->($id), $attr, $value); + } elsif ($line =~ $RE_CFS_KEY_DIGEST) { + my ($sha, $hostnqn) = @+{qw(sha host)}; + my $object = $host->($hostnqn); + die "duplicate DH-HMAC-CHAP key digest" . nvmet_label($hostnqn) . "\n" + if defined($object->{key_sha256}); + $object->{key_sha256} = $sha; + } elsif ($line =~ $RE_CFS_OTHER_ATTR) { + # attribute of an object shape the plugin does not use + } else { + die "unexpected NVMe target configfs line\n"; + } + } + + for my $name (qw(root hosts ports subsystems)) { + die "NVMe target configfs is unavailable\n" if !$top{$name}; + } + for my $nqn (keys $state->{subsystems}->%*) { + my $subsys = $state->{subsystems}->{$nqn}; + die "incomplete NVMe subsystem" . nvmet_label($nqn) . "\n" + if !$dir{"subsystem $nqn"} + || grep { !defined($subsys->{$_}) } qw(attr_model attr_serial attr_allow_any_host); + for my $nsid (keys $subsys->{namespaces}->%*) { + my $ns = $subsys->{namespaces}->{$nsid}; + die "incomplete NVMe namespace '$nsid' of subsystem" . nvmet_label($nqn) . "\n" + if !$dir{"namespace $nqn/$nsid"} + || grep { !defined($ns->{$_}) } qw(enable device_path device_uuid buffered_io); + } + } + for my $id (keys $state->{ports}->%*) { + my $object = $state->{ports}->{$id}; + my @attrs = qw(addr_trtype addr_adrfam addr_traddr addr_trsvcid); + die "incomplete NVMe port '$id'\n" + if !$dir{"port $id"} || grep { !defined($object->{$_}) } @attrs; + } + for my $hostnqn (keys $state->{hosts}->%*) { + die "DH-HMAC-CHAP key digest for unknown NVMe host" . nvmet_label($hostnqn) . "\n" + if !$dir{"host $hostnqn"}; + } + return $state; +} + +sub _nvmet_parse_mounts($text) { + for my $line (split /\n/, $text) { + my (undef, $mountpoint, $type) = split / /, $line; + return 1 if ($mountpoint // '') eq '/sys/kernel/config' && ($type // '') eq 'configfs'; + } + return 0; +} + +sub _nvmet_serial($nqn) { + return 'PVEZFS' . substr(sha256_hex($nqn), 0, 14); +} + +sub _nvmet_template_name($dataset) { + die "only VM zvols can become templates\n" + if $dataset !~ $RE_NVMET_TEMPLATE_ZVOL || $+{type} ne 'vm'; + return nvmet_template_twin($dataset); +} + +# refuses a volume whose identity another owned volume duplicates anywhere in the pool +sub _nvmet_owned_identity($inv, $nqn, $dataset) { + my $type = $inv->{types}->{$dataset} // die "ZFS volume '$dataset' does not exist\n"; + die "'$dataset' is not a ZFS volume\n" if $type ne 'volume'; + my $row = $inv->{volumes}->{$dataset}; + die "ZFS volume '$dataset' is not owned by NVMe subsystem '$nqn'\n" if $row->{nqn} ne $nqn; + my $nsid = nvmet_nsid($row->{nsid}) // die "invalid NSID on '$dataset'\n"; + my $uuid = nvmet_uuid($row->{uuid}) // die "invalid namespace UUID on '$dataset'\n"; + for my $other (keys $inv->{volumes}->%*) { + next if $other eq $dataset; + my $identity = $inv->{volumes}->{$other}; + next if $identity->{nqn} ne $nqn; + die "duplicate NVMe identity on '$dataset'\n" + if $identity->{nsid} eq $nsid || $identity->{uuid} eq $uuid; + } + return ($nsid, $uuid); +} + +# validates every owned volume first, so a bad identity refuses the whole plan before any change +sub _nvmet_desired_namespaces($inv, $nqn) { + my (%desired, %uuids); + for my $dataset (sort keys $inv->{volumes}->%*) { + my $row = $inv->{volumes}->{$dataset}; + next if $row->{nqn} ne $nqn; + my $nsid = nvmet_nsid($row->{nsid}) // die "invalid NSID on '$dataset'\n"; + my $uuid = nvmet_uuid($row->{uuid}) // die "invalid namespace UUID on '$dataset'\n"; + die "duplicate NSID '$nsid'\n" if $desired{$nsid}; + die "duplicate namespace UUID '$uuid'\n" if $uuids{ lc($uuid) }++; + $desired{$nsid} = [$uuid, "/dev/zvol/$dataset"]; + } + return \%desired; +} + +# NSIDs grow past the last one handed out in the pool, so a host that missed a namespace removal +# never sees a new volume at an old NSID. Only when they run out is the lowest free one used. +sub _nvmet_allocate_nsid($inv, $cfs, $nqn) { + my %used; + for my $row (values $inv->{volumes}->%*) { + $used{ $row->{nsid} } = 1 if $row->{nqn} eq $nqn && defined(nvmet_nsid($row->{nsid})); + } + $used{$_} = 1 for keys nvmet_namespaces($cfs, $nqn)->%*; + + my $highest = max(0, $inv->{last_nsid} // 0, keys %used); + return $highest + 1 if $highest < $nvmet_max_nsid; + my $nsid = 1; + $nsid++ while $used{$nsid}; + die "no free namespace ID\n" if $nsid > $nvmet_max_nsid; + return $nsid; +} + +# The state is present, disabled, absent, incomplete (a disabled namespace with another identity, +# for example one being built), stale (enabled on the other template name of the zvol) or nosubsys. +sub _nvmet_export_state($cfs, $nqn, $nsid, $uuid, $dev) { + return 'nosubsys' if !$cfs->{subsystems}->{$nqn}; + my $namespaces = nvmet_namespaces($cfs, $nqn); + for my $id (keys $namespaces->%*) { + next if $id eq $nsid; + die "namespace UUID '$uuid' is already in use\n" + if $namespaces->{$id}->{device_uuid} eq $uuid; + } + my $ns = $namespaces->{$nsid} // return 'absent'; + if ($ns->{device_uuid} eq $uuid && $ns->{device_path} eq $dev) { + return $ns->{enable} eq '1' ? 'present' : 'disabled'; + } + # A template conversion or its undo that ssh gave up on can rename the zvol on the target after + # an activation exported it under its old name. + my $twin = nvmet_template_twin($dev); + return 'stale' + if $ns->{enable} eq '1' + && $ns->{device_uuid} eq $uuid + && $twin ne '' + && $ns->{device_path} eq $twin; + die "NVMe namespace ID '$nsid' has a different identity; refusing to replace it\n" + if $ns->{enable} ne '0'; + return 'incomplete'; +} + +# A disabled namespace with another identity, or a stale one (of a template or a failed conversion, +# so no guest uses it), is rebuilt, which is only correct under the target lock. +sub _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev) { + die "NVMe subsystem does not exist\n" if !$cfs->{subsystems}->{$nqn}; + my $state = _nvmet_export_state($cfs, $nqn, $nsid, $uuid, $dev); + return ([nvmet_build_unit($nqn, $nsid, $uuid, $dev)], 'absent') if $state eq 'absent'; + return ([], 'present') if $state eq 'present'; + return ([nvmet_enable_unit($nqn, $nsid, $dev)], 'disabled') if $state eq 'disabled'; + my $unexport = nvmet_unexport_unit($nqn, $nsid, $state eq 'stale'); + my $build = nvmet_build_unit($nqn, $nsid, $uuid, $dev); + return ([[$unexport->@*, $build->@*]], $state eq 'stale' ? 'stale' : 'reclaim'); +} + +sub _nvmet_plan_unexport($cfs, $nqn, $uuid) { + my $namespaces = nvmet_namespaces($cfs, $nqn); + my @matches = grep { $namespaces->{$_}->{device_uuid} eq $uuid } + sort { $a <=> $b } keys $namespaces->%*; + die "duplicate namespace UUID '$uuid'\n" if @matches > 1; + return ([], undef) if !@matches; + my $enabled = $namespaces->{ $matches[0] }->{enable} eq '1'; + return ( + [nvmet_unexport_unit($nqn, $matches[0], $enabled)], + { nsid => $matches[0], enabled => $enabled }, + ); +} + +# among matching ports the one linked to $nqn wins, then the lowest id, incomplete ports never match +sub _nvmet_find_port($cfs, $nqn, $portal) { + my $wanted = nvmet_canonical_address($portal->{address}); + my @matches = grep { + my $port = $cfs->{ports}->{$_}; + $port->{addr_trtype} eq 'tcp' + && $port->{addr_adrfam} eq $portal->{family} + && $port->{addr_traddr} ne '' + && $port->{addr_trsvcid} eq "$portal->{port}" + && nvmet_canonical_address($port->{addr_traddr}) eq $wanted + } sort { + $a <=> $b + } keys $cfs->{ports}->%*; + my @linked = grep { nvmet_port_linked($cfs, $_, $nqn) } @matches; + return $linked[0] // $matches[0]; +} + +sub _nvmet_plan_activation($inv, $cfs, $conf) { + my ($nqn, $keysha) = $conf->@{qw(nqn keysha)}; + my $desired = _nvmet_desired_namespaces($inv, $nqn); # refuse before any unit + my $subsys_path = nvmet_subsys_path($nqn); + my $subsys = $cfs->{subsystems}->{$nqn}; + my (@objects, @key_hosts, @acls, @namespaces, %port_ids); + + if (!$subsys) { + push @objects, + [ + ['mkdir', $subsys_path], + nvmet_write("$subsys_path/attr_model", $nvmet_model), + nvmet_write("$subsys_path/attr_serial", _nvmet_serial($nqn)), + nvmet_write("$subsys_path/attr_allow_any_host", 0), + ]; + } else { + my $serial = _nvmet_serial($nqn); + my @attrs; + if ($subsys->{attr_model} ne $nvmet_model || $subsys->{attr_serial} ne $serial) { + die "refusing to take over existing NVMe subsystem '$nqn': it was not created by" + . " Proxmox VE; remove it on the target or use another NQN\n" + if !nvmet_unfinished_subsystem($cfs, $nqn); + push @attrs, nvmet_write("$subsys_path/attr_serial", $serial); + } + push @attrs, nvmet_write("$subsys_path/attr_allow_any_host", 0) + if $subsys->{attr_allow_any_host} ne '0'; + push @objects, [@attrs] if @attrs; + } + + my %taken = map { $_ => 1 } keys $cfs->{ports}->%*; + for my $portal ($conf->{portals}->@*) { + my $id = _nvmet_find_port($cfs, $nqn, $portal); + if (!defined($id)) { + $id = 1; + $id++ while $taken{$id}; + $taken{$id} = 1; + my $port_path = nvmet_port_path($id); + push @objects, + [ + ['mkdir', $port_path], + nvmet_write("$port_path/addr_trtype", 'tcp'), + nvmet_write("$port_path/addr_adrfam", $portal->{family}), + nvmet_write("$port_path/addr_traddr", $portal->{address}), + nvmet_write("$port_path/addr_trsvcid", $portal->{port}), + ]; + } + $port_ids{$id} = 1; + } + + # nvmet keeps the key on the global host object. A key that differs from ours is only replaced + # while no subsystem links the host. + my $linked = nvmet_linked_hosts($cfs); + for my $hostnqn ($conf->{hostnqns}->@*) { + my $host_path = nvmet_host_path($hostnqn); + if (my $host = $cfs->{hosts}->{$hostnqn}) { + my $sha = $host->{key_sha256} + // die "NVMe target does not expose a DH-HMAC-CHAP key for host '$hostnqn'\n"; + if ($sha ne $keysha) { + # a subsystem left behind by a removed storage or a failed add still links the host + if (defined(my $holder = $linked->{$hostnqn})) { + my $label = nvmet_label($holder); + die "refusing to replace an in-use DH-HMAC-CHAP key for '$hostnqn': " + . ($label ne '' ? "subsystem$label" : 'another subsystem') + . " still allows this host. Remove it on the target first\n"; + } + push @key_hosts, $host_path; + } + } else { + push @objects, [['mkdir', $host_path]]; + push @key_hosts, $host_path; + } + push @acls, [['ln', '-s', $host_path, "$subsys_path/allowed_hosts/$hostnqn"]] + if !$subsys || !($subsys->{acl} // {})->{$hostnqn}; + } + # nvmet creates the key attributes world-readable. The chmod before the write keeps later opens + # from reading the key, but a descriptor opened earlier is not affected. + my @keys; + if (@key_hosts) { + my @attrs = map { ("$_/dhchap_key", "$_/dhchap_ctrl_key") } @key_hosts; + @keys = ([['chmod', '0600', @attrs], { key => [map { "$_/dhchap_key" } @key_hosts] }]); + } + + my $current = { subsystems => { $nqn => $subsys // { acl => {}, namespaces => {} } } }; + for my $nsid (sort { $a <=> $b } keys $desired->%*) { + my ($units) = _nvmet_plan_export($current, $nqn, $nsid, $desired->{$nsid}->@*); + push @namespaces, $units->@*; + } + my $existing = nvmet_namespaces($cfs, $nqn); + for my $nsid (sort { $a <=> $b } keys $existing->%*) { + next if $desired->{$nsid}; + push @namespaces, nvmet_unexport_unit($nqn, $nsid, $existing->{$nsid}->{enable} eq '1'); + } + + return { + prepublish => [@objects, @keys, @acls, @namespaces], + port_ids => [sort { $a <=> $b } keys %port_ids], + }; +} + +# One call per port: each link repeats the guards, so it only succeeds while the subsystem denies +# unknown hosts and every configured host has its ACL, which only a manager of the target outside +# this cluster can change after the verify read. +sub _nvmet_plan_publish($cfs, $nqn, $port_ids, $hostnqns) { + my $subsys_path = nvmet_subsys_path($nqn); + my %wanted = map { $_ => 1 } $port_ids->@*; + my @guards = ( + ['grep', '-qx', '0', "$subsys_path/attr_allow_any_host"], + map { ['test', '-L', "$subsys_path/allowed_hosts/$_"] } $hostnqns->@*, + ); + + my @units; + for my $id ($port_ids->@*) { + next if nvmet_port_linked($cfs, $id, $nqn); + my $link = ['ln', '-s', $subsys_path, nvmet_port_path($id) . "/subsystems/$nqn"]; + push @units, { port => $id, action => 'link', steps => [@guards, $link] }; + } + for my $id (sort { $a <=> $b } keys $cfs->{ports}->%*) { + next if $wanted{$id} || !nvmet_port_linked($cfs, $id, $nqn); + my $unlink = ['rm', nvmet_port_path($id) . "/subsystems/$nqn"]; + push @units, { port => $id, action => 'unlink', steps => [$unlink] }; + } + return \@units; +} + +1; -- 2.54.0.windows.1