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 3161E1FF0B3 for ; Thu, 26 Nov 2026 16:10:33 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id A28DF2174F; Thu, 26 Nov 2026 16:10:14 +0100 (CET) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=neatech-ar.20260707.gappssmtp.com; s=20260707; t=1795705802; x=1796310602; 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=fvsrSOOzDz5zl/Q7iMAXyDrfuHQwZ1sC8TktnKpoo7o=; b=haTshst2t5aPc3QRg62GtrYNPtqkfRCznBAhI3JqsczBpiNPE//TTLVRMdtVgFHvxl GlCY65lA0L6cx9VCPdwT488RB5xXqmmaQFxjGB668q6YoLPx1VeNzZyM0rYeN2vY4XzO 84awSf5XoE8EId7b7woZT1z2/8jnfoa/QxEN+5Zhw1HiES2AkCbdCP/uz6WP7GkjfKD4 7PB7ke6pcgnMm0vQbHj2PQoCVa6x4ICUV0o+H0HqM1hOAGXrapiE0s6EiEP1+uQ1hwqe YS716iK1brymlgq4WyrSdw2SYX1JVM9rvwnmamuTrLDAGbfhyXaIzQ33gBy5C3yXpHRN qjAA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795705802; x=1796310602; 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=fvsrSOOzDz5zl/Q7iMAXyDrfuHQwZ1sC8TktnKpoo7o=; b=hpsr+PKRXVsse5Y3QLVW05xia8QG/waftKWKbilyMY12Zjay6zD8XuHnvaE5qOZZMp 36V1cv1etthYmD1pTY61EdtMDEOssbn3DuutqPTNbdQ5uxp/65H5sMBeBK7qyJJ5ZJB1 JAZ8IdWBFL872GZbKcFyXhX69RaJj0EIddfGfC4atC1nIObvuqeHeKCZ6t684/YITDy+ XvSpghkBlh39DtSDRr3t/GM7kAo2+Qe2iY3bj4Mi4B/UhIUUKhku7LjOzc5otKngrxAf nT4l7X/FpprrUsxY0+yeo61Pme1B8mM2y8/fHz6ikWINcZgBWhj8RPVUPTRdGk2F3NYj SiEw== X-Gm-Message-State: APuU4Z+pzUpUuu6joU0VMs2ZyEx3BTT0FiB43R5tMGIG8FFQdS4FMUqw i4o/lpZoQMJMalDLHu823XpcBf9fhfo/J6cec9L0lIiaeXTE3kEF1MY7eGVIFbev9Ee8MvKn13g F+AYUPzM= X-Gm-Gg: AZFdTZettRpdnx3ptEeAaYUD28fMw1vhjDIGuGN40hSwSZLypMgOToKmsUf6Pwl8hFs nhK3qZf6c9YzmWuTLFZl+1ibrYRi3PjfCCewWSV59rKR7Nl01DKYNjoDKU3/Kzi3iIXF3QiQlyV rL59DxP952intub/mjNF3InZAmmJofvg/Fbp7AjE+NUl8zlIs2t7DZZKPj5NFTr1H/Y/HvP7kfY JiphBOCzf2FefqsZG4ng7brF62sQ6glQezJKlHkys5zvcxILfWKICElVJOtEXBTDDr3r2vhb5ZA y1HXqTtaSyjUa0xq6OPocWIA3lP65sLfy7b4AdXi0UIViWJA4cF06PiIFjZkye22Vfh08Zethts bUEBnfaige+oX38zn6lT3hPo0+f6yr7yUVPa6ytycsb+EM6ZslvLcaBusxD2NKxEadziydAuR0b HTWUEkE0UAkapodX8x9m31AToxWV8wMa4PBDLTS+QWx13kKi6tTUHrkgEBhApiTqSLqPjV4yv+f f6V1dleTEEiCsRdnnSleh2KgnH10mFW5RX8Qpnwzq5uFHNYKAO3ytB5hILNxcC7ShM4oyO1QLFz vjvvXSorkpOb0/6I7dLGVKE2muOOIKNx8dp9+XgO3PBsj2z3dl/mgX7sz9COOdoTPqebrBgJDy2 +gYqSZt7jifOhMl8EZQCPzfNqjtq1gA== X-Received: by 2002:a05:6102:8604:20b0:7d2:7784:23b5 with SMTP id ada2fe7eead31-7d72b3479fbmr13786309137.1.1795705801909; Thu, 26 Nov 2026 07:10:01 -0800 (PST) From: Joaquin Varela To: pve-devel@lists.proxmox.com Subject: [PATCH storage v5 02/13] zfsnvme: add the target transactions Date: Thu, 26 Nov 2026 12:09:43 -0300 Message-ID: <20261126150956.310593-3-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.300 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 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: FYOUGGYH47H73F7BR4A5636C2AOGCFT5 X-Message-ID-Hash: FYOUGGYH47H73F7BR4A5636C2AOGCFT5 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: Run the planned commands on the target under a pmxcfs domain lock per target server, and add the target side of creating, cloning, destroying, rolling back, resizing and templating a volume. The ZFS dataset is the source of truth for a namespace: its subsystem NQN, NSID and UUID are ZFS user properties, so an activation rebuilds the nvmet configuration after a target restart. An operation whose SSH connection broke is reported as unknown and repaired by the next activation. Signed-off-by: Joaquin Varela --- src/PVE/Storage/ZFSNVMePlugin.pm | 563 +++++++++++++++++++++++++++++++ 1 file changed, 563 insertions(+) diff --git a/src/PVE/Storage/ZFSNVMePlugin.pm b/src/PVE/Storage/ZFSNVMePlugin.pm index 270d559c..1892bd21 100644 --- a/src/PVE/Storage/ZFSNVMePlugin.pm +++ b/src/PVE/Storage/ZFSNVMePlugin.pm @@ -261,6 +261,10 @@ my sub nvmet_uuid($value) { return defined($value) && $value =~ $RE_NVMET_UUID ? $+{uuid} : undef; } +my sub nvmet_uint($value) { + return defined($value) && $value =~ $RE_UNSIGNED_INTEGER ? $+{value} : undef; +} + my sub nvmet_canonical_address($address) { return $address if !defined($address) || index($address, ':') < 0; my $packed = inet_pton(AF_INET6, $address) // return $address; @@ -1004,4 +1008,563 @@ sub _nvmet_plan_publish($cfs, $nqn, $port_ids, $hostnqns) { return \@units; } +my %nvmet_lock_owner; # pid of the process holding the domain lock, by lock id + +# Runs $code under the pmxcfs domain lock of the target. Not re-entrant like the pmxcfs lock, and +# a child forked inside is not the owner. +my sub nvmet_locked($scfg, $code) { + my $id = nvmet_lock_id($scfg); + die "cluster not quorate - refusing NVMe target changes\n" + if !PVE::Cluster::check_cfs_quorum(1); + my $res = PVE::Cluster::cfs_lock_domain( + $id, + $nvmet_lock_wait, + sub { + local $nvmet_lock_owner{$id} = $$; + return $code->(); + }, + ); + die $@ if $@; + return $res; +} + +# Runs steps on the target. %opts: op, timeout, input, change (the steps change the target, which +# needs the lock). +# +# ssh does not stop a command on the target when it gives up on it. A change whose connection +# broke (255), any call under the lock that ssh did not run to its end (-1) and a call during +# which the task was stopped may still be running there. Its outcome is unknown, so it is never +# compensated from a read that could come before the rest of it. The next activation repairs +# from the target state. +my sub nvmet_exec($scfg, $steps, %opts) { + my $locked = ($nvmet_lock_owner{ nvmet_lock_id($scfg) } // 0) == $$; + die "internal error: NVMe target change without target lock\n" + if $opts{change} && !$locked; + my $res = _nvmet_run( + $scfg, $steps, + op => $opts{op}, + timeout => $opts{timeout} // 15, + (defined($opts{input}) ? (input => $opts{input}) : ()), + ); + die "NVMe target operation '$opts{op}' did not complete ($res->{err});" + . " the target state is unknown\n" + if ($locked && $res->{rc} == -1) + || ($opts{change} && $res->{rc} == 255); + return $res; +} + +my sub nvmet_rethrow_abandoned($error) { + die $error if $error =~ $RE_NVMET_ABANDONED; +} + +my sub nvmet_unreachable($res) { + return $res->{rc} == 255 || $res->{rc} == -1; +} + +my sub nvmet_check($res, $op) { + die "NVMe target operation '$op' failed: $res->{err}\n" if $res->{rc}; +} + +my sub nvmet_read_failed($scfg, $res) { + die "NVMe target '" . nvmet_server($scfg) . "' is unreachable: $res->{err}\n" + if nvmet_unreachable($res); + die "cannot read NVMe target state: $res->{err}\n"; +} + +my sub nvmet_output($res) { + return join('', map { "$_\n" } $res->{out}->@*); +} + +# A read without the lock can meet a configfs object that another node removes while find lists +# it, which makes find fail once. Retry twice after 200 ms unless the target is unreachable. +my sub nvmet_read_call($scfg, $steps, %opts) { + my $res; + for my $attempt (0 .. 2) { + _sleep(0.2) if $attempt; + $res = nvmet_exec($scfg, $steps, %opts, timeout => 15); + last if !$res->{rc} || nvmet_unreachable($res); + } + return $res; +} + +# modprobe (locked reads only) loads nvmet_tcp, and with it nvmet, before the read and mounts +# configfs if the read fails. tolerant returns an empty list for a failed or unparsable read unless +# the target is unreachable. +my sub nvmet_read($scfg, %opts) { + my $pool = nvmet_pool($scfg); + my $hostnqns = $opts{keys} // []; + my @modprobe = $opts{modprobe} ? (change => 1) : (); + my $read = sub () { + return nvmet_read_call( + $scfg, + nvmet_state_steps($pool, $hostnqns, $opts{modprobe}), + op => 'read target state', + @modprobe, + ); + }; + my $res = $read->(); + if ($res->{rc} && $opts{modprobe} && !nvmet_unreachable($res)) { + my $mounts = nvmet_exec($scfg, [['cat', '/proc/mounts']], op => 'read mounts'); + nvmet_check($mounts, 'read mounts'); + if (!_nvmet_parse_mounts(nvmet_output($mounts))) { + my $mount = ['mount', '-t', 'configfs', 'none', '/sys/kernel/config']; + my $mounted = nvmet_exec($scfg, [$mount], op => 'mount configfs', change => 1); + nvmet_check($mounted, 'mount configfs'); + $res = $read->(); + } + } + if ($res->{rc}) { + return () if $opts{tolerant} && !nvmet_unreachable($res); + nvmet_read_failed($scfg, $res); + } + my @state = eval { + my ($zfs, $configfs) = _nvmet_split_state(nvmet_output($res)); + (_nvmet_parse_zfs_inventory($zfs, $pool), _nvmet_parse_configfs($configfs)); + }; + if (my $error = $@) { + return () if $opts{tolerant}; + die $error; + } + return @state; +} + +my sub nvmet_read_zfs($scfg) { + my $pool = nvmet_pool($scfg); + my $res = nvmet_read_call($scfg, [nvmet_zfs_inventory_step($pool)], op => 'read ZFS inventory'); + nvmet_read_failed($scfg, $res) if $res->{rc}; + return _nvmet_parse_zfs_inventory(nvmet_output($res), $pool); +} + +# A chain only saves SSH round trips: every decision was taken locally and `&&` only stops at the +# first failing command. Only the call with the key step gets stdin. +my sub nvmet_apply($scfg, $units, %opts) { + my $input = delete $opts{input}; + $opts{timeout} //= 30; + for my $chunk (_nvmet_chunk($units)->@*) { + my $with_key = grep { ref($_) eq 'HASH' && exists($_->{key}) } $chunk->@*; + my @input = $with_key ? (input => $input) : (); + my $res = nvmet_exec($scfg, $chunk, %opts, @input, change => 1); + return $res if $res->{rc}; + } + return { rc => 0, out => [], err => '' }; +} + +my sub nvmet_change($scfg, $units, %opts) { + nvmet_check(nvmet_apply($scfg, $units, %opts), $opts{op}); +} + +my sub nvmet_wait_device($scfg, $dev) { + my $deadline = _now() + 10; + while (1) { + my $res = nvmet_exec($scfg, [['test', '-b', $dev]], op => 'wait for zvol'); + return if !$res->{rc}; + nvmet_read_failed($scfg, $res) if nvmet_unreachable($res); + last if _now() >= $deadline; + _sleep(0.25); + } + die "zvol '$dev' is not a block device after 10 seconds\n"; +} + +my sub nvmet_new_uuid($inv, $cfs) { + my %used = map { lc($_->{uuid}) => 1 } values $inv->{volumes}->%*; + for my $subsys (values $cfs->{subsystems}->%*) { + $used{ lc($_->{device_uuid}) } = 1 for values(($subsys->{namespaces} // {})->%*); + } + for (1 .. 10) { + my $uuid = nvmet_uuid(lc(file_read_firstline('/proc/sys/kernel/random/uuid') // '')); + return $uuid if defined($uuid) && !$used{$uuid}; + } + die "cannot generate an unused namespace UUID\n"; +} + +my sub nvmet_has_identity($row, $nqn, $nsid, $uuid) { + return $row && $row->{nqn} eq $nqn && $row->{nsid} eq "$nsid" && $row->{uuid} eq $uuid; +} + +my sub nvmet_without_namespace($cfs, $nqn, $pre) { + return $cfs if !$pre; + my $subsys = $cfs->{subsystems}->{$nqn}; + my %namespaces = $subsys->{namespaces}->%*; + delete $namespaces{ $pre->{nsid} }; + my $changed = { $subsys->%*, namespaces => \%namespaces }; + return { $cfs->%*, subsystems => { $cfs->{subsystems}->%*, $nqn => $changed } }; +} + +# One port that cannot be bound (for example, its address is missing on the target) only warns +# while another desired port serves the subsystem. +my sub nvmet_publish($scfg, $cfs, $nqn, $port_ids, $hostnqns) { + my @failed; + for my $unit (_nvmet_plan_publish($cfs, $nqn, $port_ids, $hostnqns)->@*) { + my $op = "$unit->{action} NVMe subsystem on port $unit->{port}"; + my $res = nvmet_apply($scfg, [$unit->{steps}], op => $op); + push @failed, { $unit->%*, err => $res->{err} } if $res->{rc}; + } + return if !@failed; + + my (undef, $fresh) = eval { nvmet_read($scfg) }; + nvmet_rethrow_abandoned($@) if $@; + my $published = $fresh && grep { nvmet_port_linked($fresh, $_, $nqn) } $port_ids->@*; + my ($first) = grep { $_->{action} eq 'link' } @failed; + $first //= $failed[0]; + die "cannot publish NVMe subsystem '$nqn': $first->{err}\n" if !$published; + for my $failure (@failed) { + my $what = $failure->{action} eq 'link' ? 'publish' : 'unpublish'; + log_warn("cannot $what NVMe subsystem '$nqn' on port $failure->{port}: $failure->{err}"); + } +} + +# A converged target costs one read and no lock. Otherwise, under the lock: read, apply, verify +# with a fresh read and publish only once the verify read plans nothing more. +sub _nvmet_activate_target($storeid, $scfg, $portals, $hostnqns, $key) { + my $nqn = nvmet_nqn($scfg); + my $conf = { + nqn => $nqn, + portals => $portals, + hostnqns => $hostnqns, + keysha => sha256_hex("$key\n"), + }; + my $converged = sub($inv, $cfs) { + my $plan = _nvmet_plan_activation($inv, $cfs, $conf); + return !$plan->{prepublish}->@* + && !_nvmet_plan_publish($cfs, $nqn, $plan->{port_ids}, $hostnqns)->@*; + }; + + # without the lock, a refusal or failed read only means "take the lock" + my @state = nvmet_read($scfg, keys => $hostnqns, tolerant => 1); + return if @state && eval { $converged->(@state) }; + + nvmet_locked( + $scfg, + sub { + # Removing the storage deletes its key file, so an activation that waited for the lock + # does not configure the target for a storage that is gone. + die "storage '$storeid' is being removed or its key changed\n" + if (file_read_firstline(secret_path($storeid)) // '') ne $key; + my ($inv, $cfs) = nvmet_read($scfg, keys => $hostnqns, modprobe => 1); + my $plan = _nvmet_plan_activation($inv, $cfs, $conf); + my $error; + for my $round (1 .. 2) { + last if !$plan->{prepublish}->@*; + my $apply = nvmet_apply( + $scfg, $plan->{prepublish}, + op => 'configure NVMe target', + input => "$key\n", + ); + $error //= $apply->{err} if $apply->{rc}; + ($inv, $cfs) = nvmet_read($scfg, keys => $hostnqns); + $plan = _nvmet_plan_activation($inv, $cfs, $conf); + } + die "NVMe target did not converge: " . ($error // 'state mismatch') . "\n" + if $plan->{prepublish}->@*; + nvmet_publish($scfg, $cfs, $nqn, $plan->{port_ids}, $hostnqns); + }, + ); + return; +} + +sub _nvmet_volume_uuid($scfg, $name) { + my $dataset = nvmet_dataset($scfg, $name); + my $inv = nvmet_read_zfs($scfg); + my (undef, $uuid) = _nvmet_owned_identity($inv, nvmet_nqn($scfg), $dataset); + return $uuid; +} + +# A failure removes only what this call created, decided from a fresh read. +my sub nvmet_create_volume($scfg, $name, %opts) { + my $nqn = nvmet_nqn($scfg); + my $dataset = nvmet_dataset($scfg, $name); + my $dev = "/dev/zvol/$dataset"; + my $size = nvmet_uint($opts{size}); + die "internal error: invalid zvol creation request\n" + if defined($opts{size}) == defined($opts{origin}) + || (defined($opts{size}) && !defined($size)); + + return nvmet_locked( + $scfg, + sub { + my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1); + die "zvol '$dataset' already exists\n" if exists($inv->{types}->{$dataset}); + die "NVMe subsystem does not exist; activate the storage first\n" + if !$cfs->{subsystems}->{$nqn}; + my $nsid = _nvmet_allocate_nsid($inv, $cfs, $nqn); + my $uuid = nvmet_new_uuid($inv, $cfs); + my (undef, $state) = _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev); + die "internal error: namespace ID '$nsid' is in use\n" if $state ne 'absent'; + + # record the NSID on the pool first, so a creation that completes late never shares it + my $timeout = nvmet_long_timeout(); + if ($nsid > $inv->{last_nsid}) { + my $reserve = ['zfs', 'set', "$nvmet_last_nsid=$nsid", nvmet_pool($scfg)]; + nvmet_change( + $scfg, [[$reserve]], + op => 'reserve namespace ID', + timeout => $timeout, + ); + } + + my @identity = map { ('-o', $_) } nvmet_identity($nqn, $nsid, $uuid); + my @create_opts = ( + ($scfg->{sparse} ? ('-s') : ()), + ($scfg->{blocksize} ? ('-b', $scfg->{blocksize}) : ()), + ); + my $create = + defined($opts{origin}) + ? ['zfs', 'clone', @identity, $opts{origin}, $dataset] + : ['zfs', 'create', @create_opts, @identity, '-V', "${size}k", $dataset]; + my $res = nvmet_apply( + $scfg, [[$create]], + op => 'create zvol', + timeout => $timeout, + ); + if ($res->{rc}) { + # A definite failure may still have created the zvol, and only one with this call's + # identity counts. Ambiguous SSH outcomes aborted the transaction in nvmet_exec. + my $check = eval { nvmet_read_zfs($scfg) }; + nvmet_rethrow_abandoned($@) if $@; + my $row = $check ? $check->{volumes}->{$dataset} : undef; + die "NVMe target operation 'create zvol' failed: $res->{err}\n" + if !nvmet_has_identity($row, $nqn, $nsid, $uuid); + } + + my $verified; + eval { + nvmet_wait_device($scfg, $dev); + my $build_unit = nvmet_build_unit($nqn, $nsid, $uuid, $dev); + my $build = nvmet_apply($scfg, [$build_unit], op => 'export namespace'); + $verified = [nvmet_read($scfg)]; + my ($vinv, $vcfs) = $verified->@*; + my ($vnsid, $vuuid) = _nvmet_owned_identity($vinv, $nqn, $dataset); + die "NVMe identity of zvol '$dataset' changed\n" + if $vnsid ne $nsid || $vuuid ne $uuid; + if (_nvmet_export_state($vcfs, $nqn, $nsid, $uuid, $dev) ne 'present') { + nvmet_check($build, 'export namespace'); + die "NVMe namespace '$nsid' was not exported\n"; + } + }; + my $error = $@ or return $uuid; + nvmet_rethrow_abandoned($error); + + eval { + my ($cinv, $ccfs) = $verified ? $verified->@* : nvmet_read($scfg); + my $namespaces = nvmet_namespaces($ccfs, $nqn); + # The build writes the UUID before it enables the namespace, so an enabled + # namespace without our UUID was not built by this call. + my @unexport = + map { nvmet_unexport_unit($nqn, $_, $namespaces->{$_}->{enable} eq '1') } + grep { + my $ns = $namespaces->{$_}; + $ns->{device_uuid} eq $uuid + || ($ns->{enable} ne '1' && $ns->{device_path} eq $dev) + } sort { + $a <=> $b + } keys $namespaces->%*; + nvmet_change($scfg, \@unexport, op => 'remove namespace') if @unexport; + if (nvmet_has_identity($cinv->{volumes}->{$dataset}, $nqn, $nsid, $uuid)) { + my $destroy = ['zfs', 'destroy', '-r', $dataset]; + nvmet_change( + $scfg, [[$destroy]], + op => 'destroy zvol', + timeout => $timeout, + ); + } + }; + log_warn("failed to clean up zvol '$name': $@") if $@; + die $error; + }, + ); +} + +my sub nvmet_destroy_volume($scfg, $name) { + my $nqn = nvmet_nqn($scfg); + my $dataset = nvmet_dataset($scfg, $name); + my $dev = "/dev/zvol/$dataset"; + my $destroy = ['zfs', 'destroy', '-r', $dataset]; + my $timeout = nvmet_long_timeout(); + + nvmet_locked( + $scfg, + sub { + my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1); + return if !exists($inv->{types}->{$dataset}); + my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset); + my ($unexport, $pre) = ([], undef); + if ($cfs->{subsystems}->{$nqn}) { + _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev); # refusals only + ($unexport, $pre) = _nvmet_plan_unexport($cfs, $nqn, $uuid); + } + my $units = [$unexport->@*, [$destroy]]; + my $res = nvmet_apply($scfg, $units, op => 'destroy zvol', timeout => $timeout); + return if !$res->{rc}; + my $error = $res->{err}; + + my ($finv, $fcfs) = eval { nvmet_read($scfg) }; + if (my $read_error = $@) { + nvmet_rethrow_abandoned($read_error); + die "failed to destroy '$dataset': $error\n"; + } + return if !exists($finv->{types}->{$dataset}); + my $namespaces = nvmet_namespaces($fcfs, $nqn); + my ($current) = + grep { $namespaces->{$_}->{device_uuid} eq $uuid } keys $namespaces->%*; + if (defined($current)) { + die "cannot disable namespace '$current': $error\n" + if $namespaces->{$current}->{enable} eq '1'; + die "cannot remove namespace '$current': $error\n" if !$pre || !$pre->{enabled}; + my $enable = [nvmet_enable_unit($nqn, $current, $dev)]; + my $restore = nvmet_apply($scfg, $enable, op => 'enable namespace'); + die "cannot remove namespace '$current': $error" + . ($restore->{rc} ? "; cannot restore namespace: $restore->{err}" : '') . "\n"; + } + + # The namespace is gone and the zvol is still there, typically busy. + for my $attempt (1 .. 5) { + _sleep(1); + my $retry = + nvmet_apply($scfg, [[$destroy]], op => 'destroy zvol', timeout => $timeout); + return if !$retry->{rc}; + $error = $retry->{err}; + } + die "failed to destroy '$dataset': $error\n" if !$pre; + eval { + my (undef, $rcfs) = nvmet_read($scfg); + my ($units) = _nvmet_plan_export($rcfs, $nqn, $nsid, $uuid, $dev); + nvmet_change($scfg, $units, op => 'restore namespace'); + }; + die "failed to destroy '$dataset': $error; namespace restoration also failed: $@" + if $@; + die "failed to destroy '$dataset': $error; namespace restored\n"; + }, + ); + return; +} + +# Rolls an owned zvol back and always exports it again with the same identity. +my sub nvmet_rollback_volume($scfg, $name, $snap) { + my $snapshot = nvmet_snapshot($scfg, $name, $snap); + my $nqn = nvmet_nqn($scfg); + my $dataset = nvmet_dataset($scfg, $name); + my $dev = "/dev/zvol/$dataset"; + + my $timeout = nvmet_long_timeout(); + + nvmet_locked( + $scfg, + sub { + my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1); + my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset); + die "NVMe subsystem does not exist\n" if !$cfs->{subsystems}->{$nqn}; + _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev); # refusals only + my ($unexport, $pre) = _nvmet_plan_unexport($cfs, $nqn, $uuid); + my $set_identity = ['zfs', 'set', nvmet_identity($nqn, $nsid, $uuid), $dataset]; + my $rollback = ['zfs', 'rollback', $snapshot]; + my $res = nvmet_apply( + $scfg, [$unexport->@*, [$rollback], [$set_identity]], + op => 'rollback zvol', + timeout => $timeout, + ); + my $error; + $error = "NVMe target operation 'rollback zvol' failed: $res->{err}" if $res->{rc}; + + eval { + my ($rinv, $rcfs) = + $error ? nvmet_read($scfg) : ($inv, nvmet_without_namespace($cfs, $nqn, $pre)); + nvmet_wait_device($scfg, $dev); + my @units; + push @units, [$set_identity] + if !nvmet_has_identity($rinv->{volumes}->{$dataset}, $nqn, $nsid, $uuid); + my ($export) = _nvmet_plan_export($rcfs, $nqn, $nsid, $uuid, $dev); + push @units, $export->@*; + nvmet_change($scfg, \@units, op => 'restore namespace', timeout => $timeout); + }; + chomp(my $restore_error = $@); + + die "rollback failed: $error; namespace restoration failed: $restore_error\n" + if defined($error) && $restore_error; + die "namespace restoration failed after rollback: $restore_error\n" + if $restore_error; + die "$error\n" if defined($error); + }, + ); + return; +} + +my sub nvmet_template_volume($scfg, $name) { + my $nqn = nvmet_nqn($scfg); + my $old = nvmet_dataset($scfg, $name); + my $new = _nvmet_template_name($old); + my ($old_dev, $new_dev) = ("/dev/zvol/$old", "/dev/zvol/$new"); + my $timeout = nvmet_long_timeout(); + + nvmet_locked( + $scfg, + sub { + my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1); + my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $old); + die "template zvol '$new' already exists\n" if exists($inv->{types}->{$new}); + die "NVMe subsystem does not exist\n" if !$cfs->{subsystems}->{$nqn}; + _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $old_dev); # refusals only + my ($unexport) = _nvmet_plan_unexport($cfs, $nqn, $uuid); + + eval { + my $rename = [$unexport->@*, [['zfs', 'rename', $old, $new]]]; + nvmet_change($scfg, $rename, op => 'rename zvol', timeout => $timeout); + nvmet_wait_device($scfg, $new_dev); + my $build = nvmet_build_unit($nqn, $nsid, $uuid, $new_dev); + my $template = [$build, [['zfs', 'snapshot', "$new\@__base__"]]]; + nvmet_change($scfg, $template, op => 'create template', timeout => $timeout); + }; + my $error = $@ or return; + nvmet_rethrow_abandoned($error); + chomp($error); + + eval { + my ($rinv, $rcfs) = nvmet_read($scfg); + if (exists($rinv->{types}->{$new})) { + my ($units) = _nvmet_plan_unexport($rcfs, $nqn, $uuid); + my $back = [$units->@*, [['zfs', 'rename', $new, $old]]]; + nvmet_change($scfg, $back, op => 'rename zvol back', timeout => $timeout); + (undef, $rcfs) = nvmet_read($scfg); + } elsif (!exists($rinv->{types}->{$old})) { + die "zvol '$old' does not exist\n"; + } + nvmet_wait_device($scfg, $old_dev); + my ($units) = _nvmet_plan_export($rcfs, $nqn, $nsid, $uuid, $old_dev); + nvmet_change($scfg, $units, op => 'restore namespace'); + }; + die "template conversion failed: $error; restoration failed: $@" if $@; + die "template conversion failed: $error\n"; + }, + ); + return; +} + +my sub nvmet_resize_volume($scfg, $name, $size) { + my $nqn = nvmet_nqn($scfg); + my $dataset = nvmet_dataset($scfg, $name); + $size = nvmet_uint($size) // die "internal error: invalid zvol size\n"; + + # The namespace read under the lock is revalidated in the same call as the resize, so the hosts + # see the new size even after a lost reply. A disabled namespace reads it when enabled. + nvmet_locked( + $scfg, + sub { + my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1); + my (undef, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset); + my $namespaces = nvmet_namespaces($cfs, $nqn); + my @matches = + grep { $namespaces->{$_}->{device_uuid} eq $uuid } keys $namespaces->%*; + die "duplicate namespace UUID '$uuid'\n" if @matches > 1; + my @resize = (['zfs', 'set', "volsize=${size}k", $dataset]); + push @resize, nvmet_write(nvmet_ns_path($nqn, $matches[0]) . '/revalidate_size', 1) + if @matches && $namespaces->{ $matches[0] }->{enable} eq '1'; + nvmet_change( + $scfg, [\@resize], + op => 'resize zvol', + timeout => nvmet_long_timeout(), + ); + }, + ); + return; +} + 1; -- 2.54.0.windows.1