diff mbox

Support adding a file to qemu's ram allocation

Message ID 1267833161-25267-1-git-send-email-cam@cs.ualberta.ca
State New
Headers show

Commit Message

Cam Macdonell March 5, 2010, 11:52 p.m. UTC
This avoids the need of using qemu_ram_alloc and mmap with MAP_FIXED to map a host file into guest RAM.  This function mmaps the opened file anywhere and adds the memory to the ram blocks.

Usage is

qemu_add_file_to_ram(fd, size, MAP_SHARED);
---
 cpu-common.h |    1 +
 exec.c       |   33 +++++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 0 deletions(-)

Comments

Avi Kivity March 8, 2010, 9:53 a.m. UTC | #1
On 03/06/2010 01:52 AM, Cam Macdonell wrote:
> This avoids the need of using qemu_ram_alloc and mmap with MAP_FIXED to map a host file into guest RAM.  This function mmaps the opened file anywhere and adds the memory to the ram blocks.
>
> Usage is
>
> qemu_add_file_to_ram(fd, size, MAP_SHARED);
>    

A traditional name would be qemu_ram_mmap() as a counterpart to 
qemu_ram_alloc().  Would be nice to accept an offset.
diff mbox

Patch

diff --git a/cpu-common.h b/cpu-common.h
index 326513d..2d95079 100644
--- a/cpu-common.h
+++ b/cpu-common.h
@@ -30,6 +30,7 @@  static inline void cpu_register_physical_memory(target_phys_addr_t start_addr,
 }
 
 ram_addr_t cpu_get_physical_page_desc(target_phys_addr_t addr);
+ram_addr_t qemu_add_file_to_ram(int, ram_addr_t, int);
 ram_addr_t qemu_ram_alloc(ram_addr_t);
 void qemu_ram_free(ram_addr_t addr);
 /* This should only be used for ram local to a device.  */
diff --git a/exec.c b/exec.c
index 69003c2..955adee 100644
--- a/exec.c
+++ b/exec.c
@@ -2623,6 +2623,39 @@  static void *file_ram_alloc(ram_addr_t memory, const char *path)
 
 extern const char *mem_path;
 
+ram_addr_t qemu_add_file_to_ram(int fd, ram_addr_t size, int flags)
+{
+    RAMBlock *new_block;
+
+    size = TARGET_PAGE_ALIGN(size);
+    new_block = qemu_malloc(sizeof(*new_block));
+
+    // map the file passed as a parameter to be this part of memory
+    new_block->host = mmap(0, size, PROT_READ|PROT_WRITE, flags, fd, 0);
+
+#ifdef MADV_MERGEABLE
+    madvise(new_block->host, size, MADV_MERGEABLE);
+#endif
+
+    new_block->offset = last_ram_offset;
+    new_block->length = size;
+
+    new_block->next = ram_blocks;
+    ram_blocks = new_block;
+
+    phys_ram_dirty = qemu_realloc(phys_ram_dirty,
+        (last_ram_offset + size) >> TARGET_PAGE_BITS);
+    memset(phys_ram_dirty + (last_ram_offset >> TARGET_PAGE_BITS),
+           0xff, size >> TARGET_PAGE_BITS);
+
+    last_ram_offset += size;
+
+    if (kvm_enabled())
+        kvm_setup_guest_memory(new_block->host, size);
+
+    return new_block->offset;
+}
+
 ram_addr_t qemu_ram_alloc(ram_addr_t size)
 {
     RAMBlock *new_block;