all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Joaquin Varela <joaquinvarela@neatech.ar>
To: pve-devel@lists.proxmox.com
Subject: [PATCH storage v5 08/13] test: zfsnvme: add node side tests
Date: Thu, 26 Nov 2026 12:09:49 -0300	[thread overview]
Message-ID: <20261126150956.310593-9-joaquinvarela@neatech.ar> (raw)
In-Reply-To: <20261126150956.310593-1-joaquinvarela@neatech.ar>

Test the /dev/nvme-fabrics options, the connect child against a
pseudoterminal that answers like the fabrics device (skipped without
/dev/ptmx) and that a connect which times out gives up the host lock.
Also test rescans, the namespace checks of a deactivation, the deletion
of controllers and its re-check under the lock, loading nvme-tcp, path
selection and storage activation.

Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
 src/test/zfsnvme_test.pm | 1584 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 1583 insertions(+), 1 deletion(-)

diff --git a/src/test/zfsnvme_test.pm b/src/test/zfsnvme_test.pm
index 41991649..4f27f38b 100644
--- a/src/test/zfsnvme_test.pm
+++ b/src/test/zfsnvme_test.pm
@@ -11,7 +11,7 @@ use lib qw(..);
 use Compress::Zlib qw(crc32);
 use Config;
 use Errno qw(EACCES ECONNREFUSED EINVAL ENOENT);
-use Fcntl qw(O_NOCTTY O_RDWR);
+use Fcntl qw(:flock O_NOCTTY O_RDWR);
 use File::Temp qw(tempdir);
 use MIME::Base64 qw(encode_base64);
 use POSIX qw(
@@ -1261,6 +1261,1588 @@ subtest 'vdisk_alloc dispatches under the shared storage lock' => sub {
     $parent_mock->unmock('lookup');
 };
 
+{
+    my $portal = { address => '192.0.2.22', port => 4420, host_iface => 'ens21' };
+    my $options = sub($scfg) {
+        return nv(
+            '_fabrics_options', $scfg, $portal, $hostnqn_a, $UUID, $KEY,
+        );
+    };
+    my ($string, $names) = $options->({ subsysnqn => $NQN });
+    is(
+        $string,
+        "transport=tcp,traddr=192.0.2.22,trsvcid=4420,host_iface=ens21,nqn=$NQN,"
+            . "hostnqn=$hostnqn_a,hostid=$UUID,dhchap_secret=$KEY,keep_alive_tmo=5,"
+            . 'reconnect_delay=2,ctrl_loss_tmo=600',
+        'the portal, the identities, the key and the default timeouts',
+    );
+    is_deeply(
+        $names,
+        [
+            qw(transport traddr trsvcid host_iface nqn hostnqn hostid dhchap_secret),
+            qw(keep_alive_tmo reconnect_delay ctrl_loss_tmo),
+        ],
+        'with the names of the options',
+    );
+    my $tuned = {
+        subsysnqn => $NQN,
+        'nvme-keep-alive-tmo' => 10,
+        'nvme-reconnect-delay' => 5,
+        'nvme-ctrl-loss-tmo' => 60,
+        'nvme-fast-io-fail-tmo' => 15,
+        'nvme-nr-io-queues' => 4,
+    };
+    ($string, $names) = $options->($tuned);
+    my $tail = 'keep_alive_tmo=10,reconnect_delay=5,ctrl_loss_tmo=60,'
+        . 'fast_io_fail_tmo=15,nr_io_queues=4';
+    like($string, qr/,\Q$tail\E\z/, 'the configured timeouts and queues');
+    is_deeply([$names->@[-2, -1]], ['fast_io_fail_tmo', 'nr_io_queues'], 'are named too');
+    ($string) = $options->({ $tuned->%*, 'nvme-fast-io-fail-tmo' => 0 });
+    like($string, qr/,fast_io_fail_tmo=0,/, 'a fast I/O fail timeout of 0 is a real value');
+    ($string) = $options->({ $tuned->%*, 'nvme-ctrl-loss-tmo' => -1 });
+    like($string, qr/,ctrl_loss_tmo=-1,/, 'an infinite loss timeout');
+
+    for my $value ('6 0', '60,duplicate_connect', "60\x00", '') {
+        eval { $options->({ $tuned->%*, 'nvme-ctrl-loss-tmo' => $value }) };
+        is(
+            $@,
+            "internal error: invalid NVMe connect option 'ctrl_loss_tmo'\n",
+            'a value that would end the option early is refused without echoing it',
+        );
+    }
+}
+
+# The connect runs in a child bounded by 10 seconds plus 10 for the host lock. Its result and
+# errors pass through, a stopped task and a timeout have their own message.
+{
+    my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+    my $connect = sub($child) {
+        local @FORKS = ();
+        $nvme_mock->redefine(_fabrics_connect => $child);
+        my $res = eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY); };
+        my $error = $@;
+        $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+        return ($res, $error, [@FORKS]);
+    };
+    @LOCKS = ();
+    my ($res, $error, $forks) = $connect->(sub($options, $names) { return 7 });
+    is($res, 7, 'returns the instance of the new controller');
+    is_deeply($forks, [20], 'from a child bounded by 10 seconds and 10 for the host lock');
+    is_deeply(\@LOCKS, ['enter', 'leave'], 'that takes the host lock of PVE::NVMeOF');
+    my $held;
+    $connect->(sub(@args) {
+        $held = $LOCK_HELD;
+        return 7;
+    });
+    ok($held, 'and creates the controller while it holds it');
+    for my $exception ("received interrupt\n", "interrupted by unexpected signal\n") {
+        (undef, $error) = $connect->(sub(@args) {
+            die $exception;
+        });
+        is($error, "received interrupt\n", 'a stopped task dies with the task marker');
+    }
+    my @warnings;
+    local $SIG{__WARN__} = sub($warning) { push @warnings, $warning };
+    $nvmeof_mock->redefine(with_lock => sub($code, $limit = undef) { die $PVE::NVMeOF::TIMED_OUT });
+    (undef, $error) = $connect->(sub(@args) {
+        return 7;
+    });
+    is($error, "NVMe/TCP connect did not complete within 20 seconds\n", 'a timeout');
+    $nvmeof_mock->redefine(
+        with_lock => sub($code, $limit = undef) {
+            warn "malformed JSON string\n"; # what a child that died without a result leaves
+            return undef;
+        },
+    );
+    (undef, $error) = $connect->(sub(@args) {
+        return 7;
+    });
+    is($error, "NVMe/TCP connect left no result\n", 'a child without a result');
+    is_deeply(\@warnings, [], 'without the warning of with_lock in the task log');
+    $nvmeof_mock->redefine(with_lock => $lock_inline);
+}
+
+# The host lock is shared with the nvmeof storage and the controller API, and another activation
+# of the same storage can run at the same time, so the portal is checked again under the lock.
+{
+    reset_host();
+    my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+    my $connect = sub() {
+        my $res = eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY); };
+        return ($res, $@);
+    };
+    my $created = 0;
+    $nvme_mock->redefine(_fabrics_connect => sub(@args) { $created++; return 7 });
+
+    local $LOCK_BUSY = 1;
+    my ($res, $error) = $connect->();
+    is(
+        $error,
+        "NVMe over Fabrics is busy - another operation is still running\n",
+        'a busy host lock fails the connect',
+    );
+    is($created, 0, 'before anything is created');
+    $LOCK_BUSY = 0;
+
+    # [name, controller, expected result]
+    for my $case (
+        ['a live controller on the interface', ['nvme5', 'live', 'ens19'], -1],
+        ['a controller that is still connecting', ['nvme5', 'connecting', 'ens19'], -1],
+        ['a dead controller', ['nvme5', 'dead', 'ens19'], 7],
+        ['a controller on another interface', ['nvme5', 'live', 'ens20'], 7],
+        ['no controller', undef, 7],
+    ) {
+        my ($name, $controller, $expected) = $case->@*;
+        reset_host();
+        $created = 0;
+        if ($controller) {
+            my ($controller_name, $state, $iface) = $controller->@*;
+            add_controller($controller_name, '192.0.2.21', 4420, $iface, $state);
+        }
+        ($res, $error) = $connect->();
+        is($res, $expected, "with $name the result is $expected");
+        is($error, '', "and there is no error");
+        is($created, $expected == 7 ? 1 : 0, "and the controller is created or not accordingly");
+    }
+    $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+}
+
+my %signal = (HUP => SIGHUP, INT => SIGINT, QUIT => SIGQUIT, TERM => SIGTERM, ALRM => SIGALRM);
+
+sub blocked_signals() {
+    my $mask = POSIX::SigSet->new();
+    sigprocmask(SIG_BLOCK, POSIX::SigSet->new(), $mask) or die "sigprocmask: $!\n";
+    return join(',', grep { $mask->ismember($signal{$_}) } sort keys %signal);
+}
+
+# The child itself: a real fork under the real with_lock, on a lock file of its own.
+subtest 'the connect child' => sub {
+    $nvmeof_mock->unmock('with_lock');
+    local $PVE::NVMeOF::RUN_DIR = tempdir(CLEANUP => 1);
+    my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+    my $connect = sub() {
+        my $res = eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY); };
+        return ($res, $@);
+    };
+    $nvme_mock->redefine(_fabrics_connect => sub(@args) { return 7 });
+    my ($res, $error) = $connect->();
+    is($res, 7, 'the result of the child reaches the parent');
+    is(blocked_signals(), '', 'and the signal mask is restored');
+    $nvme_mock->redefine(
+        _fabrics_connect => sub(@args) { die "connect failed: Connection refused\n" },
+    );
+    (undef, $error) = $connect->();
+    is($error, "connect failed: Connection refused\n", 'and so does its error');
+    is(blocked_signals(), '', 'with the signal mask restored');
+
+    my $dir = tempdir(CLEANUP => 1);
+    $nvme_mock->redefine(_fabrics_connect => sub(@args) { warn "child warning\n"; return 7 });
+    open(my $saved, '>&', \*STDERR) or die "cannot save STDERR: $!\n";
+    open(STDERR, '>', "$dir/stderr") or die "cannot redirect STDERR: $!\n";
+    ($res, $error) = $connect->();
+    open(STDERR, '>&', $saved) or die "cannot restore STDERR: $!\n";
+    is($res, 7, 'a child that warns');
+    open(my $fh, '<', "$dir/stderr") or die "cannot read '$dir/stderr': $!\n";
+    is(join('', <$fh>), "child warning\n", 'is heard');
+    close($fh);
+
+    # the signal stays pending while the child runs, then the worker handler dies with the marker
+    for my $name (qw(TERM QUIT INT)) {
+        pipe(my $from_child, my $to_parent) or die "pipe: $!\n";
+        $nvme_mock->redefine(
+            _fabrics_connect => sub(@args) {
+                kill($name, getppid()) or die "kill: $!\n";
+                print {$to_parent} "$$ " . blocked_signals() . "\n";
+                close($to_parent);
+                return 7;
+            },
+        );
+        my $seen;
+        local $SIG{$name} = sub { # as in a PVE worker
+            chomp(my $report = <$from_child> // '');
+            my ($pid, $blocked) = split(/ /, $report, 2);
+            $seen = { blocked => $blocked, reaped => $pid && waitpid($pid, WNOHANG) == -1 };
+            die "received interrupt\n";
+        };
+        ($res, $error) = $connect->();
+        close($to_parent);
+        close($from_child);
+        is($error, "received interrupt\n", "$name stops the task with the task marker");
+        is(
+            $seen->{blocked},
+            'HUP,INT,QUIT,TERM',
+            'once the child, with the inherited mask, is done',
+        );
+        ok($seen->{reaped}, 'and reaped');
+        is(blocked_signals(), '', 'and the signal mask is restored');
+    }
+    $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+    $nvmeof_mock->redefine(with_lock => $lock_inline);
+};
+
+# with_lock kills its child at the limit, so a stalled connect only keeps the host lock until the
+# caller gives up. A child inside that child would run on and keep the lock.
+subtest 'a connect that times out gives up the host lock' => sub {
+    $nvmeof_mock->unmock('with_lock');
+    my $dir = tempdir(CLEANUP => 1);
+    local $PVE::NVMeOF::RUN_DIR = $dir;
+    local $PVE::NVMeOF::LOCK_WAIT = 0;
+    # the real run_fork_with_timeout, with one second instead of the limit of the plugin
+    my $fork = \&PVE::Tools::run_fork_with_timeout;
+    my @limits;
+    $tools_mock->redefine(
+        run_fork_with_timeout => sub($limit, @rest) {
+            push @limits, $limit;
+            return $fork->($limit == 10 ? 1 : $limit, @rest);
+        },
+    );
+    my $marker = "$dir/marker";
+    $nvme_mock->redefine(
+        _fabrics_connect => sub(@args) {
+            sleep(2);
+            open(my $fh, '>', $marker) or die "cannot create '$marker': $!\n";
+            close($fh);
+            return 7;
+        },
+    );
+    my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+    eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY) };
+    is($@, "NVMe/TCP connect did not complete within 10 seconds\n", 'the caller gives up');
+    is_deeply(\@limits, [10], 'at the limit that it passes to with_lock');
+    open(my $lock, '>>', "$dir/fabrics.lock") or die "cannot open the lock file: $!\n";
+    ok(flock($lock, LOCK_EX | LOCK_NB), 'and the host lock is free at once');
+    close($lock);
+    sleep(2);
+    ok(!-e $marker, 'as the connect was stopped and not left to run to its end');
+    $tools_mock->unmock('run_fork_with_timeout');
+    $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+    $nvmeof_mock->redefine(with_lock => $lock_inline);
+};
+
+# The body of the connect child, inline. A pseudoterminal stands in for the fabrics device, a
+# character device that answers reads with the lines the test writes to the master.
+subtest 'the connect child body' => sub {
+    my $body = $nvme_mock->original('_fabrics_connect');
+    my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+    my ($options, $names) = nv('_fabrics_options', scfg(), $portal, $hostnqn_a, $UUID, $KEY);
+    my $tokens = sub(@names) {
+        return join(',', map { "$_=%s" } @names) . "\n";
+    };
+    # a body that waits for a line the test did not write must not hang the suite
+    local $SIG{ALRM} = sub { die "the child body did not finish\n" };
+    my $run = sub() {
+        @RESTRICTED = ();
+        alarm(30);
+        my $res = eval { $body->($options, $names) };
+        alarm(0);
+        return ($res, $@);
+    };
+    my $dir = tempdir(CLEANUP => 1);
+    my $file = "$dir/file";
+    open(my $fh, '>', $file) or die "cannot create '$file': $!\n";
+    close($fh);
+    for my $case (
+        [
+            'a missing device',
+            "$dir/missing",
+            qr/\A'\Q$dir\E\/missing' does not exist; load the nvme-tcp kernel module\n\z/,
+        ],
+        ['a regular file', $file, qr/\A'\Q$file\E' is not a character device\n\z/],
+        [
+            'a device without the option list',
+            '/dev/null',
+            qr/\Athe running kernel does not support the NVMe connect option 'transport'\n\z/,
+        ],
+    ) {
+        my ($name, $device, $expected) = $case->@*;
+        $nvme_mock->redefine(_fabrics_device => sub () { return $device });
+        my (undef, $error) = $run->();
+        like($error, $expected, "$name is refused");
+        unlike($error, qr/\Q$KEY\E/, 'without the key in the error');
+    }
+    is(-s $file, 0, 'and nothing is written before the device is checked');
+
+    my $pty = sub() {
+        # TIOCSPTLCK and TIOCGPTN are only known for these architectures
+        return if $Config{archname} !~ m/\A(?:x86_64|i[3-6]86|aarch64|arm|riscv64)-linux/;
+        sysopen(my $master, '/dev/ptmx', O_RDWR | O_NOCTTY) or return;
+        my $zero = pack('i', 0);
+        ioctl($master, 0x40045431, $zero) or return;
+        my $number = pack('i', 0);
+        ioctl($master, 0x80045430, $number) or return;
+        my $slave = '/dev/pts/' . unpack('i', $number);
+        # keeps the line discipline: canonical reads, no echo, no translation
+        sysopen(my $keep, $slave, O_RDWR | O_NOCTTY) or return;
+        my $termios = POSIX::Termios->new();
+        $termios->getattr(fileno($keep)) or die "tcgetattr: $!\n";
+        $termios->setlflag(($termios->getlflag() & ~(ECHO | ECHONL)) | ICANON);
+        $termios->setoflag($termios->getoflag() & ~OPOST);
+        $termios->setattr(fileno($keep), TCSANOW) or die "tcsetattr: $!\n";
+        return ($master, $slave, $keep);
+    };
+    my $received = sub($master) {
+        my $readable = '';
+        vec($readable, fileno($master), 1) = 1;
+        return '' if !select($readable, undef, undef, 0.1);
+        sysread($master, my $buffer, 65536) // die "cannot read the pseudoterminal: $!\n";
+        return $buffer;
+    };
+    my ($master, $slave, $keep) = $pty->();
+    SKIP: {
+        skip 'no pseudoterminal available', 25 if !$master;
+        $nvme_mock->redefine(_fabrics_device => sub () { return $slave });
+
+        my ($res, $error);
+        for my $instance (3, 12) {
+            syswrite($master, $tokens->($names->@*, 'tls'));
+            syswrite($master, "instance=$instance,cntlid=1\n");
+            ($res, $error) = $run->();
+            is($error, '', "a connect (instance $instance)");
+            is($res, $instance, 'returns the instance of the controller');
+            is($received->($master), $options, 'after exactly one write of the options');
+            my $attrs = "/sys/class/nvme/nvme$instance";
+            is_deeply(
+                \@RESTRICTED,
+                ["$attrs/dhchap_secret", "$attrs/dhchap_ctrl_secret"],
+                'and restricts the secret attributes of that controller',
+            );
+        }
+
+        for my $missing (qw(host_iface nqn)) {
+            syswrite($master,
+                $tokens->(map { $_ eq $missing ? "${_}_suffix" : $_ } $names->@*));
+            ($res, $error) = $run->();
+            is(
+                $error,
+                "the running kernel does not support the NVMe connect option '$missing'\n",
+                "an option the kernel does not list ($missing)",
+            );
+            is($received->($master), '', 'is found before anything is written');
+        }
+
+        for my $result ("garbage\n", "instance=3,cntlid=1,garbage\n") {
+            syswrite($master, $tokens->($names->@*));
+            syswrite($master, $result);
+            ($res, $error) = $run->();
+            is($error, "unexpected connect result\n", 'an unexpected result is refused');
+            is($received->($master), $options, 'after the one write');
+            is_deeply(\@RESTRICTED, [], 'and nothing is restricted');
+        }
+
+        symlink($slave, "$dir/link") or die "symlink: $!\n";
+        $nvme_mock->redefine(_fabrics_device => sub () { return "$dir/link" });
+        ($res, $error) = $run->();
+        is(
+            $error,
+            "cannot open '$dir/link': Too many levels of symbolic links\n",
+            'a symbolic link to the device is not followed',
+        );
+        $nvme_mock->redefine(_fabrics_device => sub () { return $slave });
+
+        # A failed write: the error has the errno text and never the options.
+        my $writes = 0;
+        $nvme_mock->redefine(
+            _fabrics_write => sub($fh, $data) { $writes++; $! = ECONNREFUSED; return undef },
+        );
+        syswrite($master, $tokens->($names->@*));
+        ($res, $error) = $run->();
+        is(
+            $error,
+            "connect failed: Connection refused\n",
+            'a refused connect has the errno text',
+        );
+        is($writes, 1, 'after one write, which is not repeated');
+        is_deeply(\@RESTRICTED, [], 'and nothing is restricted');
+        $writes = 0;
+        $nvme_mock->redefine(
+            _fabrics_write => sub($fh, $data) { $writes++; return length($data) - 1 });
+        syswrite($master, $tokens->($names->@*));
+        syswrite($master, "instance=3,cntlid=1\n"); # never read: a short write ends the connect
+        ($res, $error) = $run->();
+        is($error, "connect failed: short write\n", 'a short write');
+        is($writes, 1, 'is not completed');
+        is_deeply(\@RESTRICTED, [], 'and restricts nothing');
+        $nvme_mock->unmock('_fabrics_write');
+    }
+    $nvme_mock->unmock('_fabrics_device');
+};
+
+# no namespace of the subsystem on this node, unless a test says otherwise
+my $no_namespaces = sub($nqn) { return {} };
+$nvmeof_mock->redefine(namespaces => $no_namespaces);
+
+{
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    add_controller('nvme3', '192.0.2.23', 4420, 'ens21', 'live', $OTHER_NQN);
+    my $opened = "process 123 (qemu-system-x86_64) has namespace 'nvme0n1' open";
+    $nvme_mock->redefine(_namespace_users => sub($nqn) { return [$opened] });
+    eval { $PLUGIN->deactivate_storage('nvmetest', scfg()) };
+    is(
+        $@,
+        "refusing to disconnect NVMe storage 'nvmetest': $opened\n",
+        'deactivation refuses a namespace opened by a VM',
+    );
+    is_deeply(\@DELETED, [], 'and deletes nothing');
+    $nvme_mock->redefine(_namespace_users => sub($nqn) { return [] });
+    is($PLUGIN->deactivate_storage('nvmetest', scfg()), 1, 'an unused storage is deactivated');
+    is_deeply(\@DELETED, ['nvme1', 'nvme2'], 'by deleting the controllers of its subsystem');
+    is_deeply(\@FORKS, [25], 'in one child bounded by 15 seconds and 10 for the host lock');
+    is_deeply($DIRS{'/sys/class/nvme'}, ['nvme3'], 'the controllers of other subsystems stay');
+    is($PLUGIN->deactivate_storage('nvmetest', scfg()), 1, 'a storage without controllers');
+    is_deeply(\@FORKS, [25], 'needs no child');
+    $nvme_mock->unmock('_namespace_users');
+
+    my $delete = $nvme_mock->original('_delete_controllers');
+    @SYSFS_WRITES = ();
+    is($delete->([{ name => 'nvme1' }, { name => 'nvme2' }]), 2, 'the child deletes each one');
+    is_deeply(
+        \@SYSFS_WRITES,
+        [map { ["/sys/class/nvme/$_/delete_controller", '1'] } qw(nvme1 nvme2)],
+        'through sysfs',
+    );
+    # the stock file_write: a failed write warns with the errno text, a failed open does not
+    my $file_write = $sysfs_mock->original('file_write');
+    my $dir = tempdir(CLEANUP => 1);
+    my @warnings;
+    local $SIG{__WARN__} = sub($warning) { push @warnings, $warning };
+    for my $case (['/dev/full', 'No space left on device'], [$dir, 'Is a directory']) {
+        my ($path, $reason) = $case->@*;
+        $sysfs_mock->redefine(file_write => sub($file, @args) { $file_write->($path, @args) });
+        eval { $delete->([{ name => 'nvme1' }, { name => 'nvme2' }]) };
+        is(
+            $@,
+            "cannot delete NVMe controller 'nvme1': $reason\n",
+            "a failed delete names the controller and the errno text ($reason)",
+        );
+    }
+    $sysfs_mock->redefine(file_write => sub($file, @args) { $file_write->("$dir/a/b", @args) });
+    is(
+        $delete->([{ name => 'nvme1' }, { name => 'nvme2' }]),
+        2,
+        'a controller that went away since it was listed counts as deleted',
+    );
+    $sysfs_mock->redefine(
+        file_write => sub($path, $data, @rest) {
+            warn "error writing '$data' to '$path': Device or resource busy\n";
+            $! = 0;
+            return 0;
+        },
+    );
+    eval { $delete->([{ name => 'nvme1' }]) };
+    is(
+        $@,
+        "cannot delete NVMe controller 'nvme1': Device or resource busy\n",
+        'the errno text of a failed write is the one of the warning',
+    );
+    is_deeply(\@warnings, [], 'which is not passed on');
+    $sysfs_mock->redefine(file_write => $sysfs_write);
+}
+
+# What keeps a namespace from going away comes from the helpers of PVE::Diskmanage and PVE::NVMeOF,
+# as in disconnect_guarded. They are mocked here, so each case sets what one device answers.
+subtest 'users of the namespaces' => sub {
+    my $disk_mock = Test::MockModule->new('PVE::Diskmanage');
+    my (@heads, @asked, @claims, %mounted, %held, %claimed, %opener, %partitions);
+    $nvmeof_mock->redefine(
+        namespaces => sub($nqn) {
+            die "test error: namespaces of '$nqn'\n" if $nqn ne $NQN;
+            return { map { $_ => {} } @heads };
+        },
+    );
+    $nvmeof_mock->redefine(
+        is_claimed => sub($device) {
+            push @claims, $device;
+            return $claimed{$device};
+        },
+    );
+    $disk_mock->redefine(is_mounted => sub($device) { return $mounted{$device} });
+    $disk_mock->redefine(has_holder => sub($device) { return $held{$device} });
+    $disk_mock->redefine(
+        device_opener => sub(@devices) {
+            push @asked, [@devices];
+            return shift(($opener{ $devices[0] } //= [])->@*); # one answer for each try
+        },
+    );
+    $nvme_mock->redefine(
+        _partitions => sub($device) { return ($partitions{$device} // [])->@* });
+    my $reset = sub(@names) {
+        @heads = @names;
+        @asked = @claims = ();
+        %mounted = %held = %claimed = %opener = %partitions = ();
+        reset_host();
+    };
+
+    $reset->();
+    is_deeply(nv('_namespace_users', $NQN), [], 'no namespace, no users');
+    is_deeply([\@claims, \@asked], [[], []], 'and nothing is asked');
+
+    $reset->('nvme7n1');
+    $partitions{'/dev/nvme7n1'} = ['/dev/nvme7n1p1', '/dev/nvme7n1p2'];
+    is_deeply(nv('_namespace_users', $NQN), [], 'a namespace that nothing uses');
+    is_deeply(
+        \@claims,
+        ['/dev/nvme7n1', '/dev/nvme7n1p1', '/dev/nvme7n1p2'],
+        'is checked for a claim on the namespace and on each partition',
+    );
+    is_deeply(
+        \@asked,
+        [['/dev/nvme7n1', '/dev/nvme7n1p1', '/dev/nvme7n1p2']],
+        'and for openers of all three at once',
+    );
+
+    $reset->('nvme7n1');
+    $mounted{'/dev/nvme7n1'} = '/dev/nvme7n1p1';
+    is_deeply(
+        nv('_namespace_users', $NQN),
+        ["'/dev/nvme7n1p1' is mounted"],
+        'a mounted partition is a user',
+    );
+    is_deeply([\@claims, \@asked], [[], []], 'which ends the check of the namespace');
+
+    $reset->('nvme7n1');
+    $held{'/dev/nvme7n1'} = '/dev/nvme7n1p2';
+    is_deeply(
+        nv('_namespace_users', $NQN),
+        ["'/dev/nvme7n1p2' has a holder"],
+        'so is a partition with a holder, like a volume group',
+    );
+
+    # a swap area claims the device like a mount, and is neither mounted nor held
+    $reset->('nvme7n1');
+    $partitions{'/dev/nvme7n1'} = ['/dev/nvme7n1p1'];
+    $claimed{'/dev/nvme7n1p1'} = 1;
+    is_deeply(
+        nv('_namespace_users', $NQN),
+        ["'/dev/nvme7n1p1' is claimed, for example by a swap area"],
+        'a partition that is claimed, which is how a swap area looks',
+    );
+    is_deeply(\@asked, [], 'before anyone looks for openers');
+
+    $reset->('nvme7n1');
+    my $before = $NOW;
+    $partitions{'/dev/nvme7n1'} = ['/dev/nvme7n1p1'];
+    $opener{'/dev/nvme7n1'} = [('200 (mkfs.ext4)') x 5];
+    is_deeply(
+        nv('_namespace_users', $NQN),
+        ["process 200 (mkfs.ext4) has namespace 'nvme7n1' open"],
+        'a process that keeps a partition open is a user',
+    );
+    is(scalar(@asked), 4, 'after four tries');
+    is(sprintf('%.1f', $NOW - $before), '0.9', 'with 0.3 seconds between them');
+
+    $reset->('nvme7n1');
+    $opener{'/dev/nvme7n1'} = ['4 (udevd)'];
+    is_deeply(nv('_namespace_users', $NQN), [], 'a process that lets go meanwhile is not');
+    is(scalar(@asked), 2, 'after the second try');
+
+    $reset->('nvme7n2', 'nvme7n1');
+    $mounted{'/dev/nvme7n2'} = '/dev/nvme7n2';
+    is_deeply(
+        nv('_namespace_users', $NQN),
+        ["'/dev/nvme7n2' is mounted"],
+        'of two namespaces only the one in use is named',
+    );
+    is_deeply(\@asked, [['/dev/nvme7n1']], 'while the other one was checked');
+
+    # a namespace that cannot be read must not look like one that is gone
+    $nvmeof_mock->redefine(
+        namespaces => sub($nqn) { die "cannot read the WWID of namespace 'nvme7n1'\n" },
+    );
+    $reset->();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    eval { $PLUGIN->deactivate_storage('nvmetest', scfg()) };
+    is($@, "cannot read the WWID of namespace 'nvme7n1'\n", 'the deactivation fails with it');
+    is_deeply(\@DELETED, [], 'and deletes nothing');
+
+    # the whole deactivation on top of the real check
+    $nvmeof_mock->redefine(namespaces => sub($nqn) { return { nvme7n1 => {} } });
+    $mounted{'/dev/nvme7n1'} = '/dev/nvme7n1p1';
+    eval { $PLUGIN->deactivate_storage('nvmetest', scfg()) };
+    is(
+        $@,
+        "refusing to disconnect NVMe storage 'nvmetest': '/dev/nvme7n1p1' is mounted\n",
+        'a deactivation refuses a mounted partition',
+    );
+    is_deeply(\@DELETED, [], 'and deletes nothing');
+    delete $mounted{'/dev/nvme7n1'};
+    is($PLUGIN->deactivate_storage('nvmetest', scfg()), 1, 'and goes ahead once it is free');
+    is_deeply(\@DELETED, ['nvme1'], 'by deleting the controller');
+
+    $nvmeof_mock->redefine(namespaces => $no_namespaces);
+    $nvmeof_mock->unmock('is_claimed');
+    $nvme_mock->unmock('_partitions');
+};
+
+{
+    my $link = "/dev/disk/by-id/nvme-uuid.$UUID";
+    my $check = sub($target, %files) {
+        local %LINKS = (defined($target) ? ($link => $target) : ());
+        local %FILES = (
+            '/sys/block/nvme3n1/uuid' => uc($UUID),
+            '/sys/block/nvme3n1/nsid' => '7',
+            '/sys/block/nvme3n1/device/subsysnqn' => $NQN,
+            %files,
+        );
+        my $ok = nv('_nvmet_local_namespace_ok', $link, $NQN, 7, $UUID);
+        return $ok ? 1 : 0;
+    };
+    my $device = '../../nvme3n1';
+    is($check->($device), 1, 'accepts the namespace of the subsystem, whatever the UUID case');
+    is($check->($device, '/sys/block/nvme3n1/nsid' => '8'), 0, 'refuses another NSID');
+    is(
+        $check->($device, '/sys/block/nvme3n1/device/subsysnqn' => $OTHER_NQN),
+        0,
+        'another subsystem',
+    );
+    is(
+        $check->($device, '/sys/block/nvme3n1/uuid' => '22345678-1234-1234-1234-123456789abc'),
+        0,
+        'another UUID',
+    );
+    is($check->($device, '/sys/block/nvme3n1/uuid' => undef), 0, 'an unreadable device');
+    is($check->(undef), 0, 'a missing link');
+
+    for my $target ('../../nvme3c1n1', '../../nvme3n1p1', '../../sda') {
+        is($check->($target), 0, "a link to $target");
+    }
+
+    my $dir = tempdir(CLEANUP => 1);
+    symlink('../../nvme3n1', "$dir/link") or die "symlink: $!\n";
+    is($nvme_mock->original('_link_target')->("$dir/link"), '../../nvme3n1', 'read, not followed');
+}
+
+my $activate = sub($storeid, $scfg, $cache = undef) {
+    local $FILES{"/etc/pve/priv/storage/$storeid.nvme-dhchap"} = $KEY;
+    local %CONFIG = (%CONFIG, $storeid => $scfg);
+    @ACTIVATIONS = ();
+    $nvme_mock->redefine(
+        _nvmet_activate_target => sub(@args) { push @ACTIVATIONS, [@args]; return },
+    );
+    my $res = eval { $PLUGIN->activate_storage($storeid, $scfg, $cache) };
+    my $error = $@;
+    $nvme_mock->unmock('_nvmet_activate_target');
+    return ($res, $error);
+};
+my $forced = sub($storeid) { return { 'zfsnvme-force-reconcile' => { $storeid => 1 } } };
+
+subtest 'activation preconditions' => sub {
+    my $file = sub($path, $value) {
+        return sub() { $FILES{$path} = $value }
+    };
+    my $missing_iface = sub() {
+        $nvme_mock->redefine(_local_iface_exists => sub($iface) { return $iface ne 'ens20' });
+    };
+    my $other_storage = sub(%override) {
+        return sub() { $CONFIG{other} = scfg(subsysnqn => $OTHER_NQN, %override) };
+    };
+    my $fabrics_injection = 'traddr=198.51.100.9';
+    for my $case (
+        [
+            'a kernel without native NVMe multipath',
+            $file->('/sys/module/nvme_core/parameters/multipath', undef),
+            qr/native NVMe multipath is disabled/,
+        ],
+        [
+            'multipath disabled',
+            $file->('/sys/module/nvme_core/parameters/multipath', 'N'),
+            qr/native NVMe multipath is disabled/,
+        ],
+        [
+            'no host NQN',
+            $file->('/etc/nvme/hostnqn', undef),
+            qr/invalid or missing NVMe host NQN in '\/etc\/nvme\/hostnqn'/,
+        ],
+        [
+            'a host NQN with a connect option',
+            $file->('/etc/nvme/hostnqn', "$hostnqn_a,$fabrics_injection"),
+            qr/invalid or missing NVMe host NQN in '\/etc\/nvme\/hostnqn'/,
+        ],
+        [
+            'a host that is not allowed',
+            $file->(
+                '/etc/nvme/hostnqn',
+                'nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-00000000dead',
+            ),
+            qr/local NVMe host NQN .* is missing from nvme-host-nqns/,
+        ],
+        [
+            'no host ID',
+            $file->('/etc/nvme/hostid', undef),
+            qr/invalid or missing NVMe host ID in '\/etc\/nvme\/hostid'/,
+        ],
+        [
+            'the zero host ID',
+            $file->('/etc/nvme/hostid', '00000000-0000-0000-0000-000000000000'),
+            qr/invalid or missing NVMe host ID in '\/etc\/nvme\/hostid'/,
+        ],
+        [
+            'a host ID with a connect option',
+            $file->('/etc/nvme/hostid', "$UUID,$fabrics_injection"),
+            qr/invalid or missing NVMe host ID in '\/etc\/nvme\/hostid'/,
+        ],
+        [
+            'a host ID with a newline',
+            $file->('/etc/nvme/hostid', "$UUID\n"),
+            qr/invalid or missing NVMe host ID in '\/etc\/nvme\/hostid'/,
+        ],
+        [
+            'a connection parameter that is not a number',
+            sub() { },
+            qr/invalid NVMe connection parameter 'reconnect-delay'/,
+            'nvme-reconnect-delay' => "2,$fabrics_injection",
+        ],
+        [
+            'a missing local interface',
+            $missing_iface,
+            qr/interface 'ens20' does not exist on this node/,
+        ],
+        [
+            'a pool shared with another storage',
+            $other_storage->('nvme-portals' => '192.0.2.31,192.0.2.32'),
+            qr/ZFS pool 'tank' on '192\.0\.2\.10' is already used by storage 'other'/,
+        ],
+        [
+            'a listener shared with another storage',
+            $other_storage->(pool => 'data', 'nvme-portals' => '192.0.2.31,192.0.2.22'),
+            qr/portal '192\.0\.2\.22' port 4420 is already used by storage 'other'/,
+        ],
+    ) {
+        my ($name, $setup, $error, %override) = $case->@*;
+        reset_host();
+        local %CONFIG = ();
+        $nvme_mock->redefine(_local_iface_exists => sub($iface) { return 1 });
+        $setup->();
+        my (undef, $got) = $activate->('zfsnvme-unit-s', scfg(%override));
+        like($got, $error, "refuses $name");
+        is_deeply([@ACTIVATIONS, @CONNECTS, @SYSFS_WRITES], [], 'and does nothing');
+    }
+    $nvme_mock->redefine(_local_iface_exists => sub($iface) { return 1 });
+};
+
+# As PVE::NVMeOF does, so that a node without local NVMe disks can use the storage after a reboot
+subtest 'loading the nvme-tcp module' => sub {
+    my $multipath = '/sys/module/nvme_core/parameters/multipath';
+    my @commands;
+    local $COMMAND = sub($cmd, %opts) {
+        push @commands, [$cmd, $opts{timeout}];
+        return 0;
+    };
+    reset_host();
+    my (undef, $err) = $activate->('zfsnvme-module', scfg());
+    is($err, '', 'a node that has the module activates the storage');
+    is_deeply(\@commands, [], 'without a command');
+
+    reset_host();
+    $TCP_LOADED = 0;
+    delete $FILES{$multipath}; # the module brings nvme_core with it
+    local $COMMAND = sub($cmd, %opts) {
+        push @commands, [$cmd, $opts{timeout}];
+        $FILES{$multipath} = 'Y';
+        return 0;
+    };
+    (undef, $err) = $activate->('zfsnvme-module', scfg());
+    is($err, '', 'a node without it loads it and activates the storage');
+    is_deeply(
+        \@commands,
+        [[['modprobe', 'nvme-tcp'], 10]],
+        'with modprobe, for 10 seconds at most',
+    );
+
+    reset_host();
+    $TCP_LOADED = 0;
+    @commands = ();
+    local $COMMAND =
+        sub($cmd, %opts) { die "command 'modprobe nvme-tcp' failed: exit code 1\n" };
+    (undef, $err) = $activate->('zfsnvme-module', scfg());
+    is($err, "command 'modprobe nvme-tcp' failed: exit code 1\n",
+        'a module that does not load');
+    is_deeply([@ACTIVATIONS, @CONNECTS, @SYSFS_WRITES], [], 'fails before anything is done');
+
+    reset_host();
+    $TCP_LOADED = 0;
+    local $COMMAND = sub($cmd, %opts) { return 0 };
+    $FILES{$multipath} = 'N';
+    (undef, $err) = $activate->('zfsnvme-module', scfg());
+    like($err, qr/native NVMe multipath is disabled/,
+        'a kernel with multipath off still fails');
+};
+
+subtest 'a stopped task ends the activation at the connect' => sub {
+    for my $case (
+        ["received interrupt\n", 1],
+        ["interrupted by unexpected signal\n", 1],
+        ["connect failed: Connection refused\n", 0],
+        ["NVMe/TCP connect did not complete within 10 seconds\n", 0],
+    ) {
+        my ($exception, $cancelled) = $case->@*;
+        reset_host();
+        my $calls = 0;
+        $nvme_mock->redefine(
+            _fabrics_connect => sub($options, $names) {
+                my %option = map { split(/=/, $_, 2) } split(/,/, $options);
+                ++$calls;
+                # cancellation must escape even if the write created a live path
+                add_controller("nvme$calls", $option{traddr}, 4420, $option{host_iface})
+                    if $cancelled || $calls > 1;
+                die $exception if $calls == 1;
+                return $calls;
+            },
+        );
+        my ($res, $err) = $activate->('zfsnvme-cancel', scfg());
+        is($err, $cancelled ? "received interrupt\n" : '', 'only a stopped task escapes');
+        is($res, $cancelled ? undef : 1, 'an ordinary failure still permits a degraded path');
+        is($calls, $cancelled ? 1 : 2, 'a stopped task never attempts the next portal');
+        unlike($err . join('', @WARNINGS), qr/\Q$KEY\E/, 'errors and warnings hide the key');
+    }
+    $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+
+    reset_host();
+    no warnings 'redefine';
+    local *PVE::Storage::ZFSNVMePlugin::_restrict_attr =
+        sub($path) { die "received interrupt\n" };
+    my ($res, $err) = $activate->('zfsnvme-cancel-scan', scfg());
+    is($err, "received interrupt\n",
+        'cancellation in the post-connect permission scan escapes');
+    is(scalar(@CONNECTS), 1, 'no next portal after a cancelled permission scan');
+};
+
+# A dead path is deleted in a bounded child, 5 seconds during an activation, which goes on, and 15
+# for a deactivation, which fails. Each gets 10 more seconds for the host lock. Only a stopped task
+# escapes an activation.
+subtest 'deleting a controller is bounded and keeps a stopped task' => sub {
+    my $interrupt = "received interrupt\n";
+    my $failed = "cannot delete NVMe controller 'nvme1'\n";
+    # [label, what the child does, activation error, deactivation error]
+    for my $case (
+        ['a stopped task', $interrupt, $interrupt, $interrupt],
+        ['a signalled child', "interrupted by unexpected signal\n", $interrupt, $interrupt],
+        ['a failed deletion', $failed, '', $failed],
+        [
+            'a timeout',
+            undef,
+            '',
+            "disconnecting NVMe subsystem '$NQN' did not complete within 25 seconds\n",
+        ],
+    ) {
+        my ($label, $exception, $activation_error, $deactivation_error) = $case->@*;
+        $nvmeof_mock->redefine(
+            with_lock => sub($code, $limit = undef) {
+                # without an exception, the deletion times out
+                if (!defined($exception) && $limit != 20) {
+                    push @FORKS, $limit;
+                    die $PVE::NVMeOF::TIMED_OUT;
+                }
+                return $lock_inline->($code, $limit);
+            },
+        );
+        $nvme_mock->redefine(_delete_controllers => sub($controllers) { die $exception })
+            if defined($exception);
+
+        reset_host();
+        add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+        my ($res, $err) = $activate->('zfsnvme-delete', scfg());
+        is($err, $activation_error, "$label while a dead path is deleted");
+        is($FORKS[0], 15, 'in a child bounded by 5 seconds and 10 for the host lock');
+        is(scalar(@CONNECTS), $activation_error ? 0 : 2, 'only a failure goes on to connect');
+        my $warned = $exception
+            // "deleting NVMe controller 'nvme1' did not complete within 15 seconds\n";
+        like(join("\n", @WARNINGS), qr/\Q$warned\E/, 'and is warned about')
+            if !$activation_error;
+
+        reset_host();
+        add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+        eval { $PLUGIN->deactivate_storage('zfsnvme-delete', scfg()) };
+        is($@, $deactivation_error, "$label fails the deactivation");
+        is_deeply(\@FORKS, [25], 'in a child bounded by 15 seconds and 10 for the host lock');
+        $nvme_mock->redefine(_delete_controllers => $delete_mock);
+    }
+    $nvmeof_mock->redefine(with_lock => $lock_inline);
+};
+
+# connecting and deleting controllers take the host lock one at a time, never twice
+subtest 'the host lock of the controllers' => sub {
+    my $busy = "NVMe over Fabrics is busy - another operation is still running\n";
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+    my ($res, $err) = $activate->('zfsnvme-lock', scfg());
+    is($err, '', 'an activation that replaces a dead path and adds one');
+    is_deeply(
+        \@LOCKS,
+        [('enter', 'leave') x 3],
+        'takes the lock for the deletion and for each connect, one after the other',
+    );
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+    $LOCK_BUSY = 1;
+    ($res, $err) = $activate->('zfsnvme-lock', scfg());
+    like(
+        $err,
+        qr/^no live NVMe\/TCP path for storage 'zfsnvme-lock'/,
+        'a busy lock leaves an activation without a live path to fail',
+    );
+    is_deeply([\@DELETED, \@CONNECTS], [[], []], 'after it deleted and connected nothing');
+    like(join("\n", @WARNINGS), qr/\Q$busy\E/, 'and warned about the lock');
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    $LOCK_BUSY = 1;
+    eval { $PLUGIN->deactivate_storage('zfsnvme-lock', scfg()) };
+    is($@, $busy, 'a busy lock fails the deactivation');
+    is_deeply(\@DELETED, [], 'which keeps the controllers');
+    $LOCK_BUSY = 0;
+    is($PLUGIN->deactivate_storage('zfsnvme-lock', scfg()), 1, 'and succeeds when it is free');
+    is_deeply(\@LOCKS, ['enter', 'leave'], 'under the lock');
+
+    # Another activation connects the second portal after this one checked its controllers.
+    reset_host();
+    my $meanwhile;
+    $network_mock->redefine(
+        tcp_ping => sub($host, $port, $timeout = undef) {
+            add_controller('nvme9', $host, $port, 'ens20')
+                if $host eq '192.0.2.22' && !$meanwhile++;
+            return 1;
+        },
+    );
+    ($res, $err) = $activate->('zfsnvme-lock', scfg());
+    is($err, '', 'an activation whose portal got a controller meanwhile succeeds');
+    is_deeply(\@CONNECTS, ['192.0.2.21@ens19'], 'and does not connect that portal twice');
+    $network_mock->redefine(tcp_ping => sub($host, $port, $timeout = undef) { return 1 });
+};
+
+# The kernel reuses the name of a controller that is gone, and another process can run while this
+# one waits for the host lock. So a delete looks at the controller again once it has the lock, and
+# a deactivation lists the controllers there. $ON_LOCK runs when the lock is taken for the nth time.
+subtest 'controllers are checked again under the host lock' => sub {
+    my $path = '/sys/class/nvme/nvme1';
+    my $other_subsystem = sub() { $FILES{"$path/subsysnqn"} = $OTHER_NQN };
+    my $live_again = sub() { $FILES{"$path/state"} = 'live' };
+    my $other_address = sub() {
+        $FILES{"$path/address"} = 'traddr=192.0.2.23,trsvcid=4420,host_iface=ens19';
+    };
+    my $dead = ['dead', 'ens19'];
+    my $moved = ['live', 'ens20'];
+    # [label, state and interface of the controller, change, nth lock, deleted, connects]
+    for my $case (
+        ['dead, unchanged', $dead, sub() { }, 1, ['nvme1'], 2],
+        ['dead, name reused by another subsystem', $dead, $other_subsystem, 1, [], 2],
+        ['dead, then live again', $dead, $live_again, 1, [], 1],
+        ['dead, name reused with another address', $dead, $other_address, 1, [], 2],
+        ['moved, unchanged', $moved, sub() { }, 2, ['nvme1'], 2],
+        ['moved, name reused by another subsystem', $moved, $other_subsystem, 2, [], 2],
+    ) {
+        my ($label, $controller, $change, $nth, $deleted, $connects) = $case->@*;
+        reset_host();
+        add_controller('nvme1', '192.0.2.21', 4420, $controller->[1], $controller->[0]);
+        local $ON_LOCK = sub($entry) { $change->() if $entry == $nth };
+        my ($res, $err) = $activate->('zfsnvme-recheck', scfg());
+        is($err, '', "$label: the activation succeeds");
+        is_deeply(\@DELETED, $deleted, 'and deletes what it found, not what the name is now');
+        is(scalar(@CONNECTS), $connects, 'and connects the portals that need it');
+    }
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+    local $ON_LOCK = sub($entry) { $other_subsystem->() };
+    $activate->('zfsnvme-recheck', scfg());
+    is(
+        $FILES{"$path/subsysnqn"},
+        $OTHER_NQN,
+        'the controller of the other subsystem is left alone',
+    );
+    is_deeply($DIRS{'/sys/class/nvme'}, ['nvme1', 'nvme71', 'nvme72'], 'and still there');
+
+    # the list of a deactivation is the one under the lock
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    local $ON_LOCK = sub($entry) {
+        $other_subsystem->();
+        add_controller('nvme4', '192.0.2.21', 4420, 'ens20');
+    };
+    is($PLUGIN->deactivate_storage('zfsnvme-recheck', scfg()), 1, 'a deactivation succeeds');
+    is_deeply(
+        \@DELETED,
+        ['nvme2', 'nvme4'],
+        'and deletes the controllers of the subsystem then',
+    );
+    is(
+        $FILES{"$path/subsysnqn"},
+        $OTHER_NQN,
+        'not the one that got another subsystem meanwhile',
+    );
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    local $ON_LOCK = sub($entry) { $DIRS{'/sys/class/nvme'} = [] };
+    is($PLUGIN->deactivate_storage('zfsnvme-recheck', scfg()), 1, 'and one without any left');
+    is_deeply(\@DELETED, [], 'deletes none');
+};
+
+# the core runs the hook inside the storage.cfg lock of the cluster
+subtest 'deleting a storage only touches local files' => sub {
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    @TARGET_CALLS = ();
+    $PLUGIN->on_delete_hook('zfsnvme-delete', scfg());
+    is_deeply(
+        \@UNLINKED,
+        ['/etc/pve/priv/storage/zfsnvme-delete.nvme-dhchap'],
+        'the key file is removed',
+    );
+    is_deeply(
+        [\@TARGET_CALLS, \@DELETED, \@SYSFS_WRITES, \@FORKS, \@LOCKS, \@WARNINGS],
+        [[], [], [], [], [], []],
+        'and nothing else: no target call, no lock, the controllers stay connected',
+    );
+};
+
+subtest 'slow-path backoff' => sub {
+    reset_host();
+    local %REFUSE = ('192.0.2.22' => 1);
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    my $scfg = scfg();
+    my ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+    is($error, '', 'a degraded storage activates');
+    is(scalar(@ACTIVATIONS), 1, 'through the target');
+    is_deeply(
+        [$ACTIVATIONS[0]->@[0, 2 .. 4]],
+        [
+            'zfsnvme-unit-a',
+            [
+                map { {
+                    family => 'ipv4',
+                    address => "192.0.2.2$_",
+                    port => 4420,
+                    host_iface => 'ens' . (18 + $_),
+                } } 1,
+                2,
+            ],
+            [$hostnqn_a, $hostnqn_b],
+            $KEY,
+        ],
+        'with the storage, its parsed portals, hosts and key',
+    );
+    like(
+        join("\n", @WARNINGS),
+        qr/storage 'zfsnvme-unit-a' is degraded: 1\/2 paths live/,
+        'and warns',
+    );
+    ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+    is($error, '', 'within a minute, a live path takes the fast path');
+    is(scalar(@ACTIVATIONS), 0, 'without a target call');
+    {
+        local $NOW = $NOW + 61;
+        ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+        is(scalar(@ACTIVATIONS), 1, 'a minute later the target is tried again');
+    }
+    my $cache = $forced->('zfsnvme-unit-a');
+    ($res, $error) = $activate->('zfsnvme-unit-a', $scfg, $cache);
+    is(scalar(@ACTIVATIONS), 1, 'a forced activation always reaches the target');
+    ok(!$cache->{'zfsnvme-force-reconcile'}->{'zfsnvme-unit-a'}, 'and consumes the request');
+    $FILES{'/sys/class/nvme/nvme1/state'} = 'dead';
+    ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+    is(
+        $error,
+        "no live NVMe/TCP path for storage 'zfsnvme-unit-a'\n",
+        'within a minute, without a live path the activation fails at once',
+    );
+    is_deeply([@ACTIVATIONS, @DELETED], [], 'without a target call or a reconnect');
+    {
+        local $NOW = $NOW + 61;
+        ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+        is(scalar(@ACTIVATIONS), 1, 'a minute later the target is tried');
+        is_deeply(\@DELETED, ['nvme1'], 'and the dead path is reconnected');
+    }
+
+    reset_host();
+    local %REFUSE = ('192.0.2.22' => 1);
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    local $NOW = 30; # the monotonic clock shortly after boot
+    ($res, $error) = $activate->('zfsnvme-unit-b', $scfg);
+    is(scalar(@ACTIVATIONS), 1, 'a storage that was never activated is not in its backoff');
+
+    # a storage without any path waits for one once per backoff period, not on every status update
+    reset_host();
+    local %REFUSE = ('192.0.2.21' => 1, '192.0.2.22' => 1);
+    ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+    is($error, "no live NVMe/TCP path for storage 'zfsnvme-unit-d'\n", 'no path, no storage');
+    is_deeply(
+        [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+        [1, 2],
+        'after the target and each portal',
+    );
+    @CONNECTS = ();
+    ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+    is(
+        $error,
+        "no live NVMe/TCP path for storage 'zfsnvme-unit-d'\n",
+        'within a minute it fails',
+    );
+    is_deeply([@ACTIVATIONS, @CONNECTS], [], 'at once, without a target call or a connect');
+    ($res, $error) = $activate->('zfsnvme-unit-d', $scfg, $forced->('zfsnvme-unit-d'));
+    is_deeply(
+        [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+        [1, 2],
+        'a forced activation tries again',
+    );
+    {
+        local $NOW = $NOW + 61;
+        @CONNECTS = ();
+        ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+        is_deeply(
+            [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+            [1, 2],
+            'so does one a minute later',
+        );
+    }
+
+    # Adding a storage activates it right away, and removes it again if that fails. A new storage
+    # with the same ID must not inherit the backoff of the one that was removed.
+    ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+    is($error, "no live NVMe/TCP path for storage 'zfsnvme-unit-d'\n", 'in its backoff again');
+    $PLUGIN->on_delete_hook('zfsnvme-unit-d', $scfg);
+    @CONNECTS = ();
+    ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+    is_deeply(
+        [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+        [1, 2],
+        'after its removal, the same ID reaches the target and the portals again',
+    );
+
+    # A slow path whose target call fails starts the backoff as well.
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    local $FILES{'/etc/pve/priv/storage/zfsnvme-unit-t.nvme-dhchap'} = $KEY;
+    local %CONFIG = ('zfsnvme-unit-t' => $scfg);
+    my $calls = 0;
+    $nvme_mock->redefine(
+        _nvmet_activate_target => sub(@args) {
+            $calls++;
+            die "NVMe target '192.0.2.10' is unreachable: timeout\n";
+        },
+    );
+    eval { $PLUGIN->activate_storage('zfsnvme-unit-t', $scfg) };
+    like($@, qr/is unreachable/, 'an unreachable target fails the slow path');
+    eval { $PLUGIN->activate_storage('zfsnvme-unit-t', $scfg) };
+    is($@, '', 'within a minute the live path takes the fast path');
+    is($calls, 1, 'without another target call');
+    $nvme_mock->unmock('_nvmet_activate_target');
+};
+
+subtest 'connecting the paths' => sub {
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    $network_mock->redefine(
+        tcp_ping => sub($host, $port, $timeout = undef) { return $host ne '192.0.2.22' },
+    );
+    my (undef, $error) = $activate->('zfsnvme-unit-v', scfg(), $forced->('zfsnvme-unit-v'));
+    is_deeply(\@CONNECTS, [], 'an unreachable portal is not connected');
+    like(join("\n", @WARNINGS), qr/'192\.0\.2\.22:4420' is unreachable/, 'but warned about');
+    $network_mock->redefine(tcp_ping => sub($host, $port, $timeout = undef) { return 1 });
+
+    # After a target restart, the kernel reconnects its controllers itself.
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'connecting');
+    local %REFUSE = ('192.0.2.22' => 1);
+    my $sleeps = 0;
+    $nvme_mock->redefine(
+        _sleep => sub($seconds) {
+            $NOW += $seconds;
+            $FILES{'/sys/class/nvme/nvme1/state'} = 'live' if ++$sleeps == 3;
+            return;
+        },
+    );
+    (undef, $error) = $activate->('zfsnvme-unit-w', scfg());
+    is($error, '', 'an activation waits for a controller that reconnects');
+    is($sleeps, 3, 'until it is live');
+    $nvme_mock->redefine(_sleep => sub($seconds) { $NOW += $seconds; return });
+};
+
+subtest 'moving a path to its configured interface' => sub {
+    my $single = scfg('nvme-portals' => '192.0.2.21', 'nvme-host-ifaces' => 'ens19');
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+    my ($res, $error) = $activate->('zfsnvme-unit-c', scfg());
+    is($error, '', 'a storage whose only live path uses another interface');
+    is_deeply(\@CONNECTS, ['192.0.2.21@ens19', '192.0.2.22@ens20'], 'connects both paths');
+    is_deeply(\@DELETED, ['nvme1'], 'and then disconnects the old one');
+    is_deeply(\@WARNINGS, [], 'the storage is healthy');
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+    local %CONNECT_STATE = ('192.0.2.21' => 'connecting');
+    my $start = $NOW;
+    ($res, $error) = $activate->('zfsnvme-unit-g', $single);
+    is($error, '', 'a new path that does not become live');
+    is_deeply(\@DELETED, [], 'keeps the old path');
+    like(
+        join("\n", @WARNINGS),
+        qr/'192\.0\.2\.21:4420' is not live on 'ens19' yet; keeping its path on another interface/,
+        'and warns',
+    );
+    like(join("\n", @WARNINGS), qr/is degraded: 0\/1 paths live/, 'the storage is degraded');
+    is($NOW - $start, 10, 'after waiting 10 seconds for the new path');
+    ($res, $error) = $activate->('zfsnvme-unit-g', $single);
+    ok(!$error && !@ACTIVATIONS, 'within a minute, the old path takes the fast path');
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+    local %REFUSE = ('192.0.2.21' => 1);
+    ($res, $error) = $activate->('zfsnvme-unit-h', $single);
+    is($error, '', 'a new path that cannot connect');
+    is_deeply(\@DELETED, [], 'keeps the old path too');
+    like(
+        join("\n", @WARNINGS),
+        qr/192\.0\.2\.21:4420: connect failed: Connection refused/,
+        'and warns',
+    );
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+    my $connect = $PLUGIN->can('_connect_portal');
+    {
+        no warnings 'redefine';
+        local %REFUSE = ();
+        local *PVE::Storage::ZFSNVMePlugin::_connect_portal = sub($scfg, $portal, @ids) {
+            $connect->($scfg, $portal, @ids);
+            die "connection failed after creation\n";
+        };
+        ($res, $error) = $activate->('zfsnvme-unit-h-partial', $single);
+    }
+    ok(!$error && $res == 1, 'a partially successful connect leaves the storage usable');
+    is($FILES{'/sys/class/nvme/nvme71/state'}, 'live', 'a live replacement was created');
+    is_deeply(\@DELETED, [], 'the connect error still preserves the old interface path');
+    like(
+        join("\n", @WARNINGS),
+        qr/192\.0\.2\.21:4420: connection failed after creation/,
+        'and preserves the original connect warning',
+    );
+};
+
+subtest 'reconnect timeouts reach connected controllers' => sub {
+    my $sysfs = sub () {
+        return [
+            map { [$_->[0] =~ s{\A/sys/class/nvme/}{}r, $_->[1] =~ s/\n\z//r] }
+            grep { $_->[0] =~ m{\A/sys/class/nvme/} } @SYSFS_WRITES
+        ];
+    };
+    my $case = sub($storeid, $scfg, %current) {
+        reset_host();
+        add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+        add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+        for my $name (qw(nvme1 nvme2)) {
+            $FILES{"/sys/class/nvme/$name/$_"} = $current{$_} for keys %current;
+        }
+        my ($res, $error) = $activate->($storeid, $scfg, $forced->($storeid));
+        is($error, '', "activation of $storeid");
+        return $sysfs->();
+    };
+    my $timeouts = scfg(
+        'nvme-reconnect-delay' => 5,
+        'nvme-ctrl-loss-tmo' => 60,
+        'nvme-fast-io-fail-tmo' => 10,
+    );
+    my $written = [
+        map { (
+            ["$_/reconnect_delay", 5], ["$_/ctrl_loss_tmo", 60], ["$_/fast_io_fail_tmo", 10],
+        ) } qw(nvme1 nvme2)
+    ];
+    is_deeply($case->('zfsnvme-unit-i', $timeouts), $written, 'changes reach every controller');
+    is_deeply(
+        [grep { $_->[0] =~ /iopolicy/ } @SYSFS_WRITES],
+        [['/sys/class/nvme-subsystem/nvme-subsys7/iopolicy', "round-robin\n"]],
+        'with the multipath policy',
+    );
+    my %current = (reconnect_delay => '5', ctrl_loss_tmo => '60', fast_io_fail_tmo => '10');
+    is_deeply(
+        $case->('zfsnvme-unit-j', $timeouts, %current),
+        [],
+        'unchanged ones are not written',
+    );
+    is_deeply(
+        $case->('zfsnvme-unit-k', scfg('nvme-ctrl-loss-tmo' => -1)),
+        [map { ["$_/ctrl_loss_tmo", -1] } qw(nvme1 nvme2)],
+        'an infinite loss timeout',
+    );
+    is_deeply(
+        $case->('zfsnvme-unit-l', scfg('nvme-ctrl-loss-tmo' => 7), ctrl_loss_tmo => '8'),
+        [],
+        'the loss timeout the kernel rounds up to the reconnect delay',
+    );
+    is_deeply(
+        $case->('zfsnvme-unit-m', scfg(), fast_io_fail_tmo => '5'),
+        [map { ["$_/fast_io_fail_tmo", -1] } qw(nvme1 nvme2)],
+        'an unset fast I/O fail timeout is turned off',
+    );
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    my ($res, $error) = $activate->('zfsnvme-unit-n', $timeouts);
+    ok(!$error && $res == 1, 'a healthy storage activates on the fast path');
+    is(scalar(@ACTIVATIONS) + scalar(@CONNECTS), 0, 'without a target call or connect');
+    is_deeply($sysfs->(), $written, 'which also writes changed timeouts');
+    is_deeply(
+        [grep { $_->[0] =~ /iopolicy/ } @SYSFS_WRITES],
+        [['/sys/class/nvme-subsystem/nvme-subsys7/iopolicy', "round-robin\n"]],
+        'and the multipath policy',
+    );
+    delete $FILES{'/etc/pve/priv/storage/zfsnvme-unit-n.nvme-dhchap'};
+    $res = eval {
+        local %CONFIG = ('zfsnvme-unit-n' => $timeouts);
+        $PLUGIN->activate_storage('zfsnvme-unit-n', $timeouts);
+    };
+    is($@, "missing NVMe DH-HMAC-CHAP key\n", 'the fast path needs the key file');
+
+    # file_write warns about a failed write and is silent about a failed open, errno stays in $!
+    my @perl_warnings;
+    local $SIG{__WARN__} = sub($warning) { push @perl_warnings, $warning };
+    my $failing = sub($pattern, $errno, $warn) {
+        $sysfs_mock->redefine(
+            file_write => sub($path, $data, @rest) {
+                return $sysfs_write->($path, $data) if $path !~ $pattern;
+                $! = $errno;
+                return undef if !$warn;
+                warn "error writing '$data' to '$path': $!\n";
+                $! = ENOENT; # not the reason: file_write closed the file since
+                return 0;
+            },
+        );
+    };
+    my $reason = sub($errno) { local $! = $errno; return "$!" };
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    $failing->(qr{/nvme1/ctrl_loss_tmo\z}, EINVAL, 1);
+    ($res, $error) = $activate->('zfsnvme-unit-e', $timeouts);
+    is($error, '', 'a timeout that cannot be written does not fail the activation');
+    my $einval = $reason->(EINVAL);
+    is_deeply(
+        [@WARNINGS, @perl_warnings],
+        ["cannot set ctrl_loss_tmo of NVMe controller 'nvme1': $einval"],
+        'and is reported once, as a task warning with the reason',
+    );
+    reset_host();
+    @perl_warnings = ();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    $failing->(qr{/nvme2/ctrl_loss_tmo\z}, EACCES, 0);
+    ($res, $error) = $activate->('zfsnvme-unit-tmo-open', $timeouts);
+    is($error, '', 'a timeout that cannot be opened does not fail the activation');
+    is_deeply(
+        [@WARNINGS, @perl_warnings],
+        ["cannot set ctrl_loss_tmo of NVMe controller 'nvme2': " . $reason->(EACCES)],
+        'and is reported once, with the reason',
+    );
+    reset_host();
+    @perl_warnings = ();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    $failing->(qr{/iopolicy\z}, EACCES, 0);
+    ($res, $error) = $activate->('zfsnvme-unit-f', $timeouts);
+    is(
+        $error,
+        'unable to set NVMe multipath policy: ' . $reason->(EACCES) . "\n",
+        'a policy that cannot be set fails the activation',
+    );
+    is_deeply([@WARNINGS, @perl_warnings], [], 'with the reason in the error only');
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    $failing->(qr{/iopolicy\z}, EINVAL, 1);
+    ($res, $error) = $activate->('zfsnvme-unit-policy-write', $timeouts);
+    is(
+        $error,
+        "unable to set NVMe multipath policy: $einval\n",
+        'a policy that cannot be written fails the activation',
+    );
+    is_deeply([@WARNINGS, @perl_warnings], [],
+        'and the warning of file_write is not passed on');
+
+    # The stock file_write on an attribute that does not exist: unlike a deletion or a rescan,
+    # setting a timeout or the policy treats the failed open (ENOENT) as a failure like any other.
+    my $file_write = $sysfs_mock->original('file_write');
+    my $missing = tempdir(CLEANUP => 1) . '/a/b';
+    my $absent = sub($pattern) {
+        $sysfs_mock->redefine(
+            file_write => sub($path, $data, @rest) {
+                return $sysfs_write->($path, $data) if $path !~ $pattern;
+                return $file_write->($missing, $data, @rest);
+            },
+        );
+    };
+    my $enoent = $reason->(ENOENT);
+    reset_host();
+    @perl_warnings = ();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    $absent->(qr{/nvme1/reconnect_delay\z});
+    ($res, $error) = $activate->('zfsnvme-unit-tmo-missing', $timeouts);
+    is($error, '', 'a missing timeout attribute does not fail the activation');
+    is_deeply(
+        [@WARNINGS, @perl_warnings],
+        ["cannot set reconnect_delay of NVMe controller 'nvme1': $enoent"],
+        'but is reported once, as a task warning with the reason',
+    );
+    reset_host();
+    @perl_warnings = ();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    $absent->(qr{/iopolicy\z});
+    ($res, $error) = $activate->('zfsnvme-unit-policy-missing', $timeouts);
+    is(
+        $error,
+        "unable to set NVMe multipath policy: $enoent\n",
+        'a missing policy attribute fails the activation',
+    );
+    is_deeply([@WARNINGS, @perl_warnings], [], 'with the reason in the error only');
+    $sysfs_mock->redefine(file_write => $sysfs_write);
+};
+
+subtest 'the key attributes of the controllers are private' => sub {
+    my $attrs = sub(@names) {
+        my @attrs = qw(dhchap_secret dhchap_ctrl_secret);
+        return [
+            map {
+                my $name = $_;
+                map { "/sys/class/nvme/$name/$_" } @attrs
+            } @names
+        ];
+    };
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+    add_controller('nvme3', '192.0.2.23', 4420, 'ens21', 'live', $OTHER_NQN);
+    my ($res, $error) = $activate->('zfsnvme-unit-o', scfg());
+    is($error, '', 'a healthy storage');
+    is_deeply(
+        \@RESTRICTED,
+        $attrs->('nvme1', 'nvme2'),
+        'restricts its controllers on the fast path',
+    );
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+    ($res, $error) = $activate->('zfsnvme-unit-p', scfg(), $forced->('zfsnvme-unit-p'));
+    is($error, '', 'a forced activation');
+    is_deeply(
+        \@RESTRICTED,
+        $attrs->('nvme1', 'nvme1', 'nvme71'),
+        'restricts those of the existing controllers first, then those of new ones',
+    );
+
+    reset_host();
+    local %CONNECT_STATE = map { ($_ => 'connecting') } '192.0.2.21', '192.0.2.22';
+    ($res, $error) = $activate->('zfsnvme-unit-q', scfg());
+    is(
+        $error,
+        "no live NVMe/TCP path for storage 'zfsnvme-unit-q'\n",
+        'an activation that fails',
+    );
+    is_deeply(
+        \@RESTRICTED,
+        $attrs->('nvme71', 'nvme71', 'nvme72'),
+        'each one after its connect',
+    );
+
+    reset_host();
+    add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'connecting');
+    $nvme_mock->redefine(_nvmet_activate_target => sub(@args) { die "unreachable\n" });
+    $res = eval {
+        local $FILES{'/etc/pve/priv/storage/zfsnvme-unit-x.nvme-dhchap'} = $KEY;
+        local %CONFIG = ('zfsnvme-unit-x' => scfg());
+        $PLUGIN->activate_storage('zfsnvme-unit-x', scfg());
+    };
+    is($@, "unreachable\n", 'a slow path that fails at the target');
+    is_deeply(\@RESTRICTED, $attrs->('nvme1'), 'still restricts the existing controllers');
+    $nvme_mock->unmock('_nvmet_activate_target');
+
+    # the first connect fails after it created a live controller, in the second case the permission
+    # scan after it fails too
+    my $connect = $PLUGIN->can('_connect_portal');
+    my $connect_error = "connection failed after creation\n";
+    for my $scan_error (0, 1) {
+        reset_host();
+        my $scan_failed = 0;
+        {
+            no warnings 'redefine';
+            local *PVE::Storage::ZFSNVMePlugin::_connect_portal = sub($scfg, $portal, @ids) {
+                is_deeply(
+                    \@RESTRICTED,
+                    $attrs->('nvme71'),
+                    'a failed connect restricts both attributes before the next connect',
+                ) if @CONNECTS == 1 && !$scan_error;
+                $connect->($scfg, $portal, @ids);
+                die $connect_error if @CONNECTS == 1;
+            };
+            local *PVE::Storage::ZFSNVMePlugin::_restrict_attr = sub($path) {
+                push @RESTRICTED, $path;
+                eval { 1 }; # A permission helper must not erase the saved connect error.
+                die "permission scan failed\n" if $scan_error && !$scan_failed++;
+                return;
+            };
+            ($res, $error) = $activate->("zfsnvme-unit-secret-failure-$scan_error", scfg());
+        }
+        is($error, '', 'a connect error does not discard its live controller');
+        ok(
+            scalar(grep { $_ eq "192.0.2.21:4420: $connect_error" } @WARNINGS),
+            'and warns about it',
+        );
+        if ($scan_error) {
+            ok(
+                scalar(
+                    grep { $_ eq "cannot restrict NVMe controller attributes for '$NQN'" }
+                        @WARNINGS
+                ),
+                'the scan failure has its own warning',
+            );
+            unlike(join("\n", @WARNINGS), qr/permission scan failed/, 'without its exception');
+        } else {
+            is_deeply(
+                \@RESTRICTED,
+                $attrs->('nvme71', 'nvme71', 'nvme72'),
+                'each attempt restricts the controllers, including a failed last connect',
+            );
+        }
+    }
+
+    my $dir = tempdir(CLEANUP => 1);
+    my $restrict = $nvme_mock->original('_restrict_attr');
+    for my $mode (0644, 0640, 0600, 0400) {
+        my $file = sprintf('%s/attr-%o', $dir, $mode);
+        open(my $fh, '>', $file) or die "open: $!\n";
+        close($fh);
+        chmod($mode, $file);
+        $restrict->($file);
+        is(
+            (stat($file))[2] & 07777,
+            $mode & 077 ? 0600 : $mode,
+            sprintf('an attribute with mode %o', $mode),
+        );
+    }
+    @WARNINGS = ();
+    $restrict->("$dir/missing");
+    is_deeply(\@WARNINGS, [], 'a missing attribute is skipped');
+    my $not_directory = "$dir/attr-600/child";
+    $restrict->($not_directory);
+    like(join("\n", @WARNINGS), qr/\Q$not_directory\E/, 'another stat failure warns');
+};
+
+subtest 'controllers match IPv6 portals in any spelling' => sub {
+    reset_host();
+    add_controller('nvme1', '2001:db8:0:0::11', 4420, 'ens19');
+    add_controller('nvme2', '2001:DB8::12', 4420, 'ens20');
+    my $scfg = scfg('nvme-portals' => '[2001:db8::11],[2001:db8::0:12]');
+    my ($res, $error) = $activate->('zfsnvme-unit-r', $scfg);
+    is($error, '', 'both paths are live');
+    is(scalar(@ACTIVATIONS) + scalar(@CONNECTS), 0, 'without a target call or connect');
+};
+
+is_deeply(\@COMMANDS, [], 'the host side ran no command');
+
 done_testing();
 
 1;
-- 
2.54.0.windows.1




  parent reply	other threads:[~2026-11-26 15:12 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 ` [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 ` Joaquin Varela [this message]
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-9-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 an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal