Migration staging patches
The following changes since commit 43ba160cb4bbb193560eb0d2d7decc4b5fc599fe:
Merge tag 'for-upstream' of https://gitlab.com/bonzini/qemu into staging (2025-06-21 10:00:46 -0400)
are available in the Git repository at:
https://gitlab.com/peterx/qemu.git tags/migration-staging-pull-request
for you to fetch changes up to 2fde3fb916079ee0ff0fc26d9446c813b1d5cc28:
physmem: Support coordinated discarding of RAM with guest_memfd (2025-06-23 16:03:59 -0400)
----------------------------------------------------------------
Migration / Memory pull
- Yanfei's optimization to skip log_clear during completion
- Fabiano's cleanup to remove leftover migration-helpers.c file
- Juraj's vnc fix on display pause after migration
- Jaehoon's cpr test fix on possible race of server establishment
- Chenyi's initial support on vfio enablement for guest-memfd
----------------------------------------------------------------
Chaney, Ben (1):
migration: Don't sync volatile memory after migration completes
Chenyi Qiang (5):
memory: Export a helper to get intersection of a MemoryRegionSection
with a given range
memory: Change memory_region_set_ram_discard_manager() to return the
result
memory: Unify the definiton of ReplayRamPopulate() and
ReplayRamDiscard()
ram-block-attributes: Introduce RamBlockAttributes to manage RAMBlock
with guest_memfd
physmem: Support coordinated discarding of RAM with guest_memfd
Fabiano Rosas (1):
tests/qtest: Remove migration-helpers.c
Jaehoon Kim (2):
migration: Support fd-based socket address in cpr_transfer_input tests/migration: Setup pre-listened cpr.sock to remove race-condition.
Juraj Marcin (1):
ui/vnc: Update display update interval when VM state changes to
RUNNING
Yanfei Xu (1):
migration/ram: avoid to do log clear in the last round
MAINTAINERS | 1 + include/system/memory.h | 110 +++++-- include/system/ramblock.h | 22 ++ ui/vnc.h | 2 + accel/kvm/kvm-all.c | 9 + hw/virtio/virtio-mem.c | 83 ++--- migration/cpr-transfer.c | 7 +- migration/ram.c | 31 +- system/memory.c | 22 +- system/physmem.c | 23 +- system/ram-block-attributes.c | 444 +++++++++++++++++++++++++ tests/qtest/migration-helpers.c | 530 ------------------------------ tests/qtest/migration/cpr-tests.c | 14 +- ui/vnc.c | 12 + system/meson.build | 1 + system/trace-events | 3 + 16 files changed, 688 insertions(+), 626 deletions(-) create mode 100644 system/ram-block-attributes.c delete mode 100644 tests/qtest/migration-helpers.c
Signature · 1 line
2.49.0
[PULL 01/11] migration/ram: avoid to do log clear in the last round
From: Yanfei Xu <[email protected]>
There won't be any ram sync after the stage of save_complete, therefore it's unnecessary to do manually protect for dirty pages being sent. Skip to do this in last round can reduce noticeable downtime.
--- migration/ram.c | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-)
migration/ram.c +15 -7
@@ -831,14 +831,22 @@ static inline bool migration_bitmap_clear_dirty(RAMState *rs,bool ret;/* -* Clear dirty bitmap if needed. This _must_ be called before we -* send any of the page in the chunk because we need to make sure -* we can capture further page content changes when we sync dirty -* log the next time. So as long as we are going to send any of -* the page in the chunk we clear the remote dirty bitmap for all. -* Clearing it earlier won't be a problem, but too late will. +* During the last stage (after source VM stopped), resetting the write +* protections isn't needed as we know there will be either (1) no +* further writes if migration will complete, or (2) migration fails +* at last then tracking isn't needed either. */ -migration_clear_memory_region_dirty_bitmap (rb, page); +if (!rs->last_stage) { +/* +* Clear dirty bitmap if needed. This _must_ be called before we +* send any of the page in the chunk because we need to make sure +* we can capture further page content changes when we sync dirty +* log the next time. So as long as we are going to send any of +* the page in the chunk we clear the remote dirty bitmap for all. +* Clearing it earlier won't be a problem, but too late will. +*/ +migration_clear_memory_region_dirty_bitmap (rb, page); + } ret =test_and_clear_bit (page, rb->bmap);if (ret) {
Signature · 1 line
2.49.0
[PULL 05/11] tests/migration: Setup pre-listened cpr.sock to remove race-condition.
In reply to Peter XuFrom: Jaehoon Kim <[email protected]>
When the source VM attempts to connect to the destination VM's Unix domain socket (cpr.sock) during a cpr-transfer test, race conditions can occur if the socket file isn't ready. This can lead to connection failures when running tests.
This patch creates and listens on the socket in advance, and passes the pre-listened FD directly. This avoids timing issues and improves the reliability of CPR tests.
--- tests/qtest/migration/cpr-tests.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-)
tests/qtest/migration/cpr-tests.c +12 -2
@@ -60,13 +60,12 @@ static void test_mode_transfer_common(bool incoming_defer) g_autofree char *cpr_path = g_strdup_printf("%s/cpr.sock", tmpfs); g_autofree char *mig_path = g_strdup_printf("%s/migsocket", tmpfs); g_autofree char *uri = g_strdup_printf("unix:%s", mig_path); + g_autofree char *opts_target = NULL;const char *opts ="-machine aux-ram-share=on -nodefaults" ; g_autofree const char *cpr_channel = g_strdup_printf("cpr,addr.transport=socket,addr.type=unix,addr.path=%s" , cpr_path); - g_autofree char *opts_target = g_strdup_printf("-incoming %s %s", - cpr_channel, opts); g_autofree char *connect_channels = g_strdup_printf( "[ { 'channel-type': 'main',"
@@ -75,6 +74,17 @@ static void test_mode_transfer_common(bool incoming_defer)" 'path': '%s' } } ]" , mig_path); +/* +* Set up a UNIX domain socket for the CPR channel before +* launching the destination VM, to avoid timing issues +* during connection setup. +*/ +int cpr_sockfd =qtest_socket_server (cpr_path); +g_assert (cpr_sockfd >=0 ); + + opts_target =g_strdup_printf ("-incoming cpr,addr.transport=socket," +"addr.type=fd,addr.str=%d %s" , + cpr_sockfd, opts);MigrateCommon args = { .start.opts_source = opts, .start.opts_target = opts_target,
Signature · 1 line
2.49.0
[PULL 03/11] ui/vnc: Update display update interval when VM state changes to RUNNING
In reply to Peter XuFrom: Juraj Marcin <[email protected]>
If a virtual machine is paused for an extended period time, for example, due to an incoming migration, there are also no changes on the screen. VNC in such case increases the display update interval by VNC_REFRESH_INTERVAL_INC (50 ms). The update interval can then grow up to VNC_REFRESH_INTERVAL_MAX (3000 ms).
When the machine resumes, it can then take up to 3 seconds for the first display update. Furthermore, the update interval is then halved with each display update with changes on the screen. If there are moving elements on the screen, such as a video, this can be perceived as freezing and stuttering for few seconds before the movement is smooth again.
This patch resolves this issue, by adding a listener to VM state changes and changing the update interval when the VM state changes to RUNNING. The update_displaychangelistener() function updates the internal timer, and the display is refreshed immediately if the timer is expired.
--- ui/vnc.h | 2 ++ ui/vnc.c | 12 ++++++++++++ 2 files changed, 14 insertions(+)
ui/vnc.h +2 -0
@@ -185,6 +185,8 @@ struct VncDisplay#endif AudioState *audio_state; + +VMChangeStateEntry *vmstate_handler_entry; }; typedef struct VncTight {
ui/vnc.c +12 -0
@@ -3385,6 +3385,16 @@ static const DisplayChangeListenerOps dcl_ops = { .dpy_cursor_define = vnc_dpy_cursor_define, }; +static void vmstate_change_handler (void *opaque,bool running,RunState state) +{ +VncDisplay *vd = opaque; + +if (state !=RUN_STATE_RUNNING ) { +return ; + } +update_displaychangelistener (&vd->dcl,VNC_REFRESH_INTERVAL_BASE ); +} +void vnc_display_init (const char *id,Error **errp) {VncDisplay *vd;
@@ -3421,6 +3431,8 @@ void vnc_display_init(const char *id, Error **errp) vd->dcl.ops = &dcl_ops;register_displaychangelistener (&vd->dcl); vd->kbd =qkbd_state_init (vd->dcl.con); + vd->vmstate_handler_entry =qemu_add_vm_change_state_handler ( + &vmstate_change_handler, vd); }
Signature · 1 line
2.49.0
[PULL 02/11] tests/qtest: Remove migration-helpers.c
In reply to Peter XuFrom: Fabiano Rosas <[email protected]>
Commit 407bc4bf90 ("qapi: Move include/qapi/qmp/ to include/qobject/") brought the migration-helpers.c back by mistake. This file has been replaced with migration/migration-qmp.c and migration/migration-util.c.
Message-id: [email protected]
--- tests/qtest/migration-helpers.c | 530 -------------------------------- 1 file changed, 530 deletions(-) delete mode 100644 tests/qtest/migration-helpers.c
tests/qtest/migration-helpers.c deleted +0 -530
@@ -1,530 +0,0 @@ -/* -* QTest migration helpers -* -* Copyright (c) 2016-2018 Red Hat, Inc. and/or its affiliates -* based on the vhost-user-test.c that is: -* Copyright (c) 2014 Virtual Open Systems Sarl. -* -* This work is licensed under the terms of the GNU GPL, version 2 or later. -* See the COPYING file in the top-level directory. -* -*/ - -#include "qemu/osdep.h" -#include "qemu/ctype.h" -#include "qobject/qjson.h" -#include "qapi/qapi-visit-sockets.h" -#include "qapi/qobject-input-visitor.h" -#include "qapi/error.h" -#include "qobject/qlist.h" -#include "qemu/cutils.h" -#include "qemu/memalign.h" - -#include "migration-helpers.h" - -/* -* Number of seconds we wait when looking for migration -* status changes, to avoid test suite hanging forever -* when things go wrong. Needs to be higher enough to -* avoid false positives on loaded hosts. -*/ -#define MIGRATION_STATUS_WAIT_TIMEOUT 120 - -static char *SocketAddress_to_str (SocketAddress *addr) -{ -switch (addr->type) { -case SOCKET_ADDRESS_TYPE_INET : -return g_strdup_printf ("tcp:%s:%s" , - addr->u.inet.host, - addr->u.inet.port); -case SOCKET_ADDRESS_TYPE_UNIX : -return g_strdup_printf ("unix:%s" , - addr->u.q_unix.path); -case SOCKET_ADDRESS_TYPE_FD : -return g_strdup_printf ("fd:%s" , addr->u.fd.str); -case SOCKET_ADDRESS_TYPE_VSOCK : -return g_strdup_printf ("vsock:%s:%s" , - addr->u.vsock.cid, - addr->u.vsock.port); -default : -return g_strdup ("unknown address type" ); - } -} - -static QDict *SocketAddress_to_qdict (SocketAddress *addr) -{ -QDict *dict =qdict_new (); - -switch (addr->type) { -case SOCKET_ADDRESS_TYPE_INET : -qdict_put_str (dict,"type" ,"inet" ); -qdict_put_str (dict,"host" , addr->u.inet.host); -qdict_put_str (dict,"port" , addr->u.inet.port); -break ; -case SOCKET_ADDRESS_TYPE_UNIX : -qdict_put_str (dict,"type" ,"unix" ); -qdict_put_str (dict,"path" , addr->u.q_unix.path); -break ; -case SOCKET_ADDRESS_TYPE_FD : -qdict_put_str (dict,"type" ,"fd" ); -qdict_put_str (dict,"str" , addr->u.fd.str); -break ; -case SOCKET_ADDRESS_TYPE_VSOCK : -qdict_put_str (dict,"type" ,"vsock" ); -qdict_put_str (dict,"cid" , addr->u.vsock.cid); -qdict_put_str (dict,"port" , addr->u.vsock.port); -break ; -default : -g_assert_not_reached (); - } - -return dict; -} - -static SocketAddressList *migrate_get_socket_address (QTestState *who) -{ -QDict *rsp; -SocketAddressList *addrs; -Visitor *iv =NULL ; -QObject *object; - - rsp =migrate_query (who); - object =qdict_get (rsp,"socket-address" ); - - iv =qobject_input_visitor_new (object); -visit_type_SocketAddressList (iv,NULL , &addrs, &error_abort); -visit_free (iv); - -qobject_unref (rsp); -return addrs; -} - -static char * -migrate_get_connect_uri (QTestState *who) -{ -SocketAddressList *addrs; -char *connect_uri; - - addrs =migrate_get_socket_address (who); - connect_uri =SocketAddress_to_str (addrs->value); - -qapi_free_SocketAddressList (addrs); -return connect_uri; -} - -static QDict * -migrate_get_connect_qdict (QTestState *who) -{ -SocketAddressList *addrs; -QDict *connect_qdict; - - addrs =migrate_get_socket_address (who); - connect_qdict =SocketAddress_to_qdict (addrs->value); - -qapi_free_SocketAddressList (addrs); -return connect_qdict; -} - -static void migrate_set_ports (QTestState *to,QList *channel_list) -{ -QDict *addr; -QListEntry *entry; -const char *addr_port =NULL ; - - addr =migrate_get_connect_qdict (to); - - QLIST_FOREACH_ENTRY(channel_list, entry) { -QDict *channel =qobject_to (QDict,qlist_entry_obj (entry)); -QDict *addrdict =qdict_get_qdict (channel,"addr" ); - -if (qdict_haskey (addrdict,"port" ) && -qdict_haskey (addr,"port" ) && - (strcmp (qdict_get_str (addrdict,"port" ),"0" ) ==0 )) { - addr_port =qdict_get_str (addr,"port" ); -qdict_put_str (addrdict,"port" , addr_port); - } - } - -qobject_unref (addr); -} - -bool migrate_watch_for_events (QTestState *who,const char *name, -QDict *event,void *opaque) -{ -QTestMigrationState *state = opaque; - -if (g_str_equal (name,"STOP" )) { - state->stop_seen = true; -return true; - }else if (g_str_equal (name,"SUSPEND" )) { - state->suspend_seen = true; -return true; - }else if (g_str_equal (name,"RESUME" )) { - state->resume_seen = true; -return true; - } - -return false; -} - -void migrate_qmp_fail (QTestState *who,const char *uri, -const char *channels,const char *fmt, ...) -{ -va_list ap; -QDict *args, *err; - -va_start (ap, fmt); - args =qdict_from_vjsonf_nofail (fmt, ap); -va_end (ap); - -g_assert (!qdict_haskey (args,"uri" )); -if (uri) { -qdict_put_str (args,"uri" , uri); - } - -g_assert (!qdict_haskey (args,"channels" )); -if (channels) { -QObject *channels_obj =qobject_from_json (channels, &error_abort); -qdict_put_obj (args,"channels" , channels_obj); - } - - err =qtest_qmp_assert_failure_ref ( - who,"{ 'execute': 'migrate', 'arguments': %p}" , args); - -g_assert (qdict_haskey (err,"desc" )); - -qobject_unref (err); -} - -/* -* Send QMP command "migrate". -* Arguments are built from @fmt... (formatted like -* qobject_from_jsonf_nofail()) with "uri": @uri spliced in. -*/ -void migrate_qmp (QTestState *who,QTestState *to,const char *uri, -const char *channels,const char *fmt, ...) -{ -va_list ap; -QDict *args; - g_autofree char *connect_uri = NULL; - -va_start (ap, fmt); - args =qdict_from_vjsonf_nofail (fmt, ap); -va_end (ap); - -g_assert (!qdict_haskey (args,"uri" )); -if (uri) { -qdict_put_str (args,"uri" , uri); - }else if (!channels) { - connect_uri =migrate_get_connect_uri (to); -qdict_put_str (args,"uri" , connect_uri); - } - -g_assert (!qdict_haskey (args,"channels" )); -if (channels) { -QObject *channels_obj =qobject_from_json (channels, &error_abort); -QList *channel_list =qobject_to (QList, channels_obj); -migrate_set_ports (to, channel_list); -qdict_put_obj (args,"channels" , channels_obj); - } - -qtest_qmp_assert_success (who, -"{ 'execute': 'migrate', 'arguments': %p}" , args); -} - -void migrate_set_capability (QTestState *who,const char *capability, -bool value) -{ -qtest_qmp_assert_success (who, -"{ 'execute': 'migrate-set-capabilities'," -"'arguments': { " -"'capabilities': [ { " -"'capability': %s, 'state': %i } ] } }" , - capability, value); -} - -void migrate_incoming_qmp (QTestState *to,const char *uri,const char *fmt, ...) -{ -va_list ap; -QDict *args, *rsp; - -va_start (ap, fmt); - args =qdict_from_vjsonf_nofail (fmt, ap); -va_end (ap); - -g_assert (!qdict_haskey (args,"uri" )); -qdict_put_str (args,"uri" , uri); - -/* This function relies on the event to work, make sure it's enabled */ -migrate_set_capability (to,"events" , true); - - rsp =qtest_qmp (to,"{ 'execute': 'migrate-incoming', 'arguments': %p}" , - args); - -if (!qdict_haskey (rsp,"return" )) { -g_autoptr (GString) s =qobject_to_json_pretty (QOBJECT (rsp), true); -g_test_message ("%s" , s->str); - } - -g_assert (qdict_haskey (rsp,"return" )); -qobject_unref (rsp); - -migration_event_wait (to,"setup" ); -} - -/* -* Note: caller is responsible to free the returned object via -* qobject_unref() after use -*/ -QDict *migrate_query (QTestState *who) -{ -return qtest_qmp_assert_success_ref (who,"{ 'execute': 'query-migrate' }" ); -} - -QDict *migrate_query_not_failed (QTestState *who) -{ -const char *status; -QDict *rsp =migrate_query (who); - status =qdict_get_str (rsp,"status" ); -if (g_str_equal (status,"failed" )) { -g_printerr ("query-migrate shows failed migration: %s\n" , -qdict_get_str (rsp,"error-desc" )); - } -g_assert (!g_str_equal (status,"failed" )); -return rsp; -} - -/* -* Note: caller is responsible to free the returned object via -* g_free() after use -*/ -static gchar *migrate_query_status (QTestState *who) -{ -QDict *rsp_return =migrate_query (who); -gchar *status =g_strdup (qdict_get_str (rsp_return,"status" )); - -g_assert (status); -qobject_unref (rsp_return); - -return status; -} - -static bool check_migration_status (QTestState *who,const char *goal, -const char **ungoals) -{ -bool ready; -char *current_status; -const char **ungoal; - - current_status =migrate_query_status (who); - ready =strcmp (current_status, goal) ==0 ; -if (!ungoals) { - g_assert_cmpstr(current_status, !=, "failed"); -/* -* If looking for a state other than completed, -* completion of migration would cause the test to -* hang. -*/ -if (strcmp (goal,"completed" ) !=0 ) { - g_assert_cmpstr(current_status, !=, "completed"); - } - }else { -for (ungoal = ungoals; *ungoal; ungoal++) { - g_assert_cmpstr(current_status, !=, *ungoal); - } - } -g_free (current_status); -return ready; -} - -void wait_for_migration_status (QTestState *who, -const char *goal,const char **ungoals) -{ -g_test_timer_start (); -while (!check_migration_status (who, goal, ungoals)) { -usleep (1000 ); - -g_assert (g_test_timer_elapsed () <MIGRATION_STATUS_WAIT_TIMEOUT ); - } -} - -void wait_for_migration_complete (QTestState *who) -{ -wait_for_migration_status (who,"completed" ,NULL ); -} - -void wait_for_migration_fail (QTestState *from,bool allow_active) -{ -g_test_timer_start (); -QDict *rsp_return; -char *status; -bool failed; - -do { - status =migrate_query_status (from); -bool result = !strcmp (status,"setup" ) || !strcmp (status,"failed" ) || - (allow_active && !strcmp (status,"active" )); -if (!result) { -fprintf (stderr,"%s: unexpected status status=%s allow_active=%d\n" , - __func__, status, allow_active); - } -g_assert (result); - failed = !strcmp (status,"failed" ); -g_free (status); - -g_assert (g_test_timer_elapsed () <MIGRATION_STATUS_WAIT_TIMEOUT ); - }while (!failed); - -/* Is the machine currently running? */ - rsp_return =qtest_qmp_assert_success_ref (from, -"{ 'execute': 'query-status' }" ); -g_assert (qdict_haskey (rsp_return,"running" )); -g_assert (qdict_get_bool (rsp_return,"running" )); -qobject_unref (rsp_return); -} - -char *find_common_machine_version (const char *mtype,const char *var1, -const char *var2) -{ - g_autofree char *type1 = qtest_resolve_machine_alias(var1, mtype); - g_autofree char *type2 = qtest_resolve_machine_alias(var2, mtype); - -g_assert (type1 && type2); - -if (g_str_equal (type1, type2)) { -/* either can be used */ -return g_strdup (type1); - } - -if (qtest_has_machine_with_env (var2, type1)) { -return g_strdup (type1); - } - -if (qtest_has_machine_with_env (var1, type2)) { -return g_strdup (type2); - } - -g_test_message ("No common machine version for machine type '%s' between " -"binaries %s and %s" , mtype,getenv (var1),getenv (var2)); -g_assert_not_reached (); -} - -char *resolve_machine_version (const char *alias,const char *var1, -const char *var2) -{ -const char *mname =g_getenv ("QTEST_QEMU_MACHINE_TYPE" ); - g_autofree char *machine_name = NULL; - -if (mname) { -const char *dash =strrchr (mname,'-' ); -const char *dot =strrchr (mname,'.' ); - - machine_name =g_strdup (mname); - -if (dash && dot) { -assert (qtest_has_machine (machine_name)); -return g_steal_pointer (&machine_name); - } -/* else: probably an alias, let it be resolved below */ - }else { -/* use the hardcoded alias */ - machine_name =g_strdup (alias); - } - -return find_common_machine_version (machine_name, var1, var2); -} - -typedef struct { -char *name; -void (*func)(void ); -}MigrationTest ; - -static void migration_test_destroy (gpointer data) -{ -MigrationTest *test = (MigrationTest *)data; - -g_free (test->name); -g_free (test); -} - -static void migration_test_wrapper (const void *data) -{ -MigrationTest *test = (MigrationTest *)data; - -g_test_message ("Running /%s%s" ,qtest_get_arch (), test->name); - test->func (); -} - -void migration_test_add (const char *path,void (*fn)(void )) -{ -MigrationTest *test =g_new0 (MigrationTest,1 ); - - test->func = fn; - test->name =g_strdup (path); - -qtest_add_data_func_full (path, test, migration_test_wrapper, - migration_test_destroy); -} - -#ifdef O_DIRECT -/* -* Probe for O_DIRECT support on the filesystem. Since this is used -* for tests, be conservative, if anything fails, assume it's -* unsupported. -*/ -bool probe_o_direct_support (const char *tmpfs) -{ - g_autofree char *filename = g_strdup_printf("%s/probe-o-direct", tmpfs); -int fd, flags =O_CREAT |O_RDWR |O_TRUNC |O_DIRECT ; -void *buf; -ssize_t ret, len; -uint64_t offset; - - fd =open (filename, flags,0660 ); -if (fd <0 ) { -unlink (filename); -return false; - } - -/* -* Using 1MB alignment as conservative choice to satisfy any -* plausible architecture default page size, and/or filesystem -* alignment restrictions. -*/ - len =0x100000 ; - offset =0x100000 ; - - buf =qemu_try_memalign (len, len); -g_assert (buf); - - ret =pwrite (fd, buf, len, offset); -unlink (filename); -g_free (buf); - -if (ret <0 ) { -return false; - } - -return true; -} -#endif - -/* -* Wait for a "MIGRATION" event. This is what Libvirt uses to track -* migration status changes. -*/ -void migration_event_wait (QTestState *s,const char *target) -{ -QDict *response, *data; -const char *status; -bool found; - -do { - response =qtest_qmp_eventwait_ref (s,"MIGRATION" ); - data =qdict_get_qdict (response,"data" ); -g_assert (data); - status =qdict_get_str (data,"status" ); - found = (strcmp (status, target) ==0 ); -qobject_unref (response); - }while (!found); -}
Signature · 1 line
2.49.0
[PULL 11/11] physmem: Support coordinated discarding of RAM with guest_memfd
In reply to Peter XuFrom: Chenyi Qiang <[email protected]>
A new field, attributes, was introduced in RAMBlock to link to a RamBlockAttributes object, which centralizes all guest_memfd related information (such as fd and status bitmap) within a RAMBlock.
Create and initialize the RamBlockAttributes object upon ram_block_add(). Meanwhile, register the object in the target RAMBlock's MemoryRegion. After that, guest_memfd-backed RAMBlock is associated with the RamDiscardManager interface, and the users can execute RamDiscardManager specific handling. For example, VFIO will register the RamDiscardListener and get notifications when the state_change() helper invokes.
As coordinate discarding of RAM with guest_memfd is now supported, only block uncoordinated discard.
--- include/system/ramblock.h | 1 + accel/kvm/kvm-all.c | 9 +++++++++ system/physmem.c | 23 +++++++++++++++++++++-- 3 files changed, 31 insertions(+), 2 deletions(-)
include/system/ramblock.h +1 -0
@@ -46,6 +46,7 @@ struct RAMBlock {int fd;uint64_t fd_offset;int guest_memfd; +RamBlockAttributes *attributes;size_t page_size;/* dirty bitmap used during migration */ unsigned long *bmap;
accel/kvm/kvm-all.c +9 -0
@@ -3091,6 +3091,15 @@ int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private) addr =memory_region_get_ram_ptr (mr) + section.offset_within_region; rb =qemu_ram_block_from_host (addr, false, &offset); + ret =ram_block_attributes_state_change (RAM_BLOCK_ATTRIBUTES (mr->rdm), + offset, size, to_private); +if (ret) { +error_report ("Failed to notify the listener the state change of " +"(0x%" HWADDR_PRIx" + 0x%" HWADDR_PRIx") to %s" , + start, size, to_private ?"private" :"shared" ); + goto out_unref; + } +if (to_private) {if (rb->page_size !=qemu_real_host_page_size ()) {/*
system/physmem.c +21 -2
@@ -1916,7 +1916,7 @@ static void ram_block_add(RAMBlock *new_block, Error **errp) }assert (new_block->guest_memfd <0 ); - ret =ram_block_discard_require (true); + ret =ram_block_coordinated_discard_require (true);if (ret <0 ) {error_setg_errno (errp, -ret,"cannot set up private guest memory: discard currently blocked" );
@@ -1931,6 +1931,24 @@ static void ram_block_add(RAMBlock *new_block, Error **errp) goto out_free; } +/* +* The attribute bitmap of the RamBlockAttributes is default to +* discarded, which mimics the behavior of kvm_set_phys_mem() when it +* calls kvm_set_memory_attributes_private(). This leads to a brief +* period of inconsistency between the creation of the RAMBlock and its +* mapping into the physical address space. However, this is not +* problematic, as no users rely on the attribute status to perform +* any actions during this interval. +*/ + new_block->attributes =ram_block_attributes_create (new_block); +if (!new_block->attributes) { +error_setg (errp,"Failed to create ram block attribute" ); +close (new_block->guest_memfd); +ram_block_coordinated_discard_require (false); +qemu_mutex_unlock_ramlist (); + goto out_free; + } +/* * Add a specific guest_memfd blocker if a generic one would not be * added by ram_block_add_cpr_blocker.
@@ -2287,8 +2305,9 @@ static void reclaim_ramblock(RAMBlock *block) }if (block->guest_memfd >=0 ) { +ram_block_attributes_destroy (block->attributes);close (block->guest_memfd); -ram_block_discard_require (false); +ram_block_coordinated_discard_require (false); }g_free (block);
Signature · 1 line
2.49.0
[PULL 06/11] migration: Don't sync volatile memory after migration completes
In reply to Peter XuFrom: "Chaney, Ben" <[email protected]>
Syncing volatile memory provides no benefit, instead it can cause performance issues in some cases. Only sync memory that is marked as non-volatile after migration completes on destination.
--- migration/ram.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
migration/ram.c +3 -1
@@ -3680,7 +3680,9 @@ static int ram_load_cleanup(void *opaque)RAMBlock *rb;RAMBLOCK_FOREACH_NOT_IGNORED (rb) { -qemu_ram_block_writeback (rb); +if (memory_region_is_nonvolatile (rb->mr)) { +qemu_ram_block_writeback (rb); + } }xbzrle_load_cleanup ();
Signature · 1 line
2.49.0
[PULL 10/11] ram-block-attributes: Introduce RamBlockAttributes to manage RAMBlock with guest_memfd
In reply to Peter XuFrom: Chenyi Qiang <[email protected]>
Commit 852f0048f3 ("RAMBlock: make guest_memfd require uncoordinated discard") highlighted that subsystems like VFIO may disable RAM block discard. However, guest_memfd relies on discard operations for page conversion between private and shared memory, potentially leading to the stale IOMMU mapping issue when assigning hardware devices to confidential VMs via shared memory. To address this and allow shared device assignement, it is crucial to ensure the VFIO system refreshes its IOMMU mappings.
RamDiscardManager is an existing interface (used by virtio-mem) to adjust VFIO mappings in relation to VM page assignment. Effectively page conversion is similar to hot-removing a page in one mode and adding it back in the other. Therefore, similar actions are required for page conversion events. Introduce the RamDiscardManager to guest_memfd to facilitate this process.
Since guest_memfd is not an object, it cannot directly implement the RamDiscardManager interface. Implementing it in HostMemoryBackend is not appropriate because guest_memfd is per RAMBlock, and some RAMBlocks have a memory backend while others do not. Notably, virtual BIOS RAMBlocks using memory_region_init_ram_guest_memfd() do not have a backend.
To manage RAMBlocks with guest_memfd, define a new object named RamBlockAttributes to implement the RamDiscardManager interface. This object can store the guest_memfd information such as the bitmap for shared memory and the registered listeners for event notifications. A new state_change() helper function is provided to notify listeners, such as VFIO, allowing VFIO to do dynamically DMA map and unmap for the shared memory according to conversion events. Note that in the current context of RamDiscardManager for guest_memfd, the shared state is analogous to being populated, while the private state can be considered discarded for simplicity. In the future, it would be more complicated if considering more states like private/shared/discarded at the same time.
In current implementation, memory state tracking is performed at the host page size granularity, as the minimum conversion size can be one page per request. Additionally, VFIO expected the DMA mapping for a specific IOVA to be mapped and unmapped with the same granularity. Confidential VMs may perform partial conversions, such as conversions on small regions within a larger one. To prevent such invalid cases and until support for DMA mapping cut operations is available, all operations are performed with 4K granularity.
In addition, memory conversion failures cause QEMU to quit rather than resuming the guest or retrying the operation at present. It would be future work to add more error handling or rollback mechanisms once conversion failures are allowed. For example, in-place conversion of guest_memfd could retry the unmap operation during the conversion from shared to private. For now, keep the complex error handling out of the picture as it is not required.
--- MAINTAINERS | 1 + include/system/ramblock.h | 21 ++ system/ram-block-attributes.c | 444 ++++++++++++++++++++++++++++++++++ system/meson.build | 1 + system/trace-events | 3 + 5 files changed, 470 insertions(+) create mode 100644 system/ram-block-attributes.c
MAINTAINERS +1 -0
@@ -3175,6 +3175,7 @@ F: system/memory.c F: system/memory_mapping.c F: system/physmem.c F: system/memory-internal.h +F: system/ram-block-attributes.c F: scripts/coccinelle/memory-region-housekeeping.cocci Memory devices
include/system/ramblock.h +21 -0
@@ -22,6 +22,10 @@#include "exec/cpu-common.h" #include "qemu/rcu.h" #include "exec/ramlist.h" +#include "system/hostmem.h" + +#define TYPE_RAM_BLOCK_ATTRIBUTES "ram-block-attributes" +OBJECT_DECLARE_SIMPLE_TYPE(RamBlockAttributes, RAM_BLOCK_ATTRIBUTES)struct RAMBlock {struct rcu_head rcu;
@@ -91,4 +95,21 @@ struct RAMBlock {ram_addr_t postcopy_length; }; +struct RamBlockAttributes { +Object parent; + +RAMBlock *ram_block; + +/* 1-setting of the bitmap represents ram is populated (shared) */ +unsigned bitmap_size; +unsigned long *bitmap; + + QLIST_HEAD(, RamDiscardListener) rdl_list; +}; + +RamBlockAttributes *ram_block_attributes_create (RAMBlock *ram_block); +void ram_block_attributes_destroy (RamBlockAttributes *attr); +int ram_block_attributes_state_change (RamBlockAttributes *attr,uint64_t offset, +uint64_t size,bool to_discard); +#endif
system/ram-block-attributes.c new file +444 -0
444 lines not on this page · raw message
system/meson.build +1 -0
@@ -17,6 +17,7 @@ system_ss.add(files( 'dma-helpers.c', 'globals.c', 'ioport.c', + 'ram-block-attributes.c', 'memory_mapping.c', 'memory.c', 'physmem.c',
system/trace-events +3 -0
@@ -52,3 +52,6 @@ dirtylimit_state_finalize(void) dirtylimit_throttle_pct(int cpu_index, uint64_t pct, int64_t time_us) "CPU[%d] throttle percent: %" PRIu64 ", throttle adjust time %"PRIi64 " us" dirtylimit_set_vcpu(int cpu_index, uint64_t quota) "CPU[%d] set dirty page rate limit %"PRIu64 dirtylimit_vcpu_execute(int cpu_index, int64_t sleep_time_us) "CPU[%d] sleep %"PRIi64 " us" + +# ram-block-attributes.c +ram_block_attributes_state_change(uint64_t offset, uint64_t size, const char *from, const char *to) "offset 0x%"PRIx64" size 0x%"PRIx64" from '%s' to '%s'"
Signature · 1 line
2.49.0
[PULL 07/11] memory: Export a helper to get intersection of a MemoryRegionSection with a given range
In reply to Peter XuFrom: Chenyi Qiang <[email protected]>
Rename the helper to memory_region_section_intersect_range() to make it more generic. Meanwhile, define the @end as Int128 and replace the related operations with Int128_* format since the helper is exported as a wider API.
--- include/system/memory.h | 30 ++++++++++++++++++++++++++++++ hw/virtio/virtio-mem.c | 32 +++++--------------------------- 2 files changed, 35 insertions(+), 27 deletions(-)
include/system/memory.h +30 -0
@@ -1211,6 +1211,36 @@ MemoryRegionSection *memory_region_section_new_copy(MemoryRegionSection *s);*/ void memory_region_section_free_copy (MemoryRegionSection *s); +/** +* memory_region_section_intersect_range: Adjust the memory section to cover +* the intersection with the given range. +* +* @s: the #MemoryRegionSection to be adjusted +* @offset: the offset of the given range in the memory region +* @size: the size of the given range +* +* Returns false if the intersection is empty, otherwise returns true. +*/ +static inline bool memory_region_section_intersect_range (MemoryRegionSection *s, +uint64_t offset, +uint64_t size) +{ +uint64_t start =MAX (s->offset_within_region, offset); +Int128 end =int128_min (int128_add (int128_make64 (s->offset_within_region), + s->size), +int128_add (int128_make64 (offset), +int128_make64 (size))); + +if (int128_le (end,int128_make64 (start))) { +return false; + } + + s->offset_within_address_space += start - s->offset_within_region; + s->offset_within_region = start; + s->size =int128_sub (end,int128_make64 (start)); +return true; +} +/** * memory_region_init: Initialize a memory region *
hw/virtio/virtio-mem.c +5 -27
@@ -244,28 +244,6 @@ static int virtio_mem_for_each_plugged_range(VirtIOMEM *vmem, void *arg,return ret; } -/* -* Adjust the memory section to cover the intersection with the given range. -* -* Returns false if the intersection is empty, otherwise returns true. -*/ -static bool virtio_mem_intersect_memory_section (MemoryRegionSection *s, -uint64_t offset,uint64_t size) -{ -uint64_t start =MAX (s->offset_within_region, offset); -uint64_t end =MIN (s->offset_within_region +int128_get64 (s->size), - offset + size); - -if (end <= start) { -return false; - } - - s->offset_within_address_space += start - s->offset_within_region; - s->offset_within_region = start; - s->size =int128_make64 (end - start); -return true; -} -typedef int (*virtio_mem_section_cb )(MemoryRegionSection *s,void *arg); static int virtio_mem_for_each_plugged_section(const VirtIOMEM *vmem,
@@ -287,7 +265,7 @@ static int virtio_mem_for_each_plugged_section(const VirtIOMEM *vmem, first_bit + 1) - 1; size = (last_bit - first_bit +1 ) * vmem->block_size; -if (!virtio_mem_intersect_memory_section (&tmp, offset, size)) { +if (!memory_region_section_intersect_range (&tmp, offset, size)) {break ; } ret =cb (&tmp, arg);
@@ -319,7 +297,7 @@ static int virtio_mem_for_each_unplugged_section(const VirtIOMEM *vmem, first_bit + 1) - 1; size = (last_bit - first_bit +1 ) * vmem->block_size; -if (!virtio_mem_intersect_memory_section (&tmp, offset, size)) { +if (!memory_region_section_intersect_range (&tmp, offset, size)) {break ; } ret =cb (&tmp, arg);
@@ -355,7 +333,7 @@ static void virtio_mem_notify_unplug(VirtIOMEM *vmem, uint64_t offset, QLIST_FOREACH(rdl, &vmem->rdl_list, next) {MemoryRegionSection tmp = *rdl->section; -if (!virtio_mem_intersect_memory_section (&tmp, offset, size)) { +if (!memory_region_section_intersect_range (&tmp, offset, size)) {continue ; } rdl->notify_discard (rdl, &tmp);
@@ -371,7 +349,7 @@ static int virtio_mem_notify_plug(VirtIOMEM *vmem, uint64_t offset, QLIST_FOREACH(rdl, &vmem->rdl_list, next) {MemoryRegionSection tmp = *rdl->section; -if (!virtio_mem_intersect_memory_section (&tmp, offset, size)) { +if (!memory_region_section_intersect_range (&tmp, offset, size)) {continue ; } ret = rdl->notify_populate (rdl, &tmp);
@@ -388,7 +366,7 @@ static int virtio_mem_notify_plug(VirtIOMEM *vmem, uint64_t offset,if (rdl2 == rdl) {break ; } -if (!virtio_mem_intersect_memory_section (&tmp, offset, size)) { +if (!memory_region_section_intersect_range (&tmp, offset, size)) {continue ; } rdl2->notify_discard (rdl2, &tmp);
Signature · 1 line
2.49.0
[PULL 04/11] migration: Support fd-based socket address in cpr_transfer_input
In reply to Peter XuFrom: Jaehoon Kim <[email protected]>
Extend cpr_transfer_input to handle SOCKET_ADDRESS_TYPE_FD alongside SOCKET_ADDRESS_TYPE_UNIX. This change supports the use of pre-listened socket file descriptors for cpr migration channels.
This change is particularly useful in qtest environments, where the socket may be created externally and passed via fd.
--- migration/cpr-transfer.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
migration/cpr-transfer.c +5 -2
@@ -46,7 +46,8 @@ QEMUFile *cpr_transfer_input(MigrationChannel *channel, Error **errp)MigrationAddress *addr = channel->addr;if (addr->transport ==MIGRATION_ADDRESS_TYPE_SOCKET && - addr->u.socket.type ==SOCKET_ADDRESS_TYPE_UNIX ) { + (addr->u.socket.type ==SOCKET_ADDRESS_TYPE_UNIX || + addr->u.socket.type ==SOCKET_ADDRESS_TYPE_FD )) {g_autoptr (QIOChannelSocket) sioc =NULL ;SocketAddress *saddr = &addr->u.socket;
@@ -60,7 +61,9 @@ QEMUFile *cpr_transfer_input(MigrationChannel *channel, Error **errp) sioc =qio_net_listener_wait_client (listener); ioc =QIO_CHANNEL (sioc); -trace_cpr_transfer_input (addr->u.socket.u.q_unix.path); +trace_cpr_transfer_input ( + addr->u.socket.type ==SOCKET_ADDRESS_TYPE_UNIX ? + addr->u.socket.u.q_unix.path : addr->u.socket.u.fd.str);qio_channel_set_name (ioc,"cpr-in" );return qemu_file_new_input (ioc);
Signature · 1 line
2.49.0
[PULL 09/11] memory: Unify the definiton of ReplayRamPopulate() and ReplayRamDiscard()
In reply to Peter XuFrom: Chenyi Qiang <[email protected]>
Update ReplayRamDiscard() function to return the result and unify the ReplayRamPopulate() and ReplayRamDiscard() to ReplayRamDiscardState() at the same time due to their identical definitions. This unification simplifies related structures, such as VirtIOMEMReplayData, which makes it cleaner.
--- include/system/memory.h | 74 +++++++++++++++++++++++++++++++---------- hw/virtio/virtio-mem.c | 21 ++++++------ migration/ram.c | 5 +-- system/memory.c | 12 +++---- 4 files changed, 76 insertions(+), 36 deletions(-)
include/system/memory.h +57 -17
@@ -576,8 +576,20 @@ static inline void ram_discard_listener_init(RamDiscardListener *rdl, rdl->double_discard_supported = double_discard_supported; } -typedef int (*ReplayRamPopulate )(MemoryRegionSection *section,void *opaque); -typedef void (*ReplayRamDiscard )(MemoryRegionSection *section,void *opaque); +/** +* typedef ReplayRamDiscardState: +* +* The callback handler for #RamDiscardManagerClass.replay_populated/ +* #RamDiscardManagerClass.replay_discarded to invoke on populated/discarded +* parts. +* +* @section: the #MemoryRegionSection of populated/discarded part +* @opaque: pointer to forward to the callback +* +* Returns 0 on success, or a negative error if failed. +*/ +typedef int (*ReplayRamDiscardState )(MemoryRegionSection *section, +void *opaque);/* * RamDiscardManagerClass:
@@ -651,36 +663,38 @@ struct RamDiscardManagerClass {/** * @replay_populated: * -* Call the #ReplayRamPopulate callback for all populated parts within the -* #MemoryRegionSection via the #RamDiscardManager. +* Call the #ReplayRamDiscardState callback for all populated parts within +* the #MemoryRegionSection via the #RamDiscardManager. * * In case any call fails, no further calls are made. * * @rdm: the #RamDiscardManager * @section: the #MemoryRegionSection -* @replay_fn: the #ReplayRamPopulate callback +* @replay_fn: the #ReplayRamDiscardState callback * @opaque: pointer to forward to the callback * * Returns 0 on success, or a negative error if any notification failed. */ int (*replay_populated)(const RamDiscardManager *rdm,MemoryRegionSection *section, -ReplayRamPopulate replay_fn,void *opaque); +ReplayRamDiscardState replay_fn,void *opaque);/** * @replay_discarded: * -* Call the #ReplayRamDiscard callback for all discarded parts within the -* #MemoryRegionSection via the #RamDiscardManager. +* Call the #ReplayRamDiscardState callback for all discarded parts within +* the #MemoryRegionSection via the #RamDiscardManager. * * @rdm: the #RamDiscardManager * @section: the #MemoryRegionSection -* @replay_fn: the #ReplayRamDiscard callback +* @replay_fn: the #ReplayRamDiscardState callback * @opaque: pointer to forward to the callback +* +* Returns 0 on success, or a negative error if any notification failed. */ -void (*replay_discarded)(const RamDiscardManager *rdm, -MemoryRegionSection *section, -ReplayRamDiscard replay_fn,void *opaque); +int (*replay_discarded)(const RamDiscardManager *rdm, +MemoryRegionSection *section, +ReplayRamDiscardState replay_fn,void *opaque);/** * @register_listener:
@@ -721,15 +735,41 @@ uint64_t ram_discard_manager_get_min_granularity(const RamDiscardManager *rdm,bool ram_discard_manager_is_populated (const RamDiscardManager *rdm,const MemoryRegionSection *section); +/** +* ram_discard_manager_replay_populated: +* +* A wrapper to call the #RamDiscardManagerClass.replay_populated callback +* of the #RamDiscardManager. +* +* @rdm: the #RamDiscardManager +* @section: the #MemoryRegionSection +* @replay_fn: the #ReplayRamDiscardState callback +* @opaque: pointer to forward to the callback +* +* Returns 0 on success, or a negative error if any notification failed. +*/ int ram_discard_manager_replay_populated (const RamDiscardManager *rdm,MemoryRegionSection *section, -ReplayRamPopulate replay_fn, +ReplayRamDiscardState replay_fn,void *opaque); -void ram_discard_manager_replay_discarded (const RamDiscardManager *rdm, -MemoryRegionSection *section, -ReplayRamDiscard replay_fn, -void *opaque); +/** +* ram_discard_manager_replay_discarded: +* +* A wrapper to call the #RamDiscardManagerClass.replay_discarded callback +* of the #RamDiscardManager. +* +* @rdm: the #RamDiscardManager +* @section: the #MemoryRegionSection +* @replay_fn: the #ReplayRamDiscardState callback +* @opaque: pointer to forward to the callback +* +* Returns 0 on success, or a negative error if any notification failed. +*/ +int ram_discard_manager_replay_discarded (const RamDiscardManager *rdm, +MemoryRegionSection *section, +ReplayRamDiscardState replay_fn, +void *opaque); void ram_discard_manager_register_listener(RamDiscardManager *rdm, RamDiscardListener *rdl,
hw/virtio/virtio-mem.c +10 -11
@@ -1732,7 +1732,7 @@ static bool virtio_mem_rdm_is_populated(const RamDiscardManager *rdm, }struct VirtIOMEMReplayData { -void *fn; +ReplayRamDiscardState fn;void *opaque; };
@@ -1740,12 +1740,12 @@ static int virtio_mem_rdm_replay_populated_cb(MemoryRegionSection *s, void *arg) {struct VirtIOMEMReplayData *data = arg; -return ((ReplayRamPopulate )data->fn)(s, data->opaque); +return data->fn (s, data->opaque); }static int virtio_mem_rdm_replay_populated (const RamDiscardManager *rdm,MemoryRegionSection *s, -ReplayRamPopulate replay_fn, +ReplayRamDiscardState replay_fn,void *opaque) {const VirtIOMEM *vmem =VIRTIO_MEM (rdm);
@@ -1764,14 +1764,13 @@ static int virtio_mem_rdm_replay_discarded_cb(MemoryRegionSection *s, {struct VirtIOMEMReplayData *data = arg; - ((ReplayRamDiscard )data->fn)(s, data->opaque); -return 0 ; +return data->fn (s, data->opaque); } -static void virtio_mem_rdm_replay_discarded (const RamDiscardManager *rdm, -MemoryRegionSection *s, -ReplayRamDiscard replay_fn, -void *opaque) +static int virtio_mem_rdm_replay_discarded (const RamDiscardManager *rdm, +MemoryRegionSection *s, +ReplayRamDiscardState replay_fn, +void *opaque) {const VirtIOMEM *vmem =VIRTIO_MEM (rdm);struct VirtIOMEMReplayData data = {
@@ -1780,8 +1779,8 @@ static void virtio_mem_rdm_replay_discarded(const RamDiscardManager *rdm, };g_assert (s->mr == &vmem->memdev->mr); -virtio_mem_for_each_unplugged_section (vmem, s, &data, - virtio_mem_rdm_replay_discarded_cb); +return virtio_mem_for_each_unplugged_section (vmem, s, &data, + virtio_mem_rdm_replay_discarded_cb); } static void virtio_mem_rdm_register_listener(RamDiscardManager *rdm,
migration/ram.c +3 -2
@@ -856,8 +856,8 @@ static inline bool migration_bitmap_clear_dirty(RAMState *rs,return ret; } -static void dirty_bitmap_clear_section (MemoryRegionSection *section, -void *opaque) +static int dirty_bitmap_clear_section (MemoryRegionSection *section, +void *opaque) {const hwaddr offset = section->offset_within_region;const hwaddr size =int128_get64 (section->size);
@@ -876,6 +876,7 @@ static void dirty_bitmap_clear_section(MemoryRegionSection *section, } *cleared_bits +=bitmap_count_one_with_offset (rb->bmap, start, npages);bitmap_clear (rb->bmap, start, npages); +return 0 ; }/*
system/memory.c +6 -6
@@ -2138,7 +2138,7 @@ bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,int ram_discard_manager_replay_populated (const RamDiscardManager *rdm,MemoryRegionSection *section, -ReplayRamPopulate replay_fn, +ReplayRamDiscardState replay_fn,void *opaque) {RamDiscardManagerClass *rdmc =RAM_DISCARD_MANAGER_GET_CLASS (rdm);
@@ -2147,15 +2147,15 @@ int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,return rdmc->replay_populated (rdm, section, replay_fn, opaque); } -void ram_discard_manager_replay_discarded (const RamDiscardManager *rdm, -MemoryRegionSection *section, -ReplayRamDiscard replay_fn, -void *opaque) +int ram_discard_manager_replay_discarded (const RamDiscardManager *rdm, +MemoryRegionSection *section, +ReplayRamDiscardState replay_fn, +void *opaque) {RamDiscardManagerClass *rdmc =RAM_DISCARD_MANAGER_GET_CLASS (rdm);g_assert (rdmc->replay_discarded); - rdmc->replay_discarded (rdm, section, replay_fn, opaque); +return rdmc->replay_discarded (rdm, section, replay_fn, opaque); } void ram_discard_manager_register_listener(RamDiscardManager *rdm,
Signature · 1 line
2.49.0
[PULL 08/11] memory: Change memory_region_set_ram_discard_manager() to return the result
In reply to Peter XuFrom: Chenyi Qiang <[email protected]>
Modify memory_region_set_ram_discard_manager() to return -EBUSY if a RamDiscardManager is already set in the MemoryRegion. The caller must handle this failure, such as having virtio-mem undo its actions and fail the realize() process. Opportunistically move the call earlier to avoid complex error handling.
This change is beneficial when introducing a new RamDiscardManager instance besides virtio-mem. After ram_block_coordinated_discard_require(true) unlocks all RamDiscardManager instances, only one instance is allowed to be set for one MemoryRegion at present.
--- include/system/memory.h | 6 +++--- hw/virtio/virtio-mem.c | 30 +++++++++++++++++------------- system/memory.c | 10 +++++++--- 3 files changed, 27 insertions(+), 19 deletions(-)
include/system/memory.h +3 -3
@@ -2499,13 +2499,13 @@ static inline bool memory_region_has_ram_discard_manager(MemoryRegion *mr)* * This function must not be called for a mapped #MemoryRegion, a #MemoryRegion * that does not cover RAM, or a #MemoryRegion that already has a -* #RamDiscardManager assigned. +* #RamDiscardManager assigned. Return 0 if the rdm is set successfully. * * @mr: the #MemoryRegion * @rdm: #RamDiscardManager to set */ -void memory_region_set_ram_discard_manager (MemoryRegion *mr, -RamDiscardManager *rdm); +int memory_region_set_ram_discard_manager (MemoryRegion *mr, +RamDiscardManager *rdm);/** * memory_region_find: translate an address/size relative to a
hw/virtio/virtio-mem.c +17 -13
@@ -1047,6 +1047,17 @@ static void virtio_mem_device_realize(DeviceState *dev, Error **errp)return ; } +/* +* Set ourselves as RamDiscardManager before the plug handler maps the +* memory region and exposes it via an address space. +*/ +if (memory_region_set_ram_discard_manager (&vmem->memdev->mr, +RAM_DISCARD_MANAGER (vmem))) { +error_setg (errp,"Failed to set RamDiscardManager" ); +ram_block_coordinated_discard_require (false); +return ; + } +/* * We don't know at this point whether shared RAM is migrated using * QEMU or migrated using the file content. "x-ignore-shared" will be
@@ -1061,6 +1072,7 @@ static void virtio_mem_device_realize(DeviceState *dev, Error **errp) ret =ram_block_discard_range (rb,0 ,qemu_ram_get_used_length (rb));if (ret) {error_setg_errno (errp, -ret,"Unexpected error discarding RAM" ); +memory_region_set_ram_discard_manager (&vmem->memdev->mr,NULL );ram_block_coordinated_discard_require (false);return ; }
@@ -1122,13 +1134,6 @@ static void virtio_mem_device_realize(DeviceState *dev, Error **errp) vmem->system_reset =VIRTIO_MEM_SYSTEM_RESET (obj); vmem->system_reset->vmem = vmem;qemu_register_resettable (obj); - -/* -* Set ourselves as RamDiscardManager before the plug handler maps the -* memory region and exposes it via an address space. -*/ -memory_region_set_ram_discard_manager (&vmem->memdev->mr, -RAM_DISCARD_MANAGER (vmem)); }static void virtio_mem_device_unrealize (DeviceState *dev)
@@ -1136,12 +1141,6 @@ static void virtio_mem_device_unrealize(DeviceState *dev)VirtIODevice *vdev =VIRTIO_DEVICE (dev);VirtIOMEM *vmem =VIRTIO_MEM (dev); -/* -* The unplug handler unmapped the memory region, it cannot be -* found via an address space anymore. Unset ourselves. -*/ -memory_region_set_ram_discard_manager (&vmem->memdev->mr,NULL ); -qemu_unregister_resettable (OBJECT (vmem->system_reset));object_unref (OBJECT (vmem->system_reset));
@@ -1154,6 +1153,11 @@ static void virtio_mem_device_unrealize(DeviceState *dev)virtio_del_queue (vdev,0 );virtio_cleanup (vdev);g_free (vmem->bitmap); +/* +* The unplug handler unmapped the memory region, it cannot be +* found via an address space anymore. Unset ourselves. +*/ +memory_region_set_ram_discard_manager (&vmem->memdev->mr,NULL );ram_block_coordinated_discard_require (false); }
system/memory.c +7 -3
@@ -2106,12 +2106,16 @@ RamDiscardManager *memory_region_get_ram_discard_manager(MemoryRegion *mr)return mr->rdm; } -void memory_region_set_ram_discard_manager (MemoryRegion *mr, -RamDiscardManager *rdm) +int memory_region_set_ram_discard_manager (MemoryRegion *mr, +RamDiscardManager *rdm) {g_assert (memory_region_is_ram (mr)); -g_assert (!rdm || !mr->rdm); +if (mr->rdm && rdm) { +return -EBUSY ; + } + mr->rdm = rdm; +return 0 ; } uint64_t ram_discard_manager_get_min_granularity(const RamDiscardManager *rdm,
Signature · 1 line
2.49.0
Stefan Hajnoczi
AppliedApplied, thanks.
Please update the changelog at https://wiki.qemu.org/ChangeLog/10.1 for any user-visible changes.