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 04/13] zfsnvme: connect the nodes and register the plugin
Date: Thu, 26 Nov 2026 12:09:45 -0300	[thread overview]
Message-ID: <20261126150956.310593-5-joaquinvarela@neatech.ar> (raw)
In-Reply-To: <20261126150956.310593-1-joaquinvarela@neatech.ar>

Connect the nodes with native NVMe multipath. One write to
/dev/nvme-fabrics creates each controller, in a bounded child that
holds the PVE::NVMeOF host lock, so the key never shows up on a
command line. activate_volume checks the namespace identity.

The host NQN and ID come from nvme-cli, which is recommended already.

Register the 'zfsnvme' type, add it to @SHARED_STORAGE and let 'pvesm
add' and 'pvesm set' read --dhchap-key from a file. The delete hook
only removes the key file, as it runs under the storage.cfg lock. The
subsystem stays on the target, so a new key for its host NQNs is
refused until it is removed there.

Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
 src/PVE/CLI/pvesm.pm             |  21 +-
 src/PVE/Storage.pm               |   2 +
 src/PVE/Storage/Makefile         |   1 +
 src/PVE/Storage/Plugin.pm        |  12 +-
 src/PVE/Storage/ZFSNVMePlugin.pm | 575 +++++++++++++++++++++++++++++++
 5 files changed, 608 insertions(+), 3 deletions(-)

diff --git a/src/PVE/CLI/pvesm.pm b/src/PVE/CLI/pvesm.pm
index 05da60d8..33272fad 100755
--- a/src/PVE/CLI/pvesm.pm
+++ b/src/PVE/CLI/pvesm.pm
@@ -79,12 +79,29 @@ sub param_mapping {
         },
     };
 
+    my $dhchap_key_map = {
+        name => 'dhchap-key',
+        desc => 'a file containing the NVMe DH-HMAC-CHAP key',
+        func => sub {
+            my ($value) = @_;
+            # never repeat a key passed in place of the file name
+            die "dhchap-key expects the path of a file containing the key\n"
+                if $value =~ /^DHHC-1:/i || -d $value;
+            my ($key) = split(/\n/, PVE::Tools::file_get_contents($value), 2);
+            $key = PVE::Tools::trim($key // '');
+            die "DH-HMAC-CHAP key file '$value' is empty\n" if $key eq '';
+            return $key;
+        },
+    };
+
     my $mapping = {
         'cifsscan' => [$password_map],
         'cifs' => [$password_map],
         'pbs' => [$password_map],
-        'create' => [$password_map, $enc_key_map, $master_key_map, $keyring_map],
-        'update' => [$password_map, $enc_key_map, $master_key_map, $keyring_map],
+        'create' =>
+            [$password_map, $enc_key_map, $master_key_map, $keyring_map, $dhchap_key_map],
+        'update' =>
+            [$password_map, $enc_key_map, $master_key_map, $keyring_map, $dhchap_key_map],
     };
     return $mapping->{$name};
 }
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index c77a6755..df4c6943 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -39,6 +39,7 @@ use PVE::Storage::CephFSPlugin;
 use PVE::Storage::ISCSIDirectPlugin;
 use PVE::Storage::ZFSPoolPlugin;
 use PVE::Storage::ZFSPlugin;
+use PVE::Storage::ZFSNVMePlugin;
 use PVE::Storage::PBSPlugin;
 use PVE::Storage::BTRFSPlugin;
 use PVE::Storage::ESXiPlugin;
@@ -65,6 +66,7 @@ PVE::Storage::CephFSPlugin->register();
 PVE::Storage::ISCSIDirectPlugin->register();
 PVE::Storage::ZFSPoolPlugin->register();
 PVE::Storage::ZFSPlugin->register();
+PVE::Storage::ZFSNVMePlugin->register();
 PVE::Storage::PBSPlugin->register();
 PVE::Storage::BTRFSPlugin->register();
 PVE::Storage::ESXiPlugin->register();
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index 7f2ff6c8..553f65a3 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -12,6 +12,7 @@ SOURCES= \
 	ISCSIDirectPlugin.pm \
 	ZFSPoolPlugin.pm \
 	ZFSPlugin.pm \
+	ZFSNVMePlugin.pm \
 	PBSPlugin.pm \
 	BTRFSPlugin.pm \
 	LvmThinPlugin.pm \
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index 998bc68a..60207301 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -42,7 +42,17 @@ our @COMMON_TAR_FLAGS = qw(
 );
 
 our @SHARED_STORAGE = (
-    'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs', 'nvmeof',
+    'iscsi',
+    'nfs',
+    'cifs',
+    'rbd',
+    'cephfs',
+    'iscsidirect',
+    'zfs',
+    'zfsnvme',
+    'drbd',
+    'pbs',
+    'nvmeof',
 );
 
 our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/ZFSNVMePlugin.pm b/src/PVE/Storage/ZFSNVMePlugin.pm
index 1f95f8c5..4d2eaf7e 100644
--- a/src/PVE/Storage/ZFSNVMePlugin.pm
+++ b/src/PVE/Storage/ZFSNVMePlugin.pm
@@ -14,6 +14,7 @@ use Socket qw(AF_INET6 inet_ntop inet_pton);
 use Time::HiRes;
 
 use PVE::Cluster;
+use PVE::Diskmanage;
 use PVE::File;
 use PVE::JSONSchema;
 use PVE::Network;
@@ -2363,4 +2364,578 @@ sub on_update_hook_full($class, $storeid, $scfg, $update, $delete = undef, $sens
     return;
 }
 
+my %slow_path_last; # time of the last slow-path activation, by storeid
+
+sub _block_device($path) {
+    return -b $path;
+}
+
+sub _link_target($path) {
+    return readlink($path);
+}
+
+sub _fabrics_device() {
+    return '/dev/nvme-fabrics';
+}
+
+sub _nvme_tcp_loaded() {
+    return -e '/sys/module/nvme_tcp';
+}
+
+sub _partitions($device) {
+    return glob("${device}p[0-9]*");
+}
+
+# Runs $code in a child under the host lock of PVE::NVMeOF, which the nvmeof storage and the
+# controller API share. with_lock kills the child at its limit, which also frees the lock. The limit
+# is $timeout plus the lock wait in all, counted from the start of the call. The bound is not hard:
+# a child stuck in the kernel (a write or delete in D state) is only reaped once the kernel returns,
+# and a timeout does not mean that the operation did not happen. $code must not take locks or call
+# run_locked.
+#
+# A stopped task (TERM, HUP, INT and QUIT) stays pending in the parent while the child runs, and
+# the child inherits the mask. So a connect still creates its controller and restricts the secret
+# attributes before the stop takes effect, unless PVE escalates to KILL after 5 seconds. That ends
+# both processes and leaves the attributes world-readable until the next activation. Once the child
+# is reaped, the worker handler dies with the task marker, also over a result or an error of the
+# child. ALRM, the timeout, is not blocked.
+my sub run_locked($timeout, $what, $code) {
+    my $limit = $timeout + $PVE::NVMeOF::LOCK_WAIT;
+    my $previous = POSIX::SigSet->new();
+    sigprocmask(SIG_BLOCK, POSIX::SigSet->new(SIGHUP, SIGINT, SIGQUIT, SIGTERM), $previous)
+        or die "cannot block signals: $!\n";
+    my $outer_warn = $SIG{__WARN__};
+    my $res = eval {
+        # with_lock only warns in the parent when its child leaves no result, which dies below.
+        # The child keeps the handler of the caller, so its warnings reach the task log.
+        local $SIG{__WARN__} = sub($message) { };
+        PVE::NVMeOF::with_lock(
+            sub {
+                local $SIG{__WARN__} = $outer_warn;
+                return $code->();
+            },
+            $limit,
+        );
+    };
+    my $error = $@;
+    sigprocmask(SIG_SETMASK, $previous) or die "cannot restore signals: $!\n";
+    if ($error) {
+        rethrow_task_interrupt($error);
+        die "$what did not complete within $limit seconds\n" if $error eq $PVE::NVMeOF::TIMED_OUT;
+        die $error;
+    }
+    die "$what left no result\n" if !defined($res);
+    return $res;
+}
+
+# the values are validated by the caller, the kernel reads each one up to the next ','
+sub _fabrics_options($scfg, $portal, $hostnqn, $hostid, $key) {
+    my @options = (
+        [transport => 'tcp'],
+        [traddr => $portal->{address}],
+        [trsvcid => $portal->{port}],
+        [host_iface => $portal->{host_iface}],
+        [nqn => $scfg->{subsysnqn}],
+        [hostnqn => $hostnqn],
+        [hostid => $hostid],
+        [dhchap_secret => $key],
+        [keep_alive_tmo => $scfg->{'nvme-keep-alive-tmo'} // 5],
+        [reconnect_delay => $scfg->{'nvme-reconnect-delay'} // 2],
+        [ctrl_loss_tmo => $scfg->{'nvme-ctrl-loss-tmo'} // 600],
+    );
+    # unlike unset, which leaves fast I/O failure off, 0 is a real timeout
+    push @options, [fast_io_fail_tmo => $scfg->{'nvme-fast-io-fail-tmo'}]
+        if defined($scfg->{'nvme-fast-io-fail-tmo'});
+    push @options, [nr_io_queues => $scfg->{'nvme-nr-io-queues'}]
+        if defined($scfg->{'nvme-nr-io-queues'});
+    for my $option (@options) {
+        die "internal error: invalid NVMe connect option '$option->[0]'\n"
+            if !defined($option->[1]) || $option->[1] !~ $RE_FABRICS_VALUE;
+    }
+    return (join(',', map { "$_->[0]=$_->[1]" } @options), [map { $_->[0] } @options]);
+}
+
+# One write of $options creates exactly one controller. It is never repeated, because the kernel
+# may have created the controller even when it reports an error. Errors carry the errno text and
+# never the options, which hold the key.
+sub _fabrics_connect($options, $names) {
+    my $device = _fabrics_device();
+    my $probe;
+    if (!sysopen($probe, $device, O_RDONLY | O_NOFOLLOW)) {
+        die "'$device' does not exist; load the nvme-tcp kernel module\n" if $! == ENOENT;
+        die "cannot open '$device': $!\n";
+    }
+    my @stat = stat($probe);
+    die "'$device' is not a character device\n" if !@stat || !S_ISCHR($stat[2]);
+    # without a controller, a read lists the supported options as patterns
+    my $supported = '';
+    sysread($probe, $supported, 4096) // die "cannot read '$device': $!\n";
+    close($probe);
+    my %supported = map { s/=.*//r => 1 } split(/,/, $supported =~ s/\n\z//r);
+    for my $name ($names->@*) {
+        die "the running kernel does not support the NVMe connect option '$name'\n"
+            if !$supported{$name};
+    }
+
+    # Not PVE::SysFSTools::file_write: the kernel returns the instance of the new controller on a
+    # read of the file descriptor that wrote the options.
+    sysopen(my $fh, $device, O_RDWR | O_NOFOLLOW) or die "cannot open '$device': $!\n";
+    my $written = _fabrics_write($fh, $options);
+    die "connect failed: $!\n" if !defined($written);
+    die "connect failed: short write\n" if $written != length($options);
+    my $result = '';
+    sysread($fh, $result, 128) // die "cannot read the connect result: $!\n";
+    die "unexpected connect result\n" if $result !~ $RE_FABRICS_RESULT;
+    my $instance = int($+{instance});
+    # The kernel creates the secret attributes world-readable. The caller keeps a stopped task from
+    # interrupting before this, short of a KILL.
+    _restrict_attr("/sys/class/nvme/nvme$instance/$_") for qw(dhchap_secret dhchap_ctrl_secret);
+    close($fh);
+    return $instance;
+}
+
+sub _fabrics_write($fh, $options) {
+    return syswrite($fh, $options);
+}
+
+# PVE::SysFSTools::file_write returns undef without a warning when the open fails, leaving its
+# errno in $!, and 0 after warning "error writing ...: <errno text>" when the write fails, which is
+# not passed on. With $missing_ok, an attribute that went away with its controller is no failure.
+my sub write_attribute($path, $value, $missing_ok = 0) {
+    my $warning;
+    my $written = do {
+        local $SIG{__WARN__} = sub($message) { $warning = $message };
+        PVE::SysFSTools::file_write($path, $value);
+    };
+    return if $written;
+    return if !defined($warning) && $missing_ok && $! == ENOENT;
+    return "$!" if !defined($warning);
+    return $warning =~ s/\A.*: //sr =~ s/\n\z//r;
+}
+
+# runs in a child, as the deletion can block in the kernel
+sub _delete_controllers($controllers) {
+    for my $controller ($controllers->@*) {
+        my $path = "/sys/class/nvme/$controller->{name}/delete_controller";
+        my $error = write_attribute($path, '1', 1) // next;
+        die "cannot delete NVMe controller '$controller->{name}': $error\n";
+    }
+    return scalar($controllers->@*);
+}
+
+my sub nvme_controllers($nqn) {
+    my $controllers = [];
+    PVE::File::dir_glob_foreach(
+        '/sys/class/nvme',
+        $RE_NVME_CONTROLLER,
+        sub($entry) {
+            my $base = "/sys/class/nvme/$entry";
+            my $subsys = file_read_firstline("$base/subsysnqn");
+            return if !defined($subsys) || $subsys ne $nqn;
+            my $address = file_read_firstline("$base/address") // '';
+            my $traddr = $address =~ $RE_TRADDR ? $+{value} : undef;
+            my $trsvcid = $address =~ $RE_TRSVCID ? $+{value} : undef;
+            my $host_iface = $address =~ $RE_HOST_IFACE_ADDRESS ? $+{value} : undef;
+            push $controllers->@*,
+                {
+                    name => $entry,
+                    state => file_read_firstline("$base/state") // 'unknown',
+                    traddr => nvmet_canonical_address($traddr),
+                    trsvcid => $trsvcid,
+                    host_iface => $host_iface,
+                };
+        },
+    );
+    return $controllers;
+}
+
+# a portal has more than one controller while its path moves to another interface
+my sub controller_states($nqn) {
+    my $states = {};
+    for my $controller (nvme_controllers($nqn)->@*) {
+        next if !defined($controller->{traddr}) || !defined($controller->{trsvcid});
+        push $states->{"$controller->{traddr}:$controller->{trsvcid}"}->@*, $controller;
+    }
+    return $states;
+}
+
+# The kernel reuses the name of a controller that is gone, and the wait for the host lock can be
+# long, so the name of a listed controller can belong to another one by the time it is deleted. A
+# dead controller must still be dead, as it can recover meanwhile.
+my sub same_controller($listed, $now) {
+    return 0 if !$now;
+    for my $key (qw(traddr trsvcid host_iface)) {
+        return 0 if ($now->{$key} // '') ne ($listed->{$key} // '');
+    }
+    return $listed->{state} ne 'dead' || $now->{state} eq 'dead';
+}
+
+# runs in a child under the host lock, and deletes the listed controllers that are still the same
+my sub delete_listed($nqn, $listed) {
+    my %now = map { $_->{name} => $_ } nvme_controllers($nqn)->@*;
+    return _delete_controllers([grep { same_controller($_, $now{ $_->{name} }) } $listed->@*]);
+}
+
+# What keeps the namespaces of the subsystem from going away, as PVE::NVMeOF::disconnect_guarded
+# checks it. A swap area claims its device like a mount does, so the claim covers it.
+sub _namespace_users($nqn) {
+    my @users;
+    for my $head (sort keys PVE::NVMeOF::namespaces($nqn)->%*) {
+        my $device = "/dev/$head";
+        my @devices = ($device, _partitions($device));
+        if (defined(my $mounted = PVE::Diskmanage::is_mounted($device))) {
+            push @users, "'$mounted' is mounted";
+        } elsif (defined(my $held = PVE::Diskmanage::has_holder($device))) {
+            push @users, "'$held' has a holder";
+        } elsif (my ($claimed) = grep { PVE::NVMeOF::is_claimed($_) } @devices) {
+            push @users, "'$claimed' is claimed, for example by a swap area";
+        } else {
+            # retry briefly to ignore transient openers like LVM status scans
+            my $opener;
+            for my $try (1 .. 4) {
+                _sleep(0.3) if $try > 1;
+                $opener = PVE::Diskmanage::device_opener(@devices);
+                last if !defined($opener);
+            }
+            push @users, "process $opener has namespace '$head' open" if defined($opener);
+        }
+    }
+    return \@users;
+}
+
+my sub portal_reachable($portal) {
+    return PVE::Network::tcp_ping($portal->{address}, $portal->{port}, 2) // 0;
+}
+
+# with $any_iface, a live controller on any interface counts, as such a path carries I/O
+sub _live_portal_count($states, $portals, $any_iface = 0) {
+    my $live = 0;
+    for my $portal ($portals->@*) {
+        my $id = "$portal->{address}:$portal->{port}";
+        $live++ if grep {
+            $_->{state} eq 'live'
+                && ($any_iface || ($_->{host_iface} // '') eq $portal->{host_iface})
+        } ($states->{$id} // [])->@*;
+    }
+    return $live;
+}
+
+# Gives up after 10 seconds plus the lock wait in all, counted from the start of the call. Returns
+# -1 if the portal got a controller on its interface meanwhile, as another activation can run at
+# the same time.
+sub _connect_portal($scfg, $portal, $hostnqn, $hostid, $key) {
+    my ($options, $names) = _fabrics_options($scfg, $portal, $hostnqn, $hostid, $key);
+    my $id = "$portal->{address}:$portal->{port}";
+    return run_locked(
+        10,
+        'NVMe/TCP connect',
+        sub {
+            my $states = controller_states($scfg->{subsysnqn});
+            return -1
+                if grep {
+                    ($_->{host_iface} // '') eq $portal->{host_iface} && $_->{state} ne 'dead'
+                } ($states->{$id} // [])->@*;
+            return _fabrics_connect($options, $names);
+        },
+    );
+}
+
+my sub set_iopolicy($nqn, $policy) {
+    PVE::File::dir_glob_foreach(
+        '/sys/class/nvme-subsystem',
+        $RE_NVME_SUBSYSTEM,
+        sub($entry) {
+            my $base = "/sys/class/nvme-subsystem/$entry";
+            my $subsys = file_read_firstline("$base/subsysnqn");
+            return if !defined($subsys) || $subsys ne $nqn;
+            my $error = write_attribute("$base/iopolicy", "$policy\n");
+            die "unable to set NVMe multipath policy: $error\n" if defined($error);
+        },
+    );
+}
+
+# Connected controllers keep the values of their connect unless this writes them. sysfs shows "off"
+# for -1 and the loss timeout rounded up to a multiple of the reconnect delay.
+my sub set_tunables($scfg) {
+    my $delay = $scfg->{'nvme-reconnect-delay'} // 2;
+    my $loss = $scfg->{'nvme-ctrl-loss-tmo'} // 600;
+    my $fast = $scfg->{'nvme-fast-io-fail-tmo'};
+    my $shown_loss = $loss < 0 ? 'off' : int(($loss + $delay - 1) / $delay) * $delay;
+    my $shown_fast = defined($fast) && $fast >= 0 ? $fast : 'off';
+
+    for my $controller (nvme_controllers($scfg->{subsysnqn})->@*) {
+        my $base = "/sys/class/nvme/$controller->{name}";
+        my $current_delay = file_read_firstline("$base/reconnect_delay") // next;
+        my $write = sub($attr, $value) {
+            my $error = write_attribute("$base/$attr", "$value\n") // return;
+            log_warn("cannot set $attr of NVMe controller '$controller->{name}': $error");
+        };
+        my $delay_changed = $current_delay ne "$delay";
+        $write->('reconnect_delay', $delay) if $delay_changed;
+        $write->('ctrl_loss_tmo', $loss < 0 ? -1 : $loss)
+            if $delay_changed
+            || (file_read_firstline("$base/ctrl_loss_tmo") // '') ne "$shown_loss";
+        $write->('fast_io_fail_tmo', $shown_fast eq 'off' ? -1 : $fast)
+            if (file_read_firstline("$base/fast_io_fail_tmo") // '') ne "$shown_fast";
+    }
+}
+
+sub _restrict_attr($path) {
+    my @stat = stat($path);
+    if (!@stat) {
+        log_warn("cannot stat NVMe controller attribute '$path': $!") if $! != ENOENT;
+        return;
+    }
+    return if !($stat[2] & 077);
+    chmod(0600, $path) or log_warn("cannot restrict permissions of '$path': $!");
+}
+
+my sub restrict_secret_attrs($nqn) {
+    for my $controller (nvme_controllers($nqn)->@*) {
+        _restrict_attr("/sys/class/nvme/$controller->{name}/$_")
+            for qw(dhchap_secret dhchap_ctrl_secret);
+    }
+}
+
+my sub rescan_namespaces($nqn) {
+    for my $controller (nvme_controllers($nqn)->@*) {
+        next if $controller->{state} ne 'live';
+        my $path = "/sys/class/nvme/$controller->{name}/rescan_controller";
+        my $error = write_attribute($path, "1\n", 1) // next;
+        log_warn("cannot rescan NVMe controller '$controller->{name}': $error");
+    }
+}
+
+# the activation reconnects or keeps the path either way, so a failure only warns
+my sub disconnect_controller($nqn, $controller) {
+    my $name = $controller->{name};
+    eval {
+        run_locked(
+            5,
+            "deleting NVMe controller '$name'",
+            sub { return delete_listed($nqn, [$controller]) },
+        );
+    };
+    if (my $error = $@) {
+        rethrow_task_interrupt($error);
+        log_warn($error);
+    }
+}
+
+my sub wait_for_live_path($nqn, $portal) {
+    for (my $attempt = 0; $attempt < 40; $attempt++) {
+        return 1 if _live_portal_count(controller_states($nqn), [$portal]);
+        _sleep(0.25);
+    }
+    return 0;
+}
+
+# A path connected on another interface moves make-before-break: its old controller is only
+# disconnected once the new one is live, so a changed mapping never takes away a path with I/O.
+my sub connect_portals($scfg, $portals, $hostnqn, $hostid, $key) {
+    my $nqn = $scfg->{subsysnqn};
+    for my $portal ($portals->@*) {
+        my $id = "$portal->{address}:$portal->{port}";
+        my $iface = $portal->{host_iface};
+        my @controllers = (controller_states($nqn)->{$id} // [])->@*;
+        my ($configured) = grep { ($_->{host_iface} // '') eq $iface } @controllers;
+        my @moved = grep { ($_->{host_iface} // '') ne $iface } @controllers;
+
+        if (!$configured || $configured->{state} eq 'dead') {
+            disconnect_controller($nqn, $configured) if $configured;
+            if (!portal_reachable($portal)) {
+                log_warn("NVMe/TCP portal '$id' is unreachable");
+                next;
+            }
+            eval { _connect_portal($scfg, $portal, $hostnqn, $hostid, $key) };
+            my $connect_error = $@;
+            # A failed or timed-out connect can still have created a controller.
+            eval { restrict_secret_attrs($nqn); 1 };
+            if (my $error = $@) {
+                rethrow_task_interrupt($error);
+                log_warn("cannot restrict NVMe controller attributes for '$nqn'");
+            }
+            rethrow_task_interrupt($connect_error) if $connect_error;
+            if ($connect_error) {
+                log_warn("$id: $connect_error");
+                next;
+            }
+        }
+        next if !@moved;
+        if (!wait_for_live_path($nqn, $portal)) {
+            log_warn("NVMe/TCP portal '$id' is not live on '$iface' yet; keeping its path on"
+                . " another interface");
+            next;
+        }
+        disconnect_controller($nqn, $_) for @moved;
+    }
+}
+
+sub activate_storage($class, $storeid, $scfg, $cache = undef) {
+    $cache //= {};
+    my $nqn = $scfg->{subsysnqn};
+    # first, whatever the rest of the activation does, also for controllers connected by hand
+    restrict_secret_attrs($nqn);
+
+    # as PVE::NVMeOF::assert_support, which also wants the nvme binary that this plugin never runs
+    run_command(['modprobe', 'nvme-tcp'], timeout => 10) if !_nvme_tcp_loaded();
+    my $multipath = file_read_firstline('/sys/module/nvme_core/parameters/multipath') // '';
+    die "native NVMe multipath is disabled in the running kernel\n" if $multipath ne 'Y';
+
+    my $portals = _configured_portals($scfg);
+    verify_nvme_nqn($nqn);
+    _validate_local_ifaces($portals);
+    _assert_unique_target($storeid, $scfg);
+    my $host = PVE::NVMeOF::host_identity();
+    my $hostnqn = $host->{nqn};
+    my $hostnqns = parse_nvme_host_nqns($scfg->{'nvme-host-nqns'});
+    die "local NVMe host NQN '$hostnqn' is missing from nvme-host-nqns\n"
+        if !grep { $_ eq $hostnqn } $hostnqns->@*;
+    my $policy = $scfg->{'nvme-iopolicy'} // 'round-robin';
+    my $force_reconcile = delete($cache->{'zfsnvme-force-reconcile'}->{$storeid}) // 0;
+    my $states = controller_states($nqn);
+    my $healthy = _live_portal_count($states, $portals);
+    my $usable = _live_portal_count($states, $portals, 1);
+    my $last = $slow_path_last{$storeid};
+    my $recent = defined($last) && _now() - $last < $slow_path_backoff;
+
+    # This runs in the periodic status loop. Once every configured path is live, lifecycle
+    # operations keep the target converged, so no remote call is needed. A degraded storage retries
+    # the target at most once a minute. In between, one with a live path is usable and one
+    # without fails at once. Missing namespaces force the slow path.
+    if (!$force_reconcile && ($healthy == scalar($portals->@*) || $recent)) {
+        die "no live NVMe/TCP path for storage '$storeid'\n" if !$usable;
+        die "missing NVMe DH-HMAC-CHAP key\n"
+            if (file_read_firstline(secret_path($storeid)) // '') eq '';
+        set_iopolicy($nqn, $policy);
+        set_tunables($scfg);
+        return 1;
+    }
+
+    $slow_path_last{$storeid} = _now();
+    my $hostid = $host->{id};
+    my $key = get_secret($storeid);
+    for my $name (qw(keep-alive-tmo reconnect-delay ctrl-loss-tmo fast-io-fail-tmo nr-io-queues)) {
+        my $value = $scfg->{"nvme-$name"};
+        die "invalid NVMe connection parameter '$name'\n"
+            if defined($value) && $value !~ $RE_CONFIG_INT;
+    }
+    _nvmet_activate_target($storeid, $scfg, $portals, $hostnqns, $key);
+    connect_portals($scfg, $portals, $hostnqn, $hostid, $key);
+
+    # after a restart controllers can sit in their kernel reconnect delay, so wait, do not duplicate
+    for (my $attempt = 0; $attempt < 60; $attempt++) {
+        $states = controller_states($nqn);
+        last if _live_portal_count($states, $portals, 1);
+        _sleep(0.25);
+    }
+    die "no live NVMe/TCP path for storage '$storeid'\n"
+        if !_live_portal_count($states, $portals, 1);
+    $healthy = _live_portal_count($states, $portals);
+    log_warn("storage '$storeid' is degraded: $healthy/" . scalar($portals->@*) . " paths live")
+        if $healthy < scalar($portals->@*);
+
+    set_iopolicy($nqn, $policy);
+    set_tunables($scfg);
+    return 1;
+}
+
+sub deactivate_storage($class, $storeid, $scfg, $cache = undef) {
+    my $nqn = $scfg->{subsysnqn};
+    my $users = _namespace_users($nqn);
+    die "refusing to disconnect NVMe storage '$storeid': " . join(', ', $users->@*) . "\n"
+        if $users->@*;
+
+    return 1 if !nvme_controllers($nqn)->@*;
+    # One child deletes the controllers that it finds once it has the lock. It gives up after 15
+    # seconds plus the lock wait in all, counted from the start of the call. Then the remaining
+    # controllers stay and the deactivation fails.
+    run_locked(
+        15,
+        "disconnecting NVMe subsystem '$nqn'",
+        sub { return _delete_controllers(nvme_controllers($nqn)) },
+    );
+    return 1;
+}
+
+# The core runs this inside the storage.cfg lock of the cluster, so it only touches local state.
+# The subsystem stays on the target and the controllers of the nodes stay connected.
+sub on_delete_hook($class, $storeid, $scfg) {
+    # A storage that is added again under this ID is a new one. Adding a storage removes it again
+    # when its activation fails, and a long running worker would keep the backoff of that failure.
+    delete $slow_path_last{$storeid};
+    delete_secret($storeid);
+    return;
+}
+
+sub path($class, $scfg, $volname, $storeid, $snapname = undef) {
+    die "direct access to snapshots not implemented\n" if defined($snapname);
+    my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+    my $uuid = _nvmet_volume_uuid($scfg, $name);
+    my $path = "/dev/disk/by-id/nvme-uuid.$uuid";
+    return ($path, $vmid, $vtype);
+}
+
+sub qemu_blockdev_options(
+    $class, $scfg, $storeid, $volname,
+    $machine_version = undef,
+    $options = undef,
+) {
+    die "direct access to snapshots not implemented\n" if $options->{'snapshot-name'};
+    my ($path) = $class->path($scfg, $volname, $storeid);
+    return { driver => 'host_device', filename => $path };
+}
+
+# a UUID claimed by another subsystem must never reach a guest
+sub _nvmet_local_namespace_ok($path, $nqn, $nsid, $uuid) {
+    my $link = _link_target($path) // return 0;
+    my $device = (split m{/}, $link)[-1];
+    return 0 if !defined($device) || $device !~ $RE_NVME_NAMESPACE;
+    my $sys = "/sys/block/$+{device}";
+    return 0 if lc(file_read_firstline("$sys/uuid") // '') ne lc($uuid);
+    return 0 if (file_read_firstline("$sys/nsid") // '') ne "$nsid";
+    return 0 if (file_read_firstline("$sys/device/subsysnqn") // '') ne $nqn;
+    return 1;
+}
+
+sub activate_volume(
+    $class, $storeid, $scfg, $volname,
+    $snapname = undef,
+    $cache = undef,
+    $hints = undef,
+) {
+    die "unable to activate snapshot from remote zfs storage\n" if $snapname;
+    my (undef, $name) = $class->parse_volname($volname);
+    my $nqn = nvmet_nqn($scfg);
+    my $dataset = nvmet_dataset($scfg, $name);
+
+    my ($inv, $cfs) = nvmet_read($scfg);
+    my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset);
+    my $state = _nvmet_export_state($cfs, $nqn, $nsid, $uuid, "/dev/zvol/$dataset");
+    my $path = "/dev/disk/by-id/nvme-uuid.$uuid";
+    my $ok = sub {
+        return _block_device($path) && _nvmet_local_namespace_ok($path, $nqn, $nsid, $uuid);
+    };
+    return 1 if $state eq 'present' && $ok->();
+
+    $cache //= {};
+    $cache->{'zfsnvme-force-reconcile'}->{$storeid} = 1;
+    $class->activate_storage($storeid, $scfg, $cache);
+    for (my $attempt = 0; $attempt < 40 && !_block_device($path); $attempt++) {
+        # a host can miss the change notice, and rescanning is harmless
+        rescan_namespaces($nqn) if $attempt % 8 == 0;
+        _sleep(0.25);
+    }
+    die "NVMe namespace for '$volname' did not appear\n" if !_block_device($path);
+    die "NVMe namespace for '$volname' has an unexpected identity\n" if !$ok->();
+    return 1;
+}
+
+sub deactivate_volume(
+    $class, $storeid, $scfg, $volname, $snapname = undef, $cache = undef,
+) {
+    die "unable to deactivate snapshot from remote zfs storage\n" if $snapname;
+    return 1;
+}
+
 1;
-- 
2.54.0.windows.1




  parent reply	other threads:[~2026-11-26 15:11 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 ` [PATCH storage v5 02/13] zfsnvme: add the target transactions Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 03/13] zfsnvme: add storage configuration and volume methods Joaquin Varela
2026-11-26 15:09 ` Joaquin Varela [this message]
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-5-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