</>EmbeddedInterview

Track dirty pages with a bitmap (for live migration).

Medium"Coding: Systems, Bitmaps & Virtualization"
#include <stdint.h>
#include <string.h>

#define PAGE_SHIFT 12
#define GUEST_PAGES 4096u                          /* 16 MB guest */
static uint64_t dirty[GUEST_PAGES / 64];

static inline void mark_dirty(uint64_t gpa)
{
    uint64_t pfn = gpa >> PAGE_SHIFT;
    if (pfn < GUEST_PAGES) dirty[pfn / 64] |= 1ull << (pfn % 64);   /* atomic OR if called concurrently */
}

/* migration loop: send every dirty page once, then clear the bitmap for the next round */
unsigned sync_dirty(void (*send_page)(uint64_t pfn))
{
    unsigned sent = 0;
    for (unsigned w = 0; w < GUEST_PAGES / 64; w++) {
        uint64_t bits = dirty[w];
        dirty[w] = 0;                                /* real code: atomic exchange */
        while (bits) {
            unsigned b = (unsigned)__builtin_ctzll(bits);
            send_page((uint64_t)w * 64 + b);
            bits &= bits - 1;                        /* clear lowest set bit */
            sent++;
        }
    }
    return sent;
}

Points: one bit per guest page; pages are marked dirty when the guest writes them (KVM write-protects pages in stage-2 or uses hardware dirty tracking/PML, and reports a bitmap with KVM_GET_DIRTY_LOG; device emulation marks pages it DMAs into); migration repeatedly sends dirty pages while the guest runs, until the remaining set is small, then pauses the guest for the final copy. Read-and-clear must be atomic per word, or writes between the read and the clear are lost. Iterating set bits with ctz and bits &= bits - 1 skips clean pages quickly.