fault tolerance through micro-checkpointing
cover fault tolerance through micro-checkpointing
From: "Michael R. Hines" <[email protected]>
This patch implements RDMA-aware fault tolerance for the VM using Micro-Checkpointing (to be presented at the KVM Forum).
The breakout of the patches is not ideal and is really meant to kick things off for review, which will likely extend well past 1.7 and into 1.8 version of QEMU, assuming about 5-6 months of reviews.
Please begin with patch #01 as it provides a good narrative of what is different about this and previous attempts at fault tolerance, including a breakdown of the current empirical performance challenges.
Michael R. Hines (12):
mc: add documentation for micro-checkpointing
rdma: remove reference to github.com
migration: introduce parallelization of migration_bitmap
mc: introduce a "checkpointing" status check into the VCPU states
migration: support custom page loading
rdma: accelerated memcpy() support
mc: introduce state machine error handling and migration_bitmap prep
mc: modified QMP statistics and migration_thread handoff
mc: core logic
mc: configure and makefile support
mc: register MC qemu-file functions and expose MC tunable capability
mc: activate and use MC core logic if requested
Makefile.objs | 1 + arch_init.c | 276 +++++- configure | 45 + cpus.c | 9 +- docs/mc.txt | 261 ++++++ docs/rdma.txt | 1 - hmp-commands.hx | 14 + hmp.c | 23 + hmp.h | 1 + include/migration/migration.h | 69 +- include/migration/qemu-file.h | 55 +- include/qemu-common.h | 12 + migration-checkpoint.c | 1589 ++++++++++++++++++++++++++++++++ migration-rdma.c | 2008 ++++++++++++++++++++++++++++++----------- migration.c | 148 ++- qapi-schema.json | 92 +- qmp-commands.hx | 23 + savevm.c | 84 +- vl.c | 42 + 19 files changed, 4123 insertions(+), 630 deletions(-) create mode 100644 docs/mc.txt create mode 100644 migration-checkpoint.c
Signature · 1 line
1.8.1.2
RFC PATCH 1/12 mc: add documentation for micro-checkpointing
From: "Michael R. Hines" <[email protected]>
--- docs/mc.txt | 261 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 docs/mc.txt
docs/mc.txt new file +261 -0
@@ -0,0 +1,261 @@ +Micro Checkpointing Specification +============================================== +Wiki: http://wiki.qemu.org/Features/MicroCheckpointing +Github: [email protected]:hinesmr/qemu.git, 'mc' branch + +Copyright (C) 2014 Michael R. Hines <[email protected]> + +Contents: +========= +* Introduction +* The Micro-Checkpointing Process +* RDMA Integration +* Failure Recovery +* Before running +* Running +* Performance +* TODO + +INTRODUCTION: +============= + +Micro-Checkpointing (MC) is one method for providing Fault Tolerance to a +running virtual machine (VM) with neither runtime assistance from the guest +kernel nor from the guest application software. Furthermore, Fault Tolerance +is one method of providing high availability to a VM such that, from the +perspective of the outside world (clients, devices, and neighboring VMs that +may be paired with it), the VM and its applications have not lost any runtime +state in the event of either a failure of the hypervisor/hardware to allow the +VM to make forward progress or a complete loss of power. This mechanism for +providing fault tolerance does *not* provide any protection whatsoever against +software-level faults in the guest kernel or applications. In fact, due to +the potentially extended lifetime of the VM because of this type of high +availability, such software-level bugs may in fact manifest themselves +*more often* than they ordinarily would, in which case you would need to +employ other forms of availability to guard against such software-level faults. + +This implementation is also fully compatible with RDMA. (See docs/rdma.txt +for more details). + +THE MICRO-CHECKPOINTING PROCESS: +================================ + +Micro-Checkpointing works against the existing live migration path in QEMU, +and can effectively be understood as a "live migration that never ends". +As such, iterations rounds happen at the granularity of 10s of milliseconds +and perform the following steps: + +1. After N milliseconds, stop the VM. +2. Generate a MC by invoking the live migration software path + to identify and copy dirty memory into a local staging area inside QEMU. +3. Resume the VM immediately so that it can make forward progress. +4. Transmit the checkpoint to the destination. +5. Repeat + +Upon failure, load the contents of the last MC at the destination back +into memory and run the VM normally. + +Additionally, a MC must include a consistent view of device I/O, +particularly the network, a problem commonly referred to as "output commit". +This means that the outside world can not be allowed to experience duplicate +state that was committed by the virtual machine after failure. This is +possible because a checkpoint may diverge by N milliseconds of time and +commit state while the current checkpoint is being transmitted to the +destination. + +To guard against this problem, first, we must "buffer" the TX output of the +network (not the input) between MCs until the current MC is safely received +by the destination. For example, all outbound network packets must be held +at the source until the MC is transmitted. After transmission is complete, +those packets can be released. Similarly, in the case of disk I/O, we must +ensure that either the contents of the local disk is safely mirrored to a +remote disk before completing a MC or that the output to a shared disk, +such as iSCSI, is also buffered between checkpoints and then later released +in the same way. + +This implementation *currently* only supports buffering for the network. +This requires that the VM's root disk or any non-ephemeral disks also be +made network-accessible directly from within the VM. Until the aforementioned +buffering or mirroring support is available (ideally through drive-mirror), +the only "consistent" way to provide full fault tolerance of the VM's +non-ephemeral disks is to construct a VM whose root disk is made to boot +directly from iSCSI or NFS or similar such that all disk I/O is translated +into network I/O. + +RDMA INTEGRATION: +================= + +RDMA is instrumental in enabling better MC performance, which is the reason +why it was introduced into QEMU first. + +1. Checkpoint generation (RDMA-based memcpy): +2. Checkpoint transmission (for performance and less CPU impact) + +Checkpoint generation (step 2 in the previous section) must be done while +the VM is paused. In the worst case, the size of the checkpoint can be +equal in size to the amount of memory in total use by the VM. In order +to resume VM execution as fast as possible, the checkpoint is copied +consistently locally into a staging area before transmission. A standard +memcpy() of potentially such a large amount of memory not only gets +no use out of the CPU cache but also potentially clogs up the CPU pipeline +which would otherwise be useful by other neighbor VMs on the same +physical node that could be scheduled for execution by Linux. To minimize +the effect on neighbor VMs, we use RDMA to perform a "local" memcpy(), +bypassing the host processor. + +Checkpoint transmission can potentially consume very large amounts of +both bandwidth as well as CPU utilization that could otherwise by used by +the VM itself or its neighbors. Once the aforementioned local copy of the +checkpoint is saved, this implementation makes use of the same RDMA +hardware to perform the transmission, similar to the way a live migration +happens over RDMA (see docs/rdma.txt). + +FAILURE RECOVERY: +================= + +Due to the high-frequency nature of micro-checkpointing, we expect +a new checkpoint to be generated many times per second. Even missing just +a few checkpoints easily constitutes a failure. Because of the consistent +buffering of device I/O, this is safe because device I/O is not committed +to the outside world until the checkpoint has been received at the +destination. + +Failure is thus assumed under two conditions: + +1. MC over TCP/IP: Once the socket connection breaks, we assume failure. + This happens very early in the loss of the latest + checkpoint not only because a very large amount of bytes is + typically being sequenced in a TCP stream but perhaps + also because of the timeout in acknowledgement of + the receipt of a commit message by the destination. + +2. MC over RDMA: Since Infiniband does not provide any user-level timeout + mechanisms, this implementation enhances QEMU's + RDMA migration protocol to include a simple keep-alive. + Upon the loss of multiple keep-alive messages, the + sender is deemed to be failed. + +In both cases, either due to a failed TCP socket connection or lost RDMA +keep-alive group, both the sender or the receiver can be deemed to be failed. + +If the sender is deemed to be failed, the destination takes over immediately +using the contents of the last checkpoint. + +If the destination is deemed to be lost, we perform the same action as +a live migration: resume the sender normally and wait for management software +to make a policy decision about whether or not to re-protect the VM, +which may involve a third-party to identify a new destination host again to +use as a backup for the VM. + +BEFORE RUNNING: +=============== + +First, compile QEMU with '--enable-mc' and ensure that the corresponding +libraries for netlink are available. The netlink 'plug' support from the +Qdisc functionality is required in particular, because it allows QEMU to +direct the kernel to buffer outbound network packages between checkpoints +as described previously. + +Next, start the VM that you want to protect using your standard procedures. + +Enable MC like this: + +QEMU Monitor Command: +$ migrate_set_capability x-mc on # disabled by default + +Currently, only one network interface is supported, *and* currently you +must ensure that the root disk of your VM is booted either directly from +iSCSI or NFS, as described previously. This will be rectified with future +improvements. + +For testing only, you can ignore the aforementioned requirements +if you simply want to get an understanding of the performance +penalties associated with this feature activated. + +Next, you can optionally disable network-buffering for additional test-only +execution. This is useful if you want to get a breakdown only what the cost +of the checkpointing the memory state is without the cost of +checkpointing device state. + +QEMU Monitor Command: +$ migrate_set_capability mc-net-disable on # buffering activated by default + +Next, you can optionally enable RDMA 'memcpy' support. +This is only valid if you have RDMA support compiled into QEMU and you intend +to use the 'rdma' migration URI upon initiating MC as described later. + +QEMU Monitor Command: +$ migrate_set_capability mc-rdma-copy on # disabled by default + +Next, you can optionally enable the 'bitworkers' feature of QEMU. +This is allows QEMU to use all available host CPU cores to parallelize +the process of processing the migration dirty bitmap as described previously. +For normal live migrations, we disable this by default as migration is +typically a short-lived operation. + +QEMU Monitor Command: +$ migrate_set_capability bitworkers on # disabled by default + +Finally, if you are using QEMU's support for RDMA migration, you will want +to enable RDMA keep-alive support to allow quick detection of failure. If +you are using TCP/IP, this is not required: + +QEMU Monitor Command: +$ migrate_set_capability rdma-keepalive on # disabled by default + +RUNNING: +======== + +MC can be initiated with exactly the same command as standard live migration: + +QEMU Monitor Command: +$ migrate -d (tcp|rdma):host:port + +Upon failure, the destination VM will detect a loss in network connectivity +and automatically revert to the last checkpoint taken and resume execution +immediately. There is no need for additional QEMU monitor commands to initiate +the recovery process. + +PERFORMANCE: +============ + +By far, the biggest cost is network throughput. Virtual machines are capable +of dirtying memory well in excess of the bandwidth provided a commodity 1 Gbps +network link. If so, the MC process will always lag behind the virtual machine +and forward progress will be poor. It is highly recommended to use at least +a 10 Gbps link when using MC. + +Numbers are still coming in, but without output buffering of network I/O, +the performance penalty on a typical 4GB RAM Java-based application server workload +using a 10 Gbps link (a good worst case for testing due Java's constant +garbage collection) is on the order of 25%. With network buffering activated, +this can be as high as 50%. + +The majority of the 25% penalty is due to the preparation of the QEMU migration +dirty bitmap, which can incur tens of milliseconds of downtime against the guest. + +The remaining 25% penalty comes from network buffering is typically due to checkpoints +not occurring fast enough since a typical "round trip" time between the request of +an application-level transaction and the corresponding response should ideally be +larger than the time it takes to complete a checkpoint, otherwise, the response +to the application within the VM will appear to be congested since the VM's network +endpoint may not have even received the TX request from the application in the +first place. + +We believe that this effect is "amplified" due to the poor performance in +processing the migration bitmap and thus since an application-level RTT cannot +be serviced with more frequent checkpoints, network I/O tends to get held in +the buffer too long. This has the effect of causing the guest TCP/IP stack +to experience congestion, propagating this artificially created delay all the +way up to the application. + +TODO: +===== + +1. Eliminate as much of the cost of migration dirty bitmap preparation as possible. + Parallelization is really only a stop-gap measure. + +2. Implement local disk mirroring by integrating with QEMU's 'drive-mirror' + feature in order to full support virtual machines with local storage. + +3. Implement output commit buffering for shared storage.
Signature · 1 line
1.8.1.2
RFC PATCH 2/12 rdma: remove reference to github.com
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
--- docs/rdma.txt | 1 - 1 file changed, 1 deletion(-)
docs/rdma.txt +0 -1
@@ -2,7 +2,6 @@ RDMA Live Migration Specification, Version # 1 ============================================== Wiki: http://wiki.qemu-project.org/Features/RDMALiveMigration -Github: [email protected]:hinesmr/qemu.git, 'rdma' branch Copyright (C) 2013 Michael R. Hines <[email protected]>
Signature · 1 line
1.8.1.2
RFC PATCH 3/12 migration: introduce parallelization of migration_bitmap
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
This patch allows the preparation of the migration_bitmap to be parallelized. For very large VMs, this can take on the order of 10s of milliseconds, which translates as downtime.
We count the number of cores first, and then handout chunks of the logdirty bitmap to a thread per core. Each thread scans for dirty bits in parallel.
--- arch_init.c | 228 +++++++++++++++++++++++++++++++++++++++--- include/migration/migration.h | 10 ++ include/qemu-common.h | 12 +++ qapi-schema.json | 73 +++++++++++++- vl.c | 33 ++++++ 5 files changed, 340 insertions(+), 16 deletions(-)
arch_init.c +213 -15
@@ -189,6 +189,8 @@ typedef struct AccountingInfo {uint64_t skipped_pages;uint64_t norm_pages;uint64_t iterations; +uint64_t log_dirty_time; +uint64_t migration_bitmap_time;uint64_t xbzrle_bytes;uint64_t xbzrle_pages;uint64_t xbzrle_cache_miss;
@@ -232,6 +234,16 @@ uint64_t norm_mig_pages_transferred(void)return acct_info.norm_pages; } +uint64_t norm_mig_log_dirty_time (void ) +{ +return acct_info.log_dirty_time; +} + +uint64_t norm_mig_bitmap_time (void ) +{ +return acct_info.migration_bitmap_time; +} +uint64_t xbzrle_mig_bytes_transferred (void ) {return acct_info.xbzrle_bytes;
@@ -362,15 +374,189 @@ ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,static inline bool migration_bitmap_set_dirty (MemoryRegion *mr,ram_addr_t offset) { -bool ret; -int nr = (mr->ram_addr + offset) >>TARGET_PAGE_BITS ; +return test_and_set_bit ((mr->ram_addr + offset) >>TARGET_PAGE_BITS , + migration_bitmap); +} + +typedef struct BitmapWalkerParams { +QemuMutex ready_mutex; +QemuMutex done_mutex; +QemuCond cond; +QemuThread walker; +MigrationState *s; +int core_id; +int keep_running; +ram_addr_t start; +ram_addr_t stop; +void *block; +uint64_t dirty_pages; +}BitmapWalkerParams ; - ret =test_and_set_bit (nr, migration_bitmap); +static int nb_bitmap_workers =0 ; -if (!ret) { - migration_dirty_pages++; +BitmapWalkerParams *bitmap_walkers =NULL ; + +/* +* Bitmap workers: This is a temporary performance-driven +* workaround for the slowness (10s of milliseconds) incurred +* during calls to migration_bitmap_sync(). +* +* Ideally, migration_bitmap_sync() should be able to use the +* GET_LOG_DIRTY bitmap from KVM directly, but it does not right +* now because the bitmap is not retrieved as a single memory +* allocation which requires a couple of transformations into +* a 'unified' bitmap before the migration code can make good use +* of it. +* +* Bitmap workers perform this transformation in parallel +* in a multi-threaded fashion until a patch is ready to process +* the bitmaps from GET_LOG_DIRTY directly. +*/ +static uint64_t migration_bitmap_sync_range (RAMBlock *block, +ram_addr_t start,ram_addr_t stop) +{ +ram_addr_t addr; +uint64_t dirty_pages =0 ; + + +for (addr = start; addr < stop; addr +=TARGET_PAGE_SIZE ) { +if (memory_region_test_and_clear_dirty (block->mr, + addr,TARGET_PAGE_SIZE , +DIRTY_MEMORY_MIGRATION )) { +if (!migration_bitmap_set_dirty (block->mr, addr)) { + dirty_pages++; + } + } + } + +return dirty_pages; +} + +/* +* The worker sleeps until it gets some work to transform a +* chunk of bitmap from KVM to the migration_bitmap. +*/ +void *migration_bitmap_worker (void *opaque) +{ +BitmapWalkerParams * bwp = opaque; + +do { +qemu_mutex_lock (&bwp->ready_mutex); +qemu_mutex_lock (&bwp->done_mutex); +qemu_mutex_unlock (&bwp->ready_mutex); +qemu_cond_signal (&bwp->cond); + +if (!bwp->keep_running) { +break ; + } + + bwp->dirty_pages =migration_bitmap_sync_range (bwp->block, bwp->start, bwp->stop); + +qemu_cond_wait (&bwp->cond, &bwp->done_mutex); +qemu_mutex_unlock (&bwp->done_mutex); + }while (bwp->keep_running); + +return NULL ; +} + +void migration_bitmap_worker_start (MigrationState *s) +{ +int core; + +/* +* CPUs N - 1 are reserved for N - 1 worker threads +* processing the pc.ram bytemap => migration_bitmap. +* The migration thread goes on the last CPU, +* which process the remaining, smaller RAMblocks. +*/ + nb_bitmap_workers =getNumCores () -1 ; + + bitmap_walkers =g_malloc0 (sizeof (struct BitmapWalkerParams ) * + nb_bitmap_workers); + +memset (bitmap_walkers,0 ,sizeof (BitmapWalkerParams) * nb_bitmap_workers); + +for (core =0 ; core < nb_bitmap_workers; core++) { +BitmapWalkerParams * bwp = &bitmap_walkers[core]; + bwp->core_id = core; + bwp->keep_running =1 ; + bwp->s = s; +qemu_cond_init (&bwp->cond); +qemu_mutex_init (&bwp->ready_mutex); +qemu_mutex_init (&bwp->done_mutex); +qemu_mutex_lock (&bwp->ready_mutex); + } + +for (core =0 ; core < nb_bitmap_workers; core++) { +BitmapWalkerParams * bwp = &bitmap_walkers[core]; +qemu_thread_create (&bwp->walker, + migration_bitmap_worker, bwp,QEMU_THREAD_DETACHED ); + } +} + +void migration_bitmap_worker_stop (MigrationState *s) +{ +int core; + +for (core =0 ; core < nb_bitmap_workers; core++) { +BitmapWalkerParams * bwp = &bitmap_walkers[core]; + bwp->keep_running =0 ; +qemu_mutex_unlock (&bwp->ready_mutex); + } + +DPRINTF ("Bitmap workers stopped.\n" ); + +g_free (bitmap_walkers); + bitmap_walkers =NULL ; + nb_bitmap_workers =0 ; +} + + +static void migration_bitmap_distribute_specific_worker (MigrationState *s,RAMBlock * block,int core,ram_addr_t start,ram_addr_t stop) +{ +BitmapWalkerParams * bwp = &bitmap_walkers[core]; + + bwp->start = start; + bwp->stop = stop; + bwp->block = block; + +qemu_cond_wait (&bwp->cond, &bwp->ready_mutex); +} + +static void migration_bitmap_join_worker (MigrationState *s,int core) +{ +BitmapWalkerParams * bwp = &bitmap_walkers[core]; +qemu_mutex_lock (&bwp->done_mutex); +qemu_cond_signal (&bwp->cond); +qemu_mutex_unlock (&bwp->done_mutex); + migration_dirty_pages += bwp->dirty_pages; +} + +/* +* Chop up the QEMU 'bytemap' built around GET_LOG_DIRTY and handout +* the migration_bitmap population work to all the workers. +* +* If there are N cpus in the hypervisor, there will be N workers +* which each process equal chunks of the RAM block bytemap. +*/ +static void migration_bitmap_distribute_work (MigrationState *s,RAMBlock * block) +{ +uint64_t pages = block->length /TARGET_PAGE_SIZE ; +uint64_t inc = pages / nb_bitmap_workers; +uint64_t remainder = pages % inc; +int core; + +for (core =0 ; core < nb_bitmap_workers; core++) { +ram_addr_t start = core * inc, stop = core * inc + inc; + +if (core == (nb_bitmap_workers -1 )) + stop += remainder; + + start *=TARGET_PAGE_SIZE ; + stop *=TARGET_PAGE_SIZE ; + +migration_bitmap_distribute_specific_worker (s, block, core, start, stop); } -return ret; }/* Needs iothread lock! */
@@ -378,7 +564,6 @@ static inline bool migration_bitmap_set_dirty(MemoryRegion *mr,static void migration_bitmap_sync (void ) {RAMBlock *block; -ram_addr_t addr;uint64_t num_dirty_pages_init = migration_dirty_pages;MigrationState *s =migrate_get_current ();static int64_t start_time;
@@ -386,33 +571,46 @@ static void migration_bitmap_sync(void)static int64_t num_dirty_pages_period;int64_t end_time;int64_t bytes_xfer_now; +int64_t begin_time; +int64_t dirty_time;if (!bytes_xfer_prev) { bytes_xfer_prev =ram_bytes_transferred (); } + begin_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME );if (!start_time) { start_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); } -trace_migration_bitmap_sync_start ();address_space_sync_dirty_bitmap (&address_space_memory); + dirty_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); + QTAILQ_FOREACH(block, &ram_list.blocks, next) { -for (addr =0 ; addr < block->length; addr +=TARGET_PAGE_SIZE ) { -if (memory_region_test_and_clear_dirty (block->mr, - addr,TARGET_PAGE_SIZE , -DIRTY_MEMORY_MIGRATION )) { -migration_bitmap_set_dirty (block->mr, addr); - } +if (!strcmp (block->idstr,"pc.ram" ) && nb_bitmap_workers) { +migration_bitmap_distribute_work (s, block); +continue ; } + migration_dirty_pages +=migration_bitmap_sync_range (block,0 , block->length); } + +if (nb_bitmap_workers) { +int core; +for (core =0 ; core < nb_bitmap_workers; core++) { +migration_bitmap_join_worker (s, core); + } + } +trace_migration_bitmap_sync_end (migration_dirty_pages - num_dirty_pages_init); num_dirty_pages_period += migration_dirty_pages - num_dirty_pages_init; end_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); -/* more than 1 second = 1000 millisecons */ + acct_info.log_dirty_time += dirty_time - begin_time; + acct_info.migration_bitmap_time += end_time - dirty_time; + +/* more than 1 second = 1000 milliseconds */ if (end_time > start_time +1000 ) {if (migrate_auto_converge ()) {/* The following detection logic can be refined later. For now:
include/migration/migration.h +10 -0
@@ -45,6 +45,10 @@ struct MigrationStateint64_t total_time;int64_t downtime;int64_t expected_downtime; +int64_t xmit_time; +int64_t ram_copy_time; +int64_t log_dirty_time; +int64_t bitmap_time;int64_t dirty_pages_rate;int64_t dirty_bytes_rate;bool enabled_capabilities[MIGRATION_CAPABILITY_MAX ];
@@ -109,10 +113,16 @@ uint64_t skipped_mig_bytes_transferred(void);uint64_t skipped_mig_pages_transferred (void );uint64_t norm_mig_bytes_transferred (void );uint64_t norm_mig_pages_transferred (void ); +uint64_t norm_mig_log_dirty_time (void ); +uint64_t norm_mig_bitmap_time (void );uint64_t xbzrle_mig_bytes_transferred (void );uint64_t xbzrle_mig_pages_transferred (void );uint64_t xbzrle_mig_pages_overflow (void );uint64_t xbzrle_mig_pages_cache_miss (void ); +void *migration_bitmap_worker (void *opaque); +void migration_bitmap_worker_start (MigrationState *s); +void migration_bitmap_worker_stop (MigrationState *s); +void migrate_set_state (MigrationState *s,int old_state,int new_state);void ram_handle_compressed (void *host,uint8_t ch,uint64_t size);
include/qemu-common.h +12 -0
@@ -478,4 +478,16 @@ size_t buffer_find_nonzero_offset(const void *buf, size_t len);*/ int parse_debug_env (const char *name,int max,int initial); +/* +* Headers to get number of host processors. +*/ +int getNumCores (void ); +#if defined(WIN32 ) +#include <windows.h> +#elif defined(CONFIG_BSD ) +#include <sys/param.h> +#include <sys/sysctl.h> +#elif defined(CONFIG_LINUX ) +#include <unistd.h> +#endif #endif
qapi-schema.json +72 -1
94 lines not on this page · raw message
vl.c +33 -0
@@ -2818,6 +2818,39 @@ static int object_create(QemuOpts *opts, void *opaque)return 0 ; } +/* +* Currently, only used for migration_bitmap_sync(), +* but can be queried by anyone in the future. +*/ +int getNumCores (void ) +{ +uint32_t count; +#if defined(WIN32 ) +SYSTEM_INFO sysinfo; +GetSystemInfo (&sysinfo); + count = sysinfo.dwNumberOfProcessors; +#elif defined(CONFIG_BSD ) +int nm[2 ]; +size_t len =4 ; + nm[0 ] =CTL_HW ; + nm[1 ] =HW_AVAILCPU ; +sysctl (nm,2 , &count, &len,NULL ,0 ); + +if (count <1 ) { + nm[1 ] =HW_NCPU ; +sysctl (nm,2 , &count, &len,NULL ,0 ); +if (count <1 ) { + count =1 ; + } + } +#elif defined(CONFIG_LINUX ) + count =sysconf (_SC_NPROCESSORS_ONLN); +#else + count =1 ; +#endif +return count; +} +int main (int argc,char **argv,char **envp) {int i;
Signature · 1 line
1.8.1.2
RFC PATCH 4/12 mc: introduce a "checkpointing" status check into the VCPU states
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
During micro-checkpointing, the VCPUs get repeatedly paused and resumed. We need to not freak out when the VM begins micro-checkpointing.
--- arch_init.c | 2 +- cpus.c | 9 ++++++++- include/migration/migration.h | 2 ++ qapi-schema.json | 4 +++- vl.c | 6 ++++++ 5 files changed, 20 insertions(+), 3 deletions(-)
arch_init.c +1 -1
@@ -199,7 +199,7 @@ typedef struct AccountingInfo {static AccountingInfo acct_info; -static void acct_clear (void ) +void acct_clear (void ) {memset (&acct_info,0 ,sizeof (acct_info)); }
cpus.c +8 -1
@@ -530,7 +530,14 @@ static int do_vm_stop(RunState state)pause_all_vcpus ();runstate_set (state);vm_state_notify (0 , state); -monitor_protocol_event (QEVENT_STOP ,NULL ); +/* +* If MC is enabled, libvirt gets confused +* because it thinks the VM is stopped when +* its just being micro-checkpointed. +*/ +if (state !=RUN_STATE_CHECKPOINT_VM ) { +monitor_protocol_event (QEVENT_STOP ,NULL ); + } }bdrv_drain_all ();
include/migration/migration.h +2 -0
@@ -119,6 +119,8 @@ uint64_t xbzrle_mig_bytes_transferred(void);uint64_t xbzrle_mig_pages_transferred (void );uint64_t xbzrle_mig_pages_overflow (void );uint64_t xbzrle_mig_pages_cache_miss (void ); +void acct_clear (void ); +void *migration_bitmap_worker (void *opaque);void migration_bitmap_worker_start (MigrationState *s);void migration_bitmap_worker_stop (MigrationState *s);
qapi-schema.json +3 -1
@@ -169,6 +169,8 @@ # # @save-vm: guest is paused to save the VM state # +# @checkpoint-vm: guest is paused to checkpoint the VM state +# # @shutdown: guest is shut down (and -no-shutdown is in use) # # @suspended: guest is suspended (ACPI S3)
@@ -181,7 +183,7 @@ 'data': [ 'debug', 'inmigrate', 'internal-error', 'io-error', 'paused', 'postmigrate', 'prelaunch', 'finish-migrate', 'restore-vm', 'running', 'save-vm', 'shutdown', 'suspended', 'watchdog', - 'guest-panicked' ] } + 'guest-panicked', 'checkpoint-vm' ] } ## # @SnapshotInfo
vl.c +6 -0
@@ -611,14 +611,18 @@ static const RunStateTransition runstate_transitions_def[] = { { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING }, { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE }, + { RUN_STATE_FINISH_MIGRATE, RUN_STATE_CHECKPOINT_VM }, { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING }, + { RUN_STATE_CHECKPOINT_VM, RUN_STATE_RUNNING }, + { RUN_STATE_RUNNING, RUN_STATE_DEBUG }, { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR }, { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR }, { RUN_STATE_RUNNING, RUN_STATE_PAUSED }, { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE }, + { RUN_STATE_RUNNING, RUN_STATE_CHECKPOINT_VM }, { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM }, { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM }, { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
@@ -634,9 +638,11 @@ static const RunStateTransition runstate_transitions_def[] = { { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED }, { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING }, { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE }, + { RUN_STATE_SUSPENDED, RUN_STATE_CHECKPOINT_VM }, { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING }, { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE }, + { RUN_STATE_WATCHDOG, RUN_STATE_CHECKPOINT_VM }, { RUN_STATE_GUEST_PANICKED, RUN_STATE_PAUSED }, { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
Signature · 1 line
1.8.1.2
RFC PATCH 5/12 migration: support custom page loading
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
Just as RDMA has custom routines for saving memory, this provides us with custom routines for loading memory.
Micro-checkpointing needs this support in order to be able to handle loading of the latest checkpoint into memory as they are received from the network.
--- arch_init.c | 17 ++++++++++++----- include/migration/migration.h | 12 ++++++++++-- include/migration/qemu-file.h | 16 ++++++++++++++-- savevm.c | 27 ++++++++++++++++++++++++--- 4 files changed, 60 insertions(+), 12 deletions(-)
arch_init.c +12 -5
@@ -684,7 +684,7 @@ static int ram_save_block(QEMUFile *f, bool last_stage)/* In doubt sent page as normal */ bytes_sent =-1 ; ret =ram_control_save_page (f, block->offset, - offset,TARGET_PAGE_SIZE , &bytes_sent); + block->host, offset,TARGET_PAGE_SIZE , &bytes_sent);if (ret !=RAM_SAVE_CONTROL_NOT_SUPP ) {if (ret !=RAM_SAVE_CONTROL_DELAYED ) {
@@ -712,9 +712,11 @@ static int ram_save_block(QEMUFile *f, bool last_stage)/* XBZRLE overflow or normal page */ if (bytes_sent ==-1 ) { bytes_sent =save_block_hdr (f, block, offset, cont,RAM_SAVE_FLAG_PAGE ); -qemu_put_buffer_async (f, p,TARGET_PAGE_SIZE ); - bytes_sent +=TARGET_PAGE_SIZE ; - acct_info.norm_pages++; +if (ret !=RAM_SAVE_CONTROL_DELAYED ) { +qemu_put_buffer_async (f, p,TARGET_PAGE_SIZE ); + bytes_sent +=TARGET_PAGE_SIZE ; + acct_info.norm_pages++; + } }/* if page is unmodified, continue to the next */
@@ -1133,13 +1135,18 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)ram_handle_compressed (host, ch,TARGET_PAGE_SIZE ); }else if (flags &RAM_SAVE_FLAG_PAGE ) {void *host; +int r; host =host_from_stream_offset (f, addr, flags);if (!host) {return -EINVAL ; } -qemu_get_buffer (f, host,TARGET_PAGE_SIZE ); + r =ram_control_load_page (f, host,TARGET_PAGE_SIZE ); + +if (r ==RAM_LOAD_CONTROL_NOT_SUPP ) { +qemu_get_buffer (f, host,TARGET_PAGE_SIZE ); + } }else if (flags &RAM_SAVE_FLAG_XBZRLE ) {void *host =host_from_stream_offset (f, addr, flags);if (!host) {
include/migration/migration.h +10 -2
@@ -169,9 +169,17 @@ void ram_control_load_hook(QEMUFile *f, uint64_t flags);#define RAM_SAVE_CONTROL_NOT_SUPP -1000#define RAM_SAVE_CONTROL_DELAYED -2000 +#define RAM_LOAD_CONTROL_NOT_SUPP -3000 +#define RAM_LOAD_CONTROL_DELAYED -4000 -size_t ram_control_save_page (QEMUFile *f,ram_addr_t block_offset, -ram_addr_t offset,size_t size, +#define RDMA_CONTROL_VERSION_CURRENT 1 + +int ram_control_save_page (QEMUFile *f,ram_addr_t block_offset, +uint8_t *host_addr, +ram_addr_t offset,long size,int *bytes_sent); +int ram_control_load_page (QEMUFile *f, +void *host_addr, +long size);#endif
include/migration/qemu-file.h +14 -2
@@ -76,12 +76,22 @@ typedef int (QEMURamHookFunc)(QEMUFile *f, void *opaque, uint64_t flags);* This function allows override of where the RAM page * is saved (such as RDMA, for example.) */ -typedef size_t (QEMURamSaveFunc )(QEMUFile *f,void *opaque, +typedef int (QEMURamSaveFunc )(QEMUFile *f,void *opaque,ram_addr_t block_offset, +uint8_t *host_addr,ram_addr_t offset, -size_t size, +long size,int *bytes_sent); +/* +* This function allows override of where the RAM page +* is saved (such as RDMA, for example.) +*/ +typedef int (QEMURamLoadFunc )(QEMUFile *f, +void *opaque, +void *host_addr, +long size); + typedef struct QEMUFileOps { QEMUFilePutBufferFunc *put_buffer; QEMUFileGetBufferFunc *get_buffer;
@@ -92,12 +102,14 @@ typedef struct QEMUFileOps {QEMURamHookFunc *after_ram_iterate;QEMURamHookFunc *hook_ram_load;QEMURamSaveFunc *save_page; +QEMURamLoadFunc *load_page; } QEMUFileOps;QEMUFile *qemu_fopen_ops (void *opaque,const QEMUFileOps *ops);QEMUFile *qemu_fopen (const char *filename,const char *mode);QEMUFile *qemu_fdopen (int fd,const char *mode);QEMUFile *qemu_fopen_socket (int fd,const char *mode); +QEMUFile *qemu_fopen_mc (void *opaque,const char *mode);QEMUFile *qemu_popen_cmd (const char *command,const char *mode);int qemu_get_fd (QEMUFile *f);int qemu_fclose (QEMUFile *f);
savevm.c +24 -3
@@ -661,14 +661,17 @@ void ram_control_load_hook(QEMUFile *f, uint64_t flags) } } -size_t ram_control_save_page (QEMUFile *f,ram_addr_t block_offset, -ram_addr_t offset,size_t size,int *bytes_sent) +int ram_control_save_page (QEMUFile *f,ram_addr_t block_offset, +uint8_t *host_addr, +ram_addr_t offset,long size,int *bytes_sent) {if (f->ops->save_page) {int ret = f->ops->save_page (f, f->opaque, block_offset, + host_addr, offset, size, bytes_sent); -if (ret !=RAM_SAVE_CONTROL_DELAYED ) { +if (ret !=RAM_SAVE_CONTROL_DELAYED + && ret !=RAM_SAVE_CONTROL_NOT_SUPP ) {if (bytes_sent && *bytes_sent >0 ) {qemu_update_position (f, *bytes_sent); }else if (ret <0 ) {
@@ -682,6 +685,24 @@ size_t ram_control_save_page(QEMUFile *f, ram_addr_t block_offset,return RAM_SAVE_CONTROL_NOT_SUPP ; } +int ram_control_load_page (QEMUFile *f,void *host_addr,long size) +{ +if (f->ops->load_page) { +int ret = f->ops->load_page (f, f->opaque, host_addr, size); + +if (ret !=RAM_LOAD_CONTROL_DELAYED + && ret !=RAM_LOAD_CONTROL_NOT_SUPP ) { +if (ret <0 ) { +qemu_file_set_error (f, ret); + } + } + +return ret; + } + +return RAM_LOAD_CONTROL_NOT_SUPP ; +} +static void qemu_fill_buffer (QEMUFile *f) {int len;
Signature · 1 line
1.8.1.2
RFC PATCH 6/12 rdma: accelerated memcpy() support
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
This patch implements the ability to provide accelerated memory copies as an alternative to memcpy() using RDMA.
It requires the user to "register" the src and dest memory with the RDMA subsystem using new interfaces and then call a special copy function that is introduced to submit the copy to the hardware.
--- include/migration/migration.h | 12 + include/migration/qemu-file.h | 38 + migration-rdma.c | 2008 ++++++++++++++++++++++++++++++----------- savevm.c | 52 ++ 4 files changed, 1571 insertions(+), 539 deletions(-)
include/migration/migration.h +12 -0
@@ -159,6 +159,9 @@ int64_t xbzrle_cache_resize(int64_t new_size);void ram_control_before_iterate (QEMUFile *f,uint64_t flags);void ram_control_after_iterate (QEMUFile *f,uint64_t flags);void ram_control_load_hook (QEMUFile *f,uint64_t flags); +void ram_control_add (QEMUFile *f,void *host_addr, +ram_addr_t block_offset,uint64_t length); +void ram_control_remove (QEMUFile *f,ram_addr_t block_offset);/* Whenever this is found in the data stream, the flags * will be passed to ram_control_load_hook in the incoming-migration
@@ -171,6 +174,8 @@ void ram_control_load_hook(QEMUFile *f, uint64_t flags);#define RAM_SAVE_CONTROL_DELAYED -2000#define RAM_LOAD_CONTROL_NOT_SUPP -3000#define RAM_LOAD_CONTROL_DELAYED -4000 +#define RAM_COPY_CONTROL_NOT_SUPP -5000 +#define RAM_COPY_CONTROL_DELAYED -6000#define RDMA_CONTROL_VERSION_CURRENT 1
@@ -182,4 +187,11 @@ int ram_control_save_page(QEMUFile *f, ram_addr_t block_offset,int ram_control_load_page (QEMUFile *f,void *host_addr,long size); + +int ram_control_copy_page (QEMUFile *f, +ram_addr_t block_offset_dest, +ram_addr_t offset_dest, +ram_addr_t block_offset_source, +ram_addr_t offset_source, +long size);#endif
include/migration/qemu-file.h +38 -0
@@ -92,6 +92,41 @@ typedef int (QEMURamLoadFunc)(QEMUFile *f,void *host_addr, long size); +/* +* This function allows *local* RDMA copying memory between two registered +* RAMBlocks, both real ones as well as private memory areas independently +* registered by external callers (such as MC). If RDMA is not available, +* then this function does nothing and the caller should just use memcpy(). +*/ +typedef int (QEMURamCopyFunc )(QEMUFile *f,void *opaque, +ram_addr_t block_offset_dest, +ram_addr_t offset_dest, +ram_addr_t block_offset_source, +ram_addr_t offset_source, +long size); + +/* +* Inform the underlying transport of a new virtual memory area. +* If this area is an actual RAMBlock, then pass the corresponding +* parameters of that block. +* If this area is an arbitrary virtual memory address, then +* pass the same value for both @host_addr and @block_offset. +*/ +typedef int (QEMURamAddFunc )(QEMUFile *f,void *opaque, +void *host_addr, +ram_addr_t block_offset, +uint64_t length); + +/* +* Remove an underlying new virtual memory area. +* If this area is an actual RAMBlock, then pass the corresponding +* parameters of that block. +* If this area is an arbitrary virtual memory address, then +* pass the same value for both @host_addr and @block_offset. +*/ +typedef int (QEMURamRemoveFunc )(QEMUFile *f,void *opaque, +ram_addr_t block_offset); + typedef struct QEMUFileOps { QEMUFilePutBufferFunc *put_buffer; QEMUFileGetBufferFunc *get_buffer;
@@ -103,6 +138,9 @@ typedef struct QEMUFileOps {QEMURamHookFunc *hook_ram_load;QEMURamSaveFunc *save_page;QEMURamLoadFunc *load_page; +QEMURamCopyFunc *copy_page; +QEMURamAddFunc *add; +QEMURamRemoveFunc *remove; } QEMUFileOps;QEMUFile *qemu_fopen_ops (void *opaque,const QEMUFileOps *ops);
migration-rdma.c +1469 -539
2,922 lines not on this page · raw message
savevm.c +52 -0
52 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
1.8.1.2
Part of the diff is not shown here. View the raw message.
RFC PATCH 7/12 mc: introduce state machine error handling and migration_bitmap prep
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
Since MC will repeatedly call the pre-existing live migration call path over and over again (forever), the migration_bitmap initialization only needs to happen once and the destruction of the bitmap needs to be avoided in successive checkpoints.
Also, there some additional state machine error handling to prepare for before introducing the MC core logic.
--- arch_init.c | 29 ++++++++++++++++++++++++----- include/migration/migration.h | 19 +++++++++++++++++++ include/migration/qemu-file.h | 1 + migration.c | 33 +++++++++++++++++++-------------- 4 files changed, 63 insertions(+), 19 deletions(-)
arch_init.c +24 -5
@@ -795,13 +795,13 @@ static void ram_migration_cancel(void *opaque)migration_end (); } -static void reset_ram_globals (void ) +static void reset_ram_globals (bool reset_bulk_stage) { last_seen_block =NULL ; last_sent_block =NULL ; last_offset =0 ; last_version = ram_list.version; - ram_bulk_stage = true; + ram_bulk_stage = reset_bulk_stage; }#define MAX_WAIT 50/* ms, half buffered_file limit */
@@ -811,6 +811,15 @@ static int ram_save_setup(QEMUFile *f, void *opaque)RAMBlock *block;int64_t ram_pages =last_ram_offset () >>TARGET_PAGE_BITS ; +/* +* RAM stays open during micro-checkpointing for the next transaction. +*/ +if (migration_is_mc (migrate_get_current ())) { +qemu_mutex_lock_ramlist (); +reset_ram_globals (false); + goto skip_setup; + } + migration_bitmap =bitmap_new (ram_pages);bitmap_set (migration_bitmap,0 , ram_pages); migration_dirty_pages = ram_pages;
@@ -833,12 +842,14 @@ static int ram_save_setup(QEMUFile *f, void *opaque)qemu_mutex_lock_iothread ();qemu_mutex_lock_ramlist (); bytes_transferred =0 ; -reset_ram_globals (); +reset_ram_globals (true);memory_global_dirty_log_start ();migration_bitmap_sync ();qemu_mutex_unlock_iothread (); +skip_setup: +qemu_put_be64 (f,ram_bytes_total () |RAM_SAVE_FLAG_MEM_SIZE ); QTAILQ_FOREACH(block, &ram_list.blocks, next) {
@@ -867,7 +878,7 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)qemu_mutex_lock_ramlist ();if (ram_list.version != last_version) { -reset_ram_globals (); +reset_ram_globals (true); }ram_control_before_iterate (f,RAM_CONTROL_ROUND );
@@ -948,7 +959,15 @@ static int ram_save_complete(QEMUFile *f, void *opaque) }ram_control_after_iterate (f,RAM_CONTROL_FINISH ); -migration_end (); + +/* +* Only cleanup at the end of normal migrations +* or if the MC destination failed and we got an error. +* Otherwise, we are (or will be soon) in MIG_STATE_MC. +*/ +if (!migrate_use_mc () ||migration_has_failed (migrate_get_current ())) { +migration_end (); + }qemu_mutex_unlock_ramlist ();qemu_put_be64 (f,RAM_SAVE_FLAG_EOS );
include/migration/migration.h +19 -0
@@ -95,6 +95,8 @@ int migrate_fd_close(MigrationState *s);void add_migration_state_change_notifier (Notifier *notify);void remove_migration_state_change_notifier (Notifier *notify);bool migration_in_setup (MigrationState *); +bool migration_is_active (MigrationState *); +bool migration_is_mc (MigrationState *s);bool migration_has_finished (MigrationState *);bool migration_has_failed (MigrationState *);MigrationState *migrate_get_current (void );
@@ -126,6 +128,15 @@ void migration_bitmap_worker_start(MigrationState *s);void migration_bitmap_worker_stop (MigrationState *s);void migrate_set_state (MigrationState *s,int old_state,int new_state); +enum { +MIG_STATE_ERROR =-1 , +MIG_STATE_NONE , +MIG_STATE_SETUP , +MIG_STATE_CANCELLED , +MIG_STATE_ACTIVE , +MIG_STATE_MC , +MIG_STATE_COMPLETED , +};void ram_handle_compressed (void *host,uint8_t ch,uint64_t size);/**
@@ -194,4 +205,12 @@ int ram_control_copy_page(QEMUFile *f,ram_addr_t block_offset_source, ram_addr_t offset_source, long size); + +int migrate_use_mc (void ); +int migrate_use_mc_rdma_copy (void ); + +#define MC_VERSION 1 + +void qemu_rdma_info_save (QEMUFile *f,void *opaque); +int qemu_rdma_info_load (QEMUFile *f,void *opaque,int version_id);#endif
include/migration/qemu-file.h +1 -0
@@ -71,6 +71,7 @@ typedef int (QEMURamHookFunc)(QEMUFile *f, void *opaque, uint64_t flags);#define RAM_CONTROL_ROUND 1#define RAM_CONTROL_HOOK 2#define RAM_CONTROL_FINISH 3 +#define RAM_CONTROL_FLUSH 4/* * This function allows override of where the RAM page
migration.c +19 -14
@@ -36,15 +36,6 @@ do { } while (0)#endif -enum { -MIG_STATE_ERROR =-1 , -MIG_STATE_NONE , -MIG_STATE_SETUP , -MIG_STATE_CANCELLED , -MIG_STATE_ACTIVE , -MIG_STATE_COMPLETED , -}; -#define MAX_THROTTLE (32 << 20)/* Migration speed throttling */ /* Amount of time to allocate to each "chunk" of bandwidth-throttled
@@ -270,7 +261,7 @@ void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,MigrationState *s =migrate_get_current ();MigrationCapabilityStatusList *cap; -if (s->state ==MIG_STATE_ACTIVE || s->state ==MIG_STATE_SETUP ) { +if (migration_is_active (s)) {error_set (errp,QERR_MIGRATION_ACTIVE );return ; }
@@ -282,6 +273,17 @@ void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,/* shared migration helpers */ +bool migration_is_mc (MigrationState *s) +{ +return s->state ==MIG_STATE_MC ; +} + +bool migration_is_active (MigrationState *s) +{ +return (s->state ==MIG_STATE_ACTIVE ) ||migration_in_setup (s) + ||migration_is_mc (s); +} +static void migrate_fd_cleanup (void *opaque) {MigrationState *s = opaque;
@@ -299,7 +301,7 @@ static void migrate_fd_cleanup(void *opaque) s->file =NULL ; } -assert (s->state !=MIG_STATE_ACTIVE ); +assert (!migration_is_active (s));if (s->state !=MIG_STATE_COMPLETED ) {qemu_savevm_state_cancel ();
@@ -308,7 +310,7 @@ static void migrate_fd_cleanup(void *opaque)notifier_list_notify (&migration_state_notifiers, s); } -static void migrate_set_state (MigrationState *s,int old_state,int new_state) +void migrate_set_state (MigrationState *s,int old_state,int new_state) {if (atomic_cmpxchg (&s->state, old_state, new_state) == new_state) {trace_migrate_set_state (new_state);
@@ -405,7 +407,7 @@ void qmp_migrate(const char *uri, bool has_blk, bool blk, params.blk = has_blk && blk; params.shared = has_inc && inc; -if (s->state ==MIG_STATE_ACTIVE || s->state ==MIG_STATE_SETUP ) { +if (migration_is_active (s)) {error_set (errp,QERR_MIGRATION_ACTIVE );return ; }
@@ -594,7 +596,10 @@ static void *migration_thread(void *opaque) }if (!qemu_file_get_error (s->file)) { -migrate_set_state (s,MIG_STATE_ACTIVE ,MIG_STATE_COMPLETED ); +if (!migrate_use_mc ()) { +migrate_set_state (s, +MIG_STATE_ACTIVE ,MIG_STATE_COMPLETED ); + }break ; } }
Signature · 1 line
1.8.1.2
RFC PATCH 8/12 mc: modified QMP statistics and migration_thread handoff
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
In addition to better handling of new QMP statistics associated with the migration_bitmap and MC performance, we need to transfer control from the migration thread to the MC thread more cleanly, which means dynamically allocating the threads and doing the handoff after the initial live migration has completed.
--- hmp.c | 17 ++++++++ include/migration/migration.h | 14 ++++++- migration.c | 94 +++++++++++++++++++++++++++---------------- qapi-schema.json | 2 + savevm.c | 5 +-- 5 files changed, 93 insertions(+), 39 deletions(-)
hmp.c +17 -0
@@ -202,6 +202,23 @@ void hmp_info_migrate(Monitor *mon, const QDict *qdict) info->disk->total >> 10); } +if (info->has_mc) { +monitor_printf (mon,"checkpoints: %" PRIu64"\n" , + info->mc->checkpoints); +monitor_printf (mon,"xmit_time: %" PRIu64" ms\n" , + info->mc->xmit_time); +monitor_printf (mon,"log_dirty_time: %" PRIu64" ms\n" , + info->mc->log_dirty_time); +monitor_printf (mon,"migration_bitmap_time: %" PRIu64" ms\n" , + info->mc->migration_bitmap_time); +monitor_printf (mon,"ram_copy_time: %" PRIu64" ms\n" , + info->mc->ram_copy_time); +monitor_printf (mon,"copy_mbps: %0.2f mbps\n" , + info->mc->copy_mbps); +monitor_printf (mon,"throughput: %0.2f mbps\n" , + info->mc->mbps); + } +if (info->has_xbzrle_cache) {monitor_printf (mon,"cache size: %" PRIu64" bytes\n" , info->xbzrle_cache->cache_size);
include/migration/migration.h +13 -1
@@ -35,13 +35,14 @@ struct MigrationStateint64_t bandwidth_limit;size_t bytes_xfer;size_t xfer_limit; -QemuThread thread; +QemuThread *thread;QEMUBH *cleanup_bh;QEMUFile *file;int state;MigrationParams params;double mbps; +double copy_mbps;int64_t total_time;int64_t downtime;int64_t expected_downtime;
@@ -54,6 +55,7 @@ struct MigrationStatebool enabled_capabilities[MIGRATION_CAPABILITY_MAX ];int64_t xbzrle_cache_size;int64_t setup_time; +int64_t checkpoints; };void process_incoming_migration (QEMUFile *f);
@@ -137,6 +139,12 @@ enum {MIG_STATE_MC , MIG_STATE_COMPLETED, }; + +int mc_enable_buffering (void ); +int mc_start_buffer (void ); +void mc_init_checkpointer (MigrationState *s); +void mc_process_incoming_checkpoints_if_requested (QEMUFile *f); +void ram_handle_compressed (void *host,uint8_t ch,uint64_t size);/**
@@ -207,10 +215,14 @@ int ram_control_copy_page(QEMUFile *f, long size);int migrate_use_mc (void ); +int migrate_use_mc_net (void );int migrate_use_mc_rdma_copy (void );#define MC_VERSION 1 +int mc_info_load (QEMUFile *f,void *opaque,int version_id); +void mc_info_save (QEMUFile *f,void *opaque); +void qemu_rdma_info_save (QEMUFile *f,void *opaque);int qemu_rdma_info_load (QEMUFile *f,void *opaque,int version_id);#endif
migration.c +60 -34
134 lines not on this page · raw message
qapi-schema.json +2 -0
@@ -630,6 +630,8 @@ # migration statistics, only returned if XBZRLE feature is on and # status is 'active' or 'completed' (since 1.2) # +# @mc: #options @MCStats containing details Micro-Checkpointing statistics +# # @total-time: #optional total amount of milliseconds since migration started. # If migration has ended, it returns the total migration # time. (since 1.2)
savevm.c +1 -4
@@ -419,10 +419,7 @@ QEMUFile *qemu_fdopen(int fd, const char *mode) {QEMUFileSocket *s; -if (mode ==NULL || - (mode[0 ] !='r' && mode[0 ] !='w' ) || - mode[1 ] !='b' || mode[2 ] !=0 ) { -fprintf (stderr,"qemu_fdopen: Argument validity check failed\n" ); +if (qemu_file_mode_is_not_valid (mode)) {return NULL ; }
Signature · 1 line
1.8.1.2
RFC PATCH 9/12 mc: core logic
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
This implements the core logic, all described in docs/mc.txt
--- migration-checkpoint.c | 1589 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1589 insertions(+) create mode 100644 migration-checkpoint.c
migration-checkpoint.c new file +1589 -0
@@ -0,0 +1,1589 @@ +/* +* Copyright (C) 2014 Michael R. Hines <[email protected]> +* +* Micro-Checkpointing (MC) support +* (a.k.a. Fault Tolerance or Continuous Replication) +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; under version 2 of the License. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see <http://www.gnu.org/licenses/>. +*/ +#include <libnl3/netlink/route/qdisc/plug.h> +#include <libnl3/netlink/route/class.h> +#include <libnl3/netlink/cli/utils.h> +#include <libnl3/netlink/cli/tc.h> +#include <libnl3/netlink/cli/qdisc.h> +#include <libnl3/netlink/cli/link.h> +#include "qemu-common.h" +#include "hw/virtio/virtio.h" +#include "hw/virtio/virtio-net.h" +#include "qemu/sockets.h" +#include "migration/migration.h" +#include "migration/qemu-file.h" +#include "qmp-commands.h" +#include "net/tap-linux.h" +#include <sys/ioctl.h> + +#define DEBUG_MC +//#define DEBUG_MC_VERBOSE +//#define DEBUG_MC_REALLY_VERBOSE + +#ifdef DEBUG_MC +#define DPRINTF (fmt, ...) \ + do { printf("mc: " fmt, ## __VA_ARGS__); } while (0) +#else +#define DPRINTF (fmt, ...) \ + do { } while (0) +#endif + +#ifdef DEBUG_MC_VERBOSE +#define DDPRINTF (fmt, ...) \ + do { printf("mc: " fmt, ## __VA_ARGS__); } while (0) +#else +#define DDPRINTF (fmt, ...) \ + do { } while (0) +#endif + +#ifdef DEBUG_MC_REALLY_VERBOSE +#define DDDPRINTF (fmt, ...) \ + do { printf("mc: " fmt, ## __VA_ARGS__); } while (0) +#else +#define DDDPRINTF (fmt, ...) \ + do { } while (0) +#endif + +#define MBPS (bytes, time) time ? ((((double) bytes * 8) \ + / ((double) time / 1000.0)) / 1000.0 / 1000.0) : -1.0 + +/* +* Micro checkpoints (MC)s are typically only a few MB when idle. +* However, they can easily be very large during heavy workloads. +* In the *extreme* worst-case, QEMU might need double the amount of main memory +* than that of what was originally allocated to the virtual machine. +* +* To support this variability during transient periods, a MC +* consists of a linked list of slabs, each of identical size. A better name +* would be welcome, as the name was only chosen because it resembles linux +* memory allocation. Because MCs occur several times per second +* (a frequency of 10s of milliseconds), slabs allow MCs to grow and shrink +* without constantly re-allocating all memory in place during each checkpoint. +* +* During steady-state, the 'head' slab is permanently allocated and never goes +* away, so when the VM is idle, there is no memory allocation at all. +* This design supports the use of RDMA. Since RDMA requires memory pinning, we +* must be able to hold on to a slab for a reasonable amount of time to get any +* real use out of it. +* +* Regardless, the current strategy taken is: +* +* 1. If the checkpoint size increases, +* then grow the number of slabs to support it. +* 2. If the next checkpoint size is smaller than the last one, +then that's a "strike". +* 3. After N strikes, cut the size of the slab cache in half +* (to a minimum of 1 slab as described before). +* +* As of this writing, a typical average size of +* an Idle-VM checkpoint is under 5MB. +*/ + +#define MC_SLAB_BUFFER_SIZE (5UL * 1024UL * 1024UL)/* empirical */ +#define MC_DEV_NAME_MAX_SIZE 256 + +#define MC_DEFAULT_CHECKPOINT_FREQ_MS 100/* too slow, but best for now */ +#define CALC_MAX_STRIKES () \ + do { max_strikes = (max_strikes_delay_secs * 1000) / freq_ms; } \ + while (0) + +/* +* How many "seconds-worth" of checkpoints to wait before re-evaluating the size +* of the slab cache? +* +* #strikes_until_shrink_cache = Function(#checkpoints/sec) +* +* Increasing the number of seconds, increases the number of strikes needed to +* be reached until it is time to cut the cache in half. +* +* Below value is open for debate - we just want it to be small enough to ensure +* that a large, idle cache doesn't stay too large for too long. +*/ +#define MC_DEFAULT_SLAB_MAX_CHECK_DELAY_SECS 10 + +/* +* MC serializes the actual RAM page contents in such a way that the actual +* pages are separated from the meta-data (all the QEMUFile stuff). +* +* This is done strictly for the purposes of being able to use RDMA +* to replace memcpy() on the local machine. +* +* This serialization requires recording the page descriptions and then +* pushing them into slabs after the checkpoint has been captured +* (minus the page data). +* +* The memory holding the page descriptions are allocated in unison with the +* slabs themselves, and thus we need to know in advance the maximum number of +* page descriptions that can fit into a slab before allocating the slab. +* It should be safe to assume the *minimum* page size (not the maximum, +* that would be dangerous) is 4096. +* +* We're not actually using this assumption for any memory management +* management, only as a hint to know how big of an array to allocate. +* +* The following adds a fixed-cost of about 40 KB to each slab. +*/ +#define MC_MAX_SLAB_COPY_DESCRIPTORS (MC_SLAB_BUFFER_SIZE / 4096) + +#define SLAB_RESET (s) do { \ + s->size = 0; \ + s->read = 0; \ + } while(0) + +uint64_t freq_ms =MC_DEFAULT_CHECKPOINT_FREQ_MS ; +uint32_t max_strikes_delay_secs =MC_DEFAULT_SLAB_MAX_CHECK_DELAY_SECS ; +uint32_t max_strikes =-1 ; + +typedef struct QEMU_PACKED MCCopy { +uint64_t ramblock_offset; +uint64_t host_addr; +uint64_t offset; +uint64_t size; +} MCCopy; + +typedef struct QEMU_PACKED MCCopyset { +QTAILQ_ENTRY (MCCopyset) node; +MCCopy copies[MC_MAX_SLAB_COPY_DESCRIPTORS ]; +uint64_t nb_copies; +int idx; +} MCCopyset; + +typedef struct QEMU_PACKED MCSlab { +QTAILQ_ENTRY (MCSlab) node; +uint8_t buf[MC_SLAB_BUFFER_SIZE ]; +uint64_t read; +uint64_t size; +int idx; +} MCSlab; + +typedef struct MCParams { + QTAILQ_HEAD(shead, MCSlab) slab_head; + QTAILQ_HEAD(chead, MCCopyset) copy_head; +MCSlab *curr_slab; +MCSlab *mem_slab; +MCCopyset *curr_copyset; +MCCopy *copy; +QEMUFile *file; +QEMUFile *staging; +uint64_t start_copyset; +uint64_t slab_total; +uint64_t total_copies; +uint64_t nb_slabs; +uint64_t used_slabs; +uint32_t slab_strikes; +uint32_t copy_strikes; +int nb_copysets; +uint64_t checkpoints; +}MCParams ; + +enum { +MC_TRANSACTION_NACK =300 , +MC_TRANSACTION_START , +MC_TRANSACTION_COMMIT , +MC_TRANSACTION_ABORT , +MC_TRANSACTION_ACK , +MC_TRANSACTION_END , +MC_TRANSACTION_ANY , +}; + +static const char * mc_desc[] = { + [MC_TRANSACTION_NACK ] ="NACK" , + [MC_TRANSACTION_START ] ="START" , + [MC_TRANSACTION_COMMIT ] ="COMMIT" , + [MC_TRANSACTION_ABORT ] ="ABORT" , + [MC_TRANSACTION_ACK ] ="ACK" , + [MC_TRANSACTION_END ] ="END" , + [MC_TRANSACTION_ANY ] ="ANY" , +}; + +static struct rtnl_qdisc *qdisc =NULL ; +static struct nl_sock *sock =NULL ; +static struct rtnl_tc *tc =NULL ; +static struct nl_cache *link_cache =NULL ; +static struct rtnl_tc_ops *ops =NULL ; +static struct nl_cli_tc_module *tm =NULL ; +static int first_nic_chosen =0 ; + +/* +* Assuming a guest can 'try' to fill a 1 Gbps pipe, +* that works about to 125000000 bytes/sec. +* +* Netlink better not be pre-allocating megabytes in the +* kernel qdisc, that would be crazy.... +*/ +#define START_BUFFER (1000*1000*1000 / 8) +static int buffer_size =START_BUFFER , new_buffer_size =START_BUFFER ; +static const char * parent ="root" ; +static int buffering_enabled =0 ; +static const char *BUFFER_NIC_PREFIX ="ifb" ; +static QEMUBH *checkpoint_bh =NULL ; +static bool mc_requested = false; + +int migrate_use_mc (void ) +{ +MigrationState *s =migrate_get_current (); +return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MC ]; +} + +int migrate_use_mc_net (void ) +{ +MigrationState *s =migrate_get_current (); +return s->enabled_capabilities[MIGRATION_CAPABILITY_MC_NET_DISABLE ]; +} + +int migrate_use_mc_rdma_copy (void ) +{ +MigrationState *s =migrate_get_current (); +return s->enabled_capabilities[MIGRATION_CAPABILITY_MC_RDMA_COPY ]; +} + +static int mc_deliver (int update) +{ +int err, flags =NLM_F_CREATE ; + +if (!buffering_enabled) +return -EINVAL ; + +if (!update) + flags |=NLM_F_EXCL ; + +if ((err =rtnl_qdisc_add (sock, qdisc, flags)) <0 ) { +fprintf (stderr,"Unable control qdisc: %s! %p %p %d\n" , +nl_geterror (err), sock, qdisc, flags); +return -EINVAL ; + } + +return 0 ; +} + +static int mc_set_buffer_size (int size) +{ +int err; + +if (!buffering_enabled) { +return 1 ; + } + + buffer_size = size; + new_buffer_size = size; + +if ((err =rtnl_qdisc_plug_set_limit ((void *) qdisc, size)) <0 ) { +fprintf (stderr,"MC: Unable to change buffer size: %s\n" , +nl_geterror (err)); +return -EINVAL ; + } + +DPRINTF ("Set buffer size to %d bytes\n" , size); + +return mc_deliver (1 ); +} + +/* +* Micro-checkpointing may require buffering network packets. +* Set that up for the first NIC only.... +*/ +static void init_mc_nic_buffering (NICState *nic,void *opaque) +{ +char * device = opaque; +NetClientState * nc = &nic->ncs[0 ]; +const char * key ="ifname=" ; +int keylen =strlen (key); +char * name; +int end =0 ; +bool use_fd = false; + +if (first_nic_chosen) { +fprintf (stderr,"Micro-Checkpointing with multiple NICs not yet supported!\n" ); +return ; + } + +if (!nc->peer) { +fprintf (stderr,"Micro-Checkpoint nic %s does not have peer host device for buffering. VM will not be consistent.\n" , nc->name); +return ; + } + + name = nc->peer->info_str; + +DPRINTF ("Checking contents of %s\n" , name); + +if (strncmp (name, key, keylen)) { +fprintf (stderr,"Micro-Checkpoint nic %s does not have 'ifname' " +"in its description (%s, %s). Trying workaround...\n" , + nc->name, name, nc->peer->name); + key ="fd=" ; + keylen =strlen (key); +if (strncmp (name, key, keylen)) { +fprintf (stderr,"Still cannot find 'fd=' either. Failure.\n" ); +return ; + } + + use_fd = true; + } + + name += keylen; + +while (name[end++] != (use_fd ?'\0' :',' )); + +strncpy (device, name, end -1 ); +memset (&device[end -1 ],0 ,MC_DEV_NAME_MAX_SIZE - (end -1 )); + +if (use_fd) { +struct ifreq r; +DPRINTF ("Want to retreive name from fd: %d\n" ,atoi (device)); + +if (ioctl (atoi (device),TUNGETIFF , &r) ==-1 ) { +fprintf (stderr,"Failed to convert fd %s to name.\n" , device); +return ; + } + +DPRINTF ("Got name %s!\n" , r.ifr_name); +strcpy (device, r.ifr_name); + } + + first_nic_chosen =1 ; +} + +static int mc_suspend_buffering (void ) +{ +int err; + +if (!buffering_enabled) { +return -EINVAL ; + } + +if ((err =rtnl_qdisc_plug_release_indefinite ((void *) qdisc)) <0 ) { +fprintf (stderr,"MC: Unable to release indefinite: %s\n" , +nl_geterror (err)); +return -EINVAL ; + } + +DPRINTF ("Buffering suspended\n" ); + +return mc_deliver (1 ); +} + +static int mc_disable_buffering (void ) +{ +int err; + +if (!buffering_enabled) { + goto out; + } + +mc_suspend_buffering (); + +if (qdisc && sock && (err =rtnl_qdisc_delete (sock, (void *) qdisc)) <0 ) { +fprintf (stderr,"Unable to release indefinite: %s\n" ,nl_geterror (err)); + } + +out: + buffering_enabled =0 ; + qdisc =NULL ; + sock =NULL ; + tc =NULL ; + link_cache =NULL ; + ops =NULL ; + tm =NULL ; + +DPRINTF ("Buffering disabled\n" ); + +return 0 ; +} + +/* +* Install a Qdisc plug for micro-checkpointing. +* If it exists already (say, from a previous dead VM or debugging +* session) then just open all the netlink data structures pointing +* to the existing plug so that we can continue to manipulate it. +*/ +int mc_enable_buffering (void ) +{ +char dev[MC_DEV_NAME_MAX_SIZE ], buffer_dev[MC_DEV_NAME_MAX_SIZE ]; +int prefix_len =0 ; +int buffer_prefix_len =strlen (BUFFER_NIC_PREFIX ); + +if (buffering_enabled) { +fprintf (stderr,"Buffering already enable Skipping.\n" ); +return 0 ; + } + + first_nic_chosen =0 ; + +qemu_foreach_nic (init_mc_nic_buffering, dev); + +if (!first_nic_chosen) { +fprintf (stderr,"Enumeration of NICs complete, but failed.\n" ); + goto failed; + } + +while ((dev[prefix_len] <'0' ) || (dev[prefix_len] >'9' )) + prefix_len++; + +strcpy (buffer_dev,BUFFER_NIC_PREFIX ); +strncpy (buffer_dev + buffer_prefix_len, + dev + prefix_len,strlen (dev) - prefix_len +1 ); + +fprintf (stderr,"Initializing buffering for nic %s => %s\n" , dev, buffer_dev); + +if (sock ==NULL ) { + sock = (struct nl_sock *)nl_cli_alloc_socket (); +if (!sock) { +fprintf (stderr,"MC: failed to allocate netlink socket\n" ); + goto failed; + } +nl_cli_connect (sock,NETLINK_ROUTE ); + } + +if (qdisc ==NULL ) { + qdisc =nl_cli_qdisc_alloc (); +if (!qdisc) { +fprintf (stderr,"MC: failed to allocate netlink qdisc\n" ); + goto failed; + } + tc = (struct rtnl_tc *) qdisc; + } + +if (link_cache ==NULL ) { + link_cache =nl_cli_link_alloc_cache (sock); +if (!link_cache) { +fprintf (stderr,"MC: failed to allocate netlink link_cache\n" ); + goto failed; + } + } + +nl_cli_tc_parse_dev (tc, link_cache, (char *) buffer_dev); +nl_cli_tc_parse_parent (tc, (char *) parent); + +if (!rtnl_tc_get_ifindex (tc)) { +fprintf (stderr,"Qdisc device '%s' does not exist!\n" , buffer_dev); + goto failed; + } + +if (!rtnl_tc_get_parent (tc)) { +fprintf (stderr,"Qdisc parent '%s' is not valid!\n" , parent); + goto failed; + } + +if (rtnl_tc_set_kind (tc,"plug" ) <0 ) { +fprintf (stderr,"Could not open qdisc plug!\n" ); + goto failed; + } + +if (!(ops =rtnl_tc_get_ops (tc))) { +fprintf (stderr,"Could not open qdisc plug!\n" ); + goto failed; + } + +if (!(tm =nl_cli_tc_lookup (ops))) { +fprintf (stderr,"Qdisc plug not supported!\n" ); + goto failed; + } + + buffering_enabled =1 ; + +if (mc_deliver (0 ) <0 ) { +fprintf (stderr,"First time qdisc create failed\n" ); + goto failed; + } + +DPRINTF ("Buffering enabled, size: %d MB.\n" , buffer_size /1024 /1024 ); + +if (mc_set_buffer_size (buffer_size) <0 ) { + goto failed; + } + +if (mc_suspend_buffering () <0 ) { + goto failed; + } + + +return 0 ; + +failed: +mc_disable_buffering (); +return -EINVAL ; +} + +int mc_start_buffer (void ) +{ +int err; + +if (!buffering_enabled) { +return -EINVAL ; + } + +if (new_buffer_size != buffer_size) { + buffer_size = new_buffer_size; +fprintf (stderr,"GDB setting new buffer size to %d\n" , buffer_size); +if (mc_set_buffer_size (buffer_size) <0 ) +return -EINVAL ; + } + +if ((err =rtnl_qdisc_plug_buffer ((void *) qdisc)) <0 ) { +fprintf (stderr,"Unable to flush oldest checkpoint: %s\n" ,nl_geterror (err)); +return -EINVAL ; + } + +DDPRINTF ("Inserted checkpoint barrier\n" ); + +return mc_deliver (1 ); +} + +static int mc_flush_oldest_buffer (void ) +{ +int err; + +if (!buffering_enabled) +return -EINVAL ; + +if ((err =rtnl_qdisc_plug_release_one ((void *) qdisc)) <0 ) { +fprintf (stderr,"Unable to flush oldest checkpoint: %s\n" ,nl_geterror (err)); +return -EINVAL ; + } + +DDPRINTF ("Flushed oldest checkpoint barrier\n" ); + +return mc_deliver (1 ); +} + +/* +* Get the next slab in the list. If there is none, then make one. +*/ +static MCSlab *mc_slab_next (MCParams *mc,MCSlab *slab) +{ +if (!QTAILQ_NEXT (slab, node)) { +int idx = mc->nb_slabs++; + mc->used_slabs++; +DDPRINTF ("Extending slabs by one: %" PRIu64" slabs total, " +"%" PRIu64" MB\n" , mc->nb_slabs, + mc->nb_slabs *sizeof (MCSlab) /1024UL /1024UL ); + mc->curr_slab =qemu_memalign (4096 ,sizeof (MCSlab)); +memset (mc->curr_slab,0 ,sizeof (*(mc->curr_slab))); + mc->curr_slab->idx = idx; +QTAILQ_INSERT_TAIL (&mc->slab_head, mc->curr_slab, node); + slab = mc->curr_slab; +ram_control_add (mc->file, slab->buf, + (uint64_t ) slab->buf,MC_SLAB_BUFFER_SIZE ); + }else { + slab =QTAILQ_NEXT (slab, node); + mc->used_slabs++; + } + + mc->curr_slab = slab; +SLAB_RESET (slab); + +if (slab->idx == mc->start_copyset) { +DDPRINTF ("Found copyset slab @ idx %d\n" , slab->idx); + mc->mem_slab = slab; + } + +return slab; +} + +static int mc_put_buffer (void *opaque,const uint8_t *buf, +int64_t pos,int size) +{ +MCParams *mc = opaque; +MCSlab *slab = mc->curr_slab; +uint64_t len = size; + +assert (slab); + +while (len) { +long put =MIN (MC_SLAB_BUFFER_SIZE - slab->size, len); + +if (put ==0 ) { +DDPRINTF ("Reached the end of slab %d Need a new one\n" , slab->idx); + goto zero; + } + +if (mc->copy &&migrate_use_mc_rdma_copy ()) { +int ret =ram_control_copy_page (mc->file, + (uint64_t ) slab->buf, + slab->size, + (ram_addr_t ) mc->copy->ramblock_offset, + (ram_addr_t ) mc->copy->offset, + put); + +DDDPRINTF ("Attempted offloaded memcpy.\n" ); + +if (ret !=RAM_COPY_CONTROL_NOT_SUPP ) { +if (ret ==RAM_COPY_CONTROL_DELAYED ) { +DDDPRINTF ("Offloaded memcpy successful.\n" ); + mc->copy->offset += put; + goto next; + }else { +fprintf (stderr,"Offloaded memcpy failed: %d\n" , ret); +return ret; + } + } + } + +DDDPRINTF ("Copying to %p from %p, size %" PRId64"\n" , + slab->buf + slab->size, buf, put); + +memcpy (slab->buf + slab->size, buf, put); +next: + + buf += put; + slab->size += put; + len -= put; + mc->slab_total += put; + +DDDPRINTF ("put: %" PRIu64" len: %" PRIu64 +" total %" PRIu64" size: %" PRIu64 +" slab %d\n" , + put, len, mc->slab_total, slab->size, + slab->idx); +zero: +if (len) { + slab =mc_slab_next (mc, slab); + } + } + +return size; +} + +/* +* Stop the VM, generate the micro checkpoint, +* but save the dirty memory into staging memory +* (buffered_file will sit on it) until +* we can re-activate the VM as soon as possible. +*/ +static int capture_checkpoint (MCParams *mc,MigrationState *s) +{ +MCCopyset *copyset; +int idx, ret =0 ; +uint64_t start, stop, copies =0 ; +int64_t start_time; + + mc->total_copies =0 ; +qemu_mutex_lock_iothread (); +vm_stop_force_state (RUN_STATE_CHECKPOINT_VM ); + start =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); + +/* +* If buffering is enabled, insert a Qdisc plug here +* to hold packets for the *next* MC, (not this one, +* the packets for this one have already been plugged +* and will be released after the MC has been transmitted. +*/ +mc_start_buffer (); + +qemu_savevm_state_begin (mc->staging, &s->params); + ret =qemu_file_get_error (s->file); + +if (ret <0 ) { +migrate_set_state (s,MIG_STATE_MC ,MIG_STATE_ERROR ); + } + +qemu_savevm_state_complete (mc->staging); + + ret =qemu_file_get_error (s->file); +if (ret <0 ) { +migrate_set_state (s,MIG_STATE_MC ,MIG_STATE_ERROR ); + goto out; + } + +/* +* The copied memory gets appended to the end of the snapshot, so let's +* remember where its going to go first and start a new slab. +*/ +mc_slab_next (mc, mc->curr_slab); + mc->start_copyset = mc->curr_slab->idx; + + start_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); + +/* +* Now perform the actual copy of memory into the tail end of the slab list. +*/ + QTAILQ_FOREACH(copyset, &mc->copy_head, node) { +if (!copyset->nb_copies) { +break ; + } + + copies += copyset->nb_copies; + +DDDPRINTF ("copyset %d copies: %" PRIu64" total: %" PRIu64"\n" , + copyset->idx, copyset->nb_copies, copies); + +for (idx =0 ; idx < copyset->nb_copies; idx++) { +uint8_t *addr; +long size; + mc->copy = ©set->copies[idx]; + addr = (uint8_t *) (mc->copy->host_addr + mc->copy->offset); + size =mc_put_buffer (mc, addr, mc->copy->offset, mc->copy->size); +if (size != mc->copy->size) { +fprintf (stderr,"Failure to initiate copyset %d index %d\n" , + copyset->idx, idx); +migrate_set_state (s,MIG_STATE_MC ,MIG_STATE_ERROR ); +vm_start (); + goto out; + } + +DDDPRINTF ("Success copyset %d index %d\n" , copyset->idx, idx); + } + + copyset->nb_copies =0 ; + } + + s->ram_copy_time = (qemu_clock_get_ms (QEMU_CLOCK_REALTIME ) - start_time); + + mc->copy =NULL ; +ram_control_before_iterate (mc->file,RAM_CONTROL_FLUSH ); +assert (mc->total_copies == copies); + + stop =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); + +/* +* MC is safe in staging area. Let the VM go. +*/ +vm_start (); +qemu_fflush (mc->staging); + + s->downtime = stop - start; +out: +qemu_mutex_unlock_iothread (); +return ret; +} + +/* +* Synchronously send a micro-checkpointing command +*/ +static int mc_send (QEMUFile *f,uint64_t request) +{ +int ret =0 ; + +qemu_put_be64 (f, request); + + ret =qemu_file_get_error (f); +if (ret) { +fprintf (stderr,"transaction: send error while sending %" PRIu64", " +"bailing: %s\n" , request,strerror (-ret)); + }else { +DDPRINTF ("transaction: sent: %s (%" PRIu64")\n" , + mc_desc[request], request); + } + +qemu_fflush (f); + +return ret; +} + +/* +* Synchronously receive a micro-checkpointing command +*/ +static int mc_recv (QEMUFile *f,uint64_t request,uint64_t *action) +{ +int ret =0 ; +uint64_t got; + + got =qemu_get_be64 (f); + + ret =qemu_file_get_error (f); +if (ret) { +fprintf (stderr,"transaction: recv error while expecting %s (%" + PRIu64"), bailing: %s\n" , mc_desc[request], + request,strerror (-ret)); + }else { +if ((request !=MC_TRANSACTION_ANY ) && request != got) { +fprintf (stderr,"transaction: was expecting %s (%" PRIu64 +") but got %" PRIu64" instead\n" , + mc_desc[request], request, got); + ret = -EINVAL ; + }else { +DDPRINTF ("transaction: recv: %s (%" PRIu64")\n" , + mc_desc[got], got); + ret =0 ; +if (action) { + *action = got; + } + } + } + +return ret; +} + +static int migrate_use_bitworkers (void ) +{ +MigrationState *s =migrate_get_current (); +return s->enabled_capabilities[MIGRATION_CAPABILITY_BITWORKERS ]; +} + +static MCSlab *mc_slab_start (MCParams *mc) +{ +if (mc->nb_slabs >2 ) { +if (mc->slab_strikes >= max_strikes) { +uint64_t nb_slabs_to_free =MAX (1 , (((mc->nb_slabs -1 ) /2 ))); + +DPRINTF ("MC has reached max strikes. Will free %" + PRIu64" / %" PRIu64" slabs max %d, " +"checkpoints %" PRIu64"\n" , + nb_slabs_to_free, mc->nb_slabs, + max_strikes, mc->checkpoints); + + mc->slab_strikes =0 ; + +while (nb_slabs_to_free) { +MCSlab *slab =QTAILQ_LAST (&mc->slab_head, shead); +ram_control_remove (mc->file, (uint64_t ) slab->buf); +QTAILQ_REMOVE (&mc->slab_head, slab, node); +g_free (slab); + nb_slabs_to_free--; + mc->nb_slabs--; + } + + goto skip; + }else if (((mc->slab_total <= + ((mc->nb_slabs -1 ) *MC_SLAB_BUFFER_SIZE )))) { + mc->slab_strikes++; +DDPRINTF ("MC has strike %d slabs %" PRIu64" max %d\n" , + mc->slab_strikes, mc->nb_slabs, max_strikes); + goto skip; + } + } + +if (mc->slab_strikes) { +DDPRINTF ("MC used all slabs. Resetting strikes to zero.\n" ); + mc->slab_strikes =0 ; + } +skip: + + mc->used_slabs =1 ; + mc->slab_total =0 ; + mc->curr_slab =QTAILQ_FIRST (&mc->slab_head); +SLAB_RESET (mc->curr_slab); + +return mc->curr_slab; +} + +static MCCopyset *mc_copy_start (MCParams *mc) +{ +if (mc->nb_copysets >=2 ) { +if (mc->copy_strikes >= max_strikes) { +int nb_copies_to_free =MAX (1 , (((mc->nb_copysets -1 ) /2 ))); + +DPRINTF ("MC has reached max strikes. Will free %d / %d copies max %d\n" , + nb_copies_to_free, mc->nb_copysets, max_strikes); + + mc->copy_strikes =0 ; + +while (nb_copies_to_free) { +MCCopyset * copyset =QTAILQ_LAST (&mc->copy_head, chead); +QTAILQ_REMOVE (&mc->copy_head, copyset, node); +g_free (copyset); + nb_copies_to_free--; + mc->nb_copysets--; + } + + goto skip; + }else if (((mc->total_copies <= + ((mc->nb_copysets -1 ) *MC_MAX_SLAB_COPY_DESCRIPTORS )))) { + mc->copy_strikes++; +DDPRINTF ("MC has strike %d copies %d max %d\n" , + mc->copy_strikes, mc->nb_copysets, max_strikes); + goto skip; + } + } + +if (mc->copy_strikes) { +DDPRINTF ("MC used all copies. Resetting strikes to zero.\n" ); + mc->copy_strikes =0 ; + } +skip: + + mc->total_copies =0 ; + mc->curr_copyset =QTAILQ_FIRST (&mc->copy_head); + mc->curr_copyset->nb_copies =0 ; + +return mc->curr_copyset; +} + +/* +* Main MC loop. Stop the VM, dump the dirty memory +* into buffered_file, restart the VM, transmit the MC, +* and then sleep for some milliseconds before +* starting the next MC. +*/ +static void *mc_thread (void *opaque) +{ +MigrationState *s = opaque; +MCParams mc = { .file = s->file }; +MCSlab * slab; +int64_t initial_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); +int ret =0 , fd =qemu_get_fd (s->file), x; +QEMUFile *mc_control, *mc_staging =NULL ; +uint64_t wait_time =0 ; + +if (migrate_use_bitworkers ()) { +DPRINTF ("Starting bitmap workers.\n" ); +qemu_mutex_lock_iothread (); +migration_bitmap_worker_start (s); +qemu_mutex_unlock_iothread (); + } + +if (!(mc_control =qemu_fopen_socket (fd,"rb" ))) { +fprintf (stderr,"Failed to setup read MC control\n" ); + goto err; + } + +if (!(mc_staging =qemu_fopen_mc (&mc,"wb" ))) { +fprintf (stderr,"Failed to setup MC staging area\n" ); + goto err; + } + + mc.staging = mc_staging; + +qemu_set_block (fd); +socket_set_nodelay (fd); + + s->checkpoints =0 ; + +while (s->state ==MIG_STATE_MC ) { +int64_t current_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); +int64_t start_time, xmit_start, end_time; +bool commit_sent = false; +int nb_slab =0 ; + (void )nb_slab; + + slab =mc_slab_start (&mc); +mc_copy_start (&mc); +acct_clear (); + start_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); + +if (capture_checkpoint (&mc, s) <0 ) +break ; + + xmit_start =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); + +if ((ret =mc_send (s->file,MC_TRANSACTION_START ) <0 )) { +fprintf (stderr,"transaction start failed\n" ); +break ; + } + +DDPRINTF ("Sending checkpoint size %" PRId64 +" copyset start: %" PRIu64" nb slab %" PRIu64 +" used slabs %" PRIu64"\n" , + mc.slab_total, mc.start_copyset, mc.nb_slabs, mc.used_slabs); + + mc.curr_slab =QTAILQ_FIRST (&mc.slab_head); + +qemu_put_be64 (s->file, mc.slab_total); +qemu_put_be64 (s->file, mc.start_copyset); +qemu_put_be64 (s->file, mc.used_slabs); + +qemu_fflush (s->file); + +DDPRINTF ("Transaction commit\n" ); + +/* +* The MC is safe, and VM is running again. +* Start a transaction and send it. +*/ +ram_control_before_iterate (s->file,RAM_CONTROL_ROUND ); + + slab =QTAILQ_FIRST (&mc.slab_head); + +for (x =0 ; x < mc.used_slabs; x++) { +DDPRINTF ("Attempting write to slab #%d: %p" +" total size: %" PRId64" / %" PRIu64"\n" , + nb_slab++, slab->buf, slab->size,MC_SLAB_BUFFER_SIZE ); + + ret =ram_control_save_page (s->file, (uint64_t ) slab->buf, +NULL ,0 , slab->size,NULL ); + +if (ret ==RAM_SAVE_CONTROL_NOT_SUPP ) { +if (!commit_sent) { +if ((ret =mc_send (s->file,MC_TRANSACTION_COMMIT ) <0 )) { +fprintf (stderr,"transaction commit failed\n" ); +break ; + } + commit_sent = true; + } + +qemu_put_be64 (s->file, slab->size); +qemu_put_buffer_async (s->file, slab->buf, slab->size); + }else if ((ret <0 ) && (ret !=RAM_SAVE_CONTROL_DELAYED )) { +fprintf (stderr,"failed 1, skipping send\n" ); + goto err; + } + +if (qemu_file_get_error (s->file)) { +fprintf (stderr,"failed 2, skipping send\n" ); + goto err; + } + +DDPRINTF ("Sent %" PRId64" all %ld\n" , slab->size, mc.slab_total); + + slab =QTAILQ_NEXT (slab, node); + } + +if (!commit_sent) { +ram_control_after_iterate (s->file,RAM_CONTROL_ROUND ); + slab =QTAILQ_FIRST (&mc.slab_head); + +for (x =0 ; x < mc.used_slabs; x++) { +qemu_put_be64 (s->file, slab->size); + slab =QTAILQ_NEXT (slab, node); + } + } + +qemu_fflush (s->file); + +if (commit_sent) { +DDPRINTF ("Waiting for commit ACK\n" ); + +if ((ret =mc_recv (mc_control,MC_TRANSACTION_ACK ,NULL )) <0 ) { + goto err; + } + } + + ret =qemu_file_get_error (s->file); +if (ret) { +fprintf (stderr,"Error sending checkpoint: %d\n" , ret); + goto err; + } + +DDPRINTF ("Memory transfer complete.\n" ); + +/* +* The MC is safe on the other side now, +* go along our merry way and release the network +* packets from the buffer if enable +*/ +mc_flush_oldest_buffer (); + + end_time =qemu_clock_get_ms (QEMU_CLOCK_REALTIME ); + s->total_time = end_time - start_time; + s->xmit_time = end_time - xmit_start; + s->bitmap_time =norm_mig_bitmap_time (); + s->log_dirty_time =norm_mig_log_dirty_time (); + s->mbps =MBPS (mc.slab_total, s->xmit_time); + s->copy_mbps =MBPS (mc.slab_total, s->ram_copy_time); + s->bytes_xfer = mc.slab_total; + s->checkpoints = mc.checkpoints++; + + wait_time = (s->downtime <= freq_ms) ? (freq_ms - s->downtime) :0 ; + +if (current_time >= initial_time +1000 ) { +DPRINTF ("bytes %" PRIu64" xmit_mbps %0.1f xmit_time %" PRId64 +" downtime %" PRIu64" sync_time %" PRId64 +" logdirty_time %" PRId64" ram_copy_time %" PRId64 +" copy_mbps %0.1f wait time %" PRIu64 +" checkpoints %" PRId64"\n" , + s->bytes_xfer, + s->mbps, + s->xmit_time, + s->downtime, + s->bitmap_time, + s->log_dirty_time, + s->ram_copy_time, + s->copy_mbps, + wait_time, + s->checkpoints); + initial_time = current_time; + } + +/* +* Checkpoint frequency in microseconds. +* +* Sometimes, when checkpoints are very large, +* all of the wait time was dominated by the +* time taken to copy the checkpoint into the staging area, +* in which case wait_time, will probably be zero and we +* will end up diving right back into the next checkpoint +* as soon as the previous transmission completed. +*/ +if (wait_time) { +g_usleep (wait_time *1000 ); + } + } + + goto out; + +err: +/* +* TODO: Possible split-brain scenario: +* Normally, this should never be reached unless there was a +* connection error or network partition - in which case +* only the management software can resume the VM safely +* when it knows the exact state of the MC destination. +* +* We need management to poll the source and destination to deterine +* if the destination has already taken control. If not, then +* we need to resume the source. +* +* If there was a connection error during checkpoint *transmission* +* then the destination VM will likely have already resumed, +* in which case we need to stop the current VM from running +* and throw away any buffered packets. +* +* Verify that "disable_buffering" below does not release any traffic. +*/ +migrate_set_state (s,MIG_STATE_MC ,MIG_STATE_ERROR ); +out: +if (mc_staging) { +qemu_fclose (mc_staging); + } + +if (mc_control) { +qemu_fclose (mc_control); + } + +mc_disable_buffering (); + +qemu_mutex_lock_iothread (); + +if (migrate_use_bitworkers ()) { +DPRINTF ("Stopping bitmap workers.\n" ); +migration_bitmap_worker_stop (s); + } + +if (s->state !=MIG_STATE_ERROR ) { +migrate_set_state (s,MIG_STATE_MC ,MIG_STATE_COMPLETED ); + } + +qemu_bh_schedule (s->cleanup_bh); +qemu_mutex_unlock_iothread (); + +return NULL ; +} + +/* +* Get the next copyset in the list. If there is none, then make one. +*/ +static MCCopyset *mc_copy_next (MCParams *mc,MCCopyset *copyset) +{ +if (!QTAILQ_NEXT (copyset, node)) { +int idx = mc->nb_copysets++; +DDPRINTF ("Extending copysets by one: %d sets total, " +"%" PRIu64" MB\n" , mc->nb_copysets, + mc->nb_copysets *sizeof (MCCopyset) /1024UL /1024UL ); + mc->curr_copyset =g_malloc (sizeof (MCCopyset)); + mc->curr_copyset->idx = idx; +QTAILQ_INSERT_TAIL (&mc->copy_head, mc->curr_copyset, node); + copyset = mc->curr_copyset; + }else { + copyset =QTAILQ_NEXT (copyset, node); + } + + mc->curr_copyset = copyset; + copyset->nb_copies =0 ; + +return copyset; +} + +void mc_process_incoming_checkpoints_if_requested (QEMUFile *f) +{ +MCParams mc = { .file = f }; +MCSlab *slab; +int fd =qemu_get_fd (f); +QEMUFile *mc_control, *mc_staging; +uint64_t checkpoint_size, action; +uint64_t slabs; +int got, x, ret, received =0 ; +bool checkpoint_received; + +CALC_MAX_STRIKES (); + +if (!mc_requested) { +DPRINTF ("Source has not requested MC. Returning.\n" ); +return ; + } + +if (!(mc_control =qemu_fopen_socket (fd,"wb" ))) { +fprintf (stderr,"Could not make incoming MC control channel\n" ); + goto rollback; + } + +if (!(mc_staging =qemu_fopen_mc (&mc,"rb" ))) { +fprintf (stderr,"Could not make outgoing MC staging area\n" ); + goto rollback; + } + +//qemu_set_block(fd); +socket_set_nodelay (fd); + +while (true) { + checkpoint_received = false; + ret =mc_recv (f,MC_TRANSACTION_ANY , &action); +if (ret <0 ) { + goto rollback; + } + +switch (action) { +case MC_TRANSACTION_START : + checkpoint_size =qemu_get_be64 (f); + mc.start_copyset =qemu_get_be64 (f); + slabs =qemu_get_be64 (f); + +DDPRINTF ("Transaction start: size %" PRIu64 +" copyset start: %" PRIu64" slabs %" PRIu64"\n" , + checkpoint_size, mc.start_copyset, slabs); + +assert (checkpoint_size); +break ; +case MC_TRANSACTION_COMMIT :/* tcp */ + slab =mc_slab_start (&mc); + received =0 ; + +while (received < checkpoint_size) { +int total =0 ; + slab->size =qemu_get_be64 (f); + +DDPRINTF ("Expecting size: %" PRIu64"\n" , slab->size); + +while (total != slab->size) { + got =qemu_get_buffer (f, slab->buf + total, slab->size - total); +if (got <=0 ) { +fprintf (stderr,"Error pre-filling checkpoint: %d\n" , got); + goto rollback; + } +DDPRINTF ("Received %d slab %d / %ld received %d total %" + PRIu64"\n" , got, total, slab->size, + received, checkpoint_size); + received += got; + total += got; + } + +if (received != checkpoint_size) { + slab =mc_slab_next (&mc, slab); + } + } + +DDPRINTF ("Acknowledging successful commit\n" ); + +if (mc_send (mc_control,MC_TRANSACTION_ACK ) <0 ) { + goto rollback; + } + + checkpoint_received = true; +break ; +case RAM_SAVE_FLAG_HOOK :/* rdma */ +/* +* Must be RDMA registration handling. Preallocate +* the slabs (if not already done in a previous checkpoint) +* before allowing RDMA to register them. +*/ + slab =mc_slab_start (&mc); + +DDPRINTF ("Pre-populating slabs %" PRIu64"...\n" , slabs); + +for (x =1 ; x < slabs; x++) { + slab =mc_slab_next (&mc, slab); + } + +ram_control_load_hook (f, action); + +DDPRINTF ("Hook complete.\n" ); + + slab =QTAILQ_FIRST (&mc.slab_head); + +for (x =0 ; x < slabs; x++) { + slab->size =qemu_get_be64 (f); + slab =QTAILQ_NEXT (slab, node); + } + + checkpoint_received = true; +break ; +default : +fprintf (stderr,"Unknown MC action: %" PRIu64"\n" , action); + goto rollback; + } + +if (checkpoint_received) { + mc.curr_slab =QTAILQ_FIRST (&mc.slab_head); + mc.slab_total = checkpoint_size; + +DDPRINTF ("Committed Loading MC state \n" ); + +mc_copy_start (&mc); + +if (qemu_loadvm_state (mc_staging) <0 ) { +fprintf (stderr,"loadvm transaction failed\n" ); +/* +* This is fatal. No rollback possible because we have potentially +* applied only a subset of the checkpoint to main memory, potentially +* leaving the VM in an inconsistent state. +*/ + goto err; + } + + mc.slab_total = checkpoint_size; + +DDPRINTF ("Transaction complete.\n" ); + mc.checkpoints++; + } + } + +rollback: +fprintf (stderr,"MC: checkpointing stopped. Recovering VM\n" ); + goto out; +err: +fprintf (stderr,"Micro Checkpointing Protocol Failed\n" ); +exit (1 ); +out: +if (mc_staging) { +qemu_fclose (mc_staging); + } + +if (mc_control) { +qemu_fclose (mc_control); + } +} + +static int mc_get_buffer_internal (void *opaque,uint8_t *buf,int64_t pos, +int size,MCSlab **curr_slab,uint64_t end_idx) +{ +uint64_t len = size; +uint8_t *data = (uint8_t *) buf; +MCSlab *slab = *curr_slab; +MCParams *mc = opaque; + +assert (slab); + +DDDPRINTF ("got request for %d bytes %p %p. idx %d\n" , + size, slab,QTAILQ_FIRST (&mc->slab_head), slab->idx); + +while (len && slab) { +uint64_t get =MIN (slab->size - slab->read, len); + +memcpy (data, slab->buf + slab->read, get); + + data += get; + slab->read += get; + len -= get; + mc->slab_total -= get; + +DDDPRINTF ("got: %" PRIu64" read: %" PRIu64 +" len %" PRIu64" slab_total %" PRIu64 +" size %" PRIu64" addr: %p slab %d" +" requested %d\n" , + get, slab->read, len, mc->slab_total, + slab->size, slab->buf, slab->idx, size); + +if (len) { +if (slab->idx == end_idx) { +break ; + } + + slab =QTAILQ_NEXT (slab, node); + } + } + + *curr_slab = slab; +DDDPRINTF ("Returning %" PRIu64" / %d bytes\n" , size - len, size); + +return size - len; +} +static int mc_get_buffer (void *opaque,uint8_t *buf,int64_t pos,int size) +{ +MCParams *mc = opaque; + +return mc_get_buffer_internal (mc, buf, pos, size, &mc->curr_slab, + mc->start_copyset -1 ); +} + +static int mc_load_page (QEMUFile *f,void *opaque,void *host_addr,long size) +{ +MCParams *mc = opaque; + +DDDPRINTF ("Loading page into %p of size %" PRIu64"\n" , host_addr, size); + +return mc_get_buffer_internal (mc, host_addr,0 , size, &mc->mem_slab, + mc->nb_slabs -1 ); +} + +/* +* Provide QEMUFile with an *local* RDMA-based way to do memcpy(). +* This lowers cache pollution and allows the CPU pipeline to +* remain free for regular use by VMs (as well as by neighbors). +* +* In a future implementation, we may attempt to perform this +* copy *without* stopping the source VM - if the data shows +* that it can be done effectively. +*/ +static int mc_save_page (QEMUFile *f,void *opaque, +ram_addr_t block_offset, +uint8_t *host_addr, +ram_addr_t offset, +long size,int *bytes_sent) +{ +MCParams *mc = opaque; +MCCopyset *copyset = mc->curr_copyset; +MCCopy *c; + +if (copyset->nb_copies >=MC_MAX_SLAB_COPY_DESCRIPTORS ) { + copyset =mc_copy_next (mc, copyset); + } + + c = ©set->copies[copyset->nb_copies++]; + c->ramblock_offset = (uint64_t ) block_offset; + c->host_addr = (uint64_t ) host_addr; + c->offset = (uint64_t ) offset; + c->size = (uint64_t ) size; + mc->total_copies++; + +return RAM_SAVE_CONTROL_DELAYED ; +} + +static ssize_t mc_writev_buffer (void *opaque,struct iovec *iov, +int iovcnt,int64_t pos) +{ +ssize_t len =0 ; +unsigned int i; + +for (i =0 ; i < iovcnt; i++) { +DDDPRINTF ("iov # %d, len: %" PRId64"\n" , i, iov[i].iov_len); + len +=mc_put_buffer (opaque, iov[i].iov_base,0 , iov[i].iov_len); + } + +return len; +} + +static int mc_get_fd (void *opaque) +{ +MCParams *mc = opaque; + +return qemu_get_fd (mc->file); +} + +static int mc_close (void *opaque) +{ +MCParams *mc = opaque; +MCSlab *slab, *next; + + QTAILQ_FOREACH_SAFE(slab, &mc->slab_head, node, next) { +ram_control_remove (mc->file, (uint64_t ) slab->buf); +QTAILQ_REMOVE (&mc->slab_head, slab, node); +g_free (slab); + } + + mc->curr_slab =NULL ; + +return 0 ; +} + +static const QEMUFileOps mc_write_ops = { + .writev_buffer = mc_writev_buffer, + .put_buffer = mc_put_buffer, + .get_fd = mc_get_fd, + .close = mc_close, + .save_page = mc_save_page, +}; + +static const QEMUFileOps mc_read_ops = { + .get_buffer = mc_get_buffer, + .get_fd = mc_get_fd, + .close = mc_close, + .load_page = mc_load_page, +}; + +QEMUFile *qemu_fopen_mc (void *opaque,const char *mode) +{ +MCParams *mc = opaque; +MCSlab *slab; +MCCopyset *copyset; + +if (qemu_file_mode_is_not_valid (mode)) { +return NULL ; + } + +QTAILQ_INIT (&mc->slab_head); +QTAILQ_INIT (&mc->copy_head); + + slab =qemu_memalign (8 ,sizeof (MCSlab)); +memset (slab,0 ,sizeof (*slab)); + slab->idx =0 ; +QTAILQ_INSERT_HEAD (&mc->slab_head, slab, node); + mc->slab_total =0 ; + mc->curr_slab = slab; + mc->nb_slabs =1 ; + mc->slab_strikes =0 ; + +ram_control_add (mc->file, slab->buf, (uint64_t ) slab->buf,MC_SLAB_BUFFER_SIZE ); + + copyset =g_malloc (sizeof (MCCopyset)); + copyset->idx =0 ; +QTAILQ_INSERT_HEAD (&mc->copy_head, copyset, node); + mc->total_copies =0 ; + mc->curr_copyset = copyset; + mc->nb_copysets =1 ; + mc->copy_strikes =0 ; + +if (mode[0 ] =='w' ) { +return qemu_fopen_ops (mc, &mc_write_ops); + } + +return qemu_fopen_ops (mc, &mc_read_ops); +} + +static void mc_start_checkpointer (void *opaque) { +MigrationState *s = opaque; + +if (checkpoint_bh) { +qemu_bh_delete (checkpoint_bh); + checkpoint_bh =NULL ; + } + +qemu_mutex_unlock_iothread (); +qemu_thread_join (s->thread); +g_free (s->thread); +qemu_mutex_lock_iothread (); + +migrate_set_state (s,MIG_STATE_ACTIVE ,MIG_STATE_MC ); + s->thread =g_malloc0 (sizeof (*s->thread)); +qemu_thread_create (s->thread, mc_thread, s,QEMU_THREAD_JOINABLE ); +} + +void mc_init_checkpointer (MigrationState *s) +{ +CALC_MAX_STRIKES (); + checkpoint_bh =qemu_bh_new (mc_start_checkpointer, s); +qemu_bh_schedule (checkpoint_bh); +} + +void qmp_migrate_set_mc_delay (int64_t value,Error **errp) +{ + freq_ms = value; +CALC_MAX_STRIKES (); +DPRINTF ("Setting checkpoint frequency to %" PRId64" ms and " +"resetting strikes to %d based on a %d sec delay.\n" , + freq_ms, max_strikes, max_strikes_delay_secs); +} + +int mc_info_load (QEMUFile *f,void *opaque,int version_id) +{ +bool mc_enabled =qemu_get_byte (f); + +if (mc_enabled && !mc_requested) { +DPRINTF ("MC is requested\n" ); + mc_requested = true; + } + + max_strikes =qemu_get_be32 (f); + +return 0 ; +} + +void mc_info_save (QEMUFile *f,void *opaque) +{ +qemu_put_byte (f,migrate_use_mc ()); +qemu_put_be32 (f, max_strikes); +}
Signature · 1 line
1.8.1.2
RFC PATCH 10/12 mc: configure and makefile support
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
--- Makefile.objs | 1 + configure | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+)
Makefile.objs +1 -0
@@ -52,6 +52,7 @@ common-obj-$(CONFIG_LINUX) += fsdev/ common-obj-y += migration.o migration-tcp.o common-obj-$(CONFIG_RDMA) += migration-rdma.o +common-obj-$(CONFIG_MC) += migration-checkpoint.o common-obj-y += qemu-char.o #aio.o common-obj-y += block-migration.o common-obj-y += page_cache.o xbzrle.o
configure +45 -0
87 lines not on this page · raw message
Signature · 1 line
1.8.1.2
RFC PATCH 11/12 mc: register MC qemu-file functions and expose MC tunable capability
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
The capability allows management software to throttle the MC frequency during VM application transience.
The qemu-file savevm() functions inform the destination that the incoming traffic is MC-specific traffic and not vanilla live-migration traffic.
--- hmp-commands.hx | 14 ++++++++++++++ hmp.c | 6 ++++++ hmp.h | 1 + qapi-schema.json | 13 +++++++++++++ qmp-commands.hx | 23 +++++++++++++++++++++++ vl.c | 3 +++ 6 files changed, 60 insertions(+)
hmp-commands.hx +14 -0
@@ -960,6 +960,20 @@ Set maximum tolerated downtime (in seconds) for migration. ETEXI { + .name = "migrate-set-mc-delay", + .args_type = "value:i", + .params = "value", + .help = "set maximum delay (in milliseconds) between micro-checkpoints", + .mhandler.cmd = hmp_migrate_set_mc_delay, + }, + +STEXI +@item migrate_set_downtime @var{second} +@findex migrate_set_downtime +Set maximum tolerated downtime (in seconds) for migration. +ETEXI + + { .name = "migrate_set_capability", .args_type = "capability:s,state:b", .params = "capability state",
hmp.c +6 -0
@@ -1026,6 +1026,12 @@ void hmp_migrate_set_downtime(Monitor *mon, const QDict *qdict)qmp_migrate_set_downtime (value,NULL ); } +void hmp_migrate_set_mc_delay (Monitor *mon,const QDict *qdict) +{ +int64_t value =qdict_get_int (qdict,"value" ); +qmp_migrate_set_mc_delay (value,NULL ); +} +void hmp_migrate_set_cache_size (Monitor *mon,const QDict *qdict) {int64_t value =qdict_get_int (qdict,"value" );
hmp.h +1 -0
@@ -60,6 +60,7 @@ void hmp_drive_mirror(Monitor *mon, const QDict *qdict);void hmp_drive_backup (Monitor *mon,const QDict *qdict);void hmp_migrate_cancel (Monitor *mon,const QDict *qdict);void hmp_migrate_set_downtime (Monitor *mon,const QDict *qdict); +void hmp_migrate_set_mc_delay (Monitor *mon,const QDict *qdict);void hmp_migrate_set_speed (Monitor *mon,const QDict *qdict);void hmp_migrate_set_capability (Monitor *mon,const QDict *qdict);void hmp_migrate_set_cache_size (Monitor *mon,const QDict *qdict);
qapi-schema.json +13 -0
@@ -2135,6 +2135,19 @@ { 'command': 'migrate_set_downtime', 'data': {'value': 'number'} } ## +# @migrate-set-mc-delay +# +# Set delay (in milliseconds) between micro checkpoints. +# +# @value: maximum delay in milliseconds +# +# Returns: nothing on success +# +# Since: 1.6 +## +{ 'command': 'migrate-set-mc-delay', 'data': {'value': 'int'} } + +## # @migrate_set_speed # # Set maximum speed for migration.
qmp-commands.hx +23 -0
@@ -754,6 +754,29 @@ Example: EQMP { + .name = "migrate-set-mc-delay", + .args_type = "value:i", + .mhandler.cmd_new = qmp_marshal_input_migrate_set_mc_delay, + }, + +SQMP +migrate-set-mc-delay +-------------------- + +Set maximum delay (in milliseconds) between micro-checkpoints. + +Arguments: + +- "value": maximum delay (json-int) + +Example: + +-> { "execute": "migrate-set-mc-delay", "arguments": { "value": 100 } } +<- { "return": {} } + +EQMP + + { .name = "client_migrate_info", .args_type = "protocol:s,hostname:s,port:i?,tls-port:i?,cert-subject:s?", .params = "protocol hostname port tls-port cert-subject",
vl.c +3 -0
@@ -29,6 +29,7 @@#include <sys/time.h> #include <zlib.h> #include "qemu/bitmap.h" +#include "migration/qemu-file.h" /* Needed early for CONFIG_BSD etc. */ #include "config-host.h"
@@ -4192,6 +4193,8 @@ int main(int argc, char **argv, char **envp)default_drive (default_sdcard, snapshot,IF_SD ,0 ,SD_OPTS );register_savevm_live (NULL ,"ram" ,0 ,4 , &savevm_ram_handlers,NULL ); +register_savevm (NULL ,"mc" ,-1 ,MC_VERSION , mc_info_save, + mc_info_load,NULL );if (nb_numa_nodes >0 ) {int i;
Signature · 1 line
1.8.1.2
Re: [Qemu-devel] [RFC PATCH v1: 11/12] mc: register MC qemu-file functions and expose MC tunable capability
Since more integer parameters would come in the future, so how about set_migrate_parameter similar to set_migrate_capability? It sets integer value, while set_migrate_capability sets bool value.
thanks,
Quoted 155 lines · On Mon, Oct 21, 2013 at 01:14:21AM +0000, [email protected] wrote:
From: "Michael R. Hines" <[email protected]>
The capability allows management software to throttle the MC frequency during VM application transience.
The qemu-file
savevm()functions inform the destination that the incoming traffic is MC-specific traffic and not vanilla live-migration traffic.Signed-off-by Michael R. Hines <[email protected]>--- hmp-commands.hx | 14 ++++++++++++++ hmp.c | 6 ++++++ hmp.h | 1 + qapi-schema.json | 13 +++++++++++++ qmp-commands.hx | 23 +++++++++++++++++++++++ vl.c | 3 +++ 6 files changed, 60 insertions(+)hmp-commands.hx +14
-0@@ -960,6 +960,20 @@ Set maximum tolerated downtime (in seconds) for migration. ETEXI { + .name = "migrate-set-mc-delay", + .args_type = "value:i", + .params = "value", + .help = "set maximum delay (in milliseconds) between micro-checkpoints", + .mhandler.cmd = hmp_migrate_set_mc_delay, + }, + +STEXI +@item migrate_set_downtime @var{second} +@findex migrate_set_downtime +Set maximum tolerated downtime (in seconds) for migration. +ETEXI + + { .name = "migrate_set_capability", .args_type = "capability:s,state:b", .params = "capability state",hmp.c +6
-0@@ -1026,6 +1026,12 @@ void hmp_migrate_set_downtime(Monitor *mon, const QDict *qdict)qmp_migrate_set_downtime (value,NULL ); } +void hmp_migrate_set_mc_delay (Monitor *mon,const QDict *qdict) +{ +int64_t value =qdict_get_int (qdict,"value" ); +qmp_migrate_set_mc_delay (value,NULL ); +} +void hmp_migrate_set_cache_size (Monitor *mon,const QDict *qdict) {int64_t value =qdict_get_int (qdict,"value" );hmp.h +1
-0@@ -60,6 +60,7 @@ void hmp_drive_mirror(Monitor *mon, const QDict *qdict);void hmp_drive_backup (Monitor *mon,const QDict *qdict);void hmp_migrate_cancel (Monitor *mon,const QDict *qdict);void hmp_migrate_set_downtime (Monitor *mon,const QDict *qdict); +void hmp_migrate_set_mc_delay (Monitor *mon,const QDict *qdict);void hmp_migrate_set_speed (Monitor *mon,const QDict *qdict);void hmp_migrate_set_capability (Monitor *mon,const QDict *qdict);void hmp_migrate_set_cache_size (Monitor *mon,const QDict *qdict);qapi-schema.json +13
-0@@ -2135,6 +2135,19 @@ { 'command': 'migrate_set_downtime', 'data': {'value': 'number'} } ## +# @migrate-set-mc-delay +# +# Set delay (in milliseconds) between micro checkpoints. +# +# @value: maximum delay in milliseconds +# +# Returns: nothing on success +# +# Since: 1.6 +## +{ 'command': 'migrate-set-mc-delay', 'data': {'value': 'int'} } + +## # @migrate_set_speed # # Set maximum speed for migration.qmp-commands.hx +23
-0@@ -754,6 +754,29 @@ Example: EQMP { + .name = "migrate-set-mc-delay", + .args_type = "value:i", + .mhandler.cmd_new = qmp_marshal_input_migrate_set_mc_delay, + }, + +SQMP +migrate-set-mc-delay +-------------------- + +Set maximum delay (in milliseconds) between micro-checkpoints. + +Arguments: + +- "value": maximum delay (json-int) + +Example: + +-> { "execute": "migrate-set-mc-delay", "arguments": { "value": 100 } } +<- { "return": {} } + +EQMP + + { .name = "client_migrate_info", .args_type = "protocol:s,hostname:s,port:i?,tls-port:i?,cert-subject:s?", .params = "protocol hostname port tls-port cert-subject",vl.c +3
-0@@ -29,6 +29,7 @@#include <sys/time.h> #include <zlib.h> #include "qemu/bitmap.h" +#include "migration/qemu-file.h" /* Needed early for CONFIG_BSD etc. */ #include "config-host.h" @@ -4192,6 +4193,8 @@ int main(int argc, char **argv, char **envp)default_drive (default_sdcard, snapshot,IF_SD ,0 ,SD_OPTS );register_savevm_live (NULL ,"ram" ,0 ,4 , &savevm_ram_handlers,NULL ); +register_savevm (NULL ,"mc" ,-1 ,MC_VERSION , mc_info_save, + mc_info_load,NULL );if (nb_numa_nodes >0 ) {int i;Signature · 1 line
1.8.1.2
Re: [Qemu-devel] [RFC PATCH v1: 11/12] mc: register MC qemu-file functions and expose MC tunable capability
Quoted 158 lines · Isaku Yamahata
Since more integer parameters would come in the future, so how about
set_migrate_parametersimilar toset_migrate_capability? It sets integer value, whileset_migrate_capabilitysets bool value.thanks,
Quoted 149 lines · On Mon, Oct 21, 2013 at 01:14:21AM +0000, [email protected] wrote:
From: "Michael R. Hines" <[email protected]>
The capability allows management software to throttle the MC frequency during VM application transience.
The qemu-file
savevm()functions inform the destination that the incoming traffic is MC-specific traffic and not vanilla live-migration traffic.Signed-off-by Michael R. Hines <[email protected]>--- hmp-commands.hx | 14 ++++++++++++++ hmp.c | 6 ++++++ hmp.h | 1 + qapi-schema.json | 13 +++++++++++++ qmp-commands.hx | 23 +++++++++++++++++++++++ vl.c | 3 +++ 6 files changed, 60 insertions(+)hmp-commands.hx +14
-0@@ -960,6 +960,20 @@ Set maximum tolerated downtime (in seconds) for migration. ETEXI { + .name = "migrate-set-mc-delay", + .args_type = "value:i", + .params = "value", + .help = "set maximum delay (in milliseconds) between micro-checkpoints", + .mhandler.cmd = hmp_migrate_set_mc_delay, + }, + +STEXI +@item migrate_set_downtime @var{second} +@findex migrate_set_downtime +Set maximum tolerated downtime (in seconds) for migration. +ETEXI + + { .name = "migrate_set_capability", .args_type = "capability:s,state:b", .params = "capability state",hmp.c +6
-0@@ -1026,6 +1026,12 @@ void hmp_migrate_set_downtime(Monitor *mon, const QDict *qdict)qmp_migrate_set_downtime (value,NULL ); } +void hmp_migrate_set_mc_delay (Monitor *mon,const QDict *qdict) +{ +int64_t value =qdict_get_int (qdict,"value" ); +qmp_migrate_set_mc_delay (value,NULL ); +} +void hmp_migrate_set_cache_size (Monitor *mon,const QDict *qdict) {int64_t value =qdict_get_int (qdict,"value" );hmp.h +1
-0@@ -60,6 +60,7 @@ void hmp_drive_mirror(Monitor *mon, const QDict *qdict);void hmp_drive_backup (Monitor *mon,const QDict *qdict);void hmp_migrate_cancel (Monitor *mon,const QDict *qdict);void hmp_migrate_set_downtime (Monitor *mon,const QDict *qdict); +void hmp_migrate_set_mc_delay (Monitor *mon,const QDict *qdict);void hmp_migrate_set_speed (Monitor *mon,const QDict *qdict);void hmp_migrate_set_capability (Monitor *mon,const QDict *qdict);void hmp_migrate_set_cache_size (Monitor *mon,const QDict *qdict);qapi-schema.json +13
-0@@ -2135,6 +2135,19 @@ { 'command': 'migrate_set_downtime', 'data': {'value': 'number'} } ## +# @migrate-set-mc-delay +# +# Set delay (in milliseconds) between micro checkpoints. +# +# @value: maximum delay in milliseconds +# +# Returns: nothing on success +# +# Since: 1.6 +## +{ 'command': 'migrate-set-mc-delay', 'data': {'value': 'int'} } + +## # @migrate_set_speed # # Set maximum speed for migration.qmp-commands.hx +23
-0@@ -754,6 +754,29 @@ Example: EQMP { + .name = "migrate-set-mc-delay", + .args_type = "value:i", + .mhandler.cmd_new = qmp_marshal_input_migrate_set_mc_delay, + }, + +SQMP +migrate-set-mc-delay +-------------------- + +Set maximum delay (in milliseconds) between micro-checkpoints. + +Arguments: + +- "value": maximum delay (json-int) + +Example: + +-> { "execute": "migrate-set-mc-delay", "arguments": { "value": 100 } } +<- { "return": {} } + +EQMP + + { .name = "client_migrate_info", .args_type = "protocol:s,hostname:s,port:i?,tls-port:i?,cert-subject:s?", .params = "protocol hostname port tls-port cert-subject",vl.c +3
-0@@ -29,6 +29,7 @@#include <sys/time.h> #include <zlib.h> #include "qemu/bitmap.h" +#include "migration/qemu-file.h" /* Needed early for CONFIG_BSD etc. */ #include "config-host.h" @@ -4192,6 +4193,8 @@ int main(int argc, char **argv, char **envp)default_drive (default_sdcard, snapshot,IF_SD ,0 ,SD_OPTS );register_savevm_live (NULL ,"ram" ,0 ,4 , &savevm_ram_handlers,NULL ); +register_savevm (NULL ,"mc" ,-1 ,MC_VERSION , mc_info_save, + mc_info_load,NULL );
Quoted 6 lines
Quoted 6 lines
vl.c +0
-0if (nb_numa_nodes >0 ) {int i;Signature · 1 line
1.8.1.2
That's a very good idea, I think - but we might get some pushback from the list.
There is a hesitation to add such low-level parameters, but for something like micro-checkpointing that may potentially have large impacts on application performance, I do think it would be critical to expose more customizability
like 'set_migrate_parameter' to management software.
In fact, this separation of function may be "better" than continuing to expand the list of individual commands in the QEMU monitor.
Could you submit a patch for the framework of such a command?
- Michael
- Michael
Re: [Qemu-devel] [RFC PATCH v1: 11/12] mc: register MC qemu-file functions and expose MC tunable capability
Quoted 7 lines · Michael R. Hines
Quoted 3 lines · Isaku Yamahata
Since more integer parameters would come in the future, so how about
set_migrate_parametersimilar toset_migrate_capability? It sets integer value, whileset_migrate_capabilitysets bool value.That's a very good idea, I think - but we might get some pushback from the list.
Maybe. Actually we already have three configurable parameters. bandwith_limit, xbzrle_cache_size, max_downtime. They can be all consolidated.
Quoted 7 lines
There is a hesitation to add such low-level parameters, but for something like
micro-checkpointing that may potentially have large impacts on application performance,
I do think it would be critical to expose more customizability like 'set_migrate_parameter' to management software.
Quoted 5 lines
In fact, this separation of function may be "better" than continuing to expand
the list of individual commands in the QEMU monitor.Could you submit a patch for the framework of such a command?
Sure.
Signature · 1 line
Isaku Yamahata <[email protected]>
RFC PATCH 12/12 mc: activate and use MC core logic if requested
In reply to [email protected]From: "Michael R. Hines" <[email protected]>
Building on the previous patches, this finally actually activates protection of the VM by kicking off an MC thread after the initial live migration completes. The live migration thread will get destroyed and the MC thread will run and never die.
--- migration.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)
migration.c +20 -1
@@ -94,6 +94,9 @@ static void process_incoming_migration_co(void *opaque)int ret; ret =qemu_loadvm_state (f); +if (ret >=0 ) { +mc_process_incoming_checkpoints_if_requested (f); + }qemu_fclose (f);if (ret <0 ) {fprintf (stderr,"load of migration failed\n" );
@@ -670,11 +673,27 @@ static void *migration_thread(void *opaque) s->downtime = end_time - start_time;runstate_set (RUN_STATE_POSTMIGRATE ); }else { +if (migrate_use_mc ()) { +qemu_fflush (s->file); +if (migrate_use_mc_net ()) { +if (mc_enable_buffering () <0 || +mc_start_buffer () <0 ) { +migrate_set_state (s,MIG_STATE_ACTIVE ,MIG_STATE_ERROR ); + } + } + } +if (old_vm_running) {vm_start (); } } -qemu_bh_schedule (s->cleanup_bh); + +if (migrate_use_mc () && s->state !=MIG_STATE_ERROR ) { +mc_init_checkpointer (s); + }else { +qemu_bh_schedule (s->cleanup_bh); + } +qemu_mutex_unlock_iothread ();return NULL ;
Signature · 1 line
1.8.1.2