public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Joaquin Varela <joaquinvarela@neatech.ar>
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	[thread overview]
Message-ID: <20261126150956.310593-3-joaquinvarela@neatech.ar> (raw)
In-Reply-To: <20261126150956.310593-1-joaquinvarela@neatech.ar>

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 <joaquinvarela@neatech.ar>
---
 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




  parent reply	other threads:[~2026-11-26 15:10 UTC|newest]

Thread overview: 16+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-26 15:09 [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning Joaquin Varela
2026-11-26 15:09 ` Joaquin Varela [this message]
2026-11-26 15:09 ` [PATCH storage v5 03/13] zfsnvme: add storage configuration and volume methods Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 04/13] zfsnvme: connect the nodes and register the plugin Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 05/13] api: san luns: count zfsnvme storages as owners of their subsystem Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 06/13] api: config: check the cluster version before the first zfsnvme storage Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 07/13] test: zfsnvme: add configuration and volume tests Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 08/13] test: zfsnvme: add node side tests Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 09/13] test: zfsnvme: add an in-memory nvmet target Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 10/13] test: zfsnvme: test the target parsers and planners Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 11/13] test: zfsnvme: test the target flows Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 12/13] test: zfsnvme: add a fault sweep, renderer and taint tests Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 13/13] zfsnvme: wait up to 30 seconds for the shared storage lock Joaquin Varela
2026-11-26 15:10 ` [PATCH docs v5] storage: document ZFS over NVMe/TCP Joaquin Varela
2026-11-26 15:11 ` [PATCH manager v5] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261126150956.310593-3-joaquinvarela@neatech.ar \
    --to=joaquinvarela@neatech.ar \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal