* [RFC PATCH storage/qemu-server/docs v2 0/6] offload full clone to the storage backend
@ 2026-11-26 16:56 Ciro Iriarte
2026-11-26 16:56 ` [RFC PATCH storage v2 1/6] storage: add asynchronous copy-offload hook for full copies Ciro Iriarte
` (5 more replies)
0 siblings, 6 replies; 7+ messages in thread
From: Ciro Iriarte @ 2026-11-26 16:56 UTC (permalink / raw)
To: pve-devel
This series lets a storage plugin perform a full copy on its backend
instead of having the host read and write every byte with qemu-img or
drive-mirror. The consumer is full clone (bug #7780). v1 is at
https://lore.proxmox.com/pve-devel/20260720.0.copyoffload@cyruspy.gmail.com/
Recap
-----
A plugin advertises one of two features, copy-offload-atomic (the copy
captures a single point in time) or copy-offload-bulk (it does not), and
implements four methods:
copy_image_check() can this volume go to that target storage?
copy_image_prepare() reserve the target name, under the storage lock
copy_image_start() capture the instant; may run in a guest freeze
copy_image_status() poll until the copy is independent of its source
The split exists because a backend copy can run for hours while the
storage lock is a pmxcfs lock with a 60 second limit, and because only a
cheap call can run while a guest is frozen. 'complete' means
independent, not just readable: an RBD clone reads fine before it is
flattened, but deleting the source would destroy it.
For a running guest, qemu-server reserves every offloaded target first
and starts the copies inside the same freeze that cuts the mirrored
disks over, so all disks of the clone are captured at the same instant.
copy_images_start() passes a VM's starts to the plugin as one batch per
source/target storage pair, for backends that can capture several
volumes together.
Offload is off by default, enabled per target storage with the
copy-offload option, and only works between two storages of the same
type. The series implements it for rbd, dir (reflink), btrfs and
lvmthin.
Changes since v1
----------------
Mostly fixes from re-reviewing v1 after the rebase onto storage API 17.
Each patch lists its own changes; the main ones:
* API 17 changed parse_volname() to return 'vm-vol' instead of 'images'.
The dir, btrfs and lvmthin code compared against 'images', so after
the rebase, dir never advertised offload and btrfs and lvmthin refused
every volume in prepare. They now use vtype_matches(), and a new test
goes through the real parse_volname().
* New copy_image_check(). In v1, a pair the backend could not copy (a
different thin pool, another filesystem, a filesystem without reflink,
different Ceph monitors) made prepare die and the clone fail. The core
now checks first and falls back to the host-side copy, logging the
reason.
* qemu-server no longer uses a goto, which master had just removed.
Deferred copies record the source size in the config instead of the
placeholder's. Cutting over a final cloud-init drive starts them too,
whereas v1 froze the guest a second time. A copy from a snapshot is
not deferred. A failed guest agent freeze falls back to suspending the
guest; if that fails too, the mirrors are still cut over, as on
master, but the deferred copies are not started and the clone fails,
because their targets are only reservations. A guest that is already
paused stays paused, and a failed thaw or resume ends the task with a
warning (log_warn) instead of a plain message.
* rbd: the 'ceph rbd task' calls use the storage's connection options
and namespace, free_image() cancels a running flatten, and values read
back from rbd are untainted for pvedaemon's -T. The check falls back
when the target is on another Ceph cluster (same monhost, or else same
fsid), when the two storages use different Ceph users, and when the
user is not allowed to add manager tasks, which the flatten needs.
Each command in start has a 30 second timeout, so a hung cluster fails
the start within a bounded time instead of holding the guest frozen
indefinitely. The flatten status fix sent after v1 is folded in.
* A failed copy's target is freed in one place only. v1 freed it in
vdisk_copy_wait() and again in the caller's rollback, which could
remove a volume another task had allocated under the same name in
between. dir now keeps the name reserved after a failed start, and
btrfs free_image() removes a parked placeholder.
* The docs patch, sent separately, is now 6/6.
APIVER goes 17 -> 18 and APIAGE 8 -> 9. The base plugin declares
'copy-offload' and 'copy-offload-timeout', so under the v17 rules they
become common properties. That fits the criterion as I read it, since
core code reads them from any storage type, but it means a third-party
plugin declaring either name would stop loading. I found none.
No range-diff: the rebase onto API 17 and the clone_disk() restructuring
make it longer than the patches themselves.
qemu-server 5/6 needs a libpve-storage-perl that ships APIVER 18 (1/6);
I left the debian/control bump to you. The patches apply in order:
storage, then qemu-server, then docs.
Not covered: the edit dialogs of the in-tree storages in pve-manager are
hand-written, so copy-offload can only be set with pvesm or the API for
now. The clone bandwidth limit does not apply to an offloaded copy,
since the data does not pass through the host; the docs say so.
Open questions
--------------
1. move_disk. It already goes through clone_disk(), so moving a disk of
a stopped guest, or a detached disk, is offloaded. Moving an attached
disk of a running guest would need the bulk path, since the source
changes during the copy. Same series or later?
2. prepare() returns a volname, and a failed copy's rollback frees that
volname. The caller drops the lock between prepare and start, so each
backend has to keep the name reserved itself (btrfs swaps with
renameat2(RENAME_EXCHANGE), rbd and lvmthin park under a prefix the
lister ignores but the allocator counts). An opaque token that the
rollback verifies would move that guarantee into the core. Is that
worth an interface change now?
3. copy_offload_class() tries atomic before bulk and stops at the first
refusal. copy_image_check() does not get the class, so falling
through to bulk would require passing it in. No plugin here
advertises both; is that worth doing now?
4. run_with_guest_quiesced() changes what every full clone of a running
guest does, offloaded or not, compared with master's monitor(): a
failed guest agent freeze falls back to suspending the guest instead
of continuing unquiesced; a guest that was already paused is no
longer resumed afterwards; and a failed thaw or resume is reported
with log_warn(), so the task ends with a warning. I chose a warning
over failing the task because failing it deletes a finished clone,
and on Windows the agent's freeze is limited to about ten seconds,
after which the thaw itself reports an error; in that case the disks
may not be captured at the same instant, and the warning is the only
sign of it. Are these acceptable for all clones, or should they be
limited to clones with deferred copies?
5. copy_image_start() runs while the guest is frozen. The plugin
contract asks it to put a timeout on calls that can block on a remote
backend; rbd does, per command, while dir, btrfs and lvmthin run
local reflink, snapshot and LVM operations without one (a reflink of
a heavily fragmented file on XFS can take seconds). The core sets no
overall deadline. Given the ten second freeze limit on Windows,
should it?
6. Only the target storage's copy-offload option is consulted, as the
new volume lands there. Should the source storage be able to refuse
as well?
rbd requests clone format 2 explicitly. It worked on the test cluster,
whose require-min-compat-client is luminous; a cluster older than Mimic
was not tested.
Testing
-------
On a PVE 9.3 node (libpve-storage-perl 9.1.26, qemu-server 9.2.24,
matching the bases of this series):
* pve-storage 'make check', minus the four targets that create real
devices: all 24 targets pass, as on master. run_plugin_tests.pl runs
902 tests, all pass.
* copy_offload_functional_test.pl as root, on a loop-backed btrfs and
thin pool: 22/22. Without the vtype_matches() change it fails at the
first prepare.
* qemu-server 'make test' passes, including the new
run_guest_quiesce_tests.pl.
* Full clones of running VMs onto Ceph RBD (Tentacle, erasure coded
pool), with the patched code loaded for the qm process only: an
offloaded disk plus a mirrored one plus a final cloud-init drive; a
mirrored disk followed by an offloaded one; two offloaded disks; and
an offloaded disk of a paused guest, which stayed paused. The guests
had no agent, so this used the suspend path. In every case the RBD
snapshot was taken while the guest was quiesced, each clone was
byte-identical to its source and had no parent, the config recorded
the right size, and no snapshot was left on the source.
Not repeated from v1: the reflink runs on XFS and ZFS, and the guest
agent freeze path. The dir, btrfs and lvmthin paths were exercised by
the functional test, not through a live clone.
Ciro Iriarte (6):
storage: add asynchronous copy-offload hook for full copies
rbd: implement copy-offload via snapshot + clone + flatten
dir: implement copy-offload via reflink (FICLONE)
btrfs, lvmthin: implement copy-offload (atomic class)
use storage copy-offload for full clone
pvesm: document copy-offload and add it to the storage capability table
storage:
ApiChangeLog | 38 ++
src/PVE/Storage.pm | 268 ++++++++++-
src/PVE/Storage/BTRFSPlugin.pm | 267 +++++++++++
src/PVE/Storage/DirPlugin.pm | 193 ++++++++
src/PVE/Storage/LvmThinPlugin.pm | 202 ++++++++-
src/PVE/Storage/Plugin.pm | 180 ++++++++
src/PVE/Storage/RBDPlugin.pm | 551 ++++++++++++++++++++++-
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/copy_offload_naming_test.pm | 82 ++++
src/test/copy_offload_rbd_status_test.pm | 114 +++++
src/test/copy_offload_test.pm | 90 ++++
src/test/plugin_properties_test.pm | 5 +-
src/test/run_plugin_tests.pl | 5 +
15 files changed, 2588 insertions(+), 10 deletions(-)
qemu-server:
src/PVE/API2/Qemu.pm | 17 +++
src/PVE/QemuServer.pm | 225 ++++++++++++++++++++++++++--
src/PVE/QemuServer/BlockJob.pm | 119 +++++++++++----
src/test/Makefile | 5 +-
src/test/run_guest_quiesce_tests.pl | 154 +++++++++++++++++++
5 files changed, 479 insertions(+), 41 deletions(-)
docs:
pvesm.adoc | 79 ++++++++++++++++++++++++++++++++++++++++++------------
1 file changed, 62 insertions(+), 17 deletions(-)
--
Ciro Iriarte
^ permalink raw reply [flat|nested] 7+ messages in thread
* [RFC PATCH storage v2 1/6] storage: add asynchronous copy-offload hook for full copies
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 ` Ciro Iriarte
2026-11-26 16:56 ` [RFC PATCH storage v2 2/6] rbd: implement copy-offload via snapshot + clone + flatten Ciro Iriarte
` (4 subsequent siblings)
5 siblings, 0 replies; 7+ messages in thread
From: Ciro Iriarte @ 2026-11-26 16:56 UTC (permalink / raw)
To: pve-devel
From: Ciro Iriarte <ciro.iriarte+software@gmail.com>
Let a plugin perform a full copy, for example a full clone, on the
storage backend instead of reading and writing the data through the host
with qemu-img. See bug #7780.
The hook has three phases:
copy_image_prepare() reserve the target under the storage lock
copy_image_start() capture the instant inside a guest freeze
copy_image_status() poll until independent outside both
It cannot be synchronous: for shared storage the core calls into the
plugin under a pmxcfs lock that kills the locked code after 60 seconds,
while a backend copy can run for hours. Allocation cannot happen inside
a guest freeze either, so only the start, a single cheap backend call,
runs while the guest is frozen.
'complete' means independent of the source, not merely readable. An RBD
clone is readable immediately but depends on its parent snapshot until
the flatten finishes; reporting completion early would let the caller
delete the source out from under it.
copy_image_check() reports whether the backend can copy a volume to a
given target storage, returning undef or a reason. The core calls it
before choosing offload, so a pair the backend cannot copy (another
pool, another filesystem, a format it cannot produce) takes the
host-side path instead of failing. Plugins repeat its probe-free checks
in prepare, which runs under the storage lock, so the two cannot
disagree. A check that dies is treated as a fault rather than a refusal:
the clone still falls back, but logs a warning, so the task shows it.
copy_image_start() receives the source snapshot, since it is the call
that captures the point in time. Because it runs while the guest is
frozen, the contract asks plugins to put a timeout on calls that can
block on a remote backend and to leave any cleanup that does not undo
the start to free_image().
copy_image_status() receives what the copy was made from, so a plugin
can clean up state it left on the source once the target is independent.
copy_images_start() starts a batch between one pair of storages. Its
default starts them one by one, so there is no capability to negotiate;
a backend that can capture several volumes at the same instant overrides
it. All starts of a batch happen inside one guest freeze.
The two capability classes, copy-offload-atomic and copy-offload-bulk,
are separate features rather than one feature with an argument, so
volume_has_feature() keeps its interface. Offload is enabled per storage
with 'copy-offload' and only between instances of the same plugin type,
as the operation is opaque to PVE. vdisk_copy_wait() gives up after
'copy-offload-timeout' seconds without progress, so a dead backend copy
fails instead of hanging the worker. It polls every second at first and
backs off to every ten seconds. It leaves a failed target to the caller,
which owns it from prepare onwards: freeing it in two places would leave
a window in which another allocation takes the name and the second free
removes that volume. vdisk_copy() frees the target itself, since its
caller only gets the volume on success.
APIVER 17 -> 18 and APIAGE 8 -> 9, keeping the oldest accepted plugin
API at 9: the new methods are optional. The base plugin declares the two
options, so under the v17 rules they become common properties; the
ApiChangeLog notes this and plugin_properties_test.pm lists them.
Signed-off-by: Ciro Iriarte <ciro.iriarte+software@gmail.com>
---
Changes in v2:
* rebased onto current master
* APIVER 17 -> 18, APIAGE 8 -> 9 (v1: 15 -> 16, 6 -> 7)
* new copy_image_check(): the core asks the plugin before choosing
offload, and a pair it refuses takes the host-side path. In v1,
prepare() died instead and the whole clone failed.
* copy_offload_class() takes the target format, for that check
* a failed copy's target is freed by one owner only: vdisk_copy_wait()
leaves it to the caller, which already holds it
* a check that dies falls back with log_warn() instead of silently,
so the task ends with a warning
* the start contract asks plugins to put a timeout on calls that can
block on a remote backend, as the start runs inside a guest freeze
* vdisk_copy_wait() backs off from polling every second to every ten
seconds
* the two options become common properties under the v17 rules; the
ApiChangeLog says so, plugin_properties_test.pm lists them, and they
have titles for the generated web UI dialog
ApiChangeLog | 38 ++++
src/PVE/Storage.pm | 268 ++++++++++++++++++++++++++++-
src/PVE/Storage/Plugin.pm | 180 +++++++++++++++++++
src/test/copy_offload_test.pm | 90 ++++++++++
src/test/plugin_properties_test.pm | 5 +-
src/test/run_plugin_tests.pl | 1 +
6 files changed, 579 insertions(+), 3 deletions(-)
create mode 100644 src/test/copy_offload_test.pm
diff --git a/ApiChangeLog b/ApiChangeLog
index b7e7442..e452fab 100644
--- a/ApiChangeLog
+++ b/ApiChangeLog
@@ -6,6 +6,44 @@ without breaking anything unaware of it.)
Future changes should be documented in here.
+## Version 18:
+
+* Add optional `copy_image_check()`, `copy_image_prepare()`, `copy_image_start()`,
+ `copy_image_status()` and `copy_images_start()` plugin methods, plus a `copy-offload` storage
+ option
+
+ These let a plugin perform a full copy (e.g. a full clone) on the storage backend instead of
+ reading and writing the data through the host. They are optional: the base prepare, start and
+ status implementations die, and are only reached if a plugin advertises one of the new
+ `copy-offload-atomic` or `copy-offload-bulk` features from `volume_has_feature()`, so existing
+ plugins are unaffected.
+
+ The copy is asynchronous. `copy_image_prepare()` allocates the target and returns its volname,
+ `copy_image_start()` captures the copy's point in time and begins it, and `copy_image_status()`
+ is polled until the target is independent of its source, not merely readable. The split matters
+ for callers that must capture several volumes at the same instant: only the start has to run
+ inside a guest freeze, and it must stay cheap enough for that.
+
+ `copy_images_start()` starts a batch between the same pair of storages. Its default
+ implementation starts them one by one, so it needs no capability negotiation; a backend
+ that can capture several volumes atomically overrides it.
+
+ `copy_image_start()` receives the source `$snapname`, as it is the call that captures the point
+ in time. A plugin that snapshots the current image instead would copy live data when a snapshot
+ was requested.
+
+ `copy_image_check()` reports whether the backend can copy a volume to a given target storage,
+ returning `undef` or the reason it cannot. The core asks before choosing offload, so a pair the
+ backend cannot copy, for example one in another pool, takes the host-side path instead of
+ failing. The base implementation accepts everything the feature check accepts.
+
+* Add the common properties `copy-offload` and `copy-offload-timeout`
+
+ The base plugin declares them, so they join the common properties an isolating plugin may use
+ and must not declare itself. A third-party plugin that declares a property of either name is
+ not loaded until it renames it. A plugin that also supports older hosts should only list them
+ in `options()` when `PVE::Storage::APIVER` is at least 18, as older hosts do not declare them.
+
## Version 17:
* Add the volume types `vm-vol`, `vm-state` and `ct-vol`
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index c77a675..81b38d2 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -44,11 +44,11 @@ use PVE::Storage::BTRFSPlugin;
use PVE::Storage::ESXiPlugin;
# Storage API version. Increment it on changes in storage API interface.
-use constant APIVER => 17;
+use constant APIVER => 18;
# Age is the number of versions we're backward compatible with.
# This is like having 'current=APIVER' and age='APIAGE' in libtool,
# see https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
-use constant APIAGE => 8;
+use constant APIAGE => 9;
our $KNOWN_EXPORT_FORMATS = ['raw+size', 'tar+size', 'qcow2+size', 'vmdk+size', 'zfs', 'btrfs'];
@@ -1188,6 +1188,270 @@ sub vdisk_clone {
);
}
+# Returns the copy-offload class usable for $volid -> $target_storeid, or undef.
+#
+# Offload requires: the target storage to have copy-offload enabled, both storages to be
+# instances of the same plugin type, the plugin to advertise a class for this volume, and
+# its copy_image_check() to accept this source/target pair. $opts->{format} is the
+# target format. 'atomic' is preferred when a plugin advertises both, as it needs no
+# host-side mirror. Only the target's copy-offload option is consulted: it is the
+# storage the new volume lands on.
+sub copy_offload_class {
+ my ($cfg, $volid, $target_storeid, $snap, $running, $opts) = @_;
+
+ my ($storeid, $volname) = parse_volume_id($volid, 1);
+ return undef if !$storeid;
+
+ my $scfg = storage_config($cfg, $storeid);
+ my $target_scfg = storage_config($cfg, $target_storeid);
+
+ return undef if !$target_scfg->{'copy-offload'};
+ return undef if $scfg->{type} ne $target_scfg->{type};
+
+ for my $class (qw(atomic bulk)) {
+ next if !volume_has_feature($cfg, "copy-offload-$class", $volid, $snap, $running);
+
+ # The feature says what the source supports; whether the backend can copy it
+ # to this target is the plugin's call. A pair it cannot copy is not an error,
+ # it just takes the host-side path. A check that fails is a fault, not an
+ # answer: it falls back too, but as a warning, so the task shows it.
+ my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
+ my $reason = eval {
+ $plugin->copy_image_check(
+ $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts // {},
+ );
+ };
+ if (my $err = $@) {
+ log_warn("copy-offload check for '$volid' failed, copying through the host - $err");
+ return undef;
+ }
+ if (defined($reason)) {
+ chomp $reason;
+ print "not offloading copy of '$volid': $reason\n";
+ return undef;
+ }
+ return $class;
+ }
+
+ return undef;
+}
+
+# Allocate the target of an offloaded copy, returning the new volid. Its content is
+# undefined until vdisk_copy_start() has been called for it.
+#
+# Split out from the start so a caller cloning a running guest can prepare every disk's
+# target first and then start them all inside a single guest freeze; see vdisk_copy().
+#
+# Only this half runs under the storage lock: it is where the allocation happens, and
+# it is bounded. The copy itself must not run under the lock: for shared storage that is
+# a pmxcfs lock whose locked code is killed by an alarm(60) in PVE::Cluster, while a full
+# array copy runs for minutes to hours. The host-side path is arranged the same way,
+# allocating under the lock and running the long qemu-img convert outside it.
+sub vdisk_copy_prepare {
+ my ($cfg, $volid, $target_storeid, $target_vmid, $snap, $opts) = @_;
+
+ my ($storeid, $volname) = parse_volume_id($volid);
+
+ my $scfg = storage_config($cfg, $storeid);
+ my $target_scfg = storage_config($cfg, $target_storeid);
+
+ my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
+
+ activate_storage($cfg, $storeid);
+ activate_storage($cfg, $target_storeid) if $target_storeid ne $storeid;
+
+ my $new_volname = $plugin->cluster_lock_storage(
+ $target_storeid,
+ $target_scfg->{shared},
+ undef,
+ sub {
+ return $plugin->copy_image_prepare(
+ $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_vmid, $snap, $opts,
+ );
+ },
+ );
+
+ return "$target_storeid:$new_volname";
+}
+
+# Pin the source's point-in-time and begin copying into a prepared target.
+#
+# Must stay cheap: a caller cloning a running guest holds a filesystem freeze across
+# this call for every disk of the VM. It takes no storage lock: the
+# allocation already happened in vdisk_copy_prepare(), and taking a cluster lock inside
+# a guest freeze would be a bad trade.
+sub vdisk_copy_start {
+ my ($cfg, $volid, $target_volid, $snap) = @_;
+
+ my ($storeid, $volname) = parse_volume_id($volid);
+ my ($target_storeid, $target_volname) = parse_volume_id($target_volid);
+
+ my $scfg = storage_config($cfg, $storeid);
+ my $target_scfg = storage_config($cfg, $target_storeid);
+
+ my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
+
+ return $plugin->copy_image_start(
+ $scfg, $storeid, $volname, $target_scfg, $target_storeid, $target_volname, $snap,
+ );
+}
+
+# Start several prepared copies, grouping them so a backend that can capture multiple
+# volumes at one instant does so. $copies is an arrayref of
+# { source => $volid, target => $target_volid }.
+#
+# Copies are grouped by their (source storage, target storage) pair, since that is the
+# granularity at which a backend can act atomically; each group is handed to the
+# plugin's copy_images_start(), whose default starts them one by one.
+#
+# Same constraints as vdisk_copy_start(): cheap, no locking; the caller may hold a
+# guest freeze across this.
+sub vdisk_copy_start_group {
+ my ($cfg, $copies) = @_;
+
+ return if !$copies || !scalar(@$copies);
+
+ my $groups = {};
+ for my $copy (@$copies) {
+ my ($storeid, $volname) = parse_volume_id($copy->{source});
+ my ($target_storeid, $target_volname) = parse_volume_id($copy->{target});
+
+ my $key = "$storeid/$target_storeid";
+ $groups->{$key} //= {
+ storeid => $storeid,
+ target_storeid => $target_storeid,
+ copies => [],
+ };
+ push $groups->{$key}->{copies}->@*,
+ { source => $volname, target => $target_volname, snap => $copy->{snap} };
+ push $groups->{$key}->{orig}->@*, $copy;
+ }
+
+ # Mark each group's copies started as soon as that group returns, not after the
+ # whole batch. A later group can fail, and the caller must still know which copies
+ # are running. Otherwise cleanup cannot tell a started copy from one that never
+ # began, and would either leak a running copy or wait for one that will never
+ # report.
+ for my $key (sort keys %$groups) {
+ my $group = $groups->{$key};
+
+ my $scfg = storage_config($cfg, $group->{storeid});
+ my $target_scfg = storage_config($cfg, $group->{target_storeid});
+
+ my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
+
+ $plugin->copy_images_start(
+ $scfg, $group->{storeid},
+ $target_scfg, $group->{target_storeid},
+ $group->{copies},
+ );
+
+ $_->{started} = 1 for $group->{orig}->@*;
+ }
+
+ return;
+}
+
+# Wait for a started copy to become independent of its source. On failure the target
+# is left for the caller to free, as it owns it since vdisk_copy_prepare().
+#
+# $progress is an optional coderef called with a percentage.
+sub vdisk_copy_wait {
+ my ($cfg, $target_volid, $volid, $progress) = @_;
+
+ my ($target_storeid, $target_volname) = parse_volume_id($target_volid);
+
+ my $target_scfg = storage_config($cfg, $target_storeid);
+ my $plugin = PVE::Storage::Plugin->lookup($target_scfg->{type});
+
+ # What the copy was made from, so the plugin can clean up state it left there.
+ my $source;
+ if ($volid) {
+ my ($storeid, $volname) = parse_volume_id($volid);
+ $source = {
+ scfg => storage_config($cfg, $storeid),
+ storeid => $storeid,
+ volname => $volname,
+ };
+ }
+
+ # A bounded wait, not a bare loop: a backend whose copy dies can otherwise report
+ # 'pending' forever and hang this worker with no error and no progress. The deadline
+ # is generous because the copy is a full data copy, and it is reset whenever the
+ # backend reports forward progress, so a slow-but-live copy is never killed.
+ my $timeout = $target_scfg->{'copy-offload-timeout'} // (24 * 3600);
+ my $deadline = time() + $timeout;
+ my $last_progress;
+ # Poll quickly at first, so a copy that finishes at once is not held up, then back
+ # off: a status call may run backend commands, and a full copy can take hours.
+ my $interval = 1;
+
+ eval {
+ while (1) {
+ my $status = $plugin->copy_image_status(
+ $target_scfg, $target_storeid, $target_volname, $source,
+ );
+
+ my $state = $status->{state} // '';
+ my $done = $status->{progress};
+
+ if (defined($done) && (!defined($last_progress) || $done != $last_progress)) {
+ $progress->(int($done))
+ if $progress && (!defined($last_progress) || int($done) != int($last_progress));
+ $last_progress = $done;
+ $deadline = time() + $timeout; # forward progress: give it the full budget again
+ }
+
+ last if $state eq 'complete';
+
+ die "copy of '$target_volid' reported unexpected state '$state'\n"
+ if $state ne 'pending';
+
+ die "copy of '$target_volid' did not finish within ${timeout}s\n"
+ if time() >= $deadline;
+
+ sleep($interval);
+ $interval = $interval * 2 > 10 ? 10 : $interval * 2;
+ }
+ };
+ # The target is not freed here: the caller got it from vdisk_copy_prepare() and owns
+ # it. Freeing it in two places would leave a window in which a concurrent allocation
+ # takes the name and the second free removes that other volume.
+ die $@ if $@;
+
+ return $target_volid;
+}
+
+# Offload a full copy of $volid to $target_storeid, returning the new volid.
+#
+# The simple path, for a source nothing is writing to: prepare, start, wait. A caller
+# cloning a running guest must not use this. It has to prepare every disk, then start
+# them all inside one freeze, then wait; see the three calls above.
+#
+# The caller is responsible for checking copy_offload_class() first and, for the 'bulk'
+# class with a running guest, for the write-tracking/convergence the class implies.
+sub vdisk_copy {
+ my ($cfg, $volid, $target_storeid, $target_vmid, $snap, $opts, $progress) = @_;
+
+ my $target_volid =
+ vdisk_copy_prepare($cfg, $volid, $target_storeid, $target_vmid, $snap, $opts);
+
+ # The caller only learns the target on success, so a failure is cleaned up here,
+ # including a worker abort during the wait.
+ eval {
+ vdisk_copy_start($cfg, $volid, $target_volid, $snap);
+ vdisk_copy_wait($cfg, $target_volid, $volid, $progress);
+ };
+ if (my $err = $@) {
+ eval { vdisk_free($cfg, $target_volid) };
+ warn "could not clean up target volume '$target_volid' - $@" if $@;
+ die $err;
+ }
+
+ return $target_volid;
+}
+
sub vdisk_create_base {
my ($cfg, $volid) = @_;
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index 998bc68..ef2d5d6 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -227,6 +227,28 @@ my $defaultData = {
type => 'boolean',
optional => 1,
},
+ 'copy-offload-timeout' => {
+ title => "Copy Offload Timeout (s)",
+ description =>
+ "Maximum time in seconds to wait for an offloaded copy to become "
+ . "independent of its source. The timer restarts whenever the backend "
+ . "reports progress, so this bounds a stalled copy rather than a slow one.",
+ type => 'integer',
+ minimum => 1,
+ optional => 1,
+ default => 24 * 3600,
+ },
+ 'copy-offload' => {
+ title => "Copy Offload",
+ description =>
+ "Offload full-copy operations (e.g. full clone) to the storage backend "
+ . "instead of copying the data through the host. Only honored by plugins that "
+ . "advertise a 'copy-offload-atomic' or 'copy-offload-bulk' feature; ignored "
+ . "otherwise. Both source and target must be instances of the same plugin type.",
+ type => 'boolean',
+ optional => 1,
+ default => 0,
+ },
path => {
title => "Path",
description => "Path of the storage in the local file system,"
@@ -1261,6 +1283,152 @@ sub clone_image {
return $newvol;
}
+# Whether the backend can copy $volname (or its snapshot $snap) onto the target storage.
+# Returns undef if it can, or a short reason if it cannot. copy_offload_class() asks
+# before choosing offload, so a pair the backend cannot copy (another pool, another
+# filesystem, a format it cannot produce) takes the normal host-side path instead of
+# failing the clone. Keep it cheap: it runs for every disk of a clone. A plugin should
+# repeat in copy_image_prepare() the parts that need no backend probe, so the two cannot
+# disagree; prepare runs under the storage lock, so leave probes out there. Die only for a
+# fault, such as a failed probe: the caller falls back to the host-side copy then too,
+# but with a warning.
+#
+# $opts->{format} is the format the caller resolved for the target. The base accepts
+# everything the copy-offload feature check accepted.
+sub copy_image_check {
+ my ($class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts) = @_;
+
+ return undef;
+}
+
+# Reserve the target of a full copy of $volname on the target storage and return its
+# volname. The copy itself is asynchronous: copy_image_start() begins it and the caller
+# polls copy_image_status() until it is complete.
+#
+# It must be async because a full array copy runs for minutes to hours, while the core
+# calls this under cluster_lock_storage(). For shared storage that is a pmxcfs lock,
+# whose locked code is killed by an alarm(60) (PVE::Cluster), so a blocking copy would
+# be aborted mid-flight and the lock broken. Splitting start from wait also mirrors what
+# the host-side path already does: it allocates under the lock and runs the long
+# qemu-img convert outside it.
+#
+# The target volname is returned immediately, rather than only when the data is there,
+# so the caller can record it for rollback before anything can go wrong, and
+# free_image() is the cleanup path if the copy later fails or is aborted. A plugin must
+# therefore accept free_image() on a volume whose copy is still in flight, cancelling
+# the backend job.
+#
+# Only called when the plugin advertises 'copy-offload-atomic' or 'copy-offload-bulk'
+# via volume_has_feature() and the target storage has copy-offload enabled, so the base
+# implementation dies rather than returning undef: reaching it means a plugin advertised
+# a capability it does not implement.
+#
+# $target_scfg/$target_storeid describe the target storage. A plugin only ever receives
+# its own per-instance scfg, so it cannot judge whether a given source/target pair can
+# be copied by the backend (same array, same pool group, ...) without them.
+# Both are guaranteed to be instances of the same plugin type as the source; cross-type
+# offload is out of scope, since the operation is opaque to PVE and cannot be lowered to
+# volume_export/volume_import the way a generic copy can.
+#
+# $snap is optional: copy from that snapshot rather than the current state.
+# $opts->{format} is the format the caller resolved for the target. A plugin that cannot
+# produce it must die here rather than produce something else.
+#
+# The copy is split into prepare + start so that a caller cloning a running guest can
+# hold all the disks of a VM at one point in time: it prepares every target first, then
+# fs-freezes the guest once and calls copy_image_start() for each disk inside that
+# freeze. Consistency across disks is a VM-level property, so the core needs a cheap
+# operation it can put inside a freeze, which allocation is not.
+sub copy_image_prepare {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_vmid, $snap, $opts,
+ ) = @_;
+
+ die "storage plugin '" . $class->type() . "' does not implement copy_image_prepare\n";
+}
+
+# Fix the source's point-in-time and begin copying it into the target that
+# copy_image_prepare() returned. Only after this returns is the copy's content defined.
+#
+# Must be fast and must not block: the caller may hold a guest filesystem freeze (or a
+# suspended VM) across this call for every disk of a VM. Do the minimum that pins the
+# source (create the snapshot/pair) and let the data movement proceed in the
+# background, reported by copy_image_status(). A call that can block on a remote
+# backend needs a timeout, so that a backend that hangs fails the start rather than
+# keeps the guest frozen. Cleanup that is not needed to undo the start belongs in
+# free_image(), which the caller runs on the target after the guest is thawed.
+#
+# For the 'copy-offload-atomic' class this call is what defines the copy's point in
+# time; writes to the source after it returns must not affect the result. A plugin that
+# cannot make that guarantee must advertise 'copy-offload-bulk' instead.
+#
+# $snap names the source snapshot to copy from, or is undef for the current state. It
+# is passed here and not only to prepare because this call is what fixes the point in
+# time: a plugin that took its own snapshot of the current image here would
+# copy live data when the caller asked for a snapshot.
+sub copy_image_start {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_volname, $snap,
+ ) = @_;
+
+ die "storage plugin '" . $class->type() . "' does not implement copy_image_start\n";
+}
+
+# Start several copies as one operation. $copies is an arrayref of
+# { source => $volname, target => $target_volname, snap => $snap }, all between the
+# same pair of storages. As in copy_image_start(), 'snap' names the source snapshot to
+# copy from and may be undef; each copy in a batch carries its own.
+#
+# The default starts them one after another. A backend that can capture several
+# volumes at one instant (an array consistency group) overrides it: the disks are then
+# crash-consistent with each other even without a guest freeze, and the freeze, when
+# there is one, covers one backend call instead of N. The plugin decides how to split a
+# batch into backend groups; the core only guarantees that every start of a batch
+# happens inside one guest freeze.
+#
+# Same contract as copy_image_start(): fast, non-blocking, and for the atomic class it
+# is this call that fixes the point in time of every copy in the group.
+sub copy_images_start {
+ my ($class, $scfg, $storeid, $target_scfg, $target_storeid, $copies) = @_;
+
+ for my $copy (@$copies) {
+ $class->copy_image_start(
+ $scfg, $storeid, $copy->{source},
+ $target_scfg, $target_storeid, $copy->{target}, $copy->{snap},
+ );
+ }
+
+ return;
+}
+
+# Poll a copy started by copy_image_start(). Returns a hashref:
+#
+# { state => 'pending'|'complete', progress => $percent }
+#
+# 'progress' is optional and informational only. On failure this must die; the caller
+# then frees the target volume.
+#
+# 'complete' means the target is independent of the source, not merely that the data
+# is readable. For backends where independence is asynchronous (an RBD flatten, a ZFS
+# clone still tied to its origin, an array pair that has not dissolved yet) reporting
+# 'complete' early produces something that is not a full copy, and the caller is then
+# free to delete the source.
+#
+# This is called outside the storage lock, so it may talk to the backend, but it should
+# stay cheap: it runs in a poll loop.
+#
+# $source is { scfg, storeid, volname } describing what the copy was made from. A
+# plugin may need it to clean up state it left on the source: an RBD copy, for
+# instance, is a clone of a snapshot taken on the source image, and once the copy is
+# independent nothing else records where it came from.
+sub copy_image_status {
+ my ($class, $scfg, $storeid, $volname, $source) = @_;
+
+ die "storage plugin '" . $class->type() . "' does not implement copy_image_status\n";
+}
+
sub alloc_image {
my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
@@ -1785,6 +1953,18 @@ sub storage_can_replicate {
return 0;
}
+# Besides the features listed below, a plugin may advertise one of the two copy-offload
+# classes (see copy_image_prepare()). They are separate features rather than one feature with a
+# class argument so that this interface stays unchanged; a plugin supports whichever one
+# fits its backend, and a caller that can use both prefers 'copy-offload-atomic':
+#
+# copy-offload-atomic The backend can produce the copy from a static point-in-time
+# source (snapshot/clone), so no host-side mirror is needed to
+# keep it consistent while the source keeps changing.
+# copy-offload-bulk The copy is a bulk data movement that smears over a changing
+# source (e.g. NFS 4.2 server-side copy, zfs send/recv). For a
+# running guest the caller must track writes and converge, the
+# way live migration does.
sub volume_has_feature {
my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
diff --git a/src/test/copy_offload_test.pm b/src/test/copy_offload_test.pm
new file mode 100644
index 0000000..81a8b82
--- /dev/null
+++ b/src/test/copy_offload_test.pm
@@ -0,0 +1,90 @@
+package PVE::Storage::TestCopyOffload;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use PVE::Storage;
+use Test::More;
+
+# copy_offload_class() decides whether a full copy may be handed to the backend, and
+# which of the two classes to use. Getting it wrong either declines a possible offload
+# or drives one onto a storage pair that cannot perform it, so the rules are pinned here.
+#
+# The checks are: the target storage must have copy-offload enabled, both storages must
+# be instances of the same plugin type, and the plugin must advertise a class for that
+# volume. 'atomic' wins when a plugin advertises both, as it needs no host-side mirror.
+
+my $features = {}; # volid => { feature => 1 }
+
+{
+ no warnings 'redefine';
+ *PVE::Storage::volume_has_feature = sub {
+ my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
+ return $features->{$volid}->{$feature} ? 1 : 0;
+ };
+}
+
+my $cfg = {
+ ids => {
+ 'rbd-a' => { type => 'rbd', 'copy-offload' => 1 },
+ 'rbd-b' => { type => 'rbd', 'copy-offload' => 1 },
+ 'rbd-off' => { type => 'rbd' },
+ 'dir-a' => { type => 'dir', 'copy-offload' => 1 },
+ },
+};
+
+my $volid = 'rbd-a:vm-100-disk-0';
+
+my $tests = [
+ # [ description, target storeid, advertised features, expected class ]
+ ['nothing advertised => no offload', 'rbd-b', {}, undef],
+ ['atomic advertised', 'rbd-b', { 'copy-offload-atomic' => 1 }, 'atomic'],
+ ['bulk advertised', 'rbd-b', { 'copy-offload-bulk' => 1 }, 'bulk'],
+ [
+ 'atomic preferred when both are advertised',
+ 'rbd-b',
+ { 'copy-offload-atomic' => 1, 'copy-offload-bulk' => 1 },
+ 'atomic',
+ ],
+ [
+ 'target has copy-offload disabled',
+ 'rbd-off',
+ { 'copy-offload-atomic' => 1 },
+ undef,
+ ],
+ [
+ 'cross-type is out of scope even when advertised',
+ 'dir-a',
+ { 'copy-offload-atomic' => 1 },
+ undef,
+ ],
+ [
+ 'same storage as source is allowed',
+ 'rbd-a',
+ { 'copy-offload-atomic' => 1 },
+ 'atomic',
+ ],
+];
+
+plan tests => scalar(@$tests) + 1;
+
+for my $t (@$tests) {
+ my ($desc, $target, $adv, $expected) = @$t;
+
+ $features = { $volid => $adv };
+
+ my $got = PVE::Storage::copy_offload_class($cfg, $volid, $target, undef, 0);
+ is($got, $expected, $desc);
+}
+
+# A path that is not a storage volume must not be mistaken for an offloadable one.
+$features = { $volid => { 'copy-offload-atomic' => 1 } };
+is(
+ PVE::Storage::copy_offload_class($cfg, '/dev/sdb', 'rbd-b', undef, 0),
+ undef,
+ 'a bare path is never offloadable',
+);
+
+done_testing();
diff --git a/src/test/plugin_properties_test.pm b/src/test/plugin_properties_test.pm
index 80d36dc..3699c58 100644
--- a/src/test/plugin_properties_test.pm
+++ b/src/test/plugin_properties_test.pm
@@ -19,6 +19,8 @@ my $available = {
comstar_tg => 'string',
content => 'string:pve-storage-content-list',
'content-dirs' => 'string:pve-dir-override-list',
+ 'copy-offload' => 'boolean',
+ 'copy-offload-timeout' => 'integer minimum=1',
'create-base-path' => 'boolean',
'create-subdirs' => 'boolean',
'data-pool' => 'string',
@@ -138,7 +140,8 @@ for my $name (sort keys $available->%*) {
# adding one can break third-party plugins. A property belongs here only if methods of the base
# plugin or code outside of the plugins read it from storages of any type.
my $base = [qw(
- base bwlimit content content-dirs create-base-path create-subdirs disable format
+ base bwlimit content content-dirs copy-offload copy-offload-timeout create-base-path
+ create-subdirs disable format
max-protected-backups mkdir nodes path preallocation prune-backups shared
snapshot-as-volume-chain storage type
)];
diff --git a/src/test/run_plugin_tests.pl b/src/test/run_plugin_tests.pl
index da0d0de..57e3140 100755
--- a/src/test/run_plugin_tests.pl
+++ b/src/test/run_plugin_tests.pl
@@ -25,6 +25,7 @@ my $res = $harness->runtests(
"plugin_isolation_test.pm",
"plugin_load_test.pm",
"plugin_properties_test.pm",
+ "copy_offload_test.pm",
);
exit -1 if !$res || $res->{failed} || $res->{parse_errors};
--
2.55.0
^ permalink raw reply related [flat|nested] 7+ messages in thread
* [RFC PATCH storage v2 2/6] rbd: implement copy-offload via snapshot + clone + flatten
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 ` Ciro Iriarte
2026-11-26 16:57 ` [RFC PATCH storage v2 3/6] dir: implement copy-offload via reflink (FICLONE) Ciro Iriarte
` (3 subsequent siblings)
5 siblings, 0 replies; 7+ messages in thread
From: Ciro Iriarte @ 2026-11-26 16:56 UTC (permalink / raw)
To: pve-devel
From: Ciro Iriarte <ciro.iriarte+software@gmail.com>
Ceph can make a full copy without moving data through the host: snapshot
the source, clone the snapshot, flatten the clone. The flatten is the
data copy and runs on the cluster.
prepare create a minimal placeholder image to reserve the name
start snapshot (unless the caller gave one) and clone; both are
metadata operations, cheap enough for a guest freeze, and
they capture the point in time, hence copy-offload-atomic
status pending while the clone has a parent, complete once
flattened
The flatten is handed to the manager with 'ceph rbd task add flatten',
with the storage's connection options, so it runs cluster-side, outlives
the worker and can be cancelled. Status distinguishes complete (no
parent), pending (a task exists) and failed (still a clone, no task). A
fast flatten can leave the task list between the two reads, so if no
task is found, status re-reads the parent before reporting a failure,
and a task list that cannot be read at all, as during a manager
failover, counts as pending.
copy_image_check() refuses, and the host copies the clone instead, when
the target is on another Ceph cluster, when the two storages use
different Ceph users (the clone is made with the source's user, which
then writes to the target pool), or when the target's Ceph user is not
allowed to add manager tasks. Equal monhost values mean the same
cluster, and an unset one means the local cluster; different values are
compared by the clusters' fsid. Manager write access is probed by
cancelling a task that does not exist, which returns ENOENT if allowed
and EACCES if not. Any other probe failure dies, so the core falls back
with a warning. prepare runs only the checks that need no cluster
access, as it holds the storage lock.
Each command run by start has a 30 second timeout, so a hung cluster
fails the start within a bounded time instead of holding the guest
frozen indefinitely; the timeout is per command, and there are about
five per disk. On failure, start removes only the staging clone and its
own snapshot, with the same timeout. If the snapshot cannot be removed,
the next prepare that copies the same source to the same target name
cleans it up; prepare fails if it cannot, rather than leaving start to
fail on it inside the freeze.
start builds the clone under a staging name and renames the placeholder
out of the way instead of deleting it, so the disk name stays taken
throughout; otherwise a concurrent allocation could take it and this
copy's rollback would free the other volume. The parked placeholder is
removed by status once the copy is complete, or by free_image() if the
copy is rolled back; never by start, since 'rbd rm' walks every object
and start can run inside a guest freeze. Both transient names use
prefixes: list_images() matches on an anchored pattern, so they never
show up as a VM's disk, while find_free_diskname() matches the disk
number unanchored, so they still reserve it. copy_offload_naming_test.pm
covers both.
A caller-supplied snapshot is cloned with clone format 2, which does not
require the snapshot to be protected. Once the copy is independent,
status removes the snapshot this plugin took on the source; free_image()
does the same for a copy that failed, and cancels its flatten if it is
still running. free_image() only looks for these on a storage with
copy-offload enabled, so an ordinary free makes no extra calls.
copy_images_start() is not overridden. Ceph group snapshots do capture a
single instant, but an image can belong to only one group, so grouping
would change the source images' group membership.
Tested on Ceph Tentacle 20.2.1 with an erasure-coded pool: the copy had
no parent, matched the source and still read correctly after the source
was deleted. Running VMs were full-cloned with a mix of offloaded and
drive-mirrored disks; the clones were byte-identical and independent,
and no snapshot was left on the sources.
Signed-off-by: Ciro Iriarte <ciro.iriarte+software@gmail.com>
---
Changes in v2:
* rebased onto current master
* folded in the flatten status fix sent as a follow-up to v1 on
2026-07-22, with copy_offload_rbd_status_test.pm
* copy_image_check(): raw VM disks, one Ceph cluster (same monitors,
or else same fsid), the same Ceph user on both storages, and a user
allowed to add manager tasks; a failed probe dies, so the core falls
back with a warning. prepare repeats only the static checks,
as it holds the storage lock
* each command in start has a 30 second timeout; a failed start leaves
the parked placeholder to free_image(), and prepare removes a copy
snapshot left over from an earlier failed copy of the same source to
the same name, or fails if it cannot
* free_image() looks for copy leftovers only with copy-offload enabled
* the 'ceph rbd task' calls now use the storage's connection options,
so an external cluster works, and match the namespace
* free_image() cancels a running flatten, and status treats a
task list it cannot read as pending, not as a dead flatten
* values read back from 'rbd info' are untainted, as pvedaemon runs
with -T
src/PVE/Storage/RBDPlugin.pm | 551 ++++++++++++++++++++++-
src/test/copy_offload_naming_test.pm | 82 ++++
src/test/copy_offload_rbd_status_test.pm | 114 +++++
src/test/run_plugin_tests.pl | 2 +
4 files changed, 743 insertions(+), 6 deletions(-)
create mode 100644 src/test/copy_offload_naming_test.pm
create mode 100644 src/test/copy_offload_rbd_status_test.pm
diff --git a/src/PVE/Storage/RBDPlugin.pm b/src/PVE/Storage/RBDPlugin.pm
index ac0e0fa..061c75a 100644
--- a/src/PVE/Storage/RBDPlugin.pm
+++ b/src/PVE/Storage/RBDPlugin.pm
@@ -371,8 +371,9 @@ sub rbd_volume_du {
die "got no matching image from rbd du\n";
}
-my sub rbd_volume_exists {
- my ($scfg, $storeid, $volname) = @_;
+# Every image name in the pool, unfiltered (rbd_ls() skips names that are not disks).
+my sub rbd_image_names {
+ my ($scfg, $storeid, $timeout) = @_;
my $cmd = $rbd_cmd->($scfg, $storeid, 'ls', '--format', 'json');
my $raw = '';
@@ -381,6 +382,7 @@ my sub rbd_volume_exists {
errmsg => "rbd error",
errfunc => sub { },
outfunc => sub { $raw .= shift; },
+ (defined($timeout) ? (timeout => $timeout) : ()),
);
my $list;
@@ -391,11 +393,13 @@ my sub rbd_volume_exists {
die "got unexpected data from 'rbd ls': '$raw'\n";
}
- for my $name ($list->@*) {
- return 1 if $name eq $volname;
- }
+ return { map { $_ => 1 } $list->@* };
+}
+
+my sub rbd_volume_exists {
+ my ($scfg, $storeid, $volname) = @_;
- return 0;
+ return rbd_image_names($scfg, $storeid)->{$volname} ? 1 : 0;
}
# Needs to be public, so qemu-server can mock it for cfg2cmd.
@@ -448,6 +452,7 @@ sub plugindata {
],
'advanced-properties' => {
namespace => 1,
+ 'copy-offload-timeout' => 1,
},
'hidden-properties' => {
bwlimit => 1,
@@ -519,6 +524,8 @@ sub options {
krbd => { optional => 1 },
keyring => { optional => 1 },
bwlimit => { optional => 1 },
+ 'copy-offload' => { optional => 1 },
+ 'copy-offload-timeout' => { optional => 1 },
};
}
@@ -764,6 +771,486 @@ sub clone_image {
return $newvol;
}
+# ---- storage-offloaded full copy -------------------------------------------------
+#
+# Ceph can produce a full copy without moving the data through the host: snapshot the
+# source, clone the snapshot (copy-on-write, instant), then flatten the clone. The
+# flatten is what copies the data, and it runs on the Ceph cluster.
+#
+# That maps onto the hook's three phases as follows:
+#
+# prepare create a minimal placeholder image, reserving the target name.
+# start snapshot (unless the caller gave one) and clone it with clone format 2,
+# which needs no protected snapshot, then park the placeholder and rename
+# the clone into place. All metadata operations, so this is safe to run
+# inside a guest freeze, and it is what fixes the copy's point in time:
+# writes to the source afterwards cannot affect the clone.
+# status pending until the flatten has removed the clone's parent, that is, until
+# the target is independent and the source may be deleted.
+#
+# The last point is why 'complete' is defined as independent rather than readable: a
+# clone is fully readable the moment it exists, but deleting the source out from under
+# an unflattened clone would destroy it.
+
+my $rbd_copy_snap = sub {
+ my ($target_volname) = @_;
+ # Derived from the target name so status/cleanup can find it again without state.
+ return "__copy_$target_volname";
+};
+
+# 'ceph' with the storage's connection options, like $rbd_cmd, so an external cluster
+# (monhost/keyring set) is addressed instead of the local one.
+my sub ceph_cmd {
+ my ($scfg, $storeid, @args) = @_;
+
+ my $opt = PVE::CephConfig::ceph_connect_option($scfg, $storeid);
+ my $cmd = ['/usr/bin/ceph'];
+ push @$cmd, '-c', $opt->{ceph_conf} if $opt->{ceph_conf};
+ push @$cmd, '-m', $opt->{mon_host} if $opt->{mon_host};
+ push @$cmd, '--auth_client_required', $opt->{auth_client_required}
+ if $opt->{auth_client_required};
+ push @$cmd, '-n', "client.$opt->{userid}" if $opt->{userid};
+ push @$cmd, '--keyring', $opt->{keyring} if $opt->{keyring};
+ push @$cmd, @args;
+ return $cmd;
+}
+
+# The image's parent, from 'rbd info', or undef. Values are untainted: they come from
+# command output and are passed back to rbd, and pvedaemon runs with taint checks.
+my sub rbd_volume_parent {
+ my ($scfg, $storeid, $name) = @_;
+
+ my $cmd = $rbd_cmd->($scfg, $storeid, 'info', $name, '--format', 'json');
+ my $raw = '';
+ run_rbd_command($cmd, errmsg => "rbd info '$name' error", outfunc => sub { $raw .= shift });
+ my $parent = eval { decode_json($raw)->{parent} };
+ return undef if ref($parent) ne 'HASH';
+ for my $k (qw(pool pool_namespace image snapshot)) {
+ next if !defined($parent->{$k});
+ ($parent->{$k}) = $parent->{$k} =~ m/^([^\s\/\@]*)$/
+ or die "unexpected rbd parent $k '$parent->{$k}'\n";
+ }
+ return $parent;
+}
+
+# Bound for each backend command copy_image_start() runs, and for the probes in
+# copy_image_check(). The start runs inside a guest freeze, so a hanging cluster must
+# fail it rather than keep the guest frozen; every step is a metadata operation that
+# normally takes well under a second.
+my $COPY_CMD_TIMEOUT = 30;
+
+# Bound for the clean-up copy_image_prepare() does under the storage lock, whose
+# locked code is limited to 60 seconds: at most four such commands run there.
+my $COPY_LOCKED_CMD_TIMEOUT = 10;
+
+# Run a best-effort rbd command, bounded by $timeout (default $COPY_CMD_TIMEOUT).
+# Returns undef on success, '' if rbd reported the image or snapshot as missing, and
+# rbd's error otherwise, so a cleanup can tell "nothing to remove" from a real failure
+# without printing either.
+my sub rbd_try {
+ my ($cmd, $timeout) = @_;
+
+ my $stderr = '';
+ eval {
+ run_command(
+ $cmd,
+ outfunc => sub { },
+ errfunc => sub { $stderr .= "$_[0]\n" },
+ timeout => $timeout // $COPY_CMD_TIMEOUT,
+ );
+ };
+ my $err = $@ or return undef;
+ return '' if $stderr =~ /^rbd: .*\(2\) No such file or directory/m;
+ return $stderr || $err;
+}
+
+# The Ceph manager's rbd task queue, decoded. Dies if it cannot be read: a failed
+# look-up (a manager failover, or a key without manager access) is not the same as an
+# empty queue.
+my sub rbd_task_list {
+ my ($scfg, $storeid) = @_;
+
+ my $out = '';
+ eval {
+ run_command(ceph_cmd($scfg, $storeid, 'rbd', 'task', 'list', '--format', 'json'),
+ outfunc => sub { $out .= shift }, timeout => $COPY_CMD_TIMEOUT);
+ };
+ die "cannot list rbd tasks - $@" if $@;
+ return [] if $out !~ /\S/;
+
+ my $tasks = eval { decode_json($out) };
+ die "invalid JSON from 'ceph rbd task list' - $@" if $@ || ref($tasks) ne 'ARRAY';
+ return $tasks;
+}
+
+# The cluster's fsid, to tell whether two storages address the same Ceph cluster.
+my sub ceph_fsid {
+ my ($scfg, $storeid) = @_;
+
+ my $out = '';
+ run_command(ceph_cmd($scfg, $storeid, 'fsid'),
+ outfunc => sub { $out .= shift }, timeout => $COPY_CMD_TIMEOUT);
+ my ($fsid) = $out =~ m/^\s*([0-9a-f-]{36})\s*$/
+ or die "unexpected output from 'ceph fsid'\n";
+ return $fsid;
+}
+
+# The manager-side flatten task for an image, if one is queued or running. Dies if
+# the queue cannot be read, so the caller does not mistake a running flatten for a
+# dead one.
+my sub rbd_flatten_task {
+ my ($scfg, $storeid, $name) = @_;
+
+ my $tasks = rbd_task_list($scfg, $storeid);
+
+ my $pool = $scfg->{pool} || 'rbd';
+ my $ns = $scfg->{namespace} // '';
+ for my $task (@$tasks) {
+ my $refs = $task->{refs} // {};
+ next if ($refs->{action} // '') ne 'flatten';
+ next if ($refs->{image_name} // '') ne $name;
+ next if ($refs->{pool_name} // '') ne $pool;
+ next if ($refs->{pool_namespace} // '') ne $ns;
+ return $task;
+ }
+
+ return undef;
+}
+
+# Names for the two transient images a copy needs: the clone as it is being built, and
+# the placeholder once it has been moved out of the way.
+#
+# Both use a prefix. rbd_ls(), which feeds list_images(), selects on the anchored
+# m/^(?:vm|base)-(\d+)-/, so a prefixed name is invisible there and never appears as a
+# disk of that VM. find_free_diskname() meanwhile passes the raw 'rbd ls' output
+# to get_next_vm_diskname(), whose disk-number regex is unanchored, so a prefixed name
+# still reserves the disk number, which is what these need.
+my sub copy_staging_name { return "copynew-$_[0]" }
+my sub copy_parked_name { return "copytmp-$_[0]" }
+
+# Remove transient images a previous copy to this name left behind. They are invisible
+# to list_images(), so nothing else would ever reap them, and a leftover placeholder
+# would make the rename in copy_image_start() fail for every future copy to this name.
+my sub copy_reap_leftovers {
+ my ($scfg, $storeid, $volname, $timeout) = @_;
+ $timeout //= $COPY_CMD_TIMEOUT;
+
+ # Best effort, one 'rbd ls', each step bounded: it runs under the storage lock in
+ # copy_image_prepare() and on free_image(), which it must neither stall nor fail.
+ my $names = eval { rbd_image_names($scfg, $storeid, $timeout) };
+ if (my $err = $@) {
+ warn "could not check for stale copy images - $err";
+ return;
+ }
+ for my $stale (copy_staging_name($volname), copy_parked_name($volname)) {
+ next if !$names->{$stale};
+ warn "removing stale copy image '$stale'\n";
+ my $err = rbd_try($rbd_cmd->($scfg, $storeid, 'rm', $stale), $timeout);
+ warn "could not remove stale copy image '$stale' - $err" if defined($err);
+ }
+}
+
+# What can be told from the configuration alone. copy_image_prepare() repeats only this
+# part: it runs under the storage lock, where the cluster probes do not belong.
+my sub copy_check_static {
+ my ($class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $opts) = @_;
+
+ my ($vtype) = $class->parse_volname($volname);
+ return "only VM disks can be offloaded, not '$vtype'"
+ if !PVE::Storage::Common::vtype_matches($vtype, 'vm-vol');
+ my $format = $opts->{format} // 'raw';
+ return "cannot produce format '$format'" if $format ne 'raw';
+
+ # The clone is made with the source storage's Ceph user, which then needs write
+ # access to the target pool. Only the same user is known to have it.
+ return "storages '$storeid' and '$target_storeid' use different Ceph users"
+ if ($scfg->{username} // 'admin') ne ($target_scfg->{username} // 'admin');
+
+ return undef;
+}
+
+# Whether the Ceph user may add manager tasks, without adding one: cancelling a task
+# that does not exist is a write command too, and answers ENOENT if allowed.
+my sub rbd_task_write_allowed {
+ my ($scfg, $storeid) = @_;
+
+ my $no_such_task = '00000000-0000-0000-0000-000000000000';
+ my $err = '';
+ eval {
+ run_command(
+ ceph_cmd($scfg, $storeid, 'rbd', 'task', 'cancel', $no_such_task),
+ outfunc => sub { },
+ errfunc => sub { $err .= "$_[0]\n" },
+ timeout => $COPY_CMD_TIMEOUT,
+ );
+ };
+ return 1 if $err =~ /ENOENT/;
+ return 0 if $err =~ /^Error E(?:ACCES|PERM)\b/m;
+ die "cannot query the Ceph manager - " . ($err || $@);
+}
+
+sub copy_image_check {
+ my ($class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts) = @_;
+
+ my $reason = copy_check_static(
+ $class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $opts,
+ );
+ return $reason if defined($reason);
+
+ # Equal 'monhost' values address the same monitors, and an unset one means the
+ # cluster this node runs. Different values may still name one cluster, which only
+ # its fsid tells. A probe that fails is a fault, not an answer, so it dies.
+ if (($scfg->{monhost} // '') ne ($target_scfg->{monhost} // '')) {
+ return "storage '$target_storeid' is on a different Ceph cluster"
+ if ceph_fsid($scfg, $storeid) ne ceph_fsid($target_scfg, $target_storeid);
+ }
+
+ # The flatten that does the copy runs as a Ceph manager task, which the storage's
+ # Ceph user must be allowed to add.
+ return "the Ceph user of '$target_storeid' may not add manager tasks"
+ if !rbd_task_write_allowed($target_scfg, $target_storeid);
+
+ return undef;
+}
+
+sub copy_image_prepare {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_vmid, $snap, $opts,
+ ) = @_;
+
+ my $reason = copy_check_static(
+ $class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $opts,
+ );
+ die "cannot offload copy of '$volname': $reason\n" if defined($reason);
+
+ my $name = $class->find_free_diskname($target_storeid, $target_scfg, $target_vmid);
+
+ # Safe here: we hold the target storage lock, and the name is ours because
+ # find_free_diskname() just handed it out.
+ copy_reap_leftovers($target_scfg, $target_storeid, $name, $COPY_LOCKED_CMD_TIMEOUT);
+
+ # A snapshot of the source named after this target is left over from an earlier
+ # copy to the same name that failed before it could remove it. The name was just
+ # handed out, so no live copy uses it, and copy_image_start() would fail on it.
+ if (!defined($snap)) {
+ my (undef, $src_name) = $class->parse_volname($volname);
+ my $stale = $rbd_copy_snap->($name);
+ my $err = rbd_try(
+ $rbd_cmd->($scfg, $storeid, 'snap', 'rm', $src_name, '--snap', $stale),
+ $COPY_LOCKED_CMD_TIMEOUT,
+ );
+ if (!defined($err)) {
+ warn "removed stale copy snapshot '$stale' of '$src_name'\n";
+ } elsif ($err ne '') {
+ # left in place, copy_image_start() would fail on it inside the guest freeze
+ die "cannot remove stale copy snapshot '$stale' of '$src_name' - $err";
+ }
+ }
+
+ # 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.
+ #
+ # The smallest image rbd accepts, not the source's size: it only holds the name
+ # until copy_image_start() parks it and renames the clone into place, and 'rbd rm'
+ # walks every object of an image. Up to the 4 MiB object size it is a single object.
+ my $cmd = $rbd_cmd->(
+ $target_scfg, $target_storeid, 'create', '--image-format', '2',
+ '--size', '4K', $name,
+ );
+ push $cmd->@*, ('--data-pool', $target_scfg->{'data-pool'})
+ if $target_scfg->{'data-pool'};
+ run_rbd_command($cmd, errmsg => "rbd create '$name' error");
+
+ return $name;
+}
+
+sub copy_image_start {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_volname, $snap,
+ ) = @_;
+
+ my (undef, $name) = $class->parse_volname($volname);
+
+ my $run = sub {
+ my ($cmd, $errmsg) = @_;
+ run_rbd_command($cmd, errmsg => $errmsg, timeout => $COPY_CMD_TIMEOUT);
+ };
+
+ # Copy from the snapshot the caller asked for. Taking our own snapshot of the
+ # current image would copy live data when a snapshot was requested.
+ my $own_snap = defined($snap) ? undef : $rbd_copy_snap->($target_volname);
+ my $src_snap = $snap // $own_snap;
+
+ my $tmp = copy_staging_name($target_volname);
+ my $parked = copy_parked_name($target_volname);
+ my $cloned;
+
+ my $ok = eval {
+ # Inside the eval: a timed-out create may still have made the snapshot.
+ if ($own_snap) {
+ my $cmd = $rbd_cmd->($scfg, $storeid, 'snap', 'create', $name, '--snap', $own_snap);
+ $run->($cmd, "rbd snap create '$name' error");
+ }
+
+ # Clone format 2 so no snapshot protection is needed, which is required when copying
+ # from a caller-supplied snapshot we do not own and must not protect/unprotect.
+ my @options = (
+ '--rbd-default-clone-format', '2',
+ get_rbd_path($scfg, $name), '--snap', $src_snap,
+ );
+ push @options, ('--data-pool', $target_scfg->{'data-pool'})
+ if $target_scfg->{'data-pool'};
+
+ my $cmd = $rbd_cmd->(
+ $scfg, $storeid, 'clone', @options, get_rbd_path($target_scfg, $tmp),
+ );
+ $cloned = 1; # a timed-out clone may still have created it
+ $run->($cmd, "rbd clone '$name' error");
+
+ # Swap the clone into the reserved name. Move the placeholder aside rather than
+ # deleting it first: 'rbd rm' followed by 'rbd rename' leaves the disk number
+ # unreserved in between, and a concurrent allocation could take it, after
+ # which this copy's rollback would free somebody else's volume. Parked under a
+ # prefixed name it stays invisible to list_images() while still reserving the
+ # number. It is removed by copy_image_status() once the copy is complete, or by
+ # free_image() if the copy is rolled back; never here, as the caller may hold
+ # the guest frozen.
+ $cmd = $rbd_cmd->($target_scfg, $target_storeid, 'rename', $target_volname, $parked);
+ $run->($cmd, "rbd rename placeholder '$target_volname' error");
+ $cmd = $rbd_cmd->($target_scfg, $target_storeid, 'rename', $tmp, $target_volname);
+ if (!eval { $run->($cmd, "rbd rename '$tmp' error"); 1 }) {
+ my $rerr = $@;
+ # Put the reservation back so the caller's rollback frees what it was given.
+ my $c = $rbd_cmd->(
+ $target_scfg, $target_storeid, 'rename', $parked, $target_volname,
+ );
+ eval { $run->($c, "restoring placeholder error") };
+ warn $@ if $@;
+ die $rerr;
+ }
+ $cloned = 0; # the clone is the target now, which the caller frees
+
+ # Hand the flatten to the Ceph manager rather than running it here: it is the
+ # data copy, it must not block a caller that may be holding a guest
+ # freeze, and a cluster-side task survives this worker dying. It is also
+ # cancellable, which a detached child process would not have been.
+ $cmd = ceph_cmd($target_scfg, $target_storeid, 'rbd', 'task', 'add', 'flatten',
+ get_rbd_path($target_scfg, $target_volname));
+ run_command(
+ $cmd,
+ errmsg => "scheduling rbd flatten failed",
+ outfunc => sub { },
+ timeout => $COPY_CMD_TIMEOUT,
+ );
+ 1;
+ };
+ if (my $err = $@) {
+ # Leave the source as it was. Only what blocks removing our snapshot is removed
+ # here, each step bounded; a parked placeholder is reaped by free_image() when
+ # the caller frees the target, and a snapshot that cannot be removed now by the
+ # next copy_image_prepare() for this name.
+ if ($cloned) {
+ my $e = rbd_try($rbd_cmd->($target_scfg, $target_storeid, 'rm', $tmp));
+ warn "could not remove '$tmp' - $e" if $e;
+ }
+ if ($own_snap) {
+ my $e = rbd_try($rbd_cmd->($scfg, $storeid, 'snap', 'rm', $name, '--snap', $own_snap));
+ warn "could not remove snapshot '$own_snap' of '$name' - $e" if $e;
+ }
+ die $err;
+ }
+
+ return;
+}
+
+sub copy_image_status {
+ my ($class, $scfg, $storeid, $volname, $source) = @_;
+
+ my (undef, $name) = $class->parse_volname($volname);
+
+ # The image's parent link is the source of truth for completion: no parent means the
+ # flatten finished and the image is independent. A clone is readable from the
+ # moment it exists, but deleting the source before the flatten completes would
+ # destroy it.
+ my $read_parent = sub { rbd_volume_parent($scfg, $storeid, $name) };
+
+ my $parent = $read_parent->();
+
+ # Still a clone: the flatten is running, has just finished, or died. The manager task
+ # is only a liveness signal, not the completion signal. A fast flatten of a small
+ # image can vanish from 'rbd task list' between the info read above and this task
+ # lookup, so a missing task is ambiguous: re-read the parent before concluding the
+ # flatten died. Otherwise a copy that completed is misreported as a dead flatten,
+ # a race seen with concurrent multi-disk clones of small images.
+ if ($parent) {
+ # A failed task look-up proves nothing either way; poll again, and let the
+ # caller's timeout end a copy that never comes back.
+ my $task = eval { rbd_flatten_task($scfg, $storeid, $name) };
+ if (my $err = $@) {
+ warn $err;
+ return { state => 'pending' };
+ }
+ if ($task) {
+ my $progress = $task->{progress};
+ return {
+ state => 'pending',
+ (defined($progress) ? (progress => $progress * 100) : ()),
+ };
+ }
+
+ # No task: re-read the parent. If the flatten just finished it is now gone.
+ $parent = $read_parent->();
+ if ($parent) {
+ # Parent persists with no task. One more task look-up guards a transient
+ # empty 'rbd task list' while the flatten is still running; only when that
+ # is also empty is the flatten dead.
+ my $again = eval { rbd_flatten_task($scfg, $storeid, $name) };
+ if (my $err = $@) {
+ warn $err;
+ return { state => 'pending' };
+ }
+ die "flatten of '$volname' is no longer running and the image is still a clone\n"
+ if !$again;
+ return { state => 'pending' };
+ }
+ # Parent cleared: the flatten completed, fall through to the completion cleanup.
+ }
+
+ # independent. Drop the snapshot this copy was taken from, on the source image. Once
+ # the flatten completes the target no longer records where it came from, so this is
+ # the last chance to find it, and leaving it behind pins space on the source and
+ # blocks deleting that volume later.
+ #
+ # Only ever our own: the name is derived from the target, so a caller-supplied
+ # snapshot can never match and is left untouched.
+ if ($source) {
+ my $own_snap = $rbd_copy_snap->($volname);
+ my (undef, $src_name) = $class->parse_volname($source->{volname});
+ my $err = rbd_try($rbd_cmd->(
+ $source->{scfg}, $source->{storeid}, 'snap', 'rm', $src_name, '--snap', $own_snap,
+ ));
+ # a copy from a caller-supplied snapshot has none of ours: not worth a warning
+ warn "could not remove snapshot '$own_snap' of '$src_name' - $err" if $err;
+ }
+ # The placeholder copy_image_start() parked. Not removed there: 'rbd rm' walks
+ # every object and that call can run with a guest frozen. Best effort: the copy is
+ # already complete and correct, and dying here would make the caller free it.
+ my $parked = copy_parked_name($name);
+ eval {
+ if (rbd_volume_exists($scfg, $storeid, $parked)) {
+ my $c = $rbd_cmd->($scfg, $storeid, 'rm', $parked);
+ run_rbd_command($c, errmsg => "rbd rm placeholder '$parked' error");
+ }
+ };
+ warn $@ if $@;
+
+ return { state => 'complete' };
+}
+
sub alloc_image {
my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
@@ -790,6 +1277,41 @@ sub free_image {
my ($vtype, $name, $vmid, undef, undef, undef) = $class->parse_volname($volname);
+ # What an offloaded copy to this name can leave behind. Only looked for on a storage
+ # with copy-offload enabled, the only place such copies are made, so an ordinary
+ # free does not pay for the extra 'rbd' and 'ceph' calls.
+ my ($copy_parent, $task_id);
+ if ($scfg->{'copy-offload'}) {
+ # Transient images from a copy that died mid-flight. They are invisible to
+ # list_images(), so freeing the volume they belong to is the only occasion
+ # anything would look for them.
+ copy_reap_leftovers($scfg, $storeid, $name);
+
+ # An unfinished copy is still a clone of a snapshot this plugin took on the
+ # source image. Freeing the target would leave that snapshot behind, pinning
+ # space and blocking deletion of the source. The clone is the only record of
+ # where it came from, so read the parent now and drop the snapshot after the
+ # rm, but only when it is one of ours, never one the caller supplied.
+ my $parent = eval { rbd_volume_parent($scfg, $storeid, $name) };
+ $copy_parent = $parent if $parent && ($parent->{snapshot} // '') =~ /^__copy_/;
+
+ # Its flatten may still be running in the manager, holding the image; cancel it
+ # first, so the rm below does not fail. That includes a copy from a
+ # caller-supplied snapshot. Not looked up for a linked clone of a template.
+ if ($parent && ($parent->{snapshot} // '') ne '__base__') {
+ my $task = eval { rbd_flatten_task($scfg, $storeid, $name) };
+ warn $@ if $@;
+ ($task_id) = $task ? (($task->{id} // '') =~ m/^([\w-]+)$/) : ();
+ }
+ }
+ if (defined($task_id)) {
+ eval {
+ run_command(ceph_cmd($scfg, $storeid, 'rbd', 'task', 'cancel', $task_id),
+ errmsg => "cancelling rbd flatten of '$name' failed", outfunc => sub { });
+ };
+ warn $@ if $@;
+ }
+
my $snaps = rbd_ls_snap($scfg, $storeid, $name);
foreach my $snap (keys %$snaps) {
if ($snaps->{$snap}->{protected}) {
@@ -806,6 +1328,19 @@ sub free_image {
$cmd = $rbd_cmd->($scfg, $storeid, 'rm', $name);
run_rbd_command($cmd, errmsg => "rbd rm '$name' error");
+ if ($copy_parent) {
+ # Best effort: another unfinished copy may still hold the same snapshot.
+ eval {
+ # The parent may live in another pool or namespace than this storage.
+ my $spec = join('/', grep { defined && length } $copy_parent->{pool},
+ $copy_parent->{pool_namespace}, $copy_parent->{image});
+ my $c = $rbd_cmd->(
+ $scfg, $storeid, 'snap', 'rm', $spec, '--snap', $copy_parent->{snapshot},
+ );
+ run_rbd_command($c, errmsg => "rbd snap rm error", outfunc => sub { });
+ };
+ }
+
return undef;
}
@@ -1027,6 +1562,10 @@ sub volume_has_feature {
copy => { base => 1, current => 1, snap => 1 },
sparseinit => { base => 1, current => 1 },
rename => { current => 1 },
+ # The copy is produced from an RBD snapshot, so it comes from a static point
+ # in time and needs no host-side mirror to stay consistent while the source
+ # keeps changing; see copy_image_start().
+ 'copy-offload-atomic' => { base => 1, current => 1, snap => 1 },
};
my ($vtype, $name, $vmid, $basename, $basevmid, $isBase) = $class->parse_volname($volname);
diff --git a/src/test/copy_offload_naming_test.pm b/src/test/copy_offload_naming_test.pm
new file mode 100644
index 0000000..5f6d99e
--- /dev/null
+++ b/src/test/copy_offload_naming_test.pm
@@ -0,0 +1,82 @@
+package PVE::Storage::TestCopyOffloadNaming;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use PVE::Storage;
+use PVE::Storage::Plugin;
+use Test::More;
+
+# The names copy_image_start() parks its placeholder under must satisfy two opposing
+# properties at once, and a mistake in either is easy to miss:
+#
+# 1. Invisible to the volume lister. If the lister accepts the name, the placeholder
+# shows up as an unused disk of that VM, and stays there for good if the copy
+# dies mid-flight.
+# 2. Still reserving the disk number. The caller drops the storage lock between
+# prepare() and start(), so if the parked name stops reserving, a concurrent
+# allocation can take it, and the failing copy's rollback then frees somebody
+# else's volume.
+#
+# The two properties come from two different regexes, which is why a name can satisfy
+# one and not the other:
+#
+# - listers are anchored (rbd_ls: m/^(?:vm|base)-(\d+)-/,
+# LvmThin list_images: m/^(vm|base)-(\d+)-/)
+# - $get_vm_disk_number is unanchored (Plugin.pm)
+#
+# So a prefix is invisible but still reserves, and a suffix is the opposite on both
+# counts. This test pins that, because nothing about the naming looks load-bearing at a
+# glance and a rename to 'vm-101-disk-0.copytmp' would reintroduce both bugs without
+# failing anything else.
+
+# The anchored patterns the listers use, kept here so a change to either one is caught
+# rather than narrowing what these names protect without notice.
+my $rbd_lister_re = qr/^(?:vm|base)-(\d+)-/;
+my $lvmthin_lister_re = qr/^(vm|base)-(\d+)-/;
+
+my $tests = [
+ # [ name, listed?, reserves a disk number? ]
+ ['vm-101-disk-0', 1, 1], # the real volume: listed and reserving
+ ['copytmp-vm-101-disk-0', 0, 1], # parked placeholder
+ ['copynew-vm-101-disk-0', 0, 1], # staging clone
+ ['vm-101-disk-0.copytmp', 1, 1], # the SUFFIX form: listed => phantom. Do not use.
+];
+
+plan tests => scalar($tests->@*) * 3 + 2;
+
+for my $t ($tests->@*) {
+ my ($name, $listed, $reserves) = $t->@*;
+
+ is(!!($name =~ $rbd_lister_re), !!$listed, "rbd lister: '$name' listed = " . ($listed ? 1 : 0));
+ is(
+ !!($name =~ $lvmthin_lister_re), !!$listed,
+ "lvmthin lister: '$name' listed = " . ($listed ? 1 : 0),
+ );
+
+ # Unanchored: this is the reservation half.
+ is(
+ !!($name =~ qr/(vm|base)-101-disk-(\d+)/), !!$reserves,
+ "'$name' reserves a disk number = " . ($reserves ? 1 : 0),
+ );
+}
+
+# The property that matters, checked through the real allocator rather than a regex:
+# with only the parked placeholder present, disk 0 must not be handed out again.
+my $scfg = { type => 'rbd' };
+is(
+ PVE::Storage::Plugin::get_next_vm_diskname(['vm-101-disk-0'], 'st', 101, undef, $scfg),
+ 'vm-101-disk-1',
+ 'the real volume reserves its disk number',
+);
+is(
+ PVE::Storage::Plugin::get_next_vm_diskname(
+ ['copytmp-vm-101-disk-0'], 'st', 101, undef, $scfg,
+ ),
+ 'vm-101-disk-1',
+ 'a parked placeholder ALONE still reserves the disk number',
+);
+
+done_testing();
diff --git a/src/test/copy_offload_rbd_status_test.pm b/src/test/copy_offload_rbd_status_test.pm
new file mode 100644
index 0000000..73701e1
--- /dev/null
+++ b/src/test/copy_offload_rbd_status_test.pm
@@ -0,0 +1,114 @@
+package PVE::Storage::TestCopyOffloadRbdStatus;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use PVE::Storage::RBDPlugin;
+use PVE::CephConfig;
+use Test::More;
+
+# copy_image_status() must treat the image parent link, not the manager flatten task,
+# as the completion signal. A fast flatten of a small image can vanish from
+# `rbd task list` between the parent read and the task look-up, so a missing task while
+# the image still shows a parent is ambiguous: re-read the parent before declaring the
+# flatten dead. This pins that race (a copy that finished must not be reported as a dead
+# flatten; this was seen on a concurrent multi-disk clone) plus the
+# unambiguous states around it.
+
+my $scfg = { type => 'rbd', pool => 'testpool' };
+my $storeid = 'rbd-a';
+my $volname = 'vm-100-disk-0';
+
+# Scripted command output, consumed in call order.
+my @info_json; # what each 'rbd info' returns (parent present or not)
+my @task_json; # what each 'ceph rbd task list' returns
+
+{
+ no warnings 'redefine';
+
+ # Keep $rbd_cmd from touching the ceph config / filesystem.
+ *PVE::CephConfig::ceph_connect_option = sub { return (); };
+
+ # Every rbd subcommand copy_image_status touches goes through run_rbd_command:
+ # info -> the scripted parent state
+ # ls -> '[]' (rbd_volume_exists: the parked placeholder never exists here)
+ # other -> succeed silently (snap rm / rm are best-effort cleanup)
+ *PVE::Storage::RBDPlugin::run_rbd_command = sub {
+ my ($cmd, %param) = @_;
+ my $op = join(' ', @$cmd);
+ my $out = $param{outfunc} // sub { };
+ if ($op =~ /\binfo\b/) {
+ $out->(shift(@info_json) // '{}');
+ } elsif ($op =~ /\bls\b/) {
+ $out->('[]');
+ }
+ return 0;
+ };
+
+ # $rbd_flatten_task runs `ceph rbd task list` through run_command.
+ *PVE::Storage::RBDPlugin::run_command = sub {
+ my ($cmd, %param) = @_;
+ my $out = $param{outfunc} // sub { };
+ my $next = shift(@task_json) // '[]';
+ die "mgr unavailable\n" if $next eq 'DIE';
+ $out->($next);
+ return 0;
+ };
+}
+
+my $PARENT = '{"parent":{"pool":"testpool","image":"src","snapshot":"__copy_vm-100-disk-0"}}';
+my $NOPARENT = '{}';
+my $A_TASK =
+ '[{"refs":{"action":"flatten","image_name":"vm-100-disk-0","pool_name":"testpool"},"progress":0.5}]';
+my $NO_TASK = '[]';
+
+sub status {
+ return PVE::Storage::RBDPlugin->copy_image_status($scfg, $storeid, $volname, undef);
+}
+
+# 1. Independent on the first poll: no parent -> complete.
+@info_json = ($NOPARENT);
+@task_json = ();
+is(status()->{state}, 'complete', 'no parent on the first poll => complete');
+
+# 2. Flatten still running: parent + a live task -> pending (with progress).
+@info_json = ($PARENT);
+@task_json = ($A_TASK);
+my $st = status();
+is($st->{state}, 'pending', 'parent + a running flatten task => pending');
+is($st->{progress}, 50, ' progress surfaced from the task');
+
+# 3. The race: parent seen, task list momentarily empty, re-read shows the flatten just
+# finished. Must be complete, not a fatal "flatten no longer running".
+@info_json = ($PARENT, $NOPARENT); # info#1 parent, info#2 (re-read) parent gone
+@task_json = ($NO_TASK); # task look-up empty
+is(status()->{state}, 'complete',
+ 'empty task + parent-cleared-on-reread => complete (the fixed race)');
+
+# 4. Dead flatten: parent persists across the re-read and no task on either
+# look-up -> still fails, as before.
+@info_json = ($PARENT, $PARENT);
+@task_json = ($NO_TASK, $NO_TASK); # first lookup + the guard lookup both empty
+my $died = !eval { status(); 1 };
+ok($died, 'parent persists + no task on both look-ups => dies (real failure still fails)');
+like($@, qr/no longer running and the image is still a clone/, ' with the flatten-dead error');
+
+# 5. A failed task look-up (manager failover) is not a dead flatten: keep polling.
+@info_json = ($PARENT);
+@task_json = ('DIE');
+{
+ local $SIG{__WARN__} = sub { };
+ is(status()->{state}, 'pending', 'task list fails => pending, not a dead flatten');
+}
+@info_json = ($PARENT, $PARENT);
+@task_json = ($NO_TASK, 'DIE');
+{
+ local $SIG{__WARN__} = sub { };
+ is(status()->{state}, 'pending', 'guard look-up fails => pending, not a dead flatten');
+}
+
+done_testing();
+
+1;
diff --git a/src/test/run_plugin_tests.pl b/src/test/run_plugin_tests.pl
index 57e3140..c8db425 100755
--- a/src/test/run_plugin_tests.pl
+++ b/src/test/run_plugin_tests.pl
@@ -26,6 +26,8 @@ my $res = $harness->runtests(
"plugin_load_test.pm",
"plugin_properties_test.pm",
"copy_offload_test.pm",
+ "copy_offload_naming_test.pm",
+ "copy_offload_rbd_status_test.pm",
);
exit -1 if !$res || $res->{failed} || $res->{parse_errors};
--
2.55.0
^ permalink raw reply related [flat|nested] 7+ messages in thread
* [RFC PATCH storage v2 3/6] dir: implement copy-offload via reflink (FICLONE)
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 ` Ciro Iriarte
2026-11-26 16:57 ` [RFC PATCH storage v2 4/6] btrfs, lvmthin: implement copy-offload (atomic class) Ciro Iriarte
` (2 subsequent siblings)
5 siblings, 0 replies; 7+ messages in thread
From: Ciro Iriarte @ 2026-11-26 16:57 UTC (permalink / raw)
To: pve-devel
From: Ciro Iriarte <ciro.iriarte+software@gmail.com>
A filesystem with FICLONE support (XFS with reflink=1, btrfs, ZFS with
block cloning) can make a full copy by sharing extents copy-on-write.
The copy is independent immediately, since the extents are reference
counted, so copy_image_status() reports complete on the first poll.
Today a full clone on such a directory storage copies every byte through
qemu-img convert.
copy_image_check() refuses the following, so the clone takes the
host-side path:
- a snapshot source or a format conversion, neither of which a byte copy
can do
- a qcow2 with a backing file: a byte copy inherits the dependency and
breaks once the base is removed
- a qcow2 with internal snapshots: they would carry over into a clone
whose configuration has none
- a target on another filesystem, or a filesystem without reflink
support, detected by reflinking a one-byte scratch file: for XFS it
depends on how the filesystem was created
prepare creates the target file rather than only choosing a name, as the
caller releases the storage lock before start. A failed start truncates
it instead of removing it, so the name stays reserved until the caller's
rollback frees it. start uses 'cp --reflink=always', so a filesystem
without reflink fails instead of turning into a full copy inside a guest
freeze.
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(); under API 17
parse_volname() returns 'vm-vol', so the 'images' comparison carried
over from v1 would never advertise the feature
* new copy_image_check(), also called by prepare(). It probes reflink
support, so a filesystem without it falls back to the host copy
* refuses a qcow2 with internal snapshots
* a failed start truncates the target instead of removing it, keeping
the name reserved for the caller's rollback
src/PVE/Storage/DirPlugin.pm | 193 +++++++++++++++++++++++++++++++++++
1 file changed, 193 insertions(+)
diff --git a/src/PVE/Storage/DirPlugin.pm b/src/PVE/Storage/DirPlugin.pm
index 397d4fe..f5f227f 100644
--- a/src/PVE/Storage/DirPlugin.pm
+++ b/src/PVE/Storage/DirPlugin.pm
@@ -8,6 +8,7 @@ use Encode qw(decode encode);
use File::Path;
use File::Spec;
use IO::File;
+use JSON;
use POSIX;
use PVE::Storage::Plugin;
@@ -44,6 +45,7 @@ sub plugindata {
'advanced-properties' => {
preallocation => 1,
'snapshot-as-volume-chain' => 1,
+ 'copy-offload-timeout' => 1,
},
'hidden-properties' => {
bwlimit => 1,
@@ -89,6 +91,8 @@ sub options {
bwlimit => { optional => 1 },
preallocation => { optional => 1 },
'snapshot-as-volume-chain' => { optional => 1, fixed => 1 },
+ 'copy-offload' => { optional => 1 },
+ 'copy-offload-timeout' => { optional => 1 },
};
}
@@ -317,4 +321,193 @@ sub volume_qemu_snapshot_method {
return $scfg->{'snapshot-as-volume-chain'} ? 'mixed' : 'qemu';
}
+# qemu_img_info() returns raw JSON text, so decode before use. Returns the decoded
+# info, or undef when the image cannot be inspected.
+my sub qcow2_info {
+ my ($path) = @_;
+ my $json = eval { PVE::Storage::Common::qemu_img_info($path, undef, 10) };
+ return undef if $@ || !$json;
+ my $info = eval { decode_json($json) };
+ return undef if $@ || ref($info) ne 'HASH';
+ return $info;
+}
+
+sub volume_has_feature {
+ my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running, $opts) = @_;
+
+ if ($feature eq 'copy-offload-atomic') {
+ # reflink clones a whole file; there is no way to pick a snapshot out of one
+ return 0 if $snapname;
+
+ my ($vtype, undef, undef, undef, undef, undef, $format) =
+ eval { $class->parse_volname($volname) };
+ return 0 if $@ || !defined($vtype);
+ return 0 if !PVE::Storage::Common::vtype_matches($vtype, 'vm-vol');
+ return 0 if $format ne 'raw' && $format ne 'qcow2';
+
+ # whether this file can be copied to a given target is copy_image_check()'s call
+ return 1;
+ }
+
+ return $class->SUPER::volume_has_feature(
+ $scfg, $feature, $storeid, $volname, $snapname, $running, $opts,
+ );
+}
+
+# ---- storage-offloaded full copy via reflink -------------------------------------
+#
+# A filesystem that supports FICLONE (XFS with reflink=1, btrfs, ZFS with block
+# cloning) can produce a full copy by sharing extents copy-on-write. Unlike an RBD
+# clone or a ZFS clone-from-snapshot, the result is independent straight away: the
+# extents are reference counted, so deleting the source does not affect the copy.
+#
+# There is no background work, so copy_image_status() reports 'complete' on the
+# first poll.
+
+# Same filesystem? FICLONE cannot cross one, and the caller may be copying between
+# two different storages that happen to be directories.
+my sub same_filesystem {
+ my ($a, $b) = @_;
+ my $da = (stat($a))[0];
+ my $db = (stat($b))[0];
+ return defined($da) && defined($db) && $da == $db;
+}
+
+# The nearest existing directory at or above $dir: the target's per-VM directory may
+# not exist yet when the pair is checked.
+my sub existing_dir {
+ my ($dir) = @_;
+ $dir =~ s|/[^/]+$|| while length($dir) > 1 && !-d $dir;
+ return $dir;
+}
+
+# Whether the filesystem holding $dir can reflink, found by trying it on a one-byte
+# scratch file: there is no generic way to ask, and for XFS it depends on how the
+# filesystem was created. Returns undef or the reason it cannot.
+sub reflink_unsupported {
+ my ($class, $dir) = @_;
+
+ my ($d) = $dir =~ m|^(/.*)$| or return "invalid directory '$dir'";
+ my $src = "$d/.pve-reflink-probe-$$";
+ my $dst = "$src.clone";
+
+ my $fh = IO::File->new($src, O_WRONLY | O_CREAT | O_EXCL, 0600)
+ or return "cannot create a scratch file in '$d' - $!";
+ print $fh "x";
+ $fh->close();
+
+ my $ok = eval {
+ PVE::Tools::run_command(
+ ['/bin/cp', '--reflink=always', '--', $src, $dst],
+ outfunc => sub { },
+ errfunc => sub { },
+ );
+ 1;
+ };
+ unlink($src, $dst);
+
+ return $ok ? undef : "the filesystem of '$d' does not support reflinks";
+}
+
+sub copy_image_check {
+ my ($class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts) = @_;
+
+ return "reflink cannot copy from a snapshot" if defined($snap);
+
+ 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');
+
+ # FICLONE copies bytes; it cannot convert between formats.
+ my $target_format = $opts->{format} // $format;
+ return "cannot convert '$format' to '$target_format'" if $target_format ne $format;
+
+ my $path = $class->filesystem_path($scfg, $volname);
+
+ if ($format eq 'qcow2') {
+ my $info = qcow2_info($path) // return "cannot inspect '$volname'";
+ # A qcow2 with a backing file is not independent, and a byte-identical copy of
+ # it inherits that dependency: it would pass qemu-img check and then break
+ # when the base is removed. Only a real convert can flatten it.
+ return "'$volname' has a backing file" if $info->{'backing-filename'};
+ # Internal snapshots would travel with a byte copy: hidden space and old data in
+ # a clone whose config has no snapshots. qemu-img convert drops them.
+ return "'$volname' has internal snapshots"
+ if ref($info->{snapshots}) eq 'ARRAY' && scalar($info->{snapshots}->@*);
+ }
+
+ my $target_dir = existing_dir($class->get_subdir($target_scfg, 'images'));
+ return "source and target are on different filesystems"
+ if !same_filesystem($path, $target_dir);
+
+ return $class->reflink_unsupported($target_dir);
+}
+
+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 $path = $class->filesystem_path($scfg, $volname);
+ my $target_dir = $class->get_subdir($target_scfg, 'images') . "/$target_vmid";
+ mkpath $target_dir;
+
+ # mkpath may have created it on another mount than its parent (an automounted or
+ # bind-mounted VM directory), so check the directory the file lands in.
+ die "copy offload requires source and target on the same filesystem\n"
+ if !same_filesystem($path, $target_dir);
+
+ # 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);
+
+ # Reserve the name by creating the file. The caller drops the storage lock between
+ # prepare and start, so a name that was only chosen could be taken by a concurrent
+ # allocation, and the caller's rollback would then delete somebody else's volume.
+ # An empty file costs nothing and makes the target freeable.
+ my $target_path = "$target_dir/$name";
+ my $fh = IO::File->new($target_path, O_WRONLY | O_CREAT | O_EXCL, 0640)
+ or die "unable to reserve '$target_path' - $!\n";
+ close($fh);
+
+ return "$target_vmid/$name";
+}
+
+sub copy_image_start {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_volname, $snap,
+ ) = @_;
+
+ my $src = $class->filesystem_path($scfg, $volname);
+ my $dst = $class->filesystem_path($target_scfg, $target_volname);
+
+ # --reflink=always so an unsupported filesystem fails instead of turning this into
+ # a full byte copy that blocks the caller, which may be holding a guest frozen.
+ # On failure the target is truncated, not removed: it is the caller's reservation of
+ # the name until its rollback frees it.
+ eval { PVE::Tools::run_command(['/bin/cp', '--reflink=always', '--', $src, $dst]) };
+ if (my $err = $@) {
+ truncate($dst, 0);
+ die "reflink copy of '$volname' failed - $err";
+ }
+
+ return;
+}
+
+sub copy_image_status {
+ my ($class, $scfg, $storeid, $volname, $source) = @_;
+
+ # FICLONE is synchronous and the extents are reference counted, so the copy is
+ # already independent of its source. Nothing to poll and nothing to clean up.
+ return { state => 'complete' };
+}
+
1;
--
2.55.0
^ permalink raw reply related [flat|nested] 7+ messages in thread
* [RFC PATCH storage v2 4/6] btrfs, lvmthin: implement copy-offload (atomic class)
2026-11-26 16:56 [RFC PATCH storage/qemu-server/docs v2 0/6] offload full clone to the storage backend Ciro Iriarte
` (2 preceding siblings ...)
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
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
5 siblings, 0 replies; 7+ messages in thread
From: Ciro Iriarte @ 2026-11-26 16:57 UTC (permalink / raw)
To: pve-devel
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
^ permalink raw reply related [flat|nested] 7+ messages in thread
* [RFC PATCH qemu-server v2 5/6] use storage copy-offload for full clone
2026-11-26 16:56 [RFC PATCH storage/qemu-server/docs v2 0/6] offload full clone to the storage backend Ciro Iriarte
` (3 preceding siblings ...)
2026-11-26 16:57 ` [RFC PATCH storage v2 4/6] btrfs, lvmthin: implement copy-offload (atomic class) Ciro Iriarte
@ 2026-11-26 16:57 ` 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
5 siblings, 0 replies; 7+ messages in thread
From: Ciro Iriarte @ 2026-11-26 16:57 UTC (permalink / raw)
To: pve-devel
From: Ciro Iriarte <ciro.iriarte+software@gmail.com>
Use the pve-storage copy-offload hook for full clones. An offloaded copy
replaces both halves of a full clone in clone_disk(), the allocation and
the data copy, since the backend creates the target itself. The decision
and the offloaded copy live in two helpers, and clone_disk() picks
between linked clone, offload and the existing path.
For a running guest, consistency across disks is a VM-level property:
clone_vm() calls clone_disk() per drive, and BlockJob::monitor() cuts
all mirrors over in one freeze. An offloaded copy started per disk would
capture each disk at a different instant. So for the attached disks of a
running guest, clone_disk() only reserves the target and defers the
start, which captures the point in time. monitor() gains an on_frozen
callback, run at the cut-over, which starts the deferred copies.
Offloaded and mirrored disks are then captured at the same instant. The
copies are waited on afterwards, with the guest running.
Every cut-over gets the callback, including the one triggered by a final
cloud-init drive, and starting is idempotent. When every disk is
offloaded there is no cut-over, so clone_vm() quiesces the guest itself.
Both use the new BlockJob::run_with_guest_quiesced(), which takes over
the freeze and suspend logic from monitor() and thaws or resumes the
guest before re-raising an error. If the guest can be neither frozen nor
suspended, the mirrors are still cut over, as on master, but the
deferred copies are not started and the clone fails: their targets are
only reservations, so a host-side copy is no longer possible. A live
disk move has no freeze to defer into, so offload is skipped there
without asking the storage.
Four changes from monitor()'s old behaviour also apply to a clone
without offload:
* when the guest agent's freeze fails, the guest is suspended instead of
continuing unquiesced
* a guest that is already paused stays paused instead of being resumed
afterwards; one whose state cannot be queried is not quiesced,
matching what master does when the suspend fails
* a failed thaw or resume is reported with log_warn(), so the task ends
with a warning instead of a plain message; failing it would discard a
finished clone, and on Windows the agent's freeze is limited to about
ten seconds, after which the thaw reports an error
* when a failed freeze cannot be undone either, the guest is suspended
and the thaw is retried after the resume
run_guest_quiesce_tests.pl covers these paths.
A snapshot or a detached disk cannot change during the copy, so its copy
runs right away. A deferred copy records the source's size, as its
target is only a reservation until copy_image_start() runs. 'bulk' falls
back to the host-side path for an attached disk of a running guest: it
smears over a changing source, and the mirror convergence it would need
is not implemented. cloudinit, efidisk0 and tpmstate0 are never
offloaded.
Signed-off-by: Ciro Iriarte <ciro.iriarte+software@gmail.com>
---
Changes in v2:
* rebased onto current master, where the data copy moved into
clone_disk_copy_data(); the goto that commit removed is not brought
back: the offload decision and copy are two helpers, and clone_disk()
picks between linked clone, offload and the existing path
* a deferred copy records the source size in the config; v1 recorded
the size of the placeholder
* the cut-over triggered by a final cloud-init drive also starts the
deferred copies; in v1 they got a second freeze of their own
* only the attached disks of a running guest are deferred; v1 also
deferred a copy from a snapshot and suspended the guest for nothing
* the quiesce logic moved into BlockJob::run_with_guest_quiesced(),
shared by monitor() and the all-offloaded case. A failed guest agent
freeze now falls back to suspend, including clones without offload.
If that fails too, deferred copies are not started and the clone
fails.
* a guest that is already paused is left paused; a failed thaw or
resume ends the task with a warning (log_warn) rather than a plain
message, and if a failed freeze cannot be undone, the thaw is retried
after the resume. These also apply to clones without offload. New
run_guest_quiesce_tests.pl
* a guest whose state cannot be queried is not quiesced, so a paused
guest is never resumed by mistake
* a live disk move no longer queries the storage, as it cannot defer
* deferred copies print their progress while being waited on
* needs a libpve-storage-perl that ships APIVER 18 (1/6); debian/control
is not bumped here
src/PVE/API2/Qemu.pm | 17 +++
src/PVE/QemuServer.pm | 225 ++++++++++++++++++++++++++--
src/PVE/QemuServer/BlockJob.pm | 119 +++++++++++----
src/test/Makefile | 5 +-
src/test/run_guest_quiesce_tests.pl | 154 +++++++++++++++++++
5 files changed, 479 insertions(+), 41 deletions(-)
create mode 100755 src/test/run_guest_quiesce_tests.pl
diff --git a/src/PVE/API2/Qemu.pm b/src/PVE/API2/Qemu.pm
index 2119e69e..44c9bc64 100644
--- a/src/PVE/API2/Qemu.pm
+++ b/src/PVE/API2/Qemu.pm
@@ -4902,6 +4902,9 @@ __PACKAGE__->register_method({
my $newvollist = [];
my $jobs = {};
+ # storage-offloaded copies whose start is deferred into the guest freeze, so
+ # that every disk of a running VM is captured at the same instant
+ my $deferred_copies = [];
eval {
local $SIG{INT} = local $SIG{TERM} = local $SIG{QUIT} = local $SIG{HUP} =
@@ -4953,6 +4956,7 @@ __PACKAGE__->register_method({
$completion,
$oldconf->{agent},
$clonelimit,
+ $deferred_copies,
);
$newconf->{$opt} = PVE::QemuServer::print_drive($newdrive);
@@ -4961,6 +4965,19 @@ __PACKAGE__->register_method({
$i++;
}
+ # Anything still unstarted means there was no mirror cutover to
+ # piggyback the freeze on (every disk was offloaded), so freeze
+ # here. Keyed on the copies themselves rather than on %$jobs, so it
+ # cannot double-start if the job bookkeeping changes.
+ if (grep { !$_->{started} } @$deferred_copies) {
+ PVE::QemuServer::freeze_and_run_deferred_copies(
+ $storecfg, $vmid, $oldconf->{agent}, $deferred_copies,
+ );
+ }
+
+ # the guest is running again; the data movement is waited for here
+ PVE::QemuServer::wait_deferred_copies($storecfg, $deferred_copies);
+
delete $newconf->{lock};
# do not write pending changes
diff --git a/src/PVE/QemuServer.pm b/src/PVE/QemuServer.pm
index 1d665877..8d7b84d6 100644
--- a/src/PVE/QemuServer.pm
+++ b/src/PVE/QemuServer.pm
@@ -7991,7 +7991,10 @@ my sub clone_disk_check_io_uring {
}
my sub clone_disk_copy_data {
- my ($storecfg, $source, $dest, $use_drive_mirror, $jobs, $completion, $qga, $bwlimit) = @_;
+ my (
+ $storecfg, $source, $dest, $use_drive_mirror, $jobs, $completion, $qga, $bwlimit,
+ $on_frozen,
+ ) = @_;
my ($vmid, $drive, $size, $snapname) = $source->@{qw(vmid drive size snapname)};
my ($newvmid, $newvolid, $dst_drivename, $dst_format) =
@@ -8006,6 +8009,9 @@ my sub clone_disk_copy_data {
my $mirror_opts = {};
$mirror_opts->{'guest-agent'} = $qga;
$mirror_opts->{bwlimit} = $bwlimit if defined($bwlimit);
+ # Start any deferred offloaded copies inside the freeze this mirror's
+ # completion takes, putting every disk of the VM at one point in time.
+ $mirror_opts->{'on-frozen'} = $on_frozen if $on_frozen;
PVE::QemuServer::BlockJob::mirror(
$source_info,
$dest_info,
@@ -8051,8 +8057,180 @@ my sub clone_disk_copy_data {
return;
}
+# Start every deferred storage-offloaded copy. Must be called with the guest frozen (or
+# suspended): the start is what captures each copy's point in time, so doing them all here
+# is what makes a multi-disk clone consistent.
+#
+# One batch, so that a backend able to capture several volumes at once
+# (copy_images_start()) does so.
+#
+# Kept cheap: the guest is stalled for the duration. The data movement runs
+# afterwards and is waited for by wait_deferred_copies(), with the guest running again.
+sub run_deferred_copies {
+ my ($storecfg, $deferred_copies, $quiesced) = @_;
+
+ return if !$deferred_copies;
+
+ # idempotent: never start a copy twice
+ my $pending = [grep { !$_->{started} } @$deferred_copies];
+ return if !scalar(@$pending);
+
+ # Without a freeze or suspend the starts would land at different instants while the
+ # guest writes, which is what deferring them is meant to prevent.
+ die "guest could not be frozen or suspended - not starting the offloaded copies\n"
+ if !$quiesced;
+
+ # vdisk_copy_start_group() flags each copy as it starts it, so a failure partway
+ # through leaves an accurate record of what is running.
+ PVE::Storage::vdisk_copy_start_group($storecfg, $pending);
+
+ return;
+}
+
+# Wait for the deferred copies to become independent of their sources. Runs with the
+# guest already thawed: only the starts need the freeze, not the data movement.
+sub wait_deferred_copies {
+ my ($storecfg, $deferred_copies) = @_;
+
+ return if !$deferred_copies;
+
+ for my $copy (@$deferred_copies) {
+ # Never accept an unstarted copy: its target is allocated but its
+ # content is undefined, so returning it would hand out a corrupt disk.
+ die "internal error - offloaded copy of '$copy->{source}' was never started\n"
+ if !$copy->{started};
+
+ print("waiting for offloaded copy of '$copy->{source}' to become independent\n");
+ PVE::Storage::vdisk_copy_wait(
+ $storecfg, $copy->{target}, $copy->{source}, sub { print("copy progress: $_[0]%\n") },
+ );
+ }
+}
+
+# Freeze the guest, start the deferred copies, thaw. Used when a clone has no mirror
+# jobs to rendezvous with (every disk was offloaded), so there is no
+# BlockJob::monitor() freeze to piggyback on. Quiesces the same way monitor() does.
+sub freeze_and_run_deferred_copies {
+ my ($storecfg, $vmid, $qga, $deferred_copies) = @_;
+
+ return if !$deferred_copies || !scalar(@$deferred_copies);
+
+ PVE::QemuServer::BlockJob::run_with_guest_quiesced(
+ $vmid, $qga, sub { run_deferred_copies($storecfg, $deferred_copies, @_) },
+ );
+
+ return;
+}
+
+# The copy-offload class to use for a full clone of this disk, or undef for the host-side
+# copy, and whether its start has to be deferred into the guest freeze.
+my sub clone_disk_offload_class {
+ my ($storecfg, $source, $dest, $storeid, $deferred_copies) = @_;
+
+ my ($running, $src_drivename, $drive, $snapname) =
+ $source->@{qw(running drivename drive snapname)};
+ my $dst_drivename = $dest->{drivename};
+
+ # Not for the special drives: cloudinit is regenerated rather than copied, efidisk0 is
+ # copied with a size-limited qemu-img dd, and tpmstate0 is allocated at the size its
+ # TPM version needs. An opaque backend copy reproduces none of that. Either side being
+ # special is disqualifying.
+ my $special_re = qr/^(?:efidisk0|tpmstate0)$/;
+ return if drive_is_cloudinit($drive);
+ return if defined($dst_drivename) && $dst_drivename =~ $special_re;
+ return if defined($src_drivename) && $src_drivename =~ $special_re;
+
+ # Multi-disk consistency is a VM-level property here: clone_vm() calls clone_disk()
+ # once per drive, and BlockJob::monitor() cuts every mirror over in one freeze. The
+ # current state of a running guest's attached disk changes under the copy, so its start,
+ # which fixes its point in time, waits for that freeze. A snapshot or a detached
+ # disk does not change and is copied right away.
+ my $unused = defined($src_drivename) && $src_drivename =~ /^unused/;
+ my $defer = $running && !$snapname && !$unused;
+ # deferring needs a caller that runs the freeze, such as clone_vm(); a live disk move
+ # has none, so do not even ask the storage
+ return if $defer && !$deferred_copies;
+
+ my $class = PVE::Storage::copy_offload_class(
+ $storecfg, $drive->{file}, $storeid, $snapname, $running, { format => $dest->{format} },
+ );
+ return if !$class;
+
+ # 'bulk' smears over a changing source and would need a bitmap-seeded mirror to
+ # converge, which is not implemented, so take the host-side path instead.
+ return if $defer && $class ne 'atomic';
+
+ return ($class, $defer);
+}
+
+# Full clone through the storage backend (pve-storage copy_image). It replaces both the
+# allocation and the host-side copy, since the backend creates the target itself. Returns
+# the new volid and, for a deferred copy, the size to record: until its start, the target
+# is only a reservation.
+my sub clone_disk_offload {
+ my (
+ $storecfg, $source, $dest, $storeid, $class, $defer, $newvollist, $jobs, $completion,
+ $qga, $deferred_copies, $on_frozen,
+ ) = @_;
+
+ my ($vmid, $drive, $snapname) = $source->@{qw(vmid drive snapname)};
+ my $newvmid = $dest->{vmid};
+ my $opts = { format => $dest->{format} };
+
+ if ($defer) {
+ print("offloading full copy to storage backend ($class, deferred)\n");
+
+ my $newvolid = PVE::Storage::vdisk_copy_prepare(
+ $storecfg, $drive->{file}, $storeid, $newvmid, $snapname, $opts,
+ );
+ push @$newvollist, $newvolid;
+
+ # recorded as plain volids: the starts are issued as one batch, so that a backend
+ # able to group them can capture every disk at a single instant
+ push @$deferred_copies,
+ { source => $drive->{file}, target => $newvolid, snap => $snapname };
+
+ print("allocated target volume '$newvolid', copy starts at freeze\n");
+
+ # On the last disk with mirror jobs pending, the cut-over happens here: nothing
+ # after this calls monitor().
+ if (($completion && $completion eq 'complete') && scalar(keys %$jobs) > 0) {
+ PVE::QemuServer::BlockJob::monitor(
+ vm_qmp_peer($vmid), $newvmid, $jobs, $completion, $qga, undef, $on_frozen,
+ );
+ }
+
+ return ($newvolid, scalar(PVE::Storage::volume_size_info($storecfg, $drive->{file}, 10)));
+ }
+
+ print("offloading full copy to storage backend ($class)\n");
+
+ my $newvolid = PVE::Storage::vdisk_copy(
+ $storecfg,
+ $drive->{file},
+ $storeid,
+ $newvmid,
+ $snapname,
+ $opts,
+ sub { print("copy progress: $_[0]%\n") },
+ );
+ push @$newvollist, $newvolid;
+
+ print("created target volume '$newvolid' on the backend\n");
+
+ PVE::Storage::activate_volumes($storecfg, [$newvolid]);
+
+ return ($newvolid, undef);
+}
+
+# $deferred_copies is an optional arrayref collecting storage-offloaded copies whose
+# start must happen inside the caller's guest freeze; see clone_disk_offload() and
+# run_deferred_copies(). Without it, a running source is never offloaded.
sub clone_disk {
- my ($storecfg, $source, $dest, $full, $newvollist, $jobs, $completion, $qga, $bwlimit) = @_;
+ my (
+ $storecfg, $source, $dest, $full, $newvollist, $jobs, $completion, $qga, $bwlimit,
+ $deferred_copies,
+ ) = @_;
my ($vmid, $running) = $source->@{qw(vmid running)};
my ($src_drivename, $drive, $snapname) = $source->@{qw(drivename drive snapname)};
@@ -8077,26 +8255,45 @@ sub clone_disk {
die "cannot move TPM state while VM is running\n"
if $use_drive_mirror && $src_drivename eq 'tpmstate0';
- my $newvolid;
+ my ($newvolid, $offload_size);
print "create " . ($full ? 'full' : 'linked') . " clone of drive ";
print "$src_drivename " if $src_drivename;
print "($drive->{file})\n";
- if (!$full) {
- $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newvmid, $snapname);
- push @$newvollist, $newvolid;
- } else {
- my ($src_storeid) = PVE::Storage::parse_volume_id($drive->{file});
- my $storeid = $storage || $src_storeid;
+ # A full clone's target storage and format, and whether the backend copies it.
+ my ($src_storeid, $storeid, $dst_format, $offload_class, $defer, $on_frozen);
+ if ($full) {
+ ($src_storeid) = PVE::Storage::parse_volume_id($drive->{file});
+ $storeid = $storage || $src_storeid;
- my $dst_format = resolve_dst_disk_format($storecfg, $storeid, $drive->{file}, $format);
+ $dst_format = resolve_dst_disk_format($storecfg, $storeid, $drive->{file}, $format);
if ($format && $format ne $dst_format) {
warn "format '$format' is not supported by the target storage '$storeid' - using"
. " '$dst_format' instead\n";
}
$dest->{format} = $dst_format;
+ # Deferred offloaded copies start inside whichever freeze cuts the mirror jobs
+ # over (this or a later disk's, or clone_vm()'s own when there is none), so the
+ # offloaded and mirrored disks of a VM share an instant. Idempotent, so every
+ # cut-over gets it, including the one a final cloud-init drive triggers.
+ $on_frozen = sub { run_deferred_copies($storecfg, $deferred_copies, @_) }
+ if $deferred_copies;
+
+ ($offload_class, $defer) =
+ clone_disk_offload_class($storecfg, $source, $dest, $storeid, $deferred_copies);
+ }
+
+ if (!$full) {
+ $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newvmid, $snapname);
+ push @$newvollist, $newvolid;
+ } elsif ($offload_class) {
+ ($newvolid, $offload_size) = clone_disk_offload(
+ $storecfg, $source, $dest, $storeid, $offload_class, $defer, $newvollist, $jobs,
+ $completion, $qga, $deferred_copies, $on_frozen,
+ );
+ } else {
my $name = undef;
my $size = undef;
if (drive_is_cloudinit($drive)) {
@@ -8140,18 +8337,20 @@ sub clone_disk {
# previous drive-mirrors
if (($completion && $completion eq 'complete') && (scalar(keys %$jobs) > 0)) {
PVE::QemuServer::BlockJob::monitor(
- vm_qmp_peer($vmid), $newvmid, $jobs, $completion, $qga,
+ vm_qmp_peer($vmid), $newvmid, $jobs, $completion, $qga, undef,
+ $on_frozen,
);
}
# No data needs to be copied for the cloudinit drive.
} else {
clone_disk_copy_data(
- $storecfg, $source, $dest, $use_drive_mirror, $jobs, $completion, $qga, $bwlimit,
+ $storecfg, $source, $dest, $use_drive_mirror, $jobs, $completion, $qga,
+ $bwlimit, $on_frozen,
);
}
}
- my $size = eval { PVE::Storage::volume_size_info($storecfg, $newvolid, 10) };
+ my $size = $offload_size // eval { PVE::Storage::volume_size_info($storecfg, $newvolid, 10) };
my $disk = dclone($drive);
delete $disk->{format};
diff --git a/src/PVE/QemuServer/BlockJob.pm b/src/PVE/QemuServer/BlockJob.pm
index c6af8576..d475d44c 100644
--- a/src/PVE/QemuServer/BlockJob.pm
+++ b/src/PVE/QemuServer/BlockJob.pm
@@ -81,13 +81,82 @@ sub qemu_blockjobs_cancel {
}
}
+# Run $code with the guest quiesced: fs-frozen through the guest agent where that
+# applies, suspended otherwise or when the freeze fails. A guest that is not running
+# (paused, suspended) is left as it is. $code gets whether the guest is quiesced.
+#
+# The guest is thawed or resumed whatever $code did. A failure to do so is reported with
+# log_warn(), so the task ends with a warning: failing it would discard a finished copy,
+# and the guest agent's freeze on Windows is limited to about ten seconds, after which
+# the thaw itself reports an error.
+sub run_with_guest_quiesced {
+ my ($vmid, $qga, $code) = @_;
+
+ my $mode; # how the guest was quiesced: 'freeze', 'suspend', 'as-is' or undef
+ my $thaw_pending; # a failed freeze whose thaw failed too
+ my $status = eval { mon_cmd($vmid, 'query-status')->{status} };
+ if ($@ || !defined($status)) {
+ # Not knowing whether the guest was paused, do not risk resuming it: run $code
+ # unquiesced, which refuses what needs a quiesced guest.
+ warn "cannot query the state of VM $vmid, not quiescing it - " . ($@ || "no status\n");
+ $status = undef;
+ } elsif ($status ne 'running') {
+ print "vm is not running ($status), leaving it as it is\n";
+ $mode = 'as-is';
+ } elsif (PVE::QemuServer::Agent::guest_fs_freeze_applicable($qga, $vmid)) {
+ print "issuing guest agent 'guest-fsfreeze-freeze' command\n";
+ eval { PVE::QemuServer::Agent::guest_fs_freeze($vmid); };
+ if (my $err = $@) {
+ warn $err;
+ # The freeze may have frozen some filesystems before failing.
+ eval { PVE::QemuServer::Agent::guest_fs_thaw($vmid); };
+ $thaw_pending = 1 if $@;
+ } else {
+ $mode = 'freeze';
+ }
+ }
+ if (!$mode && defined($status)) {
+ print "suspend vm\n";
+ eval { PVE::QemuServer::RunState::vm_suspend($vmid, 1); };
+ if (my $err = $@) {
+ warn $err;
+ } else {
+ $mode = 'suspend';
+ }
+ }
+
+ my @res = eval { $code->(defined($mode)) };
+ my $err = $@;
+
+ if (defined($mode) && $mode eq 'suspend') {
+ print "resume vm\n";
+ eval { PVE::QemuServer::RunState::vm_resume($vmid, 1, 1); };
+ log_warn("failed to resume VM $vmid, it may still be paused - $@") if $@;
+ }
+ if ((defined($mode) && $mode eq 'freeze') || $thaw_pending) {
+ print "issuing guest agent 'guest-fsfreeze-thaw' command\n";
+ eval { PVE::QemuServer::Agent::guest_fs_thaw($vmid); };
+ log_warn("failed to thaw the guest filesystems of VM $vmid, check them in the guest - $@")
+ if $@;
+ }
+
+ die $err if $err;
+
+ return wantarray ? @res : $res[0];
+}
+
# $completion can be either
# 'complete': wait until all jobs are ready, job-complete them (default)
# 'cancel': wait until all jobs are ready, block-job-cancel them
# 'skip': wait until all jobs are ready, return with block jobs in ready state
# 'auto': wait until all jobs disappear, only use for jobs which complete automatically
+#
+# $on_frozen is an optional coderef, run while the guest is quiesced at the instant the
+# mirror jobs are cut over, with whether the quiesce succeeded. Clone uses it to start
+# storage-offloaded copies there, so that a VM's offloaded and mirrored disks share one
+# point in time.
sub monitor {
- my ($qmp_peer, $vmiddst, $jobs, $completion, $qga, $op) = @_;
+ my ($qmp_peer, $vmiddst, $jobs, $completion, $qga, $op, $on_frozen) = @_;
die "drive mirror: different destination is only supported when peer is main QEMU instance\n"
if $vmiddst && $qmp_peer->{type} ne 'qmp';
@@ -169,31 +238,24 @@ sub monitor {
last if $completion eq 'skip' || $completion eq 'auto';
if ($qmp_peer->{type} eq 'qmp' && $vmiddst && $vmiddst != $qmp_peer->{id}) {
- my $vmid = $qmp_peer->{id};
- my $should_fsfreeze =
- PVE::QemuServer::Agent::guest_fs_freeze_applicable($qga, $vmid);
- if ($should_fsfreeze) {
- print "issuing guest agent 'guest-fsfreeze-freeze' command\n";
- eval { PVE::QemuServer::Agent::guest_fs_freeze($vmid); };
- warn $@ if $@;
- } else {
- print "suspend vm\n";
- eval { PVE::QemuServer::RunState::vm_suspend($vmid, 1); };
- warn $@ if $@;
- }
-
- # if we clone a disk for a new target vm, we don't switch the disk
- qemu_blockjobs_cancel($qmp_peer, $jobs);
-
- if ($should_fsfreeze) {
- print "issuing guest agent 'guest-fsfreeze-thaw' command\n";
- eval { PVE::QemuServer::Agent::guest_fs_thaw($vmid); };
- warn $@ if $@;
- } else {
- print "resume vm\n";
- eval { PVE::QemuServer::RunState::vm_resume($vmid, 1, 1); };
- warn $@ if $@;
- }
+ run_with_guest_quiesced(
+ $qmp_peer->{id},
+ $qga,
+ sub {
+ my ($quiesced) = @_;
+ # Storage-offloaded copies start here: their point in time is
+ # fixed by the start, so doing it inside the freeze is what
+ # puts them at the same instant as the mirrored disks cut
+ # over below. The cut-over happens either way.
+ eval { $on_frozen->($quiesced) if $on_frozen; };
+ my $err = $@;
+
+ # if we clone a disk for a new target vm, we don't switch the disk
+ qemu_blockjobs_cancel($qmp_peer, $jobs);
+
+ die $err if $err;
+ },
+ );
last;
} else {
@@ -284,6 +346,7 @@ sub qemu_drive_mirror {
$qga,
$bwlimit,
$src_bitmap,
+ $on_frozen,
) = @_;
my $device_id = "drive-$drive_id";
@@ -319,7 +382,7 @@ sub qemu_drive_mirror {
die "mirroring error: $err\n";
}
- monitor(vm_qmp_peer($vmid), $vmiddst, $jobs, $completion, $qga);
+ monitor(vm_qmp_peer($vmid), $vmiddst, $jobs, $completion, $qga, undef, $on_frozen);
}
# Callers should version guard this (only available with a binary >= QEMU 8.2)
@@ -523,6 +586,7 @@ sub blockdev_mirror {
$completion,
$options->{'guest-agent'},
'mirror',
+ $options->{'on-frozen'},
);
}
@@ -546,6 +610,7 @@ sub mirror {
$options->{'guest-agent'},
$options->{bwlimit},
$source->{bitmap},
+ $options->{'on-frozen'},
);
}
}
diff --git a/src/test/Makefile b/src/test/Makefile
index 2d3a55da..c0ae031e 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_snapshot test_cfg_to_cmd test_cfg_to_cmd_aarch64 test_hotplug test_hotplug_aarch64 test_pci_addr_conflicts test_pci_reservation test_qemu_img_convert test_migration test_restore_config test_parse_config test_memory test_agent test_raw_config_write test_api test_api_cloudinit_dump test_mtunnel test_guest_identity test_network
+test: test_snapshot test_cfg_to_cmd test_cfg_to_cmd_aarch64 test_hotplug test_hotplug_aarch64 test_pci_addr_conflicts test_pci_reservation test_qemu_img_convert test_migration test_restore_config test_parse_config test_memory test_agent test_guest_quiesce test_raw_config_write test_api test_api_cloudinit_dump test_mtunnel test_guest_identity test_network
test_snapshot: run_snapshot_tests.pl
./run_snapshot_tests.pl
@@ -48,6 +48,9 @@ test_memory: run_memory_tests.pl
test_agent: run_agent_tests.pl
./run_agent_tests.pl
+test_guest_quiesce: run_guest_quiesce_tests.pl
+ ./run_guest_quiesce_tests.pl
+
test_raw_config_write: run_raw_config_write_tests.pl
./run_raw_config_write_tests.pl
diff --git a/src/test/run_guest_quiesce_tests.pl b/src/test/run_guest_quiesce_tests.pl
new file mode 100755
index 00000000..57be58c4
--- /dev/null
+++ b/src/test/run_guest_quiesce_tests.pl
@@ -0,0 +1,154 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use Test::MockModule;
+use Test::More;
+
+use PVE::QemuServer::BlockJob;
+
+# run_with_guest_quiesced(): how the guest is quiesced, that it is always released, and
+# that a failed release ends the task with a warning instead of failing it.
+
+my @calls;
+my %fail; # name of a call => error it raises, or an arrayref of errors for successive calls
+my @warnings; # what log_warn() got
+my $status = 'running';
+my $freeze_applicable = 1;
+
+my $call = sub {
+ my ($name) = @_;
+ push @calls, $name;
+ my $f = $fail{$name};
+ $f = shift(@$f) if ref($f) eq 'ARRAY';
+ die $f if $f;
+};
+
+my $blockjob = Test::MockModule->new('PVE::QemuServer::BlockJob');
+$blockjob->redefine(
+ mon_cmd => sub { die "qmp timeout\n" if $status eq 'DIE'; return { status => $status } },
+ log_warn => sub { push @warnings, $_[0] },
+);
+my $agent = Test::MockModule->new('PVE::QemuServer::Agent');
+$agent->redefine(
+ guest_fs_freeze_applicable => sub { $freeze_applicable },
+ guest_fs_freeze => sub { $call->('freeze') },
+ guest_fs_thaw => sub { $call->('thaw') },
+);
+my $runstate = Test::MockModule->new('PVE::QemuServer::RunState');
+$runstate->redefine(
+ vm_suspend => sub { $call->('suspend') },
+ vm_resume => sub { $call->('resume') },
+);
+
+my $tests = [
+ {
+ name => 'agent freeze, then thaw',
+ calls => ['freeze', 'code', 'thaw'],
+ quiesced => 1,
+ },
+ {
+ name => 'no agent: suspend, then resume',
+ freeze_applicable => 0,
+ calls => ['suspend', 'code', 'resume'],
+ quiesced => 1,
+ },
+ {
+ name => 'failed freeze falls back to suspend',
+ fail => { freeze => "agent timeout\n" },
+ calls => ['freeze', 'thaw', 'suspend', 'code', 'resume'],
+ quiesced => 1,
+ },
+ {
+ name => 'nothing quiesces: code runs unquiesced',
+ fail => { freeze => "agent timeout\n", suspend => "qmp timeout\n" },
+ calls => ['freeze', 'thaw', 'suspend', 'code'],
+ quiesced => 0,
+ },
+ {
+ name => 'a paused guest is left paused',
+ status => 'paused',
+ calls => ['code'],
+ quiesced => 1,
+ },
+ {
+ name => 'state unknown: not quiesced, so a paused guest is not resumed',
+ status => 'DIE',
+ calls => ['code'],
+ quiesced => 0,
+ },
+ {
+ name => 'error from code: the guest is still thawed',
+ fail => { code => "copy failed\n" },
+ calls => ['freeze', 'code', 'thaw'],
+ error => qr/^copy failed$/,
+ },
+ {
+ name => 'failed thaw warns, the operation stands',
+ fail => { thaw => "agent gone\n" },
+ calls => ['freeze', 'code', 'thaw'],
+ quiesced => 1,
+ warning => qr/failed to thaw the guest filesystems of VM 100.*agent gone/s,
+ },
+ {
+ name => 'failed resume warns, the operation stands',
+ freeze_applicable => 0,
+ fail => { resume => "qmp gone\n" },
+ calls => ['suspend', 'code', 'resume'],
+ quiesced => 1,
+ warning => qr/failed to resume VM 100, it may still be paused - qmp gone/,
+ },
+ {
+ name => 'failed freeze whose thaw fails: thawed again after the resume',
+ fail => { freeze => "agent timeout\n", thaw => ["agent busy\n", undef] },
+ calls => ['freeze', 'thaw', 'suspend', 'code', 'resume', 'thaw'],
+ quiesced => 1,
+ },
+ {
+ name => 'failed freeze whose thaw keeps failing: warns',
+ fail => { freeze => "agent timeout\n", thaw => "agent gone\n" },
+ calls => ['freeze', 'thaw', 'suspend', 'code', 'resume', 'thaw'],
+ quiesced => 1,
+ warning => qr/failed to thaw the guest filesystems/,
+ },
+];
+
+for my $t (@$tests) {
+ @calls = ();
+ @warnings = ();
+ %fail = map { $_ => (ref($t->{fail}->{$_}) ? [$t->{fail}->{$_}->@*] : $t->{fail}->{$_}) }
+ keys(($t->{fail} // {})->%*);
+ $status = $t->{status} // 'running';
+ $freeze_applicable = $t->{freeze_applicable} // 1;
+
+ my $quiesced;
+ local $SIG{__WARN__} = sub { };
+ eval {
+ PVE::QemuServer::BlockJob::run_with_guest_quiesced(
+ 100, undef,
+ sub {
+ ($quiesced) = @_;
+ $call->('code');
+ },
+ );
+ };
+ my $err = $@;
+
+ is_deeply(\@calls, $t->{calls}, "$t->{name}: calls");
+ if ($t->{error}) {
+ like($err, $t->{error}, "$t->{name}: error");
+ } else {
+ is($err, '', "$t->{name}: no error");
+ is($quiesced ? 1 : 0, $t->{quiesced}, "$t->{name}: quiesced flag");
+ }
+ if ($t->{warning}) {
+ like(join('', @warnings), $t->{warning}, "$t->{name}: warning");
+ } else {
+ is(scalar(@warnings), 0, "$t->{name}: no warning");
+ }
+}
+
+done_testing();
--
2.55.0
^ permalink raw reply related [flat|nested] 7+ messages in thread
* [RFC PATCH docs v2 6/6] pvesm: document copy-offload and add it to the storage capability table
2026-11-26 16:56 [RFC PATCH storage/qemu-server/docs v2 0/6] offload full clone to the storage backend Ciro Iriarte
` (4 preceding siblings ...)
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 ` Ciro Iriarte
5 siblings, 0 replies; 7+ messages in thread
From: Ciro Iriarte @ 2026-11-26 16:57 UTC (permalink / raw)
To: pve-devel
From: Ciro Iriarte <ciro.iriarte+software@gmail.com>
The capability table is where people look when choosing a storage, so
add a "Clone offload" column next to Snapshots, and document the
copy-offload and copy-offload-timeout options with the common storage
properties.
The column states what is implemented, not what a backend could do: NFS
and CIFS can copy server-side but are marked no because nothing uses
that yet, as the footnote explains.
The footnotes give the conditions that are not visible from the storage
configuration. A directory storage needs a filesystem with reflink
support, which for XFS is decided at mkfs time. A qcow2 with a backing
file or internal snapshots, and btrfs or LVM-thin images that are not
raw, are copied by the host. In those cases the clone falls back to the
host-side copy rather than failing, as the option text states. Ceph/RBD
finishes the copy with a manager task, so both storages must use the
same Ceph user and that user must be allowed to add manager tasks;
otherwise the host copies it. The docs also note that the clone
bandwidth limit does not apply to an offloaded copy.
Signed-off-by: Ciro Iriarte <ciro.iriarte+software@gmail.com>
---
Changes in v2:
* new in the series; v1 had it as a separate reply (2026-09-07)
* rebased onto current master: adds the NVMe-oF row (no offload)
* footnotes for raw-only btrfs and LVM-thin, the same thin pool,
qcow2 images with internal snapshots, and the Ceph manager access
RBD needs: the same Ceph user on both storages, allowed to add
manager tasks (otherwise the host copies)
* the option text no longer claims RBD copies share blocks, and says
the clone bandwidth limit does not apply and that time queued behind
other Ceph manager tasks counts toward copy-offload-timeout
* documents that a pair the backend cannot copy falls back to the host
pvesm.adoc | 79 ++++++++++++++++++++++++++++++++++++++++++------------
1 file changed, 62 insertions(+), 17 deletions(-)
diff --git a/pvesm.adoc b/pvesm.adoc
index ec2ef97..ea99b41 100644
--- a/pvesm.adoc
+++ b/pvesm.adoc
@@ -65,24 +65,24 @@ nodes that can be accessed as RBD (RADOS Block Device).
.Available storage types
-[width="100%",cols="<2d,1*m,4*d",options="header"]
+[width="100%",cols="<2d,1*m,5*d",options="header"]
|========================================================================
-|Description |Plugin type |Level |Shared|Snapshots|Stable
-|ZFS (local) |zfspool |both^1^|no |yes |yes
-|Directory |dir |file |no |yes^2^ |yes
-|BTRFS |btrfs |file |no |yes |TP^5^
-|NFS |nfs |file |yes |yes^2^ |yes
-|CIFS |cifs |file |yes |yes^2^ |yes
-|Proxmox Backup |pbs |both |yes |n/a |yes
-|CephFS |cephfs |file |yes |n/a |yes
-|LVM |lvm |block |no^3^ |yes^4^ |yes
-|LVM-thin |lvmthin |block |no |yes |yes
-|iSCSI/kernel |iscsi |block |yes^3^|yes^4^ |yes
-|iSCSI/libiscsi |iscsidirect |block |yes^3^|yes^4^ |yes
-|NVMe-oF |nvmeof |block |yes^3^|yes^4^ |yes
-|FC/SAS |native^6^ |block |yes^3^|yes^4^ |yes
-|Ceph/RBD |rbd |block |yes |yes |yes
-|ZFS over iSCSI |zfs |block |yes |yes |yes
+|Description |Plugin type |Level |Shared|Snapshots|Clone offload^7^|Stable
+|ZFS (local) |zfspool |both^1^|no |yes |no |yes
+|Directory |dir |file |no |yes^2^ |yes^8^ |yes
+|BTRFS |btrfs |file |no |yes |yes^9^ |TP^5^
+|NFS |nfs |file |yes |yes^2^ |no |yes
+|CIFS |cifs |file |yes |yes^2^ |no |yes
+|Proxmox Backup |pbs |both |yes |n/a |n/a |yes
+|CephFS |cephfs |file |yes |n/a |no |yes
+|LVM |lvm |block |no^3^ |yes^4^ |no |yes
+|LVM-thin |lvmthin |block |no |yes |yes^9^ |yes
+|iSCSI/kernel |iscsi |block |yes^3^|yes^4^ |no |yes
+|iSCSI/libiscsi |iscsidirect |block |yes^3^|yes^4^ |no |yes
+|NVMe-oF |nvmeof |block |yes^3^|yes^4^ |no |yes
+|FC/SAS |native^6^ |block |yes^3^|yes^4^ |n/a |yes
+|Ceph/RBD |rbd |block |yes |yes |yes^10^ |yes
+|ZFS over iSCSI |zfs |block |yes |yes |no |yes
|========================================================================
^1^: Disk images for VMs are stored in ZFS volume (zvol) datasets, which provide
@@ -115,6 +115,23 @@ xref:pvesm_lvm_config[LVM configuration] section.
^6^ Fibre Channel (FC) and SAS block storage is handled directly by the host
without a dedicated storage plugin.
+^7^ Whether a *full* clone can be handed to the storage instead of being copied
+byte by byte by the host. Off by default; enable it per storage with the
+`copy-offload` option. This only applies within one storage backend; copying
+between two different backends always goes through the host. Storages marked
+`no` are not necessarily incapable, they just have no implementation yet.
+
+^8^ Only when the underlying filesystem supports reflinks (XFS created with
+`reflink=1`, btrfs, or ZFS with block cloning enabled) and both storages are on
+the same filesystem. Not for a 'qcow2' image that has a backing file, since the
+copy would keep depending on the base, nor for one with internal snapshots.
+
+^9^ For BTRFS, only 'raw' images; for LVM-thin, only within the same thin pool.
+
+^10^ Only within one Ceph cluster, and only when both storages use the same Ceph
+user. The copy is finished by a Ceph manager task, so that user must be allowed
+to add manager tasks; otherwise, clones are copied by the host.
+
Thin Provisioning
~~~~~~~~~~~~~~~~~
@@ -316,6 +333,34 @@ file-based storages. The default is `metadata`, which is treated like `off` for
`raw` images. When using network storages in combination with large `qcow2`
images, using `off` can help to avoid timeouts.
+copy-offload::
+
+Let the storage perform full clones itself instead of copying the image through
+the host. Disabled by default. With reflinks, btrfs and LVM-thin the copy is
+close to instant and shares blocks with its source copy-on-write; Ceph/RBD
+copies the data on the cluster instead of through the host. The result is
+still a normal, independent disk: the source can be deleted afterwards.
+
+Set it on the storage the clone is created on. It only takes effect when the
+source storage is of the same type and that type supports it; see the ``Clone
+offload'' column above and its footnotes. Anything else, including an image or
+storage pair the backend cannot copy, falls back to the usual host-side copy.
+The `clone` bandwidth limit does not apply to an offloaded copy, as the data
+does not pass through the host.
+
+copy-offload-timeout::
+
+How long to wait, in seconds, for an offloaded copy to become independent of its
+source before giving up and cleaning up the unfinished target (default: 86400,
+one day). The timer restarts every time the backend reports progress, so this
+bounds a copy that has stalled rather than one that is merely slow. On Ceph/RBD,
+time a copy spends queued behind other manager tasks reports no progress and
+counts toward the timeout, so do not set it too low.
+
+Only relevant for backends that copy in the background, such as Ceph/RBD, where
+the clone is readable immediately but has to be flattened before it stops
+depending on its source. Backends that finish instantly never reach it.
+
WARNING: It is not advisable to use the same storage pool on different
{pve} clusters. Some storage operation need exclusive access to the
storage, so proper locking is required. While this is implemented
--
2.55.0
^ permalink raw reply related [flat|nested] 7+ messages in thread
end of thread, other threads:[~2026-11-26 16:58 UTC | newest]
Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
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 ` [RFC PATCH storage v2 4/6] btrfs, lvmthin: implement copy-offload (atomic class) Ciro Iriarte
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
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox