From: Ciro Iriarte <cyruspy@gmail.com>
To: pve-devel@lists.proxmox.com
Subject: [RFC PATCH storage v2 4/6] btrfs, lvmthin: implement copy-offload (atomic class)
Date: Thu, 26 Nov 2026 13:57:03 -0300 [thread overview]
Message-ID: <20261126.4.copyoffload-v2@cyruspy.gmail.com> (raw)
In-Reply-To: <20261126.0.copyoffload-v2@cyruspy.gmail.com>
From: Ciro Iriarte <ciro.iriarte+software@gmail.com>
Both backends already have the primitive PVE uses for linked clones:
'btrfs subvolume snapshot' and a thin snapshot. Both are instant and
immediately independent of their source, because btrfs and the thin pool
reference-count extents and blocks, so copy_image_status() reports
complete on the first poll.
btrfs handles raw VM disks, which it stores as subvolumes; qcow2 and
vmdk are plain files there. lvmthin needs the same volume group and thin
pool, since a thin snapshot cannot leave its pool. copy_image_check()
refuses other pairs, so they take the host-side path. VM disks are
recognized with vtype_matches($vtype, 'vm-vol'), as parse_volname()
returns 'vm-vol' rather than 'images' since API 17.
prepare creates the target to reserve the name, and start moves that
placeholder aside, as neither primitive writes into an existing name:
- For btrfs raw the placeholder includes the disk.raw file, since
list_images() skips a subvolume without it, and a second prepare for
the same VM would then pick the same name.
- lvmthin parks under a 'copytmp-' prefix: list_images() and
parse_volname() do not match it, while find_free_diskname(), which
matches unanchored, still sees the disk number.
- btrfs snapshots under a staging name first, then swaps it into place
with renameat2(RENAME_EXCHANGE), so the name stays reserved
throughout. A parked btrfs subvolume does not reserve the name, as its
lister ignores it.
- The btrfs same-filesystem check compares filesystem UUIDs: every
subvolume has its own st_dev, and one filesystem may be mounted at
several points.
status removes the placeholder outside the freeze. free_image() removes
it too, for a copy rolled back between start and status, and prepare
reaps one left by a copy that died.
copy_offload_functional_test.pl builds a loop-backed btrfs and thin pool
and checks the copies byte for byte: a copy from a snapshot has the
snapshot's content, copies survive deleting the source, two prepares for
one VM get different names, a leaked placeholder does not block the
name, the name stays held between start and status, and freeing a
started copy leaves no placeholder behind. It needs root, so it is not
part of run_plugin_tests.pl. copy_offload_check_test.pm covers
copy_image_check() for all four plugins with real volume names, and
checks that copy_offload_class() falls back for a refused pair.
Signed-off-by: Ciro Iriarte <ciro.iriarte+software@gmail.com>
---
Changes in v2:
* rebased onto current master
* rebase: VM disks are matched with vtype_matches(), as in 3/6; the
'images' comparison carried over from v1 would refuse every volume
* new copy_image_check() for both, also called by prepare()
* btrfs offloads raw images only; 'subvol' volumes belong to
containers, which qm never copies
* the findmnt mount point is untainted
* btrfs free_image() removes the parked placeholder of a copy rolled
back between start and status
* new copy_offload_check_test.pm, which goes through the real
parse_volname(); the functional test covers the btrfs rollback
src/PVE/Storage/BTRFSPlugin.pm | 267 ++++++++++++++++++++
src/PVE/Storage/LvmThinPlugin.pm | 202 +++++++++++++++-
src/test/copy_offload_check_test.pm | 208 ++++++++++++++++
src/test/copy_offload_feature_test.pm | 99 ++++++++
src/test/copy_offload_functional_test.pl | 296 +++++++++++++++++++++++
src/test/run_plugin_tests.pl | 2 +
6 files changed, 1073 insertions(+), 1 deletion(-)
create mode 100644 src/test/copy_offload_check_test.pm
create mode 100644 src/test/copy_offload_feature_test.pm
create mode 100644 src/test/copy_offload_functional_test.pl
diff --git a/src/PVE/Storage/BTRFSPlugin.pm b/src/PVE/Storage/BTRFSPlugin.pm
index 72cb39b..e861c5f 100644
--- a/src/PVE/Storage/BTRFSPlugin.pm
+++ b/src/PVE/Storage/BTRFSPlugin.pm
@@ -51,6 +51,7 @@ sub plugindata {
format => [{ raw => 1, subvol => 1 }, 'raw'],
'advanced-properties' => {
preallocation => 1,
+ 'copy-offload-timeout' => 1,
},
'hidden-properties' => {
'create-base-path' => 1,
@@ -95,6 +96,8 @@ sub options {
'create-base-path' => { optional => 1 },
'create-subdirs' => { optional => 1 },
preallocation => { optional => 1 },
+ 'copy-offload' => { optional => 1 },
+ 'copy-offload-timeout' => { optional => 1 },
# TODO: The new variant of mkdir with `populate` vs `create`...
};
}
@@ -467,6 +470,14 @@ sub free_image {
);
$class->btrfs_cmd(['subvolume', 'delete', '--', @snapshot_vols, $subvol]);
+
+ # The placeholder of an offloaded copy that was rolled back between start and status.
+ # It is invisible to list_images(), so nothing else would remove it.
+ if ($format eq 'raw' && -e "$subvol.copytmp") {
+ eval { $class->btrfs_cmd(['subvolume', 'delete', '--', "$subvol.copytmp"]) };
+ warn $@ if $@;
+ }
+
# try to cleanup directory to not clutter storage with empty $vmid dirs if
# all images from a guest got deleted
my $dir = dirname($subvol);
@@ -644,6 +655,16 @@ sub volume_has_feature {
rename => {
current => { qcow2 => 1, raw => 1, vmdk => 1 },
},
+ # 'btrfs subvolume snapshot' is instant, shares extents copy-on-write, and is
+ # independent of its source straight away: btrfs reference counts extents and
+ # does not pin an origin the way ZFS does. Only raw VM disks qualify: they are
+ # stored as subvolumes, while qcow2 and vmdk are plain files here and would need
+ # the reflink path. A 'subvol' is a container volume, which qm never copies.
+ 'copy-offload-atomic' => {
+ base => { raw => 1 },
+ current => { raw => 1 },
+ snap => { raw => 1 },
+ },
};
my ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format) =
@@ -1022,4 +1043,250 @@ sub get_import_metadata {
return PVE::Storage::DirPlugin::get_import_metadata(@_);
}
+# ---- storage-offloaded full copy via subvolume snapshot ---------------------------
+#
+# 'btrfs subvolume snapshot' is instant and shares extents copy-on-write. btrfs
+# reference counts those extents and has no concept of an origin that must outlive its
+# snapshots, so the copy is independent immediately; deleting the source is fine.
+# That satisfies 'copy-offload-atomic' with no background work, so copy_image_status()
+# is complete on the first poll.
+#
+# This is the same primitive clone_image() uses. The difference is what PVE records
+# afterwards: a linked clone carries a dependency it has to respect, while here we can
+# hand back a volume with no parent, because on btrfs there is none.
+#
+# Only raw VM disks are handled: they are stored inside subvolumes. qcow2 and vmdk are
+# plain files here, so they would need the reflink path, and a 'subvol' is a container
+# volume, which qm never copies. None of those is advertised.
+
+# Resolve a volume to the subvolume that backs it, honouring $snapname.
+my sub volume_subvol {
+ my ($class, $scfg, $volname, $snapname) = @_;
+
+ my (undef, undef, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
+ my $path = $class->filesystem_path($scfg, $volname, $snapname);
+
+ return $format eq 'raw' ? raw_file_to_subvol($path) : $path;
+}
+
+# btrfs cannot snapshot across filesystems, and the target may be a different storage.
+#
+# Not st_dev or statfs f_fsid: btrfs gives every subvolume its own st_dev,
+# and folds the subvolume id into f_fsid too, so both differ between two subvolumes of
+# the one filesystem and would reject every legitimate copy. The filesystem UUID is the
+# only stable identity. This costs a command, but it runs in prepare(), never in the
+# freeze-sensitive start().
+my sub btrfs_fsid {
+ my ($path) = @_;
+
+ # 'btrfs filesystem show' takes a device or a mount point, not an arbitrary path,
+ # so resolve the containing mount first. Note this cannot be done with stat():
+ # coreutils' own %m reports a btrfs subvolume as its own mount point, for the same
+ # st_dev reason.
+ my $mnt;
+ eval {
+ run_command(
+ ['findmnt', '--noheadings', '--output', 'TARGET', '--target', $path],
+ outfunc => sub { $mnt //= $_[0] if $_[0] =~ /\S/ },
+ );
+ };
+ return (undef, " - $@") if $@;
+ return (undef, " - findmnt reported no mount point") if !defined($mnt);
+ chomp $mnt;
+ # untaint: command output, and pvedaemon runs with taint checks
+ ($mnt) = $mnt =~ m|^(/.*)$| or return (undef, " - unexpected mount point '$mnt'");
+
+ # Compare by UUID rather than by mount point: one btrfs filesystem can be
+ # mounted at several places (a 'subvol=' mount per storage is a normal PVE setup),
+ # and a snapshot between them is valid.
+ my $uuid;
+ my $stderr = '';
+ eval {
+ run_command(
+ ['btrfs', 'filesystem', 'show', '--', $mnt],
+ outfunc => sub {
+ my ($line) = @_;
+ $uuid = $1 if !defined($uuid) && $line =~ m/\buuid:\s*(\S+)/i;
+ },
+ # A non-btrfs target is an ordinary "cannot offload this" answer, not a
+ # fault worth printing to the task log. The reason is returned to the
+ # caller instead, so it still ends up in the error it raises.
+ errfunc => sub { $stderr .= $_[0] },
+ );
+ };
+ return (undef, " - $@") if $@;
+ return (undef, $stderr =~ /\S/ ? " - $stderr" : " - no uuid in 'btrfs filesystem show'")
+ if !defined($uuid);
+ return ($uuid, undef);
+}
+
+sub copy_image_check {
+ my ($class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts) = @_;
+
+ my ($vtype, undef, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
+ return "only VM disks can be offloaded, not '$vtype'"
+ if !PVE::Storage::Common::vtype_matches($vtype, 'vm-vol');
+ return "cannot offload format '$format'" if $format ne 'raw';
+
+ # A subvolume snapshot copies the subvolume as it is; it cannot convert formats.
+ my $target_format = $opts->{format} // $format;
+ return "cannot convert '$format' to '$target_format'" if $target_format ne $format;
+
+ my $subvol = volume_subvol($class, $scfg, $volname, $snap);
+ return "'$subvol' does not exist" if !-e $subvol;
+
+ # Keep "could not work out which filesystem this is" distinct from "they are two
+ # different filesystems". Reporting a mismatch when findmnt or btrfs is missing, or
+ # when the path is not on btrfs at all, sends people looking in the wrong place.
+ # findmnt needs an existing path; the target's images directory may not exist yet,
+ # and the storage path holds it either way.
+ my $target_dir = $class->get_subdir($target_scfg, 'images');
+ $target_dir = $target_scfg->{path} if !-d $target_dir;
+ my ($src_fsid, $src_err) = btrfs_fsid($subvol);
+ return "cannot determine the btrfs filesystem of '$subvol'$src_err"
+ if !defined($src_fsid);
+ my ($dst_fsid, $dst_err) = btrfs_fsid($target_dir);
+ return "cannot determine the btrfs filesystem of '$target_dir'$dst_err"
+ if !defined($dst_fsid);
+ return "source and target are on different btrfs filesystems" if $src_fsid ne $dst_fsid;
+
+ return undef;
+}
+
+sub copy_image_prepare {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_vmid, $snap, $opts,
+ ) = @_;
+
+ my $reason = $class->copy_image_check(
+ $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts,
+ );
+ die "cannot offload copy of '$volname': $reason\n" if defined($reason);
+
+ my $format = ($class->parse_volname($volname))[6];
+ my $subvol = volume_subvol($class, $scfg, $volname, $snap);
+ my $imagedir = $class->get_subdir($target_scfg, 'images') . "/$target_vmid";
+ mkpath $imagedir;
+
+ # the trailing 1 adds the format suffix; without it the volname does not parse
+ my $name =
+ $class->find_free_diskname($target_storeid, $target_scfg, $target_vmid, $format, 1);
+ my $target_volname = "$target_vmid/$name";
+
+ # Create the target, do not just pick a name. The caller runs this under the
+ # target storage lock and releases it before copy_image_start(), so a name that was
+ # only chosen could be taken by a concurrent allocation in between, and the
+ # caller's rollback would then free a volume belonging to that other operation.
+ # An empty subvolume costs nothing and is what free_image() already knows how to
+ # remove.
+ my $newsubvol = volume_subvol($class, $target_scfg, $target_volname, undef);
+
+ # Reap a placeholder left by an earlier copy that died between start() and
+ # status(). The rename in start() refuses to park onto an existing path, so without
+ # this every future offloaded copy to this name fails, and the leftover is
+ # invisible to list_images(), so nothing would point at the cause. Safe here: we
+ # hold the target storage lock, we are outside any freeze, and the name is ours
+ # because find_free_diskname() just handed it out.
+ my $stale = "$newsubvol.copytmp";
+ if (-e $stale) {
+ warn "removing stale copy placeholder '$stale'\n";
+ $class->btrfs_cmd(['subvolume', 'delete', '--', $stale]);
+ }
+
+ $class->btrfs_cmd(['subvolume', 'create', '--', $newsubvol]);
+
+ # For 'raw' the volume is the disk.raw inside the subvolume, and that file is what
+ # list_images() stats. Without it file_size_info() returns undef and the entry is
+ # skipped, which would make this reservation invisible to find_free_diskname().
+ # The core prepares every disk of a VM before starting any of them, so the second
+ # prepare() for the same target would then pick this same name and die on
+ # 'subvolume create', failing every multi-disk offloaded clone. Create the file
+ # too, as alloc_image does.
+ if ($format eq 'raw') {
+ my $raw = "$newsubvol/disk.raw";
+ my $fh;
+ if (!sysopen($fh, $raw, O_WRONLY | O_CREAT | O_EXCL, 0640)) {
+ my $err = $!;
+ eval { $class->btrfs_cmd(['subvolume', 'delete', '--', $newsubvol]); };
+ warn $@ if $@;
+ die "unable to reserve '$raw' - $err\n";
+ }
+ close($fh);
+ }
+
+ return $target_volname;
+}
+
+sub copy_image_start {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_volname, $snap,
+ ) = @_;
+
+ # Snapshot the source the caller asked for. Falling back to the current subvolume
+ # when a snapshot was requested would copy live data instead.
+ my $subvol = volume_subvol($class, $scfg, $volname, $snap);
+ my $newsubvol = volume_subvol($class, $target_scfg, $target_volname, undef);
+
+ # copy_image_prepare() reserved the name with a placeholder subvolume, and
+ # 'subvolume snapshot' will not write into a path that already exists. So: snapshot
+ # to a staging name, then atomically exchange staging and the reserved name.
+ #
+ # PVE::Tools::renameat2(RENAME_EXCHANGE) rather than a pair of rename(2)s. Parking
+ # the placeholder aside and moving the copy in afterwards leaves the reserved name
+ # unheld in between, and for btrfs that loses the reservation. Unlike lvmthin,
+ # where find_free_diskname() reads the raw LV list and still sees the parked LV,
+ # btrfs goes through list_images(), whose name pattern rejects the '.copytmp'
+ # suffix. A concurrent allocation could take the name, and the caller's rollback
+ # would then free somebody else's volume. With the exchange the name is occupied
+ # at every instant, by either the placeholder or the finished copy, so that window
+ # does not exist. The placeholder ends up at the staging path.
+ my $staging = "$newsubvol.copytmp";
+
+ # The expensive part, done off to one side; the reserved name is untouched, so
+ # a failure here needs no unwinding beyond dropping the staging subvolume.
+ eval { $class->btrfs_cmd(['subvolume', 'snapshot', '--', $subvol, $staging]); };
+ if (my $err = $@) {
+ eval { $class->btrfs_cmd(['subvolume', 'delete', '--', $staging]) if -e $staging; };
+ warn $@ if $@;
+ die $err;
+ }
+
+ # The paths are absolute, so pass -1 as the file descriptors, the same call this
+ # plugin already makes when rotating a rollback target into place.
+ if (!PVE::Tools::renameat2(-1, $staging, -1, $newsubvol, &PVE::Tools::RENAME_EXCHANGE)) {
+ my $rerr = $!;
+ # Nothing moved: the reserved name still holds the placeholder, so the caller's
+ # rollback frees exactly what it was given.
+ eval { $class->btrfs_cmd(['subvolume', 'delete', '--', $staging]); };
+ warn $@ if $@;
+ die "unable to swap the copy into '$newsubvol' - $rerr\n";
+ }
+
+ # The displaced placeholder, now at the staging path, is not removed here. This
+ # runs while the caller may hold a guest filesystem frozen, and removing it is
+ # cleanup nothing depends on; copy_image_status() does it.
+ return;
+}
+
+sub copy_image_status {
+ my ($class, $scfg, $storeid, $volname, $source) = @_;
+
+ # $volname is the target. The snapshot is complete and independent the moment btrfs
+ # returns, so there is nothing to poll; what is left is dropping the placeholder
+ # copy_image_start() parked, which is done here to keep it out of the freeze window.
+ my (undef, undef, undef, undef, undef, undef, $format) =
+ eval { $class->parse_volname($volname) };
+ if (!$@ && defined($format) && $format eq 'raw') {
+ my $parked = volume_subvol($class, $scfg, $volname, undef) . '.copytmp';
+ if (-e $parked) {
+ eval { $class->btrfs_cmd(['subvolume', 'delete', '--', $parked]); };
+ warn $@ if $@;
+ }
+ }
+
+ return { state => 'complete' };
+}
+
1
diff --git a/src/PVE/Storage/LvmThinPlugin.pm b/src/PVE/Storage/LvmThinPlugin.pm
index 0baeab5..398a7d9 100644
--- a/src/PVE/Storage/LvmThinPlugin.pm
+++ b/src/PVE/Storage/LvmThinPlugin.pm
@@ -39,7 +39,7 @@ sub plugindata {
{ images => 1, 'vm-vol' => 1, 'vm-state' => 1, rootdir => 1, 'ct-vol' => 1 },
{ images => 1, rootdir => 1 },
],
- 'advanced-properties' => {},
+ 'advanced-properties' => { 'copy-offload-timeout' => 1 },
'hidden-properties' => {
bwlimit => 1,
},
@@ -66,6 +66,8 @@ sub options {
disable => { optional => 1 },
content => { optional => 1 },
bwlimit => { optional => 1 },
+ 'copy-offload' => { optional => 1 },
+ 'copy-offload-timeout' => { optional => 1 },
};
}
@@ -146,6 +148,17 @@ sub alloc_image {
return $name;
}
+# Where copy_image_start() parks the reservation while it creates the snapshot.
+#
+# A prefix, not a suffix: list_images() selects on m/^(vm|base)-(\d+)-/ and
+# parse_volname() accepts m/^((vm|base)-(\d+)-\S+)$/, so 'vm-101-disk-0.copytmp' would
+# be a valid volume name and would show up as an unused disk of VM 101, one that
+# outlives the copy if it ever leaks. Prefixing puts it outside both patterns.
+my sub parked_name {
+ my ($volname) = @_;
+ return "copytmp-$volname";
+}
+
sub free_image {
my ($class, $storeid, $scfg, $volname, $isBase) = @_;
@@ -162,6 +175,13 @@ sub free_image {
run_command($cmd, errmsg => "lvremove snapshot '$vg/$lv' error");
}
+ # a copy placeholder parked under this name, if a copy died mid-flight
+ my $parked = parked_name($volname);
+ if ($dat->{$parked}) {
+ my $cmd = ['/sbin/lvremove', '-f', "$vg/$parked"];
+ run_command($cmd, errmsg => "lvremove copy placeholder '$vg/$parked' error");
+ }
+
# finally remove original (if exists)
if ($dat->{$volname}) {
my $cmd = ['/sbin/lvremove', '-f', "$vg/$volname"];
@@ -431,6 +451,11 @@ sub volume_has_feature {
copy => { base => 1, current => 1, snap => 1 },
sparseinit => { base => 1, current => 1 },
rename => { current => 1 },
+ # A thin snapshot is instant, allocates nothing, and is independent of its
+ # origin straight away (see the note at the top of this file): the origin can
+ # be deleted without affecting it. Snapshots of a snapshot work too, so all
+ # three keys apply.
+ 'copy-offload-atomic' => { base => 1, current => 1, snap => 1 },
};
my ($vtype, $name, $vmid, $basename, $basevmid, $isBase) = $class->parse_volname($volname);
@@ -520,4 +545,179 @@ sub rename_snapshot {
die "rename_snapshot is not supported for $class";
}
+# ---- storage-offloaded full copy via thin snapshot --------------------------------
+#
+# 'lvcreate -s' on a thin LV is instant, allocates no data blocks, and, unlike a ZFS
+# clone, does not pin its origin: the thin pool reference counts blocks, so the origin
+# can be removed while the copy lives on. That is the note at the top of this file, and
+# it is what 'copy-offload-atomic' requires, so there is no background work and
+# copy_image_status() is complete on the first poll.
+#
+# This is the same primitive clone_image() already uses for linked clones. The
+# difference is in what PVE records afterwards: a linked clone carries a dependency it
+# must respect, while this path can hand back a volume with no recorded parent,
+# because thin snapshots have none.
+
+my sub thin_lv_exists {
+ my ($vg, $lv) = @_;
+ my $lvs = PVE::Storage::LVMPlugin::lvm_list_volumes($vg);
+ return defined($lvs->{$vg}) && defined($lvs->{$vg}->{$lv});
+}
+
+sub copy_image_check {
+ my ($class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts) = @_;
+
+ my $format = $opts->{format} // 'raw';
+ return "cannot produce format '$format'" if $format ne 'raw';
+ my ($vtype) = $class->parse_volname($volname);
+ return "only VM disks can be offloaded, not '$vtype'"
+ if !PVE::Storage::Common::vtype_matches($vtype, 'vm-vol');
+
+ # A thin snapshot shares blocks with its origin inside one pool, so it cannot leave
+ # that pool. Copying to another VG or another thinpool is a real data move and has
+ # to take the normal host-side path.
+ return "source and target are in different volume groups"
+ if ($target_scfg->{vgname} // '') ne $scfg->{vgname};
+ return "source and target are in different thin pools"
+ if ($target_scfg->{thinpool} // '') ne ($scfg->{thinpool} // '');
+
+ return undef;
+}
+
+sub copy_image_prepare {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_vmid, $snap, $opts,
+ ) = @_;
+
+ my $reason = $class->copy_image_check(
+ $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts,
+ );
+ die "cannot offload copy of '$volname': $reason\n" if defined($reason);
+
+ my $vg = $scfg->{vgname};
+
+ my $src_lv = defined($snap) ? "snap_${volname}_$snap" : $volname;
+ die "cannot copy '$volname': source volume '$src_lv' does not exist\n"
+ if !thin_lv_exists($vg, $src_lv);
+
+ my $name = $class->find_free_diskname($target_storeid, $target_scfg, $target_vmid);
+
+ # Reap a placeholder left by an earlier copy that died between start() and
+ # status(). 'lvrename' below refuses to park onto an existing name, so without
+ # this every future offloaded copy to this name fails. Doing it here is safe: we
+ # hold the target storage lock, are outside any freeze, and the name is ours,
+ # since find_free_diskname() just handed it out.
+ my $stale = parked_name($name);
+ if (thin_lv_exists($vg, $stale)) {
+ warn "removing stale copy placeholder '$vg/$stale'\n";
+ run_command(
+ ['/sbin/lvremove', '-f', "$vg/$stale"],
+ errmsg => "lvremove stale placeholder '$vg/$stale' error",
+ );
+ }
+
+ # Create the target, do not just pick a name. The caller runs this under the
+ # target storage lock and releases it before copy_image_start(), so a name that was
+ # only chosen could be taken by a concurrent allocation in between, and the
+ # caller's rollback would then free a volume belonging to that other operation.
+ #
+ # A thin LV is virtual, so this placeholder allocates no data blocks whatever size
+ # it claims; 1k is the smallest lvcreate accepts and rounds up.
+ my $cmd = [
+ '/sbin/lvcreate', '-aly', '-V', '1k', '--name', $name,
+ '--thinpool', "$vg/$scfg->{thinpool}",
+ ];
+ run_command($cmd, errmsg => "lvcreate placeholder '$vg/$name' error");
+ $set_lv_autoactivation->($vg, $name, 0);
+
+ return $name;
+}
+
+sub copy_image_start {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_volname, $snap,
+ ) = @_;
+
+ my $vg = $scfg->{vgname};
+
+ # Snapshot the source the caller asked for. Falling back to the current LV when a
+ # snapshot was requested would copy live data instead.
+ my $src_lv = defined($snap) ? "snap_${volname}_$snap" : $volname;
+
+ # copy_image_prepare() reserved the name with a placeholder, and 'lvcreate -s'
+ # cannot write into a name that already exists. Rename the placeholder aside rather
+ # than removing it, so the reserved name is never momentarily free for a concurrent
+ # find_free_diskname() to hand out.
+ my $parked = parked_name($target_volname);
+ run_command(
+ ['/sbin/lvrename', $vg, $target_volname, $parked],
+ errmsg => "lvrename placeholder '$vg/$target_volname' error",
+ );
+
+ eval {
+ # only the snapshot. It is what fixes the point in time; everything else this
+ # copy needs is done by copy_image_status(), outside the freeze.
+ my $cmd = ['/sbin/lvcreate', '-n', $target_volname, '-prw', '-kn', '-s', "$vg/$src_lv"];
+ run_command($cmd, errmsg => "thin snapshot of '$vg/$src_lv' error");
+ };
+ if (my $err = $@) {
+ # Put the reservation back so the caller's rollback still finds the volume it
+ # was given, and leave the source untouched. If that fails too, remove the
+ # parked LV rather than leaving an orphan: the rollback frees $target_volname,
+ # which by then names nothing, so nothing else would ever reap it.
+ eval {
+ run_command(
+ ['/sbin/lvrename', $vg, $parked, $target_volname],
+ errmsg => "restoring placeholder '$vg/$target_volname' error",
+ );
+ };
+ if (my $rerr = $@) {
+ eval { run_command(['/sbin/lvremove', '-f', "$vg/$parked"]) };
+ $err .= "additionally, could not restore the reserved name: $rerr";
+ $err .= "and '$vg/$parked' is left behind\n" if $@;
+ }
+ die $err;
+ }
+
+ # The parked placeholder is not removed here. This runs while the caller may
+ # hold a guest filesystem frozen, and every LVM command takes VG metadata locks
+ # that can queue behind other activity on the node; for a multi-disk VM those add
+ # up inside a single freeze. Only the snapshot above fixes the point in time;
+ # removal is cleanup, and copy_image_status() does it outside.
+ return;
+}
+
+sub copy_image_status {
+ my ($class, $scfg, $storeid, $volname, $source) = @_;
+
+ # $volname is the target. The thin snapshot is complete and independent the moment
+ # lvcreate returns, so there is nothing to poll and nothing of the source to
+ # release. What is left is dropping the placeholder copy_image_start() parked,
+ # which happens here to keep it out of the freeze window.
+ my $vg = $scfg->{vgname};
+
+ # Everything here is best effort, including the existence check. This runs in the
+ # caller's poll loop, and dying makes it free a copy that is already complete,
+ # correct and independent, just because a cleanup probe hit a transient LVM lock,
+ # the same contention this plugin works around elsewhere. The autoactivation flag
+ # is deferred to here for the same reason it is not done in start(): it is
+ # metadata housekeeping that takes the same VG lock.
+ eval {
+ my $parked = parked_name($volname);
+ if (thin_lv_exists($vg, $parked)) {
+ run_command(
+ ['/sbin/lvremove', '-f', "$vg/$parked"],
+ errmsg => "lvremove placeholder '$vg/$parked' error",
+ );
+ }
+ };
+ warn $@ if $@;
+
+ $set_lv_autoactivation->($vg, $volname, 0);
+
+ return { state => 'complete' };
+}
+
1;
diff --git a/src/test/copy_offload_check_test.pm b/src/test/copy_offload_check_test.pm
new file mode 100644
index 0000000..2fe54a4
--- /dev/null
+++ b/src/test/copy_offload_check_test.pm
@@ -0,0 +1,208 @@
+package PVE::Storage::TestCopyOffloadCheck;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use File::Path qw(make_path);
+use File::Temp qw(tempdir);
+use Test::MockModule;
+
+use PVE::Storage;
+use PVE::Storage::BTRFSPlugin;
+use PVE::Storage::DirPlugin;
+use PVE::Storage::LvmThinPlugin;
+use PVE::Storage::RBDPlugin;
+use Test::More;
+
+# copy_image_check() decides between offload and the host-side copy, so it must accept
+# what parse_volname() returns for a VM disk ('vm-vol' since API 17, not
+# 'images') and refuse, rather than fail later, a pair the backend cannot copy.
+
+my $lvm = { type => 'lvmthin', vgname => 'vg0', thinpool => 'tp' };
+my $rbd = { type => 'rbd', pool => 'rbd' };
+
+my @cases = (
+ # [ desc, class, scfg, volname, target_scfg, snap, opts, expect_ok, reason_re ]
+ ['lvmthin VM disk, same pool', 'PVE::Storage::LvmThinPlugin', $lvm, 'vm-100-disk-0',
+ { %$lvm }, undef, {}, 1],
+ ['lvmthin base, from a snapshot', 'PVE::Storage::LvmThinPlugin', $lvm, 'base-100-disk-0',
+ { %$lvm }, 'snap1', {}, 1],
+ ['lvmthin other VG', 'PVE::Storage::LvmThinPlugin', $lvm, 'vm-100-disk-0',
+ { %$lvm, vgname => 'vg1' }, undef, {}, 0, qr/different volume groups/],
+ ['lvmthin other thin pool', 'PVE::Storage::LvmThinPlugin', $lvm, 'vm-100-disk-0',
+ { %$lvm, thinpool => 'tp2' }, undef, {}, 0, qr/different thin pools/],
+ ['lvmthin qcow2 target', 'PVE::Storage::LvmThinPlugin', $lvm, 'vm-100-disk-0',
+ { %$lvm }, undef, { format => 'qcow2' }, 0, qr/format 'qcow2'/],
+ ['lvmthin VM state', 'PVE::Storage::LvmThinPlugin', $lvm, 'vm-100-state-s1',
+ { %$lvm }, undef, {}, 0, qr/not 'vm-state'/],
+ ['rbd VM disk, same cluster', 'PVE::Storage::RBDPlugin', $rbd, 'vm-100-disk-0',
+ { %$rbd, pool => 'other' }, undef, {}, 1],
+ ['rbd other cluster', 'PVE::Storage::RBDPlugin', $rbd, 'vm-100-disk-0',
+ { %$rbd, monhost => '10.0.0.1' }, undef, {}, 0, qr/different Ceph cluster/],
+ ['rbd qcow2 target', 'PVE::Storage::RBDPlugin', $rbd, 'vm-100-disk-0',
+ { %$rbd }, undef, { format => 'qcow2' }, 0, qr/format 'qcow2'/],
+ ['btrfs container volume', 'PVE::Storage::BTRFSPlugin', { type => 'btrfs', path => '/x' },
+ '100/subvol-100-disk-0.subvol', { type => 'btrfs', path => '/x' }, undef, {}, 0,
+ qr/not 'ct-vol'/],
+ ['btrfs qcow2', 'PVE::Storage::BTRFSPlugin', { type => 'btrfs', path => '/x' },
+ '100/vm-100-disk-0.qcow2', { type => 'btrfs', path => '/x' }, undef, {}, 0,
+ qr/format 'qcow2'/],
+);
+
+# The root cause the check guards against: in-tree plugins type VM disks as vm-vol.
+is((PVE::Storage::LvmThinPlugin->parse_volname('vm-100-disk-0'))[0], 'vm-vol',
+ 'lvmthin parses a VM disk as vm-vol');
+is((PVE::Storage::DirPlugin->parse_volname('100/vm-100-disk-0.raw'))[0], 'vm-vol',
+ 'dir parses a VM disk as vm-vol');
+
+# rbd's check asks the cluster: its fsid when the 'monhost' values differ, and whether the
+# Ceph user may add manager tasks (probed by cancelling a task that does not exist).
+# Scripted per monitor list and user here.
+my %fsid = (
+ '' => '11111111-1111-1111-1111-111111111111',
+ '10.0.0.1' => '22222222-2222-2222-2222-222222222222',
+ '10.0.0.9' => '11111111-1111-1111-1111-111111111111',
+);
+my $ceph_mock = Test::MockModule->new('PVE::CephConfig');
+$ceph_mock->redefine(ceph_connect_option => sub {
+ my ($scfg) = @_;
+ return { mon_host => $scfg->{monhost}, userid => $scfg->{username} // 'admin' };
+});
+my $rbd_mock = Test::MockModule->new('PVE::Storage::RBDPlugin');
+$rbd_mock->redefine(run_command => sub {
+ my ($cmd, %param) = @_;
+ my $op = join(' ', @$cmd);
+ my $out = $param{outfunc} // sub { };
+ if ($op =~ /\bfsid$/) {
+ my ($mon) = $op =~ /-m (\S+)/;
+ my $fsid = $fsid{ $mon // '' } // die "cannot connect\n";
+ $out->($fsid);
+ } elsif ($op =~ /\brbd task cancel\b/) {
+ my $errf = $param{errfunc} // sub { };
+ if ($op =~ /client\.nomgr\b/) {
+ $errf->('Error EACCES: access denied');
+ } elsif ($op =~ /client\.down\b/) {
+ die "command timed out\n";
+ } else {
+ $errf->('Error ENOENT: No such task 00000000-0000-0000-0000-000000000000');
+ }
+ die "command failed: exit code 2\n";
+ } else {
+ die "unexpected command '$op'\n";
+ }
+ return 0;
+});
+push @cases,
+ ['rbd other cluster, both external', 'PVE::Storage::RBDPlugin',
+ { %$rbd, monhost => '10.0.0.1' }, 'vm-100-disk-0', { %$rbd, monhost => '10.0.0.9' },
+ undef, {}, 0, qr/different Ceph cluster/],
+ ['rbd one cluster under two monitor lists', 'PVE::Storage::RBDPlugin', $rbd,
+ 'vm-100-disk-0', { %$rbd, monhost => '10.0.0.9' }, undef, {}, 1],
+ ['rbd different Ceph users', 'PVE::Storage::RBDPlugin', $rbd, 'vm-100-disk-0',
+ { %$rbd, username => 'other' }, undef, {}, 0, qr/different Ceph users/],
+ ['rbd user without manager write access', 'PVE::Storage::RBDPlugin',
+ { %$rbd, username => 'nomgr' }, 'vm-100-disk-0', { %$rbd, username => 'nomgr' },
+ undef, {}, 0, qr/may not add manager tasks/];
+
+for my $c (@cases) {
+ my ($desc, $class, $scfg, $volname, $tscfg, $snap, $opts, $ok, $re) = @$c;
+ my $reason = $class->copy_image_check($scfg, 'src', $volname, $tscfg, 'dst', $snap, $opts);
+ if ($ok) {
+ is($reason, undef, "$desc: accepted");
+ } else {
+ like($reason // '', $re, "$desc: refused");
+ }
+}
+
+# A probe that fails is a fault, not an answer: the check dies, and copy_offload_class()
+# falls back with a warning.
+for my $c (
+ ['cluster unreachable', { %$rbd, monhost => '10.0.0.7' }, $rbd],
+ ['manager unreachable', { %$rbd, username => 'down' }, { %$rbd, username => 'down' }],
+) {
+ my ($desc, $src, $dst) = @$c;
+ eval {
+ PVE::Storage::RBDPlugin->copy_image_check($src, 'src', 'vm-100-disk-0', $dst, 'dst',
+ undef, {});
+ };
+ ok($@, "rbd $desc: check dies");
+}
+
+# dir: on one filesystem a raw VM disk is advertised and accepted; a snapshot and a
+# format conversion are refused.
+{
+ my $base = tempdir(CLEANUP => 1);
+ make_path("$base/a/images/100", "$base/b");
+ open(my $fh, '>', "$base/a/images/100/vm-100-disk-0.raw") or die $!;
+ close($fh);
+ my $a = { type => 'dir', path => "$base/a" };
+ my $b = { type => 'dir', path => "$base/b" };
+ my $vol = '100/vm-100-disk-0.raw';
+
+ ok(PVE::Storage::DirPlugin->volume_has_feature($a, 'copy-offload-atomic', 'a', $vol,
+ undef, 0), 'dir raw VM disk is advertised');
+
+ # whether the test directory itself can reflink depends on the build host
+ my $probe = PVE::Storage::DirPlugin->reflink_unsupported($base);
+ ok(!defined($probe) || $probe =~ /does not support reflinks/,
+ 'dir reflink probe runs and cleans up') or diag($probe);
+ opendir(my $dh, $base) or die $!;
+ is(scalar(grep { /reflink-probe/ } readdir($dh)), 0, 'dir reflink probe left no files');
+
+ my $mock = Test::MockModule->new('PVE::Storage::DirPlugin');
+ $mock->redefine(reflink_unsupported => sub { "'$_[1]' does not support reflinks" });
+ like(PVE::Storage::DirPlugin->copy_image_check($a, 'a', $vol, $b, 'b', undef, {}) // '',
+ qr/does not support reflinks/, 'dir without reflink support: refused');
+ $mock->redefine(reflink_unsupported => sub { undef });
+
+ is(PVE::Storage::DirPlugin->copy_image_check($a, 'a', $vol, $b, 'b', undef, {}), undef,
+ 'dir same filesystem, target images dir not created yet: accepted');
+ like(PVE::Storage::DirPlugin->copy_image_check($a, 'a', $vol, $b, 'b', 's1', {}) // '',
+ qr/snapshot/, 'dir from a snapshot: refused');
+ like(PVE::Storage::DirPlugin->copy_image_check($a, 'a', $vol, $b, 'b', undef,
+ { format => 'qcow2' }) // '', qr/convert 'raw' to 'qcow2'/,
+ 'dir format conversion: refused');
+}
+
+# copy_offload_class() falls back (undef) instead of choosing offload for a pair the
+# plugin refuses, so the clone takes the host-side path rather than failing.
+{
+ my $cfg = { ids => {
+ src => { %$lvm, 'copy-offload' => 1 },
+ same => { %$lvm, 'copy-offload' => 1 },
+ other => { %$lvm, vgname => 'vg1', 'copy-offload' => 1 },
+ off => { %$lvm },
+ } };
+ my $out = '';
+ {
+ local *STDOUT;
+ open(STDOUT, '>', \$out) or die $!;
+ is(PVE::Storage::copy_offload_class($cfg, 'src:vm-100-disk-0', 'same', undef, 0),
+ 'atomic', 'same pool: offloaded');
+ is(PVE::Storage::copy_offload_class($cfg, 'src:vm-100-disk-0', 'other', undef, 0),
+ undef, 'other VG: host-side copy');
+ is(PVE::Storage::copy_offload_class($cfg, 'src:vm-100-disk-0', 'off', undef, 0),
+ undef, 'target without copy-offload: host-side copy');
+ }
+ like($out, qr/not offloading copy of 'src:vm-100-disk-0': source and target are in different volume groups/,
+ 'the fallback says why');
+
+ # a check that dies also falls back, with a warning
+ $cfg->{ids}->{rsrc} = { %$rbd, monhost => '10.0.0.7' };
+ $cfg->{ids}->{rdst} = { %$rbd, 'copy-offload' => 1 };
+ my $warned = '';
+ my $storage_mock = Test::MockModule->new('PVE::Storage');
+ $storage_mock->redefine(log_warn => sub { $warned .= $_[0] });
+ {
+ local *STDOUT;
+ open(STDOUT, '>', \my $ignored) or die $!;
+ is(PVE::Storage::copy_offload_class($cfg, 'rsrc:vm-100-disk-0', 'rdst', undef, 0),
+ undef, 'failed check: host-side copy');
+ }
+ like($warned, qr/copy-offload check for 'rsrc:vm-100-disk-0' failed, copying through the host/,
+ 'failed check: warns');
+}
+
+done_testing();
diff --git a/src/test/copy_offload_feature_test.pm b/src/test/copy_offload_feature_test.pm
new file mode 100644
index 0000000..0afa078
--- /dev/null
+++ b/src/test/copy_offload_feature_test.pm
@@ -0,0 +1,99 @@
+package PVE::Storage::TestCopyOffloadFeature;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+# PVE::Storage first: it registers the plugins in an order that resolves the
+# DirPlugin <-> Storage.pm circular load. Requiring BTRFSPlugin on its own fails.
+use PVE::Storage;
+use PVE::Storage::BTRFSPlugin;
+use PVE::Storage::LvmThinPlugin;
+use Test::More;
+
+# Which volumes a plugin advertises 'copy-offload-atomic' for. This is the gate the
+# whole path hangs off: advertising a volume the plugin cannot copy sends the clone
+# into copy_image_prepare() only to die there, and not advertising one it can copy
+# falls back to a full host-side byte copy. Neither failure is visible from a passing
+# clone, so the answers are pinned here.
+
+my $btrfs_scfg = { path => '/some/btrfs', type => 'btrfs' };
+my $lvmthin_scfg = { vgname => 'vg0', thinpool => 'tp', type => 'lvmthin' };
+
+my $tests = [
+ # [ description, class, scfg, volname, snapname, expected ]
+
+ # btrfs stores raw VM disks as subvolumes, which is what it can snapshot. A
+ # 'subvol' is a container volume, and qm never copies one.
+ [
+ 'btrfs raw is advertised',
+ 'PVE::Storage::BTRFSPlugin', $btrfs_scfg, '100/vm-100-disk-0.raw', undef, 1,
+ ],
+ [
+ 'btrfs subvol is NOT advertised',
+ 'PVE::Storage::BTRFSPlugin', $btrfs_scfg, '100/subvol-100-disk-0.subvol', undef, undef,
+ ],
+ [
+ 'btrfs raw is advertised from a snapshot too',
+ 'PVE::Storage::BTRFSPlugin', $btrfs_scfg, '100/vm-100-disk-0.raw', 'snap1', 1,
+ ],
+ # qcow2 and vmdk are plain files here, not subvolumes, so the subvolume-snapshot
+ # path does not apply to them.
+ [
+ 'btrfs qcow2 is NOT advertised',
+ 'PVE::Storage::BTRFSPlugin', $btrfs_scfg, '100/vm-100-disk-0.qcow2', undef, undef,
+ ],
+ [
+ 'btrfs vmdk is NOT advertised',
+ 'PVE::Storage::BTRFSPlugin', $btrfs_scfg, '100/vm-100-disk-0.vmdk', undef, undef,
+ ],
+
+ # lvmthin is raw-only, and a thin snapshot does not pin its origin, so every key
+ # qualifies.
+ [
+ 'lvmthin current is advertised',
+ 'PVE::Storage::LvmThinPlugin', $lvmthin_scfg, 'vm-100-disk-0', undef, 1,
+ ],
+ [
+ 'lvmthin base is advertised',
+ 'PVE::Storage::LvmThinPlugin', $lvmthin_scfg, 'base-100-disk-0', undef, 1,
+ ],
+ [
+ 'lvmthin snapshot is advertised',
+ 'PVE::Storage::LvmThinPlugin', $lvmthin_scfg, 'vm-100-disk-0', 'snap1', 1,
+ ],
+];
+
+plan tests => scalar($tests->@*) + 2;
+
+for my $t ($tests->@*) {
+ my ($desc, $class, $scfg, $volname, $snapname, $expected) = $t->@*;
+
+ my $got = $class->volume_has_feature(
+ $scfg, 'copy-offload-atomic', 'store', $volname, $snapname, 0,
+ );
+
+ if (defined($expected)) {
+ is($got, $expected, $desc);
+ } else {
+ ok(!$got, $desc);
+ }
+}
+
+# An unrelated feature must still come back from the normal table rather than being
+# swallowed by the copy-offload handling.
+ok(
+ PVE::Storage::BTRFSPlugin->volume_has_feature(
+ $btrfs_scfg, 'snapshot', 'store', '100/vm-100-disk-0.raw', undef, 0,
+ ),
+ 'btrfs still answers for unrelated features',
+);
+ok(
+ PVE::Storage::LvmThinPlugin->volume_has_feature(
+ $lvmthin_scfg, 'snapshot', 'store', 'vm-100-disk-0', undef, 0,
+ ),
+ 'lvmthin still answers for unrelated features',
+);
+
+done_testing();
diff --git a/src/test/copy_offload_functional_test.pl b/src/test/copy_offload_functional_test.pl
new file mode 100644
index 0000000..fd4498e
--- /dev/null
+++ b/src/test/copy_offload_functional_test.pl
@@ -0,0 +1,296 @@
+#!/usr/bin/perl
+
+# Functional tests for the copy-offload hooks of BTRFSPlugin and LvmThinPlugin.
+#
+# Unlike the rest of src/test, this one touches real storage: it builds a loop-backed
+# btrfs filesystem and a loop-backed LVM thin pool, drives copy_image_prepare/start/
+# status against them, and checks the resulting images byte for byte. That needs root
+# and the btrfs/lvm tools, so it is not part of run_plugin_tests.pl. Run it by hand:
+#
+# perl copy_offload_functional_test.pl
+#
+# It skips cleanly rather than failing when it cannot run. Everything it creates lives
+# under /tmp and on its own loop devices, and is torn down at exit even on failure; it
+# never touches an existing volume group or mount.
+#
+# What is checked, and why these and not others:
+#
+# - a copy taken from a snapshot returns the snapshot's content, not the live volume's.
+# Getting this wrong goes unnoticed: the clone is readable and passes every check, but
+# holds the wrong data.
+# - the copy survives deleting the source outright. That is what 'copy-offload-atomic'
+# promises and what separates these backends from a ZFS clone.
+# - two prepares for the same target VM return different names. The core prepares every
+# disk of a VM before starting any of them, so a reservation its own lister cannot see
+# makes every multi-disk clone fail.
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use File::Path qw(mkpath rmtree);
+use PVE::Storage;
+use PVE::Storage::BTRFSPlugin;
+use PVE::Storage::LvmThinPlugin;
+use PVE::Tools qw(run_command);
+use Test::More;
+
+my $BTRFS_MNT = '/tmp/pve-copyoffload-btrfs';
+my $BTRFS_IMG = '/tmp/pve-copyoffload-btrfs.img';
+my $LVM_IMG = '/tmp/pve-copyoffload-lvm.img';
+my $VG = 'pvecopyoffloadtest';
+
+my @cleanup;
+
+sub sh { return scalar(qx{$_[0] 2>/dev/null}) }
+
+sub cleanup_all {
+ for my $c (reverse @cleanup) { eval { $c->() }; }
+ @cleanup = ();
+}
+END { cleanup_all() }
+$SIG{INT} = $SIG{TERM} = sub { cleanup_all(); exit 1 };
+
+if ($> != 0) {
+ plan skip_all => 'needs root to create loop devices, filesystems and volume groups';
+}
+for my $tool (qw(btrfs mkfs.btrfs losetup findmnt lvcreate vgcreate pvcreate)) {
+ if (!sh("command -v $tool")) {
+ plan skip_all => "missing required tool '$tool'";
+ }
+}
+if (sh("vgs --noheadings -o vg_name 2>/dev/null") =~ /\b\Q$VG\E\b/) {
+ plan skip_all => "volume group '$VG' already exists - refusing to touch it";
+}
+
+plan tests => 22;
+
+# Hash the whole object, and let md5sum do its own reading.
+#
+# Not 'dd bs=1M count=N | md5sum': dd counts a short read as a full block,
+# so it can return less than asked for, and how much depends on whether the data came
+# from the page cache or off the disk. Comparing a freshly written source against a
+# cold copy that way reports a mismatch between two byte-identical files. It also hides
+# a missing file as the md5 of empty input.
+sub md5_of {
+ my ($path) = @_;
+
+ die "cannot hash '$path': not present\n" if !-e $path;
+ my $out = sh("md5sum '$path'");
+ $out =~ s/\s.*//s;
+ die "md5sum of '$path' produced nothing\n" if $out !~ /^[0-9a-f]{32}$/;
+ return $out;
+}
+
+sub identical {
+ my ($a, $b) = @_;
+ return system('cmp', '-s', $a, $b) == 0;
+}
+
+# ---------------------------------------------------------------- btrfs
+
+my $btrfs_ok = eval {
+ run_command(['truncate', '-s', '2G', $BTRFS_IMG]);
+ push @cleanup, sub { unlink $BTRFS_IMG };
+
+ my $loop = sh("losetup --find --show $BTRFS_IMG");
+ chomp $loop;
+ die "no loop device\n" if !$loop;
+ push @cleanup, sub { sh("losetup -d $loop") };
+
+ run_command(['mkfs.btrfs', '-q', '-f', $loop]);
+ mkpath $BTRFS_MNT;
+ run_command(['mount', $loop, $BTRFS_MNT]);
+ push @cleanup, sub {
+ for my $s (reverse split /\n/, sh("btrfs subvolume list -o $BTRFS_MNT | awk '{print \$NF}'")) {
+ sh("btrfs -q subvolume delete '$BTRFS_MNT/$s'");
+ }
+ sh("umount $BTRFS_MNT");
+ rmtree $BTRFS_MNT;
+ };
+ mkpath "$BTRFS_MNT/images";
+ 1;
+};
+if (!$btrfs_ok) {
+ diag("btrfs setup failed: $@");
+ SKIP: { skip 'btrfs setup failed', 11 }
+} else {
+ my $C = 'PVE::Storage::BTRFSPlugin';
+ my $scfg = { path => $BTRFS_MNT, type => 'btrfs', content => { images => 1 } };
+
+ my $src = $C->alloc_image('bt', $scfg, 100, 'raw', undef, 64 * 1024);
+ my $srcpath = $C->filesystem_path($scfg, $src);
+ sh("dd if=/dev/urandom of=$srcpath bs=1M count=16 conv=notrunc,fsync status=none");
+
+ $C->volume_snapshot($scfg, 'bt', $src, 'snap1');
+ my $snappath = $C->filesystem_path($scfg, $src, 'snap1');
+ sh("dd if=/dev/urandom of=$srcpath bs=1M count=16 conv=notrunc,fsync status=none");
+ ok(!identical($srcpath, $snappath), 'btrfs: source diverged from its snapshot');
+
+ # The multi-disk case: the core prepares every disk before starting any of them.
+ my $a = $C->copy_image_prepare($scfg, 'bt', $src, $scfg, 'bt', 201, undef, {});
+ my $b = $C->copy_image_prepare($scfg, 'bt', $src, $scfg, 'bt', 201, undef, {});
+ isnt($a, $b, 'btrfs: two prepares for one target VM reserve different names');
+
+ $C->copy_image_start($scfg, 'bt', $src, $scfg, 'bt', $a, undef);
+
+ # After start() but before status() cleans up, the reserved name must still be held.
+ # start() swaps the copy in with RENAME_EXCHANGE so the name is never momentarily
+ # free; a plain park-then-rename loses the reservation here, and a concurrent
+ # allocation could then take the name out from under the caller's rollback. Hence
+ # the check between the two calls.
+ my ($a_name) = $a =~ m{/(.*)$};
+ isnt(
+ $C->find_free_diskname('bt', $scfg, 201, 'raw', 1), $a_name,
+ 'btrfs: the reserved name is still held across the swap',
+ );
+
+ my $st = $C->copy_image_status($scfg, 'bt', $a, undef);
+ is($st->{state}, 'complete', 'btrfs: status complete on the first poll');
+ my $apath = $C->filesystem_path($scfg, $a);
+ ok(identical($apath, $srcpath), 'btrfs: copy matches the source');
+
+ my $snapcopy = $C->copy_image_prepare($scfg, 'bt', $src, $scfg, 'bt', 202, 'snap1', {});
+ $C->copy_image_start($scfg, 'bt', $src, $scfg, 'bt', $snapcopy, 'snap1');
+ $C->copy_image_status($scfg, 'bt', $snapcopy, undef);
+ # NB: assign filesystem_path() to a scalar first. It returns ($path, $vmid, $vtype)
+ # in list context, and sub arguments are list context, so passing the call directly
+ # would hand identical() the vmid as its second path.
+ my $snapcopy_path = $C->filesystem_path($scfg, $snapcopy);
+ ok(
+ identical($snapcopy_path, $snappath),
+ 'btrfs: a copy from a snapshot holds the SNAPSHOT content, not live data',
+ );
+
+ # Independence: hash the copy, destroy the source outright, hash again.
+ my $before = md5_of($apath);
+ $C->free_image('bt', $scfg, $src, 0);
+ ok(!-e $srcpath, 'btrfs: source really is gone');
+ is($before, md5_of($apath), 'btrfs: copy is unaffected by deleting the source');
+ unlike(
+ sh("find $BTRFS_MNT -maxdepth 4 -name '*.copytmp' -o -name '*.copynew'"), qr/\S/,
+ 'btrfs: no parked or staging placeholder left behind',
+ );
+
+ # Failure path, same as the lvmthin case: a placeholder left by a copy that died
+ # between start() and status() must not wedge the name, since rename() refuses to
+ # park onto an existing path and the leftover is invisible to list_images().
+ my $stale = $C->copy_image_prepare($scfg, 'bt', $a, $scfg, 'bt', 203, undef, {});
+ my $stale_subvol = $C->filesystem_path($scfg, $stale);
+ $stale_subvol =~ s|/disk\.raw$||;
+ rename($stale_subvol, "$stale_subvol.copytmp")
+ or die "could not stage the leaked-placeholder case - $!\n";
+ my $reused = eval { $C->copy_image_prepare($scfg, 'bt', $a, $scfg, 'bt', 203, undef, {}) };
+ ok(defined($reused), 'btrfs: a leaked placeholder does not wedge the disk name')
+ or diag("prepare failed: $@");
+ if (defined($reused)) {
+ $C->copy_image_start($scfg, 'bt', $a, $scfg, 'bt', $reused, undef);
+ $C->copy_image_status($scfg, 'bt', $reused, undef);
+ my $reused_path = $C->filesystem_path($scfg, $reused);
+ ok(identical($reused_path, $apath), 'btrfs: the retried copy is correct');
+ } else {
+ ok(0, 'btrfs: the retried copy is correct');
+ }
+
+ # Rollback between start() and status(): the caller frees the target, and the parked
+ # placeholder has to go with it, since nothing else ever sees it.
+ my $rb = $C->copy_image_prepare($scfg, 'bt', $a, $scfg, 'bt', 204, undef, {});
+ $C->copy_image_start($scfg, 'bt', $a, $scfg, 'bt', $rb, undef);
+ $C->free_image('bt', $scfg, $rb, 0);
+ unlike(
+ sh("find $BTRFS_MNT/images -maxdepth 2 -name 'vm-204-*'"), qr/\S/,
+ 'btrfs: freeing a started copy removes its parked placeholder too',
+ );
+}
+
+# ---------------------------------------------------------------- lvmthin
+
+my $lvm_ok = eval {
+ run_command(['truncate', '-s', '3G', $LVM_IMG]);
+ push @cleanup, sub { unlink $LVM_IMG };
+
+ my $loop = sh("losetup --find --show $LVM_IMG");
+ chomp $loop;
+ die "no loop device\n" if !$loop;
+ # Detach as its own entry, registered right away. Folding it into the entry pushed
+ # after vgcreate would leak the loop device whenever pvcreate or vgcreate fails:
+ # the eval catches that, the test skips "cleanly", and the device stays attached.
+ push @cleanup, sub { sh("losetup -d $loop") };
+
+ run_command(['pvcreate', '-qq', '-f', $loop]);
+ run_command(['vgcreate', '-qq', $VG, $loop]);
+ push @cleanup, sub { sh("vgremove -qq -f $VG"); sh("pvremove -qq -f $loop") };
+
+ run_command(['lvcreate', '-qq', '--type', 'thin-pool', '-L', '2G', '-n', 'tp', $VG]);
+ 1;
+};
+if (!$lvm_ok) {
+ diag("lvm setup failed: $@");
+ SKIP: { skip 'lvm setup failed', 10 }
+} else {
+ my $C = 'PVE::Storage::LvmThinPlugin';
+ my $scfg = { vgname => $VG, thinpool => 'tp', type => 'lvmthin', content => { images => 1 } };
+ my $act = sub { sh("lvchange -ay -K $VG/$_[0]") };
+
+ my $src = $C->alloc_image('lt', $scfg, 100, 'raw', undef, 64 * 1024);
+ $act->($src);
+ sh("dd if=/dev/urandom of=/dev/$VG/$src bs=1M count=8 conv=fsync status=none");
+
+ $C->volume_snapshot($scfg, 'lt', $src, 'snap1');
+ my $snapdev = "/dev/$VG/snap_${src}_snap1";
+ $act->("snap_${src}_snap1");
+ sh("dd if=/dev/urandom of=/dev/$VG/$src bs=1M count=8 conv=fsync status=none");
+ ok(!identical("/dev/$VG/$src", $snapdev), 'lvmthin: source diverged from its snapshot');
+
+ my $a = $C->copy_image_prepare($scfg, 'lt', $src, $scfg, 'lt', 201, undef, {});
+ my $b = $C->copy_image_prepare($scfg, 'lt', $src, $scfg, 'lt', 201, undef, {});
+ isnt($a, $b, 'lvmthin: two prepares for one target VM reserve different names');
+
+ $C->copy_image_start($scfg, 'lt', $src, $scfg, 'lt', $a, undef);
+ my $st = $C->copy_image_status($scfg, 'lt', $a, undef);
+ is($st->{state}, 'complete', 'lvmthin: status complete on the first poll');
+ $act->($a);
+ ok(identical("/dev/$VG/$a", "/dev/$VG/$src"), 'lvmthin: copy matches the source');
+
+ my $snapcopy = $C->copy_image_prepare($scfg, 'lt', $src, $scfg, 'lt', 202, 'snap1', {});
+ $C->copy_image_start($scfg, 'lt', $src, $scfg, 'lt', $snapcopy, 'snap1');
+ $C->copy_image_status($scfg, 'lt', $snapcopy, undef);
+ $act->($snapcopy);
+ ok(
+ identical("/dev/$VG/$snapcopy", $snapdev),
+ 'lvmthin: a copy from a snapshot holds the SNAPSHOT content, not live data',
+ );
+
+ # Independence: hash the copy, destroy the source outright, hash again.
+ my $before = md5_of("/dev/$VG/$a");
+ $C->volume_snapshot_delete($scfg, 'lt', $src, 'snap1');
+ $C->free_image('lt', $scfg, $src, 0);
+ ok(!-e "/dev/$VG/$src", 'lvmthin: source really is gone');
+ is($before, md5_of("/dev/$VG/$a"), 'lvmthin: copy is unaffected by deleting the source');
+
+ unlike(
+ sh("lvs --noheadings -o lv_name $VG"), qr/copytmp-/,
+ 'lvmthin: no parked placeholder left behind',
+ );
+
+ # Failure path: a placeholder left by an earlier copy that died between start() and
+ # status() must not wedge the name. Without the reaping in prepare(), 'lvrename'
+ # cannot park onto the existing name and every later copy to it fails, and the
+ # leftover is invisible to list_images(), so nothing would point at the cause.
+ my $stale = $C->copy_image_prepare($scfg, 'lt', $a, $scfg, 'lt', 203, undef, {});
+ sh("lvrename $VG $stale copytmp-$stale");
+ my $reused = eval { $C->copy_image_prepare($scfg, 'lt', $a, $scfg, 'lt', 203, undef, {}) };
+ ok(defined($reused), 'lvmthin: a leaked placeholder does not wedge the disk name')
+ or diag("prepare failed: $@");
+ if (defined($reused)) {
+ $C->copy_image_start($scfg, 'lt', $a, $scfg, 'lt', $reused, undef);
+ $C->copy_image_status($scfg, 'lt', $reused, undef);
+ $act->($reused);
+ ok(identical("/dev/$VG/$reused", "/dev/$VG/$a"), 'lvmthin: the retried copy is correct');
+ } else {
+ ok(0, 'lvmthin: the retried copy is correct');
+ }
+}
+
+cleanup_all();
diff --git a/src/test/run_plugin_tests.pl b/src/test/run_plugin_tests.pl
index c8db425..fff5b75 100755
--- a/src/test/run_plugin_tests.pl
+++ b/src/test/run_plugin_tests.pl
@@ -27,6 +27,8 @@ my $res = $harness->runtests(
"plugin_properties_test.pm",
"copy_offload_test.pm",
"copy_offload_naming_test.pm",
+ "copy_offload_feature_test.pm",
+ "copy_offload_check_test.pm",
"copy_offload_rbd_status_test.pm",
);
--
2.55.0
next prev parent reply other threads:[~2026-11-26 16:58 UTC|newest]
Thread overview: 7+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-26 16:56 [RFC PATCH storage/qemu-server/docs v2 0/6] offload full clone to the storage backend Ciro Iriarte
2026-11-26 16:56 ` [RFC PATCH storage v2 1/6] storage: add asynchronous copy-offload hook for full copies Ciro Iriarte
2026-11-26 16:56 ` [RFC PATCH storage v2 2/6] rbd: implement copy-offload via snapshot + clone + flatten Ciro Iriarte
2026-11-26 16:57 ` [RFC PATCH storage v2 3/6] dir: implement copy-offload via reflink (FICLONE) Ciro Iriarte
2026-11-26 16:57 ` Ciro Iriarte [this message]
2026-11-26 16:57 ` [RFC PATCH qemu-server v2 5/6] use storage copy-offload for full clone Ciro Iriarte
2026-11-26 16:57 ` [RFC PATCH docs v2 6/6] pvesm: document copy-offload and add it to the storage capability table Ciro Iriarte
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=20261126.4.copyoffload-v2@cyruspy.gmail.com \
--to=cyruspy@gmail.com \
--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.