QEMU tutorial: How to use ivshmem-plain。
Notes about ivshmem

1. hotplug ivshmem in QEMU monitor

Use QEMU to launch a VM, enter the monitor mode.

1
2
3
4
(qemu) object_add  memory-backend-file,size=16M,share,mem-path=/dev/shm/shm1,id=shm1
(qemu) device_add ivshmem-plain,memdev=shm1,bus=pci.0,addr=0x10,master=on
(qemu) object_add memory-backend-file,size=8M,share,mem-path=/dev/shm/shm2,id=shm2
(qemu) device_add ivshmem-plain,memdev=shm2,bus=pci.0,addr=0x11,master=on

2. write the signature into shared memory in host

1
2
echo "SIGN_01" > /dev/shm/shm1
echo "SIGN_02" > /dev/shm/shm2

3. read the signature from shared memory in guest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// t.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <assert.h>

#define SHM_SIZE (16 * 1024 * 1024)

int main(int argc, char **argv) {
char *p;
int fd;
int i;

fd = open("/sys/bus/pci/devices/0000:00:10.0/resource2", O_RDWR);
assert(fd != -1);

p = mmap(0, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
assert(p != NULL);

for (i = 0; i < 8; i++) {
printf("%c", p[i]);
}

munmap(p, SHM_SIZE);
close(fd);

return 0;
}
1
2
3
$ gcc t.c
$ ./a.out
SIGN_01

参考资料:

  1. qemu doc: Inter-VM Shared Memory device
  2. QEMU虚拟机内识别ivshmem设备